Repository navigation
Conversation
Requests carrying built-in tools (code_interpreter, file_search, ...) crashed
the Generic Guardrail with a 500. GenericGuardrailAPIRequest.tools validated
each tool against ChatCompletionToolParam, whose base TypedDict requires a
function block, so a tool like {"type": "code_interpreter"} raised a Pydantic
ValidationError before the request was ever sent.
Type the field with a permissive GuardrailToolParam model (type required,
extra=allow) so built-in tools validate and their config is forwarded to the
guardrail intact instead of being stripped.
Greptile SummaryThis PR fixes two related gaps in the Generic Guardrail integration: built-in tools (
Confidence Score: 5/5Safe to merge; both changes are correctly scoped to the generic guardrail, backward-compatible (new parameters default to existing behavior), and covered by comprehensive mock-only unit tests. The built-in tool fix is narrowly contained to a new Pydantic model used only in the guardrail request schema, and the fail-open wiring correctly re-uses the existing fail_on_error field with a fail-closed default. The only finding is a misleading log message that says unreachable for non-network errors when fail_on_error is false — a diagnostics issue that does not affect correctness or security. No files require special attention.
|
| Filename | Overview |
|---|---|
| litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py | Wires up fail_on_error into _handle_guardrail_request_error and moves request construction inside the protected try/except block; logic is correct but the shared _fail_open_passthrough log message still says "unreachable" for non-network failures. |
| litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py | Introduces GuardrailToolParam (Pydantic model with extra="allow") to replace ChatCompletionToolParam in the request schema, and adds fail_on_error to GenericGuardrailAPIOptionalParams; both changes are correct and well-scoped. |
| litellm/types/guardrails.py | Updates the fail_on_error field description in BaseLitellmParams to document its new scope beyond Model Armor; straightforward documentation change. |
| litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/init.py | Passes fail_on_error from litellm_params to GenericGuardrailAPI.__init__ with the correct default of True; one-line change, safe. |
| tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py | Adds thorough mock-only unit tests covering built-in tool forwarding, fail-open on endpoint errors and construction errors, valid BLOCK still raises under fail-open, default behavior unchanged, and both request/response paths; no real network calls. |
Reviews (2): Last reviewed commit: "test(guardrails): cover fail_on_error on..." | Re-trigger Greptile
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…uardrail The Generic Guardrail already honored unreachable_fallback, which fails open only on network-unreachable errors. This wires up the existing generic fail_on_error config (so far implemented only by Model Armor) so that fail_on_error=false degrades any guardrail error to a critical-log warning and lets the request proceed as if the guardrail were absent. Only a valid guardrail response can act: a parsed BLOCKED decision still raises, while endpoint errors, malformed responses, and internal serialization or validation errors all fall through when fail_on_error=false. To cover that last class, the request construction now runs inside the protected block, so the kind of validation error that previously surfaced as a 500 is caught here too. Defaults to true (fail closed), matching today's behavior; turning it off is an explicit availability-over-security choice and is logged at critical level on every bypass.
The existing fail_on_error tests all drive the request path. Add response-path (input_type=response) coverage: an endpoint error proceeds unchanged under fail_on_error=false, and a valid BLOCKED decision still raises. Guards against a future regression that special-cases input_type in the error handling.
CI runs black (line-length 88) over litellm/; the unreachable_fail_open assignment exceeded it. Wrap it to satisfy the formatter.
Changing the request field to List[GuardrailToolParam] left the construction passing List[ChatCompletionToolParam] (list is invariant), which tripped the basedpyright reportArgumentType budget gate. Validate each tool explicitly, which is what Pydantic did implicitly, so the types line up with no Any or suppression and the serialized payload is unchanged.
…errors The fail-open path is now shared by fail_on_error, so it fires for any guardrail error, not just unreachability. The log said 'unreachable' even for an HTTP 400 or a malformed response; reword to 'error' (the status code and exception are already logged). Addresses the Greptile review's only finding.
|
Thanks for the review. Addressed the one finding in 6b36cdf: the fail-open path is now shared by |
|
looking at this |
| unreachable_fallback=getattr( | ||
| litellm_params, "unreachable_fallback", "fail_closed" | ||
| ), | ||
| fail_on_error=getattr(litellm_params, "fail_on_error", True), |
There was a problem hiding this comment.
Could you help me better understand the intention behind this part in your PR description.
When you say “the second gives operators a general lever so that any guardrail failure can degrade gracefully instead of taking the request down with it,” do you mean adding a configurable fallback behavior so that if a guardrail fails internally, the request can still continue depending on the operator’s setting?
There was a problem hiding this comment.
@yucheng-berri Yes - internally or that the guardrail endpoint has an error.
By default it's keeping the current behavior - failing on an error.
There are use cases where the operational flow is more important than the guardrail, so this is an option to configure a guardrail to be "fully fail-open".
There was a problem hiding this comment.
once fail-open is on, would an attacker deliberately error the guardrail to bypass it?
There was a problem hiding this comment.
@yucheng-berri Yes, that's exactly why the default is still fail-close :)
Setting this should take this into consideration, and it should be documented of course (can't find the docs, were in this repo before)
There was a problem hiding this comment.
@yucheng-berri @krrish-berri-2 is there anything else that is required to merge it? I will do whatever is needed, this is for a very important customer
There was a problem hiding this comment.
Could you open a companion PR against BerriAI/litellm-docs to document it? Appreciated
The code change can merge independently; this is just so the new knob is discoverable. :)
| unreachable_fallback=getattr( | ||
| litellm_params, "unreachable_fallback", "fail_closed" | ||
| ), | ||
| fail_on_error=getattr(litellm_params, "fail_on_error", True), |
There was a problem hiding this comment.
Could you open a companion PR against BerriAI/litellm-docs to document it? Appreciated
The code change can merge independently; this is just so the new knob is discoverable. :)
|
@yucheng-berri here is the documentation PR - BerriAI/litellm-docs#414 |
…r the Generic Guardrail (#414) Companion to BerriAI/litellm#31286. Adds a fail_on_error config line and an Error handling section covering how it relates to unreachable_fallback, with a danger admonition that it defaults to fail-closed and that setting it to false bypasses the guardrail on ANY failure, so it should be chosen only when operational constraints outweigh security constraints. Also notes that built-in tools (code_interpreter, file_search) with no function block are accepted.
|
Thank you! Docs merged. Merging the code to internal_staging |
…ols and errors (adopted from #31286) (#31461) * fix(guardrails): stop Generic Guardrail API 500 on built-in tools Requests carrying built-in tools (code_interpreter, file_search, ...) crashed the Generic Guardrail with a 500. GenericGuardrailAPIRequest.tools validated each tool against ChatCompletionToolParam, whose base TypedDict requires a function block, so a tool like {"type": "code_interpreter"} raised a Pydantic ValidationError before the request was ever sent. Type the field with a permissive GuardrailToolParam model (type required, extra=allow) so built-in tools validate and their config is forwarded to the guardrail intact instead of being stripped. * feat(guardrails): add complete fail-open (fail_on_error) to Generic Guardrail The Generic Guardrail already honored unreachable_fallback, which fails open only on network-unreachable errors. This wires up the existing generic fail_on_error config (so far implemented only by Model Armor) so that fail_on_error=false degrades any guardrail error to a critical-log warning and lets the request proceed as if the guardrail were absent. Only a valid guardrail response can act: a parsed BLOCKED decision still raises, while endpoint errors, malformed responses, and internal serialization or validation errors all fall through when fail_on_error=false. To cover that last class, the request construction now runs inside the protected block, so the kind of validation error that previously surfaced as a 500 is caught here too. Defaults to true (fail closed), matching today's behavior; turning it off is an explicit availability-over-security choice and is logged at critical level on every bypass. * test(guardrails): cover fail_on_error on the response path The existing fail_on_error tests all drive the request path. Add response-path (input_type=response) coverage: an endpoint error proceeds unchanged under fail_on_error=false, and a valid BLOCKED decision still raises. Guards against a future regression that special-cases input_type in the error handling. * style(guardrails): black-format the fail-open guard expression CI runs black (line-length 88) over litellm/; the unreachable_fail_open assignment exceeded it. Wrap it to satisfy the formatter. * fix(guardrails): validate tools into GuardrailToolParam at the call site Changing the request field to List[GuardrailToolParam] left the construction passing List[ChatCompletionToolParam] (list is invariant), which tripped the basedpyright reportArgumentType budget gate. Validate each tool explicitly, which is what Pydantic did implicitly, so the types line up with no Any or suppression and the serialized payload is unchanged. * fix(guardrails): make fail-open log message accurate for non-network errors The fail-open path is now shared by fail_on_error, so it fires for any guardrail error, not just unreachability. The log said 'unreachable' even for an HTTP 400 or a malformed response; reword to 'error' (the status code and exception are already logged). Addresses the Greptile review's only finding. * fix(guardrails): align GenericGuardrailAPIResponse.tools with GuardrailToolParam Greptile flagged that the request side moved to GuardrailToolParam but the response side still annotated tools as List[ChatCompletionToolParam], which mandates a function block and contradicts the new built-in-tools support. Update the response annotation (and the now-unused import) so the two sides agree. Runtime is unchanged; from_dict stores the raw dicts and the only consumer assigns through to GenericGuardrailAPIInputs without inspecting the elements. --------- Co-authored-by: Itay Ovadia <itay@sun.security>
|
Closing as merged. This work landed on 2026-06-26 via #31461, which mirrored it onto a Your authorship was preserved: the merge commit e99151b carries Thanks @itayov, and sorry this one stayed open after the change had already shipped. |
Relevant issues
A user integrating a Generic Guardrail API hit a 500 on every request that carried a built-in tool (
code_interpreter,file_search, ...). Digging into it surfaced a broader gap: when the guardrail itself errors for any reason, there was no way to keep serving traffic unless the error happened to be a network-unreachable one. This PR addresses both, because they are the same concern from two angles. The first removes a specific way the guardrail breaks a request; the second gives operators a general lever so that any guardrail failure can degrade gracefully instead of taking the request down with itPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
make test-unit@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
CI (LiteLLM team)
Branch creation CI run
Link:
CI run for the last commit
Link:
Merge / cherry-pick CI run
Links:
Screenshots / Proof of Fix
Everything below runs against a real proxy (
proxy_cli.pyon:4000) hitting the real Anthropic API withclaude-haiku-4-5, in front of a real guardrail service I wrote that implements the LiteLLM Basic Guardrail API. In normal operation that service does genuine guardrail work: it blocks prompts that match a prohibited-content policy and strips disallowed built-in tools. It also supports deliberate fault injection so its failure modes can be driven, which is how the error matrix below is produced; nothing in the guardrail code path is mocked or patched.the guardrail service and config used for the runs
guardrail_service.py(stdlib only): real policy in the normal path, fault injection via a__fault__ <mode>message for the degraded paths.Config (the
fail_on_errorandunreachable_fallbacklines are what change across runs):The guardrail working normally
The fix: built-in tools no longer 500
Before the fix (pre-fix commit), HTTP 500 and the guardrail service is never even reached:
After the fix, HTTP 200; the guardrail receives the built-in tools intact (
code_interpreterplusfile_searchwith itsvector_store_idsandmax_num_results), applies its policy, and the model responds.Complete fail-open across every error class
Each request injects a guardrail fault via its message (
__fault__ err_503,__fault__ badjson,__fault__ drop, ...). A valid policy block always blocks and a benign request always reaches the model, in every mode.fail_on_error: false(complete fail-open). Every error class continues to the model:fail_on_error: true,unreachable_fallback: fail_closed(the defaults; today's behavior). Every error blocks:fail_on_error: true,unreachable_fallback: fail_open(the two knobs are independent). Only the unreachable class continues; everything else still blocks:Internal request-construction failure (a malformed image URL that fails
GenericGuardrailAPIRequestvalidation, the same class as the original bug) is governed the same way, and the guardrail service is never called because the failure happens while building the request:The status value itself does not change behavior beyond one exact thing: the unreachable check is literally
status_code in (502, 503, 504). Verified by injecting a spread of uncommon and non-standard codes (402, 405, 408, 410, 418, 421, 423, 431, 451, 499, 506, 510, 511, 520, 521, 530, 599). Underfail_on_error: falseall of them continue; underfail_on_error: truewithunreachable_fallback: fail_openall of them block while only 502/503/504 continue, so a random 5xx like 520 or 599 is not mistaken for unreachable:Request and response hooks
All of the above runs are
mode: pre_call(the request path). The same handling applies onmode: post_call(the response path), since both go through the sameapply_guardrail. Forcing the guardrail to return a 503 under each hook, confirmed by the service logginginput_type='request'vsinput_type='response':A valid block also works on both:
pre_callreturns "blocked by guardrail on request",post_callreturns "blocked by guardrail on response". The post-call case carries a real consequence worth stating: withfail_on_error: falsethe already-generated model response is returned, while withfail_on_error: truea successful, paid-for generation is discarded and the caller gets a 500. (The non-streaming response path is what was driven live; streaming responses call the sameapply_guardrail(input_type="response").)Type
🐛 Bug Fix
🆕 New Feature
Changes
The two changes are the same idea seen from two sides: the guardrail should not be the thing that breaks a request unexpectedly. The fix removes one concrete way that happened, and the fail-open mode is the general escape hatch for the rest
Built-in tools fix. Before forwarding a request to the guardrail, LiteLLM builds a
GenericGuardrailAPIRequest. Itstoolsfield validated each tool againstChatCompletionToolParam, whose baseTypedDictmarksfunctionas required. Built-in tools such ascode_interpreterandfile_searchcarry only atypeand nofunctionblock, so Pydantic raised aValidationErrorthat surfaced as a generic 500 before the request was ever sent. The schema was also internally inconsistent: the tooltypewas alreadyUnion[Literal["function"], str], so it claimed to allow non-function tools while still mandating a function block. The field now uses a smallGuardrailToolParammodel that requires onlytypeand setsextra="allow", so built-in tools validate and their config is forwarded intact rather than stripped. This is contained to the guardrail request model and does not touch the sharedChatCompletionToolParamComplete fail-open. Fixing the built-in tools crash removes one trigger, but a guardrail or its endpoint can fail in many other ways, and until now the only way to keep serving was
unreachable_fallback, which fires solely on network-unreachable errors. This wires up the existing genericfail_on_errorconfig (until now implemented only by Model Armor) for the Generic Guardrail. Withfail_on_error: false, any guardrail error degrades to a critical-log warning and the request proceeds as if the guardrail were absent; only a valid guardrail response can act, so a parsed BLOCKED decision still raises while endpoint errors, malformed responses, and internal serialization or validation errors all fall through. To cover that last class the request construction now runs inside the protected block, which is why the very error category behind the original 500 is now also catchable here. It defaults totrue(fail closed), so existing behavior is unchanged; turning it off is an explicit availability-over-security choice and is logged at critical level on every bypass. It composes withunreachable_fallbackrather than replacing it, as the matrix above showsTests. The tool change has a regression test that pushes a function tool, a
code_interpreter, and a configuredfile_searchthroughapply_guardrailand asserts the forwarded payload matches the input exactly. The fail-open change adds tests that a non-unreachable endpoint error and an internal construction error both proceed unchanged whenfail_on_erroris false (the latter also asserting the endpoint is never called, proving construction is inside the protected block), that a valid BLOCKED response still raises under fail-open, and that the default still blocks on error. The response path (input_type="response") has its own tests for both the fail-open and the still-blocks cases, guarding against a regression that special-cases the hook in error handling. Each fails when its target behavior is mutated