Skip to content

fix(guardrails): mask reasoning text on /v1/responses output - #52504

Merged
mateo-berri merged 9 commits into
BerriAI:mainfrom
quietjules:litellm_mask_responses_reasoning_summary
Nov 19, 2026
Merged

mateo-berri merged 9 commits into
BerriAI:mainfrom
quietjules:litellm_mask_responses_reasoning_summary

Conversation

@quietjules

@quietjules quietjules commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

A masking guardrail on the Responses API only masks the answer, so the word it should hide still reaches the client through the reasoning

This PR sends the reasoning to the guardrail in one call after the answer and masks the response and every stream event. Claude's signatures stay, so the reasoning still replays on the next turn

Original

TLDR

Problem this solves:

  • Post-call MASK leaves reasoning text raw on /v1/responses
  • Claude also leaks through encrypted_content and provider_specific_fields

How it solves it:

  • The reasoning goes to the guardrail in one call after the answer
  • Streamed reasoning that a cut-short final event leaves out is scanned too
  • The mask reaches the response and every stream event
  • Claude thinking is masked in the signed blob, signature kept

Intentional product change: BLOCK now also fires on a reasoning-only match, with 400 or response.failed instead of 200.

User Flow

Before: a developer behind a masking guardrail still sees the masked word in the reasoning of a /v1/responses reply

  1. The proxy admin attaches a post_call policy that masks the word persimmon
  2. The developer sends POST https://litellm-domain/v1/responses with "reasoning": {"effort": "high", "summary": "detailed"} and "stream": true
  3. The answer arrives as [KEYWORD_REDACTED]
  4. response.reasoning_summary_text.done and output[0].summary still show persimmon, and on Claude so does encrypted_content

After: the reasoning carries the same mask as the answer and the next turn still works

  1. The proxy admin attaches a post_call policy that masks the word persimmon
  2. The developer sends POST https://litellm-domain/v1/responses with "reasoning": {"effort": "high", "summary": "detailed"} and "stream": true
  3. The answer arrives as [KEYWORD_REDACTED]
  4. Every reasoning event shows [KEYWORD_REDACTED], and no event has the raw word
  5. The developer sends the reasoning item back on the next POST https://litellm-domain/v1/responses and gets 200

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: 1739875. /live-pr-risk ran on 53c350d. Since then, a stream with no final event masks reasoning only its finished item holds, and an empty output masks provider thinking. No dependent changed, and an empty reply without thinking makes no guardrail call. Verification: old and new code agree on 55 captured streams

Each leg ran 2 uvicorn workers per proxy and its own Redis, against real OpenAI, Anthropic, Vertex, Azure AI Foundry, and Databricks. Reasoning cases retry up to 15 times until the word appears

Setup

pipeline.yaml:

model_list:
  - model_name: gpt-5.6
    litellm_params:
      model: openai/gpt-5.6
      api_key: os.environ/OPENAI_API_KEY
  - model_name: claude-sonnet-5-5
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: claude-sonnet-vertex
    litellm_params:
      model: vertex_ai/claude-sonnet-4-6
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: os.environ/VERTEXAI_LOCATION
      vertex_credentials: os.environ/GOOGLE_APPLICATION_CREDENTIALS
  - model_name: gpt-5-mini
    litellm_params:
      model: openai/gpt-5-mini
      api_key: os.environ/OPENAI_API_KEY
  - model_name: claude-opus-foundry
    litellm_params:
      model: azure_ai/claude-opus-5-5
      api_base: os.environ/E2E_CLAUDE_FOUNDRY_API_BASE
      api_key: os.environ/E2E_CLAUDE_FOUNDRY_API_KEY
  - model_name: claude-databricks
    litellm_params:
      model: databricks/databricks-claude-sonnet-5-5
      api_base: os.environ/DATABRICKS_API_BASE
      api_key: os.environ/DATABRICKS_API_KEY
guardrails:
  - guardrail_name: output-word-filter
    litellm_params:
      guardrail: litellm_content_filter
      mode: post_call
      blocked_words:
        - keyword: persimmon
          action: MASK
        - keyword: umbrella
          action: BLOCK
policies:
  response-governance:
    guardrails:
      add: [output-word-filter]
    pipeline:
      mode: post_call
      steps:
        - guardrail: output-word-filter
          on_pass: allow
          on_fail: block
policy_attachments:
  - policy: response-governance
    scope: global
router_settings:
  redis_host: 127.0.0.1
  redis_port: 25449
general_settings:
  coordination_redis:
    host: 127.0.0.1
    port: 25449

direct.yaml has the same first two models, the same guardrail with default_on: true and only the persimmon rule, the same Redis block, and no policy. The before leg ran its own Redis on another port

