Skip to content

fix(streaming): surface in-body error payloads on OpenAI-compatible streams - #32237

Merged
yassin-berriai merged 2 commits into
litellm_internal_stagingfrom
litellm_midstream_error_payload
Jul 6, 2026
Merged

yassin-berriai merged 2 commits into
litellm_internal_stagingfrom
litellm_midstream_error_payload

Conversation

@yassin-berriai

@yassin-berriai yassin-berriai commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Fixes #25492. Related: #26015 (the CPU-spin half of the same customer report; already resolved by #31298, verified not reproducible on current staging during this investigation)

Linear ticket

Resolves LIT-4211

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 requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Screenshots / Proof of Fix

vLLM and sglang report some request errors inside an HTTP 200 SSE stream instead of a real 4xx/5xx status, e.g. sending an image to a non-multimodal model:

data: {"error": {"object": "error", "message": "The model is not multimodal. Please remove image inputs.", "type": "BadRequestError", "param": null, "code": 400}}
data: [DONE]

Repro setup: a local upstream on 127.0.0.1:41893 that emits exactly that body (a misbehaving upstream is required to reproduce, so this stands in for vLLM), plus a real OpenAI fallback, proxied by python litellm/proxy/proxy_cli.py --config msf_config.yaml --port 41894 --detailed_debug:

model_list:
  - model_name: vllm-vision
    litellm_params:
      model: hosted_vllm/qwen-vl-mock
      api_base: http://127.0.0.1:41893/v1
      api_key: fake-key
  - model_name: gpt-fallback
    litellm_params:
      model: openai/gpt-5.5
      api_key: os.environ/OPENAI_API_KEY

litellm_settings:
  fallbacks:
    - vllm-vision:
        - gpt-fallback

Before the fix, the error payload parsed into an empty chunk and the client received a silent empty 200 stream; the provider's message was lost and the configured fallback was never attempted:

$ curl -s -N http://127.0.0.1:41894/v1/chat/completions \
    -H "Authorization: Bearer sk-msf-test-1234" -H "Content-Type: application/json" \
    -d '{"model":"vllm-vision","stream":true,"messages":[{"role":"user","content":[{"type":"text","text":"describe this image"},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}}]}]}'
