Add request-scoped `SystemPromptPart(scope='request')` sent natively as Anthropic `clear_at` system messages

Merged
DO
2mo ago
+5902-105

SystemPromptPart(content, scope='request') is a system prompt for one model request: the model sees it for the request it's part of (and a continuation of that request), and not for any request after that. It stays in the message history like any other part.

[!WARNING]
Compatibility impact: Content a before_model_request hook enqueues with ctx.enqueue(...) (default priority='asap'), of any kind, now goes into the request being prepared instead of the next one. The model sees it one request earlier, and in the message history the enqueued ModelRequest comes before that request's response instead of after it. Enqueues from tools, after_model_request and outside the run, and content enqueued while resuming a suspended response, keep their timing.

Why this can ship in a minor release: 'asap' is documented as "at the earliest opportunity (next model request)", and from before_model_request that's the request being prepared; the later delivery came from the drain capability running ahead of the other hooks, an ordering the docs didn't promise.

Migration: To deliver in the following request as before, enqueue from after_model_request instead.

That's the shape Anthropic's turn-scoped system messages need. On Claude Opus 5.5, Sonnet 5.5 and Fable 5.1, a reminder injected into one request and deleted from the next is a history edit that invalidates every earlier thinking block (preserved thinking). That's what Harness SystemReminders and Planning do today, and it silently drops all earlier reasoning in every run where a reminder fires. A clear_at: 'next_user_message' entry left in place doesn't, and costs no tokens once cleared.

Design

API. A field on SystemPromptPart, scope: Literal['conversation', 'request'] = 'conversation', not a new part type: every model adapter, UI adapter and serializer already handles SystemPromptPart. The name is open (see questions). System voice only for now.

