pydantic-ai-slim 1.0.1__py3-none-any.whl → 1.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of pydantic-ai-slim might be problematic. Click here for more details.
- pydantic_ai/_agent_graph.py +50 -31
- pydantic_ai/_tool_manager.py +4 -0
- pydantic_ai/agent/__init__.py +3 -0
- pydantic_ai/durable_exec/dbos/__init__.py +6 -0
- pydantic_ai/durable_exec/dbos/_agent.py +718 -0
- pydantic_ai/durable_exec/dbos/_mcp_server.py +89 -0
- pydantic_ai/durable_exec/dbos/_model.py +137 -0
- pydantic_ai/durable_exec/dbos/_utils.py +10 -0
- pydantic_ai/mcp.py +1 -1
- pydantic_ai/messages.py +12 -0
- pydantic_ai/models/__init__.py +8 -0
- pydantic_ai/models/anthropic.py +24 -0
- pydantic_ai/models/google.py +43 -4
- pydantic_ai/models/instrumented.py +27 -14
- pydantic_ai/models/openai.py +67 -16
- pydantic_ai/providers/bedrock.py +11 -3
- pydantic_ai/tools.py +11 -0
- pydantic_ai/toolsets/function.py +7 -0
- {pydantic_ai_slim-1.0.1.dist-info → pydantic_ai_slim-1.0.2.dist-info}/METADATA +6 -4
- {pydantic_ai_slim-1.0.1.dist-info → pydantic_ai_slim-1.0.2.dist-info}/RECORD +23 -18
- {pydantic_ai_slim-1.0.1.dist-info → pydantic_ai_slim-1.0.2.dist-info}/WHEEL +0 -0
- {pydantic_ai_slim-1.0.1.dist-info → pydantic_ai_slim-1.0.2.dist-info}/entry_points.txt +0 -0
- {pydantic_ai_slim-1.0.1.dist-info → pydantic_ai_slim-1.0.2.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,718 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterable, AsyncIterator, Iterator, Sequence
|
|
4
|
+
from contextlib import AbstractAsyncContextManager, asynccontextmanager, contextmanager
|
|
5
|
+
from typing import Any, overload
|
|
6
|
+
|
|
7
|
+
from dbos import DBOS, DBOSConfiguredInstance
|
|
8
|
+
from typing_extensions import Never
|
|
9
|
+
|
|
10
|
+
from pydantic_ai import (
|
|
11
|
+
_utils,
|
|
12
|
+
messages as _messages,
|
|
13
|
+
models,
|
|
14
|
+
usage as _usage,
|
|
15
|
+
)
|
|
16
|
+
from pydantic_ai._run_context import AgentDepsT
|
|
17
|
+
from pydantic_ai.agent import AbstractAgent, AgentRun, AgentRunResult, EventStreamHandler, RunOutputDataT, WrapperAgent
|
|
18
|
+
from pydantic_ai.exceptions import UserError
|
|
19
|
+
from pydantic_ai.mcp import MCPServer
|
|
20
|
+
from pydantic_ai.models import Model
|
|
21
|
+
from pydantic_ai.output import OutputDataT, OutputSpec
|
|
22
|
+
from pydantic_ai.result import StreamedRunResult
|
|
23
|
+
from pydantic_ai.settings import ModelSettings
|
|
24
|
+
from pydantic_ai.tools import (
|
|
25
|
+
DeferredToolResults,
|
|
26
|
+
RunContext,
|
|
27
|
+
Tool,
|
|
28
|
+
ToolFuncEither,
|
|
29
|
+
)
|
|
30
|
+
from pydantic_ai.toolsets import AbstractToolset
|
|
31
|
+
|
|
32
|
+
from ._mcp_server import DBOSMCPServer
|
|
33
|
+
from ._model import DBOSModel
|
|
34
|
+
from ._utils import StepConfig
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@DBOS.dbos_class()
|
|
38
|
+
class DBOSAgent(WrapperAgent[AgentDepsT, OutputDataT], DBOSConfiguredInstance):
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
wrapped: AbstractAgent[AgentDepsT, OutputDataT],
|
|
42
|
+
*,
|
|
43
|
+
name: str | None = None,
|
|
44
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
45
|
+
mcp_step_config: StepConfig | None = None,
|
|
46
|
+
model_step_config: StepConfig | None = None,
|
|
47
|
+
):
|
|
48
|
+
"""Wrap an agent to enable it with DBOS durable workflows, by automatically offloading model requests, tool calls, and MCP server communication to DBOS steps.
|
|
49
|
+
|
|
50
|
+
After wrapping, the original agent can still be used as normal outside of the DBOS workflow.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
wrapped: The agent to wrap.
|
|
54
|
+
name: Optional unique agent name to use as the DBOS configured instance name. If not provided, the agent's `name` will be used.
|
|
55
|
+
event_stream_handler: Optional event stream handler to use instead of the one set on the wrapped agent.
|
|
56
|
+
mcp_step_config: The base DBOS step config to use for MCP server steps. If no config is provided, use the default settings of DBOS.
|
|
57
|
+
model_step_config: The DBOS step config to use for model request steps. If no config is provided, use the default settings of DBOS.
|
|
58
|
+
"""
|
|
59
|
+
super().__init__(wrapped)
|
|
60
|
+
|
|
61
|
+
self._name = name or wrapped.name
|
|
62
|
+
self._event_stream_handler = event_stream_handler
|
|
63
|
+
if self._name is None:
|
|
64
|
+
raise UserError(
|
|
65
|
+
"An agent needs to have a unique `name` in order to be used with DBOS. The name will be used to identify the agent's workflows and steps."
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
# Merge the config with the default DBOS config
|
|
69
|
+
self._mcp_step_config = mcp_step_config or {}
|
|
70
|
+
self._model_step_config = model_step_config or {}
|
|
71
|
+
|
|
72
|
+
if not isinstance(wrapped.model, Model):
|
|
73
|
+
raise UserError(
|
|
74
|
+
'An agent needs to have a `model` in order to be used with DBOS, it cannot be set at agent run time.'
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
dbos_model = DBOSModel(
|
|
78
|
+
wrapped.model,
|
|
79
|
+
step_name_prefix=self._name,
|
|
80
|
+
step_config=self._model_step_config,
|
|
81
|
+
event_stream_handler=self.event_stream_handler,
|
|
82
|
+
)
|
|
83
|
+
self._model = dbos_model
|
|
84
|
+
|
|
85
|
+
dbosagent_name = self._name
|
|
86
|
+
|
|
87
|
+
def dbosify_toolset(toolset: AbstractToolset[AgentDepsT]) -> AbstractToolset[AgentDepsT]:
|
|
88
|
+
# Replace MCPServer with DBOSMCPServer
|
|
89
|
+
if isinstance(toolset, MCPServer):
|
|
90
|
+
return DBOSMCPServer(
|
|
91
|
+
wrapped=toolset,
|
|
92
|
+
step_name_prefix=dbosagent_name,
|
|
93
|
+
step_config=self._mcp_step_config,
|
|
94
|
+
)
|
|
95
|
+
else:
|
|
96
|
+
return toolset
|
|
97
|
+
|
|
98
|
+
dbos_toolsets = [toolset.visit_and_replace(dbosify_toolset) for toolset in wrapped.toolsets]
|
|
99
|
+
self._toolsets = dbos_toolsets
|
|
100
|
+
DBOSConfiguredInstance.__init__(self, self._name)
|
|
101
|
+
|
|
102
|
+
# Wrap the `run` method in a DBOS workflow
|
|
103
|
+
@DBOS.workflow(name=f'{self._name}.run')
|
|
104
|
+
async def wrapped_run_workflow(
|
|
105
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
106
|
+
*,
|
|
107
|
+
output_type: OutputSpec[RunOutputDataT] | None = None,
|
|
108
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
109
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
110
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
111
|
+
deps: AgentDepsT,
|
|
112
|
+
model_settings: ModelSettings | None = None,
|
|
113
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
114
|
+
usage: _usage.RunUsage | None = None,
|
|
115
|
+
infer_name: bool = True,
|
|
116
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
117
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
118
|
+
**_deprecated_kwargs: Never,
|
|
119
|
+
) -> AgentRunResult[Any]:
|
|
120
|
+
with self._dbos_overrides():
|
|
121
|
+
return await super(WrapperAgent, self).run(
|
|
122
|
+
user_prompt,
|
|
123
|
+
output_type=output_type,
|
|
124
|
+
message_history=message_history,
|
|
125
|
+
deferred_tool_results=deferred_tool_results,
|
|
126
|
+
model=model,
|
|
127
|
+
deps=deps,
|
|
128
|
+
model_settings=model_settings,
|
|
129
|
+
usage_limits=usage_limits,
|
|
130
|
+
usage=usage,
|
|
131
|
+
infer_name=infer_name,
|
|
132
|
+
toolsets=toolsets,
|
|
133
|
+
event_stream_handler=event_stream_handler,
|
|
134
|
+
**_deprecated_kwargs,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
self.dbos_wrapped_run_workflow = wrapped_run_workflow
|
|
138
|
+
|
|
139
|
+
# Wrap the `run_sync` method in a DBOS workflow
|
|
140
|
+
@DBOS.workflow(name=f'{self._name}.run_sync')
|
|
141
|
+
def wrapped_run_sync_workflow(
|
|
142
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
143
|
+
*,
|
|
144
|
+
output_type: OutputSpec[RunOutputDataT] | None = None,
|
|
145
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
146
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
147
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
148
|
+
deps: AgentDepsT,
|
|
149
|
+
model_settings: ModelSettings | None = None,
|
|
150
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
151
|
+
usage: _usage.RunUsage | None = None,
|
|
152
|
+
infer_name: bool = True,
|
|
153
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
154
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
155
|
+
**_deprecated_kwargs: Never,
|
|
156
|
+
) -> AgentRunResult[Any]:
|
|
157
|
+
with self._dbos_overrides():
|
|
158
|
+
return super(DBOSAgent, self).run_sync(
|
|
159
|
+
user_prompt,
|
|
160
|
+
output_type=output_type,
|
|
161
|
+
message_history=message_history,
|
|
162
|
+
deferred_tool_results=deferred_tool_results,
|
|
163
|
+
model=model,
|
|
164
|
+
deps=deps,
|
|
165
|
+
model_settings=model_settings,
|
|
166
|
+
usage_limits=usage_limits,
|
|
167
|
+
usage=usage,
|
|
168
|
+
infer_name=infer_name,
|
|
169
|
+
toolsets=toolsets,
|
|
170
|
+
event_stream_handler=event_stream_handler,
|
|
171
|
+
**_deprecated_kwargs,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
self.dbos_wrapped_run_sync_workflow = wrapped_run_sync_workflow
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def name(self) -> str | None:
|
|
178
|
+
return self._name
|
|
179
|
+
|
|
180
|
+
@name.setter
|
|
181
|
+
def name(self, value: str | None) -> None: # pragma: no cover
|
|
182
|
+
raise UserError(
|
|
183
|
+
'The agent name cannot be changed after creation. If you need to change the name, create a new agent.'
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
@property
|
|
187
|
+
def model(self) -> Model:
|
|
188
|
+
return self._model
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def event_stream_handler(self) -> EventStreamHandler[AgentDepsT] | None:
|
|
192
|
+
handler = self._event_stream_handler or super().event_stream_handler
|
|
193
|
+
if handler is None:
|
|
194
|
+
return None
|
|
195
|
+
elif DBOS.workflow_id is not None and DBOS.step_id is None:
|
|
196
|
+
# Special case if it's in a DBOS workflow but not a step, we need to iterate through all events and call the handler.
|
|
197
|
+
return self._call_event_stream_handler_in_workflow
|
|
198
|
+
else:
|
|
199
|
+
return handler
|
|
200
|
+
|
|
201
|
+
async def _call_event_stream_handler_in_workflow(
|
|
202
|
+
self, ctx: RunContext[AgentDepsT], stream: AsyncIterable[_messages.AgentStreamEvent]
|
|
203
|
+
) -> None:
|
|
204
|
+
handler = self._event_stream_handler or super().event_stream_handler
|
|
205
|
+
assert handler is not None
|
|
206
|
+
|
|
207
|
+
async def streamed_response(event: _messages.AgentStreamEvent):
|
|
208
|
+
yield event
|
|
209
|
+
|
|
210
|
+
async for event in stream:
|
|
211
|
+
await handler(ctx, streamed_response(event))
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def toolsets(self) -> Sequence[AbstractToolset[AgentDepsT]]:
|
|
215
|
+
with self._dbos_overrides():
|
|
216
|
+
return super().toolsets
|
|
217
|
+
|
|
218
|
+
@contextmanager
|
|
219
|
+
def _dbos_overrides(self) -> Iterator[None]:
|
|
220
|
+
# Override with DBOSModel and DBOSMCPServer in the toolsets.
|
|
221
|
+
with super().override(model=self._model, toolsets=self._toolsets, tools=[]):
|
|
222
|
+
yield
|
|
223
|
+
|
|
224
|
+
@overload
|
|
225
|
+
async def run(
|
|
226
|
+
self,
|
|
227
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
228
|
+
*,
|
|
229
|
+
output_type: None = None,
|
|
230
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
231
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
232
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
233
|
+
deps: AgentDepsT = None,
|
|
234
|
+
model_settings: ModelSettings | None = None,
|
|
235
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
236
|
+
usage: _usage.RunUsage | None = None,
|
|
237
|
+
infer_name: bool = True,
|
|
238
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
239
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
240
|
+
) -> AgentRunResult[OutputDataT]: ...
|
|
241
|
+
|
|
242
|
+
@overload
|
|
243
|
+
async def run(
|
|
244
|
+
self,
|
|
245
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
246
|
+
*,
|
|
247
|
+
output_type: OutputSpec[RunOutputDataT],
|
|
248
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
249
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
250
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
251
|
+
deps: AgentDepsT = None,
|
|
252
|
+
model_settings: ModelSettings | None = None,
|
|
253
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
254
|
+
usage: _usage.RunUsage | None = None,
|
|
255
|
+
infer_name: bool = True,
|
|
256
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
257
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
258
|
+
) -> AgentRunResult[RunOutputDataT]: ...
|
|
259
|
+
|
|
260
|
+
async def run(
|
|
261
|
+
self,
|
|
262
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
263
|
+
*,
|
|
264
|
+
output_type: OutputSpec[RunOutputDataT] | None = None,
|
|
265
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
266
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
267
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
268
|
+
deps: AgentDepsT = None,
|
|
269
|
+
model_settings: ModelSettings | None = None,
|
|
270
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
271
|
+
usage: _usage.RunUsage | None = None,
|
|
272
|
+
infer_name: bool = True,
|
|
273
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
274
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
275
|
+
**_deprecated_kwargs: Never,
|
|
276
|
+
) -> AgentRunResult[Any]:
|
|
277
|
+
"""Run the agent with a user prompt in async mode.
|
|
278
|
+
|
|
279
|
+
This method builds an internal agent graph (using system prompts, tools and result schemas) and then
|
|
280
|
+
runs the graph to completion. The result of the run is returned.
|
|
281
|
+
|
|
282
|
+
Example:
|
|
283
|
+
```python
|
|
284
|
+
from pydantic_ai import Agent
|
|
285
|
+
|
|
286
|
+
agent = Agent('openai:gpt-4o')
|
|
287
|
+
|
|
288
|
+
async def main():
|
|
289
|
+
agent_run = await agent.run('What is the capital of France?')
|
|
290
|
+
print(agent_run.output)
|
|
291
|
+
#> The capital of France is Paris.
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Args:
|
|
295
|
+
user_prompt: User input to start/continue the conversation.
|
|
296
|
+
output_type: Custom output type to use for this run, `output_type` may only be used if the agent has no
|
|
297
|
+
output validators since output validators would expect an argument that matches the agent's output type.
|
|
298
|
+
message_history: History of the conversation so far.
|
|
299
|
+
deferred_tool_results: Optional results for deferred tool calls in the message history.
|
|
300
|
+
model: Optional model to use for this run, required if `model` was not set when creating the agent.
|
|
301
|
+
deps: Optional dependencies to use for this run.
|
|
302
|
+
model_settings: Optional settings to use for this model's request.
|
|
303
|
+
usage_limits: Optional limits on model request count or token usage.
|
|
304
|
+
usage: Optional usage to start with, useful for resuming a conversation or agents used in tools.
|
|
305
|
+
infer_name: Whether to try to infer the agent name from the call frame if it's not set.
|
|
306
|
+
toolsets: Optional additional toolsets for this run.
|
|
307
|
+
event_stream_handler: Optional event stream handler to use for this run.
|
|
308
|
+
|
|
309
|
+
Returns:
|
|
310
|
+
The result of the run.
|
|
311
|
+
"""
|
|
312
|
+
return await self.dbos_wrapped_run_workflow(
|
|
313
|
+
user_prompt,
|
|
314
|
+
output_type=output_type,
|
|
315
|
+
message_history=message_history,
|
|
316
|
+
deferred_tool_results=deferred_tool_results,
|
|
317
|
+
model=model,
|
|
318
|
+
deps=deps,
|
|
319
|
+
model_settings=model_settings,
|
|
320
|
+
usage_limits=usage_limits,
|
|
321
|
+
usage=usage,
|
|
322
|
+
infer_name=infer_name,
|
|
323
|
+
toolsets=toolsets,
|
|
324
|
+
event_stream_handler=event_stream_handler,
|
|
325
|
+
**_deprecated_kwargs,
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
@overload
|
|
329
|
+
def run_sync(
|
|
330
|
+
self,
|
|
331
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
332
|
+
*,
|
|
333
|
+
output_type: None = None,
|
|
334
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
335
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
336
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
337
|
+
deps: AgentDepsT = None,
|
|
338
|
+
model_settings: ModelSettings | None = None,
|
|
339
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
340
|
+
usage: _usage.RunUsage | None = None,
|
|
341
|
+
infer_name: bool = True,
|
|
342
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
343
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
344
|
+
) -> AgentRunResult[OutputDataT]: ...
|
|
345
|
+
|
|
346
|
+
@overload
|
|
347
|
+
def run_sync(
|
|
348
|
+
self,
|
|
349
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
350
|
+
*,
|
|
351
|
+
output_type: OutputSpec[RunOutputDataT],
|
|
352
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
353
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
354
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
355
|
+
deps: AgentDepsT = None,
|
|
356
|
+
model_settings: ModelSettings | None = None,
|
|
357
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
358
|
+
usage: _usage.RunUsage | None = None,
|
|
359
|
+
infer_name: bool = True,
|
|
360
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
361
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
362
|
+
) -> AgentRunResult[RunOutputDataT]: ...
|
|
363
|
+
|
|
364
|
+
def run_sync(
|
|
365
|
+
self,
|
|
366
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
367
|
+
*,
|
|
368
|
+
output_type: OutputSpec[RunOutputDataT] | None = None,
|
|
369
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
370
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
371
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
372
|
+
deps: AgentDepsT = None,
|
|
373
|
+
model_settings: ModelSettings | None = None,
|
|
374
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
375
|
+
usage: _usage.RunUsage | None = None,
|
|
376
|
+
infer_name: bool = True,
|
|
377
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
378
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
379
|
+
**_deprecated_kwargs: Never,
|
|
380
|
+
) -> AgentRunResult[Any]:
|
|
381
|
+
"""Synchronously run the agent with a user prompt.
|
|
382
|
+
|
|
383
|
+
This is a convenience method that wraps [`self.run`][pydantic_ai.agent.AbstractAgent.run] with `loop.run_until_complete(...)`.
|
|
384
|
+
You therefore can't use this method inside async code or if there's an active event loop.
|
|
385
|
+
|
|
386
|
+
Example:
|
|
387
|
+
```python
|
|
388
|
+
from pydantic_ai import Agent
|
|
389
|
+
|
|
390
|
+
agent = Agent('openai:gpt-4o')
|
|
391
|
+
|
|
392
|
+
result_sync = agent.run_sync('What is the capital of Italy?')
|
|
393
|
+
print(result_sync.output)
|
|
394
|
+
#> The capital of Italy is Rome.
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
Args:
|
|
398
|
+
user_prompt: User input to start/continue the conversation.
|
|
399
|
+
output_type: Custom output type to use for this run, `output_type` may only be used if the agent has no
|
|
400
|
+
output validators since output validators would expect an argument that matches the agent's output type.
|
|
401
|
+
message_history: History of the conversation so far.
|
|
402
|
+
deferred_tool_results: Optional results for deferred tool calls in the message history.
|
|
403
|
+
model: Optional model to use for this run, required if `model` was not set when creating the agent.
|
|
404
|
+
deps: Optional dependencies to use for this run.
|
|
405
|
+
model_settings: Optional settings to use for this model's request.
|
|
406
|
+
usage_limits: Optional limits on model request count or token usage.
|
|
407
|
+
usage: Optional usage to start with, useful for resuming a conversation or agents used in tools.
|
|
408
|
+
infer_name: Whether to try to infer the agent name from the call frame if it's not set.
|
|
409
|
+
toolsets: Optional additional toolsets for this run.
|
|
410
|
+
event_stream_handler: Optional event stream handler to use for this run.
|
|
411
|
+
|
|
412
|
+
Returns:
|
|
413
|
+
The result of the run.
|
|
414
|
+
"""
|
|
415
|
+
return self.dbos_wrapped_run_sync_workflow(
|
|
416
|
+
user_prompt,
|
|
417
|
+
output_type=output_type,
|
|
418
|
+
message_history=message_history,
|
|
419
|
+
deferred_tool_results=deferred_tool_results,
|
|
420
|
+
model=model,
|
|
421
|
+
deps=deps,
|
|
422
|
+
model_settings=model_settings,
|
|
423
|
+
usage_limits=usage_limits,
|
|
424
|
+
usage=usage,
|
|
425
|
+
infer_name=infer_name,
|
|
426
|
+
toolsets=toolsets,
|
|
427
|
+
event_stream_handler=event_stream_handler,
|
|
428
|
+
**_deprecated_kwargs,
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
@overload
|
|
432
|
+
def run_stream(
|
|
433
|
+
self,
|
|
434
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
435
|
+
*,
|
|
436
|
+
output_type: None = None,
|
|
437
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
438
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
439
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
440
|
+
deps: AgentDepsT = None,
|
|
441
|
+
model_settings: ModelSettings | None = None,
|
|
442
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
443
|
+
usage: _usage.RunUsage | None = None,
|
|
444
|
+
infer_name: bool = True,
|
|
445
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
446
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
447
|
+
) -> AbstractAsyncContextManager[StreamedRunResult[AgentDepsT, OutputDataT]]: ...
|
|
448
|
+
|
|
449
|
+
@overload
|
|
450
|
+
def run_stream(
|
|
451
|
+
self,
|
|
452
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
453
|
+
*,
|
|
454
|
+
output_type: OutputSpec[RunOutputDataT],
|
|
455
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
456
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
457
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
458
|
+
deps: AgentDepsT = None,
|
|
459
|
+
model_settings: ModelSettings | None = None,
|
|
460
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
461
|
+
usage: _usage.RunUsage | None = None,
|
|
462
|
+
infer_name: bool = True,
|
|
463
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
464
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
465
|
+
) -> AbstractAsyncContextManager[StreamedRunResult[AgentDepsT, RunOutputDataT]]: ...
|
|
466
|
+
|
|
467
|
+
@asynccontextmanager
|
|
468
|
+
async def run_stream(
|
|
469
|
+
self,
|
|
470
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
471
|
+
*,
|
|
472
|
+
output_type: OutputSpec[RunOutputDataT] | None = None,
|
|
473
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
474
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
475
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
476
|
+
deps: AgentDepsT = None,
|
|
477
|
+
model_settings: ModelSettings | None = None,
|
|
478
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
479
|
+
usage: _usage.RunUsage | None = None,
|
|
480
|
+
infer_name: bool = True,
|
|
481
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
482
|
+
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
|
|
483
|
+
**_deprecated_kwargs: Never,
|
|
484
|
+
) -> AsyncIterator[StreamedRunResult[AgentDepsT, Any]]:
|
|
485
|
+
"""Run the agent with a user prompt in async mode, returning a streamed response.
|
|
486
|
+
|
|
487
|
+
Example:
|
|
488
|
+
```python
|
|
489
|
+
from pydantic_ai import Agent
|
|
490
|
+
|
|
491
|
+
agent = Agent('openai:gpt-4o')
|
|
492
|
+
|
|
493
|
+
async def main():
|
|
494
|
+
async with agent.run_stream('What is the capital of the UK?') as response:
|
|
495
|
+
print(await response.get_output())
|
|
496
|
+
#> The capital of the UK is London.
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
Args:
|
|
500
|
+
user_prompt: User input to start/continue the conversation.
|
|
501
|
+
output_type: Custom output type to use for this run, `output_type` may only be used if the agent has no
|
|
502
|
+
output validators since output validators would expect an argument that matches the agent's output type.
|
|
503
|
+
message_history: History of the conversation so far.
|
|
504
|
+
deferred_tool_results: Optional results for deferred tool calls in the message history.
|
|
505
|
+
model: Optional model to use for this run, required if `model` was not set when creating the agent.
|
|
506
|
+
deps: Optional dependencies to use for this run.
|
|
507
|
+
model_settings: Optional settings to use for this model's request.
|
|
508
|
+
usage_limits: Optional limits on model request count or token usage.
|
|
509
|
+
usage: Optional usage to start with, useful for resuming a conversation or agents used in tools.
|
|
510
|
+
infer_name: Whether to try to infer the agent name from the call frame if it's not set.
|
|
511
|
+
toolsets: Optional additional toolsets for this run.
|
|
512
|
+
event_stream_handler: Optional event stream handler to use for this run. It will receive all the events up until the final result is found, which you can then read or stream from inside the context manager.
|
|
513
|
+
|
|
514
|
+
Returns:
|
|
515
|
+
The result of the run.
|
|
516
|
+
"""
|
|
517
|
+
if DBOS.workflow_id is not None and DBOS.step_id is None:
|
|
518
|
+
raise UserError(
|
|
519
|
+
'`agent.run_stream()` cannot currently be used inside a DBOS workflow. '
|
|
520
|
+
'Set an `event_stream_handler` on the agent and use `agent.run()` instead. '
|
|
521
|
+
'Please file an issue if this is not sufficient for your use case.'
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
async with super().run_stream(
|
|
525
|
+
user_prompt,
|
|
526
|
+
output_type=output_type,
|
|
527
|
+
message_history=message_history,
|
|
528
|
+
deferred_tool_results=deferred_tool_results,
|
|
529
|
+
model=model,
|
|
530
|
+
deps=deps,
|
|
531
|
+
model_settings=model_settings,
|
|
532
|
+
usage_limits=usage_limits,
|
|
533
|
+
usage=usage,
|
|
534
|
+
infer_name=infer_name,
|
|
535
|
+
toolsets=toolsets,
|
|
536
|
+
event_stream_handler=event_stream_handler,
|
|
537
|
+
**_deprecated_kwargs,
|
|
538
|
+
) as result:
|
|
539
|
+
yield result
|
|
540
|
+
|
|
541
|
+
@overload
|
|
542
|
+
def iter(
|
|
543
|
+
self,
|
|
544
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
545
|
+
*,
|
|
546
|
+
output_type: None = None,
|
|
547
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
548
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
549
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
550
|
+
deps: AgentDepsT = None,
|
|
551
|
+
model_settings: ModelSettings | None = None,
|
|
552
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
553
|
+
usage: _usage.RunUsage | None = None,
|
|
554
|
+
infer_name: bool = True,
|
|
555
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
556
|
+
**_deprecated_kwargs: Never,
|
|
557
|
+
) -> AbstractAsyncContextManager[AgentRun[AgentDepsT, OutputDataT]]: ...
|
|
558
|
+
|
|
559
|
+
@overload
|
|
560
|
+
def iter(
|
|
561
|
+
self,
|
|
562
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
563
|
+
*,
|
|
564
|
+
output_type: OutputSpec[RunOutputDataT],
|
|
565
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
566
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
567
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
568
|
+
deps: AgentDepsT = None,
|
|
569
|
+
model_settings: ModelSettings | None = None,
|
|
570
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
571
|
+
usage: _usage.RunUsage | None = None,
|
|
572
|
+
infer_name: bool = True,
|
|
573
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
574
|
+
**_deprecated_kwargs: Never,
|
|
575
|
+
) -> AbstractAsyncContextManager[AgentRun[AgentDepsT, RunOutputDataT]]: ...
|
|
576
|
+
|
|
577
|
+
@asynccontextmanager
|
|
578
|
+
async def iter(
|
|
579
|
+
self,
|
|
580
|
+
user_prompt: str | Sequence[_messages.UserContent] | None = None,
|
|
581
|
+
*,
|
|
582
|
+
output_type: OutputSpec[RunOutputDataT] | None = None,
|
|
583
|
+
message_history: list[_messages.ModelMessage] | None = None,
|
|
584
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
585
|
+
model: models.Model | models.KnownModelName | str | None = None,
|
|
586
|
+
deps: AgentDepsT = None,
|
|
587
|
+
model_settings: ModelSettings | None = None,
|
|
588
|
+
usage_limits: _usage.UsageLimits | None = None,
|
|
589
|
+
usage: _usage.RunUsage | None = None,
|
|
590
|
+
infer_name: bool = True,
|
|
591
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
|
|
592
|
+
**_deprecated_kwargs: Never,
|
|
593
|
+
) -> AsyncIterator[AgentRun[AgentDepsT, Any]]:
|
|
594
|
+
"""A contextmanager which can be used to iterate over the agent graph's nodes as they are executed.
|
|
595
|
+
|
|
596
|
+
This method builds an internal agent graph (using system prompts, tools and output schemas) and then returns an
|
|
597
|
+
`AgentRun` object. The `AgentRun` can be used to async-iterate over the nodes of the graph as they are
|
|
598
|
+
executed. This is the API to use if you want to consume the outputs coming from each LLM model response, or the
|
|
599
|
+
stream of events coming from the execution of tools.
|
|
600
|
+
|
|
601
|
+
The `AgentRun` also provides methods to access the full message history, new messages, and usage statistics,
|
|
602
|
+
and the final result of the run once it has completed.
|
|
603
|
+
|
|
604
|
+
For more details, see the documentation of `AgentRun`.
|
|
605
|
+
|
|
606
|
+
Example:
|
|
607
|
+
```python
|
|
608
|
+
from pydantic_ai import Agent
|
|
609
|
+
|
|
610
|
+
agent = Agent('openai:gpt-4o')
|
|
611
|
+
|
|
612
|
+
async def main():
|
|
613
|
+
nodes = []
|
|
614
|
+
async with agent.iter('What is the capital of France?') as agent_run:
|
|
615
|
+
async for node in agent_run:
|
|
616
|
+
nodes.append(node)
|
|
617
|
+
print(nodes)
|
|
618
|
+
'''
|
|
619
|
+
[
|
|
620
|
+
UserPromptNode(
|
|
621
|
+
user_prompt='What is the capital of France?',
|
|
622
|
+
instructions=None,
|
|
623
|
+
instructions_functions=[],
|
|
624
|
+
system_prompts=(),
|
|
625
|
+
system_prompt_functions=[],
|
|
626
|
+
system_prompt_dynamic_functions={},
|
|
627
|
+
),
|
|
628
|
+
ModelRequestNode(
|
|
629
|
+
request=ModelRequest(
|
|
630
|
+
parts=[
|
|
631
|
+
UserPromptPart(
|
|
632
|
+
content='What is the capital of France?',
|
|
633
|
+
timestamp=datetime.datetime(...),
|
|
634
|
+
)
|
|
635
|
+
]
|
|
636
|
+
)
|
|
637
|
+
),
|
|
638
|
+
CallToolsNode(
|
|
639
|
+
model_response=ModelResponse(
|
|
640
|
+
parts=[TextPart(content='The capital of France is Paris.')],
|
|
641
|
+
usage=RequestUsage(input_tokens=56, output_tokens=7),
|
|
642
|
+
model_name='gpt-4o',
|
|
643
|
+
timestamp=datetime.datetime(...),
|
|
644
|
+
)
|
|
645
|
+
),
|
|
646
|
+
End(data=FinalResult(output='The capital of France is Paris.')),
|
|
647
|
+
]
|
|
648
|
+
'''
|
|
649
|
+
print(agent_run.result.output)
|
|
650
|
+
#> The capital of France is Paris.
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
Args:
|
|
654
|
+
user_prompt: User input to start/continue the conversation.
|
|
655
|
+
output_type: Custom output type to use for this run, `output_type` may only be used if the agent has no
|
|
656
|
+
output validators since output validators would expect an argument that matches the agent's output type.
|
|
657
|
+
message_history: History of the conversation so far.
|
|
658
|
+
deferred_tool_results: Optional results for deferred tool calls in the message history.
|
|
659
|
+
model: Optional model to use for this run, required if `model` was not set when creating the agent.
|
|
660
|
+
deps: Optional dependencies to use for this run.
|
|
661
|
+
model_settings: Optional settings to use for this model's request.
|
|
662
|
+
usage_limits: Optional limits on model request count or token usage.
|
|
663
|
+
usage: Optional usage to start with, useful for resuming a conversation or agents used in tools.
|
|
664
|
+
infer_name: Whether to try to infer the agent name from the call frame if it's not set.
|
|
665
|
+
toolsets: Optional additional toolsets for this run.
|
|
666
|
+
|
|
667
|
+
Returns:
|
|
668
|
+
The result of the run.
|
|
669
|
+
"""
|
|
670
|
+
if model is not None and not isinstance(model, DBOSModel):
|
|
671
|
+
raise UserError(
|
|
672
|
+
'Non-DBOS model cannot be set at agent run time inside a DBOS workflow, it must be set at agent creation time.'
|
|
673
|
+
)
|
|
674
|
+
|
|
675
|
+
with self._dbos_overrides():
|
|
676
|
+
async with super().iter(
|
|
677
|
+
user_prompt=user_prompt,
|
|
678
|
+
output_type=output_type,
|
|
679
|
+
message_history=message_history,
|
|
680
|
+
deferred_tool_results=deferred_tool_results,
|
|
681
|
+
model=model,
|
|
682
|
+
deps=deps,
|
|
683
|
+
model_settings=model_settings,
|
|
684
|
+
usage_limits=usage_limits,
|
|
685
|
+
usage=usage,
|
|
686
|
+
infer_name=infer_name,
|
|
687
|
+
toolsets=toolsets,
|
|
688
|
+
**_deprecated_kwargs,
|
|
689
|
+
) as run:
|
|
690
|
+
yield run
|
|
691
|
+
|
|
692
|
+
@contextmanager
|
|
693
|
+
def override(
|
|
694
|
+
self,
|
|
695
|
+
*,
|
|
696
|
+
deps: AgentDepsT | _utils.Unset = _utils.UNSET,
|
|
697
|
+
model: models.Model | models.KnownModelName | str | _utils.Unset = _utils.UNSET,
|
|
698
|
+
toolsets: Sequence[AbstractToolset[AgentDepsT]] | _utils.Unset = _utils.UNSET,
|
|
699
|
+
tools: Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]] | _utils.Unset = _utils.UNSET,
|
|
700
|
+
) -> Iterator[None]:
|
|
701
|
+
"""Context manager to temporarily override agent dependencies, model, toolsets, or tools.
|
|
702
|
+
|
|
703
|
+
This is particularly useful when testing.
|
|
704
|
+
You can find an example of this [here](../testing.md#overriding-model-via-pytest-fixtures).
|
|
705
|
+
|
|
706
|
+
Args:
|
|
707
|
+
deps: The dependencies to use instead of the dependencies passed to the agent run.
|
|
708
|
+
model: The model to use instead of the model passed to the agent run.
|
|
709
|
+
toolsets: The toolsets to use instead of the toolsets passed to the agent constructor and agent run.
|
|
710
|
+
tools: The tools to use instead of the tools registered with the agent.
|
|
711
|
+
"""
|
|
712
|
+
if _utils.is_set(model) and not isinstance(model, (DBOSModel)):
|
|
713
|
+
raise UserError(
|
|
714
|
+
'Non-DBOS model cannot be contextually overridden inside a DBOS workflow, it must be set at agent creation time.'
|
|
715
|
+
)
|
|
716
|
+
|
|
717
|
+
with super().override(deps=deps, model=model, toolsets=toolsets, tools=tools):
|
|
718
|
+
yield
|