redis-server --port 25449 --bind 127.0.0.1 --save '' --appendonly no &
python litellm/proxy/proxy_cli.py --config pipeline.yaml --port $PORT --num_workers 2 --timeout_worker_healthcheck 60
URL=http://127.0.0.1:$PORT
PROMPT='Think step by step in your reasoning: name the fruit with orange skin, very astringent when unripe, Diospyros genus, and spell it letter by letter while you reason, then compute its letter count squared plus 17 and test primality. Your entire reply must be exactly the fruit name in lowercase, nothing else.'
TOOL_PROMPT='Think step by step about which fruit has orange skin and is in the Diospyros genus, write the name of the fruit in your reasoning, then call lookup_fruit with that name.'
BLOCK_PROMPT='Think step by step in your reasoning: name the everyday object people open over their heads when it rains, and spell it letter by letter while you reason. Then count its letters. Your entire reply must be only that count as a digit, and you must never write the object name in your reply.'
TRUNC_PROMPT='Search the web for the current price of persimmons at Kroger, Walmart, Whole Foods, Publix, and Instacart. In your reasoning, name the fruit persimmon every time you weigh a store. Then write a very long, detailed comparison table of every store.'
TOOLS='[{"type":"function","name":"lookup_fruit","description":"Look up a fruit by name","parameters":{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}}]'
body() { jq -nc --arg m "$1" --arg p "$PROMPT" --argjson s "$2" '{model:$m,stream:$s,input:$p,max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"}}'; }
events() { grep '^data: ' "$1" | sed 's/^data: //' | grep -v '^\[DONE\]'; }
post() { curl -sS -m 300 -D "$1.hdr" -o "$1" $URL/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$2"; }
Case Before After
gpt-5.6 stream Word in 4 event types Masked
gpt-5.6 non-stream Word in summary Masked
OpenAI SDK stream Word shown Masked
Claude non-stream Word in blob Masked, signature kept
Claude stream Word in 4 event types Masked
Stream cut short Word in streamed part Masked
Direct guardrail Word in summary Masked
Plain answer Masked Masked
Claude tool replay 200 200
Claude replay, no tool or no match 200 200
Vertex, Foundry, Databricks Claude tool replay 200, word in reasoning 200, masked
gpt-5.6 replay, stateless and stored 200 200
BLOCK word in reasoning 200, word shown 400
Same, stream 200, word shown response.failed
GET /v1/responses/{id} Word in summary Masked
/v1/chat/completions and /v1/messages Claude Thinking raw Thinking raw

Before (436f6d5)

gpt-5.6 stream

  1. post gpt-stream.sse "$(body gpt-5.6 true)"
  2. events gpt-stream.sse | jq -c 'select(.type|test("(reasoning_summary|output)_text.done")) | {type, text: (.text|match(".{0,30}(persimmon|KEYWORD_REDACTED).{0,10}").string)}'
    {"type":"response.reasoning_summary_text.done","text":" fruit in lowercase, which is persimmon. I’m coun"}
    {"type":"response.output_text.done","text":"[KEYWORD_REDACTED]"}
    
  3. events gpt-stream.sse | jq -r 'select(tostring|ascii_downcase|contains("persimmon")) | .type' | sort | uniq -c
          1 response.completed
          1 response.output_item.done
          1 response.reasoning_summary_part.done
          1 response.reasoning_summary_text.done
    
Every other case, before

gpt-5.6 non-stream

  1. post gpt-nonstream.json "$(body gpt-5.6 false)"
  2. jq -c '[.output[] | if .type=="reasoning" then {type, summary: ([.summary[].text]|join(" ")|.[0:140])} else {type, text: .content[0].text} end]' gpt-nonstream.json
    [{"type":"reasoning","summary":"**Following output instructions**\n\nI need to make sure I provide the output exactly as instructed. The fruit is \"persimmon,\" and it should b"},{"type":"message","text":"[KEYWORD_REDACTED]"}]
    

OpenAI Python SDK 2.54.0 stream

  1. python sdk_stream.py $URL $LITELLM_MASTER_KEY
    streamed deltas have the word: True
    final summary has the word: True
    final summary is masked: False
    answer: [KEYWORD_REDACTED]
    

Claude non-stream

  1. post claude-nonstream.json "$(body claude-sonnet-5-5 false)"
  2. jq -c '{content: ([.output[]|select(.type=="reasoning")|.content[]?.text]|join(" ")|.[0:90]), blob: ([.output[]|select(.type=="reasoning")|.encrypted_content]|join(" ")|.[0:90]), provider: (.provider_specific_fields.thinking_blocks[0].thinking//""|.[0:90]), answer: ([.output[]|select(.type=="message")|.content[0].text]|join(" ")), has_signature: ([.output[]|select(.type=="reasoning")|.encrypted_content]|join(" ")|contains("signature"))}' claude-nonstream.json
    {"content":"I'm settling on [KEYWORD_REDACTED] as the fruit, and since the reply has to be just the na","blob":"[{\"type\":\"thinking\",\"thinking\":\"I'm settling on persimmon as the fruit, and since the repl","provider":"I'm settling on persimmon as the fruit, and since the reply has to be just the name in low","answer":"[KEYWORD_REDACTED]","has_signature":true}
    

Claude stream

  1. post claude-stream.sse "$(body claude-sonnet-5-5 true)"
  2. events claude-stream.sse | jq -c 'select(.type|test("(reasoning_summary|output)_text.done")) | {type, text: (.text|match(".{0,30}(persimmon|keyword_redacted).{0,10}"; "i").string)}'
    {"type":"response.reasoning_summary_text.done","text":"I'm picking persimmon as the fr"}
    {"type":"response.output_text.done","text":"[KEYWORD_REDACTED]"}
    
  3. events claude-stream.sse | jq -r 'select(tostring|ascii_downcase|contains("persimmon")) | .type' | sort | uniq -c
          1 response.completed
          1 response.output_item.done
          1 response.reasoning_summary_part.done
          1 response.reasoning_summary_text.done
    

gpt-5-mini stream cut short by max_output_tokens

  1. post gpt-truncated.sse "$(jq -nc --arg q "$TRUNC_PROMPT" '{model:"gpt-5-mini",stream:true,input:$q,tools:[{type:"web_search"}],max_output_tokens:1500,reasoning:{effort:"medium",summary:"detailed"}}')"
  2. events gpt-truncated.sse | jq -r 'select(.type|test("^response\\.(completed|incomplete|failed)$")) | .type'
    response.incomplete
    
  3. events gpt-truncated.sse | jq -s -c '(.[-1].response.output) as $o | [.[] | select(.type=="response.reasoning_summary_text.delta")] | group_by([.output_index, .summary_index])[] | (map(.delta)|join("")) as $t | {output_index: .[0].output_index, summary_index: .[0].summary_index, in_final_event: (($o[.[0].output_index].summary[.[0].summary_index].text // "") | startswith($t)), word: ($t|ascii_downcase|contains("persimmon")), masked: ($t|contains("KEYWORD_REDACTED"))} | select(.word or .masked)'
    {"output_index":0,"summary_index":0,"in_final_event":true,"word":true,"masked":false}
    {"output_index":0,"summary_index":1,"in_final_event":true,"word":true,"masked":false}
    {"output_index":6,"summary_index":0,"in_final_event":true,"word":true,"masked":false}
    {"output_index":10,"summary_index":0,"in_final_event":true,"word":true,"masked":false}
    {"output_index":12,"summary_index":0,"in_final_event":false,"word":true,"masked":false}
    

Direct default_on guardrail, no policy, gpt-5.6 non-stream

  1. post direct-gpt-nonstream.json "$(body gpt-5.6 false)"   # URL of the direct.yaml proxy
  2. jq -c '[.output[] | if .type=="reasoning" then {type, summary: ([.summary[].text]|join(" ")|.[0:140])} else {type, text: .content[0].text} end]' direct-gpt-nonstream.json
    [{"type":"reasoning","summary":"**Identifying the fruit**\n\nI need to focus on the request for identifying a fruit, specifically persimmon. It has 9 letters, which is exactl"},{"type":"message","text":"[KEYWORD_REDACTED]"}]
    

Plain answer with no reasoning

  1. post plain-answer.json '{"model":"gpt-5.6","input":"Reply with exactly this word and nothing else: persimmon"}'
  2. jq -c '[.output[]|select(.type=="message")|.content[0].text]' plain-answer.json
    ["[KEYWORD_REDACTED]"]
    

Claude tool replay

  1. post claude-tool-1.json "$(jq -nc --arg q "$TOOL_PROMPT" --argjson t "$TOOLS" '{model:"claude-sonnet-5-5",input:$q,tools:$t,tool_choice:"auto",max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"}}')"
  2. post claude-tool-2.json "$(jq -c --arg q "$TOOL_PROMPT" --argjson t "$TOOLS" '{model:"claude-sonnet-5-5",tools:$t,max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"},input:([{role:"user",content:$q}] + [.output[] | del(.status)] + [{type:"function_call_output",call_id:(.output[] | select(.type=="function_call") | .call_id),output:"found: orange fruit"}])}' claude-tool-1.json)"
  3. sed -n 1p claude-tool-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  4. jq -c '[.output[]|select(.type=="reasoning")|tostring|ascii_downcase|{word: contains("persimmon"), masked: contains("keyword_redacted")}]' claude-tool-1.json
    [{"word":true,"masked":true}]
    

