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

On-Demand Capabilities | Pydantic Docs

https://pydantic.dev/docs/ai/capabilities/on-demand/

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

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

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

访问原网页

页面简介

On-demand capabilities, also called deferred capabilities, load like Agent Skills: the model sees a one-line catalog entry and pulls in instructions and tools only when needed, so you can hide or gate tools until a skill is loaded (progressive disclosure).

正文摘录

On-Demand Capabilities A capability is a bundle of instructions and/or tools, optionally with settings and hooks. A multi-workflow agent normally sends every workflow’s instructions and tool schemas on every turn, and applies every workflow’s settings and hooks for the whole run — even though most requests need just one workflow. That cost grows with each workflow you add: more input tokens, and worse tool selection once the visible tool set passes the ~30–50-tool mark where models start picking the wrong one (the same pressure behind tool search). Mark a capability with defer_loading=True and give it a stable id, and it becomes an on-demand capability, also called a deferred capability: it collapses to a one-line catalog entry — its id plus an optional description — that the model pulls in on demand. Its instructions and tools stay hidden until the model loads it, which gives you progressive disclosure of tools as well as instructions. (Deferred capabilities are unrelated to deferred tools, which pause individual tool calls for approval or external execution.) The minimal setup is: on_demand_capability.pyfrom pydantic_ai import Agent from pydantic_ai.capabilities import Capability refunds = Capability( id='refunds', description='Use for refund eligibility, refund status, or processing a refund.', instructions='Always confirm the order ID before issuing a refund.', defer_loading=True, ) @refunds.tool_plain def refund_status(order_id: str) -> str: """Look up the refund status for an order.""" return f'Order {order_id}: refund issued on 2026-05-01.' agent = Agent( 'openai-responses:gpt-6.1-sol', instructions='You are a customer support assistant.', capabilities=[refunds], ) On the first turn, the refund workflow is collapsed to a catalog entry. The model sees its base instructions, the framework-managed load_capability tool, and the catalog appended to the instructions: <pyai:context id="capability:deferred_capabilities"> The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded: - refunds: Use for refund eligibility, refund status, or processing a refund. </pyai:context> A later <pyai:context> element with the same id replaces the earlier one and stays in effect until replaced again. The catalog is tagged so that when it changes between runs of a conversation, for example because a capability was added, the change is appended instead of rewriting the cached prompt. The model does not receive the refund instructions or the refund_status tool definition yet, so it has no reason to call the tool. Depending on the active model, Pydantic AI may also send provider/tool-search plumbing to preserve the hidden state; that plumbing does not expose the refund tool definition until the capability is loaded. The exchange unfolds across model requests within a single agent.run_sync call: Request 1. The model sees the catalog above and the user’s prompt. It calls the load_capability tool with id='refunds'. Load. The tool result only confirms the load. Pydantic AI then states the capability’s instructions — “Always confirm the order ID before issuing a refund.” — right after it, in a system message, and exposes the refund_status definition on the next request. Request 2. The model now sees those instructions in history and refund_status in its tool list. It calls refund_status(order_id='ABC-123') and answers the user from the result. If the capability’s instructions change after it loads — a dynamic @refunds.instructions function returns something new, or the instructions in code are edited between runs of a conversation — the change is appended to message history as an update for the block capability:refunds, holding the capability’s complete instructions, or a diff against the text the model last received when that’s shorter. The earlier statement isn’t rewritten, so the cached prompt is kept. A capability whose instructions become empty, or that the agent no longer has, is withdrawn the same way. A before_model_request hook that leaves a loaded capability’s parts out of instruction_parts doesn’t affect it: the instructions are delivered as they resolved, changes included. To withdraw the block, keep its parts with empty content. Every loaded capability’s changes are tracked, whatever the on_change policy of its instructions: a loaded capability’s instructions are never in the prefix, so there is nothing to rewrite. An instruction function that returns something different on every request, such as the current time, appends an update to every request. Already-loaded capabilities stay loaded for the rest of the run — the model never needs to re-open one. A load_capability tool call for a capability that is already active is answered with a successful result confirming it is already active, and its instructions aren’t stated again; a call for one that an earlier call in the same response already loads is answered with a retry prompt. A call with an id that isn’t an on-demand capability is answered with a retry prompt listing the ids the model can load. Searching cannot reveal a capability-owned tool: it stays hidden until its capability loads. In runs that also have searchable deferred tools, the catalog explicitly steers the model to load the capability rather than search for its tools; in capability-only runs — where no search surface exists — the catalog omits any mention of searching. Loading activates the whole bundle, not just instructions: the capability’s function tools, model settings, and lifecycle hooks come live together (see What you can defer). It’s a one-line change to a capability you already register, it works on every provider, and it survives history replay. Skills on steroids: on-demand capabilities in Pydantic AI on the Pydantic blog walks through the pattern and its token savings. What you can defer Every part of a capability bundle activates together as a single unit: PartBefore loadAfter loadInstructions (static or dynamic)Not sentStated in a system message after the load_capability tool result; included in subsequent requestsFunction toolsNot exposedExposed on the next requestModel settings (static or per-step)Not appliedMerged into the run’s settings for subsequent requestsLifecycle hooksDo not fireFire after the capability is loadedNative toolsNot exposedExposed on the next request — see Cache implications When to use it Reach for on-demand capabilities when: the agent serves multiple distinct workflows (refunds, returns, fraud review, account security…) where most turns need one a workflow needs more than instructions — its own tools, raised reasoning effort, an approval hook — and those should travel together as a unit you want skills-style progressive disclosure but also want the loaded bundle to bring tools and settings, not just a runbook Skip it when: the capability is used on most turns — the discovery round-trip costs more than the tokens it saves you have a flat catalog of individually-discoverable tools with no shared instructions — use tool search instead, which discovers individual tools by name rather than loading bundles If you’ve used Anthropic’s Agent Skills, this is the same idea generalised: a skill is a markdown file the model can pull in on demand. An on-demand capability does that plus typed function tools, per-step model settings, and lifecycle hooks. Retrofitting an existing capability defer_loading=True is not specific to the Capability convenience class. The shared fields live on AbstractCapability, and built-in capabilities expose id, description, and defer_loading on construction. For custom capabilities, set those attributes on the instance. defer_existing_capability.pyfrom pydantic_ai import Agent from pydantic_ai.capabilities import MCP agent = Agent( 'openai-responses:gpt-6.1-sol', capabilities=[ MCP( url='https://mcp.example.com/analytics', native=True, id='analytics-mcp', description='Use for analytics queries, dashboards, and metric lookups.', defer_loading=True, ), ], ) Until the model loads analytics-mcp, none of the MCP server’s tool definitions enter the prompt. The same flag works on WebSearch, WebFetch, Hooks, and any custom AbstractCapability subclass — see Building custom capabilities for adding defer_loading to your own subclass. Deferring several capabilities as one To load existing capabilities together, wrap them in a CombinedCapability with its own id: defer_capability_group.pyfrom pydantic_ai import Agent from pydantic_ai.capabilities import CombinedCapability, WebFetch, WebSearch web_research = CombinedCapability( [WebSearch(), WebFetch()], id='web-research', description='Use when the question requires up-to-date information from the web.', defer_loading=True, ) agent = Agent('anthropic:claude-sonnet-5-5', capabilities=[web_research]) Loading web-research activates the tools, instructions, and hooks of both capabilities at once. Each capability keeps its own ordering position among the agent’s capabilities, as if it were passed to the agent directly. The capabilities inside the group can’t be deferred themselves: pass a capability to the agent separately if the model should load it on its own. Resumable across runs Loaded-capability and tool-availability state live in message history, not in the agent. When a conversation is persisted to a database and resumed later — possibly on a different process, machine, or model — Pydantic AI reconstructs the loaded capability IDs from each load’s record, and the revealed tool names from ToolAvailabilityDeltaPart. A load’s record is the model’s exchange, or else a delta: when the model loads a capability, its load_capability call and return are the record, as with tool search; a load from code, which has no exchange, records a CapabilityLoadDeltaPart instead. Capabilities the model loaded earlier stay loaded; capabilities it never loaded stay collapsed in the catalog. No re-discovery round-trip on resume. This is why deferred ca