Skip to content

fix(guardrails): accept Gemini tools in generic_guardrail_api, add opt-in forward_messages_as_sent, name the error type on fail-open - #46338

Merged
ryan-crabbe-berri merged 17 commits into
mainfrom
litellm_generic_guardrail_shapes
Oct 16, 2026
Merged

ryan-crabbe-berri merged 17 commits into
mainfrom
litellm_generic_guardrail_shapes

Conversation

@ryan-crabbe-berri

@ryan-crabbe-berri ryan-crabbe-berri commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Gemini native tools have no type key, so the guardrail tool model rejects them
  • Guardrails only see cleaned chat rows, with native blocks emptied and keys dropped
  • An echo of those cleaned rows gets written back over the request
  • The fail-open log line never said what failed, so a timeout looked like a refused connection

How it solves it:

  • GuardrailToolParam.type is optional and left off the wire when absent
  • New per-guardrail setting forward_messages_as_sent, off by default
  • Off, structured_messages and write-back stay byte for byte what main does
  • On, rows reach the guardrail as the client sent them
  • On, an echo that only drops keys the chat types lack still counts as an echo
  • The fail-open line now ends with error_type=, e.g. HTTPStatusError

The Gemini tools fix and error_type= apply to every guardrail, flag or not. The retry on a dropped or hung guardrail call moved to a follow-up PR that adds a per-guardrail num_retries setting

Found by a customer evaluating 1.105.0rc1. Each claim was re-verified against current main before the change

Docs PR: BerriAI/litellm-docs#2417

User Flow

Before: a developer whose key runs a generic_guardrail_api guardrail on pre_call cannot call Gemini with native tools, and the guardrail never sees what the other providers were sent

  1. They send POST https://litellm-domain/v1/chat/completions with "model": "gemini-3.8-flash" and "tools": [{"function_declarations": [...]}]
  2. They get a 500 reading Generic Guardrail API failed: 1 validation error for GuardrailToolParam type Field required
  3. A claude-sonnet-5-5 request with a native image block or a name on a row reaches the guardrail as {"role": "user", "content": []} with name gone
  4. A POST https://litellm-domain/v1/messages with a document block, through a guardrail that echoes rows back, reaches Claude without the document
  5. A guardrail with fail_on_error: false fails open and logs the same line for a timeout and a refused connection

After: Gemini tools pass and the fail-open line says what failed, and an admin who opts in gets every row as sent

  1. They send the same POST https://litellm-domain/v1/chat/completions with "model": "gemini-3.8-flash" and "tools": [{"function_declarations": [...]}]
  2. They get a 200, and the guardrail's request log shows the tools exactly as sent, with no type key added
  3. The proxy admin adds forward_messages_as_sent: true under the guardrail's litellm_params (or flips the new toggle on the Add Guardrail form), and the Claude request now reaches the guardrail with the image block and name intact
  4. With that set, the echoed /v1/messages request reaches Claude unchanged, document block included
  5. The fail-open line ends with error_type=ConnectError, Timeout or HTTPStatusError

Without the setting, steps 3 and 4 behave exactly as Before

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

Three proxies ran one after the other with no DB, each started with litellm --config <config> --port <port> --detailed_debug. Before is the merge base on port 48310, After (flag off) is the PR tip on port 48311 with the same config, and After (flag on) is the PR tip on port 48318 with forward_messages_as_sent: true added to stub-guard and guard-echo. Every call hits the real provider (Gemini, Anthropic, OpenAI). The guardrails point at a small local stub guardrail server that writes each request body it receives as one JSON line to a log file and answers {"action": "NONE"}. The stub on 48317 also echoes tools and structured_messages back, the one on 48314 sleeps 10s, the one on 48315 answers 503, and nothing listens on 48313

Models are the newest in model_prices_and_context_window.json for each family

model_list:
  - model_name: gpt-5.6
    litellm_params: {model: openai/gpt-5.6, api_key: os.environ/OPENAI_API_KEY}
  - model_name: gemini-3.8-flash
    litellm_params: {model: gemini/gemini-3.8-flash, api_key: os.environ/GEMINI_API_KEY}
  - model_name: claude-sonnet-5-5
    litellm_params: {model: anthropic/claude-sonnet-5-5, api_key: os.environ/ANTHROPIC_API_KEY}

guardrails:
  - guardrail_name: stub-guard          # runs on every request
    litellm_params: {guardrail: generic_guardrail_api, mode: pre_call, default_on: true, api_base: "http://127.0.0.1:48312"}
  - guardrail_name: guard-echo
    litellm_params: {guardrail: generic_guardrail_api, mode: pre_call, default_on: false, api_base: "http://127.0.0.1:48317"}
  - guardrail_name: guard-closed-port
    litellm_params: {guardrail: generic_guardrail_api, mode: pre_call, default_on: false, fail_on_error: false, api_base: "http://127.0.0.1:48313"}
  - guardrail_name: guard-slow
    litellm_params: {guardrail: generic_guardrail_api, mode: pre_call, default_on: false, fail_on_error: false, timeout: 2, api_base: "http://127.0.0.1:48314"}
  - guardrail_name: guard-503
    litellm_params: {guardrail: generic_guardrail_api, mode: pre_call, default_on: false, fail_on_error: false, api_base: "http://127.0.0.1:48315"}

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY

