Skip to content

fix(responses): keep the provider code and message on top-level stream error events - #46438

Merged
mateo-berri merged 8 commits into
mainfrom
litellm_responses_bridge_error_event_message
Oct 14, 2026
Merged

mateo-berri merged 8 commits into
mainfrom
litellm_responses_bridge_error_event_message

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • OpenAI documents stream error events with top-level code and message
  • LiteLLM only read a nested error object, so those fields were dropped
  • Callers got "Response API in-stream error" and a 500, even for a rate limit

How it solves it:

  • ErrorEvent accepts the documented top-level code, message and param
  • The stream iterator falls back to those fields when no nested error exists, the WebSocket path keeps numeric codes, and the ChatGPT path keeps the top-level message

This is hardening for a documented shape. Every live OpenAI stream failure we could trigger (an unreachable MCP server) sent the nested error object, which main already reads, so the top-level cases run against a local server that replays OpenAI's documented events

The ticket's finish_reason="stop" symptom is a stream closing without a terminal event. #43133 fixed that in v1.105.0, so this PR resolves the ticket together with it, and the customer, now on v1.104.2, needs v1.105.0 or later

User Flow

Before: a developer streaming OpenAI through the Responses bridge loses OpenAI's reason when the stream ends in a top-level error event

  1. They call litellm.completion(model="openai/responses/gpt-5.5", stream=True), Router.acompletion(...), or POST https://litellm-domain/v1/chat/completions with "stream": true
  2. OpenAI streams part of the answer, then an error event with code and message at the top level
  3. The error they get reads "Response API in-stream error", and rate_limit_exceeded also comes back as a 500

After: the same failure carries OpenAI's own code and message

  1. Same call
  2. Same partial answer and error event
  3. The error reads OpenAI's message, and rate_limit_exceeded raises a 429 RateLimitError (HTTP 429 on the proxy)

Linear ticket

Resolves LIT-9574

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
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

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

Each leg runs a 2-worker proxy with no DB from its own worktree. OpenAI cannot send a top-level error event on demand, so those cases use a local server replaying OpenAI's documented events. The MCP failure and healthy cases call OpenAI for real

Case Before After
SDK completion(), error event 500, generic message 500, OpenAI's message
SDK Router, rate limit event 500, generic message 429 RateLimitError
SDK responses(), error event 500, generic message 500, OpenAI's message
Chat completions, error event Error chunk, generic message Error chunk, OpenAI's message
Chat completions, rate limit event HTTP 500 HTTP 429
Responses, error event response.failed, generic message response.failed, OpenAI's message
Messages, error event event: error, generic message event: error, OpenAI's message
Real gpt-5.5, dead MCP server 500 with OpenAI's 424 Same
Real gpt-5.5, healthy stream stop, real usage Same
Replay server, SDK script and proxy config, to rerun the legs

The server_error replay sends response.created, one text delta, then {"type": "error", "code": "server_error", "message": "An error occurred while processing your request. ..."}. The rate_limit replay sends response.created, then the same event with rate_limit_exceeded. On each commit, run the replay server, a proxy with this config, the SDK script, and the curls under each leg

python replay_upstream.py 8765 &
sed s/RP_PORT/8765/ proxy_config.yaml > config.yaml
litellm --config config.yaml --port 4123 --num_workers 2 &
python sdk_cases.py http://127.0.0.1:8765

replay_upstream.py

import json
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer


def frame(event):
    return f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode()


def response_object(status):
    return {"id": "resp_replay", "object": "response", "created_at": 1, "status": status, "model": "gpt-5.5", "output": [], "usage": None}


CREATED = {"type": "response.created", "sequence_number": 0, "response": response_object("in_progress")}
DELTA = {"type": "response.output_text.delta", "item_id": "msg_replay", "output_index": 0, "content_index": 0, "delta": "The sky looks blue because the", "sequence_number": 1}
SERVER_ERROR = {"type": "error", "sequence_number": 2, "code": "server_error", "message": "An error occurred while processing your request. You can retry your request.", "param": None}
RATE_LIMIT = {"type": "error", "sequence_number": 1, "code": "rate_limit_exceeded", "message": "Rate limit reached for gpt-5.5 on tokens per min (TPM): Limit 30000, Used 30000, Requested 900. Please try again in 1.8s.", "param": None}
RATE_LIMIT_NESTED = {"type": "error", "sequence_number": 1, "error": {"type": "tokens", "code": "rate_limit_exceeded", "message": RATE_LIMIT["message"], "param": None}}
SCENARIOS = {"server_error": (CREATED, DELTA, SERVER_ERROR), "rate_limit": (CREATED, RATE_LIMIT), "rate_limit_nested": (CREATED, RATE_LIMIT_NESTED)}


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        self.rfile.read(int(self.headers.get("content-length") or 0))
        events = SCENARIOS.get(self.path.strip("/").split("/")[0])
        if events is None:
            self.send_response(404)
            self.end_headers()
            return
        self.send_response(200)
        self.send_header("content-type", "text/event-stream")
        self.end_headers()
        for event in events:
            self.wfile.write(frame(event))
            self.wfile.flush()

    def log_message(self, fmt, *args):
        sys.stderr.write(f"replay {self.command} {self.path}\n")


ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), Handler).serve_forever()

proxy_config.yaml

model_list:
  - model_name: gpt-replay-server-error
    litellm_params: {model: openai/responses/gpt-5.5, api_base: "http://127.0.0.1:RP_PORT/server_error/v1", api_key: sk-replay}
  - model_name: gpt-replay-rate-limit
    litellm_params: {model: openai/responses/gpt-5.5, api_base: "http://127.0.0.1:RP_PORT/rate_limit/v1", api_key: sk-replay}
  - model_name: responses-replay-server-error
    litellm_params: {model: openai/gpt-5.5, api_base: "http://127.0.0.1:RP_PORT/server_error/v1", api_key: sk-replay}
  - model_name: gpt-5.5-live
    litellm_params: {model: openai/responses/gpt-5.5, api_key: os.environ/OPENAI_API_KEY}
router_settings:
  num_retries: 0

sdk_cases.py

import asyncio
import os
import sys

import litellm
from litellm import Router