Claude replay with no tool

  1. post claude-replay-2.json "$(jq -c '{model:"claude-sonnet-5-5",max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"},input:([{role:"user",content:"Name the fruit from before."}] + [.output[] | del(.status)] + [{role:"user",content:"Now say done."}])}' claude-nonstream.json)"
  2. sed -n 1p claude-replay-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    

Vertex Claude tool replay

  1. Same two requests as the Claude tool replay with claude-sonnet-vertex, saved as vertex-tool-1.json and vertex-tool-2.json
  2. sed -n 1p vertex-tool-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  3. jq -c '[.output[]|select(.type=="reasoning")|tostring|ascii_downcase|{word: contains("persimmon"), masked: contains("keyword_redacted")}]' vertex-tool-1.json
    [{"word":true,"masked":true}]
    

Azure AI Foundry Claude tool replay

  1. Same two requests as the Claude tool replay with claude-opus-foundry, saved as foundry-tool-1.json and foundry-tool-2.json
  2. sed -n 1p foundry-tool-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  3. jq -c '[.output[]|select(.type=="reasoning")|tostring|ascii_downcase|{word: contains("persimmon"), masked: contains("keyword_redacted")}]' foundry-tool-1.json
    [{"word":true,"masked":true}]
    

Databricks Claude tool replay

  1. Same two requests as the Claude tool replay with claude-databricks, saved as databricks-tool-1.json and databricks-tool-2.json
  2. sed -n 1p databricks-tool-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  3. jq -c '[.output[]|select(.type=="reasoning")|tostring|ascii_downcase|{word: contains("persimmon"), masked: contains("keyword_redacted")}]' databricks-tool-1.json
    [{"word":true,"masked":true}]
    

gpt-5.6 replay, stateless

  1. post gpt-state-1.json "$(body gpt-5.6 false | jq -c '. + {store:false,include:["reasoning.encrypted_content"]}')"
  2. post gpt-state-2.json "$(jq -c '{model:"gpt-5.6",store:false,include:["reasoning.encrypted_content"],reasoning:{effort:"low"},input:([{role:"user",content:"Name the fruit."}] + [.output[] | del(.status)] + [{role:"user",content:"Now say done."}])}' gpt-state-1.json)"
  3. sed -n 1p gpt-state-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    

gpt-5.6 replay, stored

  1. post gpt-stored-2.json "$(jq -c '{model:"gpt-5.6",reasoning:{effort:"low"},input:([{role:"user",content:"Name the fruit."}] + [.output[] | del(.status)] + [{role:"user",content:"Now say done."}])}' gpt-nonstream.json)"
  2. sed -n 1p gpt-stored-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    

Claude replay with no word to mask

  1. post claude-clean-1.json '{"model":"claude-sonnet-5-5","input":"Think about what 12 times 12 is, then reply with only the number.","max_output_tokens":6000,"reasoning":{"effort":"high","summary":"detailed"}}'
  2. post claude-clean-2.json "$(jq -c '{model:"claude-sonnet-5-5",max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"},input:([{role:"user",content:"What is 12 times 12?"}] + [.output[] | del(.status)] + [{role:"user",content:"Now say done."}])}' claude-clean-1.json)"
  3. sed -n 1p claude-clean-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    

BLOCK word only in the reasoning, non-stream

  1. post block-nonstream.json "$(jq -nc --arg q "$BLOCK_PROMPT" '{model:"gpt-5.6",input:$q,max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"}}')"
  2. sed -n 1p block-nonstream.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  3. jq -c '.error.message // ([.output[]|select(.type=="reasoning")|.summary[]?.text]|join(" ")|.[0:140])' block-nonstream.json
    "**Counting objects**\n\nI need to focus on the answer, which is just a count. In this case, I’m considering “umbrella,” and the count is 8. It"
    

BLOCK word only in the reasoning, stream

  1. post block-stream.sse "$(jq -nc --arg q "$BLOCK_PROMPT" '{model:"gpt-5.6",input:$q,max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"},stream:true}')"
  2. sed -n 1p block-stream.sse.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  3. events block-stream.sse | jq -r 'select(tostring|ascii_downcase|contains("umbrella")) | .type' | sort | uniq -c
          1 response.completed
          1 response.output_item.done
          1 response.reasoning_summary_part.done
          1 response.reasoning_summary_text.done
    
  4. events block-stream.sse | jq -r '.type' | sort | uniq -c | grep -E 'failed|completed'
          1 response.completed
    

GET /v1/responses/{id}

  1. curl -sS -o retrieve.json $URL/v1/responses/$(jq -r .id gpt-nonstream.json) -H "Authorization: Bearer $LITELLM_MASTER_KEY"
  2. jq -c '[.output[] | if .type=="reasoning" then {type, summary: ([.summary[].text]|join(" ")|.[0:140])} else {type, text: .content[0].text} end]' retrieve.json
    [{"type":"reasoning","summary":"**Following output instructions**\n\nI need to make sure I provide the output exactly as instructed. The fruit is \"persimmon,\" and it should b"},{"type":"message","text":"[KEYWORD_REDACTED]"}]
    