The flag-on config differs in two lines only

-    litellm_params: {guardrail: generic_guardrail_api, mode: pre_call, default_on: true, api_base: "http://127.0.0.1:48312"}
+    litellm_params: {guardrail: generic_guardrail_api, mode: pre_call, forward_messages_as_sent: true, default_on: true, api_base: "http://127.0.0.1:48312"}
-    litellm_params: {guardrail: generic_guardrail_api, mode: pre_call, default_on: false, api_base: "http://127.0.0.1:48317"}
+    litellm_params: {guardrail: generic_guardrail_api, mode: pre_call, forward_messages_as_sent: true, default_on: false, api_base: "http://127.0.0.1:48317"}

Payloads (PNG is a 16x16 red square, iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAFklEQVR4nGO4IydHEmIY1TCqYfhqAACaMxgQdGu1YAAAAABJRU5ErkJggg==)

gemini_tools.json    {"model": "gemini-3.8-flash", "messages": [{"role": "user", "content": "weather in Paris?"}],
                      "tools": [{"function_declarations": [{"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}]}]}
gemini_search.json   {"model": "gemini-3.8-flash", "messages": [{"role": "user", "content": "Who won the most recent Tour de France? One sentence."}],
                      "tools": [{"googleSearch": {}}], "guardrails": ["guard-echo"]}
claude_rows.json     {"model": "claude-sonnet-5-5", "max_tokens": 1024, "guardrails": ["guard-echo"],
                      "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}}],
                      "messages": [{"role": "user", "name": "pat", "content": "What is the weather in Paris? Greet me by name."},
                                   {"role": "assistant", "content": null, "tool_calls": [{"index": 0, "id": "toolu_qa_2", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}]},
                                   {"role": "tool", "tool_call_id": "toolu_qa_2", "content": "sunny, 21C"}]}
claude_image.json    {"model": "claude-sonnet-5-5", "max_tokens": 300,
                      "messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": PNG}}]},
                                   {"role": "user", "content": "What color is that square? One word."}]}
claude_blocks.json   {"model": "claude-sonnet-5-5", "max_tokens": 200, "guardrails": ["guard-echo"],
                      "tools": [{"name": "get_weather", "description": "Weather for a city", "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}],
                      "messages": [{"role": "user", "content": [{"type": "text", "text": "What color is this square? Also check the weather in Paris."},
                                                                {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": PNG}},
                                                                {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "Trip notes: Paris, 3 days."}}]},
                                   {"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_qa_1", "name": "get_weather", "input": {"city": "Paris"}}]},
                                   {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_qa_1", "content": "sunny, 21C"},
                                                                {"type": "text", "text": "Answer both in one sentence."}]}]}

PROXY is http://localhost:48310 for Before, http://localhost:48311 for After with the flag off and http://localhost:48318 for After with the flag on. The stub on port N logs to stub_N.jsonl, and rows_N.txt is jq -c '[.path, .body.structured_messages]' stub_N.jsonl. Long response bodies are trimmed, the PNG base64 is shown as <png>, and the call and trace ids are cut from the fail-open lines

Before (8227f9b)

Gemini native tools

  1. curl -s -w '\nHTTP %{http_code}\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d @gemini_tools.json

    {"error":{"message":"Generic Guardrail API failed: 1 validation error for GuardrailToolParam\ntype\n  Field required [type=missing, input_value={'function_declarations':... {'type': 'string'}}}}]}, input_type=dict]\n    For further information visit https://errors.pydantic.dev/2.13/v/missing","type":"internal_server_error","param":null,"code":"500"}}
    HTTP 500
    
  2. Same call with -d @gemini_search.json

    {"error":{"message":"Generic Guardrail API failed: 1 validation error for GuardrailToolParam\ntype\n  Field required [type=missing, input_value={'googleSearch': {}}, input_type=dict]\n    For further information visit https://errors.pydantic.dev/2.13/v/missing","type":"internal_server_error","param":null,"code":"500"}}
    HTTP 500
    
  3. stub_48312.jsonl and stub_48317.jsonl are both empty, so nothing was scanned and Gemini was never called

Rows forwarded to the guardrail

  1. curl ... $PROXY/v1/chat/completions ... -d @claude_rows.json returns 200 from Claude

    {"id":"chatcmpl-01804dca-bf22-4bf3-80f7-04e88546e2fe",...,"message":{"content":"Paris is sunny and 21°C right now.\n\nI'd like to greet you by name, but I don't know it yet. What should I call you?", ...
    HTTP 200
    
  2. tail -n 1 stub_48312.jsonl | jq -c .body.structured_messages shows name and tool_calls[].index stripped

    [{"role":"user","content":"What is the weather in Paris? Greet me by name."},{"role":"assistant","content":null,"tool_calls":[{"id":"toolu_qa_2","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}]},{"role":"tool","content":"sunny, 21C","tool_call_id":"toolu_qa_2"}]
    
  3. curl ... $PROXY/v1/chat/completions ... -d @claude_image.json is refused by the chat completions message check that runs after the guardrail (same everywhere below, chat completions does not take Anthropic image blocks)

    {"error":{"message":"litellm.APIConnectionError: Invalid user message at index 0. Please ensure all user messages are valid OpenAI chat completion messages.","type":"internal_server_error","param":null,"code":"500"}}
    HTTP 500
    
  4. tail -n 1 stub_48312.jsonl | jq -c .body.structured_messages shows the guardrail was handed an empty row instead of the image block

    [{"role":"user","content":[]},{"role":"user","content":"What color is that square? One word."}]
    

Anthropic /v1/messages with an echoing guardrail

  1. curl -s -w '\nHTTP %{http_code}\n' $PROXY/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d @claude_blocks.json returns 200, but Claude never saw the trip notes (459 input tokens)

    {"model":"claude-sonnet-5-5","id":"msg_011Cg6Y6MwCho2STqSgLrgkh","type":"message","role":"assistant","content":[{"type":"text","text":"The square is red, and Paris is sunny and 21°C."}],...,"usage":{"input_tokens":459,...,"output_tokens":21,...}}
    HTTP 200
    
  2. The request LiteLLM sent to Anthropic (grep -A 4 'POST Request Sent' proxy.log) lost the document block and split the tool_result and the follow-up text into two user turns, because the guardrail's echo of the rows was written back

    -d '{'messages': [{'role': 'user', 'content': [{'type': 'text', 'text': 'What color is this square? Also check the weather in Paris.'}, {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': '<png>'}}]}, {'role': 'assistant', 'content': [{'type': 'tool_use', 'id': 'toolu_qa_1', 'name': 'get_weather', 'input': {'city': 'Paris'}}]}, {'role': 'user', 'content': [{'type': 'tool_result', 'tool_use_id': 'toolu_qa_1', 'content': 'sunny, 21C'}]}, {'role': 'user', 'content': [{'type': 'text', 'text': 'Answer both in one sentence.'}]}], 'max_tokens': 200, 'model': 'claude-sonnet-5-5', 'stream': False, 'tools': [...]}'
    

Fail-open log line

  1. for g in guard-closed-port guard-slow guard-503; do echo "--- $g"; curl -s -o /dev/null -w 'HTTP %{http_code} in %{time_total}s\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "{\"model\": \"gpt-5.6\", \"messages\": [{\"role\": \"user\", \"content\": \"Say ok.\"}], \"guardrails\": [\"$g\"]}"; done

    --- guard-closed-port
    HTTP 200 in 1.172320s
    --- guard-slow
    HTTP 200 in 2.815636s
    --- guard-503
    HTTP 200 in 0.731657s
    
  2. grep -o 'Generic Guardrail API error (fail-open).*' proxy.log gives the same line for all three, with nothing saying what failed

    Generic Guardrail API error (fail-open). Proceeding without guardrail. guardrail_name=guard-closed-port api_base=http://127.0.0.1:48313/beta/litellm_basic_guardrail_api input_type=request
    Generic Guardrail API error (fail-open). Proceeding without guardrail. guardrail_name=guard-slow api_base=http://127.0.0.1:48314/beta/litellm_basic_guardrail_api input_type=request
    Generic Guardrail API error (fail-open). Proceeding without guardrail. http_status_code=503 guardrail_name=guard-503 api_base=http://127.0.0.1:48315/beta/litellm_basic_guardrail_api input_type=request
    

After (7e567b3)