ROOT = sys.argv[1]
MESSAGES = [{"role": "user", "content": "Explain in one paragraph why the sky is blue."}]
DEAD_MCP = [{"type": "mcp", "server_label": "deadsrv", "server_url": "https://example.com/mcp-9574", "require_approval": "never"}]
LIVE = {"api_key": os.environ["OPENAI_API_KEY"]}


def summarize(label, text, finish, usage, error):
    print(f"### {label}")
    print(f"text received: {text!r}")
    if error is None:
        print(f"finish_reason: {finish}  usage: {usage}")
    else:
        print(f"raised: {type(error).__name__}  status_code: {getattr(error, 'status_code', None)}")
        print(f"message: {str(error)[:260]}")
    print()


def run_sync(label, **kwargs):
    text, finish, usage = "", None, None
    try:
        for chunk in litellm.completion(stream=True, num_retries=0, **kwargs):
            choice = chunk.choices[0] if chunk.choices else None
            if choice is not None:
                text += choice.delta.content or ""
                finish = choice.finish_reason or finish
            usage = getattr(chunk, "usage", None) or usage
        summarize(label, text, finish, usage and (usage.prompt_tokens, usage.completion_tokens), None)
    except Exception as error:
        summarize(label, text, finish, None, error)


async def run_router(label, deployment, **kwargs):
    router = Router(model_list=[{"model_name": "gpt", "litellm_params": deployment}], num_retries=0)
    text = ""
    try:
        response = await router.acompletion(model="gpt", messages=MESSAGES, stream=True, **kwargs)
        async for chunk in response:
            text += (chunk.choices[0].delta.content or "") if chunk.choices else ""
        summarize(label, text, None, None, None)
    except Exception as error:
        summarize(label, text, None, None, error)


def run_responses(label, **kwargs):
    events = []
    try:
        for event in litellm.responses(stream=True, input="Explain in one paragraph why the sky is blue.", **kwargs):
            events.append(str(getattr(event, "type", "?")))
        print(f"### {label}\nevents: {events}\nno error raised\n")
    except Exception as error:
        print(f"### {label}\nevents: {events}\nraised: {type(error).__name__}  status_code: {getattr(error, 'status_code', None)}\nmessage: {str(error)[:260]}\n")


print("litellm imported from", os.path.dirname(litellm.__file__))
run_sync("completion() on a stream ending in an OpenAI error event", model="openai/responses/gpt-5.5", api_base=f"{ROOT}/server_error/v1", api_key="sk-replay", messages=MESSAGES)
asyncio.run(run_router("Router.acompletion() on a stream that opens with an OpenAI rate limit error event", {"model": "openai/responses/gpt-5.5", "api_base": f"{ROOT}/rate_limit/v1", "api_key": "sk-replay"}))
run_responses("responses() on a stream ending in an OpenAI error event", model="openai/gpt-5.5", api_base=f"{ROOT}/server_error/v1", api_key="sk-replay")
run_sync("completion() on a real OpenAI gpt-5.5 stream that fails mid-stream (unreachable MCP server)", model="openai/responses/gpt-5.5", messages=MESSAGES, tools=DEAD_MCP, reasoning_effort="low", max_tokens=64, **LIVE)
asyncio.run(run_router("Router.acompletion() on the same real OpenAI failure", {"model": "openai/responses/gpt-5.5", **LIVE}, tools=DEAD_MCP, reasoning_effort="low", max_tokens=64))
run_sync("completion() on a healthy real OpenAI gpt-5.5 stream", model="openai/responses/gpt-5.5", messages=[{"role": "user", "content": "Reply with exactly: the bridge is healthy"}], reasoning_effort="low", stream_options={"include_usage": True}, **LIVE)

Before (493ed61)

SDK completion(), stream ending in an error event

  1. litellm.completion(model="openai/responses/gpt-5.5", api_base=<replay>/server_error/v1, stream=True)
  2. Chunk 'The sky looks blue because the', then MidStreamFallbackError 500 Response API in-stream error

SDK Router.acompletion(), stream opening with a rate limit event

Steps and output
  1. Router(...).acompletion(model="gpt", stream=True) on <replay>/rate_limit/v1
  2. InternalServerError 500 Response API in-stream error

SDK responses(), stream ending in an error event

Steps and output
  1. litellm.responses(model="openai/gpt-5.5", api_base=<replay>/server_error/v1, stream=True)
  2. A text delta, then MidStreamFallbackError 500 Response API in-stream error

POST /v1/chat/completions, stream ending in an error event

Steps and output
  1. curl -sN $PROXY/v1/chat/completions -d '{"model":"gpt-replay-server-error","stream":true,...}'
  2. HTTP 200, the text chunk, then an error chunk with Response API in-stream error

POST /v1/chat/completions, stream opening with a rate limit event

Steps and output
  1. curl -sN $PROXY/v1/chat/completions -d '{"model":"gpt-replay-rate-limit","stream":true,...}'
  2. HTTP 500, internal_server_error, Response API in-stream error

POST /v1/responses, stream ending in an error event

Steps and output
  1. curl -sN $PROXY/v1/responses -d '{"model":"responses-replay-server-error","stream":true,...}'
  2. HTTP 200, a text delta, then response.failed with Response API in-stream error

POST /v1/messages, stream ending in an error event

Steps and output
  1. curl -sN $PROXY/v1/messages -d '{"model":"gpt-replay-server-error","stream":true,...}'
  2. HTTP 200, the text delta, then event: error with api_error and Response API in-stream error

Real OpenAI gpt-5.5 stream failing on an unreachable MCP server

Steps and output
  1. litellm.completion(..., tools=[<MCP tool at a dead URL>], stream=True), then via Router and the proxy
  2. a 500 on all three with OpenAI's Error retrieving tool list from MCP server ... 424

Healthy real OpenAI gpt-5.5 stream

Steps and output
  1. litellm.completion(..., stream=True, stream_options={"include_usage": True}), then via the proxy
  2. 'the bridge is healthy', finish_reason stop, real usage
