leejunyoung5819handmade-dataset-creator

공개

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

데이터셋 편집기 프로젝트 초기 등록

작성자
LeeJunyoung
작성 시각
커밋
2fe0ace9dd025ef625a27fc886a1ea9930e70bf7
부모
없음 (첫 커밋)
이 시점의 파일 보기

변경된 파일 18개

+2,892-0

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

추가.gitignore+2-0
@@ -0,0 +1,2 @@
1추가: /target/
2추가: *.jsonl
추가Cargo.lock

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가Cargo.toml+23-0
@@ -0,0 +1,23 @@
1추가: [package]
2추가: name = "handmade-dataset-creator"
3추가: version = "0.1.0"
4추가: edition = "2024"
5추가: description = "손수 고품질 LLM 대화 데이터셋(.jsonl)을 빠르게 만들기 위한 가벼운 편집기"
6추가:
7추가: [dependencies]
8추가: eframe = { version = "0.37.0", default-features = false, features = ["glow", "wayland", "x11", "default_fonts", "system_fonts", "clipboard", "accesskit"] }
9추가: rfd = "0.18.0"
10추가: serde = { version = "1.0.229", features = ["derive"] }
11추가: serde_json = { version = "1.0.154", features = ["preserve_order"] }
12추가:
13추가: [profile.release]
14추가: opt-level = 3
15추가: lto = "thin"
16추가: codegen-units = 1
17추가: strip = true
18추가:
19추가: [profile.dev.package."*"]
20추가: opt-level = 2
21추가:
22추가: [dev-dependencies]
23추가: egui_kittest = { version = "0.37.0", features = ["eframe"] }
추가PLANS.md+77-0
@@ -0,0 +1,77 @@
1추가: # handmade-dataset-creator에 대해여
2추가:
3추가: handmade-dataset-creator는 이름 그대로, 손수 고품질 LLM 데이터셋을 제작하기로 결정했을때, 생산성을 증폭시키기 위한 프로그램이다.
4추가: 호환은 linux ubuntu 24, 26 LTS만 고려한다. (윈도우즈에서는 실행 안되도 상관없음.)
5추가:
6추가: 데이터셋은 .jsonl 파일로 저장된다.
7추가:
8추가: # 기술 스택과 개발 원칙
9추가: - Rust를 사용한다.
10추가: - 가볍고, 빠르며, 핵심 기능만 간편하게 있는 것을 목표로 한다.
11추가: - 프로그램 반응 속도가 빨라야한다.
12추가: - UI는 FeatherPad, Notepad++ 같은 프로그램 처럼 간편하고 직관적이어야 한다. UI가 아름다울 필요 없다.
13추가:
14추가: # 기능
15추가:
16추가: ## 기능 - 불러오기
17추가: 화면 상단에는 가로로 긴 메뉴바가 있는데, 거기서 '파일' -> '불러오기'를 눌러 저장된 .jsonl 파일을 불러올 수 있다.
18추가: 이때 작업 중인 .jsonl을 저장하지 않았다면
19추가: ```
20추가: 저장되지 않은 변경사항이 있습니다. 저장하시겠습니까?
21추가: [저장하지 않고 계속] [저장 후 계속] [취소]
22추가: ```
23추가: 메세지 박스가 출력되어야 한다.
24추가:
25추가: ## 기능 - 저장하기
26추가: Ctrl + S를 누르면 파일을 저장하되, 저장을 한 번 도 하지 않은 상태일 경우, 기본 파일 관리자의 파일 저장 창을 출력한다.
27추가: 만약 한 번이라도 저장하여 메모리에만 .jsonl 데이터가 있지 않고, 실제 파일로 기록되어져 있으며 현재 작업하는 내용이 해당 파일일 경우, 해당 파일에 덮어 저장한다.
28추가:
29추가: Ctrl + Shift + S는 '다른 이름으로 저장' 기능이다. 저장을 한 번도 하지 않은 것 처럼, 기본 파일 관리자의 파일 저장 창이 출력된다.
30추가:
31추가: ## 기능 - 퀵 메뉴
32추가: 1. ` 키를 누르면 마우스 커서 위치에 가로 비율의 작은 검색란에 포커스된다.
33추가: 2. 해당 검색란에 문자열을 입력하면 검색란 아래에 검색된 행동 목록이 나온다.
34추가: 3. 검색된 행동을 마우스로 클릭하거나 Tab을 눌러 아래 항목으로 포커스를 옮기거나 아래 화살표, 위쪽 화살표 키로 행동 항목 포커스를 위, 아래로 옮길 수 있다.
35추가:
36추가: ## 기능 - 대화 생성
37추가: 프로그램의 왼쪽은 사이드바로 대화 턴 목록이 있다.
38추가: 데이터셋의 대화 턴은 많을 수 있으므로 한 번에 모든 대화 턴 목록을 불러오는 것은 지양해야할 것이다.
39추가: 왼쪽 사이드 대화 턴 목록의 빈 공간을 우클릭하여 뜨는 우클릭 메뉴에서 '대화 턴 생성'이라는 항목을 선택하여 새로운 대화 턴을 생성할 수 있다.
40추가:
41추가: ## 기능 - 대화 삭제
42추가: 프로그램의 왼쪽 대화 턴 목록 사이드바에서 특정 대화 턴을 Shift를 누른 상태에서 여러 개를 선택할 수 있으며
43추가: 우클릭 -> '대화 턴 삭재' 또는 Del키를 눌러 한 개 이상의 대화 턴을 삭제할 수 있다.
44추가:
45추가: ## 기능 - 대화 편집
46추가: 프로그램의 핵심 기능이다.
47추가: 대화 턴 편집 화면은 오른쪽 화면이 크게 표시되는데, 여기서 대화 턴을 편집할 수 있다.
48추가: 대화 턴은 system, tools, tool, user, assistant 역할(role)로 구성된다. "system"은 시스템 프롬프트 역할, "tools"는 도구 목록 역할, "tool"는 LLM이 호출한 도구에 대한 결과, "user"는 사용자 메세지, "assistant"는 LLM의 메세지이다.
49추가:
50추가: `Ctrl + A`를 누르면 `메세지 편집 창`이라는 작은 창이 뜨며, 추가할 역할과 메세지를 설정할 수 있다.
51추가: - Ctrl + A를 눌렀을때 이전 메세지의 역할이 "assistant"일 경우, "user"를 메세지 생성 창의 역할 기본값으로 둔다.
52추가: - 역할이 "assistant"일 경우: 생각, 메세지, 도구 호출 영역이 따로 있다. 도구는 기본적으로 여러 개가 호출 가능하다고 가정한다.
53추가: - 메세지 편집 창이 켜지면 메세지 편집 창의 메세지 입력란에 자동 포커스된다.
54추가: `Ctrl + D`를 누르면 선택한 메세지들을 즉시 복제한다.
55추가: `Ctrl + 위쪽 화살표`를 누르면 선택한 메세지들을 한 줄 씩 위로 올린다.
56추가: `Ctrl + 아래 화살표`를 누르면 선택한 메세지들을 한 줄 씩 아래로 내린다.
57추가: `더블클릭`하면 선택된 하나의 메세지를 수정하는 창을 출력한다.
58추가: `Shift + 클릭`을 하면 한 개 이상의 메시지를 한 번에 선택하거나 이미 선택된 메세지의 선택을 해제한다.
59추가: `Ctrl + 클릭`을 하면 이미 선택된 메세지를 유지한채 새로운 메세지를 선택한다. 반대로 이미 선택된 메세지를 클릭한 것이라면, 해당 메세지만 선택을 해제한다.
60추가:
61추가: ## 기능 - Undo & Redo
62추가: 사용자의 실수를 일정 부분 완화시켜줄 수 있는 보조장치이다.
63추가: 제한된 최근 작업 내역을 저장하고 있다가 사용자가 Ctrl + Z 누르면 되돌리기(undo), Ctrl + Shift + Z를 누르면 redo를 수행한다.
64추가:
65추가:
66추가: # 행동
67추가: 행동은 ` 을 눌러 검색란을 열어 검색을 하는 것으로 행동을 검색하고, 검색된 행동 목록에서 특정 행동을 선택하여 그 행동을 실행할 수 있다.
68추가:
69추가: 검색 및 실행 가능한 행동 목록은 아래와 같다:
70추가: - 대화 생성(Create Conversation)
71추가: - 대화 삭제(Delete Conversation)
72추가: - 되돌리기(Undo)
73추가: - 다시하기(Redo)
74추가: - 저장(Save)
75추가: - 불러오기(Load)
76추가: - 다른 이름으로 저장(Save As)
77추가:
추가src/app.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가src/document.rs+174-0
@@ -0,0 +1,174 @@
1추가: //! 열려 있는 데이터셋 문서와 되돌리기/다시하기 기록.
2추가:
3추가: use crate::model::{self, Conversation, Entry};
4추가: use std::path::{Path, PathBuf};
5추가:
6추가: /// 되돌릴 수 있는 편집 하나.
7추가: #[derive(Clone, Debug)]
8추가: pub enum Op {
9추가: /// 대화 하나의 내용을 바꿈.
10추가: Replace { index: usize, before: Box<Entry>, after: Box<Entry> },
11추가: /// 대화 삽입. (최종 위치, 항목) — 위치 오름차순.
12추가: Insert { items: Vec<(usize, Entry)> },
13추가: /// 대화 삭제. (원래 위치, 항목) — 위치 오름차순.
14추가: Remove { items: Vec<(usize, Entry)> },
15추가: }
16추가:
17추가: impl Op {
18추가: fn apply(&self, entries: &mut Vec<Entry>) {
19추가: match self {
20추가: Op::Replace { index, after, .. } => entries[*index] = (**after).clone(),
21추가: Op::Insert { items } => {
22추가: for (i, e) in items {
23추가: entries.insert(*i, e.clone());
24추가: }
25추가: }
26추가: Op::Remove { items } => {
27추가: for (i, _) in items.iter().rev() {
28추가: entries.remove(*i);
29추가: }
30추가: }
31추가: }
32추가: }
33추가:
34추가: fn revert(&self, entries: &mut Vec<Entry>) {
35추가: match self {
36추가: Op::Replace { index, before, .. } => entries[*index] = (**before).clone(),
37추가: Op::Insert { items } => {
38추가: for (i, _) in items.iter().rev() {
39추가: entries.remove(*i);
40추가: }
41추가: }
42추가: Op::Remove { items } => {
43추가: for (i, e) in items {
44추가: entries.insert(*i, e.clone());
45추가: }
46추가: }
47추가: }
48추가: }
49추가:
50추가: /// 실행/되돌린 뒤 보여줄 대화 위치들.
51추가: pub fn affected(&self) -> Vec<usize> {
52추가: match self {
53추가: Op::Replace { index, .. } => vec![*index],
54추가: Op::Insert { items } | Op::Remove { items } => items.iter().map(|(i, _)| *i).collect(),
55추가: }
56추가: }
57추가: }
58추가:
59추가: pub const HISTORY_LIMIT: usize = 200;
60추가:
61추가: pub struct Document {
62추가: pub entries: Vec<Entry>,
63추가: pub path: Option<PathBuf>,
64추가: undo: Vec<(u64, Op)>,
65추가: redo: Vec<(u64, Op)>,
66추가: next_id: u64,
67추가: saved_id: u64,
68추가: }
69추가:
70추가: impl Default for Document {
71추가: fn default() -> Self {
72추가: Document::new()
73추가: }
74추가: }
75추가:
76추가: impl Document {
77추가: pub fn new() -> Self {
78추가: Document { entries: Vec::new(), path: None, undo: Vec::new(), redo: Vec::new(), next_id: 1, saved_id: 0 }
79추가: }
80추가:
81추가: pub fn open(path: &Path) -> std::io::Result<Self> {
82추가: let entries = model::load_entries(path)?;
83추가: Ok(Document { entries, path: Some(path.to_path_buf()), ..Document::new() })
84추가: }
85추가:
86추가: pub fn save_to(&mut self, path: &Path) -> std::io::Result<()> {
87추가: model::save_entries(path, &self.entries)?;
88추가: self.path = Some(path.to_path_buf());
89추가: self.saved_id = self.current_id();
90추가: Ok(())
91추가: }
92추가:
93추가: fn current_id(&self) -> u64 {
94추가: self.undo.last().map(|(id, _)| *id).unwrap_or(0)
95추가: }
96추가:
97추가: pub fn is_dirty(&self) -> bool {
98추가: self.current_id() != self.saved_id
99추가: }
100추가:
101추가: pub fn len(&self) -> usize {
102추가: self.entries.len()
103추가: }
104추가:
105추가: pub fn is_empty(&self) -> bool {
106추가: self.entries.is_empty()
107추가: }
108추가:
109추가: pub fn can_undo(&self) -> bool {
110추가: !self.undo.is_empty()
111추가: }
112추가:
113추가: pub fn can_redo(&self) -> bool {
114추가: !self.redo.is_empty()
115추가: }
116추가:
117추가: pub fn push(&mut self, op: Op) {
118추가: op.apply(&mut self.entries);
119추가: let id = self.next_id;
120추가: self.next_id += 1;
121추가: self.undo.push((id, op));
122추가: if self.undo.len() > HISTORY_LIMIT {
123추가: self.undo.remove(0);
124추가: }
125추가: self.redo.clear();
126추가: }
127추가:
128추가: pub fn undo(&mut self) -> Option<Vec<usize>> {
129추가: let (id, op) = self.undo.pop()?;
130추가: op.revert(&mut self.entries);
131추가: let affected = op.affected();
132추가: self.redo.push((id, op));
133추가: Some(affected)
134추가: }
135추가:
136추가: pub fn redo(&mut self) -> Option<Vec<usize>> {
137추가: let (id, op) = self.redo.pop()?;
138추가: op.apply(&mut self.entries);
139추가: let affected = op.affected();
140추가: self.undo.push((id, op));
141추가: Some(affected)
142추가: }
143추가:
144추가: /// `at` 위치에 새 대화를 만든다.
145추가: pub fn insert_conversation(&mut self, at: usize, conv: Conversation) {
146추가: let at = at.min(self.entries.len());
147추가: self.push(Op::Insert { items: vec![(at, Entry::from_conv(conv))] });
148추가: }
149추가:
150추가: pub fn remove_conversations(&mut self, indices: &[usize]) {
151추가: let mut idx: Vec<usize> = indices.iter().copied().filter(|&i| i < self.entries.len()).collect();
152추가: idx.sort_unstable();
153추가: idx.dedup();
154추가: if idx.is_empty() {
155추가: return;
156추가: }
157추가: let items = idx.into_iter().map(|i| (i, self.entries[i].clone())).collect();
158추가: self.push(Op::Remove { items });
159추가: }
160추가:
161추가: /// 대화 하나를 수정한다. 클로저가 false를 돌려주면 아무 일도 기록하지 않는다.
162추가: /// 파싱에 실패한 대화는 수정할 수 없다(Err).
163추가: pub fn modify<R>(&mut self, index: usize, f: impl FnOnce(&mut Conversation) -> Option<R>) -> Result<Option<R>, String> {
164추가: let entry = self.entries.get_mut(index).ok_or("대화가 없습니다")?;
165추가: let mut conv = entry.conversation()?.clone();
166추가: let before = entry.clone();
167추가: let Some(r) = f(&mut conv) else { return Ok(None) };
168추가: if Some(&conv) == before.parsed() {
169추가: return Ok(Some(r));
170추가: }
171추가: self.push(Op::Replace { index, before: Box::new(before), after: Box::new(Entry::from_conv(conv)) });
172추가: Ok(Some(r))
173추가: }
174추가: }
추가src/lib.rs+5-0
@@ -0,0 +1,5 @@
1추가: pub mod document;
2추가: pub mod markup;
3추가: pub mod model;
4추가: pub mod recent;
5추가: pub mod tools;
추가src/main.rs+22-0
@@ -0,0 +1,22 @@
1추가: #![forbid(unsafe_code)]
2추가:
3추가: mod app;
4추가: mod markup_ui;
5추가: mod tools_ui;
6추가:
7추가: fn main() -> eframe::Result {
8추가: let initial = std::env::args_os().nth(1).map(std::path::PathBuf::from);
9추가: let options = eframe::NativeOptions {
10추가: viewport: eframe::egui::ViewportBuilder::default()
11추가: .with_title("handmade-dataset-creator")
12추가: .with_app_id("handmade-dataset-creator")
13추가: .with_inner_size([1200.0, 800.0])
14추가: .with_min_inner_size([600.0, 400.0]),
15추가: ..Default::default()
16추가: };
17추가: eframe::run_native(
18추가: "handmade-dataset-creator",
19추가: options,
20추가: Box::new(move |cc| Ok(Box::new(app::App::new(cc, initial)))),
21추가: )
22추가: }
추가src/markup.rs+157-0
@@ -0,0 +1,157 @@
1추가: //! 본문 서식 표기 규칙.
2추가: //!
3추가: //! | 서식 | 표기 |
4추가: //! |---|---|
5추가: //! | 굵게 | `**텍스트**` |
6추가: //! | 취소선 | `~~텍스트~~` |
7추가: //! | 밑줄 | `<u>텍스트</u>` |
8추가: //! | 그 밖의 시각적 강조(박스·음영·형광펜 등) | `<mark>텍스트</mark>` (속성 허용: `<mark type="box">`) |
9추가: //!
10추가: //! 저장되는 것은 이 표기가 들어간 평범한 텍스트이고, 편집기는 감싸기 단축키와 목록 미리보기만 제공한다.
11추가:
12추가: use std::ops::Range;
13추가:
14추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
15추가: pub enum Fmt {
16추가: Bold,
17추가: Strike,
18추가: Underline,
19추가: Mark,
20추가: }
21추가:
22추가: impl Fmt {
23추가: pub fn open(self) -> &'static str {
24추가: match self {
25추가: Fmt::Bold => "**",
26추가: Fmt::Strike => "~~",
27추가: Fmt::Underline => "<u>",
28추가: Fmt::Mark => "<mark>",
29추가: }
30추가: }
31추가:
32추가: pub fn close(self) -> &'static str {
33추가: match self {
34추가: Fmt::Bold => "**",
35추가: Fmt::Strike => "~~",
36추가: Fmt::Underline => "</u>",
37추가: Fmt::Mark => "</mark>",
38추가: }
39추가: }
40추가: }
41추가:
42추가: fn byte_of(text: &str, char_idx: usize) -> usize {
43추가: text.char_indices().nth(char_idx).map(|(b, _)| b).unwrap_or(text.len())
44추가: }
45추가:
46추가: fn chars(s: &str) -> usize {
47추가: s.chars().count()
48추가: }
49추가:
50추가: /// 선택 영역(문자 인덱스)에 서식을 토글한다. 새 텍스트와 새 선택 영역(문자 인덱스)을 돌려준다.
51추가: /// - 선택한 텍스트가 이미 표기로 감싸져 있거나, 선택 영역 바로 바깥에 표기가 있으면 표기를 벗긴다.
52추가: /// - 아니면 감싼다. 선택이 없으면 빈 표기를 넣고 커서를 그 사이에 둔다.
53추가: pub fn toggle(text: &str, sel: Range<usize>, fmt: Fmt) -> (String, Range<usize>) {
54추가: let (open, close) = (fmt.open(), fmt.close());
55추가: let (oc, cc) = (chars(open), chars(close));
56추가: let (a, b) = (sel.start.min(sel.end), sel.start.max(sel.end));
57추가: let (ab, bb) = (byte_of(text, a), byte_of(text, b));
58추가: let selected = &text[ab..bb];
59추가:
60추가: // 1) 선택 안쪽 양 끝이 표기
61추가: if selected.len() >= open.len() + close.len() && selected.starts_with(open) && selected.ends_with(close) {
62추가: let inner = &selected[open.len()..selected.len() - close.len()];
63추가: let out = format!("{}{}{}", &text[..ab], inner, &text[bb..]);
64추가: return (out, a..b - oc - cc);
65추가: }
66추가: // 2) 선택 바로 바깥이 표기
67추가: if text[..ab].ends_with(open) && text[bb..].starts_with(close) {
68추가: let out = format!("{}{}{}", &text[..ab - open.len()], selected, &text[bb + close.len()..]);
69추가: return (out, a - oc..b - oc);
70추가: }
71추가: // 3) 감싸기
72추가: let out = format!("{}{open}{selected}{close}{}", &text[..ab], &text[bb..]);
73추가: (out, a + oc..b + oc)
74추가: }
75추가:
76추가: #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
77추가: pub struct Style {
78추가: pub bold: bool,
79추가: pub strike: bool,
80추가: pub underline: bool,
81추가: pub mark: bool,
82추가: }
83추가:
84추가: /// 미리보기용 조각. `marker`가 true면 표기 자체(`**`, `<u>` 등)이다.
85추가: #[derive(Clone, Debug, PartialEq, Eq)]
86추가: pub struct Span {
87추가: pub text: String,
88추가: pub style: Style,
89추가: pub marker: bool,
90추가: }
91추가:
92추가: /// 표기를 해석해 조각으로 나눈다. 표기 문자도 조각으로 남기므로 이어 붙이면 원문과 같다.
93추가: /// 닫히지 않은 표기는 끝까지 적용된다(미리보기에서 실수가 눈에 띄도록).
94추가: pub fn parse(text: &str) -> Vec<Span> {
95추가: let mut out: Vec<Span> = Vec::new();
96추가: let mut style = Style::default();
97추가: let mut buf = String::new();
98추가: let mut i = 0;
99추가: let flush = |buf: &mut String, out: &mut Vec<Span>, style: Style| {
100추가: if !buf.is_empty() {
101추가: out.push(Span { text: std::mem::take(buf), style, marker: false });
102추가: }
103추가: };
104추가: while i < text.len() {
105추가: let rest = &text[i..];
106추가: let marker_len = if rest.starts_with("**") {
107추가: flush(&mut buf, &mut out, style);
108추가: style.bold = !style.bold;
109추가: Some(2)
110추가: } else if rest.starts_with("~~") {
111추가: flush(&mut buf, &mut out, style);
112추가: style.strike = !style.strike;
113추가: Some(2)
114추가: } else if rest.starts_with("<u>") {
115추가: flush(&mut buf, &mut out, style);
116추가: style.underline = true;
117추가: Some(3)
118추가: } else if rest.starts_with("</u>") {
119추가: flush(&mut buf, &mut out, style);
120추가: style.underline = false;
121추가: Some(4)
122추가: } else if rest.starts_with("</mark>") {
123추가: flush(&mut buf, &mut out, style);
124추가: style.mark = false;
125추가: Some(7)
126추가: } else if rest.starts_with("<mark")
127추가: && let Some(end) = rest.find('>')
128추가: && (end == 5 || rest.as_bytes()[5] == b' ')
129추가: && !rest[..end].contains('\n')
130추가: {
131추가: flush(&mut buf, &mut out, style);
132추가: style.mark = true;
133추가: Some(end + 1)
134추가: } else {
135추가: None
136추가: };
137추가: match marker_len {
138추가: Some(n) => {
139추가: // 여는 표기는 바뀐 뒤 스타일, 닫는 표기는 바뀌기 전 스타일로 보이면 어색하므로 표기에는 스타일을 주지 않는다.
140추가: out.push(Span { text: rest[..n].to_string(), style: Style::default(), marker: true });
141추가: i += n;
142추가: }
143추가: None => {
144추가: let ch = rest.chars().next().unwrap();
145추가: buf.push(ch);
146추가: i += ch.len_utf8();
147추가: }
148추가: }
149추가: }
150추가: flush(&mut buf, &mut out, style);
151추가: out
152추가: }
153추가:
154추가: /// 미리보기에서 실제 서식이 하나라도 있는지 (없으면 일반 라벨로 그리면 된다).
155추가: pub fn has_markup(text: &str) -> bool {
156추가: text.contains("**") || text.contains("~~") || text.contains("<u>") || text.contains("<mark")
157추가: }
추가src/markup_ui.rs+98-0
@@ -0,0 +1,98 @@
1추가: //! 서식 표기(`**`, `~~`, `<u>`, `<mark>`)의 편집기 지원: 감싸기 단축키와 목록 미리보기.
2추가:
3추가: use eframe::egui::{
4추가: self, Color32, FontId, Id, Key, Modifiers, Stroke,
5추가: text::{CCursor, CCursorRange, LayoutJob, TextFormat},
6추가: };
7추가: use handmade_dataset_creator::markup::{self, Fmt};
8추가:
9추가: pub const SHORTCUT_HINT: &str = "서식: Ctrl+B 굵게 · Ctrl+U 밑줄 · Ctrl+Shift+X 취소선 · Ctrl+M 강조(<mark>) — 다시 누르면 해제";
10추가:
11추가: /// `id` 입력란에 포커스가 있으면 서식 단축키를 처리한다. 해당 TextEdit을 그리기 **직전에** 호출한다.
12추가: pub fn shortcuts(ui: &mut egui::Ui, id: Id, text: &mut String) {
13추가: if !ui.memory(|m| m.has_focus(id)) {
14추가: return;
15추가: }
16추가: let fmt = ui.input_mut(|i| {
17추가: // Shift가 붙은 조합을 먼저 확인해야 한다.
18추가: if i.consume_key(Modifiers::COMMAND | Modifiers::SHIFT, Key::X) {
19추가: Some(Fmt::Strike)
20추가: } else if i.consume_key(Modifiers::COMMAND, Key::B) {
21추가: Some(Fmt::Bold)
22추가: } else if i.consume_key(Modifiers::COMMAND, Key::U) {
23추가: Some(Fmt::Underline)
24추가: } else if i.consume_key(Modifiers::COMMAND, Key::M) {
25추가: Some(Fmt::Mark)
26추가: } else {
27추가: None
28추가: }
29추가: });
30추가: let Some(fmt) = fmt else { return };
31추가: let mut state = egui::TextEdit::load_state(ui.ctx(), id).unwrap_or_default();
32추가: let n = text.chars().count();
33추가: let range = state
34추가: .cursor
35추가: .char_range()
36추가: .map(|r| {
37추가: let (a, b) = (r.primary.index.0.min(n), r.secondary.index.0.min(n));
38추가: a.min(b)..a.max(b)
39추가: })
40추가: .unwrap_or(n..n);
41추가: let (new_text, sel) = markup::toggle(text, range, fmt);
42추가: *text = new_text;
43추가: state.cursor.set_char_range(Some(CCursorRange::two(CCursor::new(sel.start), CCursor::new(sel.end))));
44추가: state.store(ui.ctx(), id);
45추가: }
46추가:
47추가: /// 표기가 있는 텍스트를 서식이 적용된 레이아웃으로. 표기 자체는 작고 흐리게 그대로 보여 준다.
48추가: pub fn job(ui: &egui::Ui, text: &str, font: FontId, color: Color32, italics: bool) -> LayoutJob {
49추가: let visuals = ui.visuals();
50추가: let mut job = LayoutJob::default();
51추가: job.wrap.max_width = ui.available_width();
52추가: let mark_bg = if visuals.dark_mode {
53추가: Color32::from_rgba_unmultiplied(230, 190, 40, 70)
54추가: } else {
55추가: Color32::from_rgba_unmultiplied(255, 220, 0, 120)
56추가: };
57추가: for span in markup::parse(text) {
58추가: let mut f = TextFormat { font_id: font.clone(), color, italics, ..Default::default() };
59추가: if span.marker {
60추가: f.font_id = FontId::new(font.size * 0.75, font.family.clone());
61추가: f.color = visuals.weak_text_color();
62추가: f.italics = false;
63추가: } else {
64추가: let s = span.style;
65추가: if s.bold {
66추가: f.color = visuals.strong_text_color();
67추가: }
68추가: if s.underline {
69추가: f.underline = Stroke::new(1.5, f.color);
70추가: }
71추가: if s.strike {
72추가: f.strikethrough = Stroke::new(1.5, f.color);
73추가: }
74추가: if s.mark {
75추가: f.background = mark_bg;
76추가: f.expand_bg = 1.0;
77추가: }
78추가: }
79추가: job.append(&span.text, 0.0, f);
80추가: }
81추가: job
82추가: }
83추가:
84추가: /// 서식 미리보기가 적용된 줄바꿈 라벨.
85추가: pub fn label(ui: &mut egui::Ui, text: &str, italics: bool, weak: bool) {
86추가: let font = egui::TextStyle::Body.resolve(ui.style());
87추가: let color = if weak { ui.visuals().weak_text_color() } else { ui.visuals().text_color() };
88추가: if markup::has_markup(text) {
89추가: let job = job(ui, text, font, color, italics);
90추가: ui.add(egui::Label::new(job).wrap());
91추가: } else {
92추가: let mut rt = egui::RichText::new(text).color(color);
93추가: if italics {
94추가: rt = rt.italics();
95추가: }
96추가: ui.add(egui::Label::new(rt).wrap());
97추가: }
98추가: }
추가src/model.rs+548-0
@@ -0,0 +1,548 @@
1추가: //! 데이터셋 모델: .jsonl 한 줄 = 대화 턴 하나.
2추가: //!
3추가: //! 한 줄의 형식은 다음과 같다:
4추가: //! ```json
5추가: //! {"messages": [
6추가: //! {"role": "system", "content": "..."},
7추가: //! {"role": "tools", "content": [ ...도구 스키마... ]},
8추가: //! {"role": "user", "content": "..."},
9추가: //! {"role": "assistant", "reasoning_content": "...", "content": "...",
10추가: //! "tool_calls": [{"id": "...", "type": "function", "function": {"name": "...", "arguments": {...}}}]},
11추가: //! {"role": "tool", "tool_call_id": "...", "content": "..."}
12추가: //! ]}
13추가: //! ```
14추가: //! 모르는 필드는 그대로 보존하며, 수정하지 않은 줄은 원문 그대로 다시 저장된다.
15추가:
16추가: use serde_json::{Map, Value};
17추가: use std::cell::OnceCell;
18추가: use std::fmt;
19추가: use std::io::Write;
20추가: use std::path::Path;
21추가:
22추가: #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
23추가: pub enum Role {
24추가: System,
25추가: Tools,
26추가: Tool,
27추가: User,
28추가: Assistant,
29추가: }
30추가:
31추가: impl Role {
32추가: pub const ALL: [Role; 5] = [Role::System, Role::Tools, Role::User, Role::Assistant, Role::Tool];
33추가:
34추가: pub fn as_str(self) -> &'static str {
35추가: match self {
36추가: Role::System => "system",
37추가: Role::Tools => "tools",
38추가: Role::Tool => "tool",
39추가: Role::User => "user",
40추가: Role::Assistant => "assistant",
41추가: }
42추가: }
43추가:
44추가: pub fn parse(s: &str) -> Option<Role> {
45추가: Some(match s {
46추가: "system" => Role::System,
47추가: "tools" => Role::Tools,
48추가: "tool" => Role::Tool,
49추가: "user" => Role::User,
50추가: "assistant" => Role::Assistant,
51추가: _ => return None,
52추가: })
53추가: }
54추가:
55추가: /// 앞 메시지의 역할만 보고 고르는 기본 역할. (도구 호출 여부까지 보려면 `Conversation::default_role_at`)
56추가: pub fn default_after(prev: Option<Role>) -> Role {
57추가: match prev {
58추가: None => Role::System,
59추가: Some(Role::System) => Role::Tools,
60추가: Some(Role::Tools) => Role::User,
61추가: Some(Role::Assistant) => Role::User,
62추가: Some(Role::User) | Some(Role::Tool) => Role::Assistant,
63추가: }
64추가: }
65추가: }
66추가:
67추가: impl fmt::Display for Role {
68추가: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69추가: f.write_str(self.as_str())
70추가: }
71추가: }
72추가:
73추가: const THINKING_KEYS: [&str; 3] = ["reasoning_content", "thinking", "reasoning"];
74추가: const DEFAULT_THINKING_KEY: &str = "reasoning_content";
75추가:
76추가: #[derive(Clone, Debug, PartialEq)]
77추가: pub struct ToolCall {
78추가: pub id: String,
79추가: pub name: String,
80추가: /// 편집용 문자열. JSON이면 저장할 때 객체로 기록한다(`args_as_string`이 아닐 때).
81추가: pub arguments: String,
82추가: /// 원본이 문자열로 인코딩된 arguments였는지 (OpenAI 형식).
83추가: pub args_as_string: bool,
84추가: pub extra: Map<String, Value>,
85추가: }
86추가:
87추가: impl Default for ToolCall {
88추가: fn default() -> Self {
89추가: ToolCall {
90추가: id: String::new(),
91추가: name: String::new(),
92추가: arguments: "{}".to_string(),
93추가: args_as_string: false,
94추가: extra: Map::new(),
95추가: }
96추가: }
97추가: }
98추가:
99추가: #[derive(Clone, Debug, PartialEq)]
100추가: pub struct Message {
101추가: pub role: Role,
102추가: pub content: String,
103추가: /// content가 문자열이 아닌 JSON 값(배열/객체)이었는지. (예: tools 역할의 스키마 목록)
104추가: pub content_is_json: bool,
105추가: /// assistant 전용: 생각(추론) 내용.
106추가: pub thinking: String,
107추가: thinking_key: Option<String>,
108추가: /// assistant 전용: 도구 호출 목록.
109추가: pub tool_calls: Vec<ToolCall>,
110추가: /// tool 전용: 어떤 도구 호출에 대한 결과인지.
111추가: pub tool_call_id: String,
112추가: pub extra: Map<String, Value>,
113추가: }
114추가:
115추가: impl Message {
116추가: pub fn new(role: Role) -> Self {
117추가: Message {
118추가: role,
119추가: content: if role == Role::Tools { "[]".to_string() } else { String::new() },
120추가: content_is_json: role == Role::Tools,
121추가: thinking: String::new(),
122추가: thinking_key: None,
123추가: tool_calls: Vec::new(),
124추가: tool_call_id: String::new(),
125추가: extra: Map::new(),
126추가: }
127추가: }
128추가:
129추가: pub fn with_content(role: Role, content: impl Into<String>) -> Self {
130추가: let mut m = Message::new(role);
131추가: m.content = content.into();
132추가: m
133추가: }
134추가:
135추가: /// 역할이 바뀌었을 때 content의 JSON 여부를 보정한다.
136추가: pub fn set_role(&mut self, role: Role) {
137추가: if self.role == role {
138추가: return;
139추가: }
140추가: let was_tools = self.role == Role::Tools;
141추가: self.role = role;
142추가: if was_tools {
143추가: // tools용 기본값([])은 다른 역할에서 의미가 없으므로 비우고, 일반 문자열로 저장한다.
144추가: if self.content.trim() == "[]" {
145추가: self.content.clear();
146추가: }
147추가: self.content_is_json = false;
148추가: }
149추가: if role == Role::Tools {
150추가: self.content_is_json = true;
151추가: if self.content.trim().is_empty() {
152추가: self.content = "[]".to_string();
153추가: }
154추가: }
155추가: }
156추가:
157추가: pub fn from_value(v: &Value) -> Result<Message, String> {
158추가: let obj = v.as_object().ok_or("메시지가 JSON 객체가 아닙니다")?;
159추가: let role_str = obj.get("role").and_then(Value::as_str).ok_or("메시지에 role이 없습니다")?;
160추가: let role = Role::parse(role_str).ok_or_else(|| format!("알 수 없는 role: {role_str}"))?;
161추가: let mut msg = Message::new(role);
162추가: msg.content.clear();
163추가: msg.content_is_json = false;
164추가:
165추가: for (k, val) in obj {
166추가: match k.as_str() {
167추가: "role" => {}
168추가: "content" => match val {
169추가: Value::String(s) => msg.content = s.clone(),
170추가: Value::Null => {}
171추가: other => {
172추가: msg.content = serde_json::to_string_pretty(other).unwrap_or_default();
173추가: msg.content_is_json = true;
174추가: }
175추가: },
176추가: key if role == Role::Assistant
177추가: && msg.thinking_key.is_none()
178추가: && THINKING_KEYS.contains(&key)
179추가: && (val.is_string() || val.is_null()) =>
180추가: {
181추가: msg.thinking = val.as_str().unwrap_or_default().to_string();
182추가: msg.thinking_key = Some(key.to_string());
183추가: }
184추가: "tool_calls" if val.is_array() => {
185추가: for tc in val.as_array().unwrap() {
186추가: msg.tool_calls.push(parse_tool_call(tc)?);
187추가: }
188추가: }
189추가: "tool_call_id" if val.is_string() => {
190추가: msg.tool_call_id = val.as_str().unwrap().to_string();
191추가: }
192추가: _ => {
193추가: msg.extra.insert(k.clone(), val.clone());
194추가: }
195추가: }
196추가: }
197추가: Ok(msg)
198추가: }
199추가:
200추가: pub fn to_value(&self) -> Value {
201추가: let mut m = Map::new();
202추가: m.insert("role".into(), Value::String(self.role.as_str().into()));
203추가: if self.role == Role::Assistant && (!self.thinking.is_empty() || self.thinking_key.is_some()) {
204추가: let key = self.thinking_key.as_deref().unwrap_or(DEFAULT_THINKING_KEY);
205추가: m.insert(key.into(), Value::String(self.thinking.clone()));
206추가: }
207추가: let content = if self.content_is_json {
208추가: serde_json::from_str::<Value>(&self.content)
209추가: .unwrap_or_else(|_| Value::String(self.content.clone()))
210추가: } else {
211추가: Value::String(self.content.clone())
212추가: };
213추가: m.insert("content".into(), content);
214추가: if !self.tool_calls.is_empty() {
215추가: let calls = self.tool_calls.iter().map(tool_call_to_value).collect();
216추가: m.insert("tool_calls".into(), Value::Array(calls));
217추가: }
218추가: if !self.tool_call_id.is_empty() {
219추가: m.insert("tool_call_id".into(), Value::String(self.tool_call_id.clone()));
220추가: }
221추가: for (k, v) in &self.extra {
222추가: m.insert(k.clone(), v.clone());
223추가: }
224추가: Value::Object(m)
225추가: }
226추가:
227추가: /// 사이드바/목록에 보여줄 한 줄 요약.
228추가: pub fn summary(&self) -> String {
229추가: let src = if !self.content.trim().is_empty() {
230추가: self.content.as_str()
231추가: } else if !self.tool_calls.is_empty() {
232추가: return format!("[도구 호출 {}개]", self.tool_calls.len());
233추가: } else {
234추가: self.thinking.as_str()
235추가: };
236추가: one_line(src, 120)
237추가: }
238추가: }
239추가:
240추가: fn parse_tool_call(v: &Value) -> Result<ToolCall, String> {
241추가: let obj = v.as_object().ok_or("tool_calls 항목이 객체가 아닙니다")?;
242추가: let mut tc = ToolCall { arguments: String::new(), ..Default::default() };
243추가: // OpenAI 형식({"function": {...}})과 평평한 형식({"name", "arguments"}) 모두 허용.
244추가: let (func, nested) = match obj.get("function").and_then(Value::as_object) {
245추가: Some(f) => (f, true),
246추가: None => (obj, false),
247추가: };
248추가: tc.name = func.get("name").and_then(Value::as_str).unwrap_or_default().to_string();
249추가: match func.get("arguments") {
250추가: Some(Value::String(s)) => {
251추가: tc.args_as_string = true;
252추가: // 보기 좋게 펼쳐서 편집하도록 한다.
253추가: tc.arguments = match serde_json::from_str::<Value>(s) {
254추가: Ok(v) => serde_json::to_string_pretty(&v).unwrap_or_else(|_| s.clone()),
255추가: Err(_) => s.clone(),
256추가: };
257추가: }
258추가: Some(other) => tc.arguments = serde_json::to_string_pretty(other).unwrap_or_default(),
259추가: None => tc.arguments = "{}".into(),
260추가: }
261추가: for (k, val) in obj {
262추가: let skip = match k.as_str() {
263추가: "id" => {
264추가: tc.id = val.as_str().unwrap_or_default().to_string();
265추가: true
266추가: }
267추가: "function" => nested,
268추가: "type" => nested && val == "function",
269추가: "name" | "arguments" => !nested,
270추가: _ => false,
271추가: };
272추가: if !skip {
273추가: tc.extra.insert(k.clone(), val.clone());
274추가: }
275추가: }
276추가: Ok(tc)
277추가: }
278추가:
279추가: fn tool_call_to_value(tc: &ToolCall) -> Value {
280추가: let args = match serde_json::from_str::<Value>(&tc.arguments) {
281추가: Ok(v) if tc.args_as_string => Value::String(serde_json::to_string(&v).unwrap_or_default()),
282추가: Ok(v) => v,
283추가: Err(_) => Value::String(tc.arguments.clone()),
284추가: };
285추가: let mut func = Map::new();
286추가: func.insert("name".into(), Value::String(tc.name.clone()));
287추가: func.insert("arguments".into(), args);
288추가: let mut m = Map::new();
289추가: if !tc.id.is_empty() {
290추가: m.insert("id".into(), Value::String(tc.id.clone()));
291추가: }
292추가: m.insert("type".into(), Value::String("function".into()));
293추가: m.insert("function".into(), Value::Object(func));
294추가: for (k, v) in &tc.extra {
295추가: m.insert(k.clone(), v.clone());
296추가: }
297추가: Value::Object(m)
298추가: }
299추가:
300추가: #[derive(Clone, Debug, Default, PartialEq)]
301추가: pub struct Conversation {
302추가: pub messages: Vec<Message>,
303추가: pub extra: Map<String, Value>,
304추가: }
305추가:
306추가: impl Conversation {
307추가: pub fn parse_line(line: &str) -> Result<Conversation, String> {
308추가: let v: Value = serde_json::from_str(line).map_err(|e| format!("JSON 오류: {e}"))?;
309추가: let obj = v.as_object().ok_or("줄이 JSON 객체가 아닙니다")?;
310추가: let mut conv = Conversation::default();
311추가: for (k, val) in obj {
312추가: if k == "messages" {
313추가: let arr = val.as_array().ok_or("messages가 배열이 아닙니다")?;
314추가: for (i, m) in arr.iter().enumerate() {
315추가: conv.messages.push(Message::from_value(m).map_err(|e| format!("메시지 #{}: {e}", i + 1))?);
316추가: }
317추가: } else {
318추가: conv.extra.insert(k.clone(), val.clone());
319추가: }
320추가: }
321추가: Ok(conv)
322추가: }
323추가:
324추가: pub fn to_line(&self) -> String {
325추가: let mut m = Map::new();
326추가: m.insert("messages".into(), Value::Array(self.messages.iter().map(Message::to_value).collect()));
327추가: for (k, v) in &self.extra {
328추가: m.insert(k.clone(), v.clone());
329추가: }
330추가: serde_json::to_string(&Value::Object(m)).unwrap_or_default()
331추가: }
332추가:
333추가: pub fn preview(&self) -> String {
334추가: let first = self
335추가: .messages
336추가: .iter()
337추가: .find(|m| m.role == Role::User)
338추가: .or_else(|| self.messages.first());
339추가: match first {
340추가: Some(m) => format!("({}) {}", self.messages.len(), m.summary()),
341추가: None => "(빈 대화)".to_string(),
342추가: }
343추가: }
344추가:
345추가: /// `pos` 위치에 새 메시지를 넣을 때(Ctrl+A)의 기본 역할.
346추가: /// - 도구를 호출한 assistant 다음 → tool
347추가: /// - tool 다음: 직전 assistant의 호출 중 결과가 아직 없는 것이 남았으면 tool, 아니면 assistant
348추가: /// - 나머지는 `Role::default_after` (system → tools, assistant → user …)
349추가: pub fn default_role_at(&self, pos: usize) -> Role {
350추가: let before = &self.messages[..pos.min(self.messages.len())];
351추가: let Some(prev) = before.last() else { return Role::System };
352추가: match prev.role {
353추가: Role::Assistant if !prev.tool_calls.is_empty() => Role::Tool,
354추가: Role::Tool => {
355추가: let pending = before.iter().rposition(|m| m.role == Role::Assistant).is_some_and(|ai| {
356추가: let results = before[ai + 1..].iter().filter(|m| m.role == Role::Tool).count();
357추가: results < before[ai].tool_calls.len()
358추가: });
359추가: if pending { Role::Tool } else { Role::Assistant }
360추가: }
361추가: r => Role::default_after(Some(r)),
362추가: }
363추가: }
364추가:
365추가: // ---- 메시지 단위 편집. 모두 새 선택 영역(인덱스 목록)을 돌려준다. ----
366추가:
367추가: /// 선택한 메시지들을 복제해 마지막 선택 메시지 바로 뒤에 넣는다. 복제본이 선택된다.
368추가: pub fn duplicate(&mut self, sel: &[usize]) -> Vec<usize> {
369추가: let mut sel: Vec<usize> = sel.iter().copied().filter(|&i| i < self.messages.len()).collect();
370추가: sel.sort_unstable();
371추가: sel.dedup();
372추가: let Some(&last) = sel.last() else { return Vec::new() };
373추가: let copies: Vec<Message> = sel.iter().map(|&i| self.messages[i].clone()).collect();
374추가: let n = copies.len();
375추가: self.messages.splice(last + 1..last + 1, copies);
376추가: (last + 1..last + 1 + n).collect()
377추가: }
378추가:
379추가: pub fn delete(&mut self, sel: &[usize]) {
380추가: let mut sel: Vec<usize> = sel.to_vec();
381추가: sel.sort_unstable();
382추가: sel.dedup();
383추가: for &i in sel.iter().rev() {
384추가: if i < self.messages.len() {
385추가: self.messages.remove(i);
386추가: }
387추가: }
388추가: }
389추가:
390추가: /// 선택한 메시지들을 한 칸 위로. 맨 위에 붙은 묶음은 움직이지 않는다.
391추가: pub fn move_up(&mut self, sel: &[usize]) -> Vec<usize> {
392추가: let n = self.messages.len();
393추가: let mut flags = vec![false; n];
394추가: for &i in sel {
395추가: if i < n {
396추가: flags[i] = true;
397추가: }
398추가: }
399추가: for i in 1..n {
400추가: if flags[i] && !flags[i - 1] {
401추가: self.messages.swap(i, i - 1);
402추가: flags.swap(i, i - 1);
403추가: }
404추가: }
405추가: (0..n).filter(|&i| flags[i]).collect()
406추가: }
407추가:
408추가: /// 선택한 메시지들을 한 칸 아래로. 맨 아래에 붙은 묶음은 움직이지 않는다.
409추가: pub fn move_down(&mut self, sel: &[usize]) -> Vec<usize> {
410추가: let n = self.messages.len();
411추가: let mut flags = vec![false; n];
412추가: for &i in sel {
413추가: if i < n {
414추가: flags[i] = true;
415추가: }
416추가: }
417추가: for i in (0..n.saturating_sub(1)).rev() {
418추가: if flags[i] && !flags[i + 1] {
419추가: self.messages.swap(i, i + 1);
420추가: flags.swap(i, i + 1);
421추가: }
422추가: }
423추가: (0..n).filter(|&i| flags[i]).collect()
424추가: }
425추가: }
426추가:
427추가: pub fn one_line(s: &str, max_chars: usize) -> String {
428추가: let mut out = String::new();
429추가: let mut count = 0;
430추가: let mut last_space = false;
431추가: for ch in s.trim().chars() {
432추가: let ch = if ch.is_whitespace() { ' ' } else { ch };
433추가: if ch == ' ' && last_space {
434추가: continue;
435추가: }
436추가: last_space = ch == ' ';
437추가: if count >= max_chars {
438추가: out.push('…');
439추가: break;
440추가: }
441추가: out.push(ch);
442추가: count += 1;
443추가: }
444추가: out
445추가: }
446추가:
447추가: /// 데이터셋의 한 줄. 지연 파싱: 화면에 필요할 때만 파싱하고,
448추가: /// 수정되지 않은 줄은 원문(raw)을 그대로 저장한다.
449추가: #[derive(Clone, Debug)]
450추가: pub struct Entry {
451추가: raw: Option<String>,
452추가: conv: Option<Conversation>,
453추가: error: Option<String>,
454추가: preview: OnceCell<String>,
455추가: }
456추가:
457추가: impl Entry {
458추가: pub fn from_raw(raw: String) -> Self {
459추가: Entry { raw: Some(raw), conv: None, error: None, preview: OnceCell::new() }
460추가: }
461추가:
462추가: pub fn from_conv(conv: Conversation) -> Self {
463추가: Entry { raw: None, conv: Some(conv), error: None, preview: OnceCell::new() }
464추가: }
465추가:
466추가: /// 파싱해서 대화를 돌려준다. 실패하면 오류 메시지.
467추가: pub fn conversation(&mut self) -> Result<&Conversation, String> {
468추가: if self.conv.is_none() && self.error.is_none() {
469추가: match Conversation::parse_line(self.raw.as_deref().unwrap_or_default()) {
470추가: Ok(c) => self.conv = Some(c),
471추가: Err(e) => self.error = Some(e),
472추가: }
473추가: }
474추가: match (&self.conv, &self.error) {
475추가: (Some(c), _) => Ok(c),
476추가: (None, Some(e)) => Err(e.clone()),
477추가: (None, None) => unreachable!(),
478추가: }
479추가: }
480추가:
481추가: pub fn parsed(&self) -> Option<&Conversation> {
482추가: self.conv.as_ref()
483추가: }
484추가:
485추가: pub fn raw(&self) -> Option<&str> {
486추가: self.raw.as_deref()
487추가: }
488추가:
489추가: pub fn has_error(&self) -> bool {
490추가: self.error.is_some()
491추가: }
492추가:
493추가: pub fn preview(&self) -> &str {
494추가: self.preview.get_or_init(|| {
495추가: if let Some(c) = &self.conv {
496추가: return c.preview();
497추가: }
498추가: match Conversation::parse_line(self.raw.as_deref().unwrap_or_default()) {
499추가: Ok(c) => c.preview(),
500추가: Err(e) => format!("⚠ {}", one_line(&e, 80)),
501추가: }
502추가: })
503추가: }
504추가:
505추가: pub fn to_line(&self) -> String {
506추가: match (&self.raw, &self.conv) {
507추가: (Some(raw), _) => raw.clone(),
508추가: (None, Some(c)) => c.to_line(),
509추가: (None, None) => String::new(),
510추가: }
511추가: }
512추가:
513추가: /// 메모리를 아끼기 위해 수정되지 않은(원문이 있는) 파싱 결과를 버린다.
514추가: pub fn drop_parsed_cache(&mut self) {
515추가: if self.raw.is_some() {
516추가: self.conv = None;
517추가: self.error = None;
518추가: }
519추가: }
520추가: }
521추가:
522추가: pub fn load_entries(path: &Path) -> std::io::Result<Vec<Entry>> {
523추가: let text = std::fs::read_to_string(path)?;
524추가: let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
525추가: Ok(text
526추가: .lines()
527추가: .map(|l| l.trim_end_matches('\r'))
528추가: .filter(|l| !l.trim().is_empty())
529추가: .map(|l| Entry::from_raw(l.to_string()))
530추가: .collect())
531추가: }
532추가:
533추가: /// 임시 파일에 쓴 뒤 rename 하여, 저장 도중 문제가 생겨도 원본이 깨지지 않게 한다.
534추가: pub fn save_entries(path: &Path, entries: &[Entry]) -> std::io::Result<()> {
535추가: let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
536추가: let tmp = path.with_file_name(format!(".{file_name}.tmp"));
537추가: {
538추가: let f = std::fs::File::create(&tmp)?;
539추가: let mut w = std::io::BufWriter::new(f);
540추가: for e in entries {
541추가: w.write_all(e.to_line().as_bytes())?;
542추가: w.write_all(b"\n")?;
543추가: }
544추가: w.flush()?;
545추가: w.get_ref().sync_all()?;
546추가: }
547추가: std::fs::rename(&tmp, path)
548추가: }
추가src/recent.rs+65-0
@@ -0,0 +1,65 @@
1추가: //! 최근에 연 파일 목록. `~/.config/handmade-dataset-creator/recent.json` 에 저장된다.
2추가:
3추가: use std::path::{Path, PathBuf};
4추가:
5추가: pub const MAX_RECENT: usize = 10;
6추가:
7추가: #[derive(Debug, Default)]
8추가: pub struct RecentFiles {
9추가: pub paths: Vec<PathBuf>,
10추가: /// 저장 위치. None이면 저장하지 않는다(테스트 등).
11추가: store: Option<PathBuf>,
12추가: }
13추가:
14추가: impl RecentFiles {
15추가: /// `$XDG_CONFIG_HOME/handmade-dataset-creator/recent.json` (없으면 `~/.config/...`)
16추가: pub fn default_store() -> Option<PathBuf> {
17추가: let base = std::env::var_os("XDG_CONFIG_HOME")
18추가: .map(PathBuf::from)
19추가: .filter(|p| p.is_absolute())
20추가: .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
21추가: Some(base.join("handmade-dataset-creator").join("recent.json"))
22추가: }
23추가:
24추가: /// 저장 위치에서 읽는다. 파일이 없거나 깨져 있으면 빈 목록.
25추가: pub fn load(store: Option<PathBuf>) -> Self {
26추가: let paths = store
27추가: .as_deref()
28추가: .and_then(|p| std::fs::read_to_string(p).ok())
29추가: .and_then(|t| serde_json::from_str::<Vec<PathBuf>>(&t).ok())
30추가: .unwrap_or_default();
31추가: let mut r = RecentFiles { paths, store };
32추가: r.paths.truncate(MAX_RECENT);
33추가: r
34추가: }
35추가:
36추가: /// 맨 앞에 추가(이미 있으면 앞으로 이동)하고 저장.
37추가: pub fn add(&mut self, path: &Path) {
38추가: let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
39추가: self.paths.retain(|p| p != &path);
40추가: self.paths.insert(0, path);
41추가: self.paths.truncate(MAX_RECENT);
42추가: self.save();
43추가: }
44추가:
45추가: pub fn remove(&mut self, path: &Path) {
46추가: self.paths.retain(|p| p != path);
47추가: self.save();
48추가: }
49추가:
50추가: pub fn clear(&mut self) {
51추가: self.paths.clear();
52추가: self.save();
53추가: }
54추가:
55추가: fn save(&self) {
56추가: let Some(store) = &self.store else { return };
57추가: if let Some(dir) = store.parent() {
58추가: let _ = std::fs::create_dir_all(dir);
59추가: }
60추가: // 최근 파일 목록은 부가 기능이라, 저장 실패는 조용히 무시한다.
61추가: if let Ok(text) = serde_json::to_string_pretty(&self.paths) {
62추가: let _ = std::fs::write(store, text);
63추가: }
64추가: }
65추가: }
추가src/tools.rs+629-0
@@ -0,0 +1,629 @@
1추가: //! 도구(함수) 정의: 폼으로 편집할 수 있는 구조와 JSON 변환, 도구 라이브러리.
2추가: //!
3추가: //! 저장 형식은 OpenAI 형식이다:
4추가: //! `{"type":"function","function":{"name":...,"description":...,"parameters":{JSON Schema}}}`
5추가: //! 읽을 때는 Anthropic 형식(`input_schema`)과 평평한 형식(`{"name","parameters"}`)도 받아들인다.
6추가:
7추가: use crate::model::{Entry, Role};
8추가: use serde_json::{Map, Value};
9추가: use std::path::{Path, PathBuf};
10추가:
11추가: /// 폼에서 고를 수 있는 파라미터 타입.
12추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
13추가: pub enum ParamType {
14추가: String,
15추가: Number,
16추가: Integer,
17추가: Boolean,
18추가: StringArray,
19추가: NumberArray,
20추가: IntegerArray,
21추가: BooleanArray,
22추가: /// 폼으로 표현하기 어려운 스키마(중첩 객체 등)는 JSON Schema를 직접 편집한다.
23추가: Raw,
24추가: }
25추가:
26추가: impl ParamType {
27추가: pub const ALL: [ParamType; 9] = [
28추가: ParamType::String,
29추가: ParamType::Number,
30추가: ParamType::Integer,
31추가: ParamType::Boolean,
32추가: ParamType::StringArray,
33추가: ParamType::NumberArray,
34추가: ParamType::IntegerArray,
35추가: ParamType::BooleanArray,
36추가: ParamType::Raw,
37추가: ];
38추가:
39추가: pub fn label(self) -> &'static str {
40추가: match self {
41추가: ParamType::String => "string",
42추가: ParamType::Number => "number",
43추가: ParamType::Integer => "integer",
44추가: ParamType::Boolean => "boolean",
45추가: ParamType::StringArray => "string[]",
46추가: ParamType::NumberArray => "number[]",
47추가: ParamType::IntegerArray => "integer[]",
48추가: ParamType::BooleanArray => "boolean[]",
49추가: ParamType::Raw => "JSON 직접",
50추가: }
51추가: }
52추가:
53추가: fn scalar(name: &str) -> Option<ParamType> {
54추가: Some(match name {
55추가: "string" => ParamType::String,
56추가: "number" => ParamType::Number,
57추가: "integer" => ParamType::Integer,
58추가: "boolean" => ParamType::Boolean,
59추가: _ => return None,
60추가: })
61추가: }
62추가:
63추가: fn array_of(item: ParamType) -> Option<ParamType> {
64추가: Some(match item {
65추가: ParamType::String => ParamType::StringArray,
66추가: ParamType::Number => ParamType::NumberArray,
67추가: ParamType::Integer => ParamType::IntegerArray,
68추가: ParamType::Boolean => ParamType::BooleanArray,
69추가: _ => return None,
70추가: })
71추가: }
72추가:
73추가: /// (JSON Schema type, 배열이면 items의 type)
74추가: fn schema_types(self) -> Option<(&'static str, Option<&'static str>)> {
75추가: Some(match self {
76추가: ParamType::String => ("string", None),
77추가: ParamType::Number => ("number", None),
78추가: ParamType::Integer => ("integer", None),
79추가: ParamType::Boolean => ("boolean", None),
80추가: ParamType::StringArray => ("array", Some("string")),
81추가: ParamType::NumberArray => ("array", Some("number")),
82추가: ParamType::IntegerArray => ("array", Some("integer")),
83추가: ParamType::BooleanArray => ("array", Some("boolean")),
84추가: ParamType::Raw => return None,
85추가: })
86추가: }
87추가:
88추가: pub fn supports_enum(self) -> bool {
89추가: matches!(self, ParamType::String | ParamType::StringArray)
90추가: }
91추가: }
92추가:
93추가: #[derive(Clone, Debug, PartialEq)]
94추가: pub struct Param {
95추가: pub name: String,
96추가: pub ty: ParamType,
97추가: pub description: String,
98추가: pub required: bool,
99추가: /// string / string[] 전용 허용 값 목록.
100추가: pub enum_values: Vec<String>,
101추가: /// ty == Raw 일 때의 JSON Schema 텍스트.
102추가: pub raw: String,
103추가: }
104추가:
105추가: impl Default for Param {
106추가: fn default() -> Self {
107추가: Param {
108추가: name: String::new(),
109추가: ty: ParamType::String,
110추가: description: String::new(),
111추가: required: true,
112추가: enum_values: Vec::new(),
113추가: raw: String::new(),
114추가: }
115추가: }
116추가: }
117추가:
118추가: fn string_list(v: &Value) -> Option<Vec<String>> {
119추가: v.as_array()?.iter().map(|x| x.as_str().map(str::to_string)).collect()
120추가: }
121추가:
122추가: impl Param {
123추가: pub fn from_schema(name: &str, schema: &Value, required: bool) -> Param {
124추가: let mut p = Param { name: name.to_string(), required, ..Default::default() };
125추가: if let Some(simple) = Self::try_simple(schema) {
126추가: p.ty = simple.0;
127추가: p.description = simple.1;
128추가: p.enum_values = simple.2;
129추가: } else {
130추가: p.ty = ParamType::Raw;
131추가: p.raw = serde_json::to_string_pretty(schema).unwrap_or_default();
132추가: }
133추가: p
134추가: }
135추가:
136추가: /// 폼으로 손실 없이 표현할 수 있는 스키마면 (타입, 설명, enum)을 돌려준다.
137추가: fn try_simple(schema: &Value) -> Option<(ParamType, String, Vec<String>)> {
138추가: let obj = schema.as_object()?;
139추가: let ty_name = obj.get("type")?.as_str()?;
140추가: let description = match obj.get("description") {
141추가: None => String::new(),
142추가: Some(d) => d.as_str()?.to_string(),
143추가: };
144추가: let (ty, enum_src) = if ty_name == "array" {
145추가: let items = obj.get("items")?.as_object()?;
146추가: if items.keys().any(|k| k != "type" && k != "enum") {
147추가: return None;
148추가: }
149추가: let item_ty = ParamType::scalar(items.get("type")?.as_str()?)?;
150추가: if obj.keys().any(|k| !matches!(k.as_str(), "type" | "description" | "items")) {
151추가: return None;
152추가: }
153추가: (ParamType::array_of(item_ty)?, items.get("enum"))
154추가: } else {
155추가: let ty = ParamType::scalar(ty_name)?;
156추가: if obj.keys().any(|k| !matches!(k.as_str(), "type" | "description" | "enum")) {
157추가: return None;
158추가: }
159추가: (ty, obj.get("enum"))
160추가: };
161추가: let enum_values = match enum_src {
162추가: None => Vec::new(),
163추가: Some(e) if ty.supports_enum() => string_list(e)?,
164추가: Some(_) => return None,
165추가: };
166추가: Some((ty, description, enum_values))
167추가: }
168추가:
169추가: pub fn to_schema(&self) -> Value {
170추가: let Some((ty, item)) = self.ty.schema_types() else {
171추가: return serde_json::from_str(&self.raw).unwrap_or_else(|_| Value::Object(Map::new()));
172추가: };
173추가: let enum_value = || Value::Array(self.enum_values.iter().map(|s| Value::String(s.clone())).collect());
174추가: let mut m = Map::new();
175추가: m.insert("type".into(), ty.into());
176추가: if !self.description.is_empty() {
177추가: m.insert("description".into(), self.description.clone().into());
178추가: }
179추가: match item {
180추가: Some(item_ty) => {
181추가: let mut items = Map::new();
182추가: items.insert("type".into(), item_ty.into());
183추가: if !self.enum_values.is_empty() {
184추가: items.insert("enum".into(), enum_value());
185추가: }
186추가: m.insert("items".into(), Value::Object(items));
187추가: }
188추가: None => {
189추가: if !self.enum_values.is_empty() {
190추가: m.insert("enum".into(), enum_value());
191추가: }
192추가: }
193추가: }
194추가: Value::Object(m)
195추가: }
196추가:
197추가: /// 타입을 바꿀 때 내용을 최대한 유지한다.
198추가: pub fn set_type(&mut self, ty: ParamType) {
199추가: if ty == self.ty {
200추가: return;
201추가: }
202추가: if ty == ParamType::Raw {
203추가: self.raw = serde_json::to_string_pretty(&self.to_schema()).unwrap_or_default();
204추가: } else if self.ty == ParamType::Raw {
205추가: if let Ok(v) = serde_json::from_str::<Value>(&self.raw)
206추가: && let Some(d) = v.get("description").and_then(Value::as_str)
207추가: {
208추가: self.description = d.to_string();
209추가: }
210추가: self.enum_values.clear();
211추가: }
212추가: if !ty.supports_enum() {
213추가: self.enum_values.clear();
214추가: }
215추가: self.ty = ty;
216추가: }
217추가:
218추가: /// 인자 뼈대에 넣을 기본값.
219추가: pub fn default_value(&self) -> Value {
220추가: if let Some(first) = self.enum_values.first() {
221추가: return match self.ty {
222추가: ParamType::StringArray => Value::Array(vec![first.clone().into()]),
223추가: _ => first.clone().into(),
224추가: };
225추가: }
226추가: match self.ty {
227추가: ParamType::String => "".into(),
228추가: ParamType::Number | ParamType::Integer => 0.into(),
229추가: ParamType::Boolean => false.into(),
230추가: ParamType::StringArray | ParamType::NumberArray | ParamType::IntegerArray | ParamType::BooleanArray => {
231추가: Value::Array(vec![])
232추가: }
233추가: ParamType::Raw => match serde_json::from_str::<Value>(&self.raw)
234추가: .ok()
235추가: .and_then(|v| v.get("type").and_then(Value::as_str).map(str::to_string))
236추가: .as_deref()
237추가: {
238추가: Some("object") => Value::Object(Map::new()),
239추가: Some("array") => Value::Array(vec![]),
240추가: Some("string") => "".into(),
241추가: Some("number") | Some("integer") => 0.into(),
242추가: Some("boolean") => false.into(),
243추가: _ => Value::Null,
244추가: },
245추가: }
246추가: }
247추가:
248추가: /// 값이 이 파라미터의 타입과 맞는지 (Raw는 type만 대략 확인).
249추가: fn check_value(&self, v: &Value) -> Option<String> {
250추가: let type_ok = |t: &str, v: &Value| match t {
251추가: "string" => v.is_string(),
252추가: "number" => v.is_number(),
253추가: "integer" => v.is_i64() || v.is_u64(),
254추가: "boolean" => v.is_boolean(),
255추가: "array" => v.is_array(),
256추가: "object" => v.is_object(),
257추가: "null" => v.is_null(),
258추가: _ => true,
259추가: };
260추가: let (ty, item) = match self.ty.schema_types() {
261추가: Some(t) => t,
262추가: None => {
263추가: let schema: Value = serde_json::from_str(&self.raw).ok()?;
264추가: let t = schema.get("type")?.as_str()?;
265추가: return (!type_ok(t, v)).then(|| format!("'{}'는 {t} 타입이어야 합니다", self.name));
266추가: }
267추가: };
268추가: if !type_ok(ty, v) {
269추가: return Some(format!("'{}'는 {} 타입이어야 합니다", self.name, self.ty.label()));
270추가: }
271추가: if let (Some(item_ty), Some(arr)) = (item, v.as_array())
272추가: && arr.iter().any(|x| !type_ok(item_ty, x))
273추가: {
274추가: return Some(format!("'{}'의 원소는 {item_ty} 타입이어야 합니다", self.name));
275추가: }
276추가: if !self.enum_values.is_empty() {
277추가: let bad = |x: &Value| x.as_str().is_some_and(|s| !self.enum_values.iter().any(|e| e == s));
278추가: let has_bad = match v {
279추가: Value::Array(arr) => arr.iter().any(bad),
280추가: other => bad(other),
281추가: };
282추가: if has_bad {
283추가: return Some(format!("'{}'의 값은 [{}] 중 하나여야 합니다", self.name, self.enum_values.join(", ")));
284추가: }
285추가: }
286추가: None
287추가: }
288추가: }
289추가:
290추가: #[derive(Clone, Debug, PartialEq, Default)]
291추가: pub struct ToolDef {
292추가: pub name: String,
293추가: pub description: String,
294추가: pub params: Vec<Param>,
295추가: /// parameters 객체의 기타 키 (additionalProperties 등)
296추가: pub params_extra: Map<String, Value>,
297추가: /// function 객체의 기타 키 (strict 등)
298추가: pub func_extra: Map<String, Value>,
299추가: }
300추가:
301추가: impl ToolDef {
302추가: pub fn from_value(v: &Value) -> Result<ToolDef, String> {
303추가: let outer = v.as_object().ok_or("도구 정의가 JSON 객체가 아닙니다")?;
304추가: let func = match outer.get("function").and_then(Value::as_object) {
305추가: Some(f) => f,
306추가: None => outer,
307추가: };
308추가: let name = func.get("name").and_then(Value::as_str).ok_or("도구에 name이 없습니다")?;
309추가: let mut def = ToolDef { name: name.to_string(), ..Default::default() };
310추가: let mut schema = None;
311추가: for (k, val) in func {
312추가: match k.as_str() {
313추가: "name" | "type" => {}
314추가: "description" => def.description = val.as_str().unwrap_or_default().to_string(),
315추가: "parameters" | "input_schema" => schema = Some(val),
316추가: _ => {
317추가: def.func_extra.insert(k.clone(), val.clone());
318추가: }
319추가: }
320추가: }
321추가: if let Some(schema) = schema.and_then(Value::as_object) {
322추가: let required: Vec<String> = schema.get("required").and_then(string_list).unwrap_or_default();
323추가: for (k, val) in schema {
324추가: match k.as_str() {
325추가: "type" if val == "object" => {}
326추가: "required" => {}
327추가: "properties" if val.is_object() => {
328추가: for (pname, pschema) in val.as_object().unwrap() {
329추가: def.params.push(Param::from_schema(pname, pschema, required.contains(pname)));
330추가: }
331추가: }
332추가: _ => {
333추가: def.params_extra.insert(k.clone(), val.clone());
334추가: }
335추가: }
336추가: }
337추가: }
338추가: Ok(def)
339추가: }
340추가:
341추가: pub fn to_value(&self) -> Value {
342추가: let mut props = Map::new();
343추가: for p in &self.params {
344추가: props.insert(p.name.clone(), p.to_schema());
345추가: }
346추가: let mut params = Map::new();
347추가: params.insert("type".into(), "object".into());
348추가: params.insert("properties".into(), Value::Object(props));
349추가: let required: Vec<Value> = self.params.iter().filter(|p| p.required).map(|p| p.name.clone().into()).collect();
350추가: if !required.is_empty() {
351추가: params.insert("required".into(), Value::Array(required));
352추가: }
353추가: for (k, v) in &self.params_extra {
354추가: params.insert(k.clone(), v.clone());
355추가: }
356추가: let mut func = Map::new();
357추가: func.insert("name".into(), self.name.clone().into());
358추가: if !self.description.is_empty() {
359추가: func.insert("description".into(), self.description.clone().into());
360추가: }
361추가: func.insert("parameters".into(), Value::Object(params));
362추가: for (k, v) in &self.func_extra {
363추가: func.insert(k.clone(), v.clone());
364추가: }
365추가: let mut outer = Map::new();
366추가: outer.insert("type".into(), "function".into());
367추가: outer.insert("function".into(), Value::Object(func));
368추가: Value::Object(outer)
369추가: }
370추가:
371추가: pub fn param(&self, name: &str) -> Option<&Param> {
372추가: self.params.iter().find(|p| p.name == name)
373추가: }
374추가:
375추가: /// 필수 파라미터만 기본값으로 채운 인자 객체.
376추가: pub fn skeleton_args(&self) -> String {
377추가: fill_missing_required(self, "{}").unwrap_or_else(|| "{}".into())
378추가: }
379추가:
380추가: /// 도구 호출 인자를 검사해 경고 목록을 돌려준다.
381추가: pub fn validate_args(&self, args: &str) -> Vec<String> {
382추가: let v: Value = match serde_json::from_str(args) {
383추가: Ok(v) => v,
384추가: Err(_) => return vec!["arguments가 올바른 JSON이 아닙니다".into()],
385추가: };
386추가: let Some(obj) = v.as_object() else { return vec!["arguments는 JSON 객체여야 합니다".into()] };
387추가: let mut out = Vec::new();
388추가: for p in self.params.iter().filter(|p| p.required) {
389추가: if !obj.contains_key(&p.name) {
390추가: out.push(format!("필수 인자 '{}'가 없습니다", p.name));
391추가: }
392추가: }
393추가: for (k, val) in obj {
394추가: match self.param(k) {
395추가: None => out.push(format!("'{k}'는 정의되지 않은 인자입니다")),
396추가: Some(p) => out.extend(p.check_value(val)),
397추가: }
398추가: }
399추가: out
400추가: }
401추가:
402추가: /// 정의 자체의 문제 (이름 없음, 파라미터 이름 중복 등).
403추가: pub fn problems(&self) -> Vec<String> {
404추가: let mut out = Vec::new();
405추가: if self.name.trim().is_empty() {
406추가: out.push("도구 이름이 비어 있습니다".into());
407추가: }
408추가: for (i, p) in self.params.iter().enumerate() {
409추가: if p.name.trim().is_empty() {
410추가: out.push(format!("파라미터 #{}의 이름이 비어 있습니다", i + 1));
411추가: } else if self.params[..i].iter().any(|q| q.name == p.name) {
412추가: out.push(format!("파라미터 이름 '{}'가 중복됩니다", p.name));
413추가: }
414추가: if p.ty == ParamType::Raw && serde_json::from_str::<Value>(&p.raw).is_err() {
415추가: out.push(format!("'{}'의 JSON Schema가 올바른 JSON이 아닙니다", p.name));
416추가: }
417추가: }
418추가: out
419추가: }
420추가: }
421추가:
422추가: /// 인자 JSON에 빠진 필수 인자를 기본값으로 채운다. 기존 값은 건드리지 않는다.
423추가: pub fn fill_missing_required(def: &ToolDef, args: &str) -> Option<String> {
424추가: let mut obj = if args.trim().is_empty() {
425추가: Map::new()
426추가: } else {
427추가: serde_json::from_str::<Value>(args).ok()?.as_object()?.clone()
428추가: };
429추가: for p in def.params.iter().filter(|p| p.required) {
430추가: if !obj.contains_key(&p.name) {
431추가: obj.insert(p.name.clone(), p.default_value());
432추가: }
433추가: }
434추가: serde_json::to_string_pretty(&Value::Object(obj)).ok()
435추가: }
436추가:
437추가: /// tools 메시지 content(JSON 배열 또는 그 문자열)를 도구 목록으로.
438추가: pub fn parse_tool_list(content: &str) -> Result<Vec<ToolDef>, String> {
439추가: let v: Value = serde_json::from_str(content).map_err(|e| format!("JSON 오류: {e}"))?;
440추가: tools_from_value(&v)
441추가: }
442추가:
443추가: fn tools_from_value(v: &Value) -> Result<Vec<ToolDef>, String> {
444추가: match v {
445추가: Value::Array(arr) => arr
446추가: .iter()
447추가: .enumerate()
448추가: .map(|(i, t)| ToolDef::from_value(t).map_err(|e| format!("도구 #{}: {e}", i + 1)))
449추가: .collect(),
450추가: Value::String(s) => parse_tool_list(s),
451추가: _ => Err("도구 목록은 JSON 배열이어야 합니다".into()),
452추가: }
453추가: }
454추가:
455추가: pub fn tool_list_to_json(tools: &[ToolDef]) -> String {
456추가: serde_json::to_string_pretty(&Value::Array(tools.iter().map(ToolDef::to_value).collect())).unwrap_or_default()
457추가: }
458추가:
459추가: // ---------------------------------------------------------------------------
460추가: // 라이브러리
461추가: // ---------------------------------------------------------------------------
462추가:
463추가: /// 데이터셋과 함께 저장되는 도구 정의 모음. `dataset.jsonl` → `dataset.tools.json`
464추가: #[derive(Clone, Debug, Default)]
465추가: pub struct ToolLibrary {
466추가: pub tools: Vec<ToolDef>,
467추가: pub dirty: bool,
468추가: }
469추가:
470추가: impl ToolLibrary {
471추가: pub fn path_for(dataset: &Path) -> PathBuf {
472추가: let stem = dataset.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
473추가: dataset.with_file_name(format!("{stem}.tools.json"))
474추가: }
475추가:
476추가: pub fn load(path: &Path) -> Result<ToolLibrary, String> {
477추가: let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
478추가: Ok(ToolLibrary { tools: parse_tool_list(&text)?, dirty: false })
479추가: }
480추가:
481추가: pub fn save(&mut self, path: &Path) -> std::io::Result<()> {
482추가: let tmp = path.with_extension("json.tmp");
483추가: std::fs::write(&tmp, tool_list_to_json(&self.tools) + "\n")?;
484추가: std::fs::rename(&tmp, path)?;
485추가: self.dirty = false;
486추가: Ok(())
487추가: }
488추가:
489추가: pub fn get(&self, name: &str) -> Option<&ToolDef> {
490추가: self.tools.iter().find(|t| t.name == name)
491추가: }
492추가:
493추가: /// 없던 정의만 추가한다. 이름이 같아도 정의가 다르면 변형으로 추가된다. 추가된 개수를 돌려준다.
494추가: pub fn merge(&mut self, tools: impl IntoIterator<Item = ToolDef>) -> usize {
495추가: let mut added = 0;
496추가: for t in tools {
497추가: if !self.tools.contains(&t) {
498추가: self.tools.push(t);
499추가: added += 1;
500추가: }
501추가: }
502추가: if added > 0 {
503추가: self.dirty = true;
504추가: }
505추가: added
506추가: }
507추가: }
508추가:
509추가: /// 데이터셋의 모든 tools 메시지(와 줄 최상위 "tools" 키)에서 도구 정의를 모은다. 중복은 제거.
510추가: pub fn collect_tools(entries: &[Entry]) -> Vec<ToolDef> {
511추가: let mut out: Vec<ToolDef> = Vec::new();
512추가: let mut push = |t: ToolDef| {
513추가: if !out.contains(&t) {
514추가: out.push(t);
515추가: }
516추가: };
517추가: for e in entries {
518추가: match e.raw() {
519추가: Some(raw) => {
520추가: // 빠른 사전 필터: "tools"라는 글자가 없는 줄은 파싱하지 않는다.
521추가: if !raw.contains("\"tools\"") {
522추가: continue;
523추가: }
524추가: let Ok(v) = serde_json::from_str::<Value>(raw) else { continue };
525추가: if let Some(top) = v.get("tools")
526추가: && let Ok(list) = tools_from_value(top)
527추가: {
528추가: list.into_iter().for_each(&mut push);
529추가: }
530추가: for m in v.get("messages").and_then(Value::as_array).into_iter().flatten() {
531추가: if m.get("role").and_then(Value::as_str) == Some("tools")
532추가: && let Some(c) = m.get("content")
533추가: && let Ok(list) = tools_from_value(c)
534추가: {
535추가: list.into_iter().for_each(&mut push);
536추가: }
537추가: }
538추가: }
539추가: None => {
540추가: for m in e.parsed().map(|c| c.messages.as_slice()).unwrap_or_default() {
541추가: if m.role == Role::Tools
542추가: && let Ok(list) = parse_tool_list(&m.content)
543추가: {
544추가: list.into_iter().for_each(&mut push);
545추가: }
546추가: }
547추가: }
548추가: }
549추가: }
550추가: out
551추가: }
552추가:
553추가: // ---------------------------------------------------------------------------
554추가: // 도구 호출 인자 (폼 입력용)
555추가: // ---------------------------------------------------------------------------
556추가:
557추가: /// arguments 텍스트를 객체로. 빈 문자열은 빈 객체로 본다.
558추가: pub fn args_object(args: &str) -> Result<Map<String, Value>, String> {
559추가: if args.trim().is_empty() {
560추가: return Ok(Map::new());
561추가: }
562추가: match serde_json::from_str::<Value>(args) {
563추가: Ok(Value::Object(m)) => Ok(m),
564추가: Ok(_) => Err("arguments가 JSON 객체가 아닙니다".into()),
565추가: Err(e) => Err(format!("JSON 오류: {e}")),
566추가: }
567추가: }
568추가:
569추가: /// 인자 객체를 정의의 파라미터 순서대로 정렬해 보기 좋은 JSON 텍스트로.
570추가: /// 정의에 없는 키는 뒤에 원래 순서대로 붙는다. 문자열 안의 `"`, 줄바꿈 등은 자동으로 이스케이프된다.
571추가: pub fn args_to_text(def: &ToolDef, obj: &Map<String, Value>) -> String {
572추가: let mut out = Map::new();
573추가: for p in &def.params {
574추가: if let Some(v) = obj.get(&p.name) {
575추가: out.insert(p.name.clone(), v.clone());
576추가: }
577추가: }
578추가: for (k, v) in obj {
579추가: if !out.contains_key(k) {
580추가: out.insert(k.clone(), v.clone());
581추가: }
582추가: }
583추가: serde_json::to_string_pretty(&Value::Object(out)).unwrap_or_else(|_| "{}".into())
584추가: }
585추가:
586추가: /// 배열 파라미터를 "한 줄에 한 항목" 텍스트로 편집할 때의 변환.
587추가: pub fn array_to_lines(v: Option<&Value>) -> String {
588추가: match v.and_then(Value::as_array) {
589추가: Some(arr) => arr
590추가: .iter()
591추가: .map(|x| match x {
592추가: Value::String(s) => s.clone(),
593추가: other => other.to_string(),
594추가: })
595추가: .collect::<Vec<_>>()
596추가: .join("\n"),
597추가: None => String::new(),
598추가: }
599추가: }
600추가:
601추가: /// "한 줄에 한 항목" 텍스트를 배열로. 빈 줄은 무시. 원소 타입에 맞지 않으면 Err.
602추가: pub fn lines_to_array(ty: ParamType, text: &str) -> Result<Value, String> {
603추가: let mut out = Vec::new();
604추가: for (i, line) in text.lines().enumerate() {
605추가: let t = line.trim();
606추가: if t.is_empty() {
607추가: continue;
608추가: }
609추가: let v = match ty {
610추가: ParamType::StringArray => Value::String(line.to_string()),
611추가: ParamType::IntegerArray => t
612추가: .parse::<i64>()
613추가: .map(Value::from)
614추가: .map_err(|_| format!("{}번째 줄 '{t}'은(는) 정수가 아닙니다", i + 1))?,
615추가: ParamType::NumberArray => serde_json::from_str::<Value>(t)
616추가: .ok()
617추가: .filter(Value::is_number)
618추가: .ok_or_else(|| format!("{}번째 줄 '{t}'은(는) 숫자가 아닙니다", i + 1))?,
619추가: ParamType::BooleanArray => match t {
620추가: "true" => Value::Bool(true),
621추가: "false" => Value::Bool(false),
622추가: _ => return Err(format!("{}번째 줄 '{t}'은(는) true/false가 아닙니다", i + 1)),
623추가: },
624추가: _ => return Err("배열 타입이 아닙니다".into()),
625추가: };
626추가: out.push(v);
627추가: }
628추가: Ok(Value::Array(out))
629추가: }
추가src/tools_ui.rs+893-0
@@ -0,0 +1,893 @@
1추가: //! 도구 관련 화면: 도구 라이브러리 편집기(폼), tools 메시지 선택 UI, 도구 호출 자동완성.
2추가:
3추가: use eframe::egui::{self, Color32, ComboBox, Frame, Id, Key, Modal, Modifiers, RichText, ScrollArea, TextEdit};
4추가: use handmade_dataset_creator::model::{Message, ToolCall, one_line};
5추가: use handmade_dataset_creator::tools::{
6추가: self, Param, ParamType, ToolDef, ToolLibrary, fill_missing_required, parse_tool_list, tool_list_to_json,
7추가: };
8추가:
9추가: fn 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)` 형태의 요약. *는 필수.
14추가: pub 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추가:
24추가: pub enum LibraryOutcome {
25추가: Apply,
26추가: Cancel,
27추가: }
28추가:
29추가: pub 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추가:
41추가: impl 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추가: /// 쉼표로 구분한 허용 값 입력란. 입력 중인 텍스트(빈 항목, 끝 쉼표)를 유지하기 위해 별도 버퍼를 쓴다.
375추가: fn 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`에 선택할 도구 이름을 넣는다.
389추가: pub 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`은 자동완성/검증에 쓰는 도구 정의.
524추가: pub 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추가: /// 확정되면 그 도구 정의를 돌려준다(인자 뼈대 채우기용).
625추가: fn 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추가:
678추가: fn 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추가: /// 현재 버퍼 텍스트와 변경 여부를 돌려준다.
690추가: fn 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 이스케이프는 자동.
707추가: fn 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의 도구 호출 목록에서 고르기.
874추가: pub 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추가: }
추가tests/markup.rs+40-0
@@ -0,0 +1,40 @@
1추가: use handmade_dataset_creator::markup::{Fmt, Style, parse, toggle};
2추가:
3추가: #[test]
4추가: fn toggle_wraps_and_unwraps() {
5추가: let t = "가나다라마";
6추가: // "나다" 선택 → <u>나다</u>, 선택은 안쪽 텍스트 그대로
7추가: let (s, sel) = toggle(t, 1..3, Fmt::Underline);
8추가: assert_eq!(s, "가<u>나다</u>라마");
9추가: assert_eq!(sel, 4..6);
10추가: // 같은 선택으로 다시 → 벗기기 (바깥 표기)
11추가: let (s2, sel2) = toggle(&s, sel, Fmt::Underline);
12추가: assert_eq!(s2, t);
13추가: assert_eq!(sel2, 1..3);
14추가: // 표기까지 포함해 선택한 경우에도 벗기기
15추가: let (s3, sel3) = toggle("가<mark>나</mark>다", 1..15, Fmt::Mark);
16추가: assert_eq!(s3, "가나다");
17추가: assert_eq!(sel3, 1..2);
18추가: // 선택 없음 → 빈 표기, 커서는 사이
19추가: let (s4, sel4) = toggle("ab", 1..1, Fmt::Bold);
20추가: assert_eq!(s4, "a****b");
21추가: assert_eq!(sel4, 3..3);
22추가: // 역방향 선택도 처리
23추가: assert_eq!(toggle("abc", std::ops::Range { start: 2, end: 1 }, Fmt::Strike).0, "a~~b~~c");
24추가: }
25추가:
26추가: #[test]
27추가: fn parse_styles_and_preserves_text() {
28추가: let t = r#"㉠<u>밑줄</u> **굵게** ~~취소~~ <mark type="box">박스</mark> 끝"#;
29추가: let spans = parse(t);
30추가: let joined: String = spans.iter().map(|s| s.text.as_str()).collect();
31추가: assert_eq!(joined, t, "조각을 이어 붙이면 원문");
32추가: let style_of = |w: &str| spans.iter().find(|s| s.text == w && !s.marker).unwrap().style;
33추가: assert_eq!(style_of("밑줄"), Style { underline: true, ..Default::default() });
34추가: assert_eq!(style_of("굵게"), Style { bold: true, ..Default::default() });
35추가: assert_eq!(style_of("취소"), Style { strike: true, ..Default::default() });
36추가: assert_eq!(style_of("박스"), Style { mark: true, ..Default::default() });
37추가: assert_eq!(style_of(" 끝"), Style::default());
38추가: // <mark 로 시작하지만 태그가 아닌 것은 일반 텍스트
39추가: assert!(parse("<marker>").iter().all(|s| !s.marker));
40추가: }
추가tests/model_and_history.rs+136-0
@@ -0,0 +1,136 @@
1추가: use handmade_dataset_creator::document::Document;
2추가: use handmade_dataset_creator::model::{Conversation, Entry, Message, Role, ToolCall};
3추가:
4추가: const LINE: &str = r#"{"messages":[{"role":"system","content":"sys"},{"role":"tools","content":[{"type":"function","function":{"name":"get_weather"}}]},{"role":"user","content":"서울 날씨?"},{"role":"assistant","reasoning_content":"도구를 쓰자","content":"","tool_calls":[{"id":"call_1","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Seoul\"}"}}]},{"role":"tool","tool_call_id":"call_1","content":"맑음"},{"role":"assistant","content":"맑아요.","weight":1}],"id":"abc"}"#;
5추가:
6추가: #[test]
7추가: fn parse_and_roundtrip() {
8추가: let conv = Conversation::parse_line(LINE).unwrap();
9추가: assert_eq!(conv.messages.len(), 6);
10추가: assert_eq!(conv.messages[1].role, Role::Tools);
11추가: assert!(conv.messages[1].content_is_json);
12추가: let a = &conv.messages[3];
13추가: assert_eq!(a.thinking, "도구를 쓰자");
14추가: assert_eq!(a.tool_calls[0].name, "get_weather");
15추가: assert!(a.tool_calls[0].args_as_string);
16추가: assert_eq!(conv.messages[4].tool_call_id, "call_1");
17추가:
18추가: // 재직렬화 → 재파싱 결과가 같아야 하고, 알 수 없는 필드도 보존되어야 한다.
19추가: let line = conv.to_line();
20추가: let again = Conversation::parse_line(&line).unwrap();
21추가: assert_eq!(conv, again);
22추가: let v: serde_json::Value = serde_json::from_str(&line).unwrap();
23추가: assert_eq!(v["id"], "abc");
24추가: assert_eq!(v["messages"][5]["weight"], 1);
25추가: assert_eq!(v["messages"][3]["tool_calls"][0]["function"]["arguments"], r#"{"city":"Seoul"}"#);
26추가: assert!(v["messages"][1]["content"].is_array());
27추가: }
28추가:
29추가: #[test]
30추가: fn unmodified_lines_are_written_verbatim() {
31추가: let e = Entry::from_raw(LINE.to_string());
32추가: assert_eq!(e.to_line(), LINE);
33추가: let bad = Entry::from_raw("{not json".to_string());
34추가: assert!(bad.preview().starts_with('⚠'));
35추가: assert_eq!(bad.to_line(), "{not json");
36추가: }
37추가:
38추가: #[test]
39추가: fn new_tool_call_args_written_as_object() {
40추가: let mut m = Message::new(Role::Assistant);
41추가: m.tool_calls.push(ToolCall { name: "f".into(), arguments: r#"{"x": 1}"#.into(), ..Default::default() });
42추가: let v = m.to_value();
43추가: assert_eq!(v["tool_calls"][0]["function"]["arguments"]["x"], 1);
44추가: }
45추가:
46추가: #[test]
47추가: fn default_role_after_assistant_is_user() {
48추가: assert_eq!(Role::default_after(Some(Role::Assistant)), Role::User);
49추가: assert_eq!(Role::default_after(Some(Role::System)), Role::Tools);
50추가: assert_eq!(Role::default_after(None), Role::System);
51추가: }
52추가:
53추가: #[test]
54추가: fn default_role_follows_tool_calls() {
55추가: let mut call = Message::new(Role::Assistant);
56추가: for id in ["c1", "c2"] {
57추가: call.tool_calls.push(ToolCall { id: id.into(), name: "f".into(), ..Default::default() });
58추가: }
59추가: let conv = Conversation {
60추가: messages: vec![
61추가: Message::new(Role::System),
62추가: Message::new(Role::Tools),
63추가: Message::new(Role::User),
64추가: call,
65추가: Message::new(Role::Tool),
66추가: Message::new(Role::Tool),
67추가: ],
68추가: ..Default::default()
69추가: };
70추가: let roles: Vec<Role> = (0..=6).map(|p| conv.default_role_at(p)).collect();
71추가: assert_eq!(
72추가: roles,
73추가: [Role::System, Role::Tools, Role::User, Role::Assistant, Role::Tool, Role::Tool, Role::Assistant]
74추가: );
75추가: }
76추가:
77추가: fn conv_of(n: usize) -> Conversation {
78추가: Conversation {
79추가: messages: (0..n).map(|i| Message::with_content(Role::User, i.to_string())).collect(),
80추가: ..Default::default()
81추가: }
82추가: }
83추가:
84추가: fn contents(c: &Conversation) -> Vec<String> {
85추가: c.messages.iter().map(|m| m.content.clone()).collect()
86추가: }
87추가:
88추가: #[test]
89추가: fn move_duplicate_delete() {
90추가: let mut c = conv_of(5);
91추가: assert_eq!(c.move_up(&[0, 2]), vec![0, 1]);
92추가: assert_eq!(contents(&c), ["0", "2", "1", "3", "4"]);
93추가: assert_eq!(c.move_down(&[3, 4]), vec![3, 4]); // 이미 맨 아래
94추가: assert_eq!(c.move_down(&[1]), vec![2]);
95추가: assert_eq!(contents(&c), ["0", "1", "2", "3", "4"]);
96추가: assert_eq!(c.duplicate(&[1, 3]), vec![4, 5]);
97추가: assert_eq!(contents(&c), ["0", "1", "2", "3", "1", "3", "4"]);
98추가: c.delete(&[4, 5]);
99추가: assert_eq!(contents(&c), ["0", "1", "2", "3", "4"]);
100추가: }
101추가:
102추가: #[test]
103추가: fn undo_redo_and_dirty() {
104추가: let dir = std::env::temp_dir().join(format!("hdc-test-{}", std::process::id()));
105추가: std::fs::create_dir_all(&dir).unwrap();
106추가: let path = dir.join("a.jsonl");
107추가:
108추가: let mut doc = Document::new();
109추가: assert!(!doc.is_dirty());
110추가: doc.insert_conversation(0, conv_of(1));
111추가: doc.insert_conversation(1, conv_of(2));
112추가: assert!(doc.is_dirty());
113추가: doc.save_to(&path).unwrap();
114추가: assert!(!doc.is_dirty());
115추가:
116추가: doc.modify(0, |c| {
117추가: c.messages.push(Message::with_content(Role::Assistant, "hi"));
118추가: Some(())
119추가: })
120추가: .unwrap();
121추가: assert!(doc.is_dirty());
122추가: doc.remove_conversations(&[1]);
123추가: assert_eq!(doc.len(), 1);
124추가:
125추가: doc.undo();
126추가: assert_eq!(doc.len(), 2);
127추가: doc.undo();
128추가: assert!(!doc.is_dirty(), "저장 시점으로 되돌리면 깨끗한 상태");
129추가: assert_eq!(doc.entries[0].conversation().unwrap().messages.len(), 1);
130추가: doc.redo();
131추가: assert_eq!(doc.entries[0].conversation().unwrap().messages.len(), 2);
132추가:
133추가: let reopened = Document::open(&path).unwrap();
134추가: assert_eq!(reopened.len(), 2);
135추가: std::fs::remove_dir_all(&dir).ok();
136추가: }
추가tests/recent.rs+23-0
@@ -0,0 +1,23 @@
1추가: use handmade_dataset_creator::recent::{MAX_RECENT, RecentFiles};
2추가:
3추가: #[test]
4추가: fn recent_files_order_limit_and_persist() {
5추가: let dir = std::env::temp_dir().join(format!("hdc-recent-{}", std::process::id()));
6추가: let store = dir.join("cfg").join("recent.json");
7추가: let mut r = RecentFiles::load(Some(store.clone()));
8추가: assert!(r.paths.is_empty());
9추가: for i in 0..12 {
10추가: r.add(&dir.join(format!("{i}.jsonl")));
11추가: }
12추가: assert_eq!(r.paths.len(), MAX_RECENT);
13추가: assert!(r.paths[0].ends_with("11.jsonl"));
14추가: r.add(&dir.join("5.jsonl")); // 다시 열면 맨 앞으로
15추가: assert!(r.paths[0].ends_with("5.jsonl"));
16추가: assert_eq!(r.paths.iter().filter(|p| p.ends_with("5.jsonl")).count(), 1);
17추가:
18추가: let reloaded = RecentFiles::load(Some(store.clone()));
19추가: assert_eq!(reloaded.paths, r.paths);
20추가: r.clear();
21추가: assert!(RecentFiles::load(Some(store)).paths.is_empty());
22추가: std::fs::remove_dir_all(&dir).ok();
23추가: }
추가tests/tools.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기