leejunyoung5819handmade-dataset-creator

공개

고품질 LLM 데이터셋 수제작을 위한 생산성 도구

893줄36 KB
1//! 도구 관련 화면: 도구 라이브러리 편집기(폼), tools 메시지 선택 UI, 도구 호출 자동완성.
2
3use eframe::egui::{self, Color32, ComboBox, Frame, Id, Key, Modal, Modifiers, RichText, ScrollArea, TextEdit};
4use handmade_dataset_creator::model::{Message, ToolCall, one_line};
5use handmade_dataset_creator::tools::{
6 self, Param, ParamType, ToolDef, ToolLibrary, fill_missing_required, parse_tool_list, tool_list_to_json,
7};
8
9fn warn(ui: &mut egui::Ui, text: impl Into<String>) {
10 ui.colored_label(ui.visuals().warn_fg_color, format!("⚠ {}", text.into()));
11}
12
13/// `get_weather(city*, unit, days)` 형태의 요약. *는 필수.
14pub fn signature(def: &ToolDef) -> String {
15 let params: Vec<String> =
16 def.params.iter().map(|p| if p.required { format!("{}*", p.name) } else { p.name.clone() }).collect();
17 format!("{}({})", def.name, params.join(", "))
18}
19
20// ---------------------------------------------------------------------------
21// 도구 라이브러리 편집기
22// ---------------------------------------------------------------------------
23
24pub enum LibraryOutcome {
25 Apply,
26 Cancel,
27}
28
29pub struct LibraryEditor {
30 pub tools: Vec<ToolDef>,
31 selected: Option<usize>,
32 json_mode: bool,
33 json_text: String,
34 json_error: Option<String>,
35 /// enum 입력 버퍼(egui 임시 메모리)를 무효화하기 위한 세대 번호.
36 generation: u64,
37 focus_name: bool,
38 target: Option<String>,
39}
40
41impl LibraryEditor {
42 /// `target`: 라이브러리가 저장될 파일 경로(없으면 아직 데이터셋 경로가 없음).
43 pub fn new(lib: &ToolLibrary, select: Option<&str>, target: Option<String>) -> Self {
44 let selected = select
45 .and_then(|n| lib.tools.iter().position(|t| t.name == n))
46 .or(if lib.tools.is_empty() { None } else { Some(0) });
47 LibraryEditor {
48 tools: lib.tools.clone(),
49 selected,
50 json_mode: false,
51 json_text: String::new(),
52 json_error: None,
53 generation: 0,
54 focus_name: false,
55 target,
56 }
57 }
58
59 /// 확인/저장 전에 호출: JSON 편집 중이면 반영한다. JSON이 잘못되어 있으면 false.
60 pub fn finish(&mut self) -> bool {
61 self.leave_json()
62 }
63
64 /// JSON 모드를 빠져나온다. JSON이 잘못되어 있으면 false.
65 fn leave_json(&mut self) -> bool {
66 if self.json_mode {
67 if self.json_error.is_some() {
68 return false;
69 }
70 self.json_mode = false;
71 self.generation += 1;
72 }
73 true
74 }
75
76 fn select(&mut self, i: Option<usize>) {
77 if self.leave_json() {
78 self.selected = i;
79 self.generation += 1;
80 }
81 }
82
83 pub fn show(&mut self, ctx: &egui::Context) -> Option<LibraryOutcome> {
84 let (mut ok, mut cancel) = ctx.input_mut(|i| {
85 (i.consume_key(Modifiers::COMMAND, Key::Enter), i.consume_key(Modifiers::NONE, Key::Escape))
86 });
87 let screen = ctx.content_rect();
88 Modal::new(Id::unique("tool_library")).show(ctx, |ui| {
89 ui.set_width((screen.width() - 40.0).clamp(480.0, 1160.0));
90 ui.strong("도구 라이브러리");
91 ui.weak("여기서 정의한 도구를 tools 메시지에서 체크해 넣을 수 있습니다.");
92 match &self.target {
93 Some(path) => ui.weak(format!("확인(또는 Ctrl+S)을 누르면 바로 저장됩니다: {path}")),
94 None => ui.weak("데이터셋을 처음 저장할 때 <이름>.tools.json 으로 함께 저장됩니다."),
95 };
96 ui.separator();
97 let h = (screen.height() - 200.0).clamp(200.0, 640.0);
98 // 세로 구분선이 화면 끝까지 늘어나지 않도록 높이를 고정한 영역 안에 배치한다.
99 let w = ui.available_width();
100 ui.allocate_ui_with_layout(egui::vec2(w, h), egui::Layout::left_to_right(egui::Align::TOP), |ui| {
101 ui.set_height(h);
102 ui.vertical(|ui| {
103 ui.set_width(250.0);
104 self.list_ui(ui, h);
105 });
106 ui.separator();
107 ui.vertical(|ui| {
108 ScrollArea::vertical()
109 .id_salt("tool_form")
110 .max_height(h)
111 .auto_shrink([false, true])
112 .show(ui, |ui| self.form_ui(ui));
113 });
114 });
115 ui.separator();
116 ui.horizontal(|ui| {
117 if ui.button("확인 (Ctrl+Enter)").clicked() {
118 ok = true;
119 }
120 if ui.button("취소 (Esc)").clicked() {
121 cancel = true;
122 }
123 if let Some(e) = &self.json_error {
124 warn(ui, format!("JSON 오류를 고쳐야 적용할 수 있습니다: {}", one_line(e, 80)));
125 }
126 });
127 });
128 if ok && self.leave_json() {
129 return Some(LibraryOutcome::Apply);
130 }
131 if cancel {
132 return Some(LibraryOutcome::Cancel);
133 }
134 None
135 }
136
137 fn list_ui(&mut self, ui: &mut egui::Ui, height: f32) {
138 ui.horizontal_wrapped(|ui| {
139 if ui.button("+ 새 도구").clicked() && self.leave_json() {
140 self.tools.push(ToolDef::default());
141 self.select(Some(self.tools.len() - 1));
142 self.focus_name = true;
143 }
144 let has = self.selected.is_some();
145 if ui.add_enabled(has, egui::Button::new("복제")).clicked() && self.leave_json() {
146 let i = self.selected.unwrap();
147 let mut copy = self.tools[i].clone();
148 copy.name.push_str("_copy");
149 self.tools.insert(i + 1, copy);
150 self.select(Some(i + 1));
151 }
152 if ui.add_enabled(has, egui::Button::new("삭제")).clicked() {
153 let i = self.selected.unwrap();
154 self.json_mode = false;
155 self.json_error = None;
156 self.tools.remove(i);
157 let next = if self.tools.is_empty() { None } else { Some(i.min(self.tools.len() - 1)) };
158 self.select(next);
159 }
160 if ui.add_enabled(self.selected.is_some_and(|i| i > 0), egui::Button::new("↑")).clicked()
161 && self.leave_json()
162 {
163 let i = self.selected.unwrap();
164 self.tools.swap(i, i - 1);
165 self.select(Some(i - 1));
166 }
167 if ui
168 .add_enabled(self.selected.is_some_and(|i| i + 1 < self.tools.len()), egui::Button::new("↓"))
169 .clicked()
170 && self.leave_json()
171 {
172 let i = self.selected.unwrap();
173 self.tools.swap(i, i + 1);
174 self.select(Some(i + 1));
175 }
176 });
177 ui.add_space(4.0);
178 let mut clicked = None;
179 ScrollArea::vertical().id_salt("tool_list").max_height(height - 40.0).auto_shrink([false, true]).show(
180 ui,
181 |ui| {
182 if self.tools.is_empty() {
183 ui.weak("도구가 없습니다.");
184 }
185 for (i, t) in self.tools.iter().enumerate() {
186 let dup = self.tools.iter().filter(|o| o.name == t.name).count() > 1;
187 let mut text = if t.name.is_empty() { "(이름 없음)".to_string() } else { t.name.clone() };
188 if dup {
189 text.push_str(" (변형)");
190 }
191 let mut rt = RichText::new(text).monospace();
192 if !t.problems().is_empty() {
193 rt = rt.color(ui.visuals().warn_fg_color);
194 }
195 let r = ui.selectable_label(self.selected == Some(i), rt);
196 let r = if t.description.is_empty() { r } else { r.on_hover_text(&t.description) };
197 if r.clicked() {
198 clicked = Some(i);
199 }
200 }
201 },
202 );
203 if let Some(i) = clicked {
204 self.select(Some(i));
205 }
206 }
207
208 fn form_ui(&mut self, ui: &mut egui::Ui) {
209 let Some(ti) = self.selected else {
210 ui.weak("왼쪽에서 도구를 선택하거나 '+ 새 도구'로 만드세요.");
211 return;
212 };
213 let mut json_mode = self.json_mode;
214 if ui.checkbox(&mut json_mode, "JSON으로 직접 편집").changed() {
215 if json_mode {
216 self.json_text = serde_json::to_string_pretty(&self.tools[ti].to_value()).unwrap_or_default();
217 self.json_error = None;
218 self.json_mode = true;
219 } else {
220 self.leave_json();
221 }
222 }
223 ui.add_space(4.0);
224
225 if self.json_mode {
226 let r = ui.add(
227 TextEdit::multiline(&mut self.json_text)
228 .id(Id::unique("tool_json"))
229 .code_editor()
230 .desired_rows(22)
231 .desired_width(f32::INFINITY),
232 );
233 if r.changed() {
234 match serde_json::from_str(&self.json_text)
235 .map_err(|e| e.to_string())
236 .and_then(|v| ToolDef::from_value(&v))
237 {
238 Ok(def) => {
239 self.tools[ti] = def;
240 self.json_error = None;
241 }
242 Err(e) => self.json_error = Some(e),
243 }
244 }
245 if let Some(e) = &self.json_error {
246 warn(ui, e.clone());
247 }
248 ui.weak("Anthropic 형식(input_schema)도 붙여넣을 수 있습니다. 저장은 OpenAI 형식으로 됩니다.");
249 return;
250 }
251
252 let generation = self.generation;
253 let focus_name = std::mem::take(&mut self.focus_name);
254 let tool = &mut self.tools[ti];
255 ui.horizontal(|ui| {
256 ui.label("이름");
257 let r = ui.add(
258 TextEdit::singleline(&mut tool.name)
259 .id(Id::unique(("tool_name", ti)))
260 .hint_text("get_weather")
261 .font(egui::TextStyle::Monospace)
262 .desired_width(300.0),
263 );
264 if focus_name {
265 r.request_focus();
266 }
267 });
268 ui.label("설명");
269 ui.add(
270 TextEdit::multiline(&mut tool.description)
271 .id(Id::unique(("tool_desc", ti)))
272 .hint_text("이 도구가 하는 일")
273 .desired_rows(2)
274 .desired_width(f32::INFINITY),
275 );
276 ui.add_space(6.0);
277 ui.strong("파라미터");
278 ui.horizontal(|ui| {
279 let w = |ui: &mut egui::Ui, width: f32, text: &str| {
280 ui.add_sized([width, 16.0], egui::Label::new(RichText::new(text).small().weak()));
281 };
282 w(ui, 150.0, "이름");
283 w(ui, 115.0, "타입");
284 w(ui, 34.0, "필수");
285 w(ui, 260.0, "설명");
286 w(ui, 170.0, "허용 값 (쉼표로 구분)");
287 });
288
289 enum RowAction {
290 Up(usize),
291 Down(usize),
292 Remove(usize),
293 }
294 let mut action = None;
295 let n = tool.params.len();
296 for (k, p) in tool.params.iter_mut().enumerate() {
297 ui.horizontal(|ui| {
298 ui.add(
299 TextEdit::singleline(&mut p.name)
300 .id(Id::unique(("pname", ti, k)))
301 .hint_text("이름")
302 .font(egui::TextStyle::Monospace)
303 .desired_width(150.0),
304 );
305 let mut ty = p.ty;
306 ComboBox::from_id_salt(("ptype", ti, k)).width(115.0).selected_text(ty.label()).show_ui(ui, |ui| {
307 for t in ParamType::ALL {
308 ui.selectable_value(&mut ty, t, t.label());
309 }
310 });
311 p.set_type(ty);
312 ui.add_sized([34.0, 22.0], egui::Checkbox::without_text(&mut p.required))
313 .on_hover_text("필수 인자");
314 ui.add(
315 TextEdit::singleline(&mut p.description)
316 .id(Id::unique(("pdesc", ti, k)))
317 .hint_text("설명")
318 .desired_width(260.0),
319 );
320 if p.ty.supports_enum() {
321 enum_field(ui, Id::unique(("penum", ti, k, generation)), &mut p.enum_values);
322 } else {
323 ui.add_space(178.0);
324 }
325 if ui.add_enabled(k > 0, egui::Button::new("↑").small()).clicked() {
326 action = Some(RowAction::Up(k));
327 }
328 if ui.add_enabled(k + 1 < n, egui::Button::new("↓").small()).clicked() {
329 action = Some(RowAction::Down(k));
330 }
331 if ui.small_button("✕").on_hover_text("파라미터 삭제").clicked() {
332 action = Some(RowAction::Remove(k));
333 }
334 });
335 if p.ty == ParamType::Raw {
336 ui.add(
337 TextEdit::multiline(&mut p.raw)
338 .id(Id::unique(("praw", ti, k)))
339 .code_editor()
340 .desired_rows(4)
341 .desired_width(f32::INFINITY),
342 );
343 }
344 }
345 match action {
346 Some(RowAction::Up(k)) => tool.params.swap(k, k - 1),
347 Some(RowAction::Down(k)) => tool.params.swap(k, k + 1),
348 Some(RowAction::Remove(k)) => {
349 tool.params.remove(k);
350 }
351 None => {}
352 }
353 if action.is_some() {
354 self.generation += 1;
355 }
356 let tool = &mut self.tools[ti];
357 if ui.button("+ 파라미터 추가").clicked() {
358 tool.params.push(Param::default());
359 }
360 for p in tool.problems() {
361 warn(ui, p);
362 }
363 if self.tools.iter().filter(|t| t.name == self.tools[ti].name).count() > 1 {
364 ui.weak("같은 이름의 도구가 여러 개 있습니다(변형). tools 메시지에서는 정의가 정확히 같은 것만 체크됩니다.");
365 }
366 ui.add_space(6.0);
367 egui::CollapsingHeader::new("JSON 미리보기").id_salt(("tool_preview", ti)).show(ui, |ui| {
368 let json = serde_json::to_string_pretty(&self.tools[ti].to_value()).unwrap_or_default();
369 ui.add(egui::Label::new(RichText::new(json).monospace()).wrap());
370 });
371 }
372}
373
374/// 쉼표로 구분한 허용 값 입력란. 입력 중인 텍스트(빈 항목, 끝 쉼표)를 유지하기 위해 별도 버퍼를 쓴다.
375fn enum_field(ui: &mut egui::Ui, id: Id, values: &mut Vec<String>) {
376 let mut buf: String = ui.data_mut(|d| d.get_temp_mut_or_insert_with(id, || values.join(", ")).clone());
377 let r = ui.add(TextEdit::singleline(&mut buf).id(id.with("edit")).hint_text("a, b, c").desired_width(170.0));
378 if r.changed() {
379 *values = buf.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
380 }
381 ui.data_mut(|d| d.insert_temp(id, buf));
382}
383
384// ---------------------------------------------------------------------------
385// tools 메시지 편집
386// ---------------------------------------------------------------------------
387
388/// tools 역할 메시지 편집. 라이브러리 편집기를 열어야 하면 `open_library`에 선택할 도구 이름을 넣는다.
389pub fn tools_message_fields(
390 ui: &mut egui::Ui,
391 msg: &mut Message,
392 json_tab: &mut bool,
393 library: &mut ToolLibrary,
394 open_library: &mut Option<Option<String>>,
395 focus: bool,
396) {
397 ui.horizontal(|ui| {
398 ui.selectable_value(json_tab, false, "라이브러리에서 선택");
399 ui.selectable_value(json_tab, true, "JSON 직접 편집");
400 ui.separator();
401 if ui.button("도구 라이브러리 편집…").clicked() {
402 *open_library = Some(None);
403 }
404 });
405 ui.add_space(4.0);
406
407 if *json_tab {
408 let r = ui.add(
409 TextEdit::multiline(&mut msg.content)
410 .id(Id::unique("editor_content"))
411 .code_editor()
412 .desired_rows(14)
413 .desired_width(f32::INFINITY),
414 );
415 if focus {
416 r.request_focus();
417 }
418 if let Err(e) = parse_tool_list(&msg.content) {
419 warn(ui, format!("도구 목록 형식이 아닙니다: {e}"));
420 }
421 return;
422 }
423
424 let mut list = match parse_tool_list(&msg.content) {
425 Ok(l) => l,
426 Err(e) => {
427 warn(ui, format!("현재 내용이 도구 목록 형식이 아닙니다: {e}"));
428 ui.weak("'JSON 직접 편집' 탭에서 고쳐 주세요.");
429 return;
430 }
431 };
432 let mut changed = false;
433
434 if library.tools.is_empty() {
435 ui.weak("도구 라이브러리가 비어 있습니다. '도구 라이브러리 편집…'에서 도구를 정의하세요.");
436 }
437 let mut edit_request = None;
438 for lt in &library.tools {
439 let pos = list.iter().position(|t| t == lt);
440 let mut on = pos.is_some();
441 ui.horizontal(|ui| {
442 if ui.checkbox(&mut on, RichText::new(signature(lt)).monospace()).changed() {
443 match pos {
444 Some(p) => {
445 list.remove(p);
446 }
447 None => list.push(lt.clone()),
448 }
449 changed = true;
450 }
451 if !lt.description.is_empty() {
452 ui.weak(one_line(&lt.description, 70));
453 }
454 if ui.small_button("✎").on_hover_text("라이브러리에서 이 도구 편집").clicked() {
455 edit_request = Some(lt.name.clone());
456 }
457 });
458 }
459 if let Some(name) = edit_request {
460 *open_library = Some(Some(name));
461 }
462
463 // 라이브러리에 정확히 같은 정의가 없는 도구들.
464 let extras: Vec<usize> = (0..list.len()).filter(|&i| !library.tools.contains(&list[i])).collect();
465 if !extras.is_empty() {
466 ui.separator();
467 ui.label("라이브러리와 다른 도구 (이 메시지에만 있음)");
468 enum Fix {
469 Remove(usize),
470 UseLibrary(usize),
471 AddToLibrary(usize),
472 }
473 let mut fix = None;
474 for &i in &extras {
475 let t = &list[i];
476 ui.horizontal(|ui| {
477 let mut on = true;
478 if ui.checkbox(&mut on, RichText::new(signature(t)).monospace()).changed() {
479 fix = Some(Fix::Remove(i));
480 }
481 if library.get(&t.name).is_some() {
482 ui.colored_label(ui.visuals().warn_fg_color, "라이브러리 정의와 다름");
483 if ui.small_button("라이브러리 버전으로 교체").clicked() {
484 fix = Some(Fix::UseLibrary(i));
485 }
486 }
487 if ui.small_button("라이브러리에 추가").clicked() {
488 fix = Some(Fix::AddToLibrary(i));
489 }
490 });
491 }
492 match fix {
493 Some(Fix::Remove(i)) => {
494 list.remove(i);
495 changed = true;
496 }
497 Some(Fix::UseLibrary(i)) => {
498 if let Some(lt) = library.get(&list[i].name) {
499 list[i] = lt.clone();
500 changed = true;
501 }
502 }
503 Some(Fix::AddToLibrary(i)) => {
504 library.tools.push(list[i].clone());
505 library.dirty = true;
506 }
507 None => {}
508 }
509 }
510
511 if changed {
512 msg.content = tool_list_to_json(&list);
513 msg.content_is_json = true;
514 }
515 ui.add_space(4.0);
516 ui.weak(format!("이 메시지에 들어간 도구 {}개 · 체크한 순서대로 저장됩니다.", list.len()));
517}
518
519// ---------------------------------------------------------------------------
520// 도구 호출 / 도구 결과 편집
521// ---------------------------------------------------------------------------
522
523/// assistant 메시지의 도구 호출 목록. `available`은 자동완성/검증에 쓰는 도구 정의.
524pub fn tool_calls_fields(ui: &mut egui::Ui, calls: &mut Vec<ToolCall>, available: &[ToolDef], source: &str) {
525 ui.horizontal(|ui| {
526 ui.label(format!("도구 호출 ({})", calls.len()));
527 if ui.button("+ 도구 호출 추가").clicked() {
528 let mut n = calls.len() + 1;
529 while calls.iter().any(|c| c.id == format!("call_{n}")) {
530 n += 1;
531 }
532 calls.push(ToolCall { id: format!("call_{n}"), ..Default::default() });
533 }
534 ui.weak(format!("· 사용 가능한 도구: {source} 기준 {}개", available.len()));
535 });
536 let mut remove = None;
537 for (k, tc) in calls.iter_mut().enumerate() {
538 Frame::group(ui.style()).show(ui, |ui| {
539 ui.set_width(ui.available_width());
540 ui.horizontal(|ui| {
541 let label = ui.label("이름");
542 let mut picked = name_field(ui, k, &mut tc.name, available, label.id);
543 ComboBox::from_id_salt(("tc_pick", k)).selected_text("도구 선택 ▾").width(110.0).show_ui(ui, |ui| {
544 if available.is_empty() {
545 ui.weak("정의된 도구가 없습니다");
546 }
547 for def in available {
548 let r = ui.selectable_label(def.name == tc.name, RichText::new(signature(def)).monospace());
549 let r = if def.description.is_empty() { r } else { r.on_hover_text(&def.description) };
550 if r.clicked() {
551 picked = Some(def);
552 }
553 }
554 });
555 if let Some(def) = picked {
556 tc.name = def.name.clone();
557 // 이미 쓴 값은 유지하고, 빠진 필수 인자만 채운다.
558 if let Some(filled) = fill_missing_required(def, &tc.arguments) {
559 tc.arguments = filled;
560 }
561 }
562 ui.label("id");
563 ui.add(TextEdit::singleline(&mut tc.id).id(Id::unique(("tc_id", k))).desired_width(110.0));
564 ui.checkbox(&mut tc.args_as_string, "문자열로")
565 .on_hover_text("OpenAI 형식처럼 arguments를 JSON 문자열로 저장합니다.");
566 if ui.button("삭제").clicked() {
567 remove = Some(k);
568 }
569 });
570
571 let def = available.iter().find(|d| d.name == tc.name);
572 match def {
573 Some(def) => {
574 let mode_id = Id::unique(("tc_json_mode", k));
575 let mut json_mode = ui.data(|d| d.get_temp::<bool>(mode_id)).unwrap_or(false);
576 ui.horizontal(|ui| {
577 ui.selectable_value(&mut json_mode, false, "폼");
578 ui.selectable_value(&mut json_mode, true, "JSON");
579 let mut line = signature(def);
580 if !def.description.is_empty() {
581 line = format!("{line} — {}", one_line(&def.description, 80));
582 }
583 ui.weak(line);
584 });
585 ui.data_mut(|d| d.insert_temp(mode_id, json_mode));
586 if json_mode {
587 args_json_editor(ui, k, &mut tc.arguments);
588 } else {
589 args_form(ui, k, def, &mut tc.arguments);
590 }
591 let warnings = def.validate_args(&tc.arguments);
592 let missing = tools::args_object(&tc.arguments)
593 .map(|o| def.params.iter().any(|p| p.required && !o.contains_key(&p.name)))
594 .unwrap_or(false);
595 for w in &warnings {
596 warn(ui, w.clone());
597 }
598 if missing
599 && ui.small_button("빠진 필수 인자 채우기").clicked()
600 && let Some(filled) = fill_missing_required(def, &tc.arguments)
601 {
602 tc.arguments = filled;
603 }
604 }
605 None => {
606 if !tc.name.is_empty() && !available.is_empty() {
607 warn(ui, format!("'{}'은(는) 사용 가능한 도구 목록에 없습니다", tc.name));
608 }
609 ui.label("arguments (JSON)");
610 args_json_editor(ui, k, &mut tc.arguments);
611 if serde_json::from_str::<serde_json::Value>(&tc.arguments).is_err() {
612 warn(ui, "올바른 JSON이 아닙니다 — 문자열 그대로 저장됩니다.");
613 }
614 }
615 }
616 });
617 }
618 if let Some(k) = remove {
619 calls.remove(k);
620 }
621}
622
623/// 이름 입력 중에 일치하는 도구 이름을 흐린 글씨로 이어 보여 주고, Tab으로 확정한다.
624/// 확정되면 그 도구 정의를 돌려준다(인자 뼈대 채우기용).
625fn name_field<'a>(
626 ui: &mut egui::Ui,
627 k: usize,
628 name: &mut String,
629 available: &'a [ToolDef],
630 label_id: Id,
631) -> Option<&'a ToolDef> {
632 let id = Id::unique(("tc_name", k));
633 let suggest = |text: &str| -> Option<&'a ToolDef> {
634 if text.is_empty() {
635 return None;
636 }
637 let lower = text.to_lowercase();
638 available.iter().find(|d| d.name != text && d.name.to_lowercase().starts_with(&lower))
639 };
640 let focused = ui.memory(|m| m.has_focus(id));
641 let mut accepted = None;
642 if focused
643 && let Some(def) = suggest(name)
644 && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab))
645 {
646 *name = def.name.clone();
647 accepted = Some(def);
648 // 커서를 끝으로.
649 if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), id) {
650 let end = egui::text::CCursor::new(name.chars().count());
651 state.cursor.set_char_range(Some(egui::text::CCursorRange::one(end)));
652 state.store(ui.ctx(), id);
653 }
654 }
655 // 제안이 떠 있는 동안에는 Tab이 다음 칸으로 넘어가지 않도록 포커스를 잡아 둔다.
656 let has_suggestion = suggest(name).is_some();
657 let output = TextEdit::singleline(name)
658 .id(id)
659 .hint_text("도구 이름 (Tab: 자동완성)")
660 .font(egui::TextStyle::Monospace)
661 .lock_focus(has_suggestion)
662 .desired_width(220.0)
663 .show(ui);
664 let response = output.response.response.labelled_by(label_id);
665 if response.has_focus()
666 && let Some(def) = suggest(name)
667 {
668 let typed = name.chars().count();
669 let rest: String = def.name.chars().skip(typed).collect();
670 let font = egui::TextStyle::Monospace.resolve(ui.style());
671 let color = ui.visuals().weak_text_color();
672 let pos = output.galley_pos + egui::vec2(output.galley.size().x, 0.0);
673 ui.painter().with_clip_rect(output.text_clip_rect).text(pos, egui::Align2::LEFT_TOP, rest, font, color);
674 }
675 accepted
676}
677
678fn args_json_editor(ui: &mut egui::Ui, k: usize, args: &mut String) {
679 ui.add(
680 TextEdit::multiline(args)
681 .id(Id::unique(("tc_args", k)))
682 .code_editor()
683 .desired_rows(14)
684 .desired_width(f32::INFINITY),
685 );
686}
687
688/// 포커스가 있는 동안에는 입력 중인 텍스트(임시 버퍼)를 유지하고, 아니면 실제 값으로 다시 맞추는 여러 줄 입력란.
689/// 현재 버퍼 텍스트와 변경 여부를 돌려준다.
690fn buffered_multiline(ui: &mut egui::Ui, id: Id, canonical: String, rows: usize, hint: &str) -> (String, bool) {
691 let edit_id = id.with("edit");
692 let focused = ui.memory(|m| m.has_focus(edit_id));
693 let mut buf = if focused { ui.data(|d| d.get_temp::<String>(id)).unwrap_or(canonical) } else { canonical };
694 let r = ui.add(
695 TextEdit::multiline(&mut buf)
696 .id(edit_id)
697 .code_editor()
698 .hint_text(hint)
699 .desired_rows(rows)
700 .desired_width(f32::INFINITY),
701 );
702 ui.data_mut(|d| d.insert_temp(id, buf.clone()));
703 (buf, r.changed())
704}
705
706/// 도구 정의를 보고 파라미터마다 입력란을 만든다. 문자열은 그대로 입력하면 되고 JSON 이스케이프는 자동.
707fn args_form(ui: &mut egui::Ui, k: usize, def: &ToolDef, args: &mut String) {
708 use serde_json::Value;
709 let mut obj = match tools::args_object(args) {
710 Ok(o) => o,
711 Err(e) => {
712 warn(ui, format!("{e} — 폼으로 보여 줄 수 없어 JSON으로 표시합니다."));
713 args_json_editor(ui, k, args);
714 return;
715 }
716 };
717 let free_strings =
718 def.params.iter().filter(|p| p.ty == ParamType::String && p.enum_values.is_empty()).count();
719 // 인자 입력란은 넉넉하게. 긴 문자열 인자가 적을수록 더 높게.
720 let rows = match free_strings {
721 0 | 1 => 14,
722 2 => 10,
723 _ => 7,
724 };
725 let mut changed = false;
726
727 if def.params.is_empty() {
728 ui.weak("이 도구는 인자가 없습니다.");
729 }
730 for p in &def.params {
731 let present = obj.contains_key(&p.name);
732 let label = ui
733 .horizontal(|ui| {
734 let text = if p.required { format!("{} *", p.name) } else { p.name.clone() };
735 let label = ui.label(RichText::new(text).monospace().strong());
736 ui.weak(p.ty.label());
737 if !p.description.is_empty() {
738 ui.weak(one_line(&p.description, 90));
739 }
740 if !p.required {
741 if present {
742 if ui.small_button("✕ 빼기").on_hover_text("선택 인자를 arguments에서 뺍니다").clicked() {
743 obj.remove(&p.name);
744 changed = true;
745 }
746 } else if ui.small_button("+ 넣기").on_hover_text("선택 인자를 arguments에 넣습니다").clicked() {
747 obj.insert(p.name.clone(), p.default_value());
748 changed = true;
749 }
750 }
751 label
752 })
753 .inner;
754 if !p.required && !obj.contains_key(&p.name) {
755 continue;
756 }
757 let fid = Id::unique(("tc_arg", k, p.name.as_str()));
758 let current = obj.get(&p.name).cloned();
759 match p.ty {
760 ParamType::String if !p.enum_values.is_empty() => {
761 let cur = current.as_ref().and_then(Value::as_str).unwrap_or_default().to_string();
762 let mut sel = cur.clone();
763 ComboBox::from_id_salt(fid).selected_text(if cur.is_empty() { "(선택)" } else { cur.as_str() }).show_ui(
764 ui,
765 |ui| {
766 for v in &p.enum_values {
767 ui.selectable_value(&mut sel, v.clone(), v);
768 }
769 },
770 );
771 if sel != cur || current.is_none() && !sel.is_empty() {
772 obj.insert(p.name.clone(), Value::String(sel));
773 changed = true;
774 }
775 }
776 ParamType::String => {
777 let original = match &current {
778 Some(Value::String(s)) => s.clone(),
779 Some(other) => other.to_string(),
780 None => String::new(),
781 };
782 let mut text = original.clone();
783 // 서식 단축키(Ctrl+B 등)는 입력란을 그리기 전에 텍스트를 바꾼다.
784 crate::markup_ui::shortcuts(ui, fid, &mut text);
785 let r = ui.add(
786 TextEdit::multiline(&mut text)
787 .id(fid)
788 .hint_text("그대로 입력/붙여넣기 하세요 (따옴표·줄바꿈 자동 처리)")
789 .desired_rows(rows)
790 .desired_width(f32::INFINITY),
791 );
792 r.labelled_by(label.id);
793 if text != original {
794 obj.insert(p.name.clone(), Value::String(text));
795 changed = true;
796 }
797 }
798 ParamType::Integer => {
799 let mut v = current.as_ref().and_then(Value::as_i64).unwrap_or(0);
800 if ui.add(egui::DragValue::new(&mut v).speed(0.2)).changed() {
801 obj.insert(p.name.clone(), Value::from(v));
802 changed = true;
803 }
804 }
805 ParamType::Number => {
806 let mut v = current.as_ref().and_then(Value::as_f64).unwrap_or(0.0);
807 if ui.add(egui::DragValue::new(&mut v).speed(0.1)).changed() {
808 let num = serde_json::Number::from_f64(v).map(Value::Number).unwrap_or(Value::from(0));
809 obj.insert(p.name.clone(), num);
810 changed = true;
811 }
812 }
813 ParamType::Boolean => {
814 let mut v = current.as_ref().and_then(Value::as_bool).unwrap_or(false);
815 if ui.checkbox(&mut v, "true").changed() {
816 obj.insert(p.name.clone(), Value::Bool(v));
817 changed = true;
818 }
819 }
820 ParamType::StringArray | ParamType::NumberArray | ParamType::IntegerArray | ParamType::BooleanArray => {
821 let canonical = tools::array_to_lines(current.as_ref());
822 let (buf, edited) = buffered_multiline(ui, fid, canonical, 6, "한 줄에 한 항목");
823 match tools::lines_to_array(p.ty, &buf) {
824 Ok(v) => {
825 if edited {
826 obj.insert(p.name.clone(), v);
827 changed = true;
828 }
829 }
830 Err(e) => warn(ui, e),
831 }
832 if !p.enum_values.is_empty() {
833 ui.weak(format!("허용 값: {}", p.enum_values.join(", ")));
834 }
835 }
836 ParamType::Raw => {
837 let canonical =
838 current.as_ref().map(|v| serde_json::to_string_pretty(v).unwrap_or_default()).unwrap_or_default();
839 let (buf, edited) = buffered_multiline(ui, fid, canonical, 8, "JSON 값");
840 if !buf.trim().is_empty() {
841 match serde_json::from_str::<Value>(&buf) {
842 Ok(v) => {
843 if edited {
844 obj.insert(p.name.clone(), v);
845 changed = true;
846 }
847 }
848 Err(e) => warn(ui, format!("JSON 오류: {e}")),
849 }
850 }
851 }
852 }
853 ui.add_space(6.0);
854 }
855
856 // 정의에 없는 인자
857 let extras: Vec<String> = obj.keys().filter(|k| def.param(k).is_none()).cloned().collect();
858 for key in extras {
859 ui.horizontal(|ui| {
860 warn(ui, format!("정의에 없는 인자 '{key}'"));
861 if ui.small_button("삭제").clicked() {
862 obj.remove(&key);
863 changed = true;
864 }
865 });
866 }
867
868 if changed {
869 *args = tools::args_to_text(def, &obj);
870 }
871}
872
873/// tool 메시지의 tool_call_id 입력 + 직전 assistant의 도구 호출 목록에서 고르기.
874pub fn tool_call_id_field(ui: &mut egui::Ui, id: &mut String, choices: &[(String, String)]) {
875 ui.horizontal(|ui| {
876 ui.label("tool_call_id");
877 ui.add(TextEdit::singleline(id).id(Id::unique("editor_tool_call_id")).desired_width(200.0));
878 if !choices.is_empty() {
879 ComboBox::from_id_salt("tool_call_pick").selected_text("호출 선택 ▾").width(110.0).show_ui(ui, |ui| {
880 for (cid, name) in choices {
881 if ui.selectable_label(cid == id, format!("{cid} — {name}")).clicked() {
882 *id = cid.clone();
883 }
884 }
885 });
886 if let Some((_, name)) = choices.iter().find(|(c, _)| c == id) {
887 ui.weak(format!("→ {name}"));
888 } else if !id.is_empty() {
889 ui.colored_label(Color32::from_rgb(220, 160, 60), "직전 assistant의 호출 id와 다릅니다");
890 }
891 }
892 });
893}