Raw output, SDK cases
### completion() on a stream ending in an OpenAI error event
text received: 'The sky looks blue because the'
raised: MidStreamFallbackError  status_code: 500
message: litellm.MidStreamFallbackError: litellm.InternalServerError: InternalServerError: OpenAIException - Response API in-stream error Original exception: InternalServerError: litellm.InternalServerError: InternalServerError: OpenAIException - Response API in-stream
### Router.acompletion() on a stream that opens with an OpenAI rate limit error event
text received: ''
raised: InternalServerError  status_code: 500
message: litellm.InternalServerError: InternalServerError: OpenAIException - Response API in-stream error
### responses() on a stream ending in an OpenAI error event
events: ['ResponsesAPIStreamEvents.RESPONSE_CREATED', 'ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA']
raised: MidStreamFallbackError  status_code: 500
message: litellm.MidStreamFallbackError: litellm.InternalServerError: InternalServerError: OpenAIException - Response API in-stream error Original exception: InternalServerError: litellm.InternalServerError: InternalServerError: OpenAIException - Response API in-stream
### completion() on a real OpenAI gpt-5.5 stream that fails mid-stream (unreachable MCP server)
text received: ''
raised: MidStreamFallbackError  status_code: 500
message: litellm.MidStreamFallbackError: litellm.InternalServerError: InternalServerError: OpenAIException - Error retrieving tool list from MCP server: 'deadsrv'. Http status code: 424 (Failed Dependency) Original exception: InternalServerError: litellm.InternalServer
### Router.acompletion() on the same real OpenAI failure
text received: ''
raised: InternalServerError  status_code: 500
message: litellm.InternalServerError: InternalServerError: OpenAIException - Error retrieving tool list from MCP server: 'deadsrv'. Http status code: 424 (Failed Dependency)
### completion() on a healthy real OpenAI gpt-5.5 stream
text received: 'the bridge is healthy'
finish_reason: stop  usage: (14, 19)
Raw output, proxy cases
### chat completions, stream ending in an OpenAI error event
$ curl -sN /v1/chat/completions -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"gpt-replay-server-error","stream":true,"messages":[{"role":"user","content":"Explain in one paragraph why the sky is blue."}]}'
data: {"id":"resp_replay","object":"chat.completion.chunk","created":1792011348,"model":"gpt-replay-server-error","choices":[{"index":0,"delta":{"role":"assistant","content":"The sky looks blue because the"}}]}
data: {"error": {"message": "litellm.InternalServerError: InternalServerError: OpenAIException - Response API in-stream error", "type": "internal_server_error", "param": null, "code": "500"}}
HTTP 200

### chat completions, stream opening with an OpenAI rate limit error event
$ curl -sN /v1/chat/completions -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"gpt-replay-rate-limit","stream":true,"messages":[{"role":"user","content":"Explain in one paragraph why the sky is blue."}]}'
{"error":{"message":"litellm.InternalServerError: InternalServerError: OpenAIException - Response API in-stream error","type":"internal_server_error","param":null,"code":"500"}}
HTTP 500

### responses, stream ending in an OpenAI error event
$ curl -sN /v1/responses -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"responses-replay-server-error","stream":true,"input":"Explain in one paragraph why the sky is blue."}'
data: {"type":"response.created","response":{"id":"resp_hqZZ-ZnnIRcs-Hc2OmEFgkSf90iMdBQcjeEestd2CGM3qu4CmJeYQBI4o-qtq2-bd_a9PfeAG6Q4_9_XYVRXgH4QAbdbatnfxI3GHy-4wkKamwdYRmAWZJZAm7NIyCmwvNCa1NyEcaqMg094nycDJoPJQJ738djANkGGgX0VzpeXfHZSyzLln6Bh5aXavVfpZLjC7Qy6qusOmPSQby9prJV_7y9nni00PQfpIkGH-yy-zu4XOCI2IcJT1a3gIm0NNXmQp5Qs1EFbu_nk1W4yeeZXzprkiy0EbYn4f_WxNhBKXc7Wjzvi8OF0eG295p9I2rgDZmTf9HEsx_QneWmqlojEZVbnACt5EaggxAbMFGwz
data: {"type":"response.output_text.delta","item_id":"msg_replay","output_index":0,"content_index":0,"delta":"The sky looks blue because the","sequence_number":1,"model":"responses-replay-server-error"}
event: response.failed
data: {"type":"response.failed","response":{"id":"resp_hqZZ-ZnnIRcs-Hc2OmEFgkSf90iMdBQcjeEestd2CGM3qu4CmJeYQBI4o-qtq2-bd_a9PfeAG6Q4_9_XYVRXgH4QAbdbatnfxI3GHy-4wkKamwdYRmAWZJZAm7NIyCmwvNCa1NyEcaqMg094nycDJoPJQJ738djANkGGgX0VzpeXfHZSyzLln6Bh5aXavVfpZLjC7Qy6qusOmPSQby9prJV_7y9nni00PQfpIkGH-yy-zu4XOCI2IcJT1a3gIm0NNXmQp5Qs1EFbu_nk1W4yeeZXzprkiy0EbYn4f_WxNhBKXc7Wjzvi8OF0eG295p9I2rgDZmTf9HEsx_QneWmqlojEZVbnACt5EaggxAbMFGwzU
data: [DONE]
HTTP 200

### messages, stream ending in an OpenAI error event
$ curl -sN /v1/messages -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"gpt-replay-server-error","stream":true,"max_tokens":256,"messages":[{"role":"user","content":"Explain in one paragraph why the sky is blue."}]}'
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "The sky looks blue because the"}}
event: error
data: {"type": "error", "error": {"type": "api_error", "message": "litellm.InternalServerError: InternalServerError: OpenAIException - Response API in-stream error"}}
HTTP 200

### chat completions, real OpenAI gpt-5.5 stream that fails mid-stream (unreachable MCP server)
$ curl -sN /v1/chat/completions -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"gpt-5.5-live","stream":true,"max_tokens":64,"reasoning_effort":"low","tools":[{"type":"mcp","server_label":"deadsrv","server_url":"https://example.com/mcp-9574","require_approval":"never"}],"messages":[{"role":"user","content":"say hi"}]}'
{"error":{"message":"litellm.InternalServerError: InternalServerError: OpenAIException - Error retrieving tool list from MCP server: 'deadsrv'. Http status code: 424 (Failed Dependency)","type":"internal_server_error","param":null,"code":"500"}}
HTTP 500