/v1/chat/completions Claude, not changed by this PR

  1. curl -sS -o chat-claude.json $URL/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-5-5","max_tokens":6000,"reasoning_effort":"high","messages":[{"role":"user","content":"Think step by step: name the fruit with orange skin in the Diospyros genus in your reasoning, spell it, then reply with exactly that fruit name in lowercase."}]}'
  2. jq -c '.choices[0].message | {content, reasoning_content: (.reasoning_content//""|.[0:90])}' chat-claude.json
    {"content":"[KEYWORD_REDACTED]","reasoning_content":"I'm settling on persimmon as the fruit and spelling it out in my reasoning. The user wants"}
    

/v1/messages Claude, not changed by this PR

  1. curl -sS -o messages-claude.json $URL/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"claude-sonnet-5-5","max_tokens":6000,"thinking":{"type":"adaptive","display":"summarized"},"messages":[{"role":"user","content":"Think step by step: name the fruit with orange skin in the Diospyros genus in your reasoning, spell it, then reply with exactly that fruit name in lowercase."}]}'
  2. jq -c '[.content[] | {type, text: ((.text // .thinking // "")|.[0:90])}]' messages-claude.json
    [{"type":"thinking","text":"I'm settling on persimmon as the fruit and noting that it should be spelled out letter by "},{"type":"text","text":"[KEYWORD_REDACTED]"}]
    

After (1739875)

gpt-5.6 stream

  1. post gpt-stream.sse "$(body gpt-5.6 true)"
  2. events gpt-stream.sse | jq -c 'select(.type|test("(reasoning_summary|output)_text.done")) | {type, text: (.text|match(".{0,30}(persimmon|KEYWORD_REDACTED).{0,10}").string)}'
    {"type":"response.reasoning_summary_text.done","text":"eed to output just the word \"[KEYWORD_REDACTED]\" in lowe"}
    {"type":"response.output_text.done","text":"[KEYWORD_REDACTED]"}
    
  3. events gpt-stream.sse | jq -r 'select(tostring|ascii_downcase|contains("persimmon")) | .type' | sort | uniq -c
    (no output)
    
Every other case, after

gpt-5.6 non-stream

  1. post gpt-nonstream.json "$(body gpt-5.6 false)"
  2. jq -c '[.output[] | if .type=="reasoning" then {type, summary: ([.summary[].text]|join(" ")|.[0:140])} else {type, text: .content[0].text} end]' gpt-nonstream.json
    [{"type":"reasoning","summary":"**Calculating fruit details**\n\nI need to ensure I’m following the instructions precisely. The word “[KEYWORD_REDACTED]” has 9 letters, which"},{"type":"message","text":"[KEYWORD_REDACTED]"}]
    

OpenAI Python SDK 2.54.0 stream

  1. python sdk_stream.py $URL $LITELLM_MASTER_KEY
    streamed deltas have the word: False
    final summary has the word: False
    final summary is masked: True
    answer: [KEYWORD_REDACTED]
    

Claude non-stream

  1. post claude-nonstream.json "$(body claude-sonnet-5-5 false)"
  2. jq -c '{content: ([.output[]|select(.type=="reasoning")|.content[]?.text]|join(" ")|.[0:90]), blob: ([.output[]|select(.type=="reasoning")|.encrypted_content]|join(" ")|.[0:90]), provider: (.provider_specific_fields.thinking_blocks[0].thinking//""|.[0:90]), answer: ([.output[]|select(.type=="message")|.content[0].text]|join(" ")), has_signature: ([.output[]|select(.type=="reasoning")|.encrypted_content]|join(" ")|contains("signature"))}' claude-nonstream.json
    {"content":"I've got the fruit as [KEYWORD_REDACTED], and its nine letters give 81 + 17 = 98, which is","blob":"[{\"type\":\"thinking\",\"thinking\":\"I've got the fruit as [KEYWORD_REDACTED], and its nine let","provider":"I've got the fruit as [KEYWORD_REDACTED], and its nine letters give 81 + 17 = 98, which is","answer":"[KEYWORD_REDACTED]","has_signature":true}
    

Claude stream

  1. post claude-stream.sse "$(body claude-sonnet-5-5 true)"
  2. events claude-stream.sse | jq -c 'select(.type|test("(reasoning_summary|output)_text.done")) | {type, text: (.text|match(".{0,30}(persimmon|keyword_redacted).{0,10}"; "i").string)}'
    {"type":"response.reasoning_summary_text.done","text":"The fruit is [KEYWORD_REDACTED], which h"}
    {"type":"response.output_text.done","text":"[KEYWORD_REDACTED]"}
    
  3. events claude-stream.sse | jq -r 'select(tostring|ascii_downcase|contains("persimmon")) | .type' | sort | uniq -c
    (no output)
    

gpt-5-mini stream cut short by max_output_tokens

  1. post gpt-truncated.sse "$(jq -nc --arg q "$TRUNC_PROMPT" '{model:"gpt-5-mini",stream:true,input:$q,tools:[{type:"web_search"}],max_output_tokens:1500,reasoning:{effort:"medium",summary:"detailed"}}')"
  2. events gpt-truncated.sse | jq -r 'select(.type|test("^response\\.(completed|incomplete|failed)$")) | .type'
    response.incomplete
    
  3. events gpt-truncated.sse | jq -s -c '(.[-1].response.output) as $o | [.[] | select(.type=="response.reasoning_summary_text.delta")] | group_by([.output_index, .summary_index])[] | (map(.delta)|join("")) as $t | {output_index: .[0].output_index, summary_index: .[0].summary_index, in_final_event: (($o[.[0].output_index].summary[.[0].summary_index].text // "") | startswith($t)), word: ($t|ascii_downcase|contains("persimmon")), masked: ($t|contains("KEYWORD_REDACTED"))} | select(.word or .masked)'
    {"output_index":0,"summary_index":0,"in_final_event":true,"word":false,"masked":true}
    {"output_index":2,"summary_index":0,"in_final_event":true,"word":false,"masked":true}
    {"output_index":6,"summary_index":0,"in_final_event":true,"word":false,"masked":true}
    {"output_index":8,"summary_index":0,"in_final_event":false,"word":false,"masked":true}
    

