call_agent/chat/function.rs
1use std::fmt;
2
3use serde::{de::{self, Visitor}, Deserialize, Deserializer, Serialize, Serializer};
4use serde_json::Value;
5
6/// function call の定義
7#[derive(Debug, Serialize, Deserialize, Clone)]
8pub struct ToolDef {
9 /// ツールの種類:
10 /// 現在 "function" のみサポートされています
11 /// 固定値: "function"
12 #[serde(rename = "type")]
13 pub tool_type: String,
14 /// ツールの定義
15 /// ツールの関数名、説明、パラメータの定義を含みます
16 pub function: FunctionDef,
17}
18
19#[derive(Debug, Serialize, Deserialize, Clone)]
20pub struct FunctionDef {
21 /// 関数名
22 pub name: String,
23 /// 関数の説明
24 pub description: String,
25 /// 関数のパラメータの定義(json schema)
26 /// enumなどの制約を指定することが推奨されます
27 /// 機能は明確で直感的であるべきです
28 pub parameters: serde_json::Value,
29 /// 厳密に構造化します
30 /// default: false
31 /// 並列ToolCallsでは強制無効化されます
32 pub strict: bool,
33}
34
35#[derive(Debug, Deserialize, Clone, Serialize)]
36pub struct FunctionCall {
37 /// ツールの呼び出しID
38 /// ツールの呼び出しを一意に識別するためのID
39 /// 返却時にこのIDを指定する必要があります
40 pub id: String,
41 /// ツールの種類:
42 /// 現在 "function" のみサポートされています
43 /// 固定値: "function"
44 #[serde(rename = "type", alias = "type")]
45 pub tool_type: String,
46 /// 関数の呼び出し内容
47 pub function: FunctionCallInner,
48}
49
50#[derive(Debug, Deserialize, Clone, Serialize)]
51pub struct FunctionCallInner {
52 /// 関数名
53 /// 呼び出された関数の名前
54 pub name: String,
55 /// 関数の引数
56 /// JSONとして提供されます
57 /// 例: {"input": "Hello, world!"}
58 #[serde(deserialize_with = "deserialize_arguments",serialize_with = "serialize_arguments")]
59 pub arguments: Value,
60}
61
62fn deserialize_arguments<'de, D>(deserializer: D) -> Result<Value, D::Error>
63where
64 D: Deserializer<'de>,
65{
66 struct ArgumentsVisitor;
67
68 impl<'de> Visitor<'de> for ArgumentsVisitor {
69 type Value = Value;
70
71 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
72 formatter.write_str("a JSON string or object representing the function arguments")
73 }
74
75 // 文字列として渡された場合
76 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
77 where
78 E: de::Error,
79 {
80 // まず、文字列をJSONとしてパースを試みる
81 serde_json::from_str(value)
82 .or_else(|_| Ok(Value::String(value.to_owned())))
83 .map_err(|e| de::Error::custom::<String>(e))
84 }
85
86 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
87 where
88 E: de::Error,
89 {
90 serde_json::from_str(&value)
91 .or_else(|_| Ok(Value::String(value)))
92 .map_err(|e| de::Error::custom::<String>(e))
93 }
94
95 // 既にオブジェクト(マップ)として渡された場合
96 fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
97 where
98 M: de::MapAccess<'de>,
99 {
100 Value::deserialize(de::value::MapAccessDeserializer::new(map))
101 }
102 }
103
104 deserializer.deserialize_any(ArgumentsVisitor)
105}
106
107fn serialize_arguments<S>(value: &Value, serializer: S) -> Result<S::Ok, S::Error>
108where
109 S: Serializer,
110{
111 // Value を JSON 文字列に変換する
112 let s = value.to_string();
113 serializer.serialize_str(&s)
114}
115
116
117/// toolの定義
118/// The Tool trait defines the interface for executable tools within the crate.
119/// Implementers of this trait must provide concrete definitions for:
120///
121/// - Identifying the tool via a unique name (used as the function or tool identifier).
122/// - Describing the tool's functionality in plain text.
123/// - Defining the expected input parameters in the form of a JSON schema.
124/// - Executing the tool's operation with the provided JSON parameters, returning either a result string on success or an error string on failure.
125///
126/// # Methods
127///
128/// - def_name()
129/// - Returns the unique name of the tool as a string slice.
130/// - This name acts as the primary identifier when selecting or referencing the tool.
131///
132/// - def_description()
133/// - Provides a concise description of what the tool does.
134/// - Intended to offer an overview of the tool's purpose and behavior.
135///
136/// - def_parameters()
137/// - Returns a JSON value representing the input parameters' schema.
138/// - The schema should detail the expected keys and value types, ensuring consumers provide input adhering to the specification.
139///
140/// - run(args: serde_json::Value)
141/// - Executes the tool's functionality using the provided JSON arguments.
142/// - Returns a Result containing a string on success or an error description string on failure.
143///
144/// # Example
145///
146/// ```rust
147/// // Assuming MyTool implements the Tool trait:
148/// struct MyTool;
149///
150/// impl Tool for MyTool {
151/// fn def_name(&self) -> &str {
152/// "my_tool"
153/// }
154///
155/// fn def_description(&self) -> &str {
156/// "Performs a specific operation on the provided data."
157/// }
158///
159/// fn def_parameters(&self) -> serde_json::Value {
160/// serde_json::json!({
161/// "type": "object",
162/// "properties": {
163/// "input": { "type": "string", "description": "Input data for the tool" }
164/// },
165/// "required": ["input"]
166/// })
167/// }
168///
169/// fn run(&self, args: serde_json::Value) -> Result<String, String> {
170/// // Execute the tool's operation based on the provided arguments.
171/// Ok("Operation completed successfully".to_string())
172/// }
173/// }
174/// ```
175///
176/// # Error Handling
177///
178/// - The run() method returns an Err variant with a descriptive error message if the execution fails.
179pub trait Tool {
180 /// 関数名
181 /// ツール名として使用される
182 fn def_name(&self) -> &str;
183 /// 関数の説明
184 fn def_description(&self) -> &str;
185 /// 関数のパラメータの定義(json schema)
186 fn def_parameters(&self) -> serde_json::Value;
187 /// 関数の実行
188 fn run(&self, args: serde_json::Value) -> Result<String, String>;
189}