Repository navigation
fix(streaming): surface in-body error payloads on OpenAI-compatible streams - #32237
Conversation
…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
|
|
Greptile SummaryThis PR fixes silent swallowing of in-body error payloads on OpenAI-compatible streams (vLLM, sglang) by detecting
Confidence Score: 5/5Safe 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.
|
| 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: |
There was a problem hiding this comment.
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 SummaryThis PR fixes silent swallowing of in-body error payloads emitted by OpenAI-compatible backends (vLLM, sglang) that return HTTP 200 SSE streams containing
Confidence Score: 4/5The change is a focused, additive detection layer in The fix is narrow and well-tested at both unit and integration levels. The one minor issue is that a missing
|
| 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
|
@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 |
|
The fix in 80060e8 looks correct. The falsy guard for LGTM on both counts. |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
@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 |
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
@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewScreenshots / 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:
Repro setup: a local upstream on
127.0.0.1:41893that emits exactly that body (a misbehaving upstream is required to reproduce, so this stands in for vLLM), plus a real OpenAI fallback, proxied bypython litellm/proxy/proxy_cli.py --config msf_config.yaml --port 41894 --detailed_debug: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:
After the fix, the same request surfaces the provider's error as a clean 400:
And an in-body 5xx (vLLM engine crash shape,
"code": 500) now wraps intoMidStreamFallbackError, so the router serves the request from the configured fallback (real OpenAI API call, real spend):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 withKeyError: 'id'and leaked a 503MidStreamFallbackErrorto the client; since #23931 switched tochunk.get("id"), the payload instead parsed into an emptyModelResponseStreamand the stream ended silently with HTTP 200This PR detects the payload in
chunk_parserand raisesOpenAIErrorcarrying the upstream message and status code (integercodein the 4xx/5xx range is honored, anything else maps to 500; a"error": nullfield on a normal chunk is tolerated). From there the existing mid-stream gate instreaming_handler._handle_stream_fallback_errorapplies unchanged: 4xx other than 429 surface directly to the client, 429 and 5xx wrap intoMidStreamFallbackErrorso the router runs configured fallbacksOne 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/absentcodemapping to 500,"error": nulltolerance) and gate-level tests intests/test_litellm/litellm_core_utils/test_streaming_handler.pydriving the real iterator throughCustomStreamWrapper(400 surfaces asBadRequestError, 500 wraps for mid-stream fallback)Link to Devin session: https://app.devin.ai/sessions/280f53a344ef4e7d8460adc0ff3bd7c0