Skip to content

fix(websearch_interception): drop stream_options when forcing stream=False and replay it on the final stream - #45433

Merged
mateo-berri merged 12 commits into
mainfrom
litellm_websearch_interception_pop_stream_options
Oct 10, 2026
Merged

mateo-berri merged 12 commits into
mainfrom
litellm_websearch_interception_pop_stream_options

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Streamed web search chat requests answer 400 on Azure
  • The proxy's own include_usage stays on the forced non-streaming call
  • Azure models on the Responses bridge answer 500 instead
  • Code interpreter, headroom, and Fireworks streams hit the same 400
  • /v1/responses streams with a client stream_options hit it too
  • Sync litellm.responses() streams in the Python SDK hit it too

How it solves it:

  • Interceptions move stream_options off the forced stream=False call
  • The client's value is kept on an internal key
  • The replayed answer ends with the usage chunk when asked
  • The chat loop now replays web search answers as a stream
  • /v1/messages adapters stop passing the replay flag inward
  • The proxy strips every agentic-loop control key from client bodies
  • The sync SDK Responses path now drops the keys a hook removed, like the async path

User Flow

Before: a developer streaming chat completions with web search on Azure gets an error instead of an answer

  1. They send POST https://litellm-domain/v1/chat/completions with "model": "azure-gpt-4o", "stream": true, and a litellm_web_search tool
  2. They get HTTP 400 The 'stream_options' parameter is only allowed when 'stream' is enabled., and code interpreter and headroom streams get the same
  3. On azure-gpt-5.4-mini they get HTTP 500 'ModelResponse' object has no attribute '__aiter__' instead
  4. Only "stream": false answers 200, so they have to turn streaming off

After: the same streamed request answers with the searched result and the usage the client asked for

  1. They send POST https://litellm-domain/v1/chat/completions with "model": "azure-gpt-4o", "stream": true, and a litellm_web_search tool
  2. The SSE stream answers 200 with the searched answer and a finish_reason: stop chunk, and so do code interpreter and headroom streams
  3. azure-gpt-5.4-mini streams the same way, and with include_usage the last chunk carries real usage and cost
  4. "stream": false keeps answering 200

Linear ticket

Resolves LIT-9339

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

Last updated: a4f376d. The proxy cells and /live-pr-risk ran on 7f87030, the last commit with a product diff, the SDK cells ran on eac5e07, and the audit below ran its tests on top of 7f87030. eac5e07, 4ae9f5e, 0dffa7a, e4f147c, and a4f376d only add or change tests

Shared setup: each leg is a proxy booted from its own git worktree and venv with --num_workers 2 and its own Postgres database (python litellm/proxy/proxy_cli.py --config config.yaml --port <port> --num_workers 2 --use_prisma_db_push). Azure (two deployments on one Foundry resource), Gemini, and Fireworks sit behind a forwarding recorder per leg that logs each outbound request and passes it on to the real provider, and Tavily is the search tool. The clients are the OpenAI Python SDK 2.33.0 (/v1/chat/completions, /v1/responses), curl 8.7.1, and the Anthropic Python SDK 0.84.0 (/v1/messages), pointed at the proxy through qa_client.py <mode> (MODEL picks the deployment, INCLUDE_USAGE=1 adds stream_options; source and request bodies below). The sync SDK cells call litellm.responses() in-process from each checkout (PYTHONPATH=<checkout>, one shared venv) against the same Azure gpt-4o deployment, with Perplexity as the SDK's default search provider. Every call hits Azure, Gemini, Fireworks, Tavily, and Perplexity for real, and both legs ran the same cells in the same order

model_list:
  - model_name: azure-gpt-4o
    litellm_params:
      model: azure/gpt-4o
      api_base: os.environ/<redacted>
      api_key: os.environ/<redacted>
      api_version: "2025-04-01-preview"

  - model_name: azure-gpt-5.4-mini
    litellm_params:
      model: azure/gpt-5.4-mini
      api_base: os.environ/<redacted>
      api_key: os.environ/<redacted>
      api_version: "2025-04-01-preview"

  - model_name: azure-gpt-4o-direct
    litellm_params:
      model: azure/gpt-4o
      api_base: os.environ/<redacted>
      api_key: os.environ/<redacted>
      api_version: "2025-04-01-preview"

  - model_name: azure-broken
    litellm_params:
      model: azure/no-such-deployment-lit9339
      api_base: os.environ/<redacted>
      api_key: os.environ/<redacted>
      api_version: "2025-04-01-preview"

  - model_name: gemini-flash
    litellm_params:
      model: gemini/gemini-3.8-flash
      api_base: os.environ/<redacted>
      api_key: os.environ/<redacted>

  - model_name: fireworks-gpt-oss
    litellm_params:
      model: fireworks_ai/accounts/fireworks/models/gpt-oss-120b
      api_base: os.environ/<redacted>
      api_key: os.environ/<redacted>

guardrails:
  - guardrail_name: headroom-dead-vendor
    litellm_params:
      guardrail: headroom
      mode: post_call
      api_base: http://127.0.0.1:9
      unreachable_fallback: fail_open
      default_on: false

search_tools:
  - search_tool_name: tavily-search
    litellm_params:
      search_provider: tavily
      api_key: os.environ/<redacted>

litellm_settings:
  callbacks: ["websearch_interception", "code_interpreter_interception", "lit9339_probe.probe"]
  code_interpreter_interception_params:
    enabled_providers: ["azure"]
  fallbacks: [{"azure-broken": ["azure-gpt-4o"]}]
  websearch_interception_params:
    enabled_providers: ["azure", "gemini", "fireworks_ai"]
    search_tool_name: tavily-search

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY

azure-gpt-4o-direct, azure-broken with its fallback, gemini-flash, and lit9339_probe.probe (a logger that records the keys each hook sees) serve the /live-pr-risk cells further down

Control, the same body straight at Azure with no proxy: stream=false plus stream_options answers 400 The 'stream_options' parameter is only allowed when 'stream' is enabled., stream=false alone and stream=true plus stream_options both answer 200

Outbound requests the recorders saw: at the base every forced stream=false call carried stream_options, and Azure and Fireworks answered it 400. At the head no stream=false call carried stream_options, and no internal control key reached a provider. The sync SDK cells went through the same kind of recorder in front of Azure: the base's forced stream=false web search and code interpreter calls carried stream_options and got 400, the head's did not and got 200, and the two control cells sent the same key sets and request counts on both sides

Before (3571b5d)

Streamed chat completion with the web search tool, azure-gpt-4o

  1. MODEL=azure-gpt-4o qa_client.py chat-stream-websearch
