Repository navigation
fix(utils): run post-call deployment hook on converted chat streams - #41495
Conversation
A pre-call deployment hook can turn a requested stream into a non-streaming provider call and the result is wrapped back into a fake stream. The async client wrapper treated that wrapper like a caller-requested stream and returned before async_post_call_success_deployment_hook, so SDK callers lost post-call deployment processing (including CustomGuardrail post_call enforcement) on converted streams. Run the hook on the complete ModelResponse behind the wrapper and rewrap a modified response so it reaches the emitted chunks. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
🤖 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:
|
|
bugbot run |
Greptile SummaryThis PR fixes converted asynchronous chat streams so successful deployment hooks run against the buffered response and any replacement response reaches emitted chunks while retaining the existing stream wrapper and metadata
Confidence Score: 5/5The PR appears safe to merge, with no outstanding correctness or repository-rule failures The converted-stream hook path is narrowly gated, preserves the original wrapper, and has focused coverage for rewritten and skipped cases. The provider-header finding and the in-place-mutation finding were manually resolved without explanation. The callback monkeypatch finding was correctly withdrawn after devin-ai-integration[bot] explained that the test patches the production registry and restores it afterward Important Files Changed
Reviews (5): Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." | Re-trigger Greptile |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…ping Keeps the original CustomStreamWrapper so response headers and the correlation-context cleanup in __del__ are untouched when a deployment hook rewrites the converted response. Covers the early-return branches for real provider streams and unmapped call types Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…eam_post_call_hook
|
@greptileai review latest head |
|
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 e1cce94. Configure here.
Backport of BerriAI#41495 to rc/1.102.0. Cherry-picked from merge commit 0add8c0 (main), originally by app/devin-ai-integration. The only conflict was the test import header: the rc line never gained the logging_executor import that main carries next to this change, so only the MockResponseIterator import comes along.
TLDR
Problem this solves:
CustomGuardrailpost_call checks silently did not runHow it solves it:
MockResponseIteratorfor one over the modified response so the change reaches the emitted chunks; theCustomStreamWrapperitself, its headers, logging object and__del__cleanup are untouchedUser Flow
Before: an SDK user with a post-call deployment hook sees it skipped whenever another hook converted their stream
stream=Truerequests into a non-streaming provider call, and a post-call hook that appends[post_call_deployment_hook ran]to the reply (or aCustomGuardrailwithmode: post_callthat raises on bad output)litellm.acompletion(model="openai/gpt-5.6", messages=[...], stream=True)with a prompt that triggers the conversionpong, untagged, and the guardrail never raisedAfter: the same call runs the post-call hook on the converted stream
litellm.acompletion(..., stream=True)callpong [post_call_deployment_hook ran], and with the guardrail registered the call raisesValueError: BLOCKED: response contains pongexactly like the non-streaming call doesThrough the proxy the same conversion now also tags the converted stream, while proxy-side guardrails behave the same before and after because the proxy enforces them in its own post-call layer
Relevant issues
Follow-up to #41171, which added the converted-stream logging path this hook skip lives on
Affected release
Not in any stable release. The gap arrived with #41171 (c3222ec, first tagged in v1.103.0-dev.1). That PR carries
backport-stablefor rc/1.102.0, so this fix carries the same label to ship alongside itLinear ticket
Refs LIT-7729
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<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 moremiscprice-map failure recorded under Caveats) (e.g., lint, schema.d.ts sync check, etc.)@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 audit, Before at the merge base (port 16442) and After at this PR's tip (port 16443). Each leg runs 2 uvicorn workers from its own worktree against its own Postgres and hits real OpenAI (
openai/gpt-5.6) and Anthropic (anthropic/claude-sonnet-5), no mocks anywhere in the product path. Every stream was consumed to the end, thenLiteLLM_SpendLogswas queried byrequest_id. UI screenshots and the annotated recording are in this comment; the full 52 cell matrix with every response id is in the audit report attached to the sessionShared setup:
audit_callbacks.pyonPYTHONPATHholds the hooks, the config registers themShared commands (
$PORTis 16442 or 16443,$KEYthe proxy master key)Before (b3898df)
Converted stream, /v1/chat/completions, curl
$CHAT '{"model":"gpt-5.6","stream":true,"messages":[{"role":"user","content":"convert-me: reply with exactly: ping"}]}'status=200, idchatcmpl-EOswbjG9mybTUY8cDPSBdh0FwrZqs, 2 data chunks, first chunk"content":"ping", no tag$SPEND:1|ping"model":"claude","max_tokens":32:status=200, idchatcmpl-d4e3e40b-7c56-4b73-bbbe-4909b516fb6b, textping, no tag,1|pingConverted stream, /v1/chat/completions, OpenAI SDK
openai.OpenAI(base_url="http://127.0.0.1:16442", api_key=KEY).chat.completions.create(model="gpt-5.6", stream=True, messages=[{"role":"user","content":"convert-me: reply with exactly: ping"}]), iterated to the endchatcmpl-EOsyvWfvXsYoHlTDc9qYHWNtE1Vej, textping, no tag, one spend rowopenai.AsyncOpenAI: idchatcmpl-EOsyxHZ4r8hw3P5aZpMAvAMbUqgEf, textping, no tag, one spend rowAsyncOpenAIconverted streams: 0/8 tagged, 8 distinct ids, exactly one spend row per idOrdinary stream and non-stream, /v1/chat/completions
$CHAT '{"model":"gpt-5.6","stream":true,"messages":[{"role":"user","content":"Reply with exactly: ping"}]}':status=200, idchatcmpl-EOswaPMrJBazMz8m5LYILnrNYRBjj, 3 chunks, textping, no tag$CHAT '{"model":"gpt-5.6","messages":[{"role":"user","content":"Reply with exactly: ping"}]}':status=200, idchatcmpl-EOswYuUxDIO882wOlJCK1PBSN4eIf, contentping [post_call_deployment_hook ran]/v1/messages stream
curl -sS http://127.0.0.1:16442/v1/messages -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{"model":"gpt-5.6","max_tokens":32,"stream":true,"messages":[{"role":"user","content":"convert-me: reply with exactly: ping"}]}'status=200, idmsg_a04136f7-9cb6-4efc-b561-cc9eac950f1a, 6 events ending inmessage_stop, textping, no tag/v1/responses
curl -sS http://127.0.0.1:16442/v1/responses ... -d '{"model":"gpt-5.6","input":"Reply with exactly: ping"}':status=200, idresp_4p_P4INL..., textping, no tag... -d '{"model":"gpt-5.6","stream":true,"input":"convert-me: reply with exactly: ping"}':status=200,response.completed, textping, no tag... -d '{"model":"claude","stream":true,"input":"convert-me: reply with exactly: ping"}'(bridged to chat):status=200, textping, no tag, spend row underchatcmpl-def12d72-...Hook raises on a converted stream
$CHAT '{"model":"gpt-5.6","stream":true,"messages":[{"role":"user","content":"convert-me raise-me: reply with exactly: ping"}]}'status=200, idchatcmpl-EOt2hKWGuWitYNwdQoddRglzCk9RL, textping, the hook never ran so the error never reached the caller$CHAT '{"model":"gpt-5.6","messages":[{"role":"user","content":"raise-me: reply with exactly: ping"}]}':status=500,{"error":{"message":"hook exploded","type":"internal_server_error","param":null,"code":"500"}}Proxy post_call guardrail
$CHAT '{"model":"gpt-5.6","messages":[{"role":"user","content":"Reply with exactly: pong"}],"guardrails":["block-pong"]}':status=500,BLOCKED by proxy post_call guardrail: response contains pong"stream":true:status=200, idchatcmpl-EOt2lTldmpIW0a9b9t9ogvK5v9XrL, textpong, then one guardrail error event"stream":trueandconvert-me: reply with exactly: pong:status=200, idchatcmpl-EOt2mfeDDjXBAgBqL0FJqdSGRbh6Q, textpong, no tag, then the guardrail error eventProvider errors, virtual key, management endpoints
status=400Invalid model name passed in model=no-such-model; invalid provider keystatus=401OpenAIException - Incorrect API key providedstatus=200, idchatcmpl-EOt2nEGEtDAIcDLkCsjIRoYH7IVTX, textping, no tagPOST /key/healthwith that keystatus=200{"key":"healthy","logging_callbacks":null}; with a bad keystatus=401;POST /v1/no-such-routestatus=404GET /health/readinessstatus=200{"status":"healthy","db":"connected"}, both worker processes alive after every cellRepeated and edge requests
chatcmpl-EOt7CZMS...,chatcmpl-EOt7D1YJ...,chatcmpl-EOt7Eodp..., all untagged, exactly one spend row eachconvert-me no-tag(hook returns None),"guardrails":[],"guardrails":null,"stream_options":{"include_usage":true}(usage chunk present, 18 tokens),"response_format":{"type":"json_object"}(text{"answer":"ping"}): allstatus=200, untagged, one spend row eachChaos
docker stopof the leg's Postgres during a 30 request mixed burst (chat, converted chat, Messages, Responses, streaming and not): 30/30status=200,/health/readinessstatus=200"db":"disconnected"while down; afterdocker startplus 30, 60, 90 and 120 s waits only 2/30 ids have a spend row, 28 missing, 0 duplicatesAfter (62b6929)
Converted stream, /v1/chat/completions, curl
$CHAT '{"model":"gpt-5.6","stream":true,"messages":[{"role":"user","content":"convert-me: reply with exactly: ping"}]}'status=200, idchatcmpl-EOswDc1KW3omh6uZekfUdQz21WuRR, 2 data chunks, first chunk$SPEND:1|ping [post_call_deployment_hook ran]"model":"claude","max_tokens":32:status=200, idchatcmpl-45b32ac9-4424-4b1c-951b-b64aceee27a3, textping [post_call_deployment_hook ran],1|ping [post_call_deployment_hook ran]Converted stream, /v1/chat/completions, OpenAI SDK
openai.OpenAI(...)call against port 16443, iterated to the endchatcmpl-EOsyjipfc1Bx5PsPEOqWxoNm9lidI, textping [post_call_deployment_hook ran], one spend rowopenai.AsyncOpenAI: idchatcmpl-EOsyl0k6emvv8EXuK0PkqReILqHvk, textping [post_call_deployment_hook ran], one spend rowAsyncOpenAIconverted streams: 8/8 tagged, 8 distinct ids, exactly one spend row per idOrdinary stream and non-stream, /v1/chat/completions
status=200, idchatcmpl-EOswCt67WiQJTO59yVFinpUeI0xoU, 3 chunks, textping, no tag (caller-requested streams still skip the hook)status=200, idchatcmpl-EOswBHjUa5C9HY9EaedI7LzLkFLG1, contentping [post_call_deployment_hook ran]/v1/messages stream
status=200, idmsg_c5424263-8764-453c-a142-5ac76b5102e4, 6 events ending inmessage_stop, textping, no tag (unchanged)/v1/responses
status=200, idresp_KrqqUlG9..., textping, no tag (unchanged)status=200,response.completed, textping, no tag (unchanged, the Responses iterator runs its own hooks)claude:status=200, textping [post_call_deployment_hook ran]in theoutput_textdeltas, spend row underchatcmpl-415a0ebe-5e70-4ede-bf6a-8dd37321bec1(bridge reaches the fixed chat path, so it follows the chat fix)Hook raises on a converted stream
convert-me raise-mestream requeststatus=500,{"error":{"message":"hook exploded","type":"internal_server_error","param":null,"code":"500"}}status=500,hook exploded(same as before)Proxy post_call guardrail
status=500,BLOCKED by proxy post_call guardrail: response contains pong(unchanged)status=200, idchatcmpl-EOt268hJVyUBohaZLwnjm1cUsDdSP, textpong, then one guardrail error event (unchanged)status=200, idchatcmpl-EOt27aIaUdQ9h8Sl9KYLcX90C0kIf, textpong [post_call_deployment_hook ran], then the same guardrail error eventProvider errors, virtual key, management endpoints
status=400, invalid provider keystatus=401, same bodies as beforestatus=200, idchatcmpl-EOt290D7epfm59MRtKLuTn765xRrw, textping [post_call_deployment_hook ran]POST /key/healthstatus=200{"key":"healthy","logging_callbacks":null}; bad keystatus=401; unknown routestatus=404GET /health/readinessstatus=200{"status":"healthy","db":"connected"}, both worker processes alive after every cellRepeated and edge requests
chatcmpl-EOt6u2u8...,chatcmpl-EOt6vkJ7...,chatcmpl-EOt6xiD3..., all tagged, exactly one spend row eachconvert-me no-tag(hook returns None):status=200, textping, no tag, original response kept"guardrails":[],"guardrails":null,"stream_options":{"include_usage":true}(usage chunk present, 29 tokens),"response_format":{"type":"json_object"}(text{"answer":"ping"} [post_call_deployment_hook ran]): allstatus=200, tagged, one spend row eachChaos
docker stopof Postgres during the same 30 request burst: 30/30status=200, readiness"db":"disconnected"while down; afterdocker startand 120 s of waits 14/30 ids have a spend row, 16 missing, 0 duplicates (same pre-existing loss as Before, LIT-7848)docker pauseof Postgres during a 20 request mixed burst: 20/20status=200, all 20 spend rows land exactly once afterdocker unpause, no duplicateskill -9of one worker mid burst: the other worker keeps serving, a replacement worker appears, 20/20 requests complete, 20/20 spend rows exactly onceRegression test
tests/test_litellm/test_utils.py::test_wrapper_async_runs_success_deployment_hook_on_converted_chat_streamfails at the merge base (assert 0 == 1on the hook call count) and passes here; a control test pins that a caller-requested fake stream still skips the hook, and a parametrized test pins the early returns for a real provider iterator and an unmapped call typeType
🐛 Bug Fix
Caveats (if any)
Medium
Low
misc / Run testsfails only ontest_price_map_has_no_duplicate_keys, which flags six duplicatecache_read_input_token_costkeys in the price mapmainat 9357491, which carried those duplicates;mainfixed them in a6b10ad (landed 23:52 UTC via fix(gemini): map minimal thinking to low for Gemini 3.7 and 3.8 Flash #41201). This PR does not touch either price map and the test passes at both the merge base and this tip locallyhandle_response_errorsAttributeError thatupdate_spend_logsdoes not classify as transient; tracked in LIT-7848, not changed herelitellm.post_call_rulesstill skip converted streams, same as caller-requested streams; not in scope hereFinal Attestation
ran /live-pr-risk and found no regressions/backward incompatible risks
Note
Medium Risk
Changes when deployment hooks and hook-raised errors apply on converted chat streams; behavior now matches non-streaming calls, which may surface errors or modified output where hooks previously never ran.
Overview
Fixes a gap where
stream=Truerequests converted to a non-stream provider call (then wrapped as a stream) never ranasync_post_call_success_deployment_hook, so tagging, enrichment, and post-call guardrails could silently no-op on those streams.The async wrapper now detects converted chat streams (
streaming_requestedis false but the result is a converted stream) and calls_run_success_deployment_hook_on_converted_chat_stream, which runs the hook against the underlyingModelResponseonMockResponseIteratorand, when the hook returns a new response, rebindscompletion_streamto a freshMockResponseIteratorso emitted chunks match the hooked body without replacingCustomStreamWrapper. Caller-requested streams are unchanged (hook still skipped there).Tests cover rewritten converted mock streams, early exits for real provider iterators / unknown call types, and that requested fake streams (e.g. Langflow) still skip the hook.
Reviewed by Cursor Bugbot for commit e1cce94. Bugbot is set up for automated code reviews on this repo. Configure here.
Link to Devin session: https://app.devin.ai/sessions/b7fddcb21db14890a7e5eae9195f08b6
Open in Devin Desktop: https://app.devin.ai/desktop/session/b7fddcb21db14890a7e5eae9195f08b6?variant=devin
Requested by: @yucheng-berri