Skip to content

Commit 2627af6

Browse files
feat: adds structured output docs (#86)
* feat: adds structured output docs * fix: mkdocs formatting * docs: add structured output documentation and examples * feat: correct api ref links, cleaned up docs * fix: deduplication, clearer IDE message * fix: error handling * fix: remove old heading
1 parent 5552f93 commit 2627af6

File tree

4 files changed

+421
-0
lines changed

4 files changed

+421
-0
lines changed
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
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).
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Structured Output Example
4+
5+
This example demonstrates how to use structured output with Strands Agents to
6+
get type-safe, validated responses using Pydantic models.
7+
"""
8+
9+
from typing import List, Optional
10+
from pydantic import BaseModel, Field
11+
from strands import Agent
12+
13+
def basic_example():
14+
"""Basic example extracting structured information from text."""
15+
print("\n--- Basic Example ---")
16+
17+
class PersonInfo(BaseModel):
18+
name: str
19+
age: int
20+
occupation: str
21+
22+
agent = Agent()
23+
result = agent.structured_output(
24+
PersonInfo,
25+
"John Smith is a 30-year-old software engineer"
26+
)
27+
28+
print(f"Name: {result.name}") # "John Smith"
29+
print(f"Age: {result.age}") # 30
30+
print(f"Job: {result.occupation}") # "software engineer"
31+
32+
33+
def conversation_history_example():
34+
"""Example using conversation history with structured output."""
35+
print("\n--- Conversation History Example ---")
36+
37+
agent = Agent()
38+
39+
# Build up conversation context
40+
print("Building conversation context...")
41+
agent("What do you know about Paris, France?")
42+
agent("Tell me about the weather there in spring.")
43+
44+
# Extract structured information without additional prompt
45+
class CityInfo(BaseModel):
46+
city: str
47+
country: str
48+
population: Optional[int] = None
49+
climate: str
50+
51+
# Uses existing conversation context with a prompt
52+
print("Extracting structured information from conversation context...")
53+
result = agent.structured_output(CityInfo, "Extract structured information about Paris")
54+
55+
print(f"City: {result.city}")
56+
print(f"Country: {result.country}")
57+
print(f"Population: {result.population}")
58+
print(f"Climate: {result.climate}")
59+
60+
61+
def complex_nested_model_example():
62+
"""Example handling complex nested data structures."""
63+
print("\n--- Complex Nested Model Example ---")
64+
65+
class Address(BaseModel):
66+
street: str
67+
city: str
68+
country: str
69+
postal_code: Optional[str] = None
70+
71+
class Contact(BaseModel):
72+
email: Optional[str] = None
73+
phone: Optional[str] = None
74+
75+
class Person(BaseModel):
76+
"""Complete person information."""
77+
name: str = Field(description="Full name of the person")
78+
age: int = Field(description="Age in years")
79+
address: Address = Field(description="Home address")
80+
contacts: List[Contact] = Field(default_factory=list, description="Contact methods")
81+
skills: List[str] = Field(default_factory=list, description="Professional skills")
82+
83+
agent = Agent()
84+
result = agent.structured_output(
85+
Person,
86+
"Extract info: Jane Doe, a systems admin, 28, lives at 123 Main St, New York, USA. Email: jane@example.com"
87+
)
88+
89+
print(f"Name: {result.name}") # "Jane Doe"
90+
print(f"Age: {result.age}") # 28
91+
print(f"Street: {result.address.street}") # "123 Main St"
92+
print(f"City: {result.address.city}") # "New York"
93+
print(f"Country: {result.address.country}") # "USA"
94+
print(f"Email: {result.contacts[0].email}") # "jane@example.com"
95+
print(f"Skills: {result.skills}") # ["systems admin"]
96+
97+
98+
if __name__ == "__main__":
99+
print("Structured Output Examples\n")
100+
101+
basic_example()
102+
conversation_history_example()
103+
complex_nested_model_example()
104+
105+
print("\nExamples completed.")

0 commit comments

Comments
 (0)