leejunyoung5819handmade-dataset-creator

공개

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

629줄23 KB
1//! 도구(함수) 정의: 폼으로 편집할 수 있는 구조와 JSON 변환, 도구 라이브러리.
2//!
3//! 저장 형식은 OpenAI 형식이다:
4//! `{"type":"function","function":{"name":...,"description":...,"parameters":{JSON Schema}}}`
5//! 읽을 때는 Anthropic 형식(`input_schema`)과 평평한 형식(`{"name","parameters"}`)도 받아들인다.
6
7use crate::model::{Entry, Role};
8use serde_json::{Map, Value};
9use std::path::{Path, PathBuf};
10
11/// 폼에서 고를 수 있는 파라미터 타입.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub 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
26impl 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)]
94pub 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
105impl 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
118fn string_list(v: &Value) -> Option<Vec<String>> {
119 v.as_array()?.iter().map(|x| x.as_str().map(str::to_string)).collect()
120}
121
122impl 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)]
291pub 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
301impl 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에 빠진 필수 인자를 기본값으로 채운다. 기존 값은 건드리지 않는다.
423pub 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 배열 또는 그 문자열)를 도구 목록으로.
438pub 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
443fn 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
455pub 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)]
465pub struct ToolLibrary {
466 pub tools: Vec<ToolDef>,
467 pub dirty: bool,
468}
469
470impl 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" 키)에서 도구 정의를 모은다. 중복은 제거.
510pub 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 텍스트를 객체로. 빈 문자열은 빈 객체로 본다.
558pub 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/// 정의에 없는 키는 뒤에 원래 순서대로 붙는다. 문자열 안의 `"`, 줄바꿈 등은 자동으로 이스케이프된다.
571pub 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/// 배열 파라미터를 "한 줄에 한 항목" 텍스트로 편집할 때의 변환.
587pub 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.
602pub 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}