Repository navigation
fix(headroom): resolve CCR retrieval on streaming /chat/completions - #35017
mateo-berri merged 11 commits into
Conversation
Streaming chat completions returned a CustomStreamWrapper, so the agentic loop dispatch in main.py (guarded on ModelResponse) never ran and the headroom_retrieve tool call was streamed straight to a client that never declared the tool. The guardrail now converts a CCR stream request to a non-streaming call in its deployment hook and the loop fake-streams the resolved answer back.
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
|
|
Greptile SummaryThe PR resolves Headroom retrieval for streaming chat completions.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| litellm/litellm_core_utils/chat_completion_agentic_loop.py | Extends converted-stream detection to Headroom and returns resolved responses through the standard iterable fake-stream wrapper. |
| litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py | Converts eligible streaming chat-completion requests after Headroom has injected its retrieval tool. |
| litellm/proxy/litellm_pre_call_utils.py | Prevents clients from supplying the server-controlled Headroom conversion field. |
| litellm/types/integrations/custom_logger.py | Defines the Headroom interception key and ensures it is excluded from agentic follow-up provider parameters. |
| litellm/types/utils.py | Registers the conversion key as an internal LiteLLM parameter so it is not forwarded to providers. |
| tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py | Adds deployment-hook and end-to-end coverage for resolving Headroom retrieval before producing a synthetic stream. |
| tests/test_litellm/proxy/test_litellm_pre_call_utils.py | Covers sanitization of the newly introduced internal control field. |
Reviews (5): Last reviewed commit: "test(headroom): cover stream conversion ..." | Re-trigger Greptile
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
What are we waiting for to merge this one? It's affecting the main usability of headroom, without that, it's useless. |
…streaming_ccr Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… snapshot Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…udget Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…itellm_lit_4913_headroom_streaming_ccr
…n test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…tream wrapper Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…itellm_lit_4913_headroom_streaming_ccr
…he proxy boundary
|
bugbot run |
…evel configs still compress
|
bugbot run |
There was a problem hiding this comment.
✅ 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 2affd80. Configure here.
Deployment hooks such as Headroom downgrade stream=True to a non-streaming provider call and the agentic loop then hands back a CustomStreamWrapper (or MockResponsesAPIStreamingIterator for Responses). wrapper_async still saw kwargs["stream"] is False, so it took the non-streaming success path with a lazy stream object: no standard_logging_object was built, the proxy cost callback raised failed_tracking_spend, and the wrapper's own end-of-stream dispatch was deduped away. Treat a lazy stream result as streaming for logging regardless of the downgraded kwarg. Regression in v1.99.0 via #35017 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Deployment hooks such as Headroom downgrade stream=True to a non-streaming provider call and the agentic loop then hands back a CustomStreamWrapper (or MockResponsesAPIStreamingIterator for Responses). wrapper_async still saw kwargs["stream"] is False, so it took the non-streaming success path with a lazy stream object: no standard_logging_object was built, the proxy cost callback raised failed_tracking_spend, and the wrapper's own end-of-stream dispatch was deduped away. Treat a lazy stream result as streaming for logging regardless of the downgraded kwarg. Regression in v1.99.0 via #35017 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
TLDR
Problem this solves:
headroom_retrievetool call, empty answerHow it solves it:
User Flow
Before: a developer streaming chat completions through a proxy with Headroom compression on gets a tool call for a tool their app never declared, and no answer
"stream": true, declaring no toolstool_callsdeltas namingheadroom_retrieve, everydelta.contentempty"finish_reason": "tool_calls"anddata: [DONE], so the app shows the user nothingheadroom_retrievethemselves, against an internal endpoint they were never told aboutAfter: the same request streams back the answer, and the retrieve call never reaches the client
"stream": truedelta.contentwith the answer built from the compressed-away text"finish_reason": "stop"anddata: [DONE]headroom_retrieve, so the app needs no knowledge of itRelevant issues
Linear ticket
Resolves LIT-4913
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito 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
Live run against a local proxy (2 uvicorn workers, random high port) hitting the real Anthropic API (
anthropic/claude-sonnet-5, real spend). Only the Headroom compression vendor is stubbed locally, since Headroom is a self-hosted sidecar and no vendor credentials exist here:POST /v1/compressswaps a long user message for[compressed document; retrieve the full text with hash=...]andGET /v1/retrieve/{hash}returns the original text. The guardrail, the agentic loop and the streaming path are the real codeShared setup, identical for both sides; only the checked-out commit differs
payload.jsonis a 1906 char user message burying "the internal codename for the 2026 launch is BLUE HERON, and the launch window opens on March 14" in filler, an assistant ack, then a short user question asking for the codename and date. The client declares no tools; the guardrail injectsheadroom_retrieveitself.BLUE HERONandMarch 14are inside the text compression replaced with a hash before the model ever saw it, so they can only appear in the answer if retrieval really ran server-side and fed a follow-up callThree cases per side, same order: the streaming CCR chat completion above, a short non-CCR streaming request as a control (
payload_short.json, "Say the word pineapple and nothing else."), and the same CCR conversation as a streaming/v1/messagesrequest (payload_messages.json), the surface #36245 already fixed, as a regression controlBefore (
352789257d, merge base)pineapplewithfinish_reason: stop, and streaming/v1/messagesresolves retrieval server-side (BLUE HERONin the reply,stop_reason: end_turn, noheadroom_retrieveframe)After (
4d4cf40334, PR tip)pineapple/finish_reason: stop;/v1/messagesanswers withBLUE HERONandstop_reason: end_turn), and the stub vendor log confirms the retrieval happened inside the proxy for both CCR casesAn earlier screen recording of the same before/after comparison, captured at
cd9c410ae2(before) andfa5a4f06ed(after), is in the Slack thread; the run above supersedes itThe response is still
data:-prefixedchat.completion.chunkframes ending indata: [DONE], so the fake-stream wrapper did not degrade the reply into a non-streaming bodyNotes from this run:
litellm_params.guardrailsconfig resolves streaming CCR too, verified liveCommit
2affd800ecsince this run only adds a unit test for the deployment-level streaming case (no runtime code), so the proof above still holds at the tipType
🐛 Bug Fix
Changes
The Headroom guardrail doesn't drive retrieval itself; it injects
headroom_retrieveinapply_guardrailand resolves the call through the chat-completions agentic loop hooks. That dispatch inlitellm/main.pyonly fires for aModelResponse, and a streaming call returns aCustomStreamWrapper, so streaming requests walked straight past it and handed the client the raw tool callThe guardrail now converts an eligible streaming request to non-streaming in
async_pre_call_deployment_hook, the same trick the websearch and code-interpreter interceptions use. The override delegates to the baseCustomGuardrailhook first, so deployment-level guardrail configs (litellm_params.guardrails: [headroom]) still get compressed, then converts on top of whatever the base returned:The conversion is narrow on purpose: only chat completions, only when the retrieve tool is actually on the request, so nothing changes for requests that never engaged CCR.
/v1/messagesalready resolves the loop throughAgenticAnthropicStreamingIterator, and streaming/v1/responsesis deliberately left for a follow-upchat_completion_agentic_loop.pythen honors_headroom_interception_converted_streamalongside the code-interpreter flag when deciding to fake-stream the resolved response. That re-wrap also changed shape: it used to hand back a bareModelResponseStreamchunk, which is not an async iterable, so a caller that asked forstream=Truecould not iterate it. It now returns aCustomStreamWrapperover aMockResponseIterator, which is what every other fake-stream path in the codebase returns; this fixes the code-interpreter chat-completions path in the same strokeThe new flag is registered in
agentic_loop_internal_litellm_paramsand in the proxy's untrusted-control-field list so it can't leak into a provider body or be forged by a clientThe test gap the ticket called out is closed:
test_streaming_chat_completion_resolves_ccr_retrieval_end_to_enddrives a reallitellm.acompletion(..., stream=True)through the registered guardrail, fakes the OpenAI HTTP boundary with respx (retrieve tool call first, final answer on the follow-up) plus the Headroom retrieve endpoint, and asserts the streamed text is the follow-up answer with noheadroom_retrievechunk. It fails on the pre-fix code. A parametrized test pins the deployment hook to CCR chat completions only, and a second one proves a deployment-level guardrail config still compresses through the base hookCaveats (if any)
Medium
/v1/responsesstill leaks the retrieve call: scoped out here, tracked in LIT-6481 (the hook converts chat-completion call types only, and the responses handler honors only the code-interpreter and websearch converted-stream keys). Workaround: non-streaming/v1/responsesor the/v1/chat/completionssurfaceLow
Final Attestation
Link to Devin session: https://app.devin.ai/sessions/38a43b70ce84466dbbc1ca792732653c
Open in Devin Desktop: https://app.devin.ai/desktop/session/38a43b70ce84466dbbc1ca792732653c?variant=devin
Requested by: @shivamrawat1
Note
Medium Risk
Changes request routing (stream→non-stream→fake stream) and agentic-loop behavior on a hot proxy path; scope is narrow (CCR chat completions with retrieve tool only) and includes regression tests.
Overview
Streaming Headroom CCR on
/v1/chat/completionsused to skip the agentic loop (streaming returns aCustomStreamWrapper, not aModelResponse), so clients saw rawheadroom_retrievetool calls and no answer.The Headroom guardrail now converts eligible streaming chat-completion requests to non-streaming in
async_pre_call_deployment_hookwhenheadroom_retrieveis on the request—mirroring websearch/code-interpreter interception. It calls the parent deployment hook first so deployment-level guardrail configs still compress, then setsstream: falseand_headroom_interception_converted_stream.chat_completion_agentic_looptreats that flag (and the existing code-interpreter converted-stream flag) when re-wrapping the resolved response for callers who asked forstream=true. Fake streaming now returns aCustomStreamWrapperoverMockResponseIteratorinstead of a bare chunk object, so iteration works for Headroom and fixes the same pattern for code-interpreter chat completions.The new internal key is registered so it cannot be forged by clients or forwarded to providers. Tests cover hook gating, deployment-level compression + conversion, and end-to-end
litellm.acompletion(..., stream=True)with retrieval resolved server-side.Reviewed by Cursor Bugbot for commit 2affd80. Bugbot is set up for automated code reviews on this repo. Configure here.