Add `anthropic_previous_message_id` setting for Anthropic message threads

Merged
HA
16d ago
+2739-159

Draft for discussion: the issue has no maintainer reply yet, so the three design choices below are provisional and I'm happy to change any of them.

Why

Anthropic's message threads beta lets each request send only the new messages, which keeps time to first token low in long agent loops.

New public surface

  • AnthropicModelSettings.anthropic_previous_message_id: Literal['auto'] (unset by default), matching OpenAIResponsesModelSettings.openai_previous_response_id
  • AnthropicModel(history_digest_key=...): optional, makes the digest and the fingerprint HMACs, like OpenAIResponsesModel(history_digest_key=...)
  • AnthropicModelProfile.anthropic_supports_message_threads: bool: on for the AsyncAnthropic and Foundry clients, off for the Bedrock, Bedrock Mantle and Vertex AI clients unless the provider's profile sets it, like anthropic_supports_inference_geo

Behavior

With anthropic_previous_message_id='auto', a request continues the thread of the most recent response in the message history and sends only the messages after it, without system and tools. Otherwise it creates a thread with the full history. A new thread is created when the instructions, tools, betas or another fixed field change (including a new message that needs a beta the thread was created without, like the Files API's), when the latest response or the history before it was edited, after a refusal or a response from another model (a FallbackModel's, or one a server-side fallback model wrote, which Anthropic doesn't store in the thread), and when the new messages open with a CachePoint, which marks the end of the previous response that a continue request can't send again. thread_not_found, thread_already_continued and thread_continue_in_flight replay the full history, and the replayed response records provider_details['thread_replayed']; thread_unsupported_request sends the request without a thread, with a warning, and records provider_details['thread_unsupported'] beside the fingerprint, so later requests with the same fixed fields skip the thread. A continue from a replayed response that gets thread_not_found again is handled the same way, as Anthropic may be unable to store that conversation, which is what the SDK helper's continue_unthreaded does. An extra_body that sets messages is sent without a thread too, as it replaces the history the thread is built from. On Bedrock and Vertex AI, where Anthropic doesn't offer threads, anthropic_previous_message_id is ignored with a UserWarning. A turn paused with pause_turn is resumed in a full-history create. Resuming it with a continue and no messages, as the thread docs describe, is #13262. With history from a client, the docs and THREAT_MODEL.md say to set history_digest_key or leave threads off: the keyed digest covers the response ID and the fingerprint, so a client can't continue another conversation's thread, or its own under other instructions or tools.

Provisional choices (the issue's open questions):

  1. Thread state is two values on each response: a fingerprint of the fixed fields in provider_details['thread_fingerprint'], and history_digest over the response's ID, the fingerprint, its parts and the history before it, the same field OpenAIResponsesModel uses. The digest helpers moved from openai.py to models/_history_digest.py, unchanged, so both models share them.
  2. thread is sent through extra_body, so no anthropic>=2.2.0 bump.
  3. Decided: anthropic_previous_message_id: Literal['auto'], the shape of openai_previous_response_id. A concrete message ID may come later; a continue without the thread's earlier turns can't be replayed, so it's left out for now.

Verification

  • test_create_then_continue_live: create then continue through Agent, plain and streamed, recorded against the live API on claude-fable-5-2. The continue request sends only the new prompt and the previous response's ID, without system or tools, and the API answers it.
  • test_create_then_continue_live_through_the_gateway: the same, recorded through Pydantic AI Gateway (gateway_provider('anthropic')), which forwards the threads beta and serves the continue request.
  • tests/models/anthropic/test_message_threads.py: create then continue (plain and streamed), continue inside a tool-call loop, replay for each error (plain and streamed), new thread after changed instructions, skills, a new beta (an UploadedFile follow-up), edited history, a refusal or another model's response, or a response with a fallback_message iteration (plain and streamed), a pause_turn resume sent in a full-history create with nothing lost, a new thread after an interrupted response, thinking, tools, container skills and whether fallbacks is sent fixed for the thread when extra_body sets them (a kept tools override isn't sent on continue), a new MCP authorization_token continuing the thread while a new server URL creates one (servers from MCPServerTool or extra_body), no thread when extra_body sets messages, replay and the send without a thread when a retrying transport gave up on the thread error, no thread on a compact_messages request (and may_use_thread turning a compaction request down), unsupported request sent without a thread, with a warning, and the next request with the same fixed fields sent without one straight away, the same after a second thread_not_found right after a replay (plain and streamed), edited or redacted latest response (plain and streamed), a system prompt added in the new messages sent on continue, a CachePoint opening the new messages, cache breakpoints recorded for the request as sent (plain and streamed), history_digest_key keying the digest and the fingerprint, a forged digest, a swapped response ID or a copied fingerprint creating a thread when it's set, application metadata (including non-JSON values) left out of the digest, threads sent on the Claude API and Foundry clients and ignored with a warning on the Bedrock, Bedrock Mantle and Vertex AI clients, a provider profile's anthropic_supports_message_threads winning over the client default (plain and streamed), a history stored as JSON and loaded back continuing the thread while one edited after loading creates one, off by default.
  • Apart from the live test, these use a mock transport: expiry errors can't be triggered on demand. Not covered: the 4 cache_control breakpoint limit with the anthropic_cache_* settings, and a stream stopped early.

What changes for existing users

Nothing: the setting is off by default.

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.

Summary by cubic

Adds AnthropicModelSettings.anthropic_previous_message_id (off by default) so long conversations continue in Anthropic message threads, sending only new messages per request to keep time to first token low. Existing behavior is unchanged. Closes #12257.

Thread behavior

  • A request continues the thread of the most recent response, sending only the messages after it and omitting system and tools, which the thread retains.
  • Starts a new thread when a thread-fixed field changes (instructions, tools, thinking, container skills, betas, or the same via extra_body), when the history or latest response was edited or redacted, after a refusal or another model's response, or when the new messages open with a CachePoint.
  • An extra_body override of messages is sent without a thread; whether fallbacks is sent is fixed for the thread, and a kept system or tools override is left unsent on continue.
  • Replays the full history in a new thread on thread_not_found, thread_already_continued, and thread_continue_in_flight; a replayed response records thread_replayed: True.
  • Sends without a thread after thread_unsupported_request, or when a continue from a replayed response gets thread_not_found again; stamps the response thread_unsupported: True beside thread_fingerprint, warns on the first rejection, and skips the failed create on the next request with the same fingerprint.
  • A thread continue downloads its new messages' files twice (#13804); this is documented.
  • The provider profile flag anthropic_supports_message_threads turns the setting off with a warning on Bedrock and Vertex AI, where Anthropic doesn't offer threads.

Digest and verification

  • Records thread_fingerprint and a history_digest over the response's parts and history; AnthropicModel takes an optional history_digest_key that HMACs the digest and fingerprint, with the digest helpers shared with the OpenAI models. Each request records its cache breakpoints on the model-request span.
  • Tests use a mock transport plus live cassettes for create-then-continue, standalone and through the Pydantic AI Gateway (plain and streamed), and a pause_turn resume sending a full-history create, including that a new MCP authorization_token continues a thread, compact_messages sends no thread, a stored history continues across a JSON round trip (and creates after it's edited), and the profile flag off is covered streamed as well.