ERROR BadRequestError 400 Error code: 400 - {'error': {'message': "litellm.BadRequestError: AzureException BadRequestError - The 'stream_options' parameter is only allowed when 'stream' is enabled.\n\nLiteLLM: model group 'azure-gpt-4o' failed with the error above and no fallback model group was found for it, so the request was not retried on another model. Fallbacks are configured for: azure-broken. Add a fallbacks entry for that model group (Router fallbacks or proxy router_settings.fallbacks) to retry on another model.", 'type': 'invalid_request_error', 'param': 'stream_options', 'code': '400'}}
  1. Same request with stream_options.include_usage: INCLUDE_USAGE=1 MODEL=azure-gpt-4o qa_client.py chat-stream-websearch
ERROR BadRequestError 400 Error code: 400 - {'error': {'message': "litellm.BadRequestError: AzureException BadRequestError - The 'stream_options' parameter is only allowed when 'stream' is enabled.\n\nLiteLLM: model group 'azure-gpt-4o' failed with the error above and no fallback model group was found for it, so the request was not retried on another model. Fallbacks are configured for: azure-broken. Add a fallbacks entry for that model group (Router fallbacks or proxy router_settings.fallbacks) to retry on another model.", 'type': 'invalid_request_error', 'param': 'stream_options', 'code': '400'}}
  1. Raw SSE for the same body with curl: curl -sSN -w '\nstatus=%{http_code} total=%{time_total}s\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d @curl_body.json
{"error":{"message":"litellm.BadRequestError: AzureException BadRequestError - The 'stream_options' parameter is only allowed when 'stream' is enabled.\n\nLiteLLM: model group 'azure-gpt-4o' failed with the error above and no fallback model group was found for it, so the request was not retried on another model. Fallbacks are configured for: azure-broken. Add a fallbacks entry for that model group (Router fallbacks or proxy router_settings.fallbacks) to retry on another model.","type":"invalid_request_error","param":"stream_options","code":"400"}}
status=400 total=1.299385s

Streamed chat completion with the web search tool, azure-gpt-5.4-mini (Responses bridge)

  1. INCLUDE_USAGE=1 MODEL=azure-gpt-5.4-mini qa_client.py chat-stream-websearch
ERROR InternalServerError 500 Error code: 500 - {'error': {'message': "'ModelResponse' object has no attribute '__aiter__'", 'type': 'None', 'param': 'None', 'code': '500'}}

Non-streamed chat completion with the web search tool, azure-gpt-4o

  1. MODEL=azure-gpt-4o qa_client.py chat-nostream-websearch
STATUS 200 non-stream
CONTENT: The latest LiteLLM release version as of now is v1.104.2.
USAGE: CompletionUsage(completion_tokens=19, prompt_tokens=4069, total_tokens=4088, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0), latency_checkpoint={'engine_tbt_ms': 6, 'engine_ttft_ms': 126, 'engine_ttlt_ms': 245, 'pre_inference_ms': 216, 'service_tbt_ms': 6, 'service_ttft_ms': 368, 'service_ttlt_ms': 483, 'user_visible_ttft_ms': 151})

Streamed /v1/responses with a web_search tool, azure-gpt-4o

  1. MODEL=azure-gpt-4o qa_client.py responses-stream-websearch
STATUS 200 stream events=28
OUTPUT_TEXT: The current latest LiteLLM release version as of now is **v1.104.2**, released on October 8, 2023.
USAGE: ResponseUsage(input_tokens=3569, input_tokens_details=InputTokensDetails(cached_tokens=0, cache_write_tokens=0), output_tokens=32, output_tokens_details=OutputTokensDetails(reasoning_tokens=0), total_tokens=3601, cost=0.0092425)

Streamed /v1/responses with a web_search tool and a client stream_options, azure-gpt-4o

  1. curl -sS -o c44.out -w '%{http_code}\n' $PROXY/v1/responses -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d @responses_stream_ws_stream_options.json
400
  1. cat c44.out
{"error":{"message":"litellm.BadRequestError: AzureException BadRequestError - {\n  \"error\": {\n    \"message\": \"The 'stream_options' parameter is only allowed when 'stream' is enabled.\",\n    \"type\": \"invalid_request_error\",\n    \"param\": \"stream_options\",\n    \"code\": null\n  }\n}\n\nLiteLLM: model group 'azure-gpt-4o' failed with the error above and no fallback model group was found for it, so the request was not retried on another model. Fallbacks are configured for: azure-broken. Add a fallbacks entry for that model group (Router fallbacks or proxy router_settings.fallbacks) to retry on another model.","type":"invalid_request_error","param":null,"code":"400"}}

Sync SDK litellm.responses() streamed with a web_search tool and a client stream_options, azure/gpt-4o

  1. PYTHONPATH=<checkout> python sync_responses_web_search.py
litellm from <3571b5dc72 checkout>/litellm

Give Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new
LiteLLM.Info: If you need to debug this error, use `litellm.turn_on_debug()'.

BadRequestError: litellm.BadRequestError: AzureException BadRequestError - {
  "error": {
    "message": "The 'stream_options' parameter is only allowed when 'stream' is enabled.",
    "type": "invalid_request_error",
    "param": "stream_options",
    "code": null
  }
}
exit=1
  1. Same shape with the code interpreter tool: python sync_responses_cells.py code_interpreter_stream_opts
cell code_interpreter_stream_opts litellm from <3571b5dc72 checkout>/litellm

Give Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new
LiteLLM.Info: If you need to debug this error, use `litellm.turn_on_debug()'.

BadRequestError: litellm.BadRequestError: AzureException BadRequestError - {
  "error": {
    "message": "The 'stream_options' parameter is only allowed when 'stream' is enabled.",
    "type": "invalid_request_error",
    "param": "stream_options",
    "code": null
  }
}
exit=1
  1. Control, web search without streaming: python sync_responses_cells.py web_search_no_stream
cell web_search_no_stream litellm from <3571b5dc72 checkout>/litellm
output_text: The LiteLLM project most recently announced the release of version 1.104.0 on October 3, 2023, introducing features like Claude Opus 5.5, GPT-6 support, master key enforcement, and team routing contro
usage total_tokens: 2070
exit=0
  1. Control, a plain stream with stream_options and no tool: python sync_responses_cells.py plain_stream_opts
cell plain_stream_opts litellm from <3571b5dc72 checkout>/litellm
events: 9 last: ResponsesAPIStreamEvents.RESPONSE_COMPLETED deltas with obfuscation: 0
output_text: Hello
usage total_tokens: 19
exit=0

Streamed /v1/messages with the Anthropic web_search tool, azure-gpt-4o (Anthropic Python SDK)

  1. MODEL=azure-gpt-4o qa_client.py messages-stream-websearch
STATUS 200 stream events=7 stop_reason=end_turn content_blocks=['text']
CONTENT: Title: Release Notes | liteLLM
URL: https://docs.litellm.ai/release_notes
Snippet: LiteLLM is moving to Rust [...]

# Release Notes

LiteLLM ships new releases regularly with new provider support, performance improvements, and enterprise features. Use the sidebar to browse all r
USAGE: Usage(cache_creation=None, cache_creation_input_tokens=None, cache_read_input_tokens=None, inference_geo=None, input_tokens=0, output_tokens=0, server_tool_use=None, service_tier=None)

