Add `RunContext.load_capability` to load on-demand capabilities from code

Merged
AD
1mo ago
+6880-128

Today only the model can load an on-demand capability (defer_loading=True), by calling the load_capability tool. But often your code knows first which capability applies, for example a tool that has just classified the request.

This PR adds ctx.load_capability(...) so your code can load it directly, wherever a model request follows: from a tool or tool hook, from a before_run or before_model_request capability hook, or from after_model_request on a response with tool calls:

@agent.tool
def open_ticket(ctx: RunContext[Ticket]) -> str:
    if ctx.deps.category == 'refund':
        ctx.load_capability('refunds')  # id or capability instance
    return 'Ticket opened.'

On the model request that follows (the next one from a tool or after_model_request, the one being prepared from before_model_request, the run's first from before_run), refunds behaves exactly as if the model had loaded it: its instructions are stated, its tools are visible, and its settings and hooks apply.

Docs: "Loading a capability from code" in docs/capabilities/on-demand.md.

Started by @adtyavrdhn; reworked by @DouweM per the 10-26 design comment. Aditya's API, scope rules, durable-execution rules and tests are kept. What changed is how a load is recorded; see "What changed in the rework" below.

Closes #10089.

How it works

A load is recorded in message history, without a load_capability call. A code load appends a new part, CapabilityLoadDeltaPart, to the request after the tool results. It names the capability in loaded and the tool call that loaded it in tool_call_id. If the capability has tools, the same ToolAvailabilityDeltaPart reveal that a model's load leaves after its return follows it:

CapabilityLoadDeltaPart(loaded=['refunds'], tool_call_id='open')
ToolAvailabilityDeltaPart(tools_added=['refund_status'], tool_call_id='open')

What's loaded is read from each load's record: the model's exchange, or else a delta. A model's load is recorded by its load_capability call and return, as with tool search, and writes no delta (unchanged from main); a load from code, which has no exchange, writes this part. Because the load lives in history, it survives resuming a conversation and durable replay. The capability's instructions are then stated as the InstructionDeltaPart(id='capability:refunds') from #11103, in the system voice, as after a model load. The model never sees the CapabilityLoadDeltaPart itself: prepare_messages drops it, so no wire bytes change.

When you call it, it checks that a model request follows (a tool call, before_run, before_model_request, or after_model_request on a response with tool calls), and queues the records. Nothing reaches history yet. If the capability is already loaded or already queued, it does nothing and returns False; otherwise it returns True. It's a plain method, so sync tools can call it too.

On the next model request (for a load from a tool, or from before_run), the queued records are appended to that request, after the tool results, before the request is prepared. So that request already includes the capability: its tools, instructions, model settings, native tools and hooks. The records are also emitted as a CapabilityLoadDeltaEvent and a ToolAvailabilityDeltaEvent after the request's hooks run, so UI clients that rebuild history from the stream keep them in the same place. If the run ends at this step instead (final output, or a tool waiting for approval), the queued load is dropped. A load never triggers a model request by itself.

your tool calls ctx.load_capability('refunds')
  └─ checks, queues CapabilityLoadDeltaPart (+ ToolAvailabilityDeltaPart)   toolsets/_deferred_capability_loader.py, _enqueue.py
next model request
  ├─ records appended to the tool-results request                                  _agent_graph.py (_deliver_capability_loads)
  ├─ history re-read → refunds is loaded                                           _deferred_capabilities.py (LoadExchanges.loads)
  └─ request built with refunds' tools, instructions and settings
run ends at this step instead → queued load dropped

Several loads before the same request each get their own records, in the order they were made.

Good to know

  • It works wherever a model request follows: in a tool call (tool function or tool hook such as after_tool_execute), and in before_run or before_model_request. A load from before_model_request is recorded on the request being prepared, right after the hooks and before its loaded capabilities' instructions are resolved, so that request has the capability's tools and instructions; its model settings, native tools and hooks were resolved before the hook ran, so they apply from the next request. A load from before_run is recorded on the first request; before_run runs before any step has resolved its tools, so that step adds the tool reveal once it has. From after_model_request, it works on a response that calls a tool that isn't an output tool (or one the run doesn't know, which it answers with a retry): the run executes the calls and sends their results, and the load is recorded after them. If that step ends the run anyway (a call needs approval or is deferred, or an output tool ends it first), the load is discarded, as for a load from a tool; if the response loads the same capability itself, the call returns False. Where no request follows (after_model_request on a response without such calls, after_node_run, after_run), from output tools, and in realtime sessions, it raises UserError. The permission to load is scoped to the run that opened it, so a run nested in one of these hooks follows its own rules.
  • Under Temporal and Prefect, tool functions run in a separate activity or task whose result is replayed, so a load there would be lost; it raises instead. Load from a tool hook, which runs in the workflow. DBOS plain function tools can load; a function the user marks @DBOS.step can't be detected, and the docs warn against loading from one. The records have no random parts (their tool_call_id comes from the model response), so a replayed hook records the same parts.
  • If the run stops for an approval, a load from another tool in that step is dropped, and resuming doesn't rerun that tool. A load from the approved tool, or from an after_tool_execute hook as it runs for that tool, works after the resume.
  • If a tool both ctx.enqueue()s content and loads a capability, the content goes right after the tool's result, ahead of the load's records, both in history and in the event stream (#7043).
  • A tool that loads and then raises ModelRetry keeps the load.
  • If the model loads the same capability in the same response, your call returns False and the model's call decides.
  • Loading a non-deferred member of a deferred group that isn't loaded yet raises UserError, pointing to the group, like the model's load_capability does.
  • Like any load, a load from code ends at a compaction. Pydantic AI Harness's compaction strategies record the model's loads again after what they removed (#11394), but not yet a load from code; that's a follow-up (see "Decisions").

Design choices

  • Whenever a model request follows: the load rides along with that request. Loading after a final answer would force an extra model turn, which in testing discarded final answers and broke run_stream, so it raises there. For after_model_request, the graph decides from the response's tool calls, the same ones CallToolsNode executes.
  • One capability per call: it matches the model's load_capability tool and keeps the bool return. A loop costs no extra turns. A batch load_capabilities() would only add all-or-nothing validation, and can be added later without breaking anything.
  • On RunContext, not the capability: a load changes the run, like ctx.enqueue().
  • Sync, not async: nothing in it awaits; it only validates and appends to the thread-safe pending-message queue, like ctx.enqueue().

Nothing changes for existing users' code. Model loads write exactly what they did before, and existing histories load the same capabilities.

What changed in the rework

Aditya's version wrote a synthesized load_capability call and its return into history, the exchange the model's tool call would have written. Three things moved since it was opened (see the 10-26 comment):

  1. #11103 merged: a model load now returns a fixed confirmation, and the capability's instructions go in a system-voice InstructionDeltaPart, not in the tool result.
  2. #11274 proposes on-demand capabilities that only code activates. When every on-demand capability in a run is like that, there is no load_capability tool, and Anthropic rejects a call to a tool the request doesn't declare.
  3. #11264 / #11394: compaction has to record loads again after the summary.

So a load from code no longer writes a call. It writes the records described above:

  • CapabilityLoadDeltaPart(loaded: list[str], tool_call_id: str | None), part_kind='capability-load-delta', a new ModelRequestPart, plus CapabilityLoadDeltaEvent (event_kind='capability_load_delta') in HandleResponseEvent. It's a delta over the loaded set: additions only for now, and an unloaded counterpart can join later without a rename.
  • LoadExchanges.loads() counts it alongside the call/return pairs. LoadExchanges.observe() keeps its call/return-only contract, which the harness compaction helper relies on.
  • prepare_messages drops it (it's in _UnpreparedPart, so every adapter's exhaustive branch covers it); MCP sampling and both realtime protocols skip it.
  • OTel renders it as Loaded capabilities changed: +refunds, in the system role like a tool reveal.
  • Both UI adapters carry it: AG-UI as a pydantic_ai_capability_load_delta activity message, Vercel AI as a data-capability-load-delta data part ({'loaded': [...], 'tool_call_id': ...}), streamed and dumped, and rebuilt on load. A malformed or empty payload is dropped.
  • The harness token estimator, conversation search and is_load_part treat it as load bookkeeping.
  • Durable round-trip coverage includes the part and event.
  • The _capability_load_request bookkeeping in ModelRequestNode is gone, and so is the sha256-derived synthetic call id.

Release note

RunContext.load_capability records a load as the new CapabilityLoadDeltaPart. Pydantic AI versions without that part can't load a message history that contains one: validation of the whole history fails on its unknown part_kind. Histories with no load from code are unaffected; a model's load is recorded as before.

API-compat waivers for the two union changes (ModelRequestPart, HandleResponseEvent) are in .github/api-compatibility-allowlist.json.

Decisions (by @DouweM)

  • Record shape: a new part type, CapabilityLoadDeltaPart(loaded, tool_call_id), not a field on ToolAvailabilityDeltaPart. Serialized ToolAvailabilityDeltaParts are unchanged. For capabilities, "loaded" is what load_capability does and "available" is reserved for catalog listing.
  • Sync API: RunContext.load_capability is a plain def.
  • tool_call_id on a code load's record is the tool call that ran ctx.load_capability(), for provenance and so UIs can attach it to that tool's output; it's None for a load from before_run or before_model_request.
  • The model's exchange, or else a delta. A model's load is recorded by its call/return exchange (and the tool reveal), as on main and as with tool search, and writes no delta; only a load from code writes the part. So histories without a load from code stay readable by older versions.
  • Harness compaction (step 3 of the comment) isn't in this PR: re-recording loads after a compaction as this part is a separate follow-up. Until then, a harness compaction drops a load from code; the docs say so.
  • No-tool test: the request without a load_capability tool is produced by a before_model_request hook that removes it from function_tools. A prepare_tools hook can't remove it: the loader adds the tool outside that hook. The unlisted mode from #11274 will make this a real configuration.

Verification

  • Unit and integration tests in tests/test_capability_deferred_loading.py, including a sync tool's load, plus Temporal, DBOS, Prefect, Harness BackgroundTools and realtime tests.
  • tests/test_history_append_only.py: case deferred:loaded_from_code, a tool loads a capability with ctx.load_capability, over all providers.
  • Recorded against Anthropic (claude-haiku-4-5, thinking enabled), test_anthropic_load_capability_from_code[with-load-tool|without-load-tool]. The cassettes still replay with the new part, so the wire bytes are unchanged: the request after the load has no load_capability call, only the refund_status reveal and the capability's instructions as system text. In the without-load-tool case the request declares no load_capability tool at all.
  • UI round trips (Vercel AI and AG-UI) of the part, a Vercel AI client-rebuilt stream after a load from code, an AG-UI stream matching its dumped activity message, and payload hygiene.
  • Serialization: the part round-trips under its own part_kind, and a ToolAvailabilityDeltaPart serializes as on main.
  • Aditya's earlier live runs on gpt-5-mini (Responses and Chat Completions), claude-sonnet-4-6 and gemini-3-flash-preview exercised the synthesized-call version; they weren't repeated for the rework.

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
  • PR title is fit for the release changelog.

🤖 Generated with Claude Code