pydantic_ai.run
AgentRun
dataclass
Bases: Generic[AgentDepsT, OutputDataT]
A stateful, async-iterable run of an Agent
.
You generally obtain an AgentRun
instance by calling async with my_agent.iter(...) as agent_run:
.
Once you have an instance, you can use it to iterate through the run's nodes as they execute. When an
End
is reached, the run finishes and result
becomes available.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-4o')
async def main():
nodes = []
# Iterate through the run, recording each node along the way:
async with agent.iter('What is the capital of France?') as agent_run:
async for node in agent_run:
nodes.append(node)
print(nodes)
'''
[
UserPromptNode(
user_prompt='What is the capital of France?',
instructions_functions=[],
system_prompts=(),
system_prompt_functions=[],
system_prompt_dynamic_functions={},
),
ModelRequestNode(
request=ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=datetime.datetime(...),
)
]
)
),
CallToolsNode(
model_response=ModelResponse(
parts=[TextPart(content='The capital of France is Paris.')],
usage=RequestUsage(input_tokens=56, output_tokens=7),
model_name='gpt-4o',
timestamp=datetime.datetime(...),
)
),
End(data=FinalResult(output='The capital of France is Paris.')),
]
'''
print(agent_run.result.output)
#> The capital of France is Paris.
You can also manually drive the iteration using the next
method for
more granular control.
Source code in pydantic_ai_slim/pydantic_ai/run.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
|
ctx
property
ctx: GraphRunContext[
GraphAgentState, GraphAgentDeps[AgentDepsT, Any]
]
The current context of the agent run.
next_node
property
next_node: (
AgentNode[AgentDepsT, OutputDataT]
| End[FinalResult[OutputDataT]]
)
The next node that will be run in the agent graph.
This is the next node that will be used during async iteration, or if a node is not passed to self.next(...)
.
result
property
result: AgentRunResult[OutputDataT] | None
The final result of the run if it has ended, otherwise None
.
Once the run returns an End
node, result
is populated
with an AgentRunResult
.
__aiter__
__aiter__() -> (
AsyncIterator[
AgentNode[AgentDepsT, OutputDataT]
| End[FinalResult[OutputDataT]]
]
)
Provide async-iteration over the nodes in the agent run.
Source code in pydantic_ai_slim/pydantic_ai/run.py
140 141 142 143 144 |
|
__anext__
async
__anext__() -> (
AgentNode[AgentDepsT, OutputDataT]
| End[FinalResult[OutputDataT]]
)
Advance to the next node automatically based on the last returned node.
Source code in pydantic_ai_slim/pydantic_ai/run.py
146 147 148 149 150 151 152 153 154 |
|
next
async
next(
node: AgentNode[AgentDepsT, OutputDataT],
) -> (
AgentNode[AgentDepsT, OutputDataT]
| End[FinalResult[OutputDataT]]
)
Manually drive the agent run by passing in the node you want to run next.
This lets you inspect or mutate the node before continuing execution, or skip certain nodes
under dynamic conditions. The agent run should be stopped when you return an End
node.
Example:
from pydantic_ai import Agent
from pydantic_graph import End
agent = Agent('openai:gpt-4o')
async def main():
async with agent.iter('What is the capital of France?') as agent_run:
next_node = agent_run.next_node # start with the first node
nodes = [next_node]
while not isinstance(next_node, End):
next_node = await agent_run.next(next_node)
nodes.append(next_node)
# Once `next_node` is an End, we've finished:
print(nodes)
'''
[
UserPromptNode(
user_prompt='What is the capital of France?',
instructions_functions=[],
system_prompts=(),
system_prompt_functions=[],
system_prompt_dynamic_functions={},
),
ModelRequestNode(
request=ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=datetime.datetime(...),
)
]
)
),
CallToolsNode(
model_response=ModelResponse(
parts=[TextPart(content='The capital of France is Paris.')],
usage=RequestUsage(input_tokens=56, output_tokens=7),
model_name='gpt-4o',
timestamp=datetime.datetime(...),
)
),
End(data=FinalResult(output='The capital of France is Paris.')),
]
'''
print('Final result:', agent_run.result.output)
#> Final result: The capital of France is Paris.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
node
|
AgentNode[AgentDepsT, OutputDataT]
|
The node to run next in the graph. |
required |
Returns:
Type | Description |
---|---|
AgentNode[AgentDepsT, OutputDataT] | End[FinalResult[OutputDataT]]
|
The next node returned by the graph logic, or an |
AgentNode[AgentDepsT, OutputDataT] | End[FinalResult[OutputDataT]]
|
the run has completed. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
|
usage
usage() -> RunUsage
Get usage statistics for the run so far, including token usage, model requests, and so on.
Source code in pydantic_ai_slim/pydantic_ai/run.py
232 233 234 |
|
AgentRunResult
dataclass
Bases: Generic[OutputDataT]
The final result of an agent run.
Source code in pydantic_ai_slim/pydantic_ai/run.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
|
all_messages
all_messages(
*, output_tool_return_content: str | None = None
) -> list[ModelMessage]
Return the history of _messages.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output_tool_return_content
|
str | None
|
The return content of the tool call to set in the last message.
This provides a convenient way to modify the content of the output tool call if you want to continue
the conversation and want to set the response to the output tool call. If |
None
|
Returns:
Type | Description |
---|---|
list[ModelMessage]
|
List of messages. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
|
all_messages_json
Return all messages from all_messages
as JSON bytes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output_tool_return_content
|
str | None
|
The return content of the tool call to set in the last message.
This provides a convenient way to modify the content of the output tool call if you want to continue
the conversation and want to set the response to the output tool call. If |
None
|
Returns:
Type | Description |
---|---|
bytes
|
JSON bytes representing the messages. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
|
new_messages
new_messages(
*, output_tool_return_content: str | None = None
) -> list[ModelMessage]
Return new messages associated with this run.
Messages from older runs are excluded.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output_tool_return_content
|
str | None
|
The return content of the tool call to set in the last message.
This provides a convenient way to modify the content of the output tool call if you want to continue
the conversation and want to set the response to the output tool call. If |
None
|
Returns:
Type | Description |
---|---|
list[ModelMessage]
|
List of new messages. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 |
|
new_messages_json
Return new messages from new_messages
as JSON bytes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output_tool_return_content
|
str | None
|
The return content of the tool call to set in the last message.
This provides a convenient way to modify the content of the output tool call if you want to continue
the conversation and want to set the response to the output tool call. If |
None
|
Returns:
Type | Description |
---|---|
bytes
|
JSON bytes representing the new messages. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
|
usage
usage() -> RunUsage
Return the usage of the whole run.
Source code in pydantic_ai_slim/pydantic_ai/run.py
361 362 363 |
|
timestamp
timestamp() -> datetime
Return the timestamp of last response.
Source code in pydantic_ai_slim/pydantic_ai/run.py
366 367 368 |
|
AgentRunResultEvent
dataclass
Bases: Generic[OutputDataT]
An event indicating the agent run ended and containing the final result of the agent run.
Source code in pydantic_ai_slim/pydantic_ai/run.py
371 372 373 374 375 376 377 378 379 380 381 382 383 |
|
event_kind
class-attribute
instance-attribute
event_kind: Literal["agent_run_result"] = "agent_run_result"
Event type identifier, used as a discriminator.