Streamed chat completion with the code interpreter tool, azure-gpt-4o

  1. curl -sSN -w '\nstatus=%{http_code} total=%{time_total}s\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d @code_interp_stream_usage.json
{"error":{"message":"litellm.BadRequestError: AzureException BadRequestError - The 'stream_options' parameter is only allowed when 'stream' is enabled.\n\nLiteLLM: model group 'azure-gpt-4o' failed with the error above and no fallback model group was found for it, so the request was not retried on another model. Fallbacks are configured for: azure-broken. Add a fallbacks entry for that model group (Router fallbacks or proxy router_settings.fallbacks) to retry on another model.","type":"invalid_request_error","param":"stream_options","code":"400"}}
status=400 total=0.770081s

Streamed chat completion with the headroom_retrieve tool, azure-gpt-4o

  1. curl -sSN -w '\nstatus=%{http_code} total=%{time_total}s\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d @headroom_stream_usage.json
{"error":{"message":"litellm.BadRequestError: AzureException BadRequestError - The 'stream_options' parameter is only allowed when 'stream' is enabled.\n\nLiteLLM: model group 'azure-gpt-4o' failed with the error above and no fallback model group was found for it, so the request was not retried on another model. Fallbacks are configured for: azure-broken. Add a fallbacks entry for that model group (Router fallbacks or proxy router_settings.fallbacks) to retry on another model.","type":"invalid_request_error","param":"stream_options","code":"400"}}
status=400 total=0.727849s

Streamed chat completion with the web search tool, Fireworks gpt-oss-120b

  1. curl -sSN -w '\nstatus=%{http_code} total=%{time_total}s\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d @fireworks_chat_stream_ws_usage.json
{"error":{"message":"litellm.BadRequestError: Fireworks_aiException - {\"error\":{\"object\":\"error\",\"type\":\"invalid_request_error\",\"code\":\"invalid_request_error\",\"message\":\"stream_options is only valid when stream=true. Set stream=true or remove stream_options.\"}}\n\nLiteLLM: model group 'fireworks-gpt-oss' failed with the error above and no fallback model group was found for it, so the request was not retried on another model. Fallbacks are configured for: azure-broken. Add a fallbacks entry for that model group (Router fallbacks or proxy router_settings.fallbacks) to retry on another model.","type":"invalid_request_error","param":null,"code":"400"}}
status=400 total=0.550859s

After (7f87030)

Streamed chat completion with the web search tool, azure-gpt-4o

  1. MODEL=azure-gpt-4o qa_client.py chat-stream-websearch
STATUS 200 stream chunks=2 finish_reason=stop
CONTENT: The latest LiteLLM release version is **v1.104.2**, as of October 8, 2026.
USAGE CHUNK: None
  1. Same request with stream_options.include_usage: INCLUDE_USAGE=1 MODEL=azure-gpt-4o qa_client.py chat-stream-websearch
STATUS 200 stream chunks=3 finish_reason=stop
CONTENT: The current latest LiteLLM release version is **v1.104.2**, as of October 8, 2026.
USAGE CHUNK: CompletionUsage(completion_tokens=28, prompt_tokens=3416, total_tokens=3444, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0), cost=0.008820000000000001)
  1. Raw SSE for the same body with curl: curl -sSN -w '\nstatus=%{http_code} total=%{time_total}s\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d @curl_body.json
data: {"id":"chatcmpl-EXDrynGnYc1YboiQ1lUIU3eRPhjRv","created":1791586846,"model":"azure-gpt-4o","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"provider_specific_fields":{"refusal":null},"content":"The latest LiteLLM release version is v1.104.2, released on October 8, 2026.","role":"assistant","annotations":[]}}]}

data: {"id":"chatcmpl-EXDrynGnYc1YboiQ1lUIU3eRPhjRv","object":"chat.completion.chunk","created":1791586846,"model":"azure-gpt-4o","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"id":"chatcmpl-EXDrynGnYc1YboiQ1lUIU3eRPhjRv","created":1791586846,"model":"azure-gpt-4o","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"usage":{"completion_tokens":26,"prompt_tokens":3425,"total_tokens":3451,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0},"cost":0.0088225}}

data: [DONE]


status=200 total=6.242940s

Streamed chat completion with the web search tool, azure-gpt-5.4-mini (Responses bridge)

  1. INCLUDE_USAGE=1 MODEL=azure-gpt-5.4-mini qa_client.py chat-stream-websearch
STATUS 200 stream chunks=3 finish_reason=stop
CONTENT: The current latest LiteLLM release version appears to be **v1.104.2**.
USAGE CHUNK: CompletionUsage(completion_tokens=24, prompt_tokens=3762, total_tokens=3786, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=0, rejected_prediction_tokens=None), prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cached_tokens=0, cache_write_tokens=0, cache_creation_tokens=0), cost=0.0029295000000000002)

Non-streamed chat completion with the web search tool, azure-gpt-4o

  1. MODEL=azure-gpt-4o qa_client.py chat-nostream-websearch
STATUS 200 non-stream
CONTENT: The latest release version of LiteLLM is v1.104.0, as of October 2026.
USAGE: CompletionUsage(completion_tokens=24, prompt_tokens=4106, total_tokens=4130, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0), latency_checkpoint={'engine_tbt_ms': 4, 'engine_ttft_ms': 298, 'engine_ttlt_ms': 404, 'pre_inference_ms': 517, 'service_tbt_ms': 4, 'service_ttft_ms': 1336, 'service_ttlt_ms': 1436, 'user_visible_ttft_ms': 819})

Streamed /v1/responses with a web_search tool, azure-gpt-4o

  1. MODEL=azure-gpt-4o qa_client.py responses-stream-websearch
STATUS 200 stream events=28
OUTPUT_TEXT: The latest LiteLLM release version as of now is **v1.104.2**, which was released on October 8, 2023.
USAGE: ResponseUsage(input_tokens=3711, input_tokens_details=InputTokensDetails(cached_tokens=0, cache_write_tokens=0), output_tokens=33, output_tokens_details=OutputTokensDetails(reasoning_tokens=0), total_tokens=3744, cost=0.009607500000000001)

Streamed /v1/responses with a web_search tool and a client stream_options, azure-gpt-4o

  1. curl -sSN -w '\nstatus=%{http_code} total=%{time_total}s\n' $PROXY/v1/responses -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d @responses_stream_ws_stream_options.json > c44.out; grep status= c44.out