### chat completions, healthy real OpenAI gpt-5.5 stream
$ curl -sN /v1/chat/completions -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"gpt-5.5-live","stream":true,"reasoning_effort":"low","stream_options":{"include_usage":true},"messages":[{"role":"user","content":"Reply with exactly: the bridge is healthy"}]}'
data: {"id":"resp_07fd74c3ff350180006acfec56df9087d28279befcad4c1b79","object":"chat.completion.chunk","created":1792011351,"model":"gpt-5.5-live","service_tier":"auto","choices":[{"index":0,"delta":{"content":" is"}}]}
data: {"id":"resp_07fd74c3ff350180006acfec56df9087d28279befcad4c1b79","object":"chat.completion.chunk","created":1792011351,"model":"gpt-5.5-live","service_tier":"auto","choices":[{"index":0,"delta":{"content":" healthy"}}]}
data: {"id":"resp_07fd74c3ff350180006acfec56df9087d28279befcad4c1b79","created":1792011351,"model":"gpt-5.5-live","object":"chat.completion.chunk","choices":[{"finish_reason":"stop","index":0,"delta":{}}],"provider_specific_fields":{"access_programs":{"cyber":"daybreak_blue"},"frequency_penalty":0.0,"presence_penalty":0.0,"service_tier":"default","tool_usage":{"image_gen":{"input_tokens":0,"input_tokens_details":{"im
data: {"id":"resp_07fd74c3ff350180006acfec56df9087d28279befcad4c1b79","created":1792011351,"model":"gpt-5.5-live","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"usage":{"completion_tokens":8,"prompt_tokens":14,"total_tokens":22,"completion_tokens_details":{"reasoning_tokens":0},"prompt_tokens_details":{"cached_tokens":0,"cache_write_tokens":0,"cache_creation_tokens":0},"cost":0.00031},"service_t
data: [DONE]
HTTP 200

After (d8552da)

SDK completion(), stream ending in an error event

  1. Same call
  2. Chunk 'The sky looks blue because the', then MidStreamFallbackError 500 OpenAI's An error occurred ...

SDK Router.acompletion(), stream opening with a rate limit event

Steps and output
  1. Same call
  2. RateLimitError 429 Rate limit reached for gpt-5.5 ...

SDK responses(), stream ending in an error event

Steps and output
  1. Same call
  2. A text delta, then MidStreamFallbackError 500 OpenAI's An error occurred ...

POST /v1/chat/completions, stream ending in an error event

Steps and output
  1. Same call
  2. HTTP 200, the text chunk, then an error chunk with OpenAI's An error occurred ...

POST /v1/chat/completions, stream opening with a rate limit event

Steps and output
  1. Same call
  2. HTTP 429, throttling_error, Rate limit reached for gpt-5.5 ...

POST /v1/responses, stream ending in an error event

Steps and output
  1. Same call
  2. HTTP 200, a text delta, then response.failed with OpenAI's An error occurred ...

POST /v1/messages, stream ending in an error event

Steps and output
  1. Same call
  2. HTTP 200, the text delta, then event: error with api_error and OpenAI's An error occurred ...

Real OpenAI gpt-5.5 stream failing on an unreachable MCP server

Steps and output
  1. Same call
  2. Same as Before

Healthy real OpenAI gpt-5.5 stream

Steps and output
  1. Same call
  2. Same as Before
Raw output, SDK cases
### completion() on a stream ending in an OpenAI error event
text received: 'The sky looks blue because the'
raised: MidStreamFallbackError  status_code: 500
message: litellm.MidStreamFallbackError: litellm.InternalServerError: InternalServerError: OpenAIException - An error occurred while processing your request. You can retry your request. Original exception: InternalServerError: litellm.InternalServerError: InternalServe
### Router.acompletion() on a stream that opens with an OpenAI rate limit error event
text received: ''
raised: RateLimitError  status_code: 429
message: litellm.RateLimitError: RateLimitError: OpenAIException - Rate limit reached for gpt-5.5 on tokens per min (TPM): Limit 30000, Used 30000, Requested 900. Please try again in 1.8s.
### responses() on a stream ending in an OpenAI error event
events: ['ResponsesAPIStreamEvents.RESPONSE_CREATED', 'ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA']
raised: MidStreamFallbackError  status_code: 500
message: litellm.MidStreamFallbackError: litellm.InternalServerError: InternalServerError: OpenAIException - An error occurred while processing your request. You can retry your request. Original exception: InternalServerError: litellm.InternalServerError: InternalServe
### completion() on a real OpenAI gpt-5.5 stream that fails mid-stream (unreachable MCP server)
text received: ''
raised: MidStreamFallbackError  status_code: 500
message: litellm.MidStreamFallbackError: litellm.InternalServerError: InternalServerError: OpenAIException - Error retrieving tool list from MCP server: 'deadsrv'. Http status code: 424 (Failed Dependency) Original exception: InternalServerError: litellm.InternalServer
### Router.acompletion() on the same real OpenAI failure
text received: ''
raised: InternalServerError  status_code: 500
message: litellm.InternalServerError: InternalServerError: OpenAIException - Error retrieving tool list from MCP server: 'deadsrv'. Http status code: 424 (Failed Dependency)
### completion() on a healthy real OpenAI gpt-5.5 stream
text received: 'the bridge is healthy'
finish_reason: stop  usage: (14, 8)
Raw output, proxy cases
### chat completions, stream ending in an OpenAI error event
$ curl -sN /v1/chat/completions -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"gpt-replay-server-error","stream":true,"messages":[{"role":"user","content":"Explain in one paragraph why the sky is blue."}]}'
data: {"id":"resp_replay","object":"chat.completion.chunk","created":1792014794,"model":"gpt-replay-server-error","choices":[{"index":0,"delta":{"role":"assistant","content":"The sky looks blue because the"}}]}
data: {"error": {"message": "litellm.InternalServerError: InternalServerError: OpenAIException - An error occurred while processing your request. You can retry your request.", "type": "internal_server_error", "param": null, "code": "500"}}
HTTP 200

### chat completions, stream opening with an OpenAI rate limit error event
$ curl -sN /v1/chat/completions -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"gpt-replay-rate-limit","stream":true,"messages":[{"role":"user","content":"Explain in one paragraph why the sky is blue."}]}'
{"error":{"message":"litellm.RateLimitError: RateLimitError: OpenAIException - Rate limit reached for gpt-5.5 on tokens per min (TPM): Limit 30000, Used 30000, Requested 900. Please try again in 1.8s.","type":"throttling_error","param":null,"code":"429"}}
HTTP 429

### responses, stream ending in an OpenAI error event
$ curl -sN /v1/responses -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"responses-replay-server-error","stream":true,"input":"Explain in one paragraph why the sky is blue."}'
data: {"type":"response.created","response":{"id":"resp_wj1tgiPIj_OkPr5VEyPNeUvZr9PFv8JXezYF8i6rYB1xohTofbKb8hwpy4J-bRcdxhida8sLwo2Ih8iqHSCu-8cMPV1WarCW9HvHKskBKC1b8RO27SDdyzfUoL-fJX3nV4y-5SxRcw5z7EKtpZj3zetqPHfEKJk-rxeu_JOKFNquIGwUlPDRfOzQcdCjrme1gjwLQIEJard97jztN9Vz7VJRKOfJM-oPIN4A1pI3RPVkjw-Lyp2ak4VDg7cZusPaTTmc82PL0WpKOxnufWVt04pFQuWwHiHS2D11xEHgS0HtL0QCQaU9Bez-rftZorKjDXLEzUBt7GOgDxYkPzjXOd_iZJoDyZ3cVxZV4n-Z0dDF
data: {"type":"response.output_text.delta","item_id":"msg_replay","output_index":0,"content_index":0,"delta":"The sky looks blue because the","sequence_number":1,"model":"responses-replay-server-error"}
event: response.failed
data: {"type":"response.failed","response":{"id":"resp_wj1tgiPIj_OkPr5VEyPNeUvZr9PFv8JXezYF8i6rYB1xohTofbKb8hwpy4J-bRcdxhida8sLwo2Ih8iqHSCu-8cMPV1WarCW9HvHKskBKC1b8RO27SDdyzfUoL-fJX3nV4y-5SxRcw5z7EKtpZj3zetqPHfEKJk-rxeu_JOKFNquIGwUlPDRfOzQcdCjrme1gjwLQIEJard97jztN9Vz7VJRKOfJM-oPIN4A1pI3RPVkjw-Lyp2ak4VDg7cZusPaTTmc82PL0WpKOxnufWVt04pFQuWwHiHS2D11xEHgS0HtL0QCQaU9Bez-rftZorKjDXLEzUBt7GOgDxYkPzjXOd_iZJoDyZ3cVxZV4n-Z0dDFD
data: [DONE]
HTTP 200

### messages, stream ending in an OpenAI error event
$ curl -sN /v1/messages -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"gpt-replay-server-error","stream":true,"max_tokens":256,"messages":[{"role":"user","content":"Explain in one paragraph why the sky is blue."}]}'
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "The sky looks blue because the"}}
event: error
data: {"type": "error", "error": {"type": "api_error", "message": "litellm.InternalServerError: InternalServerError: OpenAIException - An error occurred while processing your request. You can retry your request."}}
HTTP 200

### chat completions, real OpenAI gpt-5.5 stream that fails mid-stream (unreachable MCP server)
$ curl -sN /v1/chat/completions -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"gpt-5.5-live","stream":true,"max_tokens":64,"reasoning_effort":"low","tools":[{"type":"mcp","server_label":"deadsrv","server_url":"https://example.com/mcp-9574","require_approval":"never"}],"messages":[{"role":"user","content":"say hi"}]}'
{"error":{"message":"litellm.InternalServerError: InternalServerError: OpenAIException - Error retrieving tool list from MCP server: 'deadsrv'. Http status code: 424 (Failed Dependency)","type":"internal_server_error","param":null,"code":"500"}}
HTTP 500

### chat completions, healthy real OpenAI gpt-5.5 stream
$ curl -sN /v1/chat/completions -H 'Authorization: Bearer $LITELLM_MASTER_KEY' -H 'Content-Type: application/json' -d '{"model":"gpt-5.5-live","stream":true,"reasoning_effort":"low","stream_options":{"include_usage":true},"messages":[{"role":"user","content":"Reply with exactly: the bridge is healthy"}]}'
data: {"id":"resp_0c3370972d295e24006acff9cc449c87d282118cd696427946","object":"chat.completion.chunk","created":1792014796,"model":"gpt-5.5-live","service_tier":"auto","choices":[{"index":0,"delta":{"content":" is"}}]}
data: {"id":"resp_0c3370972d295e24006acff9cc449c87d282118cd696427946","object":"chat.completion.chunk","created":1792014796,"model":"gpt-5.5-live","service_tier":"auto","choices":[{"index":0,"delta":{"content":" healthy"}}]}
data: {"id":"resp_0c3370972d295e24006acff9cc449c87d282118cd696427946","created":1792014796,"model":"gpt-5.5-live","object":"chat.completion.chunk","choices":[{"finish_reason":"stop","index":0,"delta":{}}],"provider_specific_fields":{"access_programs":{"cyber":"daybreak_blue"},"frequency_penalty":0.0,"presence_penalty":0.0,"service_tier":"default","tool_usage":{"image_gen":{"input_tokens":0,"input_tokens_details":{"im
data: {"id":"resp_0c3370972d295e24006acff9cc449c87d282118cd696427946","created":1792014796,"model":"gpt-5.5-live","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"usage":{"completion_tokens":8,"prompt_tokens":14,"total_tokens":22,"completion_tokens_details":{"reasoning_tokens":0},"prompt_tokens_details":{"cached_tokens":0,"cache_write_tokens":0,"cache_creation_tokens":0},"cost":0.00031},"service_t
data: [DONE]
HTTP 200

Seen on both legs and unchanged by this PR:

  • OpenAI's MCP 424 reaches clients as a 500
  • completion() raises the wrapper error, Router the inner one
  • /v1/responses turns OpenAI's error event into response.failed
  • A Pydantic ResponseAPIUsage serializer warning prints on healthy streams

/live-pr-risk at d8552da

Verdict: no dependent path broke on the routes we ran live at the tip and the merge base 493ed61. The changes a client or operator can see are listed below as backward incompatible, each one intended by this PR

Breaking

None observed. Every scenario above ran on both sides, and the only differences are the ones this PR names

Backward incompatible

  • A stream whose error event carries a top-level code now raises that code's status (429 RateLimitError for rate_limit_exceeded) with OpenAI's message, where it raised a 500 "Response API in-stream error". Clients and the router now retry, fall back, and cool down on it like any 429. Intended, it is the ticket's ask
  • ErrorEvent.error is now optional, since a top-level error event has no nested object. SDK code that reads event.error.message on such an event has to handle None. Events with the nested shape still fill it. model_dump() of any ErrorEvent now also carries code, message and param, None on the nested shape, which the proxy drops with exclude_none
  • A top-level 4xx code such as invalid_prompt now raises BadRequestError 400, so the Router no longer falls back on it. At 493ed61 it raised a generic 500 and the fallback answered. Intended, the nested shape already gets the 400 on main, and test_bridged_invalid_prompt_answers_a_bad_request_without_trying_the_fallback checks both shapes

Regression risk

  • A top-level rate_limit_exceeded now cools its deployment down. On main, a mid-stream 429 that falls back sometimes cools down the healthy fallback deployment too (3 of 24 requests on /v1/responses with the nested shape at 493ed61). This PR leaves that race as it is, and it is tracked separately
  • The chatgpt/ provider's non-stream path reads only the message of an error event, never its code, for both shapes. A top-level error that does not say "rate limit" keeps the HTTP status, as a nested one does on main

Dependency graph

Dependent Entry Status
Responses stream failure /v1/responses stream verified-live
Responses bridge on chat /v1/chat/completions stream verified-live
Responses bridge on messages /v1/messages stream verified-live
Router mid-stream fallback Router.acompletion verified-live
Router cooldown on a 429 two-deployment group pre-existing race
ErrorEvent constructors MCP, guardrail translation tested
ChatGPT error parsing chatgpt/ provider tested
WebSocket error parsing Responses WebSocket mode tested

Not verified

  • A real OpenAI stream that sends a top-level error event. The live API nests it in every failure we could trigger, so that shape ran against a replay upstream
  • The chatgpt/ provider and Responses WebSocket mode against the real services. Both ran against local wire servers only

Audit round 4 of 3 (past the cap: the round-3 tip's logging wait was reverted)

Head d8552da against base 493ed61 on rig lit9574au, with seed 46438 and order seed 9574. Head lanes are head-run1/run2-{providers,sdk,chaos}-r4d, and controls are ctl-{providers,sdk}-r4d. Base lanes are base-providers-r3 and base-sdk-r3, plus base-chaos-r4 for X1 and X2, which ran after the chaos fix in 67b2752. The base leg's test files match d8552da's

id cell base head 1 head 2
C1 chat, OpenAI SDK, 429 red green green
C2 chat codex, async SDK, 429 red green green
C3 chat, raw error event red green green
C4 chat, insufficient_quota red green green
C5 chat, server_error red green green
C6 chat, invalid_prompt 400 red green green
C7 chat, context_length 400 red green green
C8 chat, code "503" red green green
C9 chat, unknown code 500 red green green
C10 chat, error after text red green green
C11 nested beats top level green green green
C12 error: null red green green
C13 integer code 429 red green green
C14 empty code red green green
C15a empty message red green green
C15b object message red green green
C16 5 KB message red green green
C17 duplicated code red green green
C18 never cached red green green
C19 429 falls back green green green
C20n nested 400, no fallback green green green
C20t top-level 400, no fallback red green green
R1 /v1/responses 429 red green green
R2 responses SDK, quota red green green
R3 responses async, 500 red green green
R4 responses, after text red green green
M1 /v1/messages 429 red green green
M2 Anthropic async SDK red green green
M3 Anthropic sync SDK red green green
S1 completion() 500 red green green
S2 acompletion() 429 red green green
S3 Router async 429 red green green
S4 Router sync, no fallback red green green
S5 Router fallback green green green
S6 responses() sync red green green
S7 aresponses() quota red green green
G1 chatgpt stream red green green
G2 chatgpt non-stream red green green
W1 websocket spend row red green green
X1 chaos burst red green green
X2 chaos worker kill red green green
ctl 25 controls n/a green n/a

C11, C19, C20n and S5 are parity rows, so they are green on both legs by design. The chaos lanes ran X1 and X2 with both variants in one session, with the second SIGKILL after the first. Rounds 1 and 2 at 08e7650 found C13, G2 and W1 red on both head runs, and 6380fbf fixed them. Round 3 at 3b2709a was all green. Round 4 at f4b446b was stopped when the logging wait was reverted

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • A top-level 4xx such as invalid_prompt now answers 400 and skips the Router fallback, where main fell back and answered. The nested shape already does this on main
  • A top-level rate limit now cools its deployment down, so it reaches a race main already has with the nested shape, where a mid-stream 429 that falls back can also cool down the healthy fallback. That race is tracked separately

Low

  • OpenAI cannot send a top-level error event on demand, so that shape ran against a replay of its documented events. The replay server and SDK script are in the proof section
  • The ticket's finish_reason="stop" fix is fix(responses): fall back on pre-output stream drops, fail truncated streams, honor request_timeout #43133 in v1.105.0, so the customer needs that version too
  • Proxy clients get "code":"429" or "500", the HTTP status, not OpenAI's string code, the same as every other proxy error
  • ErrorEvent accepts a top-level param, but nothing reads it downstream, the same as with the nested shape
  • ErrorEvent.error is now optional, so typed SDK code that reads event.error.message on a top-level event has to handle None, and SDK dumps of any ErrorEvent now carry null for code, message and param
  • The chatgpt/ non-stream path still maps errors by message text and HTTP status, never by code, for both shapes

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

Link to Devin session: https://app.devin.ai/sessions/f9e767de340e4d9e91d35e0b3a56a9f3
Open in Devin Desktop: https://app.devin.ai/desktop/session/f9e767de340e4d9e91d35e0b3a56a9f3?variant=devin


Note

Medium Risk
Changes mid-stream error parsing and HTTP status mapping across Responses streaming, bridges, WebSocket, and Router fallback/cooldown paths; behavior shifts (e.g. 429 vs 500) are intentional but affect production retry and routing semantics.

Overview
OpenAI Responses streams can emit error events with top-level code and message (not only a nested error object). This PR teaches LiteLLM to read that shape end-to-end so mid-stream failures keep the provider’s code and text instead of collapsing to a generic 500 “Response API in-stream error”.

ErrorEvent now allows an optional nested error and optional top-level code, message, and param. Shared helpers in the Responses stream iterator build an error object from nested fields when present, otherwise from top-level message/code (including numeric codes). That path is used for HTTP streaming, the Responses WebSocket bridge, and ChatGPT SSE aggregation when no nested error exists.

Downstream behavior changes are intentional: e.g. rate_limit_exceeded surfaces as 429 / RateLimitError with the upstream message across chat bridge, /v1/responses, /v1/messages, Router streaming, and fallbacks where eligible. Integration and unit tests cover nested vs top-level shapes, malformed fields, cache behavior, and ChatGPT non-stream errors.

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

…m error events

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

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.

Stale Bugbot comment from a previous run.

@litereview

litereview Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

The PR description no longer claims the router cooldown fix. It now lists the mid-stream 429 cooldown race as a pre-existing issue that is tracked separately, so the earlier finding is fixed.

Checks and execution details
  • Passed · Real testing evidence (required): In scope: litellm/llms/chatgpt/responses/transformation.py now pulls the error message from a top-level message on error and response.failed SSE chunks.

Coverage: tests/integration/providers/test_chatgpt_responses_top_level_error_wire.py drives the proxy at a local wire server. That server replays response.created followed by a top-level {type: error, code: rate_limit_exceeded, message, param: null} event. The tests check that the streamed response.failed carries the provider code and message, and that the aggregated path returns a 429 with the provider message.

Fixture provenance: The installed OpenAI SDK's generated openai/types/responses/response_error_event.py defines ResponseErrorEvent with top-level code, message, param, sequence_number and type. That matches the replayed shape.

Results (local, at head):

  • uv run python tests/integration/run.py providers --workers 4 on the five changed provider and streaming files: 54 passed.

  • The SDK integration file: 12 passed.

  • Passed · Changed unit tests (optional): uv run pytest tests/unit/responses/test_streaming_iterator_error_events.py tests/unit/llms/chatgpt/responses/test_chatgpt_responses_transformation.py tests/unit/responses/test_responses_websocket_all_providers.py -n 4: 241 passed.

  • Passed · Changed integration tests (optional): Ran against local Postgres 15 and Redis 7 after uv sync --all-groups and prisma generate.

  • providers group, 5 files: 54 passed in 149.35s

  • tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py: 12 passed

  • Passed · Caller trace and compatibility (optional): Callers checked: _error_event_error_object returns the nested error when one exists. Otherwise it builds {message, code} from the top-level fields. Its callers are _maybe_raise_for_error_event and _ws_event_error. Both pass the result to _error_event_fields and _map_stream_error_to_exception, which already accept dicts and numeric codes.

Constructors: The in-repo ErrorEvent constructors in the MCP iterator and guardrail handler still set error=.

Compatibility: ErrorEvent.error is now optional, and a top-level rate_limit_exceeded now maps to 429. Both are corrections of a documented provider shape, and the PR description discloses them. Neither breaks a supported contract.


View review · Reviewed d8552da4c8f4

@codspeed

codspeed Bot commented Oct 14, 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

✅ 31 untouched benchmarks


Comparing litellm_responses_bridge_error_event_message (d8552da) with main (f101347)1

Open in CodSpeed

Footnotes

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

@codecov

codecov Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

CustomStreamWrapper now waits for failure logging before it raises the
error the router falls back on, so the cooldown lands on the deployment
that failed instead of the fallback that replaced it. Also keeps numeric
error codes and the top-level message on the WebSocket and ChatGPT paths.
…ls back to another deployment

The router cools a deployment down from a sync failure callback that reads the request's model_info. A failed stream submitted that callback to the logging executor without waiting, so it often ran after the router's fallback had overwritten model_info and cooled down the healthy fallback deployment instead, leaving the model group with no deployments
…dge_error_event_message

# Conflicts:
#	litellm/litellm_core_utils/streaming_handler.py
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 14, 2026

Copy link
Copy Markdown

Review already requested

code-review is already reviewing 3b2709aa5217. View existing review.

async def test_worker_sigkill_mid_burst_leaves_the_sibling_answering_the_bridged_streams(rig: _Rig) -> None:
calls: Final = _calls(20, _CHAT_KINDS)
@pytest.mark.parametrize("kinds", [_CHAT_KINDS, _TOP_LEVEL_CHAT_KINDS], ids=["nested", "top_level"])
async def test_worker_sigkill_mid_burst_leaves_the_sibling_answering_the_bridged_streams(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Medium · Parametrized SIGKILL chaos test fails because the earlier variant leaves a third worker PID in the shared proxy log

  1. The rig fixture is module-scoped. Both parameters of test_worker_sigkill_mid_burst_leaves_the_sibling_answering_the_bridged_streams share one 2-worker proxy and one log file.
  2. The first variant ([nested]) SIGKILLs a worker, and uvicorn logs Started server process [...] again for the replacement.
  3. The second variant ([top_level], added in this PR) calls _worker_pids(rig.proxy.log, 2). That helper counts every Started server process line in the whole log.
  4. It now sees 3 PIDs, never reaches 2, and fails after 30s with State did not converge: (pid1, pid2, pid3). This happens before any top-level error behavior gets exercised.

Whichever variant runs second hits this. I reproduced it locally in two separate runs. The [top_level] variant passes when it runs alone, so the product code is fine.

Smallest fix: read the live worker PIDs from the process tree (rig.proxy.worker_pids()), or give each parameter its own proxy instead of scanning the cumulative log.

Evidence

Run 1, five changed integration files via tests/integration/run.py providers ... against local Postgres/Redis: 1 failed, 53 passed. The failure was test_worker_sigkill_mid_burst_..._bridged_streams[top_level] → tests/integration/streaming/test_responses_bridge_stream_chaos.py:309 _worker_pids ... AssertionError: State did not converge: (17816, 17815, 18115)

Run 2, the test function only (both params): [nested] PASSED, [top_level] FAILED, State did not converge: (18815, 18816, 19008)

The owned proxy log from run 2 has Started server process [18815], [18816], Child process [18815] died, then Started server process [19008]

Run 3, [top_level] alone: 1 passed in 52.16s

_worker_pids uses _STARTED_WORKER.finditer(log.read_text()) with the predicate len(pids) == count, so killed workers stay in the count

Latest summary by code-review · View this review · Reviewed 3b2709aa5217

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.

Fixed in 67b2752, the chaos test now reads live worker pids from the proxy, so the second SIGKILL variant sees exactly two workers

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Finding withdrawn

The reply is right. The failure came from _worker_pids scanning the shared proxy log with a regex. A worker killed by the [nested] variant stayed in that log, so the [top_level] variant saw three PIDs and never reached two.

At head, _worker_pids polls OwnedProxy.worker_pids(). That method lists the live, serving child processes of the supervisor. By the time the first variant exits replacing_worker, the killed worker has been reaped and its replacement is serving. The second variant therefore sees exactly two PIDs. The module-scoped rig can stay shared because the stale log lines no longer affect the count.

I verified this by reading the code and did not rerun the integration test.

Evidence

tests/integration/streaming/test_responses_bridge_stream_chaos.py:307-308: def _worker_pids(proxy: OwnedProxy, count: int) -> frozenset[int]: return eventually(proxy.worker_pids, lambda pids: len(pids) == count, seconds=30)

tests/integration/streaming/test_responses_bridge_stream_chaos.py:360: workers: Final = _worker_pids(rig.proxy, 2)

tests/integration/_support/process.py:192-197: worker_pids returns frozenset(child.pid for child in psutil.Process(self.process.pid).children() if _is_serving_worker(child))

tests/integration/_support/process.py:259-264: replacing_worker asserts the kill fired, then calls _await_replacement(before). WorkerKill.__call__ waits through _wait_until_gone and _wait_until_reaped.

The _STARTED_WORKER.finditer(log.read_text()) log scan cited in the original finding no longer appears in _worker_pids.

GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.

Reviewed d8552da4c8f4 · View follow-up

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

Waiting for sync failure callbacks before a failed stream raises fixed the router cooldown race, but it slowed healthy calls under many failing streams with a slow callback, since the wait shares a thread pool with every call's start. The race is pre-existing on main and is tracked separately, so this PR goes back to main's logging timing and keeps only the top-level error event changes
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

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 d8552da. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot

litellm-stampbot Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

litellm-stampbot: risk high

Not approved at d8552da. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): high, default behavior change, request hot path, complex diff

  • tier: high (confidence 0.90)
  • change_kind: default_behavior_change (confidence 0.91)
  • blast_radius: request_hot_path (confidence 0.85)
  • complexity: complex (confidence 1.00)

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:high Sensitive, broad, or high-risk change label Oct 14, 2026
@mateo-berri
mateo-berri enabled auto-merge (squash) October 14, 2026 22:39
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@yucheng-berri

Copy link
Copy Markdown
Contributor

@litereview full

@litereview

litereview Bot commented Oct 14, 2026

Copy link
Copy Markdown

✅ full

Scope: full · Full PR review.

Completed · Some checks not run.

Verdict: no actionable defects found

This PR teaches the Responses stream error paths to read OpenAI's documented top-level code/message when an error event carries no nested error object. I followed every dependent I could find, and none of them regress.

What changed

  • ErrorEvent contract (litellm/types/llms/openai.py): error is now optional (None by default), and the event gains optional code, message and param. The model already allowed extra fields, so the old shape still validates.
  • _error_event_error_object (litellm/responses/streaming_iterator.py): it prefers the nested error and falls back to a dict built from top-level message/code. Two call sites use it: _maybe_raise_for_error_event (SDK/proxy streaming) and _ws_event_error (WebSocket failure booking).
  • ChatGPT _extract_error_message: it falls back to a top-level message, but only when that value is a str.

Who depends on it

  • Code that builds ErrorEvent: both producers, OpenAIResponsesHandler.build_stream_error_items (guardrail) and _make_stream_error_event (MCP), still pass a nested ErrorEventError. The nested branch wins, so their behaviour is the same.
  • Code that reads .error off an ErrorEvent: I grepped litellm/ and enterprise/ for .error. and isinstance(..., ErrorEvent). Nothing outside this diff dereferences ErrorEvent.error, so making it optional breaks no attribute access.
  • Serialization: proxy SSE uses model_dump_json(exclude_none=True, exclude_unset=True) and the WebSocket path uses model_dump_json(exclude_none=True). The new None defaults are therefore not written to the wire, and a nested-error event serializes exactly as before.
  • Registry dispatch: get_event_model_class maps ResponsesAPIStreamEvents.ERROR to ErrorEvent. A top-level payload used to fail validation and drop to model_construct. It now validates cleanly. I ran it through transform_streaming_response, which gave (429, 'm') for rate_limit_exceeded and (500, 'nested') for the nested shape, and the code: null coalescing still applies.
  • Anthropic pass-through adapter: it only reads response.failed, so it is untouched.

Caveat on scope

I verified with unit-level drives and the PR's own tests. I did not build the live base-vs-head proxy rig with real provider credentials, so the HTTP 429-vs-500 change on the proxy is reasoned from the mapping code and the unit runs, not observed on a proxy.

Checks and execution details
  • Passed · Streaming-iterator error-event and ChatGPT transformation unit tests (optional): Ran uv run --no-sync pytest tests/unit/responses/test_streaming_iterator_error_events.py tests/unit/llms/chatgpt/responses/test_chatgpt_responses_transformation.py: 110 passed.
  • Passed · WebSocket failure-frame booking tests (optional): Ran pytest tests/unit/responses/test_responses_websocket_all_providers.py -k failure_frames: 3 passed. The first run failed with ModuleNotFoundError: websockets. After uv pip install websockets, all 3 passed.
  • Passed · Event-registry dispatch drive (optional): Pushed three payloads through OpenAIResponsesAPIConfig.transform_streaming_response: top-level, nested with code: null, and top-level with code: null. Each validated to ErrorEvent, serialized without the new None fields, and mapped to 429/500 with the provider message preserved.
  • Not run · Live base-vs-head proxy A/B (live-pr-risk phase 6) (optional): Did not run: the sandbox has no provider credentials and no git history for a base worktree. The change is narrow enough that registry, serialization and dependent sweeps plus unit drives cover the dependents.

View review · Reviewed d8552da4c8f4

@yucheng-berri yucheng-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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants