页面简介
Let a Pydantic AI agent run pick up where it left off after a crash, using pgtask, a task queue that keeps its state in Postgres.
正文摘录
pgtask Durability PGTaskDurability lets an agent run survive a crash. It works with pgtask, a task queue that keeps its state in Postgres. Run the agent inside a pgtask task, and each model request and tool call is saved to Postgres when it finishes. If the worker crashes, pgtask runs the task again, and the agent gets the saved results back instead of calling the model or the tool a second time, so you don’t pay twice for finished work. Outside a pgtask task nothing is saved and the agent runs as usual, except that tool calls still follow parallel_execution_mode, which runs them one at a time by default (see Running tools at the same time). Source While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy. flowchart TB accTitle: pgtask Durability: pick up a crashed run where it left off accDescr: In attempt 1, the worker finishes a model request and a tool call, and each is saved to Postgres as a pgtask step. The worker then crashes during the next model request, before that step is saved. pgtask runs the task again: the PGTaskDurability capability returns the stored results of the saved steps with no model or tool call, and then the next model request runs live. subgraph first["Worker, attempt 1"] done["model request, tool call<br/>each one finishes"] crash["next model request<br/>worker crashes before<br/>the step is saved"]:::blocked end steps[("Postgres<br/>pgtask steps")]:::external subgraph retry["Task run again"] replay["PGTaskDurability()<br/>returns stored results,<br/>no model or tool call"]:::capability live["next model request<br/>runs live"] end done -.-x crash done -->|"each saved as a step"| steps crash -.->|"pgtask runs<br/>the task again"| replay steps -->|"saved steps"| replay replay --> live classDef capability stroke:#E520E9,stroke-width:2px classDef external stroke:#0E9C86,stroke-width:2px classDef blocked stroke:#E5533D,stroke-width:2px,stroke-dasharray:4 3 Installation pip uv Terminalpip install "pydantic-ai-harness[pgtask]" "pydantic-ai-slim[openai]" pgtask keeps its state in tables in your database. Create them once per database: from pgtask import Client client = await Client.connect('postgresql://localhost/agents') await client.migrate() Quick start Give the agent a name and write a pgtask task that runs it. Then add tasks to the queue, and run a worker to process them: from pgtask import Client, Task, TaskRegistry, Worker from pydantic_ai import Agent from pydantic_ai_harness.pgtask import PGTaskDurability tasks = TaskRegistry(queue_name='agents') agent = Agent('openai:gpt-6.1-sol', name='analyst', capabilities=[PGTaskDurability()]) @tasks.task('analyse') async def analyse(task: Task, payload: dict[str, str]) -> dict[str, str]: result = await agent.run(payload['prompt']) return {'output': result.output} # Add a task to the queue. client = await Client.connect('postgresql://localhost/agents') await client.enqueue(analyse.request({'prompt': 'Summarize the Q3 report.'})) # Run tasks, usually in a separate process. await Worker('postgresql://localhost/agents', tasks).run() What happens after a crash pgtask saves each finished piece of work as a step: a name and a result. When a worker crashes, pgtask runs your task function again from the start. Ordinary code in the function runs again, but when the agent reaches a model request or tool call that already has a saved step, it uses the saved result and skips the call. A tool that raises ModelRetry or ToolFailed, or a sub-agent run inside a tool that cancels itself or times out (RunCancelled), has that outcome saved too, so after a crash the model gets the same error and the tool doesn’t run again. A tool that raises any other exception has nothing saved, so it runs again when pgtask retries the task. An MCP server is only connected when a call needs it. If every call to it already has a saved result, the server isn’t contacted. Step names Each step is named after the agent’s name and the toolset’s id. These are the names you see in Postgres, and the reason not to rename an agent or toolset while its tasks are still running. Step nameWhat it saves{name}__model.requesta model request{name}__model.request_streama streamed model request{name}__model.request.retry_after, {name}__model.request_stream.retry_after, {name}__model.compact_messages.retry_after, {name}__model.cancel_suspended_response.retry_afterthe wait a model error’s retry_after asked for, before that model operation runs again{name}__model.compact_messagesa request asking the model to shorten the message history{name}__model.count_tokensa token count ahead of a model request, with count_tokens_before_request{name}__model.cancel_suspended_responsecancelling a response the model provider is still working on in the background{name}__sleepa wait before checking again on a response the model provider is still working on, such as a batch{name}__capability__{capability_id}.{operation}work added by another capability{name}__function_toolset__{id}.validate_argschecking a tool’s arguments with its args_validator{name}__function_toolset__{id}.call_tool:{tool}a function tool call{name}__dynamic_toolset__{id}.get_toolsbuilding the tools of a DynamicToolset{name}__dynamic_toolset__{id}.call_tool:{tool}a DynamicToolset tool call{name}__mcp_server__{id}.get_toolsfetching an MCP server’s tool list{name}__mcp_server__{id}.get_instructionsfetching an MCP server’s instructions{name}__mcp_server__{id}.call_toolan MCP tool call{name}__event_stream_handlerone event passed to event_stream_handler A run that uses a model other than the agent’s default adds the model’s id to the end: {name}__model.request.{model_id}. Characters pgtask doesn’t allow in step names become _. For example, tools added with @agent.tool are saved under the toolset id _agent_. When the same step name comes up more than once in a task, such as the same tool called twice or agent.run() called twice, pgtask numbers them 0, 1, 2, and so on, in the order they happen. Finish one agent.run() before starting the next in the same task, so the numbers come out the same after a crash. A run started without run_id= gets a default built from the task ID, the agent’s name, and how many runs that agent has started in the task so far, and its default conversation_id follows from it, so after a crash each run gets the IDs it had before. Runs are numbered in the order they start, like steps, so pass run_id= to runs of one agent that start at the same time. A run started inside a step, such as a sub-agent called from a tool, gets a random ID, because the saved step is used instead of running it again. An async function tool with durable=False gets no step: it runs in the task on every attempt, so keep it deterministic and free of I/O. A DynamicToolset built with per_run_step=False is resolved once per run and held for its steps. Its factory, and the for_run of the toolset it returns (for an MCPToolset, its auth or headers function), run in the task outside any step on every attempt, so keep them deterministic and leave their I/O to the steps. Rules The agent needs a name, or pass name= to PGTaskDurability. Every function, MCP, and dynamic toolset needs its own id. Agent(...) raises a UserError if either is missing. Don’t rename an agent or toolset while tasks that use it are still running. Their steps are saved under the old names, so after a crash the renamed calls run again. Tool results are saved as JSON, so tools must return values that can be converted to JSON. A result that can’t be fails the task, and pgtask retries it until max_attempts runs out. If a saved result no longer matches the type the call returns, the run fails with CheckpointDecodeError instead of running the tool again. A result is saved only after the call finishes. If the worker crashes after a tool has done something but before its result is saved, the tool runs again. Write tools and event_stream_handler so that running them twice does no harm. Inside a task, passing function, MCP, or dynamic toolsets to a single run with run(toolsets=...) raises a UserError. Add them to the agent instead. ExternalToolset is fine, and so is a FunctionToolset whose tools are all async and set durable=False. Streaming inside a task isn’t live: the whole model response is received and saved first, and then its events are sent to you. The waits between checks of a background response or a BatchModelRequests batch are pgtask sleeps: the task is suspended until a wait is over, so no worker holds it while a batch is processed. When pgtask wakes the task, its run passes the waits it already did straight away. A model request that fails with a model error that has a retry_after (read from a provider’s Retry-After header, for example) is saved as a failed attempt. The task then sleeps that long with pgtask’s durable sleep_for (the {name}__model.request.retry_after step), which suspends it until then, and the request runs again as the next occurrence of its step. The task’s retry_delay is set where its handler is registered and isn’t available to the run, so the wait is capped at a minute. Each model request waits at most as many times as the task has attempts left after the current one; after that, the model error fails the attempt and pgtask’s own retry applies. The suspension leaves agent.run as pgtask’s own signal, so an on_model_request_error hook that handles every exception has to re-raise it. Running tools at the same time By default the agent runs tool calls one at a time, inside a task or not. To run the tool calls from one model response at the same time, pass parallel_execution_mode='parallel_ordered_events'. Their events are sent in the order the model asked for the calls, once all of them finish. Plain 'parallel' isn’t supported, because the step numbers have to come out the same after a crash. Keep the default if a