status=200 total=4.863536s
  1. grep -o '^data: {"type":"[a-z_.]*"' c44.out | sort | uniq -c
   1 data: {"type":"response.completed"
   1 data: {"type":"response.content_part.added"
   1 data: {"type":"response.content_part.done"
   1 data: {"type":"response.created"
   1 data: {"type":"response.in_progress"
   1 data: {"type":"response.output_item.added"
   1 data: {"type":"response.output_item.done"
  15 data: {"type":"response.output_text.delta"
   1 data: {"type":"response.output_text.done"
  1. grep '"response.output_text.done"' c44.out
data: {"type":"response.output_text.done","item_id":"msg_0dedcdd3a42aac3f006ac9737cbdec8190b8d01b6e8a7153c8","output_index":0,"content_index":0,"text":"The latest LiteLLM release version is **v1.104.2**, as of October 8, 2023.","model":"azure-gpt-4o"}
  1. grep -c '"obfuscation"' c44.out
0

Sync SDK litellm.responses() streamed with a web_search tool and a client stream_options, azure/gpt-4o

  1. PYTHONPATH=<checkout> python sync_responses_web_search.py
litellm from <eac5e07310 checkout>/litellm
event types: [<ResponsesAPIStreamEvents.RESPONSE_COMPLETED: 'response.completed'>, <ResponsesAPIStreamEvents.CONTENT_PART_ADDED: 'response.content_part.added'>, <ResponsesAPIStreamEvents.CONTENT_PART_DONE: 'response.content_part.done'>, <ResponsesAPIStreamEvents.RESPONSE_CREATED: 'response.created'>, <ResponsesAPIStreamEvents.RESPONSE_IN_PROGRESS: 'response.in_progress'>, <ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED: 'response.output_item.added'>, <ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE: 'response.output_item.done'>, <ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA: 'response.output_text.delta'>, <ResponsesAPIStreamEvents.OUTPUT_TEXT_DONE: 'response.output_text.done'>]
answer: The LiteLLM project most recently released version v1.104.2 on October 8, 2026, which includes updates such as master key enforcement and team routing controls, among other improvements.
usage on response.completed: input_tokens=2248 input_tokens_details=InputTokensDetails(audio_tokens=None, cached_tokens=0, cached_tokens_details=None, image_tokens=None, text_tokens=None, video_tokens=None, cache_write_tokens=0) output_tokens=43 output_tokens_details=OutputTokensDetails(audio_tokens=None, reasoning_tokens=0, text_tokens=None) total_tokens=2291 cost=0.006050000000000001
exit=0
  1. Same shape with the code interpreter tool: python sync_responses_cells.py code_interpreter_stream_opts
cell code_interpreter_stream_opts litellm from <eac5e07310 checkout>/litellm
events: 9 last: ResponsesAPIStreamEvents.RESPONSE_COMPLETED deltas with obfuscation: 0
output_text: Hello
usage total_tokens: 57
exit=0
  1. Control, web search without streaming: python sync_responses_cells.py web_search_no_stream
cell web_search_no_stream litellm from <eac5e07310 checkout>/litellm
output_text: LiteLLM most recently shipped version 1.104.0 on October 3, 2026, which includes support for Claude Opus 5.5 and GPT-6, new provider integrations, master key enforcement, and new team routing controls
usage total_tokens: 4233
exit=0
  1. Control, a plain stream with stream_options and no tool: python sync_responses_cells.py plain_stream_opts
cell plain_stream_opts litellm from <eac5e07310 checkout>/litellm
events: 9 last: ResponsesAPIStreamEvents.RESPONSE_COMPLETED deltas with obfuscation: 0
output_text: Hello
usage total_tokens: 19
exit=0

Streamed /v1/messages with the Anthropic web_search tool, azure-gpt-4o (Anthropic Python SDK)

  1. MODEL=azure-gpt-4o qa_client.py messages-stream-websearch
STATUS 200 stream events=7 stop_reason=end_turn content_blocks=['text']
CONTENT: Title: Release Notes | liteLLM
URL: https://docs.litellm.ai/release_notes
Snippet: LiteLLM is moving to Rust [...]

# Release Notes

LiteLLM ships new releases regularly with new provider support, performance improvements, and enterprise features. Use the sidebar to browse all r
USAGE: Usage(cache_creation=None, cache_creation_input_tokens=None, cache_read_input_tokens=None, inference_geo=None, input_tokens=0, output_tokens=0, server_tool_use=None, service_tier=None)

Streamed chat completion with the code interpreter tool, azure-gpt-4o

  1. curl -sSN -w '\nstatus=%{http_code} total=%{time_total}s\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d @code_interp_stream_usage.json
data: {"id":"chatcmpl-EXDwkZlkZczFCDmrSkjFCPB9foXGF","created":1791587143,"model":"azure-gpt-4o","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"provider_specific_fields":{"refusal":null},"content":"hello","role":"assistant","annotations":[]}}]}

data: {"id":"chatcmpl-EXDwkZlkZczFCDmrSkjFCPB9foXGF","object":"chat.completion.chunk","created":1791587143,"model":"azure-gpt-4o","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"id":"chatcmpl-EXDwkZlkZczFCDmrSkjFCPB9foXGF","created":1791587143,"model":"azure-gpt-4o","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"usage":{"completion_tokens":2,"prompt_tokens":60,"total_tokens":62,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0},"cost":0.00017}}

data: [DONE]


status=200 total=1.154923s

Streamed chat completion with the headroom_retrieve tool, azure-gpt-4o

  1. curl -sSN -w '\nstatus=%{http_code} total=%{time_total}s\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d @headroom_stream_usage.json
data: {"id":"chatcmpl-EXDwnCJDI7KGBAsFmSTfE9BlBb5Mh","created":1791587145,"model":"azure-gpt-4o","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"provider_specific_fields":{"refusal":null},"content":"hello","role":"assistant","annotations":[]}}]}

data: {"id":"chatcmpl-EXDwnCJDI7KGBAsFmSTfE9BlBb5Mh","object":"chat.completion.chunk","created":1791587145,"model":"azure-gpt-4o","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"id":"chatcmpl-EXDwnCJDI7KGBAsFmSTfE9BlBb5Mh","created":1791587145,"model":"azure-gpt-4o","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"usage":{"completion_tokens":2,"prompt_tokens":55,"total_tokens":57,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0},"cost":0.0001575}}

data: [DONE]


status=200 total=0.988648s

Streamed chat completion with the web search tool, Fireworks gpt-oss-120b

  1. curl -sSN -w '\nstatus=%{http_code} total=%{time_total}s\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d @fireworks_chat_stream_ws_usage.json
data: {"id":"chatcmpl-69a6926f2b0e432a9d773f6f97156759","created":1791587612,"model":"fireworks-gpt-oss","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"reasoning_content":"We need to answer with latest LiteLLM release version, in one sentence. Search result shows GitHub releases latest version v1.104.2 (released Oct 8, 2026). Also docs release notes show v1.104.0. The latest is v1.104.2. Provide answer: \"The latest LiteLLM release is version v1.104.2.\"","content":"The latest LiteLLM release is version v1.104.2.","role":"assistant"}}]}

data: {"id":"chatcmpl-69a6926f2b0e432a9d773f6f97156759","object":"chat.completion.chunk","created":1791587612,"model":"fireworks-gpt-oss","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"id":"chatcmpl-69a6926f2b0e432a9d773f6f97156759","created":1791587612,"model":"fireworks-gpt-oss","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"usage":{"completion_tokens":108,"prompt_tokens":3602,"total_tokens":3710,"completion_tokens_details":{"reasoning_tokens":82},"prompt_tokens_details":{"cached_tokens":234},"cost":0.00057351}}

data: [DONE]


status=200 total=5.147484s

Merge-ref check: 4ae9f5e merged into main at 2fcc780 (d81e5b74de, no conflicts) ran every proxy cell again and matched the 7f87030 head on status, body shape, finish reason, and usage, apart from the Gemini cell noted below. The unit suites the merge touched (test_llm_http_handler.py, test_litellm_pre_call_utils.py, test_utils.py, test_litellm_params.py, and the web search and code interpreter interception tests) pass on the merged tree. An earlier merge of 9f2ae08 into 43f07d0 also matched on the recorded outbound requests

qa_client.py, the SDK scripts, and the request bodies
import os
import sys

from anthropic import Anthropic
from openai import OpenAI

mode = sys.argv[1]
proxy = os.environ["PROXY_BASE_URL"]
key = os.environ["LITELLM_MASTER_KEY"]
client = OpenAI(base_url=proxy + "/v1", api_key=key)
model = os.environ.get("MODEL", "azure-gpt-5.4-mini")
question = "Use web search to find what the current latest LiteLLM release version is, then answer in one sentence."
chat_web_search_tool = {
    "type": "function",
    "function": {
        "name": "litellm_web_search",
        "description": "Search the web",
        "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]},
    },
}


def chat(stream: bool, tools: list | None) -> None:
    kwargs = {"model": model, "messages": [{"role": "user", "content": question}], "stream": stream}
    if tools is not None:
        kwargs["tools"] = tools
    if stream and os.environ.get("INCLUDE_USAGE") == "1":
        kwargs["stream_options"] = {"include_usage": True}
    try:
        resp = client.chat.completions.create(**kwargs)
    except Exception as exc:
        print("ERROR", type(exc).__name__, getattr(exc, "status_code", ""), str(exc)[:1200])
        return
    if not stream:
        print("STATUS 200 non-stream")
        print("CONTENT:", (resp.choices[0].message.content or "")[:300])
        print("USAGE:", resp.usage)
        return
    n = 0
    text = ""
    usage = None
    finish = None
    for chunk in resp:
        n += 1
        if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
            text += chunk.choices[0].delta.content
        if chunk.choices and chunk.choices[0].finish_reason:
            finish = chunk.choices[0].finish_reason
        if getattr(chunk, "usage", None):
            usage = chunk.usage
    print(f"STATUS 200 stream chunks={n} finish_reason={finish}")
    print("CONTENT:", text[:300])
    print("USAGE CHUNK:", usage)


def responses(stream: bool) -> None:
    kwargs = {"model": model, "input": question, "tools": [{"type": "web_search"}], "stream": stream}
    try:
        resp = client.responses.create(**kwargs)
    except Exception as exc:
        print("ERROR", type(exc).__name__, getattr(exc, "status_code", ""), str(exc)[:1200])
        return
    if not stream:
        print("STATUS 200 non-stream")
        print("OUTPUT_TEXT:", (resp.output_text or "")[:300])
        print("USAGE:", resp.usage)
        return
    n = 0
    final = None
    for event in resp:
        n += 1
        if event.type == "response.completed":
            final = event.response
    print(f"STATUS 200 stream events={n}")
    if final is not None:
        print("OUTPUT_TEXT:", (final.output_text or "")[:300])
        print("USAGE:", final.usage)


WEATHER_TOOL = {
    "name": "get_weather",
    "description": "Get the current weather for a city",
    "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}


def messages_stream(extra_tools: list | None = None) -> None:
    anthropic_client = Anthropic(base_url=proxy, api_key=key)
    try:
        with anthropic_client.messages.stream(
            model=model,
            max_tokens=400,
            messages=[{"role": "user", "content": question}],
            tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 1}, *(extra_tools or [])],
        ) as stream:
            n = 0
            for _event in stream:
                n += 1
            final = stream.get_final_message()
    except Exception as exc:
        print("ERROR", type(exc).__name__, getattr(exc, "status_code", ""), str(exc)[:1200])
        return
    text = "".join(block.text for block in final.content if getattr(block, "type", "") == "text")
    block_types = [getattr(block, "type", "?") for block in final.content]
    print(f"STATUS 200 stream events={n} stop_reason={final.stop_reason} content_blocks={block_types}")
    print("CONTENT:", text[:300])
    print("USAGE:", final.usage)


match mode:
    case "chat-stream-websearch":
        chat(stream=True, tools=[chat_web_search_tool])
    case "chat-nostream-websearch":
        chat(stream=False, tools=[chat_web_search_tool])
    case "chat-stream-plain":
        chat(stream=True, tools=None)
    case "responses-stream-websearch":
        responses(stream=True)
    case "responses-nostream-websearch":
        responses(stream=False)
    case "messages-stream-websearch":
        messages_stream()
    case "messages-stream-websearch-two-tools":
        messages_stream([WEATHER_TOOL])
    case _:
        raise SystemExit(f"unknown mode {mode}")

curl_body.json

{"model": "azure-gpt-4o", "stream": true, "stream_options": {"include_usage": true},
 "messages": [{"role": "user", "content": "Use web search to find the latest LiteLLM release version and answer in one sentence."}],
 "tools": [{"type": "function", "function": {"name": "litellm_web_search", "description": "Search the web", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}}]}

code_interp_stream_usage.json

{"model": "azure-gpt-4o", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "Reply with the single word hello and nothing else."}], "tools": [{"type": "code_interpreter", "container": {"type": "auto"}}]}

headroom_stream_usage.json

{"model": "azure-gpt-4o", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "Reply with the single word hello and nothing else."}], "tools": [{"type": "function", "function": {"name": "headroom_retrieve", "description": "Retrieve compressed content by id", "parameters": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]}}}]}