Direct default_on guardrail, no policy, gpt-5.6 non-stream

  1. post direct-gpt-nonstream.json "$(body gpt-5.6 false)"   # URL of the direct.yaml proxy
  2. jq -c '[.output[] | if .type=="reasoning" then {type, summary: ([.summary[].text]|join(" ")|.[0:140])} else {type, text: .content[0].text} end]' direct-gpt-nonstream.json
    [{"type":"reasoning","summary":"**Clarifying output requirements**\n\nIt looks like I need to focus on giving the output in all lowercase and only showing \"fruit.\" So, [KEYWO"},{"type":"message","text":"[KEYWORD_REDACTED]"}]
    

Plain answer with no reasoning

  1. post plain-answer.json '{"model":"gpt-5.6","input":"Reply with exactly this word and nothing else: persimmon"}'
  2. jq -c '[.output[]|select(.type=="message")|.content[0].text]' plain-answer.json
    ["[KEYWORD_REDACTED]"]
    

Claude tool replay

  1. post claude-tool-1.json "$(jq -nc --arg q "$TOOL_PROMPT" --argjson t "$TOOLS" '{model:"claude-sonnet-5-5",input:$q,tools:$t,tool_choice:"auto",max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"}}')"
  2. post claude-tool-2.json "$(jq -c --arg q "$TOOL_PROMPT" --argjson t "$TOOLS" '{model:"claude-sonnet-5-5",tools:$t,max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"},input:([{role:"user",content:$q}] + [.output[] | del(.status)] + [{type:"function_call_output",call_id:(.output[] | select(.type=="function_call") | .call_id),output:"found: orange fruit"}])}' claude-tool-1.json)"
  3. sed -n 1p claude-tool-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  4. jq -c '[.output[]|select(.type=="reasoning")|tostring|ascii_downcase|{word: contains("persimmon"), masked: contains("keyword_redacted")}]' claude-tool-1.json
    [{"word":false,"masked":true}]
    

Claude replay with no tool

At this tip one of four runs of this replay got HTTP 200 with Anthropic's terms-of-service refusal as the message. The other three completed. Each replayed thinking that carried the mask

  1. post claude-replay-2.json "$(jq -c '{model:"claude-sonnet-5-5",max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"},input:([{role:"user",content:"Name the fruit from before."}] + [.output[] | del(.status)] + [{role:"user",content:"Now say done."}])}' claude-nonstream.json)"
  2. sed -n 1p claude-replay-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    

Vertex Claude tool replay

  1. Same two requests as the Claude tool replay with claude-sonnet-vertex, saved as vertex-tool-1.json and vertex-tool-2.json
  2. sed -n 1p vertex-tool-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  3. jq -c '[.output[]|select(.type=="reasoning")|tostring|ascii_downcase|{word: contains("persimmon"), masked: contains("keyword_redacted")}]' vertex-tool-1.json
    [{"word":false,"masked":true}]
    

Azure AI Foundry Claude tool replay

  1. Same two requests as the Claude tool replay with claude-opus-foundry, saved as foundry-tool-1.json and foundry-tool-2.json
  2. sed -n 1p foundry-tool-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  3. jq -c '[.output[]|select(.type=="reasoning")|tostring|ascii_downcase|{word: contains("persimmon"), masked: contains("keyword_redacted")}]' foundry-tool-1.json
    [{"word":false,"masked":true}]
    

Databricks Claude tool replay

  1. Same two requests as the Claude tool replay with claude-databricks, saved as databricks-tool-1.json and databricks-tool-2.json
  2. sed -n 1p databricks-tool-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  3. jq -c '[.output[]|select(.type=="reasoning")|tostring|ascii_downcase|{word: contains("persimmon"), masked: contains("keyword_redacted")}]' databricks-tool-1.json
    [{"word":false,"masked":true}]
    

gpt-5.6 replay, stateless

  1. post gpt-state-1.json "$(body gpt-5.6 false | jq -c '. + {store:false,include:["reasoning.encrypted_content"]}')"
  2. post gpt-state-2.json "$(jq -c '{model:"gpt-5.6",store:false,include:["reasoning.encrypted_content"],reasoning:{effort:"low"},input:([{role:"user",content:"Name the fruit."}] + [.output[] | del(.status)] + [{role:"user",content:"Now say done."}])}' gpt-state-1.json)"
  3. sed -n 1p gpt-state-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    

gpt-5.6 replay, stored

  1. post gpt-stored-2.json "$(jq -c '{model:"gpt-5.6",reasoning:{effort:"low"},input:([{role:"user",content:"Name the fruit."}] + [.output[] | del(.status)] + [{role:"user",content:"Now say done."}])}' gpt-nonstream.json)"
  2. sed -n 1p gpt-stored-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    

Claude replay with no word to mask

  1. post claude-clean-1.json '{"model":"claude-sonnet-5-5","input":"Think about what 12 times 12 is, then reply with only the number.","max_output_tokens":6000,"reasoning":{"effort":"high","summary":"detailed"}}'
  2. post claude-clean-2.json "$(jq -c '{model:"claude-sonnet-5-5",max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"},input:([{role:"user",content:"What is 12 times 12?"}] + [.output[] | del(.status)] + [{role:"user",content:"Now say done."}])}' claude-clean-1.json)"
  3. sed -n 1p claude-clean-2.json.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    

BLOCK word only in the reasoning, non-stream

  1. post block-nonstream.json "$(jq -nc --arg q "$BLOCK_PROMPT" '{model:"gpt-5.6",input:$q,max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"}}')"
  2. sed -n 1p block-nonstream.json.hdr | tr -d '\r'
    HTTP/1.1 400 Bad Request
    
  3. jq -c '.error.message // ([.output[]|select(.type=="reasoning")|.summary[]?.text]|join(" ")|.[0:140])' block-nonstream.json
    "Content blocked: keyword 'umbrella' detected"
    

BLOCK word only in the reasoning, stream

  1. post block-stream.sse "$(jq -nc --arg q "$BLOCK_PROMPT" '{model:"gpt-5.6",input:$q,max_output_tokens:6000,reasoning:{effort:"high",summary:"detailed"},stream:true}')"
  2. sed -n 1p block-stream.sse.hdr | tr -d '\r'
    HTTP/1.1 200 OK
    
  3. events block-stream.sse | jq -r 'select(tostring|ascii_downcase|contains("umbrella")) | .type' | sort | uniq -c
          1 response.failed
    
  4. events block-stream.sse | jq -r '.type' | sort | uniq -c | grep -E 'failed|completed'
          1 response.failed
    

