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

Azure Durable Task | Pydantic Docs

https://pydantic.dev/docs/ai/harness/azure-durable-task/

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

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

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

访问原网页

页面简介

Make a Pydantic AI agent durable with Azure Durable Task Scheduler: model requests and tool calls run as activities, so an orchestration resumes after a worker restart.

正文摘录

Azure Durable Task AzureDurableTaskDurability lets agents survive worker restarts with Durable Task and Azure Durable Task Scheduler. You write the orchestrator; model requests, tool calls and durable capability operations run as activities, and completed results come from orchestration history when the orchestrator replays. Outside an orchestration, the agent runs normally. Streamed model responses are buffered inside the activity, not streamed to the client. Azure Durable Functions also uses Durable Task, but this capability does not register orchestrators or activities with Azure Functions. 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: Azure Durable Task: replay completed activities after a worker restart accDescr: In the initial orchestration run, a model request and tool call run as activities whose results are stored in Azure Durable Task Scheduler orchestration history, and the worker restarts during the next model request before its result is recorded. The scheduler replays the orchestrator: AzureDurableTaskDurability returns completed activity results from history without re-running them, then schedules the next model request as an activity. subgraph run1["Orchestration, initial run"] done["model request, tool call<br/>run as activities"] restart["next model request<br/>worker restarts before<br/>result is recorded"]:::blocked end history[("Azure Durable Task Scheduler<br/>orchestration history")]:::external subgraph replay["Orchestrator replay"] dur["AzureDurableTaskDurability()<br/>replays completed activities<br/>and schedules new ones"]:::capability live["next model request<br/>runs as an activity"] end done -.-x restart done -->|"activity results"| history restart -.->|"scheduler replays<br/>orchestrator"| dur history -->|"completed results,<br/>not re-run"| dur dur --> 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[azure-durable-task]" "pydantic-ai-slim[openai]" Run locally Start the Durable Task Scheduler emulator: Terminaldocker run --rm --name dts-emulator -p 127.0.0.1:8080:8080 -p 127.0.0.1:8082:8082 mcr.microsoft.com/dts/dts-emulator:v0.0.9 The emulator uses task hub default; its dashboard is at http://localhost:8082. With the emulator running and OPENAI_API_KEY set: from collections.abc import Generator from durabletask import task from durabletask.client import TaskHubGrpcClient from durabletask.worker import TaskHubGrpcWorker from pydantic_ai import Agent from pydantic_ai_harness.azure_durable_task import AzureDurableTaskDurability, run_durable agent = Agent('openai:gpt-6.1-sol', name='support', capabilities=[AzureDurableTaskDurability()]) def support(ctx: task.OrchestrationContext, prompt: str) -> Generator[task.Task[object], object, str]: result = yield from run_durable(ctx, lambda: agent.run(prompt)) return result.output worker = TaskHubGrpcWorker( host_address='localhost:8080', metadata=[('taskhub', 'default')], secure_channel=False ) worker.add_orchestrator(support) durability = AzureDurableTaskDurability.from_agent(agent) assert durability is not None with durability.register(worker), worker, TaskHubGrpcClient( host_address='localhost:8080', metadata=[('taskhub', 'default')], secure_channel=False ) as client: worker.start() instance_id = client.schedule_new_orchestration(support, input='Explain durable execution.') state = client.wait_for_orchestration_completion(instance_id, timeout=60) assert state is not None state.raise_if_failed() print(state.get_output()) Call yield from run_durable(ctx, lambda: agent.run(...)) wherever the agent belongs in your orchestrator. Agent binds a copy of its capabilities, so get the bound one with from_agent. Enter its register(worker) before starting the worker and leave it after the worker stops; it registers the agent’s activities and runs them. Register orchestrators and use clients with the SDK as usual. Clients can run in other processes and don’t need the agent. The orchestrator returns JSON-compatible output. For a Pydantic output model, return result.output.model_dump(mode='json'). Deploy to Azure Durable Task Scheduler Swap the emulator worker and client for the Azure-managed ones; the orchestrator and register(worker) stay the same. The azure-durable-task extra installs them and azure-identity: from azure.identity import DefaultAzureCredential from durabletask.azuremanaged.client import DurableTaskSchedulerClient from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker credential = DefaultAzureCredential() endpoint = '<scheduler>.<region>.durabletask.io' worker = DurableTaskSchedulerWorker(host_address=endpoint, taskhub='<hub>', token_credential=credential) client = DurableTaskSchedulerClient(host_address=endpoint, taskhub='<hub>', token_credential=credential) Grant the worker’s identity the Durable Task Data Contributor role on the scheduler or task hub. Use the same taskhub on workers and clients, and a separate hub per environment. Replay and side effects Every time an activity finishes, the SDK runs your orchestrator again from the start and replays completed results from history. This shapes how you write agents for it: Activities run at least once. A worker can fail after a tool’s side effect but before its result is recorded. Make tools and event handlers idempotent; ctx.run_id and ctx.tool_call_id make good idempotency keys. Orchestrator-side code runs on every replay. Hooks, instruction functions, output validators and inline tools must be deterministic and do no network, file or thread I/O. Put I/O in tools or a capability’s @durable_operation method. Names are persisted. Activity names come from the agent’s name, toolset IDs and tool names. Don’t rename them while orchestrations that use them are still running. Token counts are activities. With count_tokens_before_request=True, the token count before each model request runs as an activity. Rejected responses reach the handler in an activity. With an event_stream_handler, each ModelResponseRejectedEvent is delivered to it in an activity. Drain running orchestrations before upgrading. A release can change which operations run as activities, which breaks replay for orchestrations already in flight. Replay cost grows with run length. Each replay re-runs the agent up to its latest step, so orchestrator CPU grows with the square of the number of model and tool steps. Keep very long conversations in separate orchestrations. Instrumented runs repeat spans. Pydantic AI spans created in orchestrator code are emitted again on every replay, so one run shows its agent run and model request spans several times. Activity errors change type. An exception raised in a model request or tool reaches the orchestrator as durabletask.task.TaskFailedError. UserError keeps its type. Activities on a worker share one event loop. A blocking call in an async tool or event handler stalls every other activity on that worker. Dependencies Dependencies must be JSON-serializable: dataclasses, Pydantic models and JSON values. Activities rebuild them from the agent’s deps_type. Create clients and connections inside the tool or @durable_operation that uses them. from collections.abc import Generator from dataclasses import dataclass from durabletask import task from pydantic_ai import Agent, RunContext from pydantic_ai_harness.azure_durable_task import AzureDurableTaskDurability, run_durable @dataclass class Dependencies: tenant: str agent = Agent( 'openai:gpt-6.1-sol', name='tenant_support', deps_type=Dependencies, capabilities=[AzureDurableTaskDurability()], ) @agent.tool def tenant(ctx: RunContext[Dependencies]) -> str: return ctx.deps.tenant def support( ctx: task.OrchestrationContext, payload: dict[str, str] ) -> Generator[task.Task[object], object, str]: result = yield from run_durable( ctx, lambda: agent.run(payload['prompt'], deps=Dependencies(tenant=payload['tenant'])) ) return result.output Inside activities, live run fields such as ctx.messages and ctx.prompt are unavailable and raise UserError, and tools cannot emit run events. Tool arguments Function tool arguments are serialized to JSON when crossing into an activity, then validated again against the tool’s schema (which validates by alias). If a field serializes under a key that validation does not accept, a required field fails validation and an optional field is dropped or takes its default. Two cases need explicit configuration: Aliased TypedDict or standard-library dataclass (outside a Pydantic model or dataclass): these serialize by Python attribute name, while the activity validates by alias. Enable validate_by_name=True on the type (the same decorator works on standard-library dataclasses): from typing import Annotated from pydantic import ConfigDict, Field, with_config from typing_extensions import TypedDict @with_config(ConfigDict(validate_by_name=True)) class Venue(TypedDict): room: Annotated[str, Field(alias='roomName')] Asymmetric serialization aliases: a field with serialization_alias, a differing validation_alias, a serialization-only alias_generator, or validate_by_alias=False serializes under a key validation ignores. Keep validate_by_alias enabled and add the serialization alias to validation_alias with AliasChoices, alongside the names the field already validates by: from pydantic import AliasChoices, BaseModel, Field class Room(BaseModel): room: str = Field(serialization_alias='roomOut', validation_alias=AliasChoices('room', 'roomOut')) floor: int = Field(validation_alias=AliasChoices('floorIn', 'floorOut'), serialization_alias='floorOut') Approvals and deferred calls Approvals belong to your orchestrator. Include D