fireworks_chat_stream_ws_usage.json

{"model": "fireworks-gpt-oss", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "Use web search to find the latest LiteLLM release version and answer in one sentence."}], "tools": [{"type": "function", "function": {"name": "litellm_web_search", "description": "Search the web", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}}]}

responses_stream_ws_stream_options.json

{"model": "azure-gpt-4o", "stream": true, "stream_options": {"include_obfuscation": true}, "input": "Use web search to find what the current latest LiteLLM release version is, then answer in one sentence.", "tools": [{"type": "web_search"}]}

sync_responses_web_search.py

import os

import litellm
from litellm.integrations.websearch_interception.handler import WebSearchInterceptionLogger

litellm.callbacks = [WebSearchInterceptionLogger(enabled_providers=["azure"])]

print("litellm from", os.path.dirname(litellm.__file__))
try:
    stream = litellm.responses(
        model="azure/gpt-4o",
        api_base=os.environ["AZURE_FOUNDRY_API_BASE"],
        api_key=os.environ["AZURE_FOUNDRY_API_KEY"],
        api_version="2025-04-01-preview",
        input="What did the LiteLLM project ship most recently? Search the web and answer in one sentence.",
        tools=[{"type": "web_search"}],
        stream=True,
        stream_options={"include_obfuscation": True},
    )
    events = [event for event in stream]
except Exception as error:
    print(f"{type(error).__name__}: {str(error)[:400]}")
    raise SystemExit(1)

print("event types:", sorted({event.type for event in events}))
completed = [event for event in events if event.type == "response.completed"]
text = [event.text for event in events if event.type == "response.output_text.done"]
print("answer:", text[-1][:300] if text else None)
print("usage on response.completed:", completed[-1].response.usage if completed else None)

sync_responses_cells.py

import os
import sys

import litellm
from litellm.integrations.code_interpreter_interception.handler import CodeInterpreterInterceptionLogger
from litellm.integrations.websearch_interception.handler import WebSearchInterceptionLogger

CELLS = {
    "code_interpreter_stream_opts": dict(
        callback=CodeInterpreterInterceptionLogger(enabled_providers=["azure"]),
        input="Reply with the single word hello and nothing else.",
        tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
        stream=True,
        stream_options={"include_obfuscation": True},
    ),
    "web_search_no_stream": dict(
        callback=WebSearchInterceptionLogger(enabled_providers=["azure"]),
        input="What did the LiteLLM project ship most recently? Search the web and answer in one sentence.",
        tools=[{"type": "web_search"}],
    ),
    "plain_stream_opts": dict(
        callback=WebSearchInterceptionLogger(enabled_providers=["azure"]),
        input="Reply with the single word hello and nothing else.",
        stream=True,
        stream_options={"include_obfuscation": False},
    ),
}

cell = dict(CELLS[sys.argv[1]])
litellm.callbacks = [cell.pop("callback")]
print("cell", sys.argv[1], "litellm from", os.path.dirname(litellm.__file__))
try:
    result = litellm.responses(
        model="azure/gpt-4o",
        api_base=os.environ["AZURE_FOUNDRY_API_BASE"],
        api_key=os.environ["AZURE_FOUNDRY_API_KEY"],
        api_version="2025-04-01-preview",
        **cell,
    )
    if cell.get("stream"):
        events = list(result)
        types = [str(event.type).split(".")[-1].split(":")[0] for event in events]
        obfuscation = sum(1 for event in events if getattr(event, "obfuscation", None))
        print("events:", len(events), "last:", events[-1].type, "deltas with obfuscation:", obfuscation)
        final = events[-1].response
    else:
        final = result
    print("output_text:", (final.output_text or "")[:200] if hasattr(final, "output_text") else final.output)
    print("usage total_tokens:", final.usage.total_tokens if final.usage else None)
except Exception as error:
    print(f"{type(error).__name__}: {str(error)[:300]}")
    raise SystemExit(1)

Observed next to the fix, the same on both legs:

  • /v1/messages web search on Azure answers the raw search dump with zero usage, not a synthesized answer
  • Streamed /v1/messages with web search plus a second tool gets a JSON body instead of SSE on Azure and Gemini, and a 500 'StreamingChoices' object has no attribute 'message' on Fireworks
  • The replayed web search stream arrives as one content chunk, then the stop chunk, which is how the replay works
  • On Gemini, a chat stream whose follow-up asks to search again ends with that litellm_web_search tool call, a tool the client sent itself (twice in three head and merge-ref runs; the base answers 500 for that body)
  • tests/integration/streaming/test_stream_contracts.py::test_proxy_stream_usage_visibility_keeps_exact_persisted_charge fails at the base too
/live-pr-risk report (7f87030)

Verdict: no regression found. Every difference between base and head is a base 400 or 500 that answers 200 at the head. 7f87030 got its own graph walk, below

Breaking

None. Across 44 proxy cells on Azure, Gemini, and Fireworks plus 4 sync SDK cells, the cells that differ are base failures that pass at the head (web search, code interpreter, and headroom streams, /v1/responses with a client stream_options, malformed and duplicated stream_options, client-sent stash keys). Every other cell matches on status, body shape, recorded outbound requests, and attempt count

Backward incompatible

None observed. The proxy now strips the web search control keys and the new *_stream_options keys from client bodies, like the agentic-loop keys it already stripped. At the base a client-sent _headroom_interception_stream_options reached Azure and answered 400; at the head it is dropped and the call answers 200

Regression risk

  • A converted web search call's cache key changes once after the upgrade, since stream_options moves to an internal key (checked in-process, no cache on the rig)
  • A cache-hit replay of a converted stream still reads include_usage from the logging object (traced)
  • SDK num_retries and the context-window fallback reuse the post-hook kwargs, so the replay flag and the stored stream_options carry over (traced)
  • Logging callbacks see no stream_options in optional_params for the forced non-streaming call (traced)
  • Sync litellm.responses (SDK only) used to merge the hook output over the original params, so a key a hook removed came back. 7f87030 keeps only the keys the hook returned, in both the request params and litellm_params, which is what the async path already did. Every deployment hook in the repo either returns the full kwargs or None, so only the hooks that remove a key behave differently: web search, code interpreter, and headroom, the three this PR fixes (traced; the web search and code interpreter cases verified live). A custom hook that returns only the keys it changed loses the rest on this path now, which the shared hook chain and the async path already did

Dependency graph

  • /v1/chat/completions web search on Azure, streamed and not, with and without usage: verified live
  • The same on the Responses bridge (gpt-5.4-mini), Gemini, and Fireworks: verified live
  • Router fallback from a broken deployment into a web search stream: verified live
  • Code interpreter and headroom streams, plus their spend rows with cost: verified live
  • /v1/responses web search, streamed and not: verified live
  • /v1/responses web search stream with a client stream_options: verified live, base 400, head 200 with no obfuscation fields
  • /v1/messages web search on the chat adapter (Azure, Gemini, Fireworks; one and two tools): verified live, same as base
  • Client-sent control keys, garbage stash values, malformed stream_options, no auth: verified live
  • Pass-through and A2A endpoints drop the new key names through the shared param list: traced, untested
  • Sync SDK litellm.responses() web search and code interpreter streams with stream_options: verified live, base 400, head 200
  • Sync SDK litellm.responses() web search without streaming and a plain stream with stream_options: verified live, same as base
  • The sync Responses deployment-hook runner is called only from the sync branch of the Responses handler, so no proxy route reaches it: traced
  • Cache, SDK retries, logging payloads: traced, see Regression risk
  • Unit tests for every changed module: tested
  • Legacy suites on the head: tests/integration providers 17 of 18 pass (the one failure also fails at base), management 20 pass and 7 skip, guardrail timeouts 45 pass

Not verified

  • Other chat-adapter providers that keep stream_options when stream=false (hosted_vllm, groq, xai, openrouter, together_ai and more); Fireworks stands in for them
  • A proxy with caching on