GET /v1/responses/{id}

  1. curl -sS -o retrieve.json $URL/v1/responses/$(jq -r .id gpt-nonstream.json) -H "Authorization: Bearer $LITELLM_MASTER_KEY"
  2. jq -c '[.output[] | if .type=="reasoning" then {type, summary: ([.summary[].text]|join(" ")|.[0:140])} else {type, text: .content[0].text} end]' retrieve.json
    [{"type":"reasoning","summary":"**Calculating fruit details**\n\nI need to ensure I’m following the instructions precisely. The word “[KEYWORD_REDACTED]” has 9 letters, which"},{"type":"message","text":"[KEYWORD_REDACTED]"}]
    

/v1/chat/completions Claude, not changed by this PR

  1. curl -sS -o chat-claude.json $URL/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-5-5","max_tokens":6000,"reasoning_effort":"high","messages":[{"role":"user","content":"Think step by step: name the fruit with orange skin in the Diospyros genus in your reasoning, spell it, then reply with exactly that fruit name in lowercase."}]}'
  2. jq -c '.choices[0].message | {content, reasoning_content: (.reasoning_content//""|.[0:90])}' chat-claude.json
    {"content":"[KEYWORD_REDACTED]","reasoning_content":"I'm settling on persimmon as the fruit, and I'll spell it out in my reasoning. The user wa"}
    

/v1/messages Claude, not changed by this PR

  1. curl -sS -o messages-claude.json $URL/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"claude-sonnet-5-5","max_tokens":6000,"thinking":{"type":"adaptive","display":"summarized"},"messages":[{"role":"user","content":"Think step by step: name the fruit with orange skin in the Diospyros genus in your reasoning, spell it, then reply with exactly that fruit name in lowercase."}]}'
  2. jq -c '[.content[] | {type, text: ((.text // .thinking // "")|.[0:90])}]' messages-claude.json
    [{"type":"thinking","text":"I'm settling on persimmon as the fruit and spelling it out letter by letter. The reply sho"},{"type":"text","text":"Reasoning: the fruit is the [KEYWORD_REDACTED], spelled p-e-r-s-i-m-m-o-n.\n\n[KEYWORD_REDAC"}]
    
sdk_stream.py
import sys

from openai import OpenAI

client = OpenAI(base_url=f"{sys.argv[1]}/v1", api_key=sys.argv[2])
prompt = "Think step by step in your reasoning: name the fruit with orange skin, very astringent when unripe, Diospyros genus, and spell it letter by letter while you reason, then compute its letter count squared plus 17 and test primality. Your entire reply must be exactly the fruit name in lowercase, nothing else."
with client.responses.stream(
    model="gpt-5.6", input=prompt, max_output_tokens=6000, reasoning={"effort": "high", "summary": "detailed"}
) as stream:
    streamed_reasoning = "".join(
        event.delta for event in stream if event.type == "response.reasoning_summary_text.delta"
    )
    final = stream.get_final_response()
summary = " ".join(part.text for item in final.output if item.type == "reasoning" for part in item.summary)
print("streamed deltas have the word:", "persimmon" in streamed_reasoning.lower())
print("final summary has the word:", "persimmon" in summary.lower())
print("final summary is masked:", "keyword_redacted" in summary.lower())
print("answer:", final.output_text)

Seen during QA, the first three left alone by this PR:

  • Letter-spaced spellings pass a keyword filter
  • The block message names the keyword
  • Web search queries keep the raw word
  • One masked Claude replay got Anthropic's ToS refusal, retries passed

Type

🐛 Bug Fix

Caveats (if any)

High

  • Every reply with reasoning makes a second guardrail call after the answer call (Decisions 7 and 8)
    • Guardrails that opt out get 1 + N calls for N reasoning texts
    • The reasoning call waits for the answer's mask, so guardrail latency doubles. Running both at once would make Akto block masked replies
    • Straiker v3 and Onyx scan the whole response twice, and guardrail logs get two entries

Medium

  • BLOCK now fails a reply when only its reasoning matches, for every guardrail, with no off switch (Decision 17)
    • A non-stream reply goes from 200 to 400, and a stream ends in response.failed with HTTP 200
  • Masked Claude thinking replays only because Anthropic does not enforce its documented 400 for edited thinking today (Decision 1)
  • Guardrails that read only one end of texts mask only that end of the reasoning
    • The only opt-out is the Python method scans_each_text_separately, so a Generic Guardrail API server has none
  • Only the content filter, llm_as_a_judge, and test guardrails ran live. Other vendors were unit tested or traced only

