The Pattern
Instead of parsing free-form text, define a tool that captures the exact structure you need. The AI will call it with structured data.Complete Example: Data Extraction Pipeline
Extract structured data from unstructured text:Classification
Use structured output for classification tasks:Multiple Extractions
Extract multiple items from a document:Tips
Use clear field descriptions
Use clear field descriptions
The AI uses field descriptions to understand what to extract. Be specific.
Use has_tool_call to stop
Use has_tool_call to stop
Stop the loop when your extraction tool is called to avoid extra processing.
Capture data via closure
Capture data via closure
Use a mutable dict or list in the outer scope to capture the tool’s arguments.
Validate the output
Validate the output
Always validate extracted data before using it in production.