Audit round 1 of 3

Verdict PASS. Every inventory row below has a cell that ran at the head with the expected outcome, and nothing inside the proxy was mocked or patched

Merge base 3571b5d, product tip 7f87030, tests commit a4f376d. Every row ran at e4f147c except R20, R20b, and R30, whose cells a4f376d rewrote or added, so those three ran again on both legs at a4f376d. Neither commit has a product diff after 7f87030

Each leg is a two-worker proxy on the GCE box with its own Postgres database and Redis. Azure and Tavily are a scripted upstream (tests/integration/_support/interception_vendor.py) that answers 400 to stream_options on a non-streaming call and to any _-prefixed key, the way Azure does. Each cell checks what the client got, what the upstream received, and the spend row, matched by the response id. The base and base-sdk lanes ran on the merge base. head-run1, head-run1-sdk, head-run2, and head-run2-sdk ran on the head with seed 9339 and order seed 9339, with no skips and no retries. At e4f147c run 1 and run 2 each collected the same 35 cells and failed the same two, R20's old error assertion and R30's teardown, which a4f376d rewrote. At a4f376d run 1 and run 2 collected and passed the same 3 changed cells. The ctl lane ran the six controls once on the head at e4f147c

Every red base cell failed on Azure's stream_options refusal, except R17 (the forged _websearch_interception_stream_options key was refused) and R12 (the missing deployment's 404, with the fallback refused for stream_options). R16 and R26 pass on both legs, so a malformed or empty stream_options on /v1/responses did not reach Azure before this PR either. R10 shows that a streamed /v1/messages request whose only tool is web search still answers from the search itself and never calls the model. R13 and R14 cover the cache case that the /live-pr-risk section lists as not verified. R20 and R20b show what a failed follow-up model call does. The first call's search tool call comes back with 200 and finish_reason tool_calls, on the JSON request at both legs (R20b) and now on the stream too (R20), with the first call's usage chunk because the caller asked for it. The Caveats section says why that stays as is. L1 and L2 are the live rows from the A/B above, on real Azure gpt-4o at 3571b5d and 7f87030

Row Scenario Base Head run 1 Head run 2 Result Last ran at
R1 chat stream, OpenAI SDK red, 400 pass pass PASS e4f147c
R2 chat stream, async SDK red, 400 pass pass PASS e4f147c
R3 chat stream, no stream_options red, 400 pass pass PASS e4f147c
R4 responses stream, SDK red, 400 pass pass PASS e4f147c
R5 responses stream, async SDK red, 400 pass pass PASS e4f147c
R6 responses stream, no options control pass control, once PASS e4f147c
R7 chat JSON, web search control pass control, once PASS e4f147c
R8 code interpreter stream red, 400 pass pass PASS e4f147c
R9 headroom retrieve stream red, 400 pass pass PASS e4f147c
R10 messages stream, search only control pass control, once PASS e4f147c
R11 tool offered, unused red, 400 pass pass PASS e4f147c
R12 fallback from missing deployment red, 404 pass pass PASS e4f147c
R13 chat cache twin red, 400 pass pass PASS e4f147c
R14 responses cache twin red, 400 pass pass PASS e4f147c
R15 malformed chat options (5 cells) red, 400 pass pass PASS e4f147c
R16 malformed responses options (4 cells) green, 200 pass pass PASS e4f147c
R17 forged keys, JSON red, 400 pass pass PASS e4f147c
R18 forged garbage stash red, 400 pass pass PASS e4f147c
R19 wrong Azure key control pass control, once PASS e4f147c
R20 follow-up call fails, stream red, 400 pass pass PASS a4f376d
R20b follow-up call fails, JSON green, 200 pass pass PASS a4f376d
R21 search provider down red, 400 pass pass PASS e4f147c
R22 unknown virtual key control pass control, once PASS e4f147c
R23 JSON with own options control pass control, once PASS e4f147c
R24 include_usage false red, 400 pass pass PASS e4f147c
R25 chat options null, {} (2 cells) red, 400 pass pass PASS e4f147c
R26 responses options null, {} (2 cells) green, 200 pass pass PASS e4f147c
R27 three identical streams red, 400 pass pass PASS e4f147c
R28 burst of 20, mixed red, 400 pass pass PASS e4f147c
R29 always_include_stream_usage red, 400 pass pass PASS e4f147c
R30 worker SIGKILL mid burst red, 400 pass pass PASS a4f376d
R31 SDK litellm.responses red, 400 pass pass PASS e4f147c
R32 SDK litellm.aresponses red, 400 pass pass PASS e4f147c
L1 live chat stream, Azure red, 400 200, usage live, once PASS 7f87030
L2 live responses stream, Azure red, 400 200 live, once PASS 7f87030

Node ids

