Skip to main content

strands/tools/
structured_output_tool.rs

1//! The tool that validates structured output.
2
3use std::fmt;
4use std::sync::Arc;
5
6use schemars::JsonSchema as SchemarsJsonSchema;
7
8use super::schema::{SchemaValidator, schema_for};
9use super::tool::{Tool, ToolContext, ToolStream};
10use crate::error::{Result, StructuredOutputError};
11use crate::types::{ContentBlock, JsonSchema, JsonValue, Message, ToolResultBlock, ToolResultContent, ToolSpec};
12
13/// The name of the structured output tool.
14pub const STRUCTURED_OUTPUT_TOOL_NAME: &str = "strands_structured_output";
15
16/// The error text when the model neither called the structured output tool nor returned a JSON
17/// object.
18pub(crate) const NO_STRUCTURED_OUTPUT_MESSAGE: &str = "The model did not produce structured output: it neither called the structured output tool nor returned a JSON object.";
19
20const INSTRUCTION: &str =
21    "This tool MUST only be invoked as the last and final tool before returning the completed result to the caller.";
22
23/// Validates the model's structured output against a JSON Schema (`StructuredOutputTool`).
24///
25/// A valid input is the result, as JSON content; an invalid one is an error result listing the
26/// violations, so the model can retry. The schema's top-level `description` is added to the tool
27/// description.
28#[derive(Clone)]
29pub struct StructuredOutputTool {
30    spec: ToolSpec,
31    validator: Arc<SchemaValidator>,
32}
33
34impl StructuredOutputTool {
35    /// Creates the tool for a JSON Schema.
36    ///
37    /// # Errors
38    ///
39    /// When `schema` is not a valid JSON Schema.
40    pub fn new(schema: JsonSchema) -> Result<Self> {
41        let validator = Arc::new(SchemaValidator::new(&schema)?);
42        let description = match schema.get("description").and_then(JsonValue::as_str) {
43            Some(description) => format!("{INSTRUCTION}\n<description>{description}</description>"),
44            None => INSTRUCTION.to_owned(),
45        };
46        let spec = ToolSpec::new(STRUCTURED_OUTPUT_TOOL_NAME, description).with_input_schema(schema);
47        Ok(Self { spec, validator })
48    }
49
50    /// Creates the tool for the normalized schema of `T`.
51    ///
52    /// # Errors
53    ///
54    /// When the generated schema does not compile.
55    pub fn for_type<T: SchemarsJsonSchema>() -> Result<Self> {
56        Self::new(schema_for::<T>())
57    }
58
59    /// Validates the text of an assistant message as structured output, for
60    /// providers that return it as JSON text instead of calling the tool. The text blocks, joined,
61    /// must be exactly one JSON object.
62    ///
63    /// # Errors
64    ///
65    /// [`StructuredOutputError`] when the text is not a JSON object, or the object does not
66    /// validate (`Structured output failed validation: ...`).
67    pub fn result_from_text(&self, message: &Message) -> Result<JsonValue> {
68        let text: String = message.content.iter().filter_map(ContentBlock::as_text).collect();
69        let data = serde_json::from_str::<JsonValue>(&text)
70            .ok()
71            .filter(JsonValue::is_object)
72            .ok_or_else(|| StructuredOutputError::new(NO_STRUCTURED_OUTPUT_MESSAGE))?;
73        self.validator.validate(&data).map_err(|error| {
74            StructuredOutputError::new(format!("Structured output failed validation: {}", error.message))
75        })?;
76        Ok(data)
77    }
78}
79
80impl Tool for StructuredOutputTool {
81    fn name(&self) -> &str {
82        &self.spec.name
83    }
84
85    fn description(&self) -> &str {
86        &self.spec.description
87    }
88
89    fn tool_spec(&self) -> ToolSpec {
90        self.spec.clone()
91    }
92
93    fn stream(&self, context: ToolContext) -> ToolStream {
94        let tool_use = context.tool_use();
95        let result = match self.validator.validate(&tool_use.input) {
96            Ok(()) => ToolResultBlock::success(
97                tool_use.tool_use_id.clone(),
98                vec![ToolResultContent::json(tool_use.input.clone())],
99            ),
100            Err(error) => ToolResultBlock::error(
101                tool_use.tool_use_id.clone(),
102                vec![ToolResultContent::text(error.message.clone())],
103            )
104            .with_error(error),
105        };
106        ToolStream::ready(result)
107    }
108}
109
110impl fmt::Debug for StructuredOutputTool {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        f.debug_struct("StructuredOutputTool")
113            .field("spec", &self.spec)
114            .finish_non_exhaustive()
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use serde_json::json;
121
122    use super::*;
123    use crate::Error;
124    use crate::testing::tool_context;
125    use crate::tools::ToolOutcome;
126    use crate::types::{ReasoningBlock, Role, ToolResultStatus, ToolUse};
127
128    fn person_schema() -> JsonSchema {
129        json!({
130            "type": "object",
131            "properties": {"name": {"type": "string"}, "age": {"type": "number"}},
132            "required": ["name", "age"]
133        })
134    }
135
136    async fn run(tool: &StructuredOutputTool, input: JsonValue) -> ToolResultBlock {
137        let context = tool_context(ToolUse::new(STRUCTURED_OUTPUT_TOOL_NAME, "tool-1", input));
138        match tool.stream(context).run(|_| {}).await {
139            Some(ToolOutcome::Result(result)) => result,
140            other => panic!("expected a result, got {other:?}"),
141        }
142    }
143
144    fn text_of(result: &ToolResultBlock) -> String {
145        match &result.content[0] {
146            ToolResultContent::Text(text) => text.text.clone(),
147            other => panic!("expected text, got {other:?}"),
148        }
149    }
150
151    #[test]
152    fn builds_tool_spec_from_schema() {
153        let mut schema = person_schema();
154        schema["description"] = json!("A person schema");
155        let tool = StructuredOutputTool::new(schema).unwrap();
156        assert_eq!(tool.name(), STRUCTURED_OUTPUT_TOOL_NAME);
157        assert_eq!(tool.tool_spec().name, STRUCTURED_OUTPUT_TOOL_NAME);
158        assert!(tool.tool_spec().input_schema.is_some());
159        assert_eq!(
160            tool.description(),
161            format!("{INSTRUCTION}\n<description>A person schema</description>")
162        );
163    }
164
165    #[test]
166    fn uses_base_description_when_schema_has_no_description() {
167        let tool = StructuredOutputTool::new(person_schema()).unwrap();
168        assert!(tool.description().contains("MUST only be invoked"));
169        assert!(!tool.description().contains("<description>"));
170    }
171
172    #[test]
173    fn builds_the_schema_of_a_type_with_its_doc_comment() {
174        /// A person.
175        #[derive(schemars::JsonSchema)]
176        #[allow(dead_code, reason = "schema-only type")]
177        struct Person {
178            name: String,
179        }
180        let tool = StructuredOutputTool::for_type::<Person>().unwrap();
181        assert!(tool.description().ends_with("<description>A person.</description>"));
182    }
183
184    #[tokio::test]
185    async fn returns_success_with_validated_json_for_valid_input() {
186        let tool = StructuredOutputTool::new(person_schema()).unwrap();
187        let result = run(&tool, json!({"name": "John", "age": 30})).await;
188        assert_eq!(
189            result,
190            ToolResultBlock::success(
191                "tool-1",
192                vec![ToolResultContent::json(json!({"name": "John", "age": 30}))]
193            )
194        );
195    }
196
197    #[tokio::test]
198    async fn returns_error_with_validation_error_for_invalid_input() {
199        let tool = StructuredOutputTool::new(person_schema()).unwrap();
200        let result = run(&tool, json!({"name": "John", "age": "invalid"})).await;
201        assert_eq!(result.status, ToolResultStatus::Error);
202        assert!(result.error.is_some());
203        assert!(text_of(&result).contains("age"));
204    }
205
206    #[tokio::test]
207    async fn includes_validation_details_for_multiple_fields() {
208        let schema = json!({
209            "type": "object",
210            "properties": {
211                "name": {"type": "string"},
212                "age": {"type": "number"},
213                "email": {"type": "string", "pattern": "^[^@]+@[^@]+$"}
214            },
215            "required": ["name", "age", "email"]
216        });
217        let tool = StructuredOutputTool::new(schema).unwrap();
218        let result = run(&tool, json!({"name": 123, "age": "invalid", "email": "not-email"})).await;
219        assert_eq!(result.status, ToolResultStatus::Error);
220        let text = text_of(&result);
221        assert!(
222            text.contains("name") && text.contains("age") && text.contains("email"),
223            "{text}"
224        );
225    }
226
227    #[tokio::test]
228    async fn validates_nested_objects() {
229        let schema = json!({
230            "type": "object",
231            "properties": {"user": person_schema()},
232            "required": ["user"]
233        });
234        let tool = StructuredOutputTool::new(schema).unwrap();
235        let result = run(&tool, json!({"user": {"name": "John", "age": 30}})).await;
236        assert_eq!(result.status, ToolResultStatus::Success);
237        assert_eq!(
238            result.content,
239            vec![ToolResultContent::json(json!({"user": {"name": "John", "age": 30}}))]
240        );
241    }
242
243    #[tokio::test]
244    async fn validates_arrays() {
245        let schema = json!({"type": "object", "properties": {"items": {"type": "array", "items": {"type": "string"}}}});
246        let tool = StructuredOutputTool::new(schema).unwrap();
247        let result = run(&tool, json!({"items": ["a", "b", "c"]})).await;
248        assert_eq!(
249            result.content,
250            vec![ToolResultContent::json(json!({"items": ["a", "b", "c"]}))]
251        );
252    }
253
254    #[tokio::test]
255    async fn handles_optional_fields() {
256        let schema = json!({
257            "type": "object",
258            "properties": {"name": {"type": "string"}, "age": {"type": "number"}},
259            "required": ["name"]
260        });
261        let tool = StructuredOutputTool::new(schema).unwrap();
262        let result = run(&tool, json!({"name": "John"})).await;
263        assert_eq!(result.status, ToolResultStatus::Success);
264        assert_eq!(result.content, vec![ToolResultContent::json(json!({"name": "John"}))]);
265    }
266
267    fn assistant(content: Vec<ContentBlock>) -> Message {
268        Message::new(Role::Assistant, content)
269    }
270
271    #[test]
272    fn returns_the_validated_json_object_from_the_text_blocks_ignoring_reasoning() {
273        let tool = StructuredOutputTool::new(person_schema()).unwrap();
274        let message = assistant(vec![
275            ReasoningBlock::new().with_text("thinking").into(),
276            ContentBlock::text(r#"{"name": "John", "#),
277            ContentBlock::text(r#""age": 30, "extra": true}"#),
278        ]);
279        assert_eq!(
280            tool.result_from_text(&message).unwrap(),
281            json!({"name": "John", "age": 30, "extra": true})
282        );
283    }
284
285    #[test]
286    fn throws_the_no_structured_output_error_for_non_objects() {
287        let tool = StructuredOutputTool::new(person_schema()).unwrap();
288        for text in ["John is 30", r#"[{"name": "John", "age": 30}]"#, "42", "null", ""] {
289            let error = tool
290                .result_from_text(&assistant(vec![ContentBlock::text(text)]))
291                .unwrap_err();
292            assert!(matches!(error, Error::StructuredOutput(_)), "{text}");
293            assert_eq!(error.to_string(), NO_STRUCTURED_OUTPUT_MESSAGE);
294        }
295    }
296
297    #[test]
298    fn throws_a_validation_error_for_an_object_that_does_not_match_the_schema() {
299        let tool = StructuredOutputTool::new(person_schema()).unwrap();
300        let message = assistant(vec![ContentBlock::text(r#"{"name": "John", "age": "thirty"}"#)]);
301        let error = tool.result_from_text(&message).unwrap_err();
302        assert!(matches!(error, Error::StructuredOutput(_)));
303        let text = error.to_string();
304        assert!(text.starts_with("Structured output failed validation: "), "{text}");
305        assert!(text.contains("age"), "{text}");
306    }
307}