Skip to content

Commit 45d0ff2

Browse files
authored
Support functions as output_type, as well as lists of functions and other types (#1785)
1 parent 08cf5dd commit 45d0ff2

File tree

14 files changed

+1321
-383
lines changed

14 files changed

+1321
-383
lines changed

docs/multi-agent-applications.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ Of course, you can combine multiple strategies in a single application.
1212
## Agent delegation
1313

1414
"Agent delegation" refers to the scenario where an agent delegates work to another agent, then takes back control when the delegate agent (the agent called from within a tool) finishes.
15+
If you want to hand off control to another agent completely, without coming back to the first agent, you can use an [output function](output.md#output-functions).
1516

1617
Since agents are stateless and designed to be global, you do not need to include the agent itself in agent [dependencies](dependencies.md).
1718

docs/output.md

Lines changed: 151 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1-
"Output" refers to the final value returned from [running an agent](agents.md#running-agents) these can be either plain text or structured data.
1+
"Output" refers to the final value returned from [running an agent](agents.md#running-agents). This can be either plain text, [structured data](#structured-output), or the result of a [function](#output-functions) called with arguments provided by the model.
22

3-
The output is wrapped in [`AgentRunResult`][pydantic_ai.agent.AgentRunResult] or [`StreamedRunResult`][pydantic_ai.result.StreamedRunResult] so you can access other data like [usage][pydantic_ai.usage.Usage] of the run and [message history](message-history.md#accessing-messages-from-results)
3+
The output is wrapped in [`AgentRunResult`][pydantic_ai.agent.AgentRunResult] or [`StreamedRunResult`][pydantic_ai.result.StreamedRunResult] so that you can access other data, like [usage][pydantic_ai.usage.Usage] of the run and [message history](message-history.md#accessing-messages-from-results).
44

55
Both `AgentRunResult` and `StreamedRunResult` are generic in the data they wrap, so typing information about the data returned by the agent is preserved.
66

7+
A run ends when a plain text response is received (assuming no output type is specified or `str` is one of the allowed options), or when the model responds with one of the structured output types by calling a special output tool. A run can also be cancelled if usage limits are exceeded, see [Usage Limits](agents.md#usage-limits).
8+
9+
Here's an example using a Pydantic model as the `output_type`, forcing the model to respond with data matching our specification:
10+
711
```python {title="olympics.py" line_length="90"}
812
from pydantic import BaseModel
913

@@ -25,27 +29,32 @@ print(result.usage())
2529

2630
_(This example is complete, it can be run "as is")_
2731

28-
Runs end when either a plain text response is received or the model calls a tool associated with one of the structured output types (run can also be cancelled if usage limits are exceeded, see [Usage Limits](agents.md#usage-limits)).
29-
3032
## Output data {#structured-output}
3133

32-
When the output type is `str`, or a union including `str`, plain text responses are enabled on the model, and the raw text response from the model is used as the response data.
34+
The [`Agent`][pydantic_ai.Agent] class constructor takes an `output_type` argument that takes one or more types or [output functions](#output-functions). It supports both type unions and lists of types and functions.
35+
36+
When no output type is specified, or when the output type is `str` or a union or list of types including `str`, the model is allowed to respond with plain text, and this text is used as the output data.
37+
If `str` is not among the allowed output types, the model is not allowed to respond with plain text and is forced to return structured data (or arguments to an output function).
3338

34-
If the output type is a union with multiple members (after removing `str` from the members), each member is registered as a separate tool with the model in order to reduce the complexity of the tool schemas and maximise the chances a model will respond correctly.
39+
If the output type is a union or list with multiple members, each member (except for `str`, if it is a member) is registered with the model as a separate output tool in order to reduce the complexity of the tool schemas and maximise the chances a model will respond correctly.
3540

3641
If the output type schema is not of type `"object"` (e.g. it's `int` or `list[int]`), the output type is wrapped in a single element object, so the schema of all tools registered with the model are object schemas.
3742

3843
Structured outputs (like tools) use Pydantic to build the JSON schema used for the tool, and to validate the data returned by the model.
3944

40-
!!! note "Bring on PEP-747"
41-
Until [PEP-747](https://peps.python.org/pep-0747/) "Annotating Type Forms" lands, unions are not valid as `type`s in Python.
45+
!!! note "Type checking considerations"
46+
The Agent class is generic in its output type, and this type is carried through to `AgentRunResult.output` and `StreamedRunResult.output` so that your IDE or static type checker can warn you when your code doesn't properly take into account all the possible values those outputs could have.
4247

43-
When creating the agent we need to `# type: ignore` the `output_type` argument, and add a type hint to tell type checkers about the type of the agent.
48+
Static type checkers like pyright and mypy will do their best the infer the agent's output type from the `output_type` you've specified, but they're not always able to do so correctly when you provide functions or multiple types in a union or list, even though PydanticAI will behave correctly. When this happens, your type checker will complain even when you're confident you've passed a valid `output_type`, and you'll need to help the type checker by explicitly specifying the generic parameters on the `Agent` constructor. This is shown in the second example below and the output functions example further down.
4449

45-
Here's an example of returning either text or a structured value
50+
Specifically, there are three valid uses of `output_type` where you'll need to do this:
51+
1. When using a union of types, e.g. `output_type=Foo | Bar` or in older Python, `output_type=Union[Foo, Bar]`. Until [PEP-747](https://peps.python.org/pep-0747/) "Annotating Type Forms" lands in Python 3.15, type checkers do not consider these a valid value for `output_type`. In addition to the generic parameters on the `Agent` constructor, you'll need to add `# type: ignore` to the line that passes the union to `output_type`.
52+
2. With mypy: When using a list, as a functionally equivalent alternative to a union, or because you're passing in [output functions](#output-functions). Pyright does handle this correctly, and we've filed [an issue](https://github.com/python/mypy/issues/19142) with mypy to try and get this fixed.
53+
3. With mypy: when using an async output function. Pyright does handle this correctly, and we've filed [an issue](https://github.com/python/mypy/issues/19143) with mypy to try and get this fixed.
54+
55+
Here's an example of returning either text or structured data:
4656

4757
```python {title="box_or_error.py"}
48-
from typing import Union
4958

5059
from pydantic import BaseModel
5160

@@ -59,9 +68,9 @@ class Box(BaseModel):
5968
units: str
6069

6170

62-
agent: Agent[None, Union[Box, str]] = Agent(
71+
agent = Agent(
6372
'openai:gpt-4o-mini',
64-
output_type=Union[Box, str], # type: ignore
73+
output_type=[Box, str],
6574
system_prompt=(
6675
"Extract me the dimensions of a box, "
6776
"if you can't extract all data, ask the user to try again."
@@ -79,14 +88,14 @@ print(result.output)
7988

8089
_(This example is complete, it can be run "as is")_
8190

82-
Here's an example of using a union return type which registers multiple tools, and wraps non-object schemas in an object:
91+
Here's an example of using a union return type, for which PydanticAI will register multiple tools and wraps non-object schemas in an object:
8392

8493
```python {title="colors_or_sizes.py"}
8594
from typing import Union
8695

8796
from pydantic_ai import Agent
8897

89-
agent: Agent[None, Union[list[str], list[int]]] = Agent(
98+
agent = Agent[None, Union[list[str], list[int]]](
9099
'openai:gpt-4o-mini',
91100
output_type=Union[list[str], list[int]], # type: ignore
92101
system_prompt='Extract either colors or sizes from the shapes provided.',
@@ -103,10 +112,135 @@ print(result.output)
103112

104113
_(This example is complete, it can be run "as is")_
105114

106-
### Output validator functions
115+
### Output functions
116+
117+
Instead of plain text or structured data, you may want the output of your agent run to be the result of a function called with arguments provided by the model, for example to further process or validate the data provided through the arguments (with the option to tell the model to try again), or to hand off to another agent.
118+
119+
Output functions are similar to [function tools](tools.md), but the model is forced to call one of them, the call ends the agent run, and the result is not passed back to the model.
120+
121+
As with tool functions, output function arguments provided by the model are validated using Pydantic, they can optionally take [`RunContext`][pydantic_ai.tools.RunContext] as the first argument, and they can raise [`ModelRetry`][pydantic_ai.exceptions.ModelRetry] to ask the model to try again with modified arguments (or with a different output type).
122+
123+
To specify output functions, you set the agent's `output_type` to either a single function (or bound instance method), or a list of functions. The list can also contain other output types like simple scalars or entire Pydantic models.
124+
You typically do not want to also register your output function as a tool (using the `@agent.tool` decorator or `tools` argument), as this could confuse the model about which it should be calling.
125+
126+
Here's an example of all of these features in action:
127+
128+
```python {title="output_functions.py"}
129+
import re
130+
from typing import Union
131+
132+
from pydantic import BaseModel
133+
134+
from pydantic_ai import Agent, ModelRetry, RunContext
135+
from pydantic_ai._output import ToolRetryError
136+
from pydantic_ai.exceptions import UnexpectedModelBehavior
137+
138+
139+
class Row(BaseModel):
140+
name: str
141+
country: str
142+
143+
144+
tables = {
145+
'capital_cities': [
146+
Row(name='Amsterdam', country='Netherlands'),
147+
Row(name='Mexico City', country='Mexico'),
148+
]
149+
}
150+
151+
152+
class SQLFailure(BaseModel):
153+
"""An unrecoverable failure. Only use this when you can't change the query to make it work."""
154+
155+
explanation: str
156+
157+
158+
def run_sql_query(query: str) -> list[Row]:
159+
"""Run a SQL query on the database."""
160+
161+
select_table = re.match(r'SELECT (.+) FROM (\w+)', query)
162+
if select_table:
163+
column_names = select_table.group(1)
164+
if column_names != '*':
165+
raise ModelRetry("Only 'SELECT *' is supported, you'll have to do column filtering manually.")
166+
167+
table_name = select_table.group(2)
168+
if table_name not in tables:
169+
raise ModelRetry(
170+
f"Unknown table '{table_name}' in query '{query}'. Available tables: {', '.join(tables.keys())}."
171+
)
172+
173+
return tables[table_name]
174+
175+
raise ModelRetry(f"Unsupported query: '{query}'.")
176+
177+
178+
sql_agent = Agent[None, Union[list[Row], SQLFailure]](
179+
'openai:gpt-4o',
180+
output_type=[run_sql_query, SQLFailure],
181+
instructions='You are a SQL agent that can run SQL queries on a database.',
182+
)
183+
184+
185+
async def hand_off_to_sql_agent(ctx: RunContext, query: str) -> list[Row]:
186+
"""I take natural language queries, turn them into SQL, and run them on a database."""
187+
188+
# Drop the final message with the output tool call, as it shouldn't be passed on to the SQL agent
189+
messages = ctx.messages[:-1]
190+
try:
191+
result = await sql_agent.run(query, message_history=messages)
192+
output = result.output
193+
if isinstance(output, SQLFailure):
194+
raise ModelRetry(f'SQL agent failed: {output.explanation}')
195+
return output
196+
except UnexpectedModelBehavior as e:
197+
# Bubble up potentially retryable errors to the router agent
198+
if (cause := e.__cause__) and isinstance(cause, ToolRetryError):
199+
raise ModelRetry(f'SQL agent failed: {cause.tool_retry.content}') from e
200+
else:
201+
raise
202+
203+
204+
class RouterFailure(BaseModel):
205+
"""Use me when no appropriate agent is found or the used agent failed."""
206+
207+
explanation: str
208+
209+
210+
router_agent = Agent[None, Union[list[Row], RouterFailure]](
211+
'openai:gpt-4o',
212+
output_type=[hand_off_to_sql_agent, RouterFailure],
213+
instructions='You are a router to other agents. Never try to solve a problem yourself, just pass it on.',
214+
)
215+
216+
result = router_agent.run_sync('Select the names and countries of all capitals')
217+
print(result.output)
218+
"""
219+
[
220+
Row(name='Amsterdam', country='Netherlands'),
221+
Row(name='Mexico City', country='Mexico'),
222+
]
223+
"""
224+
225+
result = router_agent.run_sync('Select all pets')
226+
print(result.output)
227+
"""
228+
explanation = "The requested table 'pets' does not exist in the database. The only available table is 'capital_cities', which does not contain data about pets."
229+
"""
230+
231+
result = router_agent.run_sync('How do I fly from Amsterdam to Mexico City?')
232+
print(result.output)
233+
"""
234+
explanation = 'I am not equipped to provide travel information, such as flights from Amsterdam to Mexico City.'
235+
"""
236+
```
237+
238+
### Output validators {#output-validator-functions}
107239

108240
Some validation is inconvenient or impossible to do in Pydantic validators, in particular when the validation requires IO and is asynchronous. PydanticAI provides a way to add validation functions via the [`agent.output_validator`][pydantic_ai.Agent.output_validator] decorator.
109241

242+
If you want to implement separate validation logic for different output types, it's recommended to use [output functions](#output-functions) instead, to save you from having to do `isinstance` checks inside the output validator.
243+
110244
Here's a simplified variant of the [SQL Generation example](examples/sql-gen.md):
111245

112246
```python {title="sql_gen.py"}
@@ -127,7 +261,7 @@ class InvalidRequest(BaseModel):
127261

128262

129263
Output = Union[Success, InvalidRequest]
130-
agent: Agent[DatabaseConn, Output] = Agent(
264+
agent = Agent[DatabaseConn, Output](
131265
'google-gla:gemini-1.5-flash',
132266
output_type=Output, # type: ignore
133267
deps_type=DatabaseConn,

docs/tools.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
Function tools provide a mechanism for models to retrieve extra information to help them generate a response.
44

5-
They're useful when it is impractical or impossible to put all the context an agent might need into the system prompt, or when you want to make agents' behavior more deterministic or reliable by deferring some of the logic required to generate a response to another (not necessarily AI-powered) tool.
5+
They're useful when you want to enable the model to take some action and use the result, when it is impractical or impossible to put all the context an agent might need into the system prompt, or when you want to make agents' behavior more deterministic or reliable by deferring some of the logic required to generate a response to another (not necessarily AI-powered) tool.
6+
7+
If you want a model to be able to call a function as its final action, without the result being sent back to the model, you can use an [output function](output.md#output-functions) instead.
68

79
!!! info "Function tools vs. RAG"
810
Function tools are basically the "R" of RAG (Retrieval-Augmented Generation) — they augment what the model can do by letting it request extra information.

examples/pydantic_ai_examples/sql_gen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ class InvalidRequest(BaseModel):
9292

9393

9494
Response: TypeAlias = Union[Success, InvalidRequest]
95-
agent: Agent[Deps, Response] = Agent(
95+
agent = Agent[Deps, Response](
9696
'google-gla:gemini-1.5-flash',
9797
# Type ignore while we wait for PEP-0747, nonetheless unions will work fine everywhere else
9898
output_type=Response, # type: ignore

0 commit comments

Comments
 (0)