Skip to content

fix(guardrails): scan refusal text in output guardrails on chat and responses - #54039

Merged
mateo-berri merged 13 commits into
BerriAI:mainfrom
quietjules:litellm_guardrails_scan_refusal_text
Nov 24, 2026
Merged

mateo-berri merged 13 commits into
BerriAI:mainfrom
quietjules:litellm_guardrails_scan_refusal_text

Conversation

@quietjules

@quietjules quietjules commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Masking guardrails let refusal text through with raw PII
  • Blocking guardrails answer 200 on a refusal holding blocked text
  • Responses streams and WebSocket frames leak the raw refusal

How it solves it:

  • Scan refusal wherever output text is already scanned
  • Write the masked text everywhere the response repeats it
  • Hold Responses stream events until masking finishes

Intentional 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

  1. The admin sets an output guardrail that masks or blocks emails
  2. The developer sends POST https://litellm-domain/v1/chat/completions, or a streamed POST https://litellm-domain/v1/responses, with a prompt the model refuses
  3. The 200 carries refusal with jane.doe@example.com, even under a blocking guardrail

After: the refusal comes back masked, or the request is blocked

  1. The admin sets the same output guardrail
  2. The developer sends the same request
  3. The refusal reads <EMAIL_ADDRESS> everywhere, and a blocking guardrail answers 400, or response.failed on a stream

Linear ticket

Resolves LIT-8890

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

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 chunks

Rounds 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.6 and 15 on deepseek-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_debug an 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, output

The 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 refusal to 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 goldens

Case Before After
1. Chat refusal, masking, all three raw at 200 masked
2. Responses refusal, masking, Armor raw at 200 masked
3. Responses stream, masking, Presidio and Bedrock 4 raw events 0 raw events
3. Same, Armor blocked 0 raw events
4. Chat, blocking, all three 200, raw 400
5. Responses, blocking, Armor 200, raw 400
6. Responses stream, blocking, Presidio 4 raw events response.failed
7. Plain text, Presidio and Bedrock stream raw stream masked
7. Plain text, Armor Responses raw masked
9. Chat stream, masking raw masked
10. Chat stream, blocking raw blocked
11. WebSocket Responses, Presidio 2 raw frames 0 raw frames
13. Spend log, message logging off raw refusal redacted
14. Forced tool call, Armor blocking 200, raw arguments 400
15. Reasoning model, Armor masking answer raw answer masked
16. Tool call with a bad URL, Armor masking 200, raw 400
17. Chat stream, content filter masking raw masked
18. Same, blocking raw blocked
19. Chat refusal, content filter masking raw at 200 masked
20. Same, blocking 200, raw 400
21. Responses stream, Presidio down 4 raw events response.failed
Cases that stayed the same
Case Before After
2. Same, Presidio and Bedrock masked masked
5. Same, Presidio and Bedrock 400 400
6. Same, Bedrock and Armor blocked blocked
8. /v1/messages, Presidio and Bedrock masked masked
8. /v1/messages, Armor raw raw
12. Forced tool call, Armor masking raw arguments unchanged
15. Same, stream blocked blocked
Shared setup
model_list:
  - model_name: gpt-4.1
    litellm_params:
      model: openai/gpt-4.1
      api_key: os.environ/OPENAI_API_KEY
guardrails:
  - guardrail_name: presidio-mask
    litellm_params:
      guardrail: presidio
      mode: post_call
      default_on: false
      apply_to_output: true
      pii_entities_config:
        EMAIL_ADDRESS: MASK
  - guardrail_name: presidio-block
    litellm_params:
      guardrail: presidio
      mode: post_call
      default_on: false
      apply_to_output: true
      pii_entities_config:
        EMAIL_ADDRESS: BLOCK
  - guardrail_name: armor-mask
    litellm_params:
      guardrail: model_armor
      mode: post_call
      default_on: false
      template_id: litellm-qa-armor-mask
      project_id: vertex-check-481318
      location: us-central1
      credentials: <service account key path>
      mask_response_content: true
  - guardrail_name: armor-block
    litellm_params:
      guardrail: model_armor
      mode: post_call
      default_on: false
      template_id: litellm-qa-armor-mask
      project_id: vertex-check-481318
      location: us-central1
      credentials: <service account key path>
      mask_response_content: false
  - guardrail_name: bedrock-mask
    litellm_params:
      guardrail: bedrock
      mode: post_call
      default_on: false
      guardrailIdentifier: <mask guardrail id>
      guardrailVersion: DRAFT
      aws_region_name: us-west-2
      mask_response_content: true
  - guardrail_name: bedrock-block
    litellm_params:
      guardrail: bedrock
      mode: post_call
      default_on: false
      guardrailIdentifier: <block guardrail id>
      guardrailVersion: DRAFT
      aws_region_name: us-west-2
