You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/multi-agent-applications.md
+1Lines changed: 1 addition & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -12,6 +12,7 @@ Of course, you can combine multiple strategies in a single application.
12
12
## Agent delegation
13
13
14
14
"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).
15
16
16
17
Since agents are stateless and designed to be global, you do not need to include the agent itself in agent [dependencies](dependencies.md).
"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.
2
2
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).
4
4
5
5
Both `AgentRunResult` and `StreamedRunResult` are generic in the data they wrap, so typing information about the data returned by the agent is preserved.
6
6
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
+
7
11
```python {title="olympics.py" line_length="90"}
8
12
from pydantic import BaseModel
9
13
@@ -25,27 +29,32 @@ print(result.usage())
25
29
26
30
_(This example is complete, it can be run "as is")_
27
31
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
-
30
32
## Output data {#structured-output}
31
33
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).
33
38
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.
35
40
36
41
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.
37
42
38
43
Structured outputs (like tools) use Pydantic to build the JSON schema used for the tool, and to validate the data returned by the model.
39
44
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.
42
47
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.
44
49
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:
46
56
47
57
```python {title="box_or_error.py"}
48
-
from typing import Union
49
58
50
59
from pydantic import BaseModel
51
60
@@ -59,9 +68,9 @@ class Box(BaseModel):
59
68
units: str
60
69
61
70
62
-
agent: Agent[None, Union[Box, str]]= Agent(
71
+
agent = Agent(
63
72
'openai:gpt-4o-mini',
64
-
output_type=Union[Box, str],# type:ignore
73
+
output_type=[Box, str],
65
74
system_prompt=(
66
75
"Extract me the dimensions of a box, "
67
76
"if you can't extract all data, ask the user to try again."
@@ -79,14 +88,14 @@ print(result.output)
79
88
80
89
_(This example is complete, it can be run "as is")_
81
90
82
-
Here's an example of using a union return typewhich 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:
system_prompt='Extract either colors or sizes from the shapes provided.',
@@ -103,10 +112,135 @@ print(result.output)
103
112
104
113
_(This example is complete, it can be run "as is")_
105
114
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
+
classRow(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
+
classSQLFailure(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
+
defrun_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 notin tables:
169
+
raise ModelRetry(
170
+
f"Unknown table '{table_name}' in query '{query}'. Available tables: {', '.join(tables.keys())}."
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.'
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.
109
241
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
+
110
244
Here's a simplified variant of the [SQL Generation example](examples/sql-gen.md):
111
245
112
246
```python {title="sql_gen.py"}
@@ -127,7 +261,7 @@ class InvalidRequest(BaseModel):
Copy file name to clipboardExpand all lines: docs/tools.md
+3-1Lines changed: 3 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -2,7 +2,9 @@
2
2
3
3
Function tools provide a mechanism for models to retrieve extra information to help them generate a response.
4
4
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.
6
8
7
9
!!! info "Function tools vs. RAG"
8
10
Function tools are basically the "R" of RAG (Retrieval-Augmented Generation) — they augment what the model can do by letting it request extra information.
0 commit comments