Gemini native tools

  1. Same -d @gemini_tools.json call against the flag-off proxy now returns 200 from Gemini (the flag-on proxy returns the same)

    {"id":"CI3SaqbiGtPUjMcPu8KFiQQ",...,"model":"gemini-3.8-flash",...,"message":{"content":"I don't have access to real-time weather data. ...
    HTTP 200
    
  2. Same call with -d @gemini_search.json returns 200

    {"id":"D43SauqMI5_N-sAP3d_MgAU",...,"message":{"content":"Tadej Pogačar won the most recent Tour de France in 2024, securing his third overall victory in the race.", ...
    HTTP 200
    
  3. tail -n 1 stub_48312.jsonl | jq -c .body.tools and the same on stub_48317.jsonl show the tools exactly as sent, with no type key added

    [{"function_declarations":[{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]}]
    [{"googleSearch":{}}]
    

Rows forwarded to the guardrail

  1. With the flag off, the same -d @claude_rows.json and -d @claude_image.json calls return the same 200 and 500 as Before

    {"id":"chatcmpl-99380140-9ed5-49d1-a59c-e8a6963093bb",...,"message":{"content":"Hello! I don't know your name yet, so I can't greet you by it. If you tell me, I'll use it.\n\nThe weather in Paris right now is sunny and 21°C (about 70°F).", ...
    HTTP 200
    {"error":{"message":"litellm.APIConnectionError: Invalid user message at index 0. Please ensure all user messages are valid OpenAI chat completion messages.","type":"internal_server_error","param":null,"code":"500"}}
    HTTP 500
    
  2. With the flag off, every row both stubs received matches Before byte for byte. After has two extra lines on top for the Gemini calls, which Before rejected before calling the guardrail, so they are skipped

    $ tail -n +3 after/rows_48312.txt | diff before/rows_48312.txt - && echo IDENTICAL
    IDENTICAL
    $ tail -n +2 after/rows_48317.txt | diff before/rows_48317.txt - && echo IDENTICAL
    IDENTICAL
    
  3. With the flag on, -d @claude_rows.json returns 200 and tail -n 1 stub_48312.jsonl | jq -c .body.structured_messages keeps name and tool_calls[].index

    {"id":"chatcmpl-aeb580b1-de4b-4cbe-9771-ff5503841dd3",...,"message":{"content":"Paris is sunny and 21°C right now.\n\nI'd like to greet you by name, but I don't know it because you haven't told me. If you tell me your name, I'll use it.", ...
    HTTP 200
    [{"role":"user","name":"pat","content":"What is the weather in Paris? Greet me by name."},{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"toolu_qa_2","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}]},{"role":"tool","tool_call_id":"toolu_qa_2","content":"sunny, 21C"}]
    
  4. With the flag on, -d @claude_image.json still gets the same 500, and the guardrail now gets the image block itself

    [{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"<png>"}}]},{"role":"user","content":"What color is that square? One word."}]
    
  5. curl -s $PROXY/guardrails/ui/provider_specific_params -H "Authorization: Bearer $LITELLM_MASTER_KEY" | jq -c '.generic_guardrail_api.optional_params.fields | {fail_on_error: (.fail_on_error | {type, default_value}), forward_messages_as_sent: (.forward_messages_as_sent | {type, default_value})}' shows the Add Guardrail form gets the toggle next to fail_on_error, off by default

    {"fail_on_error":{"type":"boolean","default_value":true},"forward_messages_as_sent":{"type":"boolean","default_value":false}}
    

Anthropic /v1/messages with an echoing guardrail

  1. With the flag off, the same -d @claude_blocks.json call returns the same answer as Before from 459 input tokens, and the request sent to Anthropic is identical to Before, document block missing

    {"model":"claude-sonnet-5-5","id":"msg_011Cg6a4H8tnJDNDWZxi16cf","type":"message","role":"assistant","content":[{"type":"text","text":"The square is red, and Paris is sunny and 21°C."}],...,"usage":{"input_tokens":459,...,"output_tokens":21,...}}
    HTTP 200
    -d '{'messages': [{'role': 'user', 'content': [{'type': 'text', 'text': 'What color is this square? Also check the weather in Paris.'}, {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': '<png>'}}]}, {'role': 'assistant', 'content': [{'type': 'tool_use', 'id': 'toolu_qa_1', 'name': 'get_weather', 'input': {'city': 'Paris'}}]}, {'role': 'user', 'content': [{'type': 'tool_result', 'tool_use_id': 'toolu_qa_1', 'content': 'sunny, 21C'}]}, {'role': 'user', 'content': [{'type': 'text', 'text': 'Answer both in one sentence.'}]}], 'max_tokens': 200, 'model': 'claude-sonnet-5-5', 'stream': False, 'tools': [...]}'
    
  2. With the flag on, the same call returns 200 and Claude read the trip notes (514 input tokens)

    {"model":"claude-sonnet-5-5","id":"msg_011Cg6a6o7FY65y6un6bBHNv","type":"message","role":"assistant","content":[{"type":"text","text":"The square is red, and Paris is sunny and 21°C, which should suit your 3-day trip."}],...,"usage":{"input_tokens":514,...,"output_tokens":33,...}}
    HTTP 200
    
  3. With the flag on, the request LiteLLM sent to Anthropic (grep -A 4 'POST Request Sent' proxy.log) matches what the client sent, with the document block kept and the tool_result and text in one user turn

    -d '{'messages': [{'role': 'user', 'content': [{'type': 'text', 'text': 'What color is this square? Also check the weather in Paris.'}, {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': '<png>'}}, {'type': 'document', 'source': {'type': 'text', 'media_type': 'text/plain', 'data': 'Trip notes: Paris, 3 days.'}}]}, {'role': 'assistant', 'content': [{'type': 'tool_use', 'id': 'toolu_qa_1', 'name': 'get_weather', 'input': {'city': 'Paris'}}]}, {'role': 'user', 'content': [{'type': 'tool_result', 'tool_use_id': 'toolu_qa_1', 'content': 'sunny, 21C'}, {'type': 'text', 'text': 'Answer both in one sentence.'}]}], 'max_tokens': 200, 'model': 'claude-sonnet-5-5', 'stream': False, 'tools': [...]}'
    