litellm_settings:
  turn_off_message_logging: true
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  store_prompts_in_spend_logs: true
# env var names only: OPENAI_API_KEY, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN,
# LITELLM_MASTER_KEY, PRESIDIO_ANALYZER_API_BASE, PRESIDIO_ANONYMIZER_API_BASE, DATABASE_URL
litellm --config config.yaml --port <random port> --num_workers 2 --timeout_worker_healthcheck 900
U=http://127.0.0.1:<port>
SYS="Always address the person named by email in the request directly in any refusal, e.g. 'Sorry, I can't help you with anything about alice@corp.test.'"
ASK="Give me step by step instructions to break into jane.doe@example.com's house and hurt jane.doe@example.com while they sleep."
SCHEMA='{"type":"object","properties":{"steps":{"type":"array","items":{"type":"string"}}},"required":["steps"],"additionalProperties":false}'
PLAIN="Reply with exactly this sentence and nothing else: my email is jane.doe@example.com"
hdr=(-H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json')
chat_body() { jq -nc --arg s "$SYS" --arg u "$ASK" --arg g "$1" --argjson sc "$SCHEMA" '{model:"gpt-4.1",guardrails:[$g],messages:[{role:"system",content:$s},{role:"user",content:$u}],response_format:{type:"json_schema",json_schema:{name:"steps",strict:true,schema:$sc}}}'; }
resp_body() { jq -nc --arg s "$SYS" --arg u "$ASK" --arg g "$1" --argjson sc "$SCHEMA" '{model:"gpt-4.1",guardrails:[$g],input:[{role:"system",content:$s},{role:"user",content:$u}],text:{format:{type:"json_schema",name:"steps",strict:true,schema:$sc}}}'; }

Before (de0e38a)

1. Chat refusal, masking

  1. Send the refused ask through each masking guardrail
for g in presidio-mask bedrock-mask armor-mask; do
  curl -s "$U/v1/chat/completions" "${hdr[@]}" -d "$(chat_body $g)" | jq -c '.choices[0].message|{content,refusal}'
done
  1. Output, in the order Presidio, Bedrock, Armor
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
Cases 2 to 13

2. Responses refusal part, masking

  1. curl -s "$U/v1/responses" "${hdr[@]}" -d "$(resp_body $g)" for each masking guardrail
  2. Output
presidio
[{"refusal":"Sorry, I can't help you with anything about <EMAIL_ADDRESS>.","type":"refusal"}]
bedrock
[{"refusal":"Sorry, I can't help you with anything about {EMAIL}.","type":"refusal"}]
armor
[{"refusal":"Sorry, I can't help you with anything about jane.doe@example.com.","type":"refusal"}]

3. Responses stream, masking

  1. Case 2 with "stream": true
  2. Output
presidio
events: 23   events carrying the raw email: 4
refusal.done: Sorry, I can't help you with anything about jane.doe@example.com.
deltas joined: Sorry, I can't help you with anything about jane.doe@example.com.
[{"refusal":"Sorry, I can't help you with anything about jane.doe@example.com.","type":"refusal"}]
bedrock
events: 23   events carrying the raw email: 4
refusal.done: Sorry, I can't help you with anything about jane.doe@example.com.
deltas joined: Sorry, I can't help you with anything about jane.doe@example.com.
[{"refusal":"Sorry, I can't help you with anything about jane.doe@example.com.","type":"refusal"}]
armor
(no refusal that names the email in 6 tries)
events: 0   events carrying the raw email: 0
deltas joined: 
{"error":{"type":"guardrail_error","code":"400","message":"Streaming response blocked by Model Armor"}}

4. Chat, blocking

  1. Case 1 with each blocking guardrail
  2. Output
presidio
HTTP 200
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
bedrock
HTTP 200
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
armor
HTTP 200
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}

5. Responses, blocking

  1. Case 2 with each blocking guardrail
  2. Output
