1use std::fmt;
4use std::future::Future;
5use std::sync::Arc;
6
7use futures::future::BoxFuture;
8use futures::{Stream, StreamExt};
9use schemars::JsonSchema as SchemarsJsonSchema;
10use serde_json::json;
11
12use super::error::ToolError;
13use super::schema::{SchemaValidator, schema_for};
14use super::tool::{Tool, ToolContext, ToolOutcome, ToolStream, ToolStreamEvent, ToolStreamItem};
15use crate::models::BoxStream;
16use crate::types::{JsonSchema, JsonValue, ToolResultBlock, ToolResultContent, ToolSpec};
17
18#[derive(Debug, Clone, PartialEq)]
20#[non_exhaustive]
21pub enum FunctionToolItem {
22 Update(JsonValue),
24 Return(JsonValue),
26}
27
28type Callback = Arc<dyn Fn(JsonValue, ToolContext) -> BoxFuture<'static, Result<JsonValue, ToolError>> + Send + Sync>;
29type StreamCallback =
30 Arc<dyn Fn(JsonValue, ToolContext) -> BoxStream<'static, Result<FunctionToolItem, ToolError>> + Send + Sync>;
31
32#[derive(Clone)]
33enum Body {
34 Future(Callback),
35 Stream(StreamCallback),
36}
37
38#[derive(Clone)]
67pub struct FunctionTool {
68 spec: ToolSpec,
69 validator: Option<Arc<SchemaValidator>>,
70 body: Body,
71}
72
73#[derive(Debug)]
76pub struct FunctionToolBuilder {
77 name: String,
78 description: String,
79 input_schema: Option<JsonSchema>,
80 validator: Option<Arc<SchemaValidator>>,
81}
82
83impl FunctionTool {
84 pub fn builder(name: impl Into<String>, description: impl Into<String>) -> FunctionToolBuilder {
86 FunctionToolBuilder {
87 name: name.into(),
88 description: description.into(),
89 input_schema: None,
90 validator: None,
91 }
92 }
93
94 async fn run_future(
95 callback: Callback,
96 validator: Option<Arc<SchemaValidator>>,
97 context: ToolContext,
98 ) -> ToolOutcome {
99 let tool_use_id = context.tool_use().tool_use_id.clone();
100 let input = context.tool_use().input.clone();
101 if let Some(error) = validator.and_then(|validator| validator.validate(&input).err()) {
102 return ToolError::new(error).into_outcome(tool_use_id);
103 }
104 match callback(input, context).await {
105 Ok(value) => wrap_in_tool_result(value, tool_use_id).into(),
106 Err(error) => error.into_outcome(tool_use_id),
107 }
108 }
109
110 fn run_stream(callback: &StreamCallback, validator: Option<&SchemaValidator>, context: ToolContext) -> ToolStream {
111 let tool_use_id = context.tool_use().tool_use_id.clone();
112 let input = context.tool_use().input.clone();
113 if let Some(error) = validator.and_then(|validator| validator.validate(&input).err()) {
114 return ToolStream::ready(ToolError::new(error).into_outcome(tool_use_id));
115 }
116 let items = callback(input, context);
117 ToolStream::new(async_stream::stream! {
118 futures::pin_mut!(items);
119 while let Some(item) = items.next().await {
120 match item {
121 Ok(FunctionToolItem::Update(data)) => yield ToolStreamItem::Event(ToolStreamEvent::new(data)),
122 Ok(FunctionToolItem::Return(value)) => {
123 yield ToolStreamItem::Outcome(wrap_in_tool_result(value, tool_use_id.clone()).into());
124 return;
125 }
126 Err(error) => {
127 yield ToolStreamItem::Outcome(error.into_outcome(tool_use_id.clone()));
128 return;
129 }
130 }
131 }
132 yield ToolStreamItem::Outcome(wrap_in_tool_result(JsonValue::Null, tool_use_id).into());
133 })
134 }
135}
136
137impl FunctionToolBuilder {
138 #[must_use]
142 pub fn input_schema(mut self, schema: JsonSchema) -> Self {
143 self.input_schema = Some(schema);
144 self.validator = None;
145 self
146 }
147
148 #[must_use]
151 pub fn input_schema_for<T: SchemarsJsonSchema>(mut self) -> Self {
152 let schema = schema_for::<T>();
153 self.validator = SchemaValidator::new(&schema).ok().map(Arc::new);
154 self.input_schema = Some(schema);
155 self
156 }
157
158 fn spec(&self) -> ToolSpec {
159 let schema = self
160 .input_schema
161 .clone()
162 .unwrap_or_else(|| json!({"type": "object", "properties": {}, "additionalProperties": false}));
163 ToolSpec::new(&self.name, &self.description).with_input_schema(schema)
164 }
165
166 pub fn callback<F, Fut>(self, callback: F) -> FunctionTool
168 where
169 F: Fn(JsonValue, ToolContext) -> Fut + Send + Sync + 'static,
170 Fut: Future<Output = Result<JsonValue, ToolError>> + Send + 'static,
171 {
172 let callback: Callback = Arc::new(move |input, context| Box::pin(callback(input, context)));
173 FunctionTool {
174 spec: self.spec(),
175 validator: self.validator,
176 body: Body::Future(callback),
177 }
178 }
179
180 pub fn stream_callback<F, S>(self, callback: F) -> FunctionTool
184 where
185 F: Fn(JsonValue, ToolContext) -> S + Send + Sync + 'static,
186 S: Stream<Item = Result<FunctionToolItem, ToolError>> + Send + 'static,
187 {
188 let callback: StreamCallback = Arc::new(move |input, context| Box::pin(callback(input, context)));
189 FunctionTool {
190 spec: self.spec(),
191 validator: self.validator,
192 body: Body::Stream(callback),
193 }
194 }
195}
196
197impl Tool for FunctionTool {
198 fn name(&self) -> &str {
199 &self.spec.name
200 }
201
202 fn description(&self) -> &str {
203 &self.spec.description
204 }
205
206 fn tool_spec(&self) -> ToolSpec {
207 self.spec.clone()
208 }
209
210 fn stream(&self, context: ToolContext) -> ToolStream {
211 match &self.body {
212 Body::Future(callback) => {
213 ToolStream::from_future(Self::run_future(callback.clone(), self.validator.clone(), context))
214 }
215 Body::Stream(callback) => Self::run_stream(callback, self.validator.as_deref(), context),
216 }
217 }
218}
219
220impl fmt::Debug for FunctionTool {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 f.debug_struct("FunctionTool")
223 .field("spec", &self.spec)
224 .finish_non_exhaustive()
225 }
226}
227
228#[must_use]
231pub(crate) fn wrap_in_tool_result(value: JsonValue, tool_use_id: impl Into<String>) -> ToolResultBlock {
232 ToolResultBlock::success(tool_use_id, result_content(value))
233}
234
235fn result_content(value: JsonValue) -> Vec<ToolResultContent> {
236 if let Some(content) = as_tool_result_content(&value) {
237 return vec![content];
238 }
239 match value {
240 JsonValue::Null => vec![ToolResultContent::text("null")],
241 JsonValue::String(text) => vec![ToolResultContent::text(text)],
242 JsonValue::Bool(flag) => vec![ToolResultContent::text(flag.to_string())],
243 JsonValue::Number(number) => vec![ToolResultContent::text(js_number_string(&number))],
244 JsonValue::Array(items) => content_list(&items)
245 .unwrap_or_else(|| vec![ToolResultContent::json(json!({"$value": JsonValue::Array(items)}))]),
246 object @ JsonValue::Object(_) => vec![ToolResultContent::json(object)],
247 }
248}
249
250fn content_list(items: &[JsonValue]) -> Option<Vec<ToolResultContent>> {
251 if items.is_empty() {
252 return None;
253 }
254 items.iter().map(as_tool_result_content).collect()
255}
256
257fn as_tool_result_content(value: &JsonValue) -> Option<ToolResultContent> {
259 let JsonValue::Object(map) = value else {
260 return None;
261 };
262 if map.len() != 1 {
263 return None;
264 }
265 ToolResultContent::from_data(value.clone()).ok()
266}
267
268fn js_number_string(number: &serde_json::Number) -> String {
270 const MAX_PLAIN_INTEGER: f64 = 1e21;
271 match number.as_f64() {
272 Some(float) if number.is_f64() && float.fract() == 0.0 && float.abs() < MAX_PLAIN_INTEGER => {
273 format!("{float:.0}")
274 }
275 _ => number.to_string(),
276 }
277}
278
279#[cfg(test)]
280mod tests;