Skip to content

feat(prompt_templates): opt-in LITELLM_DROP_MIDTURN_SYSTEM removes mid-conversation system turns - #40969

Open
dkrisman wants to merge 1 commit into
BerriAI:mainfrom
dkrisman:litellm_demote_midturn_system
Open

dkrisman wants to merge 1 commit into
BerriAI:mainfrom
dkrisman:litellm_demote_midturn_system

Conversation

@dkrisman

@dkrisman dkrisman commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Reworked 2026-09-26: main now converts mid-conversation system turns to user turns on the bridge by default (#41493), which is what this PR's former demote mode did. The PR is reduced to the one thing main still lacks: an opt-in that removes those turns instead of delivering them, on the bridge and on the hosted_vllm chat completions path. Env var renamed accordingly.

TLDR

Problem this solves:

  • The bridge now delivers every mid-turn system reminder as a user turn with an operator note
  • Some operators do not want the reminder delivered at all
  • On the OpenAI-shaped /v1/chat/completions path a mid-turn system row still 400s on strict templates

How it solves it:

  • new opt-in env flag LITELLM_DROP_MIDTURN_SYSTEM=true
  • system rows after the leading run are removed before placement
  • applies to the /v1/messages bridge and to hosted_vllm chat completions
  • callers that pass preserve_midturn_system=True (guardrails, compaction) still see the rows
  • without the flag nothing changes

User Flow

Before: a developer whose proxy fronts a strict-template vLLM model gets the harness reminder injected as a user turn, and an OpenAI SDK client sending the same shape gets a 400

  1. The proxy admin routes local-qwen to hosted_vllm/qwen3 and the developer points Claude Code (or an OpenAI SDK) at the proxy
  2. The client sends POST http://localhost:4000/v1/messages with a system prompt, a user turn, a mid-turn system reminder ending "End your reply with the word PINEAPPLE", and another user turn
  3. The reply is 200 with input_tokens: 114 and text Hi again PINEAPPLE: the reminder reached the model as a user turn carrying the operator note
  4. The same conversation as POST http://localhost:4000/v1/chat/completions comes back 400: System message must be at the beginning.

After: the admin opts out of delivering the reminders, and both surfaces succeed without them

  1. The proxy admin sets LITELLM_DROP_MIDTURN_SYSTEM=true, restarts the proxy, and the developer sends the same requests
  2. POST http://localhost:4000/v1/messages returns 200 with input_tokens: 71 and text Hi: no PINEAPPLE, the input is exactly the reminder smaller
  3. POST http://localhost:4000/v1/chat/completions returns 200 with prompt_tokens: 71 and text Hi.
  4. A full Claude Code session against the proxy completes with zero template errors in the proxy log

Relevant issues

Related: #26879 covers the same failure class on the Responses API surface

Pre-Submission checklist

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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • 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

Shared setup. A live vLLM worker serving Qwen3.8-27B-FP8 (the strict-template backend), one proxy config, one Claude Code-shaped payload per surface. The mid-turn reminder carries a marker so the two modes are distinguishable from the response text alone. "Before" is the same tip with the flag unset, which is byte-for-byte main's code path.

# config.yaml
model_list:
  - model_name: local-qwen
    litellm_params:
      model: hosted_vllm/qwen-3.8-fp8-27b-code-1m
      api_base: http://127.0.0.1:15020/v1
      api_key: dummy
general_settings:
  master_key: sk-proof-local
{"model": "local-qwen", "max_tokens": 200,
 "system": "You are a terse assistant.",
 "messages": [
   {"role": "user", "content": "Say hi."},
   {"role": "system", "content": [{"type": "text", "text": "<system-reminder>End your reply with the word PINEAPPLE.</system-reminder>"}]},
   {"role": "user", "content": "Say hi again."}]}

The chat completions payload is the same conversation with the system prompt as the first message.

Before (flag unset)

  1. litellm --config config.yaml --port 4010
  2. curl -sS http://127.0.0.1:4010/v1/messages -H "Authorization: Bearer sk-proof-local" -H "Content-Type: application/json" -d @payload.json, observed text Hi again PINEAPPLE, usage {"input_tokens": 114, "output_tokens": 160}: 200, the reminder was delivered as a user turn
  3. curl -sS http://127.0.0.1:4010/v1/chat/completions ... -d @payload_chat.json, observed: litellm.BadRequestError: Hosted_vllmException - {"error":{"message":"System message must be at the beginning.","type":"BadRequestError","param":null,"code":400}}

After (LITELLM_DROP_MIDTURN_SYSTEM=true)

  1. LITELLM_DROP_MIDTURN_SYSTEM=true litellm --config config.yaml --port 4011
  2. The identical /v1/messages curl, observed text Hi, usage {"input_tokens": 71, "output_tokens": 128}: 200, no PINEAPPLE, 43 input tokens smaller (the operator note plus the reminder)
  3. The identical /v1/chat/completions curl, observed text Hi., usage {"prompt_tokens": 71, "completion_tokens": 75}: 200
  4. ANTHROPIC_BASE_URL=http://127.0.0.1:4011 claude -p "Reply with exactly: drop mode online" --model local-qwen returns drop mode online; the proxy log shows 3 POST /v1/messages and 0 template errors

Type

🆕 New Feature

Caveats (if any)

  • process-wide env flag, applies to every model behind the bridge and every hosted_vllm deployment
  • discards reminder content the client believes was delivered
  • default stays main's in-place conversion

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

@dkrisman
dkrisman requested a review from a team September 13, 2026 05:41
@dkrisman
dkrisman force-pushed the litellm_demote_midturn_system branch from 8f497c9 to 3608e27 Compare September 26, 2026 07:37
@CLAassistant

CLAassistant commented Sep 26, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@dkrisman dkrisman changed the title feat(anthropic-bridge): opt-in demotion or dropping of mid-turn system messages feat(prompt_templates): opt-in LITELLM_DROP_MIDTURN_SYSTEM removes mid-conversation system turns Sep 26, 2026
@dkrisman

Copy link
Copy Markdown
Contributor Author

@greptileai reworked to drop-only on top of #41493's default conversion; hosted_vllm chat path covered, live proof in the body.

@greptile-apps

greptile-apps Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[Medium risk] Adds optional filtering of mid-conversation system messages.

The PR appears safe to merge, though hosted_vllm prompt logging should be aligned with the filtered request.

Findings

  1. P2 Logged prompt differs from request ▶

Summary

The PR adds an opt-in flag to remove mid-conversation system messages before Anthropic bridge placement and hosted_vllm chat transformation, with tests for dropping, default behavior, and preservation. The hosted_vllm request body is filtered, but its logged input remains unfiltered.

Reviews (1) · Last reviewed commit: "feat(prompt_templates): opt-in LITELLM_D..."

Comment on lines +173 to +177
kept_messages: Final = (
list(drop_mid_conversation_system(messages)) # mutable-ok: super()._transform_messages takes a list
if drops_mid_conversation_system()
else messages
)

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.

P2 Logged prompt differs from request

When LITELLM_DROP_MIDTURN_SYSTEM=true, this creates a filtered list for the hosted_vllm request but leaves the original messages list intact. The HTTP handler passes that original list to pre-call logging, so logs and observability callbacks can show mid-turn system reminders that were never sent to the model. This makes the recorded prompt unreliable when checking what the model received.

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.

Intentional: the logged input stays the client's request, same as the bridge path, which also leaves its input list untouched.

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.

That’s fair. If pre-call logging is intentionally defined as the client’s raw request—as it is on the bridge path—retaining messages here is consistent and does not make the log inaccurate under that contract. The filtered list is still passed to super()._transform_messages, so the model request omits the mid-turn system rows. I’m withdrawing this finding.

@codecov

codecov Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing dkrisman:litellm_demote_midturn_system (7a23771) with main (84eeebd)

Open in CodSpeed

@dkrisman
dkrisman force-pushed the litellm_demote_midturn_system branch from 3608e27 to e3e0432 Compare September 26, 2026 07:54
@dkrisman
dkrisman force-pushed the litellm_demote_midturn_system branch from e3e0432 to 5190682 Compare October 16, 2026 06:33
@greptile-apps

greptile-apps Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@dkrisman
dkrisman force-pushed the litellm_demote_midturn_system branch from 5190682 to d61f131 Compare October 16, 2026 07:10
"""
for message in messages:
kept_messages: Final = (
list(drop_mid_conversation_system(messages))

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: Guardrail advisories are silently discarded

With LITELLM_DROP_MIDTURN_SYSTEM=true and Lakera configured with on_flagged="inject_system_message", an attacker can submit a prompt that Lakera flags and have it forwarded without the configured advisory. CustomGuardrail.inject_advisory_message() appends a trailing system message and reports delivery, but this filter—and the equivalent new filter in the Anthropic adapter—then deletes it.

Preserve server-injected advisories in the retained system prefix, or block when they cannot be delivered, rather than treating them as disposable conversation reminders.

@veria-ai

veria-ai Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

This PR adds the opt-in LITELLM_DROP_MIDTURN_SYSTEM setting to remove mid-conversation system messages in the hosted vLLM and Anthropic adapters.

One issue remains open: when this setting is enabled and Lakera is configured to inject advisories, the filters also remove server-injected guardrail messages. An attacker can therefore have a flagged prompt forwarded without the configured advisory, even though advisory delivery is reported as successful. The impact is conditional on this configuration and concerns advisory delivery rather than a demonstrated bypass of blocking enforcement.

Open issues (1)

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

Reviews

@dkrisman
dkrisman force-pushed the litellm_demote_midturn_system branch 2 times, most recently from d8be529 to 7a23771 Compare October 16, 2026 08:44
@dkrisman
dkrisman force-pushed the litellm_demote_midturn_system branch from 7a23771 to 23b418e Compare October 29, 2026 05:00
@dkrisman
dkrisman force-pushed the litellm_demote_midturn_system branch from 23b418e to 37e855d Compare November 10, 2026 01:57
…stem turns after the leading run

Strict chat templates (Qwen3 on vLLM) reject a system row that is not first.
The Anthropic bridge now converts such turns to user turns with an operator
note; operators who would rather not deliver the reminder at all can set
LITELLM_DROP_MIDTURN_SYSTEM=true to remove them before placement, on the
/v1/messages bridge and on the hosted_vllm chat completions path. Callers
that pass preserve_midturn_system=True (guardrails, compaction) still see
the turns. Off by default.
@dkrisman
dkrisman force-pushed the litellm_demote_midturn_system branch from 37e855d to 75661cd Compare November 10, 2026 04:46

This branch has not been deployed

No deployments
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.

2 participants