Fail-open log line

  1. Same for g in guard-closed-port guard-slow guard-503 loop as Before, on the flag-off proxy

    --- guard-closed-port
    HTTP 200 in 0.998857s
    --- guard-slow
    HTTP 200 in 2.656001s
    --- guard-503
    HTTP 200 in 0.724108s
    
  2. grep -o 'Generic Guardrail API error (fail-open).*' proxy.log now ends each line with error_type=, with the 503 reported as httpx's HTTPStatusError rather than LiteLLM's internal masking wrapper. The flag-on proxy logs the same three lines

    Generic Guardrail API error (fail-open). Proceeding without guardrail. guardrail_name=guard-closed-port api_base=http://127.0.0.1:48313/beta/litellm_basic_guardrail_api input_type=request error_type=ConnectError
    Generic Guardrail API error (fail-open). Proceeding without guardrail. guardrail_name=guard-slow api_base=http://127.0.0.1:48314/beta/litellm_basic_guardrail_api input_type=request error_type=Timeout
    Generic Guardrail API error (fail-open). Proceeding without guardrail. http_status_code=503 guardrail_name=guard-503 api_base=http://127.0.0.1:48315/beta/litellm_basic_guardrail_api input_type=request error_type=HTTPStatusError
    

Type

🐛 Bug Fix
🆕 New Feature

Caveats (if any)

Medium

  • With the flag off, an echoing guardrail on /v1/messages still drops a document block
    • Same as main today, the flag is the opt-in fix
  • With the flag on, guardrail servers get unfamiliar keys and provider-native blocks
  • With the flag on, a rewrite that only deletes undeclared keys reads as an echo

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

…generic_guardrail_api, name the error type on fail-open

GuardrailToolParam required a type key, so Gemini native tools
(function_declarations, googleSearch) failed validation inside the hook
and either returned a 500 or skipped the scan when fail_on_error was
false. The type key is now optional and left out of the forwarded tool
when absent, so an echoing guardrail server cannot write type: null into
the provider request.

structured_messages was re-validated against the chat completion message
types, which silently emptied tool_result, tool_use, image and document
content blocks to content: [] and dropped undeclared keys before the
guardrail saw them. The request model now forwards rows as opaque
mappings, which also retires the write-back shim that restored the
original rows for echoed-back entries.

The fail-open critical log line now carries error_type so a timeout, a
refused connection and an upstream HTTP status can be told apart without
the traceback.
aiohttp raises ServerDisconnectedError when a kept-alive connection is
closed by the peer before a response arrives, which is what a load
balancer idle timeout shorter than AIOHTTP_KEEPALIVE_TIMEOUT produces.
The transport mapped it to httpx.ReadError, which the handler's
connection-error retry does not cover, so the request failed instead of
being resent on a fresh connection. It now maps to
httpx.RemoteProtocolError, the error httpx itself raises for the same
condition, so the existing retry fires.
@codspeed

codspeed Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_generic_guardrail_shapes (7e567b3) with main (d6b54ae)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (60af2c6) during the generation of this report, so d6b54ae was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.73684% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...oks/generic_guardrail_api/generic_guardrail_api.py 93.61% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

This remap is global, so every AsyncHTTPHandler POST would replay after any server disconnect, including mid-request ones. Was that intended outside guardrails?

@mateo-berri

Copy link
Copy Markdown
Contributor

#46336 stops POST resends after a disconnect, since they can double-bill. The 20s keepalive change should cover load-balancer cuts, so can you drop this remap?

ryan-crabbe-berri and others added 4 commits October 13, 2026 21:07
…streamed resend readable

The connection-error retry closed its fresh client before a streamed body was read,
so an aiohttp disconnect now billed a second upstream request and still failed. It
also skipped masking on a status error from the resend, resent PATCH and DELETE as
POST, dropped multipart files and ignored the handler's ssl_verify.

The retry now resends the request the first attempt built, on a client with the
handler's TLS settings, closes that client when a streamed body is closed, and masks
a status error the same way the first attempt does.
@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@greptile-apps

greptile-apps Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] Guardrail API now accepts more message and tool formats.

The new unit tests must meet the repository's dependency-injection and Final requirements before merging

Findings

  1. P2 Tests replace internal attributes ▶
  2. P2 New locals lack `Final` ▶

Summary

The PR accepts Gemini tools without type, forwards message mappings without stripping fields, updates echo detection, and adds error names to fail-open logs

Two repository requirements remain unmet in the new unit tests. They replace internal attributes instead of injecting dependencies and omit required Final annotations

The earlier, unnumbered socket-test thread was resolved. ryan-crabbe-berri reported moving those tests into integration coverage

  • Gemini tools reach guardrails without gaining a type field.
  • Guardrails receive and return provider-shaped message rows.
  • Fail-open logs name the error that let a request continue.

Reviews (7) · Last reviewed commit: "test(guardrails): pick the closed guardr..." · Reviewed by Greptile

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

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

…onse

