页面简介
Make a Pydantic AI agent run durable on Absurd, a Postgres-based durable-execution engine -- model requests, MCP calls, and function tool calls are checkpointed into steps so a crashed worker resumes mid-run.
正文摘录
Absurd Durability AbsurdDurability makes an agent run durable on Absurd, a Postgres-based durable-execution engine. Run the agent inside an Absurd task handler and every model request, MCP call, and function tool call is checkpointed as a step, so a worker that crashes mid-run resumes from the last completed step instead of re-spending tokens on finished work. Outside a task the capability is transparent. 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: Absurd Durability: resume a crashed run from its last saved step accDescr: On a worker's first attempt, a model request and a tool call each finish, and each is saved to Postgres as an Absurd step. The worker crashes before the next model request's step is saved, so Absurd retries the task. On the retried task, AbsurdDurability returns stored results from the saved steps with no model or tool call, 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/>Absurd steps")]:::external subgraph retry["Task retried"] replay["AbsurdDurability()<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 -.->|"Absurd retries<br/>the task"| 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[absurd]" "pydantic-ai-slim[openai]" Absurd stores its state in Postgres. Install the Absurd schema once per database (see the Absurd repository), then create a queue: from absurd_sdk import AsyncAbsurd absurd = AsyncAbsurd('postgresql://localhost/absurd', queue_name='agents') await absurd.create_queue() Quick start Give the agent a name, register a task handler that runs it, then spawn tasks from a producer and execute them in a worker: from absurd_sdk import AsyncAbsurd, AsyncTaskContext, JsonValue from pydantic_ai import Agent from pydantic_ai_harness.absurd import AbsurdDurability absurd = AsyncAbsurd('postgresql://localhost/absurd', queue_name='agents') agent = Agent('openai:gpt-6.1-sol', name='analyst', capabilities=[AbsurdDurability()]) @absurd.register_task(name='analyse') async def analyse(params: JsonValue, ctx: AsyncTaskContext) -> JsonValue: assert isinstance(params, dict) result = await agent.run(params['prompt']) return {'output': result.output} # Producer: enqueue a task. await absurd.spawn('analyse', {'prompt': 'Summarize the Q3 report.'}) # Worker: claim and run tasks (in its own process). await absurd.start_worker() The handler must be async: a synchronous TaskContext raises a UserError. What gets checkpointed After a crash, Absurd re-runs the task handler from the top. Plain Python in the handler runs again, but each completed step returns its stored result instead of re-issuing the model request or tool call. Step names are built from the agent’s name and each toolset’s id: Step nameOperation{name}__model.requestone model request segment{name}__model.request_streamone streamed model request segment{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_messagesone model message-compaction operation{name}__model.count_tokensone token count ahead of a model request, with count_tokens_before_request{name}__model.cancel_suspended_responsetearing down a suspended response{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}an operation contributed by another capability{name}__function_toolset__{id}.validate_argsrunning a function tool’s args_validator{name}__function_toolset__{id}.call_tool:{tool}a function tool call{name}__mcp_server__{id}.get_toolslisting an MCP server’s tools{name}__mcp_server__{id}.get_instructionsan MCP server’s instructions{name}__mcp_server__{id}.call_toolan MCP tool call{name}__event_stream_handlerone event delivered to an event_stream_handler A model other than the agent’s default adds its id to the step name ({name}__model.request.{model_id}). A step name that recurs, such as a second agent.run() in the same task or the same tool called twice, gets an encounter-order suffix (#2, #3, …). Await one run before starting the next in the same task. 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. A retried task therefore gives each run the IDs it had before the crash. Runs are numbered in the order they start, so pass run_id= to runs of one agent that start concurrently. A run started inside a step, such as a sub-agent called from a tool, gets a random ID: the step’s result is replayed without running it again. An async function tool with durable=False gets no step: it runs in the task handler on every attempt, so keep it deterministic and free of I/O. These are not checkpointed and run again on replay: a tool call that raises ModelRetry, ToolFailed, CallDeferred, or ApprovalRequired; a tool call whose ToolReturn.content holds items that aren’t UserContent; tools from a DynamicToolset. Upgrading Pydantic AI to a version in which stateless OpenAICompaction emits compaction events adds two {name}__event_stream_handler steps, one per event, to a run in which it compacts, so tasks already in flight that compact this way and have an event_stream_handler resume with a different step sequence: let them finish on the previous version before upgrading. Runs without an event_stream_handler, or that don’t use OpenAICompaction(stateless=True), are unaffected by that. With ModelFallback, or a hook of your own that raises RetryModelRequest, stateless OpenAICompaction now compacts in each request attempt, for the model serving it. Every attempt that reaches compaction emits a compaction start event, even when its candidate isn’t an OpenAIResponsesModel and declines to compact; only an OpenAIResponsesModel candidate makes the compaction call. When an attempt fails, its compaction is discarded and a later OpenAIResponsesModel candidate compacts again. Stateless OpenAICompaction also makes a run retry a request that exceeds the model’s context window, even without ModelFallback: the request is compacted and sent again, which is one more compaction call and one more model request. A task already in flight that used stateless OpenAICompaction and hits either case can therefore resume with extra steps; let it finish on the previous version before upgrading. Without ModelFallback, a hook that raises RetryModelRequest, or an overflow, a step makes one attempt and compacts once, as before. Constraints The agent needs a name (or pass name= to AbsurdDurability), and every function, MCP, or dynamic toolset needs a unique id; Agent(...) raises a UserError otherwise. Don’t rename either once deployed: in-flight tasks re-run the steps whose names changed. A checkpointed tool’s return value is stored as JSON, so it must be JSON-serializable. A step is checkpointed after it runs, so a crash between a tool’s side effect and its checkpoint re-runs the tool. Keep side effects in tools and in an event_stream_handler idempotent. Function, MCP, or dynamic toolsets passed per run with run(toolsets=...) inside a task raise a UserError; register them on the agent instead. ExternalToolset is allowed, and so is a FunctionToolset whose tools are all async and set durable=False. Streaming inside a task is not live: the model stream is consumed inside the step, then its final response is replayed to the caller, one event per part. The waits between checks of a background response or a BatchModelRequests batch are Absurd sleeps: the task is suspended until a wait is over, so no worker holds it while a batch is processed. When Absurd 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 checkpointed as a failed attempt. The task then sleeps that long with Absurd’s durable sleep_for (the {name}__model.request.retry_after step), which suspends it until then without using one of its attempts, and the request runs again as the next occurrence of its step. The wait is capped at the delay the task’s RetryStrategy would wait before its next attempt, or at a minute, whichever is longer. 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 run and Absurd’s own retry applies. The suspension leaves agent.run as Absurd’s SuspendTask, so an on_model_request_error hook that handles every exception has to re-raise it. Parallel execution Tool calls run sequentially by default. Pass parallel_execution_mode='parallel_ordered_events' to run them concurrently; plain 'parallel' is not supported. Stay sequential if a capability hook such as before_tool_execute or wrap_tool_execute awaits before the tool runs, as that can reorder concurrent calls of the same tool on replay. Code Mode AbsurdDurability composes with Code Mode: each tool call made from run_code is its own step, served from its checkpoint on replay, while the run_code body itself re-runs. Migrating from pydantic-ai-absurd Imp