data: {"id":"chatcmpl-f359f14b-7977-4968-8e73-290bd649b280","object":"chat.completion.chunk","created":1783328811,"model":"vllm-vision","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]

After the fix, the same request surfaces the provider's error as a clean 400:

$ curl -s -w "\nHTTP %{http_code}\n" -N http://127.0.0.1:41894/v1/chat/completions \
    -H "Authorization: Bearer sk-msf-test-1234" -H "Content-Type: application/json" \
    -d '{"model":"vllm-vision","stream":true,"messages":[{"role":"user","content":[{"type":"text","text":"what color is this image? one word."},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}}]}]}'
{"error":{"message":"litellm.BadRequestError: Hosted_vllmException - The model is not multimodal. Please remove image inputs.","type":null,"param":null,"code":"400"}}
HTTP 400

And an in-body 5xx (vLLM engine crash shape, "code": 500) now wraps into MidStreamFallbackError, so the router serves the request from the configured fallback (real OpenAI API call, real spend):

$ curl -s -N http://127.0.0.1:41894/v1/chat/completions \
    -H "Authorization: Bearer sk-msf-test-1234" -H "Content-Type: application/json" \
    -d '{"model":"vllm-vision","stream":true,"messages":[{"role":"user","content":"servererror: reply with the single word pong"}]}' \
    | grep -o '"content":"[^"]*"'
"content":""
"content":"pong"

Independent e2e recording using mock vLLM upstream and the LiteLLM proxy from this branch, covering all three scenarios (400 surfaced, 500 fallback, normal stream) plus pytest regression tests: video recording

Type

🐛 Bug Fix

Changes

OpenAIChatCompletionStreamingHandler.chunk_parser (shared by hosted_vllm, openai_like, groq, xai, mistral, fireworks_ai and every other provider that reuses the OpenAI-compatible streaming iterator) had no detection for an {"error": ...} SSE payload. On the version in issue #25492 this crashed with KeyError: 'id' and leaked a 503 MidStreamFallbackError to the client; since #23931 switched to chunk.get("id"), the payload instead parsed into an empty ModelResponseStream and the stream ended silently with HTTP 200

This PR detects the payload in chunk_parser and raises OpenAIError carrying the upstream message and status code (integer code in the 4xx/5xx range is honored, anything else maps to 500; a "error": null field on a normal chunk is tolerated). From there the existing mid-stream gate in streaming_handler._handle_stream_fallback_error applies unchanged: 4xx other than 429 surface directly to the client, 429 and 5xx wrap into MidStreamFallbackError so the router runs configured fallbacks

One deliberate scope note: for an in-body 400 with a fallback configured, the client now gets the 400 directly rather than a fallback response. That matches the existing, test-pinned mid-stream contract from #22375 (non-retriable 4xx skip fallback). Making pre-first-chunk 4xx eligible for fallbacks would align streaming with how the same provider error is treated when it arrives as a real HTTP 400 pre-call, but that is a semantics change across all providers and belongs in its own discussion

Regression tests fail without the fix and pass with it: parser-level tests in tests/test_litellm/llms/openai/chat/test_openai_gpt_transformation.py (vLLM 400 shape, string/absent code mapping to 500, "error": null tolerance) and gate-level tests in tests/test_litellm/litellm_core_utils/test_streaming_handler.py driving the real iterator through CustomStreamWrapper (400 surfaces as BadRequestError, 500 wraps for mid-stream fallback)

Link to Devin session: https://app.devin.ai/sessions/280f53a344ef4e7d8460adc0ff3bd7c0

…treams

vLLM and sglang return HTTP 200 streams whose SSE body carries the error,
e.g. data: {"error": {"message": "...", "code": 400}}. The OpenAI-compatible
chunk parser had no detection for this shape: since #23931 the payload parsed
into an empty chunk (choices=[]) and the stream ended silently with 200,
losing the provider's error and never attempting configured fallbacks.

Detect the payload in OpenAIChatCompletionStreamingHandler.chunk_parser and
raise OpenAIError with the upstream message and status code. The existing
mid-stream gate then applies: 4xx surface directly to the client, 5xx wrap
into MidStreamFallbackError so the router can run configured fallbacks.

Fixes #25492
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes silent swallowing of in-body error payloads on OpenAI-compatible streams (vLLM, sglang) by detecting {"error": {...}} SSE frames in chunk_parser and raising OpenAIError with the upstream message and status code. From there, the existing _handle_stream_fallback_error gate routes 4xx directly to the client and wraps 5xx in MidStreamFallbackError for router-level fallback.

  • _extract_error_from_chunk is added as a static method in OpenAIChatCompletionStreamingHandler; it handles dict errors, non-dict/string errors, missing/non-integer code values (defaulting to 500), and "error": null (tolerated as no-error). The json.dumps fallback for a dict with no message key is present in this HEAD.
  • Five new mock-only tests cover parser-level behavior (400 shape, string code → 500, no-message → json.dumps, null tolerance) and full-CustomStreamWrapper gate behavior (400 → BadRequestError, 500 → MidStreamFallbackError).

Confidence Score: 5/5

Safe to merge — the change is a targeted bug fix in a single static method with no side effects on the happy path, and the json.dumps fallback previously flagged is confirmed present in this HEAD.

The new _extract_error_from_chunk method is correctly guarded: not error short-circuits on None and {} (the two most common non-error cases), the fallback to 500 for non-integer or out-of-range codes is conservative and safe, and the json.dumps path for a dict with no message key produces a valid JSON string rather than a Python repr. The existing _handle_stream_fallback_error gate is unchanged and correctly routes 4xx to the client and 5xx to fallback. All five new tests are mock-only and hit both the parser layer and the full streaming wrapper layer, covering the exact shapes reported in the original issue.

No files require special attention.

Important Files Changed

Filename Overview
litellm/llms/openai/chat/gpt_transformation.py Adds _extract_error_from_chunk static method and in-body error detection in chunk_parser; json.dumps fallback already present in HEAD; logic is correct and well-guarded.
tests/test_litellm/litellm_core_utils/test_streaming_handler.py Adds two gate-level regression tests driving the full CustomStreamWrapper with 400 and 500 in-body error payloads; all mocked, no real network calls.
tests/test_litellm/llms/openai/chat/test_openai_gpt_transformation.py Adds three unit-level tests covering vLLM 400 shape, string/absent code mapping to 500, and "error": null tolerance; all pass against the new implementation.

Reviews (3): Last reviewed commit: "fix(streaming): serialize messageless er..." | Re-trigger Greptile

stream whose body carries an error payload, e.g.
``data: {"error": {"message": "...", "code": 400}}``."""
error = chunk.get("error")
if not error:

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 Falsy-check may silently drop edge-case error shapes

if not error: returns None for any falsy value: None (intended), {} (empty dict, harmless), but also 0, False, or "". The real edge is {"error": {}} being treated as no error at all since {} is falsy. That's probably the right call, but it is undocumented.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@greptile-apps

greptile-apps Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes silent swallowing of in-body error payloads emitted by OpenAI-compatible backends (vLLM, sglang) that return HTTP 200 SSE streams containing {"error": {...}} chunks. The new _extract_error_from_chunk helper in OpenAIChatCompletionStreamingHandler.chunk_parser detects such payloads and raises OpenAIError, letting the existing mid-stream gate route 4xx errors to the client and 5xx errors to configured fallbacks.

  • Adds _extract_error_from_chunk static method that maps integer HTTP codes in 400–599 to the error status and falls back to 500 for string/absent codes; "error": null on normal chunks is correctly tolerated.
  • Raises OpenAIError early in chunk_parser so the existing _handle_stream_fallback_error path handles classification into BadRequestError (4xx non-429) vs. MidStreamFallbackError (5xx/429) unchanged.
  • Adds regression tests at both the parser level and the full CustomStreamWrapper level, with no real network calls.

Confidence Score: 4/5

The change is a focused, additive detection layer in chunk_parser; the existing mid-stream gate is untouched and the new code has no effect on normal (non-error) chunks.

The fix is narrow and well-tested at both unit and integration levels. The one minor issue is that a missing "message" field in the error dict produces a Python repr string in the error message rather than clean JSON, but this affects only unusual upstream payloads and carries no correctness risk.

gpt_transformation.py — the str(error) fallback message path is the only thing worth a second look before merging.

Important Files Changed

Filename Overview
litellm/llms/openai/chat/gpt_transformation.py Adds _extract_error_from_chunk and early-exit in chunk_parser to detect in-body SSE error payloads and raise OpenAIError; logic is correct and existing mid-stream gate routes them appropriately
tests/test_litellm/litellm_core_utils/test_streaming_handler.py New integration-style tests drive a real CustomStreamWrapper over an in-memory async generator; no network calls, correctly verifies 400→BadRequestError and 500→MidStreamFallbackError paths
tests/test_litellm/llms/openai/chat/test_openai_gpt_transformation.py Unit tests for chunk_parser at the parser level: vLLM 400 shape, string/absent code → 500, and "error": null tolerance are all exercised

Reviews (2): Last reviewed commit: "fix(streaming): surface in-body error pa..." | Re-trigger Greptile

Address review feedback: an error dict without a message field now
serializes via json.dumps instead of Python dict repr
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai Addressed the messageless-dict case in 80060e8: the fallback now serializes the error payload with json.dumps instead of Python dict repr, with a test pinning the exact output. The falsy check that ignores an empty {} error field is deliberate: a chunk carrying "error": {} alongside real choices should not kill the stream, and an empty object carries no diagnostic value anyway; treating only truthy payloads as fatal keeps the guard from ever false-positiving on benign chunks

@greptile-apps

greptile-apps Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

The fix in 80060e8 looks correct. json.dumps(error) produces valid JSON output (e.g. '{"code": 400}') instead of Python's repr (e.g. "{'code': 400}") — that's the right call for an error message surfaced to API clients.

The falsy guard for {} is also sound. An empty dict produces no diagnostic value and treating it as fatal would risk false-positives on any chunk that happens to carry "error": null or "error": {} alongside a real choices array (some providers do emit this). Only a truthy, non-empty error payload should kill the stream.

LGTM on both counts.

@codecov

codecov Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai please review the current head 80060e8; the previous two reviews are pinned to 5ad1496, which predates the json.dumps fix you confirmed as LGTM

@yassin-berriai
yassin-berriai enabled auto-merge (squash) July 6, 2026 09:32
@yassin-berriai
yassin-berriai merged commit cb3a7ac into litellm_internal_staging Jul 6, 2026
76 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_midstream_error_payload branch July 6, 2026 15:13
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.

[Bug]: when upstream return BadRequestError,litellm handle the stream normally and raise the 503 MidStreamFallbackError

3 participants