R1  tests/integration/streaming/test_interception_converted_stream_options.py::test_openai_sdk_chat_stream_through_web_search_is_restreamed_with_its_usage_chunk
R2  tests/integration/streaming/test_interception_converted_stream_options.py::test_async_openai_sdk_chat_stream_through_web_search_is_restreamed_with_its_usage_chunk
R3  tests/integration/streaming/test_interception_converted_stream_options.py::test_raw_chat_stream_without_stream_options_answers_without_a_usage_chunk
R4  tests/integration/streaming/test_interception_converted_stream_options.py::test_openai_sdk_responses_stream_through_web_search_keeps_stream_options_off_azure
R5  tests/integration/streaming/test_interception_converted_stream_options.py::test_async_openai_sdk_responses_stream_through_web_search_keeps_stream_options_off_azure
R6  tests/integration/streaming/test_interception_converted_stream_options.py::test_raw_responses_stream_without_stream_options_answers
R7  tests/integration/streaming/test_interception_converted_stream_options.py::test_openai_sdk_chat_without_streaming_through_web_search_answers_in_json
R8  tests/integration/streaming/test_interception_converted_stream_options.py::test_converted_chat_stream_with_usage_replays_the_single_call_usage[code-interpreter]
R9  tests/integration/streaming/test_interception_converted_stream_options.py::test_converted_chat_stream_with_usage_replays_the_single_call_usage[headroom-retrieve]
R10  tests/integration/streaming/test_interception_converted_stream_options.py::test_anthropic_sdk_messages_stream_with_only_web_search_on_azure_answers_from_the_search
R11  tests/integration/streaming/test_interception_converted_stream_options.py::test_converted_chat_stream_with_usage_replays_the_single_call_usage[web-search-unused]
R12  tests/integration/streaming/test_interception_converted_stream_options.py::test_per_request_fallback_from_a_missing_deployment_restreams_with_usage
R13  tests/integration/streaming/test_interception_converted_stream_options.py::test_chat_stream_cache_hit_replays_the_answer_without_calling_azure
R14  tests/integration/streaming/test_interception_converted_stream_options.py::test_responses_stream_cache_hit_replays_the_answer_without_calling_azure
R15  tests/integration/streaming/test_interception_converted_stream_options.py::test_malformed_chat_stream_options_never_reach_azure[int]
R15  tests/integration/streaming/test_interception_converted_stream_options.py::test_malformed_chat_stream_options_never_reach_azure[list]
R15  tests/integration/streaming/test_interception_converted_stream_options.py::test_malformed_chat_stream_options_never_reach_azure[empty-string]
R15  tests/integration/streaming/test_interception_converted_stream_options.py::test_malformed_chat_stream_options_never_reach_azure[5kb-string]
R15  tests/integration/streaming/test_interception_converted_stream_options.py::test_duplicated_chat_stream_options_key_never_reaches_azure
R16  tests/integration/streaming/test_interception_converted_stream_options.py::test_malformed_responses_stream_options_never_reach_azure[int]
R16  tests/integration/streaming/test_interception_converted_stream_options.py::test_malformed_responses_stream_options_never_reach_azure[list]
R16  tests/integration/streaming/test_interception_converted_stream_options.py::test_malformed_responses_stream_options_never_reach_azure[empty-string]
R16  tests/integration/streaming/test_interception_converted_stream_options.py::test_malformed_responses_stream_options_never_reach_azure[5kb-string]
R17  tests/integration/streaming/test_interception_converted_stream_options.py::test_forged_interception_keys_on_a_json_request_never_reach_azure
R18  tests/integration/streaming/test_interception_converted_stream_options.py::test_forged_garbage_stash_on_a_stream_is_replaced_by_the_real_stream_options
R19  tests/integration/streaming/test_interception_converted_stream_options.py::test_wrong_azure_key_surfaces_azures_401
R20  tests/integration/streaming/test_interception_converted_stream_options.py::test_failed_follow_up_call_hands_the_search_tool_call_back_with_its_usage
R20b  tests/integration/streaming/test_interception_converted_stream_options.py::test_failed_follow_up_call_on_a_json_request_hands_the_search_tool_call_back
R21  tests/integration/streaming/test_interception_converted_stream_options.py::test_search_outage_still_restreams_the_follow_up_answer
R22  tests/integration/streaming/test_interception_converted_stream_options.py::test_unknown_virtual_key_is_refused_before_azure
R23  tests/integration/streaming/test_interception_converted_stream_options.py::test_json_request_with_its_own_stream_options_still_gets_azures_refusal
R24  tests/integration/streaming/test_interception_converted_stream_options.py::test_chat_stream_without_a_usage_request_answers_without_a_usage_chunk[include-usage-false]
R25  tests/integration/streaming/test_interception_converted_stream_options.py::test_chat_stream_without_a_usage_request_answers_without_a_usage_chunk[null]
R25  tests/integration/streaming/test_interception_converted_stream_options.py::test_chat_stream_without_a_usage_request_answers_without_a_usage_chunk[empty]
R26  tests/integration/streaming/test_interception_converted_stream_options.py::test_responses_stream_with_empty_stream_options_answers[null]
R26  tests/integration/streaming/test_interception_converted_stream_options.py::test_responses_stream_with_empty_stream_options_answers[empty]
R27  tests/integration/streaming/test_interception_converted_stream_options.py::test_repeated_identical_streams_each_land_their_own_row
R28  tests/integration/streaming/test_interception_converted_stream_options.py::test_concurrent_burst_across_chat_and_responses_answers_each_and_lands_each_once
R29  tests/integration/streaming/test_interception_converted_stream_options.py::test_always_include_stream_usage_restreams_usage_on_chat_and_strips_it_from_azure_on_responses
R30  tests/integration/streaming/test_interception_converted_stream_options.py::test_worker_sigkill_mid_burst_leaves_the_sibling_restreaming_with_usage
R31  tests/integration/sdk/test_interception_converted_stream_options_sdk.py::test_sync_responses_stream_with_web_search_keeps_stream_options_off_azure
R32  tests/integration/sdk/test_interception_converted_stream_options_sdk.py::test_async_responses_stream_with_web_search_keeps_stream_options_off_azure

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Decision: the client's stream_options is kept on its own internal key
    • A malformed stored value means the replay has no usage chunk
    • Only SDK callers can hit it: the proxy already rewrites malformed values
  • Replays honor include_usage only, not include_obfuscation
    • Verified on /v1/responses: base 400, head 200 without obfuscation fields
  • Streamed /v1/messages web search plus a second tool still fails
    • Same at the base, tracked separately
  • /v1/messages web search on Azure returns the raw search dump, unchanged
  • When the follow-up model call fails, a web search stream answers 200 with the search tool call and the first call's usage
    • The JSON request already answered this way at the base (R20b), so the stream now matches it
    • Raising only on streams would split the two paths. Raising on both changes every interception's status, so a separate fix tracks it

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

  • 9f2ae08 passes /live-pr-risk

  • 7f87030 passes /live-pr-risk


Note

Medium Risk
Touches request shaping and streaming replay across web search, code interpreter, headroom, proxy stripping, and sync Responses merging; behavior change is intentional but broad across hot paths.

Overview
Fixes Azure (and similar) 400 errors when web search, code interpreter, or headroom interceptors turn a client stream into an internal stream=False agentic call but still forwarded stream_options.

Shared helpers (as_converted_stream, stashed_stream_options, CONVERTED_STREAM_KEYS) now strip stream_options from upstream requests, stash the client value on per-interceptor internal keys, and the chat agentic loop replays the final answer as a fake stream with an usage chunk when include_usage was requested. Anthropic /v1/messages bridges stop forwarding converted-stream flags into nested completions/responses; the sync Responses HTTP handler only merges hook kwargs that the hook actually returned (so removed keys do not reappear). The proxy strips expanded agentic-loop control fields via AGENTIC_LOOP_KWARG_NAMES.

Large integration coverage asserts upstream bodies never leak stream_options or _-prefixed interception keys.

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

@devin-ai-integration

devin-ai-integration Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@greptile-apps

greptile-apps Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; the latest test changes introduce no actionable issue.

Summary

The PR removes stream_options from calls forced to use stream=False and keeps the requested usage setting for the replayed stream.

  • Tool-assisted chat answers stream again after their provider call.
  • Internal replay controls stay out of client and provider requests.
  • Sync Responses calls keep options removed by deployment hooks.

Reviews (12) · Last reviewed commit: "test(integration): pin the follow-up fai..." · Reviewed by Greptile

@codspeed

codspeed Bot commented Oct 8, 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_websearch_interception_pop_stream_options (a4f376d) with main (4f08cf2)

Open in CodSpeed

@codecov

codecov Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.11111% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...litellm_core_utils/chat_completion_agentic_loop.py 80.00% 3 Missing ⚠️
litellm/proxy/litellm_pre_call_utils.py 0.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…r code interpreter and headroom, and keep adapters from replaying nested calls
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

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

Reviewed by Cursor Bugbot for commit a4f376d. Configure here.

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

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.

1 participant