Let `@agent.system_prompt(dynamic=True)` append its changes with `on_change='append'` to keep the cached prompt

Merged
DO
1mo ago
+1026-41

@agent.system_prompt(dynamic=True) re-runs its function for each later run of a conversation, and rewrites its SystemPromptPart in the history in place. That changes the start of every later request, so the provider can't reuse the conversation's cached prompt. The append-only property test carries this as a KNOWN failure.

This adds an opt-in on_change='append', using the names and values of the instruction decorators (#8188, #10788, #10789):

@agent.system_prompt(on_change='append')
def user_name(ctx: RunContext[str]) -> str:
    return f"The user's name is {ctx.deps}."
  • on_change='append' makes the prompt dynamic, whatever dynamic says. The signature is unchanged (dynamic: bool = False).
  • The first value stays where it is. A changed value is appended as a new SystemPromptPart at the start of the run that saw it. An unchanged value adds nothing, and None or '' withdraws the prompt.
  • The model gets the same replacement semantics and wording as instruction deltas:
    • Each statement is sent as a <context id="system_prompt:<name>"> element. #8188's supersession sentence is sent once per request, after the last element opened with the first ones: after the appending instruction blocks when the prefix has any, otherwise after the system prompt elements.
    • Later statements are sent as replacement elements, or as the withdrawal element. On models without inline system prompts, the withdrawal element uses the variant that says it stays in effect, <system>-tagged.
    • The rendering reuses messages.py's _context_element, _SUPERSESSION_SENTENCE and the withdrawal text, which is now shared with InstructionDeltaPart.render. No new wording.
  • The id comes from the function's __name__, or name=, which has no effect without on_change='append'. It must be unique among the agent's appending system prompts and can't contain :. It's never the dynamic_ref qualname, and the docs say the model sees it. History still ties the prompt to the function's __qualname__ (dynamic_ref), with or without name=, so renaming or moving the function disconnects it: the old part keeps its last value and the renamed function isn't sent. The docs and the name docstring say so.
  • History stores only the content, plus the new SystemPromptPart.context_id. Model.prepare_messages renders the elements, so an agent that continues the history without the function sends the parts the same way.
  • Realtime sessions warn and rewrite in place, as they do for appending instructions.
  • The function still runs once per run, as before.

Docs: docs/agent.md now explains what the default rewrite costs in caching, points most users to @agent.instructions(name=..., on_change='append'), and adds an "Appending system prompt changes" section. The agent skill is updated too. The default doesn't change: flipping it to 'append' is tracked with #10520 for V3.

Tests:

  • tests/test_history_append_only.py: the default scenario moves from KNOWN to ALLOWED, citing the docs. New agent:dynamic_system_prompt_append and agent:dynamic_system_prompt_withdrawal scenarios must stay append-only on all 3 providers. Both fail if append mode rewrites in place, which I checked by mutating the code.
  • tests/test_dynamic_system_prompt_changes.py: snapshots of history and of what the model is sent, covering changes, withdrawal with both inline variants, the supersession sentence with appending instructions and system prompts both present, a first value that starts empty, name=, an agent that inherits the history after a JSON round trip, ReinjectSystemPrompt (both the missing-prompt case and replace_existing=True), and argument validation.
  • tests/realtime/test_session.py: the realtime warning.

Note: every serialized SystemPromptPart now includes "context_id": null, as it did when scope was added. Older versions loading new history ignore the field and send the content without the <context> element.

Measured (live, 2026-10-28)

On the latest frontier models with inline system messages (Claude Opus 5.5, GPT-6.1 Sol), and on every production model without them (Gemini 4 Argon, Gemini 3.8 Flash, Claude Sonnet 5.5 on Bedrock, Grok 4.7), the model followed a change, a withdrawal, and a change whose supersession sentence comes only from the instruction prefix in 5 of 5 runs each. On models without inline system messages, appended statements take #11506's <system> path: the standing announcement, plus escaping of <system> in user text. Claude Haiku 5.5 inline is the weak spot: 9 of 15 runs on the prefix case. Full table: https://github.com/pydantic/pydantic-ai/pull/11445#discussion_r4395701209

Checklist

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

šŸ¤– Generated with Claude Code