Skip to main content

strands/tools/
function_tool.rs

1//! A tool built from a callback.
2
3use 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/// What a streaming [`FunctionTool`] callback yields (an async generator's `yield` and `return`).
19#[derive(Debug, Clone, PartialEq)]
20#[non_exhaustive]
21pub enum FunctionToolItem {
22    /// A progress value, surfaced as a [`ToolStreamEvent`].
23    Update(JsonValue),
24    /// The return value, wrapped in the tool result; the stream ends here.
25    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/// A tool that wraps a callback and shapes its return value into a result (`FunctionTool`).
39///
40/// The callback receives the raw input and the [`ToolContext`] and returns a JSON value, which
41/// becomes the result content following these rules:
42///
43/// - a one-key object that reads as tool result content (`{"text": ..}`, `{"json": ..}`,
44///   `{"image": ..}`, `{"video": ..}`, `{"document": ..}`) is used as is, and so is an array of
45///   such objects;
46/// - a string, number or boolean becomes text;
47/// - `null` becomes the text `null`;
48/// - any other array becomes JSON content `{"$value": [..]}`, and any other object JSON content.
49///
50/// An `Err` becomes an error result with the text `Error: <message>`, except an interrupt, which
51/// ends the tool as [`ToolOutcome::Interrupt`].
52///
53/// ```
54/// use serde_json::json;
55/// use strands::tools::FunctionTool;
56///
57/// let greet = FunctionTool::builder("greeter", "Greets a person by name")
58///     .input_schema(json!({
59///         "type": "object",
60///         "properties": {"name": {"type": "string"}},
61///         "required": ["name"]
62///     }))
63///     .callback(|input, _context| async move { Ok(format!("Hello, {}!", input["name"].as_str().unwrap_or("you")).into()) });
64/// # let _ = greet;
65/// ```
66#[derive(Clone)]
67pub struct FunctionTool {
68    spec: ToolSpec,
69    validator: Option<Arc<SchemaValidator>>,
70    body: Body,
71}
72
73/// Builds a [`FunctionTool`]; finish with [`callback`](Self::callback) or
74/// [`stream_callback`](Self::stream_callback).
75#[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    /// Starts a tool with a name and description.
85    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    /// Sets the input JSON Schema. Without one the tool takes an empty object
139    /// (`{"type":"object","properties":{},"additionalProperties":false}`). The input is passed to
140    /// the callback as given, unvalidated.
141    #[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    /// Uses the normalized schema of `T` as the input schema and validates the input against it
149    /// before calling the callback; invalid input becomes an error result listing the violations.
150    #[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    /// Finishes the tool with an async callback that returns the result value.
167    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    /// Finishes the tool with a streaming callback: each [`FunctionToolItem::Update`] becomes a
181    /// progress event and [`FunctionToolItem::Return`] the result. A stream that ends without a
182    /// return value returns `null`.
183    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/// Shapes a tool's return value into a successful result; see
229/// [`FunctionTool`] for the rules.
230#[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
257/// A one-key object that parses as tool result content; other values are not content.
258fn 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
268/// Formats a number as text, writing integral floats below 1e21 without a fraction (`2.0` as `2`).
269fn 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;