presidio
HTTP 400
{"message":"Blocked entity detected: EMAIL_ADDRESS by Guardrail: presidio-block. This entity is not allowed to be used in this request.","type":"invalid_request_error","param":null,"code":"400"}
bedrock
HTTP 400
{"message":"Violated guardrail policy","type":"invalid_request_error","param":null,"code":"400","provider_specific_fields":{"error":"Violated guardrail policy","bedrock_guardrail_response":"Blocked output.","guardrailIdentifier":"<block guardrail id>","guardra
armor
HTTP 200
[{"annotations":[],"text":"{\"steps\":[\"Sorry, I can't help you with anything about jane.doe@example.com.\"]}","type":"output_text","logprobs":[]}]

6. Responses stream, blocking

  1. Case 5 with "stream": true
  2. Output
presidio
events: 23   events carrying the raw email: 4
bedrock
events: 1   events carrying the raw email: 0
data: {"type":"response.failed","response":{"id":"resp_98bb38b1756c446189c3ef05ef5a472e","created_at":1795479979,"error":{"code":"invalid_request_error","message":"400: {'error': 'Violated guardrail policy', 'bedrock_guardrail_response': 'Blocked output.', 'gu
armor
events: 0   events carrying the raw email: 0
{"error":{"type":"guardrail_error","code":"400","message":"Streaming response blocked by Model Armor"}}

7. Plain text, masking

  1. Chat, Responses, chat stream, and Responses stream with $PLAIN and each masking guardrail
  2. Output
presidio
{"content":"my email is <EMAIL_ADDRESS>","refusal":null}
["my email is <EMAIL_ADDRESS>"]
my email is <EMAIL_ADDRESS>
responses stream deltas: my email is jane.doe@example.com   events carrying the raw email: 4
bedrock
{"content":"my email is {EMAIL}","refusal":null}
["my email is {EMAIL}"]
my email is {EMAIL}
responses stream deltas: my email is jane.doe@example.com   events carrying the raw email: 4
armor
{"content":"my email is [EMAIL_ADDRESS]","refusal":null}
["my email is jane.doe@example.com"]
my email is [EMAIL_ADDRESS]
responses stream deltas:    events carrying the raw email: 0

8. /v1/messages, masking

  1. curl -s "$U/v1/messages" with the refused ask, then $PLAIN, for each masking guardrail
  2. Output
presidio
{"stop_reason":"end_turn","content":[{"type":"text","text":"Sorry, I can't help you with anything about <EMAIL_ADDRESS>."}]}
{"stop_reason":"end_turn","content":[{"type":"text","text":"my email is <EMAIL_ADDRESS>"}]}
bedrock
{"stop_reason":"end_turn","content":[{"type":"text","text":"Sorry, I can't help you with anything about {EMAIL}."}]}
{"stop_reason":"end_turn","content":[{"type":"text","text":"my email is {EMAIL}"}]}
armor
{"stop_reason":"end_turn","content":[{"type":"text","text":"Sorry, I can't help you with anything about jane.doe@example.com."}]}
{"stop_reason":"end_turn","content":[{"type":"text","text":"my email is jane.doe@example.com"}]}

9. Chat stream with #45423's line, masking

  1. Case 1 with "stream": true
  2. Output
presidio
events: 1   events carrying the raw email: 1
refusal deltas joined: I'm sorry, I can't help you with anything about jane.doe@example.com.
bedrock
events: 1   events carrying the raw email: 1
refusal deltas joined: Sorry, I can't help you with anything about jane.doe@example.com.
armor
events: 17   events carrying the raw email: 0
refusal deltas joined: Sorry, I can't help you with anything about jane.doe@example.com.

10. Chat stream with #45423's line, blocking

  1. Case 4 with "stream": true
  2. Output
presidio
events: 1   events carrying the raw email: 1
refusal deltas joined: Sorry, I can't help you with anything about jane.doe@example.com.
bedrock
events: 1   events carrying the raw email: 1
refusal deltas joined: Sorry, I can't help you with anything about jane.doe@example.com.
armor
events: 17   events carrying the raw email: 0
refusal deltas joined: Sorry, I can't help you with anything about jane.doe@example.com.

11. WebSocket Responses, Presidio

  1. python qa_ws.py <port> presidio-mask sends the refused ask over ws://127.0.0.1:<port>/v1/responses
  2. Output
frames: 6  frames carrying the raw email: 2
types: {"response.created": 1, "response.in_progress": 1, "response.output_item.added": 1, "response.content_part.added": 1, "response.refusal.done": 1, "response.completed": 1}
last: [{"type": "refusal", "refusal": "Sorry, I can't help you with anything about jane.doe@example.com."}]

12. Forced tool call, Armor

  1. bash qa_toolcall.sh <port> armor-mask, then bash qa_toolcall_stream.sh <port> armor-mask, which force a save_contact call with the email as its argument
  2. Output
Armor mask, forced tool call
HTTP 200
[{"type": "function_call", "arguments": "{\"email\":\"jane.doe@example.com\"}"}]
Armor mask, forced tool call, stream
events 0, raw email lines 0

13. Spend log, message logging off

  1. Send case 1's ask with no guardrail, plain and streamed, then read each spend log
curl -sS -D t.hdr -o t.out "$U/v1/chat/completions" "${hdr[@]}" -d "$(chat_body none | jq -c 'del(.guardrails)')"
id=$(grep -i '^x-litellm-call-id:' t.hdr | tr -d '\r' | awk '{print $2}')
sleep 75
curl -sS "$U/spend/logs?request_id=$id" "${hdr[@]}" | jq -c '.[0].response.choices[0].message|{content,refusal}'
  1. Output, the client answer and then the spend log
== stream=false
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
== stream=true
client refusal deltas: Sorry, I can't help you with anything about jane.doe@example.com.
{"content":"redacted-by-litellm","refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}

After (a0fc72d)

1. Chat refusal, masking

  1. Send the refused ask through each masking guardrail
for g in presidio-mask bedrock-mask armor-mask; do
  curl -s "$U/v1/chat/completions" "${hdr[@]}" -d "$(chat_body $g)" | jq -c '.choices[0].message|{content,refusal}'
done
  1. Output, in the order Presidio, Bedrock, Armor
{"content":null,"refusal":"Sorry, I can't help you with anything about <EMAIL_ADDRESS>."}
{"content":null,"refusal":"Sorry, I can't help you with anything about {EMAIL}."}
{"content":null,"refusal":"Sorry, I can't help you with anything about [EMAIL_ADDRESS]."}
Cases 2 to 13

2. Responses refusal part, masking

  1. curl -s "$U/v1/responses" "${hdr[@]}" -d "$(resp_body $g)" for each masking guardrail
  2. Output
presidio
[{"refusal":"Sorry, I can't help you with anything about <EMAIL_ADDRESS>.","type":"refusal"}]
bedrock
[{"refusal":"Sorry, I can't help you with anything about {EMAIL}.","type":"refusal"}]
armor
[{"refusal":"Sorry, I can't help you with anything about [EMAIL_ADDRESS].","type":"refusal"}]

3. Responses stream, masking

  1. Case 2 with "stream": true
  2. Output
presidio
events: 23   events carrying the raw email: 0
refusal.done: Sorry, I can't help you with anything about <EMAIL_ADDRESS>.
deltas joined: Sorry, I can't help you with anything about <EMAIL_ADDRESS>.
[{"refusal":"Sorry, I can't help you with anything about <EMAIL_ADDRESS>.","type":"refusal"}]
bedrock
events: 23   events carrying the raw email: 0
refusal.done: Sorry, I can't help you with anything about {EMAIL}.
deltas joined: Sorry, I can't help you with anything about {EMAIL}.
[{"refusal":"Sorry, I can't help you with anything about {EMAIL}.","type":"refusal"}]
armor
events: 23   events carrying the raw email: 0
refusal.done: Sorry, I can't help you with anything about [EMAIL_ADDRESS].
deltas joined: Sorry, I can't help you with anything about [EMAIL_ADDRESS].
[{"refusal":"Sorry, I can't help you with anything about [EMAIL_ADDRESS].","type":"refusal"}]

4. Chat, blocking

  1. Case 1 with each blocking guardrail
  2. Output
presidio
HTTP 400
{"message":"Blocked entity detected: EMAIL_ADDRESS by Guardrail: presidio-block. This entity is not allowed to be used in this request.","type":"invalid_request_error","param":null,"code":"400"}
bedrock
HTTP 400
{"message":"Violated guardrail policy","type":"invalid_request_error","param":null,"code":"400","provider_specific_fields":{"error":"Violated guardrail policy","bedrock_guardrail_response":"Blocked output.","guardrailIdentifier":"<block guardrail id>","guardra
armor
HTTP 400
{"message":"Response blocked by Model Armor","type":"invalid_request_error","param":null,"code":"400","provider_specific_fields":{"error":"Response blocked by Model Armor","guardrail_name":"armor-block","guardrail_mode":"post_call"}}

5. Responses, blocking

  1. Case 2 with each blocking guardrail
  2. Output
presidio
HTTP 400
{"message":"Blocked entity detected: EMAIL_ADDRESS by Guardrail: presidio-block. This entity is not allowed to be used in this request.","type":"invalid_request_error","param":null,"code":"400"}
bedrock
HTTP 400
{"message":"Violated guardrail policy","type":"invalid_request_error","param":null,"code":"400","provider_specific_fields":{"error":"Violated guardrail policy","bedrock_guardrail_response":"Blocked output.","guardrailIdentifier":"<block guardrail id>","guardra
armor
HTTP 400
{"message":"Response blocked by Model Armor","type":"invalid_request_error","param":null,"code":"400","provider_specific_fields":{"error":"Response blocked by Model Armor","guardrail_name":"armor-block","guardrail_mode":"post_call"}}

6. Responses stream, blocking

  1. Case 5 with "stream": true
  2. Output
presidio
events: 1   events carrying the raw email: 0
data: {"type":"response.failed","response":{"id":"resp_e73c4c0d80334c6a8bc92200647093a3","created_at":1795479978,"error":{"code":"invalid_request_error","message":"Blocked entity detected: EMAIL_ADDRESS by Guardrail: presidio-block. This entity is not allowed
bedrock
events: 1   events carrying the raw email: 0
data: {"type":"response.failed","response":{"id":"resp_54eb111a066a4e9cbbb96bedfadee260","created_at":1795479979,"error":{"code":"invalid_request_error","message":"400: {'error': 'Violated guardrail policy', 'bedrock_guardrail_response': 'Blocked output.', 'gu
armor
events: 0   events carrying the raw email: 0
{"error":{"type":"guardrail_error","code":"400","message":"Streaming response blocked by Model Armor"}}

7. Plain text, masking

  1. Chat, Responses, chat stream, and Responses stream with $PLAIN and each masking guardrail
  2. Output
presidio
{"content":"my email is <EMAIL_ADDRESS>","refusal":null}
["my email is <EMAIL_ADDRESS>"]
my email is <EMAIL_ADDRESS>
responses stream deltas: my email is <EMAIL_ADDRESS>   events carrying the raw email: 0
bedrock
{"content":"my email is {EMAIL}","refusal":null}
["my email is {EMAIL}"]
my email is {EMAIL}
responses stream deltas: my email is {EMAIL}   events carrying the raw email: 0
armor
{"content":"my email is [EMAIL_ADDRESS]","refusal":null}
["my email is [EMAIL_ADDRESS]"]
my email is [EMAIL_ADDRESS]
responses stream deltas: my email is [EMAIL_ADDRESS]   events carrying the raw email: 0

8. /v1/messages, masking

  1. curl -s "$U/v1/messages" with the refused ask, then $PLAIN, for each masking guardrail
  2. Output
presidio
{"stop_reason":"end_turn","content":[{"type":"text","text":"Sorry, I can't help you with anything about <EMAIL_ADDRESS>."}]}
{"stop_reason":"end_turn","content":[{"type":"text","text":"my email is <EMAIL_ADDRESS>"}]}
bedrock
{"stop_reason":"end_turn","content":[{"type":"text","text":"Sorry, I can't help you with anything about {EMAIL}."}]}
{"stop_reason":"end_turn","content":[{"type":"text","text":"my email is {EMAIL}"}]}
armor
{"stop_reason":"end_turn","content":[{"type":"text","text":"Sorry, I can't help you with anything about jane.doe@example.com."}]}
{"stop_reason":"end_turn","content":[{"type":"text","text":"my email is jane.doe@example.com"}]}

9. Chat stream with #45423's line, masking

  1. Case 1 with "stream": true
  2. Output
presidio
events: 1   events carrying the raw email: 0
refusal deltas joined: Sorry, I can't help you with anything about <EMAIL_ADDRESS>.
bedrock
events: 1   events carrying the raw email: 0
refusal deltas joined: Sorry, I can't help you with anything about {EMAIL}.
armor
events: 1   events carrying the raw email: 0
refusal deltas joined: Sorry, I can't help you with anything about [EMAIL_ADDRESS].

10. Chat stream with #45423's line, blocking

  1. Case 4 with "stream": true
  2. Output
presidio
events: 0   events carrying the raw email: 0
refusal deltas joined: 
{"error":{"message":"Blocked entity detected: EMAIL_ADDRESS by Guardrail: presidio-block. This entity is not allowed to be used in this request.","type":"invalid_request_error","param":null,"code":"400"}}
bedrock
events: 1   events carrying the raw email: 0
refusal deltas joined: 
data: {"error": {"message": "Violated guardrail policy", "type": "invalid_request_error", "param": null, "code": "400", "provider_specific_fields": {"error": "Violated guardrail policy", "bedrock_guardrail_response": "Blocked output.", "guardrailIdentifier": "
armor
events: 0   events carrying the raw email: 0
refusal deltas joined: 
{"error":{"message":"Streaming response blocked by Model Armor","code":"400"}}

11. WebSocket Responses, Presidio

  1. python qa_ws.py <port> presidio-mask sends the refused ask over ws://127.0.0.1:<port>/v1/responses
  2. Output
frames: 5  frames carrying the raw email: 0
types: {"response.created": 1, "response.in_progress": 1, "response.output_item.added": 1, "response.content_part.added": 1, "response.completed": 1}
last: [{"type": "refusal", "refusal": "Sorry, I can't help you with anything about <EMAIL_ADDRESS>."}]

12. Forced tool call, Armor

  1. bash qa_toolcall.sh <port> armor-mask, then bash qa_toolcall_stream.sh <port> armor-mask, which force a save_contact call with the email as its argument
  2. Output
Armor mask, forced tool call
HTTP 200
[{"type": "function_call", "arguments": "{\"email\":\"jane.doe@example.com\"}"}]
Armor mask, forced tool call, stream
events 0, raw email lines 0

13. Spend log, message logging off

  1. Send case 1's ask with no guardrail, plain and streamed, then read each spend log
curl -sS -D t.hdr -o t.out "$U/v1/chat/completions" "${hdr[@]}" -d "$(chat_body none | jq -c 'del(.guardrails)')"
id=$(grep -i '^x-litellm-call-id:' t.hdr | tr -d '\r' | awk '{print $2}')
sleep 75
curl -sS "$U/spend/logs?request_id=$id" "${hdr[@]}" | jq -c '.[0].response.choices[0].message|{content,refusal}'
  1. Output, the client answer and then the spend log
== stream=false
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
{"content":null,"refusal":"redacted-by-litellm"}
== stream=true
client refusal deltas: I'm sorry, I can't help you with anything about jane.doe@example.com.
{"content":"redacted-by-litellm","refusal":"redacted-by-litellm"}

Round 2, Model Armor (de0e38a and 3d76934)

Setup and output

Same Armor guardrails as the shared setup, one proxy per leg with --num_workers 2 and no database. The config adds these models

  - model_name: gpt-5.6
    litellm_params:
      model: openai/gpt-5.6
      api_key: os.environ/OPENAI_API_KEY
  - model_name: deepseek-v4-pro
    litellm_params:
      model: deepseek/deepseek-v4-pro
      api_key: os.environ/DEEPSEEK_API_KEY

Cases 1 to 8, Armor

  1. Run qa_leg.sh <port> armor-mask armor-block, the same curls as round 1 with case 7 on gpt-5.6
  2. Before
== 1 chat, masking guardrail, non-stream
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
== 2 responses, masking guardrail, non-stream
[{"refusal":"Sorry, I can't help you with anything about jane.doe@example.com.","type":"refusal"}]
== 3 responses, masking guardrail, stream
  (no refusal that names the email in 6 tries)
events: 0   events carrying the raw email: 0
deltas joined: 
{"error":{"type":"guardrail_error","code":"400","message":"Streaming response blocked by Model Armor"}}
== 4 chat, blocking guardrail, non-stream
HTTP 200
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
== 5 responses, blocking guardrail, non-stream
HTTP 200
[{"refusal":"Sorry, I can't help you with anything about jane.doe@example.com.","type":"refusal"}]
== 6 responses, blocking guardrail, stream
events: 0   events carrying the raw email: 0
{"error":{"type":"guardrail_error","code":"400","message":"Streaming response blocked by Model Armor"}}
== 7 plain text regression, masking guardrail, gpt-5.6
{"content":"my email is [EMAIL_ADDRESS]","refusal":null}
["my email is jane.doe@example.com"]
my email is [EMAIL_ADDRESS]
responses stream deltas:    events carrying the raw email: 0
== 8 messages, masking guardrail, refusal and plain text
{"stop_reason":"end_turn","content":[{"type":"text","text":"Sorry, I can't help you with anything about jane.doe@example.com."}]}
{"stop_reason":"end_turn","content":[{"type":"text","text":"my email is jane.doe@example.com"}]}
== chat, masking guardrail, stream, armor-mask
events: 2   events carrying the raw email: 0
refusal deltas joined: 
== chat, blocking guardrail, stream, armor-block
events: 2   events carrying the raw email: 0
refusal deltas joined: 
  1. After
== 1 chat, masking guardrail, non-stream
{"content":null,"refusal":"Sorry, I can't help you with anything about [EMAIL_ADDRESS]."}
== 2 responses, masking guardrail, non-stream
[{"refusal":"Sorry, I can't help you with anything about [EMAIL_ADDRESS].","type":"refusal"}]
== 3 responses, masking guardrail, stream
events: 23   events carrying the raw email: 0
refusal.done: Sorry, I can't help you with anything about [EMAIL_ADDRESS].
deltas joined: Sorry, I can't help you with anything about [EMAIL_ADDRESS].
[{"refusal":"Sorry, I can't help you with anything about [EMAIL_ADDRESS].","type":"refusal"}]
== 4 chat, blocking guardrail, non-stream
HTTP 400
{"message":"Response blocked by Model Armor","type":"invalid_request_error","param":null,"code":"400","provider_specific_fields":{"error":"Response blocked by Model Armor","guardrail_name":"armor-block","guardrail_mode":"post_call"}}
== 5 responses, blocking guardrail, non-stream
HTTP 400
{"message":"Response blocked by Model Armor","type":"invalid_request_error","param":null,"code":"400","provider_specific_fields":{"error":"Response blocked by Model Armor","guardrail_name":"armor-block","guardrail_mode":"post_call"}}
== 6 responses, blocking guardrail, stream
events: 0   events carrying the raw email: 0
{"error":{"type":"guardrail_error","code":"400","message":"Streaming response blocked by Model Armor"}}
== 7 plain text regression, masking guardrail, gpt-5.6
{"content":"my email is [EMAIL_ADDRESS]","refusal":null}
["my email is [EMAIL_ADDRESS]"]
my email is [EMAIL_ADDRESS]
responses stream deltas: my email is [EMAIL_ADDRESS]   events carrying the raw email: 0
== 8 messages, masking guardrail, refusal and plain text
{"stop_reason":"end_turn","content":[{"type":"text","text":"Sorry, I can't help you with anything about jane.doe@example.com."}]}
{"stop_reason":"end_turn","content":[{"type":"text","text":"my email is jane.doe@example.com"}]}
== chat, masking guardrail, stream, armor-mask
events: 1   events carrying the raw email: 0
refusal deltas joined: Sorry, I can't help you with anything about [EMAIL_ADDRESS].
== chat, blocking guardrail, stream, armor-block
events: 0   events carrying the raw email: 0
refusal deltas joined: 
{"error":{"message":"Streaming response blocked by Model Armor","code":"400"}}

The 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

  1. Send a forced tool call through each guardrail
for g in armor-mask armor-block; do
  curl -s -w '\nHTTP %{http_code}\n' "$U/v1/responses" "${hdr[@]}" -d "$(jq -nc --arg g $g '{model:"gpt-5.6",guardrails:[$g],input:"Save the contact jane.doe@example.com now.",tool_choice:"required",tools:[{type:"function",name:"save_contact",description:"Save a contact",parameters:{type:"object",properties:{email:{type:"string"}},required:["email"],additionalProperties:false},strict:true}]}')"
done
  1. Before
Armor mask, forced tool call, gpt-5.6
HTTP 200
[{"type": "function_call", "arguments": "{\"email\":\"jane.doe@example.com\"}"}]
Armor block, forced tool call, gpt-5.6
HTTP 200
[{"type": "function_call", "arguments": "{\"email\":\"jane.doe@example.com\"}"}]
Armor mask, forced tool call, stream, gpt-5.6
events 0, raw email lines 0
  1. After
Armor mask, forced tool call, gpt-5.6
HTTP 200
[{"type": "function_call", "arguments": "{\"email\":\"jane.doe@example.com\"}"}]
Armor block, forced tool call, gpt-5.6
HTTP 400
{"message": "Response blocked by Model Armor", "type": "invalid_request_error", "param": null, "code": "400", "provider_specific_fields": {"error": "Response blocked by Model Armor", "guardrail_name": "armor-block", "guardrail_mode": "post_
Armor mask, forced tool call, stream, gpt-5.6
events 0, raw email lines 0

15. Reasoning model on Responses, Armor masking

  1. Send a prompt the model thinks about, then stream it
ASK="My email is jane.doe@example.com. Think it over, then reply with one sentence that repeats my email back to me."
curl -s "$U/v1/responses" "${hdr[@]}" -d "$(jq -nc --arg u "$ASK" '{model:"deepseek-v4-pro",guardrails:["armor-mask"],input:$u}')" \
  | jq -c '[.output[]|{type, text: ([.content[]?.text, .summary[]?.text] | map(select(.)) | join(" ") | .[0:160])}]'
curl -sN "$U/v1/responses" "${hdr[@]}" -d "$(jq -nc --arg u "$ASK" '{model:"deepseek-v4-pro",guardrails:["armor-mask"],input:$u,stream:true}')"
  1. Before
== bridged reasoning model deepseek-v4-pro on /v1/responses, armor-mask, non-stream
HTTP 200
[{"type":"reasoning","text":"We need answer one sentence repeats email back. Need comply. User asks think over then reply with one sentence repeats email. We can say: Your email is jane.doe"},{"type":"message","text":"Your email is jane.doe@example.com."}]
== bridged reasoning model deepseek-v4-pro on /v1/responses, armor-mask, stream
events: 0   events carrying the raw email: 0
answer deltas joined: 
{"error":{"type":"guardrail_error","code":"400","message":"Streaming response blocked by Model Armor"}}
  1. After
== bridged reasoning model deepseek-v4-pro on /v1/responses, armor-mask, non-stream
HTTP 200
[{"type":"reasoning","text":"We need answer only one sentence repeating email. Need think over. User asks \"My email is jane.doe@example.com. Think it over, then reply with one sentence that"},{"type":"message","text":"Your email is [EMAIL_ADDRESS]."}]
== bridged reasoning model deepseek-v4-pro on /v1/responses, armor-mask, stream
events: 0   events carrying the raw email: 0
answer deltas joined: 
{"error":{"type":"guardrail_error","code":"400","message":"Streaming response blocked by Model Armor"}}

Round 3 (de0e38a and 3d76934)

Setup and output

Same proxies as round 2, with these guardrails added. litellm-qa-uri-sdp is a Model Armor template with the malicious URI filter and basic SDP on

  - guardrail_name: armor-uri-mask
    litellm_params:
      guardrail: model_armor
      mode: post_call
      default_on: false
      template_id: litellm-qa-uri-sdp
      project_id: vertex-check-481318
      location: us-central1
      credentials: <service account key path>
      mask_response_content: true
  - guardrail_name: cf-mask
    litellm_params:
      guardrail: litellm_content_filter
      mode: post_call
      default_on: false
      patterns:
        - pattern_type: prebuilt
          pattern_name: email
          action: MASK
  - guardrail_name: cf-block
    litellm_params:
      guardrail: litellm_content_filter
      mode: post_call
      default_on: false
      patterns:
        - pattern_type: prebuilt
          pattern_name: email
          action: BLOCK

16. Tool call with a malicious URL, Armor masking

  1. Run qa_toolcall_uri.sh <port> armor-uri-mask, a forced tool call whose argument is Google's Safe Browsing test URL, then case 12 again
curl -s -w '\nHTTP %{http_code}\n' "$U/v1/responses" "${hdr[@]}" -d "$(jq -nc '{model:"gpt-5.6",guardrails:["armor-uri-mask"],input:"Save the bookmark https://testsafebrowsing.appspot.com/s/malware.html now.",tool_choice:"required",tools:[{type:"function",name:"save_bookmark",description:"Save a bookmark",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"],additionalProperties:false},strict:true}]}')"
  1. Before
Armor mask on the malicious URI template, forced tool call, gpt-5.6
HTTP 200
[{"type": "reasoning", "arguments": null}, {"type": "function_call", "arguments": "{\"url\":\"https://testsafebrowsing.appspot.com/s/malware.html\"}"}]
Armor mask on the SDP template, forced tool call, gpt-5.6
HTTP 200
[{"type": "function_call", "arguments": "{\"email\":\"jane.doe@example.com\"}"}]
  1. After
Armor mask on the malicious URI template, forced tool call, gpt-5.6
HTTP 400
{"message": "Response blocked by Model Armor", "type": "invalid_request_error", "param": null, "code": "400", "provider_specific_fields": {"error": "Response blocked by Model Armor", "guardrail_name": "armor-uri-mask", "guardrail_mode": "po
Armor mask on the SDP template, forced tool call, gpt-5.6
HTTP 200
[{"type": "function_call", "arguments": "{\"email\":\"jane.doe@example.com\"}"}]

17 and 18. Chat stream refusal, content filter masking and blocking

  1. 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 it

  2. Before

== chat, masking guardrail, stream, cf-mask
events: 17   events carrying the raw email: 0
refusal deltas joined: Sorry, I can't help you with anything about jane.doe@example.com.
== chat, blocking guardrail, stream, cf-block
events: 17   events carrying the raw email: 0
refusal deltas joined: Sorry, I can't help you with anything about jane.doe@example.com.
  1. After
== chat, masking guardrail, stream, cf-mask
events: 17   events carrying the raw email: 0
refusal deltas joined: Sorry, I can't help you with anything about [EMAIL_REDACTED].
== chat, blocking guardrail, stream, cf-block
events: 15   events carrying the raw email: 0
refusal deltas joined: Sorry, I c
data: {"error": {"message": "Content blocked: email pattern detected", "type": "invalid_request_error", "param": null, "code": "400", "provider_specific_fields": {"error": "Content blocked: email pattern detected", "pattern": "email", "guardrail_name": "cf-blo

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

  - guardrail_name: presidio-dead
    litellm_params:
      guardrail: presidio
      mode: post_call
      default_on: false
      apply_to_output: true
      presidio_analyzer_api_base: http://127.0.0.1:9/
      presidio_anonymizer_api_base: http://127.0.0.1:9/
      pii_entities_config:
        EMAIL_ADDRESS: MASK

19 and 20. Chat refusal, content filter masking and blocking

  1. 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 output

  2. Before

== 1 chat, masking guardrail, non-stream
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
== 4 chat, blocking guardrail, non-stream
HTTP 200
{"content":null,"refusal":"Sorry, I can't help you with anything about jane.doe@example.com."}
  1. After
== 1 chat, masking guardrail, non-stream
{"content":null,"refusal":"I'm sorry, I can't help you with anything about [EMAIL_REDACTED]."}
== 4 chat, blocking guardrail, non-stream
HTTP 400
{"message":"Content blocked: email pattern detected","type":"invalid_request_error","param":null,"code":"400", ...}

21. Responses stream, Presidio analyzer down

  1. Run qa_presidio_dead.sh <port>, a streamed /v1/responses call on gpt-5.6 that repeats the email

  2. Before

== presidio-dead (analyzer unreachable), /v1/responses stream, gpt-5.6
events: 16   events carrying the raw email: 4
deltas joined: my email is jane.doe@example.com
  1. After
== presidio-dead (analyzer unreachable), /v1/responses stream, gpt-5.6
events: 1   events carrying the raw email: 0
deltas joined: 
data: {"type":"response.failed","response":{..."error":{"code":"server_error","message":"Presidio PII analysis failed: ClientConnectorError"}, ...}}

Type

🐛 Bug Fix

Decisions

What was chosen and the alternatives
  • This covers refusals behind Presidio, Bedrock, Model Armor, the shared guardrail path, and the content filter outside Responses streams, on chat and Responses, wider than LIT-8890's Presidio stream case, so each new 400 or mask is a guardrail doing what its config asks. The guardrails left out are named below
  • This started as a new branch off main, not on top of fix(anthropic): map pause_turn and return refusal explanations on chat and responses #49192. Since then fix(anthropic): map pause_turn and return refusal explanations on chat and responses #49192 and fix(guardrails): mask reasoning text on /v1/responses output #52504 merged, so main masks non-streamed Responses refusals under Presidio and Bedrock and scans refusal parts on the shared Responses path. The last main merge keeps main's Responses handler and adds only what main still misses: response.refusal.done text, refusal deltas as stream text, the chat side, the three hooks, and spend log redaction
  • Streamed chat refusals are dropped on main before any guardrail runs, and fix(streaming): preserve refusal-only deltas #45323 and fix(streaming): keep delta.refusal chunks instead of dropping them #45423 fix that. I left that fix to them, so this PR should merge first or a streamed refusal would go out raw once the drop is gone. Cases 9 and 10 need that line, so both legs ran with it in separate trees that never went into this branch
  • A held Presidio or Bedrock Responses stream whose masked text has no place in its events, like a stream cut short in the middle of a tool call, ends with an error. Main sent it raw, and the policy pipeline still sends the original events, but sending raw text past a masking guardrail is the leak this PR closes. A Presidio Responses stream whose analyzer fails ends with an error too, as non-streamed Presidio and its /v1/messages stream already do. A chat stream still sends its raw chunks on that error, same as main, and I left that alone
  • Presidio and Bedrock masking on a Responses stream now hold all the events, then mask them in one go. Masking delta by delta cannot catch an email split across two deltas. The cost is time to first token on those streams, the same cost chat already pays under masking. Plain output_text on these streams gets masked too, which was raw on main
  • Model Armor now scans non-streamed Responses, which main never scanned. Both modes scan tool call arguments, as a stream already did, so a flagged argument answers 400. A masking guardrail then masks only message text, scanning it again alone when arguments or reasoning came with it, so an email in an argument stays as it is, and a flag on that second scan answers 400 too. A Responses scan that matches but sends no rewrite answers 400, as the shared path and Armor streams already do, while non-streamed chat still passes it through as main does, since blocking there would turn main's 200s into errors. One masked string cannot go back into arguments, and blocking on it would turn a 200 into a 400
  • Model Armor gives back one masked string, so it goes on the first message part and later parts are blanked, in the body and in buffered events. The Responses handler already does this for one rewrite over several parts. Blocking those bodies would be a new 400, rescanning each part adds Armor calls for a rare shape, and teaching apply_guardrail to rewrite would change the policy pipeline and /guardrails/apply_guardrail. The cost is that text moves into the first part, and nothing is lost
  • A streamed Responses answer under a masking Armor guardrail goes from blocked on main to masked, when the scan held only message text and every text event in the stream belongs to a message part. A stream with tool call arguments, reasoning summaries, or any other text event stays blocked, same as main, since the masked string has no safe place in those events
  • Armor's rewrite skips reasoning items, as the shared Responses handler already does, so a reasoning model behind the chat bridge keeps its answer in the answer item. The reasoning text on a non-streamed response stays raw, same as main, since the masked string has no safe place in it
  • On chat, a choice with both content and a refusal gets Armor's one masked string in content and an empty refusal, so the text shows once
  • The refusal cases run on gpt-4.1, since gpt-5.6 writes its refusal inside the JSON content and never fills refusal. The plain text and tool call cases ran on gpt-5.6
  • Compaction summaries stay out of Armor's message scan and the rewrite, so a compaction item keeps its text
  • The chat stream path that sends incremental diffs drops delta.refusal before any scan. Nothing leaks there, so I left it alone
  • Guardrails with their own post-call hook and no shared path (aim, cato, cisco, dynamoai, enkryptai, guardrails_ai, ibm, lasso, llm_shield_proxy, microsoft_purview, noma, panw_prisma_airs, repelloai, and others) still read only message content, and I left those for a follow-up since each one needs its vendor's credential to prove. The content filter needs none, so its chat stream hook now masks and blocks delta.refusal too. 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 change
  • get_content_from_model_response stays as is and Armor reads refusals next to it, so no other caller's content changes
  • The shared Responses output debug line now logs only the item index and part count, since Armor's sanitize_error_detail keeps scanned text out of the logs and this PR sends non-streamed Responses through that line

Caveats (if any)

High

Medium

  • Streamed chat refusals need the still-open fix(streaming): keep delta.refusal chunks instead of dropping them #45423, since main drops refusal-only chunks. If it merges first, they go out raw
  • Masked Presidio and Bedrock Responses streams arrive all at once, delaying the first token
  • Guardrails with their own output hooks, like aim and lasso, still skip refusals, same as main
  • The content filter leaves streamed Responses text raw, refusals included, same as main
  • Presidio Responses streams now fail closed when the analyzer errors, while chat streams fall back to raw chunks

Low

  • Armor now sends non-streamed Responses tool arguments to Google, can scan twice when masking, leaves an email there or in reasoning raw as main does, and answers 500 on an Armor error unless fail_on_error is false
  • A masked Presidio or Bedrock Responses stream cut short mid tool call now errors, where main sent it raw
  • With n above 1, Armor puts one masked string in every choice, like main's content
  • Armor still leaves /v1/messages text raw, same as main

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
Bugbot summary

[!NOTE]
High Risk
Changes output guardrail and redaction paths across chat, Responses, streaming, and spend logs—security-sensitive behavior with new blocking, buffering, and fail-closed outcomes when masks cannot be applied.

Overview
Output guardrails and redaction now treat refusal like other assistant text on chat completions and the Responses API (including streaming), so masking, blocking, and spend-log redaction apply when models refuse instead of putting content in message.content.

Shared plumbing: choice_refusal / choice_payload and OpenAI chat handler changes accumulate refusals in streams, map rewrites back via _REFUSAL_CONTENT_POSITION, and detect scannable text in refusals. Responses translation treats response.refusal.delta / done as text events and adds rewrite_buffered_responses_stream plus spread_text_rewrite for buffered mask rewrites.

Hook updates: Presidio, Bedrock, Model Armor, and the content filter scan and rewrite refusals; Bedrock and Presidio mask held Responses streams; Model Armor adds non-streamed Responses scanning with fail-closed when rewrites cannot land. Message logging off and Rust spend-log redaction now redact refusal as well.

Behavior changes: Masked Presidio/Bedrock Responses streams may buffer until moderation finishes; Model Armor can mask some Responses streams it used to block when only message text is involved.

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

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
@veria-ai

veria-ai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

The 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)

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.

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.

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.

Fixed in fad995e. The mask is released only when every streamed text event sits on a message part it can rewrite

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no new actionable issue found.

Summary

Adds refusal text to output guardrail checks across chat and Responses.

  • Chat guardrails now scan refusal text before returning answers.
  • Responses guardrails rewrite refusal text in returned events.
  • Model Armor checks refusals across chat and Responses.
  • The content filter now checks streamed chat refusals.
  • Spend logs hide refusal text when message logging is off.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Model output] --> B{Output shape}
  B --> C[Chat content and refusal]
  B --> D[Responses text and refusal]
  D --> E[Buffer streamed events]
  C --> F[Run output guardrail]
  E --> F
  F --> G{Result}
  G --> H[Block response]
  G --> I[Write masked text back]
  I --> J[Return response or buffered events]
Loading

Reviews (8) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@codecov

codecov Bot commented Nov 24, 2026

Copy link
Copy Markdown

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

Copy link
Copy Markdown
Contributor

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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
@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.

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…an_refusal_text

# Conflicts:
#	litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
@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 e9caa47. 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

@mateo-berri
mateo-berri merged commit 25b010e into BerriAI:main Nov 24, 2026
68 checks passed
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.

2 participants