Low

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
Decisions
  1. Claude thinking text is masked in place inside the minted blob, with signature, block order, and redacted_thinking kept, and the bytes stay the same when nothing matched. I rejected dropping the block (it loses the reasoning on the next turn) and leaving it raw (it leaks). A live probe showed Anthropic checks signature and not the thinking text, with edited text at 200 and a tampered signature at 400 on claude-opus-5-5, claude-sonnet-5-5, claude-sonnet-4-6, claude-sonnet-4-5, and claude-haiku-4-5. Opaque OpenAI blobs are left alone. An unverifiable block inside a verifiable blob is masked too
  2. OpenAI answers 200 when an edited summary is replayed, stored and stateless, so the summary can be masked with no replay cost
  3. Message positions are a NamedTuple and not a bare tuple, so they sit in one union with the new reasoning positions and still equal the old tuple keys
  4. Stream rewrites key on output_index, the same key the response positions use, rather than item_id
  5. .added events are written only when their text is non-empty, and response.reasoning_text.* events are handled even though the event enum lacks them
  6. A stream that ends with no terminal event gets a synthetic envelope that goes back through the same path, instead of a second rewrite path. The client never receives that envelope
  7. Reasoning joins the answer call only for a guardrail that takes every text at once (Decisions 9 and 16). A first version added it to the answer's text list for every guardrail, and a live run showed a guardrail that reads only the last text overwriting the answer with masked reasoning, since hiddenlayer, grayswan, ovalix, and customer guardrails can read one end of texts. Claude reasoning content was in the answer call at the merge base, so a guardrail that reads the first text now reads the answer there
  8. All distinct reasoning texts go to the guardrail in one call, which starts once the answer's mask is written to the response, since apply_guardrail takes a list and applies to every text in it. A guardrail that opts out through scans_each_text_separately gets one call per text instead, and so does a batch that comes back with a different number of texts, so a guardrail that returns one text never fails the reply or leaves a text raw. Qualifire, HiddenLayer, Gray Swan, and Bedrock with experimental_use_latest_role_message_only read one end, Ovalix raises only for the last text, and custom code and CollieAI run code this repo cannot see, so all of them opt out. I rejected one call per text for every guardrail, which cost 1 + N vendor calls for N texts, and an opt-in on each of the 30 or so built-ins that read every text. I also rejected running the answer and reasoning calls at the same time. It saves one guardrail round trip, but Akto reads the whole response in the reasoning call and blocks when an answer it masked is still raw there. A customer guardrail that reads one end gets one call too and masks only that end of the reasoning until it opts out
  9. A legacy post-call hook in a pipeline step stays at one call, with reasoning in its text list, through scans_all_response_texts_in_one_call. Separate calls would run the hook once per text and put reasoning into the answer. It skips the extra pass for reasoning that a cut-short final event left out, so that reasoning stays raw as at the merge base
  10. Text with no place to go back to (a refusal, code interpreter output, missing indexes) goes to the old fallback, which fails open. So does an envelope missing the streamed answer, and a stream that ends with no final event after streaming such text, since a rebuilt final event would drop that text
  11. Cached replay is fixed in the handler, and streaming_iterator.py is not touched
  12. _open_item_state and _open_item_closing_events are not touched, because .added has no reasoning text on real streams
  13. Model Armor is not changed, and Qualifire changes only to opt out under Decision 8. Model Armor still scans Claude reasoning content and does not scan OpenAI summaries
  14. A guardrail that scans the whole response and not its texts (Straiker v3, Onyx) scans it once more in the reasoning call. I left those vendors alone. XecGuard reads choices, which a Responses API reply does not have, so it scans nothing on /v1/responses at the merge base or here
  15. A stream cut short by max_output_tokens can end with a final event that lacks reasoning it already streamed. That reasoning gets its own call and its mask goes to the stream events, while the final event keeps what the provider sent. The merge base caught this case only through the old fallback, which blocked but never masked
  16. llm_as_a_judge takes the answer and the reasoning in one call through scans_all_response_texts_in_one_call, so it makes one model call and judges both. At the merge base it judged Claude reasoning, which was in the answer call, and not OpenAI summaries. I rejected skipping reasoning, which stopped judging Claude reasoning, and a second judge call, which doubles its model cost
  17. BLOCK applies to reasoning like MASK does, for every guardrail. I rejected blocking on the answer only, which lets the word through in the reasoning, and an opt-in flag per keyword or guardrail, which adds config each guardrail's own action already covers
/live-pr-risk at 53c350d

Base 436f6d5. Both sides ran 2 uvicorn workers with Postgres, and recorders in front of OpenAI and Anthropic. The rig's guardrails read one end of texts or record what they get, like a custom guardrail would

Breaking: none. A guardrail that reads and sends back only the last text now masks every reasoning text, and llm_as_a_judge now judges gpt-5.6 reasoning too

Case Base Head
Last-text guardrail, Claude Answer raw, reasoning replaced Both masked
Same in a policy, Claude stream Raw in 4 event types No raw word
Same in a policy, gpt-5.6 stream Raw in 5 event types No raw word
Legacy hook in a policy, stream 1 call, reasoning raw 1 call, all masked
llm_as_a_judge, gpt-5.6 1 call, answer only 1 call, both
llm_as_a_judge, Claude 1 call, both 1 call, both
Tool call, first-text guardrail Tools scanned Tools scanned
Direct guardrail stream Rewrite not sent Rewrite not sent

Backward incompatible: BLOCK on reasoning alone (Decision 17), one more guardrail call for the reasoning (Decision 8), Claude reasoning out of the answer call except for a guardrail that takes every text at once (Decisions 7 and 16), and masked text in non-stream logs. A custom guardrail that reads one end of texts and sends every text back masks only that end of the reasoning until it opts out (Decision 8). scans_each_text_separately and scans_all_response_texts_in_one_call are new and additive, and the policy stream wrapper forwards both

Regression risk: Akto maps masks by exact text over the whole response, which one call with all reasoning keeps working. Straiker v3 and Onyx scan the whole response once more in the reasoning call. Both are traced only

Not verified: Bedrock guardrails and Bedrock Claude replay (no AWS access), Qualifire, HiddenLayer, Ovalix, Gray Swan, CollieAI, Akto, Straiker, and a stream that ends with no final event after a refusal. Each opt-out except CollieAI's, whose package is not installed here, has a unit test that fails without it

Bugbot summary

[!NOTE]
High Risk
Changes the core post-call guardrail pipeline for Responses (streaming rewrite, extra vendor calls, and stricter BLOCK semantics), which can affect latency, billing, and whether reasoning-only policy hits block previously successful responses.

Overview
Post-call guardrails on /v1/responses now scan and rewrite reasoning output, not just the final answer—covering summary parts, reasoning text stream events, Claude signed thinking blobs, and provider_specific_fields, with the same masks applied back to completed responses and to streamed deltas/done events (including cut-short streams built from released partial envelopes).

Scan orchestration is explicit via new CustomGuardrail hooks: scans_all_response_texts_in_one_call (e.g. LLM-as-judge keeps one combined call with the answer) vs a second reasoning pass that batches distinct texts or calls per text when scans_each_text_separately is false (Bedrock latest-message-only, HiddenLayer, Gray Swan, etc.). Blocking guardrails now fail when a match is only in reasoning (non-stream 400 / stream response.failed), not only when the answer matches.

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

Post-call masking guardrails only saw the answer on /v1/responses, so a
reasoning summary, the Claude bridge's reasoning content, and the thinking
text inside its encrypted_content and provider_specific_fields reached the
client raw. Scan those texts with the answer, answers first, and write the
mask back to the response and every stream event. Thinking signatures stay
untouched so the blob still replays.
A guardrail that reads one end of its text list overwrote the answer with masked reasoning when both shared one call. Each distinct reasoning text now gets its own apply_guardrail call after the answer rewrite, and whole-response scanners keep one call.
# Conflicts:
#	litellm/llms/openai/responses/guardrail_translation/handler.py
#	tests/unit/llms/openai/responses/test_openai_responses_guardrail_handler.py
@veria-ai