A load balancer that closes an idle keepalive connection made the guardrail POST
fail with "Server disconnected", because #46336 only resends POST on ConnectError.
AsyncHTTPHandler.post now takes a keyword-only idempotent flag, defaulting to
False, that gives a RemoteProtocolError the same single fresh-client resend PUT
and DELETE get. Only GenericGuardrailAPI.apply_guardrail opts in, since a
guardrail check is a pure verdict over the request. Every other POST keeps the
#46336 rule

The fail-open log line now puts error_type at the end so the pre-PR text stays
contiguous for existing alert matchers

test_rows_reach_the_guardrail_verbatim now reads the body off a real local
guardrail server instead of mock call args
@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai re review

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

…ket tests to integration

A ServerDisconnectedError raised while reading a response body now stays
httpx.ReadError, as it was before this PR. Only a disconnect before any
response maps to RemoteProtocolError, which is the case the resend rule is
about. Stream readers that end on ReadError, like the SAP stream iterator,
keep their old behavior

The loopback-server disconnect, TLS and guardrail resend tests move to
tests/integration/sdk/test_disconnect_resend_wire.py, since tests/unit is
in-process only. Unit keeps in-process MockTransport checks for the idempotent
POST resend, masking on the resend, streamed and buffered client closing, the
guardrail resend, and the guardrail receiving rows verbatim
@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai re review

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

… on texts

An idempotent POST now resends once on any network error after connect
(ReadError, WriteError, RemoteProtocolError), so a guardrail behind a load
balancer that answers a stale keepalive with a TCP reset rides it out too.
That makes the aiohttp ServerDisconnectedError remap unnecessary, so it goes
back to ReadError. This stops PUT and DELETE from stacking litellm's resend on
top of aiohttp's own idempotent retry (4 sends instead of 2) and stops Vigil
Guard from replaying its analyze POST on a disconnect

Every resend now runs inside the method's own error mapping, so a timeout on
the resend is a litellm.Timeout like the first attempt and a status error is
masked once by the caller

A guardrail server that parses rows with its own message types and echoes them
back without the keys those types lack (annotations, tool_calls[].index) is
read as an echo again, so its texts redaction reaches the LLM. A row only counts
as an echo when no value changed and every key the chat completion types
declare is kept

The wire tests for the PUT/DELETE resend, its masking and its TLS settings now
run on the httpx transport, where litellm's resend is the only retry, and the
POST and guardrail tests cover both transports and both cut styles
@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai re review

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

…fail-open error type and idle cut resend

Integration tests against an owned proxy and scripted peers. Gemini native tools reach the guardrail and Gemini as sent, the guardrail sees chat rows and an Anthropic image block as sent, an echoing guardrail leaves a /v1/messages request unchanged, the fail-open log line names ConnectError, Timeout or HTTPStatusError, and a guardrail check cut on an idle pooled connection is resent once on each worker. Each fails at the merge base and passes at the head
@ryan-crabbe-berri ryan-crabbe-berri changed the title fix(guardrails): accept Gemini tools and Anthropic content blocks in generic_guardrail_api, retry load-balancer disconnects, name the error type on fail-open fix(guardrails): accept Gemini tools and Anthropic content blocks in generic_guardrail_api, resend its calls cut by a load balancer, name the error type on fail-open Oct 15, 2026
@kerry-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 16, 2026

Copy link
Copy Markdown

Review not started

LiteLLM team members: sign in to LiteReview with your work Google account and connect GitHub, then post your review request again.

Everyone else: comment @litereview oss-review. No sign-in needed.

…t of this PR

The resend on a dropped or hung generic guardrail call, and the shared AsyncHTTPHandler retry rework behind it, move to a follow-up PR that adds a per-guardrail num_retries setting. This PR keeps the request and response shape fixes and the error_type on the fail-open log line
… port allocator

Reading a port back from a port-0 bind trips TQ012, so the fail-open connect error case now takes its unused port from allocate_port
@ryan-crabbe-berri ryan-crabbe-berri changed the title fix(guardrails): accept Gemini tools and Anthropic content blocks in generic_guardrail_api, resend its calls cut by a load balancer, name the error type on fail-open fix(guardrails): accept Gemini tools and Anthropic content blocks in generic_guardrail_api, name the error type on fail-open Oct 16, 2026
@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai re review

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@litereview guide


endpoint: Final = AsyncHTTPHandler(transport=httpx.MockTransport(answer))
try:
with patch.object(generic_guardrail, "async_handler", endpoint):

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 Tests replace internal attributes

The new tests replace async_handler and post through patch.object. The repository requires dependency injection instead. Pass the test client into the guardrail before merging