Rendering, per model, at projection (Model.prepare_messages plus the adapters' message mapping, so each FallbackModel candidate renders its own):

ModelCurrent requestLater requests
New profile flag supports_request_scoped_system_prompts (Anthropic models with mid-conversation system messages: Fable 5/5.1, Mythos 5, Opus 4.8/5/5.5, Sonnet 5.5; narrowed off on Foundry along with the system role){'role': 'system', 'clear_at': 'next_user_message'} entry after the request's other system entry; mid-conversation-system-clear-at-2026-08-21 beta added automaticallySent unchanged; the API clears it
Everything elseMoved to the end of its request; renders like any other mid-conversation SystemPromptPart (native inline system/developer message where supports_inline_system_prompts, else <system>-tagged user text)Left out

"Current request" is the trailing run of ModelRequests after the last response, plus any trailing ModelResponses continuing it (a suspended pause_turn being resumed). That matches what the agent sends as one request after _clean_message_history merges adjacent requests.

Opting out of the beta (e.g. an account without access): set the profile flag to False; the part then falls back to being sent only while current. No new setting.

Cache breakpoints. Automatic placement anchors on the last block the next request will still send:

  • Anthropic: anthropic_cache_messages and the Bedrock/Vertex per-block fallback skip a clear_at entry (cache_control on one is a 400) and trailing request-scoped text. With anthropic_cache on a model without native support, the server would put its breakpoint on the reminder, writing an entry the next request can't read, so an explicit breakpoint goes on the block before it. A leading CachePoint never attaches to a clear_at entry either.
  • bedrock_cache_messages and openrouter_cache_messages: the cache point goes before the trailing reminder.
  • Non-native adapters find the reminder through a count prepare_messages stamps in the prepared request's __pydantic_ai__ metadata (request_scoped_tail). It survives _clean_message_history's merge and the Temporal boundary, since prepared messages are what the model activity receives.

This replaces the leading CachePoint the Harness adds by hand, which is the source of the GPT-5.6 Chat crash #9582 fixes.

Orphans. A step that gives up without a response drops its request-scoped parts from history: the run raised or was cancelled before a response (ModelRequestNode.run/stream), or a capability asked for a retry without one (_build_retry_node). Otherwise they'd carry into the next step's request next to the parts it adds for itself. Never between attempts: FallbackModel attempts, and #9348's RetryModelRequest attempts, are still the same step, which test_fallback_attempts_keep_the_request_scoped_prompt pins. A stream that fails after it opened commits its partial response, which answers the request, so its reminder stays. The 400 the API returns for a request-scoped entry followed directly by a user message can't happen on our wire: adjacent requests are merged, and Anthropic's existing slide moves a system entry past user turns to just before the reply.

Enqueue. ctx.enqueue(SystemPromptPart(..., scope='request')) works with no new parameter; delivery timing (priority) and lifetime (scope) stay separate. Called from before_model_request, it lands in the request being prepared and in history, so a reminder capability needs one call (see Decisions, 7). Not from inside a Temporal activity, which enqueue already refuses.

Durable execution. scope serializes through ModelMessagesTypeAdapter like any field. History records exactly what each request was built from; a Temporal replay test runs a workflow that adds a reminder every request and replays it.

UI adapters. dump_messages leaves request-scoped parts out (Decisions, 8), so a history round-tripped through a frontend loses them. Documented, with "keep the history server-side" as the remedy.

OTel: not in this PR. The chat span's input messages include cleared copies on Anthropic. Leaving them out depends on a message's position relative to the end of history, which the per-message JSON cache in _instrumentation.py keys by message, so it needs cache invalidation work. Marking the current one would add a non-semconv attribute. Tracked in a follow-up issue, #10505.

How this fits #7053 and #9348

  • #7053 (request-only request_context.messages, now merged into this branch). Core never relies on the deprecated append. The documented pattern, and the one the tests and the Harness rewrite use, is ctx.messages.append(reminder) plus request_context.messages = [*request_context.messages, reminder], which is #7053's own migration message and works before and after it. Under its hook order a wrap_model_request that raises before calling its handler skips before_model_request, so no reminder was added and there's nothing to drop; the tests fail the step after the reminder is added instead (from a later before_model_request, and from the model with on_model_request_error turning it into a retry). The orphan drop replaces messages in the history list rather than mutating them, since instrumentation caches each message's serialized form.
  • #9348 (per-attempt prepare_model_request). Rendering lives in Model.prepare_messages and the adapters, which #9348 runs once per attempt with the candidate's own profile; nothing is rendered before the attempt loop.
  • Orphans vs retries. Dropping happens only once a step has given up, never between attempts. The seams are ModelRequestNode.run/stream giving up and _build_retry_node, which #9348 keeps; _commit_interrupted_response commits a response, so it needs nothing.
  • Compaction. test_current_reminder_survives_compaction runs a reminder capability ahead of a compaction capability that rewrites ctx.messages and the request together, and the reminder stays in the request it compacts to.
  • #9580. No interaction: model errors don't touch the part.

vs #6343 and #8188

  • #6343 (add_ephemeral_part, request-only) is the design this replaces. Request-only injection is a history edit on models with preserved thinking, and the native fix only works if the client keeps the message. #6343's other job, anchoring the breakpoint for capabilities, is covered here for every request-scoped part. I'd close it.
  • #8188 (on_change='append' instruction deltas) is lasting state: appended once on change, rendered for the rest of the conversation. Request-scoped parts are nudges re-sent each request for recency. They compose: Planning could keep plan state as an instruction delta and add a request-scoped "current step" nudge.

Live evidence

uv run --env-file .env, real APIs, a three-call weather tool loop with a reminder added every request:

anthropic:claude-opus-5-5   thinking + drop_block, anthropic_cache_messages
  in=3652 read=0    write=3632 | in=3967 read=3632 | in=4036 read=3948 | in=4105 read=4017   input_transformations: none
anthropic:claude-sonnet-5-5 same                   | in=3967 read=3632 | in=4056 read=3948 | in=4125 read=4037   none
anthropic:claude-fable-5-1  same                   | in=4030 read=3632 | in=4099 read=4011 | in=4168 read=4080   none
anthropic:claude-haiku-4-5  cache_messages: in=5466 read=0 | 5660 read=5446 | 5733 read=5631 | 5806 read=5704   0 empty responses
anthropic:claude-haiku-4-5  anthropic_cache: in=5466 read=5446 | 5682 read=5446 | 5755 read=5653 | 5828 read=5726
openai-chat:gpt-5.6         in=4725 read=0 | 4760 read=4707 | 4797 read=4742 | 4832 read=4779
openai-responses:gpt-5.6    in=4644 read=0 | 4814 read=4626 | 4852 read=4796 | 4888 read=4834

No input_transformations (no thinking block dropped) and no AnthropicStaleThinkingBlockWarning on the three preserved-thinking models; each cache read covers the previous request bar the reminder. The research behind this (same probe with today's per-request-copy shape) reported thinking_dropped prefix_binding_mismatch for every earlier thinking block on Opus 5.5 and Sonnet 5.5.

Shapes probed directly: clear_at entry followed by a user message is a 400 (role 'system' must precede an 'assistant' message); cache_control on one is a 400; a lasting entry and a request-scoped entry are accepted in either order. claude-sonnet-5 accepts, clears (0 tokens once superseded) and follows both plain and request-scoped entries, though the docs list it as unsupported (see questions).

Recorded as cassettes: the three preserved-thinking models, Haiku 4.5 with each cache mode, and GPT-5.6 Chat and Responses.

Tests

tests/models/test_request_scoped_system_prompts.py (22 tests) and tests/durable_exec/temporal/test_request_scoped_prompts.py fail on main, where scope doesn't exist. Mutations they catch, each verified by applying it:

  • no clear_at rendering; no beta header; provider flag off; Foundry not narrowed;
  • breakpoint allowed on a clear_at entry; on trailing reminder text; no explicit anchor under anthropic_cache; Bedrock and OpenRouter anchoring on the reminder;
  • superseded parts not dropped; current parts not moved to the tail; _standing_system_prompt_count hoisting a leading request-scoped part;
  • no orphan drop when the step raises (run and run_stream) or retries without a response.

The cassette tests carry moves_cache_prefix: the Anthropic one because anthropic_cache_messages moves its breakpoint each request (the test checks the wire is append-only with breakpoints stripped); the others because leaving a finished reminder out is the design.

Decisions

  1. Name: scope='request' (default 'conversation'), kept a Literal so more values can be added later. Renamed from 'turn': Pydantic AI's unit is the model request, and "turn" is left for Anthropic's own pause_turn / clear_at semantics. "Request-scoped" (a part in history the model is shown for its own request) is distinct from "request-only" (assigning request_context.messages, which never reaches history); the docs say so where both come up.
  2. No request-scoped UserPromptPart: the field is on SystemPromptPart only.
  3. Sonnet 5: stays out of the native list, following Anthropic's docs (which now also list Mythos 5.1 and Haiku 5.5, both already covered by the inline-system prefixes).
  4. Beta opt-out: the profile flag only, no setting.
  5. Server-side conversation state: with openai_previous_response_id or openai_conversation_id, OpenAI Responses sends only the messages after the last response and the server replays everything it was sent before (_resolve_server_side_state trims the request to them), so a request-scoped prompt sent once stays visible on later requests. Documented, no warning.
  6. OTel: follow-up, tracked in #10505.
  7. One-call path: ctx.enqueue(SystemPromptPart(..., scope='request')) from before_model_request now lands in the request being prepared and in history. The graph delivers 'asap' content once more after the before_model_request chain (the drain capability runs ahead of the other hooks, so it used to wait for the next request). Docs, the skill reference and the tests use it as the pattern; writing to ctx.messages and request_context.messages yourself still works. Enqueues from tools, after_model_request and outside the run keep their timing. #7014 (tool-body enqueues into the same ModelRequest as the ToolReturnPart) is separate: it's about which history message tool-time content lands in, not when.
  8. UI dump paths: the Vercel AI and AG-UI adapters leave request-scoped parts out of dump_messages. They're for the model's current request only, and with manage_system_prompt='client' a dumped one would load back as a lasting SystemPromptPart, sent with every later request.
  9. Resuming a suspended response: content a before_model_request hook enqueues while the run resumes a provider-suspended turn (Anthropic pause_turn) waits for the next request, since the resume request has to end with the suspended response. If the continuation finishes the run, that pending reminder makes the end-of-run drain open one more model request, as 'asap' content enqueued during a final step already does.

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 (no public API changed, so no waiver).
  • PR title is fit for the release changelog.

🤖 Generated with Claude Code