翻篇收录说明
翻篇网页快照

Durable Execution with Temporal | Pydantic Docs

https://pydantic.dev/docs/ai/capabilities/durable_execution/temporal/

最近抓取:2026-12-03 06:34:02(北京时间)

最近内容变化:2026-12-03 06:34:02(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Make Pydantic AI agents durable with Temporal, running model requests and tool calls as activities so agents recover from crashes and resume long-running work.

正文摘录

Durable Execution with Temporal Temporal is a popular durable execution platform that’s natively supported by Pydantic AI. Durable Execution In Temporal’s durable execution implementation, a program that crashes or encounters an exception while interacting with a model or API will retry until it can successfully complete. Temporal relies primarily on a replay mechanism to recover from failures. As the program makes progress, Temporal saves key inputs and decisions, allowing a re-started program to pick up right where it left off. The key to making this work is to separate the application’s repeatable (deterministic) and non-repeatable (non-deterministic) parts: Deterministic pieces, termed workflows, execute the same way when re-run with the same inputs. Non-deterministic pieces, termed activities, can run arbitrary code, performing I/O and any other operations. Workflow code can run for extended periods and, if interrupted, resume exactly where it left off. Critically, workflow code generally cannot include any kind of I/O, over the network, disk, etc. Activity code faces no restrictions on I/O or external interactions, but if an activity fails part-way through it is restarted from the beginning. In the case of Pydantic AI agents, integration with Temporal means that model requests, tool calls that may require I/O, and MCP server communication all need to be offloaded to Temporal activities due to their I/O requirements, while the logic that coordinates them (i.e. the agent run) lives in the workflow. Code that handles a scheduled job or web request can then execute the workflow, which will in turn execute the activities as needed. The diagram below shows the overall architecture of an agentic application in Temporal. The Temporal Server is responsible for tracking program execution and making sure the associated state is preserved reliably (i.e., stored to an internal database, and possibly replicated across cloud regions). Temporal Server manages data in encrypted form, so all data processing occurs on the Worker, which runs the workflow and activities. +---------------------+ | Temporal Server | (Stores workflow state, +---------------------+ schedules activities, ^ persists progress) | Save state, | Schedule Tasks, progress, | load state on resume timeouts | | +------------------------------------------------------+ | Worker | | +----------------------------------------------+ | | | Workflow Code | | | | (Agent Run Loop) | | | +----------------------------------------------+ | | | | | | | v v v | | +-----------+ +------------+ +-------------+ | | | Activity | | Activity | | Activity | | | | (Tool) | | (MCP Tool) | | (Model API) | | | +-----------+ +------------+ +-------------+ | | | | | | +------------------------------------------------------+ | | | v v v [External APIs, services, databases, etc.] See the Temporal documentation for more information. Durable Agent To make a run durable, call agent.run() inside a Temporal workflow executed on a worker; outside one, the agent runs as a normal, non-durable agent. Add durable execution to any Agent by attaching the TemporalDurability capability. The agent stays a normal Agent everywhere — outside a workflow it behaves transparently, and inside a workflow the capability routes model requests, tool calls, and MCP server communication through Temporal activities. Here is a simple but complete example of attaching durable execution to an agent, creating a Temporal workflow with durable execution logic, connecting to a Temporal server, and running the workflow from non-durable code. All it requires is to install Pydantic AI with the temporal optional group: pip uv Terminalpip install pydantic-ai[temporal] Or if you’re using the slim package, you can install it with the temporal optional group: pip uv Terminalpip install pydantic-ai-slim[temporal] You’ll also need a Temporal server to be running locally: Terminalbrew install temporal temporal server start-dev temporal_durability.py import uuid from temporalio import workflow from temporalio.client import Client from temporalio.worker import Worker from pydantic_ai import Agent from pydantic_ai.durable_exec.temporal import ( PydanticAIPlugin, PydanticAIWorkflow, TemporalDurability, ) agent = Agent( 'openai:gpt-6.1-sol', instructions="You're an expert in geography.", name='geography', # (1) capabilities=[TemporalDurability()], # (2) ) @workflow.defn class GeographyWorkflow(PydanticAIWorkflow): # (3) __pydantic_ai_agents__ = [agent] # (4) @workflow.run async def run(self, prompt: str) -> str: result = await agent.run(prompt) # (5) return result.output async def main(): client = await Client.connect( # (6) 'localhost:7233', # (7) plugins=[PydanticAIPlugin()], # (8) ) async with Worker( # (9) client, task_queue='geography', workflows=[GeographyWorkflow], ): output = await client.execute_workflow( # (10) GeographyWorkflow.run, args=['What is the capital of Mexico?'], id=f'geography-{uuid.uuid4()}', task_queue='geography', ) print(output) #> Mexico City (Ciudad de México, CDMX) The agent's name is used to uniquely identify its activities. Attach durability via capabilities=[...]. The capability discovers the agent's name, model, and toolsets when bound to the agent, and registers an activity for each. Outside a workflow, the capability is transparent — the agent behaves as a normal Agent. The workflow represents a deterministic piece of code that can use non-deterministic activities for operations that require I/O. Subclassing PydanticAIWorkflow is optional but provides proper typing for the __pydantic_ai_agents__ class variable. List the agents used by this workflow. The PydanticAIPlugin automatically registers the activities and child workflows contributed by each agent's TemporalDurability capability with the worker. Alternatively, if modifying the worker initialization is easier than the workflow class, you can use AgentPlugin to register an agent's activities and child workflows directly on the worker. Use one of these plugin paths when any tool is configured with child_workflow; registering only TemporalDurability.temporal_activities is rejected because it would omit the required workflow definitions. A worker that only runs activities uses AgentPlugin(agent, register_workflows=False), as Child workflows describes. agent.run() works as usual; inside the workflow, model requests, tool calls, and MCP server communication are routed through Temporal activities. We connect to the Temporal server which keeps track of workflow and activity execution. This assumes the Temporal server is running locally. The PydanticAIPlugin tells Temporal to use Pydantic for serialization and deserialization, and automatically registers activities for agents listed in __pydantic_ai_agents__. Activity retry policies treat UserError, PydanticUserError, UnexpectedModelBehavior, UsageLimitExceeded, and SuspendedResponseExpired as non-retryable, along with Temporal's own over-limit-payload failure types, PayloadsTooLarge and (before temporalio 1.31) PayloadSizeError (see Large Payloads), and the workspace errors WorkspaceTimeoutError, WorkspaceOutputLimitError, WorkspaceReadOnlyError and WorkspaceUnavailableError. A subclass of one of these errors, like ContentFilterError or your own UserError subclass, isn't retried either: since a retry policy's non_retryable_error_types only matches exact class names, the activity marks such an error as non-retryable itself. A FallbackExceptionGroup, which a FallbackModel raises when all its models failed, is retried unless every error in it is non-retryable, counting the model activity's non_retryable_model_errors, the error types its retry policy's non_retryable_error_types names, and an UnsupportedSettingWarning raised for a fallback_on that names it: a chain whose models were all rate-limited or unavailable is retried on the retry policy's backoff, and one whose models all rejected the request isn't. A response a fallback_on response handler rejected, counted by ResponseRejected, is retryable, as another attempt can get a different response; a handler that rejects every response is retried until the retry policy's maximum_attempts or the activity's timeout stops it. The worker registers UserError, PydanticUserError, AgentRunError, FallbackExceptionGroup, UnsupportedEventLoopError, and WorkspaceError as workflow_failure_exception_types. We start the worker that will listen on the specified task queue and run workflows and activities. In a real world application, this might be run in a separate service. We call on the server to execute the workflow on a worker that's listening on the specified task queue. (To run this example, ensure asyncio is imported and add asyncio.run(main()); no other changes are needed.) Because the same agent works inside and outside a workflow, TemporalDurability composes with all other capabilities (instrumentation, SetToolMetadata, ProcessEventStream, etc.) without each needing a Temporal-specific wrapper variant. Workflow code has to use the async API: Agent.run_sync() drives the event loop itself, which Temporal’s workflow event loop doesn’t allow, so calling it inside a workflow raises a UserError telling you to await agent.run() instead. Outside a workflow, an agent with TemporalDurability behaves like a normal agent, so run_sync() works as usual. In a real world application, the agent, workflow, and worker are typically defined separately from the code that calls for a workflow to be executed. Because Temporal workflows need to be defined at the top level of the file and the agent is needed inside the workflow and when starting the worker (to register the activities), it needs to be defined at the top level of the file as well. For more information on how to use Temporal in Python applications, see their Python SDK guide. Wrapper-agent path (deprecated) Any agent can be wrapped in a TemporalAgent to get a durable agent variant that can be used inside a Temporal workflow.