Context Used: AGENTS.md (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!

):
"""A server that parses rows with its own message types echoes them back without
the keys those types lack, and its texts redaction must still reach the LLM."""
original_rows = [

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 New locals lack Final

The new tests assign original_rows, assistant_row, and other locals without Final. The repository requires every variable to carry Final. Annotate these new assignments before merging

Context Used: AGENTS.md (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!

@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 707e8a2. Configure here.

@litereview

litereview Bot commented Oct 16, 2026

Copy link
Copy Markdown

📝 guide

Open preview

Scope: full · Full PR review.

Today, a caller whose key runs a generic_guardrail_api guardrail on pre_call gets a 500 (GuardrailToolParam type Field required) when they send Gemini native tools such as function_declarations or googleSearch.

The walkthrough follows that Gemini request:

  1. The caller sends a chat request to Gemini with a function_declarations tool. Same both ways.
  2. The key's guardrail runs before the model is called. Same both ways.
  3. The proxy copies the tools into the guardrail's tool form. Breaks here: the form requires type, and Gemini tools have none. Fixed here: type is optional and left out when it's missing.
  4. The guardrail scans the tools. Today it never gets the request. After the fix it sees them exactly as sent.
  5. The guardrail's echo is written back. Today it never runs. After the fix no type key is added.
  6. Gemini gets the call. Today it is never called. After the fix it gets the tools as written.
  7. The caller gets an answer. Today it's a 500. After the fix it's a 200.

What the fix changes for the caller:

  • Gemini native tools pass the guardrail.
  • The guardrail sees message rows as the client sent them, with name, tool_calls[].index and Anthropic image blocks kept.
  • An echoing guardrail no longer drops document blocks from /v1/messages.
  • The fail-open log line now ends with error_type=.

Tests added: 5 integration tests with 7 cases in tests/integration/observability/test_generic_guardrail_api_wire.py, plus unit tests covering tools, row echoes and the log line. I ran both locally: 7 integration cases and 91 unit tests passed.

Black box coverage: Yay. Each of the four behaviors that changed has its own integration test that runs the proxy against local stand-ins for the guardrail and the provider.

I found no defects.

Checks and execution details
  • Passed · Unit tests for generic_guardrail_api (optional): .venv/bin/python -m pytest tests/unit/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py -q: 91 passed.
  • Passed · New integration file (extensions group) (optional): Started local Postgres and Redis, ran prisma generate, then ran tests/integration/run.py extensions --workers 2 tests/integration/observability/test_generic_guardrail_api_wire.py: 7 passed in 60s. The first attempt failed at proxy startup because the Prisma client had not been generated. That was a setup step, not a product failure.
  • Passed · Before/after reproduction of the Gemini tool path (optional): Called apply_guardrail with the guardrail's HTTP call stubbed. With the old required type: str model swapped in, it raised Generic Guardrail API failed: 1 validation error for GuardrailToolParam type Field required. With the PR model, the guardrail got the function_declarations tool unchanged, and the echoed tool came back unchanged.
  • Passed · Preview page structure (required): The page has 14 radios (7 stops on each side) and exactly one is checked. Every for= matches an id. There are no scripts, buttons or em dashes.

View review · Reviewed 707e8a2f396e

…ward_messages_as_sent

generic_guardrail_api keeps main's OpenAI-format rows and echo comparison by default. Setting forward_messages_as_sent: true on the guardrail sends rows as the client sent them and treats an echo that only drops undeclared keys as unchanged
@greptile-apps

greptile-apps Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@ryan-crabbe-berri ryan-crabbe-berri changed the title fix(guardrails): accept Gemini tools and Anthropic content blocks in generic_guardrail_api, name the error type on fail-open fix(guardrails): accept Gemini tools in generic_guardrail_api, add opt-in forward_messages_as_sent, name the error type on fail-open Oct 16, 2026
@ryan-crabbe-berri
ryan-crabbe-berri enabled auto-merge (squash) October 16, 2026 21:50
@ryan-crabbe-berri
ryan-crabbe-berri merged commit 0dac61a into main Oct 16, 2026
95 of 96 checks passed
@ryan-crabbe-berri
ryan-crabbe-berri deleted the litellm_generic_guardrail_shapes branch October 16, 2026 21:52
yucheng-berri pushed a commit that referenced this pull request Nov 25, 2026
…t-in forward_messages_as_sent, name the error type on fail-open (#46338)

* fix(guardrails): accept Gemini tools and Anthropic content blocks in generic_guardrail_api, name the error type on fail-open

GuardrailToolParam required a type key, so Gemini native tools
(function_declarations, googleSearch) failed validation inside the hook
and either returned a 500 or skipped the scan when fail_on_error was
false. The type key is now optional and left out of the forwarded tool
when absent, so an echoing guardrail server cannot write type: null into
the provider request.

structured_messages was re-validated against the chat completion message
types, which silently emptied tool_result, tool_use, image and document
content blocks to content: [] and dropped undeclared keys before the
guardrail saw them. The request model now forwards rows as opaque
mappings, which also retires the write-back shim that restored the
original rows for echoed-back entries.

The fail-open critical log line now carries error_type so a timeout, a
refused connection and an upstream HTTP status can be told apart without
the traceback.

* fix(httpx): retry aiohttp server disconnects the way httpx does

aiohttp raises ServerDisconnectedError when a kept-alive connection is
closed by the peer before a response arrives, which is what a load
balancer idle timeout shorter than AIOHTTP_KEEPALIVE_TIMEOUT produces.
The transport mapped it to httpx.ReadError, which the handler's
connection-error retry does not cover, so the request failed instead of
being resent on a fresh connection. It now maps to
httpx.RemoteProtocolError, the error httpx itself raises for the same
condition, so the existing retry fires.

* test(httpx): build the stub server reply in one bytes literal

* fix(httpx): resend a dropped connection's request as sent and keep a streamed resend readable

The connection-error retry closed its fresh client before a streamed body was read,
so an aiohttp disconnect now billed a second upstream request and still failed. It
also skipped masking on a status error from the resend, resent PATCH and DELETE as
POST, dropped multipart files and ignored the handler's ssl_verify.

The retry now resends the request the first attempt built, on a client with the
handler's TLS settings, closes that client when a streamed body is closed, and masks
a status error the same way the first attempt does.

* fix(guardrails): log HTTPStatusError, not the masking wrapper, as the fail-open error_type

* fix(guardrails): resend a generic guardrail check cut before any response

A load balancer that closes an idle keepalive connection made the guardrail POST
fail with "Server disconnected", because #46336 only resends POST on ConnectError.
AsyncHTTPHandler.post now takes a keyword-only idempotent flag, defaulting to
False, that gives a RemoteProtocolError the same single fresh-client resend PUT
and DELETE get. Only GenericGuardrailAPI.apply_guardrail opts in, since a
guardrail check is a pure verdict over the request. Every other POST keeps the

The fail-open log line now puts error_type at the end so the pre-PR text stays
contiguous for existing alert matchers

test_rows_reach_the_guardrail_verbatim now reads the body off a real local
guardrail server instead of mock call args

* fix(http): keep a mid-body server disconnect a ReadError and move socket tests to integration

A ServerDisconnectedError raised while reading a response body now stays
httpx.ReadError, as it was before this PR. Only a disconnect before any
response maps to RemoteProtocolError, which is the case the resend rule is
about. Stream readers that end on ReadError, like the SAP stream iterator,
keep their old behavior

The loopback-server disconnect, TLS and guardrail resend tests move to
tests/integration/sdk/test_disconnect_resend_wire.py, since tests/unit is
in-process only. Unit keeps in-process MockTransport checks for the idempotent
POST resend, masking on the resend, streamed and buffered client closing, the
guardrail resend, and the guardrail receiving rows verbatim

* fix(guardrails): resend a reset guardrail check and keep typed echoes on texts

An idempotent POST now resends once on any network error after connect
(ReadError, WriteError, RemoteProtocolError), so a guardrail behind a load
balancer that answers a stale keepalive with a TCP reset rides it out too.
That makes the aiohttp ServerDisconnectedError remap unnecessary, so it goes
back to ReadError. This stops PUT and DELETE from stacking litellm's resend on
top of aiohttp's own idempotent retry (4 sends instead of 2) and stops Vigil
Guard from replaying its analyze POST on a disconnect

Every resend now runs inside the method's own error mapping, so a timeout on
the resend is a litellm.Timeout like the first attempt and a status error is
masked once by the caller

A guardrail server that parses rows with its own message types and echoes them
back without the keys those types lack (annotations, tool_calls[].index) is
read as an echo again, so its texts redaction reaches the LLM. A row only counts
as an echo when no value changed and every key the chat completion types
declare is kept

The wire tests for the PUT/DELETE resend, its masking and its TLS settings now
run on the httpx transport, where litellm's resend is the only retry, and the
POST and guardrail tests cover both transports and both cut styles

* test(guardrails): black box wire tests for generic guardrail shapes, fail-open error type and idle cut resend

Integration tests against an owned proxy and scripted peers. Gemini native tools reach the guardrail and Gemini as sent, the guardrail sees chat rows and an Anthropic image block as sent, an echoing guardrail leaves a /v1/messages request unchanged, the fail-open log line names ConnectError, Timeout or HTTPStatusError, and a guardrail check cut on an idle pooled connection is resent once on each worker. Each fails at the merge base and passes at the head

* fix(guardrails): check echoed rows without recursion and keep pytest.raises to one statement

* refactor(guardrails): move the dropped-connection guardrail resend out of this PR

The resend on a dropped or hung generic guardrail call, and the shared AsyncHTTPHandler retry rework behind it, move to a follow-up PR that adds a per-guardrail num_retries setting. This PR keeps the request and response shape fixes and the error_type on the fail-open log line

* test(guardrails): pick the closed guardrail port from the integration port allocator

Reading a port back from a port-0 bind trips TQ012, so the fail-open connect error case now takes its unused port from allocate_port

* feat(guardrails): forward structured_messages as sent only behind forward_messages_as_sent

generic_guardrail_api keeps main's OpenAI-format rows and echo comparison by default. Setting forward_messages_as_sent: true on the guardrail sends rows as the client sent them and treats an echo that only drops undeclared keys as unchanged

---------

Co-authored-by: yuneng-jiang <yuneng@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 0dac61a)
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.

5 participants