|
| 1 | +# Structured Output Example |
| 2 | + |
| 3 | +This example demonstrates how to use Strands' structured output feature to get type-safe, validated responses from language models using [Pydantic](https://docs.pydantic.dev/latest/concepts/models/) models. Instead of raw text that you need to parse manually, you define the exact structure you want and receive a validated Python object. |
| 4 | + |
| 5 | +## What You'll Learn |
| 6 | + |
| 7 | +- How to define Pydantic models for structured output |
| 8 | +- Extracting structured information from text |
| 9 | +- Using conversation history with structured output |
| 10 | +- Working with complex nested models |
| 11 | + |
| 12 | +## Code Example |
| 13 | + |
| 14 | +The example covers four key use cases: |
| 15 | + |
| 16 | +1. Basic structured output |
| 17 | +2. Using existing conversation context |
| 18 | +3. Working with complex nested models |
| 19 | + |
| 20 | +```python |
| 21 | +#!/usr/bin/env python3 |
| 22 | +""" |
| 23 | +Structured Output Example |
| 24 | +
|
| 25 | +This example demonstrates how to use structured output with Strands Agents to |
| 26 | +get type-safe, validated responses using Pydantic models. |
| 27 | +""" |
| 28 | + |
| 29 | +from typing import List, Optional |
| 30 | +from pydantic import BaseModel, Field |
| 31 | +from strands import Agent |
| 32 | + |
| 33 | +def basic_example(): |
| 34 | + """Basic example extracting structured information from text.""" |
| 35 | + print("\n--- Basic Example ---") |
| 36 | + |
| 37 | + class PersonInfo(BaseModel): |
| 38 | + name: str |
| 39 | + age: int |
| 40 | + occupation: str |
| 41 | + |
| 42 | + agent = Agent() |
| 43 | + result = agent.structured_output( |
| 44 | + PersonInfo, |
| 45 | + "John Smith is a 30-year-old software engineer" |
| 46 | + ) |
| 47 | + |
| 48 | + print(f"Name: {result.name}") # "John Smith" |
| 49 | + print(f"Age: {result.age}") # 30 |
| 50 | + print(f"Job: {result.occupation}") # "software engineer" |
| 51 | + |
| 52 | + |
| 53 | +def conversation_history_example(): |
| 54 | + """Example using conversation history with structured output.""" |
| 55 | + print("\n--- Conversation History Example ---") |
| 56 | + |
| 57 | + agent = Agent() |
| 58 | + |
| 59 | + # Build up conversation context |
| 60 | + print("Building conversation context...") |
| 61 | + agent("What do you know about Paris, France?") |
| 62 | + agent("Tell me about the weather there in spring.") |
| 63 | + |
| 64 | + # Extract structured information with a prompt |
| 65 | + class CityInfo(BaseModel): |
| 66 | + city: str |
| 67 | + country: str |
| 68 | + population: Optional[int] = None |
| 69 | + climate: str |
| 70 | + |
| 71 | + # Uses existing conversation context with a prompt |
| 72 | + print("Extracting structured information from conversation context...") |
| 73 | + result = agent.structured_output(CityInfo, "Extract structured information about Paris") |
| 74 | + |
| 75 | + print(f"City: {result.city}") |
| 76 | + print(f"Country: {result.country}") |
| 77 | + print(f"Population: {result.population}") |
| 78 | + print(f"Climate: {result.climate}") |
| 79 | + |
| 80 | + |
| 81 | +def complex_nested_model_example(): |
| 82 | + """Example handling complex nested data structures.""" |
| 83 | + print("\n--- Complex Nested Model Example ---") |
| 84 | + |
| 85 | + class Address(BaseModel): |
| 86 | + street: str |
| 87 | + city: str |
| 88 | + country: str |
| 89 | + postal_code: Optional[str] = None |
| 90 | + |
| 91 | + class Contact(BaseModel): |
| 92 | + email: Optional[str] = None |
| 93 | + phone: Optional[str] = None |
| 94 | + |
| 95 | + class Person(BaseModel): |
| 96 | + """Complete person information.""" |
| 97 | + name: str = Field(description="Full name of the person") |
| 98 | + age: int = Field(description="Age in years") |
| 99 | + address: Address = Field(description="Home address") |
| 100 | + contacts: List[Contact] = Field(default_factory=list, description="Contact methods") |
| 101 | + skills: List[str] = Field(default_factory=list, description="Professional skills") |
| 102 | + |
| 103 | + agent = Agent() |
| 104 | + result = agent.structured_output( |
| 105 | + Person, |
| 106 | + "Extract info: Jane Doe, a systems admin, 28, lives at 123 Main St, New York, USA. Email: jane@example.com" |
| 107 | + ) |
| 108 | + |
| 109 | + print(f"Name: {result.name}") # "Jane Doe" |
| 110 | + print(f"Age: {result.age}") # 28 |
| 111 | + print(f"Street: {result.address.street}") # "123 Main St" |
| 112 | + print(f"City: {result.address.city}") # "New York" |
| 113 | + print(f"Country: {result.address.country}") # "USA" |
| 114 | + print(f"Email: {result.contacts[0].email}") # "jane@example.com" |
| 115 | + print(f"Skills: {result.skills}") # ["systems admin"] |
| 116 | + |
| 117 | + |
| 118 | +if __name__ == "__main__": |
| 119 | + print("Structured Output Examples\n") |
| 120 | + |
| 121 | + basic_example() |
| 122 | + conversation_history_example() |
| 123 | + complex_nested_model_example() |
| 124 | + |
| 125 | + print("\nExamples completed.") |
| 126 | +``` |
| 127 | + |
| 128 | +## How It Works |
| 129 | + |
| 130 | +1. **Define a Schema**: Create a Pydantic model that defines the structure you want |
| 131 | +2. **Call structured_output()**: Pass your model and optionally a prompt to the agent |
| 132 | +3. **Get Validated Results**: Receive a properly typed Python object matching your schema |
| 133 | + |
| 134 | +The `structured_output()` method ensures that the language model generates a response that conforms to your specified schema. It handles converting your Pydantic model into a format the model understands and validates the response. |
| 135 | + |
| 136 | +## Key Benefits |
| 137 | + |
| 138 | +- Type-safe responses with proper Python types |
| 139 | +- Automatic validation against your schema |
| 140 | +- IDE type hinting from LLM-generated responses |
| 141 | +- Clear documentation of expected output |
| 142 | +- Error prevention for malformed responses |
| 143 | + |
| 144 | +## Learn More |
| 145 | + |
| 146 | +For more details on structured output, see the [Structured Output documentation](../../user-guide/concepts/agents/structured-output.md). |
0 commit comments