Skip to content

fix: preserve prompt cache for mid-conversation system on unflagged Claude models - #36968

Merged
mateo-berri merged 6 commits into
BerriAI:litellm_internal_stagingfrom
oneKn8:fix-anthropic-mid-conversation-system-cache
Aug 20, 2026
Merged

mateo-berri merged 6 commits into
BerriAI:litellm_internal_stagingfrom
oneKn8:fix-anthropic-mid-conversation-system-cache

Conversation

@oneKn8

@oneKn8 oneKn8 commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Mid-conversation system reminders on pre-4.8 Claude get hoisted into system
  • The hoist rewrites the cached prefix, re-billing the whole conversation

How it solves it:

  • Convert the reminder to a user turn in place instead
  • A system run caught between a tool call and its result moves to right after the result, so the pair stays adjacent
  • Leading system runs still hoist; flagged models are untouched

User Flow

Before: a Claude Code user routed to a Vertex Claude 4.6 deployment pays full cache-write pricing every turn a reminder appears

  1. They run a long session against POST https://litellm-domain/v1/messages with their proxy key, history carrying cache_control breakpoints
  2. Claude Code inserts a role: "system" reminder mid-conversation
  3. The response is 200, but usage shows cache_creation_input_tokens around 1746 with cache_read_input_tokens dropping to 5265: the whole prior history was re-billed at cache-write pricing (reporter's real Vertex numbers in Mid-conversation system-role hoist invalidates the entire prompt-cache prefix (AnthropicMessagesConfig) #36559)
  4. Every later reminder repeats the same full-prefix rebill

After: the same session keeps its cache; only the new turn is fresh

  1. They run a long session against POST https://litellm-domain/v1/messages with their proxy key, history carrying cache_control breakpoints
  2. Claude Code inserts a role: "system" reminder mid-conversation
  3. The response is 200, and usage shows cache_read_input_tokens around 6973 with cache_creation_input_tokens around 60: the full prior history read back from cache
  4. Follow-up turns keep reading the full cached prefix

Relevant issues

Fixes #36559

Linear ticket

Resolves LIT-5872

https://linear.app/litellm-ai/issue/LIT-5872/hoisting-mid-conversation-system-reminders-on-pre-48-claude

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

The changed path runs only for the partner routes (Vertex, Bedrock Invoke, Azure Foundry) behind POST /v1/messages; the first-party Anthropic route and chat completions never call it. Both legs drive the real Claude Code CLI (2.1.237) through a local proxy, one session per provider, with the proxy booted from the merge base (Before) and from this PR (After) and nothing else different

Shared setup. config.yaml (keys come from the environment):

model_list:
  - model_name: vertex-sonnet-4-6
    litellm_params:
      model: vertex_ai/claude-sonnet-4-6
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
  - model_name: bedrock-haiku-4-5
    litellm_params:
      model: bedrock/invoke/us.anthropic.claude-haiku-4-5-20251001-v1:0
      aws_region_name: us-east-1
  - model_name: azure-foundry-opus-4-7
    litellm_params:
      model: azure_ai/claude-opus-4-7
      api_base: os.environ/AZURE_FOUNDRY_API_BASE
      api_key: os.environ/AZURE_FOUNDRY_API_KEY

The aliases are deliberately names Claude Code does not recognize: for those it sends its reminders as role: "system" turns after every prompt, which is the issue's setup. For a recognized name such as claude-sonnet-4-6 it inlines them as <system-reminder> text instead, and that session read its cache fine on both legs. big.txt in the working directory is 400 lines of inventory text, about 45k tokens. Each session:

python litellm/proxy/proxy_cli.py --config config.yaml --port $PORT
export ANTHROPIC_BASE_URL=http://127.0.0.1:$PORT ANTHROPIC_AUTH_TOKEN=$PROXY_KEY CLAUDE_CODE_EFFORT_LEVEL=high
claude --model <alias> --strict-mcp-config --mcp-config '{"mcpServers":{}}'

then the user types, in order, Read big.txt in full, then reply with exactly one word: done, Reply with exactly one word: thanks, Reply with exactly one word: again, and /cost. Every session answered done, thanks, again on both legs. Per-response usage below comes from the session transcript Claude Code writes for the user (cache_read_input_tokens / cache_creation_input_tokens, one line per response):

jq -r 'select(.type=="assistant") | [.message.id, .message.usage.cache_read_input_tokens, .message.usage.cache_creation_input_tokens] | @tsv' ~/.claude/projects/<cwd>/<session>.jsonl | awk '!seen[$1]++'

Before (6fcdea0)

Vertex (vertex-sonnet-4-6)

  1. claude --model vertex-sonnet-4-6 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts
  2. Usage per response: 0 / 48827, 0 / 64609, 42868 / 22089, 42868 / 22439. The read never grows past the first breakpoint and about 22k tokens are written again on every turn
  3. /cost: vertex-sonnet-4-6: 10 input, 163 output, 85.7k cache read, 158.0k cache write ($1.03)

Bedrock (bedrock-haiku-4-5)

  1. claude --model bedrock-haiku-4-5 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts
  2. Usage per response: 0 / 50156, 44174 / 21062, 44174 / 21275, 44174 / 21625
  3. /cost: bedrock-haiku-4-5: 862 input, 751 output, 132.5k cache read, 114.1k cache write ($0.80)

Azure Foundry (azure-foundry-opus-4-7)

  1. claude --model azure-foundry-opus-4-7 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts
  2. Usage per response: 0 / 53972, 45998 / 8302, 45998 / 26473, 45998 / 26969, 45998 / 27471
  3. /cost: azure-foundry-opus-4-7: 1.2k input, 385 output, 184.0k cache read, 143.2k cache write ($1.00)

After (155ef8c)

e11399f on top of it only touches tests/e2e, which cannot change proxy behavior

Vertex (vertex-sonnet-4-6)

  1. claude --model vertex-sonnet-4-6 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts
  2. Usage per response: 0 / 45456, 36513 / 28111, 64624 / 54, 65041 / 10. The read grows to the whole conversation and later turns write only the new turn
  3. /cost: vertex-sonnet-4-6: 4.9k input, 190 output, 295.9k cache read, 74.4k cache write ($0.64)

Bedrock (bedrock-haiku-4-5)

  1. claude --model bedrock-haiku-4-5 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts
  2. Usage per response: 0 / 46785, 46785 / 18319, 65104 / 59, 65526 / 10
  3. /cost: bedrock-haiku-4-5: 5.7k input, 1.9k output, 308.1k cache read, 65.9k cache write ($0.64)

Azure Foundry (azure-foundry-opus-4-7)

  1. claude --model azure-foundry-opus-4-7 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts
  2. Usage per response: 0 / 49570, 49570 / 4738, 54308 / 18211, 72519 / 79, 73115 / 15
  3. /cost: azure-foundry-opus-4-7: 7.8k input, 411 output, 395.2k cache read, 73.6k cache write ($0.71)

Observations from the run:

  • Recognized model names never hit the symptom; PR leaves alone
  • Azure opus-4-7 sometimes calls the operator note injection; PR causes
  • Vertex global location can miss fresh cache writes; pre-existing
  • Trailing-system turn: Vertex/Azure 400 becomes 200; PR causes

Type

🐛 Bug Fix

Caveats (if any)

QA runbook

The unflagged-model tests in both e2e files prime the prompt cache first and assert the reminder turn reads the whole primed prefix back, so the same steps prove both the completion and the cache. Priming waits until the first turn reads back on three sends in a row, because the Vertex global location serves the cache per region and a chunk written seconds earlier can still be missing from the region the next request lands on; the Vertex test also pins us-east5, a single cache store, for the same reason. The flagged-model cache tests stay skipped under LIT-4873 and are untouched

  • tests/e2e/llm_translation/test_messages_mid_conversation_system_e2e.py::TestBedrockInvokeMidConversationSystem::test_unflagged_model_converts_system_reminder_and_succeeds - an unflagged Bedrock Claude still answers when a reminder appears, and the reminder turn reads the full primed prefix from cache
    • POST /model/new with the master key registering bedrock/invoke/us.anthropic.claude-haiku-4-5-20251001-v1:0 in us-east-1 (needs AWS credentials), then POST /key/generate for a key scoped to it
    • Prime: POST /v1/messages with a system block unique to this run (300 short paragraphs, above Haiku's 2048-token cache minimum) carrying cache_control, plus one cache_control user turn of about 100 notes; repeat with a fresh user turn every 3s until one response shows both cache_read_input_tokens > 0 and cache_creation_input_tokens > 0, note their sum, then re-send that exact turn until cache_read_input_tokens reaches that sum on three sends in a row
    • POST /v1/messages with the same system block, that same first user turn, a role: "system" reminder, an assistant turn, and a fresh cache_control user turn
    • Expect 200 with assistant text, no provider 400 about role "system", and cache_read_input_tokens at least the sum noted above
    • Sanity check: this test makes sense and is not hand-wavey or potentially flaky
  • tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py::TestAzureFoundryMidConversationSystem::test_unflagged_model_converts_system_reminder_and_succeeds - same shape against Azure Foundry with azure_ai/claude-opus-4-7 (needs AZURE_AI_API_BASE and AZURE_AI_API_KEY)
    • Same four steps as above with the Azure Foundry deployment
    • Sanity check: this test makes sense and is not hand-wavey or potentially flaky
  • tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py::TestVertexMidConversationSystem::test_unflagged_model_converts_system_reminder_and_succeeds - same shape against Vertex with vertex_ai/claude-sonnet-4-6 in us-east5 (needs VERTEXAI_PROJECT and Google credentials)
    • Same four steps as above with the Vertex deployment
    • Sanity check: this test makes sense and is not hand-wavey or potentially flaky

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Note

Medium Risk
Changes request shaping on hot proxy paths (Bedrock/Vertex/Azure Messages) and alters how system reminders are interpreted for older Claude; leading-system hoist and flagged-model paths are unchanged but billing/cache behavior is sensitive.

Overview
Fixes prompt-cache invalidation on Bedrock Invoke, Vertex, and Azure Foundry when Claude Code sends a mid-conversation role: "system" reminder on pre-4.8 Claude models.

Before: models without supports_mid_conversation_system had every in-thread system message hoisted into the top-level system field. That rewrote the cached prefix and forced full cache-write billing on later turns.

After: _normalize_system_role_messages still hoists only a leading run of system messages (required by the API). Mid-conversation reminders on unflagged models are rewritten in place to role: "user" with a fixed operator-note prefix plus the original content, so bytes before the reminder stay unchanged. Flagged Claude 4.8+/5 behavior is unchanged (reminders stay as system in messages).

Unit tests for Azure, Bedrock, and Vertex pin the new message shape; unflagged-model e2e flows now prime the cache and assert cache_read_input_tokens on the reminder turn. Vertex adds coverage that leading system runs are still hoisted on unsupported models.

Reviewed by Cursor Bugbot for commit 1b5e507. Bugbot is set up for automated code reviews on this repo. Configure here.

@CLAassistant

CLAassistant commented Aug 14, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

def _system_role_message_as_user(self, message: dict) -> dict:
return {
**message,
"role": "user",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low: Trusted instructions are downgraded to user input

Changing the role to user removes the provider-enforced priority of application-supplied system reminders. An attacker controlling a later user turn can submit contradictory instructions at the same priority and override restrictions such as tool-use or data-handling rules; the textual operator note does not restore the system trust boundary. For models that cannot accept this role in place, retain the previous top-level hoist despite the cache miss, route to a supporting model, or reject the request rather than silently weakening the instruction.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Known tradeoff, discussed in #36559 and accepted by the maintainer: these models reject true system turns entirely, so the alternative is losing the cache

@greptile-apps

greptile-apps Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR preserves prompt-cache prefixes for unflagged Claude models by converting mid-conversation system reminders into user turns while retaining leading-system hoisting and flagged-model behavior.

  • Adds tool-result-aware ordering for converted reminders.
  • Adds unit coverage across Bedrock Invoke, Azure Foundry, and Vertex.
  • Updates the previously requested unflagged-model e2e coverage to prime the cache and assert that the full prefix is read on the reminder turn.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains; the previously reported unflagged-model cache-coverage gap is addressed by priming the cache and asserting that the reminder turn reads the complete cached prefix.

Important Files Changed

Filename Overview
litellm/llms/anthropic/experimental_pass_through/messages/transformation.py Converts unsupported mid-conversation system messages in place and preserves tool-use/tool-result adjacency.
tests/e2e/llm_translation/test_messages_mid_conversation_system_e2e.py The Bedrock unflagged-model test now primes the full cache prefix and directly checks that the reminder turn reads it back.
tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py Azure and Vertex unflagged-model tests now assert full-prefix cache reuse, with Vertex pinned to a regional endpoint.
tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py Adds focused request-shape coverage for conversion, tool-result ordering, extra-field removal, and unmapped models.
tests/test_litellm/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py Updates Azure transformation expectations for in-place conversion.
tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py Updates Vertex conversion expectations and verifies leading system runs remain hoisted.

Reviews (5): Last reviewed commit: "test(e2e): pin the unflagged Vertex cach..." | Re-trigger Greptile

@veria-ai

veria-ai Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

PR overview

This pull request changes Anthropic pass-through message transformation so mid-conversation system messages on unflagged Claude models are represented as user messages, preserving prompt caching instead of hoisting them to the top-level system prompt.

One security concern remains open, with no issues addressed yet. The new transformation removes provider-enforced priority from application-supplied reminders, allowing a later user message to contradict them when those reminders govern behavior such as tool use or data handling. Exploitation depends on applications relying on mid-conversation system instructions for those controls.

Open issues (1)

Fixed/addressed: 0 · PR risk: 4/10

@codecov

codecov Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@oneKn8

oneKn8 commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai

@codspeed

codspeed Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing oneKn8:fix-anthropic-mid-conversation-system-cache (e11399f) with litellm_internal_staging (6fcdea0)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (e11399f) during the generation of this report, so 6fcdea0 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 1b5e507. Configure here.

…rsation system turns

On models without supports_mid_conversation_system, a system entry between
an assistant tool_use turn and the user tool_result turn became a user turn
in that position and the provider rejected the request ("tool_use ids were
found without tool_result blocks immediately after"). That run of entries
now goes right after the tool_result turn, where consecutive user turns
merge upstream. The converted turn also carries only role and content, as
the hoist did, so an entry with extra keys no longer 400s with "Extra
inputs are not permitted".

The e2e cache priming re-sends the identical first turn until its own cache
entry reads back before the reminder turn goes out, since Vertex can take a
few seconds to serve a freshly written entry.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit e11399f. Configure here.

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks for the contribution!

@mateo-berri
mateo-berri merged commit 6d47468 into BerriAI:litellm_internal_staging Aug 20, 2026
71 checks passed
oneKn8 added a commit to oneKn8/litellm that referenced this pull request Aug 25, 2026
…ons system prompt

translate_system_message hoisted every role=system message, at any index, into
the top-level system block. On a conversation carrying a mid-session reminder
that rewrites the cached prefix, so the provider re-bills the whole history at
cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages;
the chat completions path, shared by first-party Anthropic, Vertex, Azure AI
and Bedrock Invoke, still hoisted.

Only the leading system run becomes the system prompt now. Later system
messages go through the placement policy, and anthropic_messages_pt emits a
system message instead of rejecting the role. The caller's message list is no
longer mutated. Tests pin the two-turn prefix invariant across all four chat
configs and both flag states.
oneKn8 added a commit to oneKn8/litellm that referenced this pull request Aug 26, 2026
…ons system prompt

translate_system_message hoisted every role=system message, at any index, into
the top-level system block. On a conversation carrying a mid-session reminder
that rewrites the cached prefix, so the provider re-bills the whole history at
cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages;
the chat completions path, shared by first-party Anthropic, Vertex, Azure AI
and Bedrock Invoke, still hoisted.

Only the leading system run becomes the system prompt now. Later system
messages go through the placement policy, and anthropic_messages_pt emits a
system message instead of rejecting the role. The caller's message list is no
longer mutated. Tests pin the two-turn prefix invariant across all four chat
configs and both flag states.
oneKn8 added a commit to oneKn8/litellm that referenced this pull request Aug 27, 2026
…ons system prompt

translate_system_message hoisted every role=system message, at any index, into
the top-level system block. On a conversation carrying a mid-session reminder
that rewrites the cached prefix, so the provider re-bills the whole history at
cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages;
the chat completions path, shared by first-party Anthropic, Vertex, Azure AI
and Bedrock Invoke, still hoisted.

Only the leading system run becomes the system prompt now. Later system
messages go through the placement policy, and anthropic_messages_pt emits a
system message instead of rejecting the role. The caller's message list is no
longer mutated. Tests pin the two-turn prefix invariant across all four chat
configs and both flag states.
oneKn8 added a commit to oneKn8/litellm that referenced this pull request Aug 27, 2026
…ons system prompt

translate_system_message hoisted every role=system message, at any index, into
the top-level system block. On a conversation carrying a mid-session reminder
that rewrites the cached prefix, so the provider re-bills the whole history at
cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages;
the chat completions path, shared by first-party Anthropic, Vertex, Azure AI
and Bedrock Invoke, still hoisted.

Only the leading system run becomes the system prompt now. Later system
messages go through the placement policy, and anthropic_messages_pt emits a
system message instead of rejecting the role. The caller's message list is no
longer mutated. Tests pin the two-turn prefix invariant across all four chat
configs and both flag states.
oneKn8 added a commit to oneKn8/litellm that referenced this pull request Sep 7, 2026
…ons system prompt

translate_system_message hoisted every role=system message, at any index, into
the top-level system block. On a conversation carrying a mid-session reminder
that rewrites the cached prefix, so the provider re-bills the whole history at
cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages;
the chat completions path, shared by first-party Anthropic, Vertex, Azure AI
and Bedrock Invoke, still hoisted.

Only the leading system run becomes the system prompt now. Later system
messages go through the placement policy, and anthropic_messages_pt emits a
system message instead of rejecting the role. The caller's message list is no
longer mutated. Tests pin the two-turn prefix invariant across all four chat
configs and both flag states.
oneKn8 added a commit to oneKn8/litellm that referenced this pull request Sep 14, 2026
…ons system prompt

translate_system_message hoisted every role=system message, at any index, into
the top-level system block. On a conversation carrying a mid-session reminder
that rewrites the cached prefix, so the provider re-bills the whole history at
cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages;
the chat completions path, shared by first-party Anthropic, Vertex, Azure AI
and Bedrock Invoke, still hoisted.

Only the leading system run becomes the system prompt now. Later system
messages go through the placement policy, and anthropic_messages_pt emits a
system message instead of rejecting the role. The caller's message list is no
longer mutated. Tests pin the two-turn prefix invariant across all four chat
configs and both flag states.
oneKn8 added a commit to oneKn8/litellm that referenced this pull request Sep 14, 2026
…ons system prompt

translate_system_message hoisted every role=system message, at any index, into
the top-level system block. On a conversation carrying a mid-session reminder
that rewrites the cached prefix, so the provider re-bills the whole history at
cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages;
the chat completions path, shared by first-party Anthropic, Vertex, Azure AI
and Bedrock Invoke, still hoisted.

Only the leading system run becomes the system prompt now. Later system
messages go through the placement policy, and anthropic_messages_pt emits a
system message instead of rejecting the role. The caller's message list is no
longer mutated. Tests pin the two-turn prefix invariant across all four chat
configs and both flag states.
mateo-berri added a commit that referenced this pull request Sep 25, 2026
…inking on chat completions (#42630)

* feat(anthropic): placement policy for mid-conversation system messages

Pure functions over the OpenAI-format message list: split off the leading
system run, keep later system messages as role=system at a placement Anthropic
accepts on models flagged supports_mid_conversation_system (after a user turn,
before an assistant turn or the end, never adjacent), and convert them to user
turns in place elsewhere, keeping tool_result first in a merged user turn.

* fix(anthropic): keep mid-conversation system out of the chat completions system prompt

translate_system_message hoisted every role=system message, at any index, into
the top-level system block. On a conversation carrying a mid-session reminder
that rewrites the cached prefix, so the provider re-bills the whole history at
cache-write pricing on every turn (#36559). #36968 fixed this on /v1/messages;
the chat completions path, shared by first-party Anthropic, Vertex, Azure AI
and Bedrock Invoke, still hoisted.

Only the leading system run becomes the system prompt now. Later system
messages go through the placement policy, and anthropic_messages_pt emits a
system message instead of rejecting the role. The caller's message list is no
longer mutated. Tests pin the two-turn prefix invariant across all four chat
configs and both flag states.

* refactor(anthropic): single-source the converted system note

The /v1/messages pass-through and the chat completions path must prefix a
converted system turn with the same operator note.

* test(e2e): prove the prompt cache survives a mid-conversation system reminder on chat completions

Same priming and assertions as the /v1/messages cases, through
/v1/chat/completions with OpenAI-format messages, for first-party Anthropic
and Bedrock Invoke on a flagged (Opus 4.8) and an unflagged (Haiku 4.5) model.
The reminder sits between the assistant turn and the next user turn, the shape
OpenAI-style agent frameworks send, which is the placement the chat path has
to translate.

* test(anthropic): cover the cache_control rebuild shapes and type the test helpers

Codecov flagged the 5m ttl branch and the empty-system path of the wire
builder; both now have a test. Greptile asked for full typing on the new
test helpers.

* refactor(anthropic): read the mid-conversation flag through a public supports_ helper

supports_mid_conversation_system joins the other supports_* helpers in
litellm.utils, so the chat transformation stops importing the private
_supports_factory.

* chore(typing): declare the mid-conversation type aliases with TypeAlias

The Final sweep tightened LIT010, which exempts TypeAlias declarations but
counts a bare alias assignment as an unannotated binding.

* fix(anthropic): let add_code_execution_tool take the pass-through message union

The translator now emits role=system inside messages for models that accept it,
so anthropic_messages_pt returns the pass-through union. add_code_execution_tool
still declared the narrower user/assistant union while only ever reading
content, so upstream's strip_advisor_blocks_from_messages call in between made
the mismatch visible to the type checker.

* fix(bedrock): keep mid-conversation system messages in place on converse path

* fix: ruff format + multi tool_result order + regression test

* fix: satisfy type-discipline gate + update osv ignore for mlflow PYSEC-2026-3865

* fix(bedrock): restore role narrowing in hoisted system loop for basedpyright budget

* test(bedrock): cover mid-conversation system conversion branches

- non-dict guard in _opens_with_tool_result
- in-place conversion without tool context
- str/list cache_control preservation in mid-conversation path
- drop unreachable non-system guard in hoisted loop

* Place type-discipline suppressions on the lines the gate scans

* Narrow hoisted loop to system role so basedpyright sees the right TypedDict

* fix(anthropic): place mid-conversation system runs by their neighbours only

A run after an assistant turn now slides behind the user turn that
immediately follows it, and a run that ends the array or precedes an
assistant turn becomes a user turn in place. No later message can move
an earlier run, so a client that replays the conversation with more
turns appended sends a byte-identical prefix and preserved thinking
blocks keep their binding

* refactor(bedrock): share the converted system note with the anthropic module

Converse imports CONVERTED_SYSTEM_NOTE instead of carrying its own copy
of the same text, and the reordering helpers lose their comments

* test: pin the replayed request prefix across preserved-thinking turns

One test per audited feature, through the real entrypoint: the chat
transformations for anthropic, bedrock invoke, vertex and converse, the
modify_params dummy tool result, dotprompt with unchanged variables, and
Presidio masking against an in-process fake. Each serializes system,
tools and the earlier messages of turn N and N+1 and asserts they match.
The e2e mid-conversation system test imports its content blocks from
models.py again and is marked provider_live

* fix(anthropic): move mid-conversation system placement into prompt_templates

The prompt factory imported the placement helper from the Anthropic provider
package, whose common_utils reads a factory constant at import time, so loading
the factory first raised ImportError. The module now sits next to
anthropic_messages_pt and every consumer imports core utils

A user turn with content [] or None puts no block on the wire, so a system run
anchored to it landed first in messages or behind an assistant turn. Such a run
now converts in place; empty strings and empty text blocks still anchor because
the factory fills them with a placeholder

* fix(anthropic): anchor system messages only on user turns that reach the wire

* fix(bedrock): type the converse system-message helpers over the message TypedDicts

* fix(anthropic): read replayed pydantic messages in the Converse helpers and convert a system run whose assistant follower sends nothing

A history that replays the previous turn as the litellm.Message object
was invisible to the Converse system-message helpers, so a mid-conversation
system stayed between a tool call and its result or reached Converse as
role: system. The helpers now read fields through the shared
message_field and parts_of accessors and drop the local role predicate.

Flagged placement anchored a system run on any assistant follower, but
anthropic_messages_pt drops an assistant turn that puts no block on the
wire (content None, an empty list, an unsigned thinking part), so the
system landed directly before the next user turn, which Anthropic
rejects. Such a run now converts in place. An empty or whitespace text
turn still anchors, since the converter pads it with a placeholder.

* fix(anthropic): treat bridged encrypted reasoning as a vanishing assistant turn for system placement

An assistant turn whose only blocks carry Responses API encrypted reasoning is
dropped by anthropic_messages_pt, so a mid-conversation system run anchored
before it landed directly before the next user turn. The unsignable-thinking
predicate now lives in common_utils and both the factory and the placement
policy consult it.

* fix(anthropic): let an inline thinking part hide separate thinking_blocks in system placement

anthropic_messages_pt skips an assistant turn's separate thinking_blocks as soon
as its content list carries an inline thinking or redacted_thinking part, so a
turn whose inline part is unsigned puts nothing on the wire even when the
separate block is signed. The placement policy now mirrors that rule.

---------

Co-authored-by: Shifat Islam Santo <shifatislamsanto764@gmail.com>
Co-authored-by: ege-arhan <egearhany@gmail.com>
Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mid-conversation system-role hoist invalidates the entire prompt-cache prefix (AnthropicMessagesConfig)

3 participants