Repository navigation
fix(guardrails): scan refusal text in output guardrails on chat and responses - #54039
Conversation
Output guardrails only read message content and output_text parts, so a model refusal reached the client unmasked and a blocking guardrail let it through. Presidio, Bedrock Guardrails, Model Armor and the unified handlers now read and rewrite chat message.refusal, streamed delta.refusal, Responses refusal parts and refusal stream events, on HTTP and on WebSocket Responses.
…onses body Model Armor returns one sanitized string for everything it scanned, so a Responses body answered 400 and a stream was blocked whenever masking had to rewrite it. When the scan came from one content part, write the string into that part and sync the buffered stream events. A body that joined several parts or tool-call arguments has no single place for the string and stays blocked.
…ssage text A masking Model Armor answered 400 on a Responses body with an email in forced tool call arguments, where main answers 200. Scan only message text on that path, since one sanitized string cannot be written back into tool call arguments, and spread that string over every part so a body with several parts is masked instead of blocked
PR overviewThe PR updates output guardrails to scan refusal text in chat and Responses API outputs, including buffered streaming responses. Five issues have been addressed, with one conditional streaming gap remaining. If buffered event indices differ from their positions in the response envelope, some original text may reach the client without the guardrail rewrite being applied, and the current consistency check may not detect it. Open issues (1)
Fixed/addressed: 5 · PR risk: 3/10 Reviews |
| responses=list(rewrites_by_position.values()), | ||
| task_mappings=list(rewrites_by_position), | ||
| ) | ||
| self._sync_stream_events_with_rewrites(stream_events=stream_events, rewrites_by_position=rewrites_by_position) |
There was a problem hiding this comment.
Low: Rewrite is not checked against every buffered text event
spread_text_rewrite keys its rewrites by message-part positions in the envelope. Any delta, .done or content_part.done event whose (output_index, content_index) doesn't match one of those positions keeps its original text. Model Armor now releases the buffered stream after this call, where base blocked it. Its equality check in _resolve_streaming_outcome doesn't catch this case: delta text that is a substring of the envelope text is never added to unscanned. If event and envelope indices ever disagree, the client gets the pre-redaction text in those events. I couldn't confirm a provider that sends misaligned indices today.
Suggested fix: do the same check _spread_text_rewrite_over_stream_events already does. Collect the positions of events where _carries_stream_text is true, and raise UndeliverableStreamRewrite (or have Model Armor block) if any of them is missing from rewrites_by_position.
There was a problem hiding this comment.
Fixed in fad995e. The mask is released only when every streamed text event sits on a message part it can rewrite
[Medium impact] The PR appears safe to merge, with no new actionable issue found.
|
…k emptied refusals A refusal a guardrail empties on an ended chat stream is now written back as an empty string instead of escaping raw Model Armor on non-streamed Responses scans tool call arguments when it blocks, masks only answer message parts so a bridged reasoning item keeps its own text, and blocks a stream whose text events fall outside message parts. A chat choice with both content and a refusal gets the masked text once, in content
…r streamed refusals Model Armor masking on non-streamed Responses now scans tool call arguments and reasoning too, so its URI, jailbreak and RAI filters block a flagged argument. It scans the message text again alone when the two differ, so the mask lands only on the answer The content filter's chat stream hook keeps one holdback per choice and field, so a streamed refusal is masked or blocked like content The shared chat stream scan skips relayed error strings instead of crashing on them, and the Rust spend log redaction covers the refusal field like the Python one
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…escan flags When Model Armor masks a non-streamed Responses body that also carries tool calls or reasoning, it scans the message text again alone to place its mask. That second scan now blocks the response when it flags the text, instead of only reading its masked copy Adds a regression test that a Presidio Responses stream cut short in the middle of a tool call ends with an error before any event goes out, so its raw arguments never reach the client
…hes without a rewrite Model Armor's second scan of non-streamed Responses message text now answers 400 when it reports a de-identify match but returns no rewrite, as the shared guardrail path already does, instead of sending the matched text out unchanged. The rescan also writes its own guardrail log entry, so a block from it no longer reads as success Presidio already ends a Responses stream when the analyzer cannot be reached, and a regression test now pins that. A streamed chunk builder test that passed at the merge base is removed, since it caught nothing
…t debug log The shared Responses output extractor logged each whole output item at debug level, so with debug logging on, the answer text that Model Armor now scans on non-streamed Responses reached the logs even with sanitize_error_detail on. The line now logs only the item index and its part count
|
bugbot run |
…s back without a rewrite Under a masking Model Armor guardrail, a non-streamed Responses scan that reports a de-identify match but returns no rewrite now answers 400, as the message-only rescan and the stream path already do, instead of sending the matched text out unchanged. Chat keeps main's behavior there, since failing it would turn requests main answers with 200 into errors
…an_refusal_text # Conflicts: # litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
|
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 e9caa47. Configure here.
Handwritten 1-3 sentence description
When a model refuses, OpenAI puts the answer in a separate refusal field, and our output guardrails never read it. So a refusal could reach the user with a raw email even behind a masking or blocking guardrail. Now Presidio, Bedrock Guardrails, Model Armor, and the shared guardrail path check refusals on chat and Responses, streamed or not, the content filter does too except on Responses streams, and spend logs redact them when message logging is off
Details
TLDR
Problem this solves:
How it solves it:
refusalwherever output text is already scannedIntentional product change: masked Presidio and Bedrock Responses streams now arrive all at once. Model Armor now checks non-streamed Responses and masks a streamed answer it used to block
User Flow
Before: a developer behind an output guardrail gets a refusal with the raw email
refusalwithjane.doe@example.com, even under a blocking guardrailAfter: the refusal comes back masked, or the request is blocked
<EMAIL_ADDRESS>everywhere, and a blocking guardrail answers 400, orresponse.failedon a streamLinear ticket
Resolves LIT-8890
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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 moreDelays 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: e9caa47. Before ran at main's de0e38a
Every case hit a real model and guardrail, with a system prompt that makes the refusal name the email. Raw output and scripts
Which commit each case ran at
Round 1 ran every case at a0fc72d on
gpt-4.1. Both legs carry #45423's one line, since main drops refusal-only chat chunksRounds 2 and 3 ran Armor cases 1 to 8, 12, 14, and 15 plus new cases 16 to 18 at 3d76934, with 7, 12, 14, and 16 on
gpt-5.6and 15 ondeepseek-v4-pro. Round 4 ran cases 12, 14, 15, and 16 again at 0abb86f, which changes only Armor masking of non-streamed Responses that carry tool calls or reasoning, and they came out the same, output. Round 5 ran cases 19 to 21 at 0986fa8, plus cases 12 and 15 again, which came out the same, output. Unit tests cover the Armor log change and the 400 on a rescan match with no rewrite, since a test logging callback saw no post-call Armor entry at the base or here, and the live template always sends a rewrite. Round 6 at a5543c0 made the shared Responses output debug line log only counts, and with--detailed_debugan Armor masked Responses call logged its answer text once before and zero times after, output. Round 7 at ebf9a52 makes a non-streamed Responses Armor match that comes back with no rewrite answer 400, which a unit test covers since the live template always sends a rewrite, and Armor cases 1 to 8, 12, 14, 15, and 16 came out the same, outputThe other rows carry from a0fc72d. After it, fad995e made the chat handler write back a refusal that a guardrail empties at the end of a stream, and no carried case empties one. 3d76934 made the chat stream scan skip non-chunk items, which leaves an all-chunk stream like cases 9 and 10 the same, and added
refusalto the Rust spend log redaction. Case 13 already showed it redacted at a0fc72d, since Python redacts the response before the Rust writer gets it, and the crate's goldens cover the Rust side. At ebf9a52 the guardrail and Responses and chat handler unit tests pass, 7328 in all. e9caa47 merges main and resolves one import conflict in the Armor hook, so every case carries. On it those tests plus the Responses and redaction tests pass, 10173 in all, and so do the Rust spend log goldensresponse.failedresponse.failedCases that stayed the same
/v1/messages, Presidio and Bedrock/v1/messages, ArmorShared setup
Before (de0e38a)
1. Chat refusal, masking
Cases 2 to 13
2. Responses refusal part, masking
curl -s "$U/v1/responses" "${hdr[@]}" -d "$(resp_body $g)"for each masking guardrail3. Responses stream, masking
"stream": true4. Chat, blocking
5. Responses, blocking
6. Responses stream, blocking
"stream": true7. Plain text, masking
$PLAINand each masking guardrail8.
/v1/messages, maskingcurl -s "$U/v1/messages"with the refused ask, then$PLAIN, for each masking guardrail9. Chat stream with #45423's line, masking
"stream": true10. Chat stream with #45423's line, blocking
"stream": true11. WebSocket Responses, Presidio
python qa_ws.py <port> presidio-masksends the refused ask overws://127.0.0.1:<port>/v1/responses12. Forced tool call, Armor
bash qa_toolcall.sh <port> armor-mask, thenbash qa_toolcall_stream.sh <port> armor-mask, which force asave_contactcall with the email as its argument13. Spend log, message logging off
After (a0fc72d)
1. Chat refusal, masking
Cases 2 to 13
2. Responses refusal part, masking
curl -s "$U/v1/responses" "${hdr[@]}" -d "$(resp_body $g)"for each masking guardrail3. Responses stream, masking
"stream": true4. Chat, blocking
5. Responses, blocking
6. Responses stream, blocking
"stream": true7. Plain text, masking
$PLAINand each masking guardrail8.
/v1/messages, maskingcurl -s "$U/v1/messages"with the refused ask, then$PLAIN, for each masking guardrail9. Chat stream with #45423's line, masking
"stream": true10. Chat stream with #45423's line, blocking
"stream": true11. WebSocket Responses, Presidio
python qa_ws.py <port> presidio-masksends the refused ask overws://127.0.0.1:<port>/v1/responses12. Forced tool call, Armor
bash qa_toolcall.sh <port> armor-mask, thenbash qa_toolcall_stream.sh <port> armor-mask, which force asave_contactcall with the email as its argument13. Spend log, message logging off
Round 2, Model Armor (de0e38a and 3d76934)
Setup and output
Same Armor guardrails as the shared setup, one proxy per leg with
--num_workers 2and no database. The config adds these modelsCases 1 to 8, Armor
qa_leg.sh <port> armor-mask armor-block, the same curls as round 1 with case 7 ongpt-5.6The two chat stream lines at the end ran without #45423's line before, so main drops the refusal chunks there, and with it after
12 and 14. Forced tool call, Armor masking and blocking
15. Reasoning model on Responses, Armor masking
Round 3 (de0e38a and 3d76934)
Setup and output
Same proxies as round 2, with these guardrails added.
litellm-qa-uri-sdpis a Model Armor template with the malicious URI filter and basic SDP on16. Tool call with a malicious URL, Armor masking
qa_toolcall_uri.sh <port> armor-uri-mask, a forced tool call whose argument is Google's Safe Browsing test URL, then case 12 again17 and 18. Chat stream refusal, content filter masking and blocking
Run
qa_chat_stream.sh <port> cf-mask cf-block, the same streams as cases 9 and 10. Both legs carry fix(streaming): keep delta.refusal chunks instead of dropping them #45423's line. The email splits across deltas, so the joined refusal shows itBefore
Round 5 (de0e38a and 0986fa8)
Setup and output
Same proxies as round 3, with this guardrail added. Nothing listens on port 9, so every Presidio call fails
19 and 20. Chat refusal, content filter masking and blocking
Run
qa_leg.sh <port> cf-mask cf-block, the same requests as cases 1 to 8. Only the chat lines are below. On non-streamed Responses the content filter already masked and blocked the refusal at the base, full outputBefore
21. Responses stream, Presidio analyzer down
Run
qa_presidio_dead.sh <port>, a streamed/v1/responsescall ongpt-5.6that repeats the emailBefore
Type
🐛 Bug Fix
Decisions
What was chosen and the alternatives
response.refusal.donetext, refusal deltas as stream text, the chat side, the three hooks, and spend log redaction/v1/messagesstream already do. A chat stream still sends its raw chunks on that error, same as main, and I left that aloneoutput_texton these streams gets masked too, which was raw on mainapply_guardrailto rewrite would change the policy pipeline and/guardrails/apply_guardrail. The cost is that text moves into the first part, and nothing is lostcontentand an emptyrefusal, so the text shows oncegpt-4.1, sincegpt-5.6writes its refusal inside the JSON content and never fillsrefusal. The plain text and tool call cases ran ongpt-5.6delta.refusalbefore any scan. Nothing leaks there, so I left it alonedelta.refusaltoo. Its Responses stream hook leaves all text raw, refusals included, same as main, and fixing that is its own change. The Responses WebSocket runs only Presidio on output, on main too, so Armor and Bedrock never see WebSocket text, and adding them there is its own changeget_content_from_model_responsestays as is and Armor reads refusals next to it, so no other caller's content changessanitize_error_detailkeeps scanned text out of the logs and this PR sends non-streamed Responses through that lineCaveats (if any)
High
Medium
Low
fail_on_erroris falsenabove 1, Armor puts one masked string in every choice, like main's content/v1/messagestext raw, same as mainFinal Attestation
Bugbot summary