veria-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

The PR updates guardrail handling for /v1/responses output to mask reasoning text, including buffered streams and synthetic response envelopes.

One issue has been addressed, but two open gaps still allow released stream content to escape guardrail checks. A partial terminal envelope can leave buffered reasoning unchecked, while a synthetic envelope for a cut-short stream can omit refusal text from final moderation and audit checks. These gaps can allow blocked content to pass through under those stream conditions.

Open issues (2)

Fixed/addressed: 1 · PR risk: 6/10

Reviews

self._sync_stream_events_with_output_rewrites(responses_so_far, response_obj, reasoning_rewrites)

envelope_has_scannable_content: Final = bool(texts_to_check or tool_calls_to_check or reasoning_texts)
if envelope_has_scannable_content and not answer_outside_envelope:

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.

Medium: Buffered reasoning can bypass scanning with a partial envelope

A nonempty reasoning_texts does not prove the envelope covers the buffered stream: with reasoning deltas at output indices 0 (clean) and 1 (SECRET), followed by response.incomplete containing only index 0, a guardrail that blocks SECRET now scans only clean and returns the unchecked index-1 delta; the base implementation blocked this sequence through the string fallback. Compare buffered reasoning positions against the terminal envelope and scan or reconstruct missing parts before returning.

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 cafc01f. Streamed reasoning that a cut-short final event lacks now gets its own guardrail call, and the mask reaches the stream

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.

Still fixed at 53c350d. test_reasoning_a_partial_envelope_lacks_is_scanned_and_masked streams reasoning an incomplete envelope lacks and asserts it is scanned and masked

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.

Ran your exact sequence at 1739875 with a guardrail that blocks SECRET. It scans clean and SECRET, then raises, so the stream is blocked

@codspeed

codspeed Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 45 untouched benchmarks


Comparing quietjules:litellm_mask_responses_reasoning_summary (6901edd) with main (90991cb)

Open in CodSpeed

@codecov

codecov Bot commented Nov 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…nd send reasoning in one call

A stream cut short by max_output_tokens can end with a terminal envelope that
lacks reasoning it already streamed, so that reasoning skipped BLOCK and MASK.
It now gets its own guardrail call and the mask reaches its stream events.

Every distinct reasoning text now goes to the guardrail in one call instead of
one call per text. A guardrail that returns a different number of texts falls
back to one call per text so each text keeps its own rewrite.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The changes since the previous review appear safe to merge.

Summary

The PR extends Responses API guardrails to reasoning text and writes masks back into replies and stream events. The latest fixes preserve reasoning parts found only in a finished item and scan provider thinking even when output is empty.

  • Responses replies now mask matching words in reasoning too.
  • Guardrails choose whether to scan response texts together or separately.

Reviews (6) · Last reviewed commit: "fix(guardrails): mask reasoning parts on..." · Reviewed by Greptile

incomplete: Final = ResponsesAPIStreamEvents.RESPONSE_INCOMPLETE.value
envelope: Final = {"type": incomplete, "response": response}
return (*responses_so_far, envelope)
return (*responses_so_far, _released_envelope(responses_so_far))

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.

Medium: Synthetic envelopes skip released text

A cut-short buffer with clean reasoning and output-text deltas plus a response.refusal.delta containing a blocked value now receives a synthetic envelope that omits the refusal; _scan_released_stream_after_disconnect() and _scan_pipeline_stream_cut_short() then scan only the clean envelope, so that value never reaches the final moderation/audit check. Check _has_unplaceable_stream_text() here as well and retain a fallback scan for emitted text the envelope cannot represent.

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 2be3f95. A cut-short stream with a refusal or code interpreter text now skips the synthetic envelope and goes to the full fallback scan

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.

Still fixed at 53c350d. test_a_refusal_released_next_to_reasoning_reaches_the_guardrail_after_the_stream_is_cut_short cuts a stream after a blocked refusal delta and asserts the guardrail scans it

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.

Ran your sequence at 1739875 with a guardrail that blocks SECRET. No synthetic envelope is added, the fallback scans the refusal, and it blocks

…rail batches, keep the judge on the answer

A guardrail that reads one end of its text list now checks every reasoning text, the content filter keeps one call for all of them, llm_as_a_judge judges the answer alone, and a legacy hook keeps its answer mask when reasoning streams past a cut-short final event
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment on lines +2136 to +2139
case "response.content_part.added" if content_position in rewrites.contents and stream_item_field(
part, part_field
):
write_field(part, part_field, rewrites.contents[content_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.

P2 Latest streaming fix lacks QA. Live QA must cover the latest product commit. Rerun 36750f3dd9 with nonempty response.content_part.added reasoning.

Rule Used: Apply this rule only to PRs that fix LLM translation bugs or add LLM translation features. LLM translation means converting requests, responses, streaming events, tool calls, and errors between the API a caller uses on LiteLLM (any endpoint or SDK fu... (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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.

Neither Claude nor gpt-5.6 streams a non-empty reasoning content_part.added, and litellm opens parts empty, so no live leg reaches it. A unit test covers it

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.

That’s a fair point. I shouldn’t require a live leg for an event the tested providers don’t emit; the unit test is the appropriate coverage for that branch.

The remaining gap is QA freshness, not that specific event: the PR says live QA ran on 2be3f95882, while 36750f3dd9 is the latest product commit. Please rerun the existing reachable live QA cases on 36750f3dd9 and update the proof. No need to manufacture a non-empty response.content_part.added event.

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.

Re-ran the reachable live QA at 53c350d, now the latest product commit, and the After proof in the description shows that run

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.

Re-ran the live QA at 1739875, the latest product commit, and the After proof in the description now shows that run

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…t the judge read reasoning

Reasoning texts go to a guardrail in one call after the answer by default. Guardrails that read one end of texts (Qualifire, HiddenLayer, Gray Swan, Ovalix, custom code, CollieAI, Bedrock latest-message-only) opt out through scans_each_text_separately and get one call per text. A batch answered with a different number of texts is re-sent one text per call.

llm_as_a_judge takes the answer and the reasoning in one call through scans_all_response_texts_in_one_call, and scans_reasoning is removed
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

1 similar comment
@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 1739875. 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 9eb867b into BerriAI:main Nov 19, 2026
54 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