Repository navigation
feat(guardrails): make the Generic Guardrail resilient to built-in tools and errors (adopted from #31286) - #31461
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.
…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.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Greptile SummaryThis PR makes the Generic Guardrail API resilient to two failure classes: requests containing built-in tools (e.g.,
Confidence Score: 5/5Safe to merge. The changes are isolated to the Generic Guardrail, defaults are unchanged (fail-closed), and all new behavior requires explicit opt-in. Both fixes are well-contained and their corner cases are explicitly tested. The fail-open path cannot suppress a valid BLOCK decision, the catch-all runs after
|
| Filename | Overview |
|---|---|
| litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py | Core guardrail logic: moves request construction inside the try block, adds catch-all except Exception for fail-open, and validates tools into GuardrailToolParam at the call site. Logic is correct, backward-compatible, and well-guarded. |
| litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py | Introduces GuardrailToolParam, updates request model to use it, and aligns GenericGuardrailAPIResponse.tools annotation. However, from_dict still stores raw dicts without calling GuardrailToolParam.model_validate, so the annotation and runtime value are mismatched. |
| tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py | Comprehensive new tests for built-in tools passthrough, fail-open on endpoint error, fail-open on construction error, and response-path fail-open. All tests are mock-only (no live network calls) and cover both directions (request/response). |
| litellm/types/guardrails.py | Adds fail_on_error to BaseLitellmParams with accurate documentation naming both model_armor and generic_guardrail_api; no issues. |
| litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/init.py | Wires fail_on_error from litellm_params into GenericGuardrailAPI.__init__; straightforward and correct. |
Reviews (3): Last reviewed commit: "fix(guardrails): align GenericGuardrailA..." | Re-trigger Greptile
Greptile SummaryThis PR makes the Generic Guardrail resilient to two failure classes: built-in tools (
Confidence Score: 4/5Safe to merge; the one open gap (response-side tool type annotation) is cosmetic and has no runtime impact. Both changes are narrowly scoped to the Generic Guardrail path. The built-in tool fix is clearly correct: GuardrailToolParam with extra=allow is the minimal schema change needed and extra keys are preserved through model_dump. The fail-open flag preserves all existing defaults, and GuardrailRaisedException re-raise ensures a valid BLOCKED decision always blocks. The only gap is that GenericGuardrailAPIResponse.tools is still annotated as List[ChatCompletionToolParam] while the request now uses List[GuardrailToolParam] — a type annotation inconsistency, not a runtime issue. Tests are thorough and mock-only. litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py — GenericGuardrailAPIResponse.tools type annotation should be updated to List[GuardrailToolParam] for consistency with the request model.
|
| Filename | Overview |
|---|---|
| litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py | Wires up fail_on_error support; moves request construction inside the try block so construction errors also degrade gracefully; re-raises GuardrailRaisedException so valid BLOCKED decisions are unaffected. Logic is sound. |
| litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py | Adds GuardrailToolParam (type-only, extra=allow) and switches the request model's tools field to use it. GenericGuardrailAPIResponse.tools is still typed as List[ChatCompletionToolParam], which is inconsistent with the request change. |
| litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/init.py | Threads fail_on_error through initialize_guardrail, defaulting to True (fail-closed). Safe. |
| litellm/types/guardrails.py | Updates fail_on_error field description in BaseLitellmParams to document that both Model Armor and Generic Guardrail API now implement it. No logic changes. |
| tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py | Adds regression test for built-in tools and comprehensive fail-open tests (endpoint error, construction error, valid BLOCKED still raises, default still blocks, response path parity). All tests use mocks only — no real network calls. |
Comments Outside Diff (1)
-
litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py, line 113-114 (link)Response-side
toolstype not updated toGuardrailToolParamThe request model now correctly uses
List[GuardrailToolParam]to accept built-in tools, butGenericGuardrailAPIResponse.toolsis still annotated asList[ChatCompletionToolParam].from_dictstores raw dicts (data.get("tools")), so there's no runtime crash, but if a guardrail modifies and returns built-in tools (e.g., a rewrittencode_interpreterconfig), the annotation misleads type-checkers and any downstream code that inspectsguardrail_response.toolsasChatCompletionToolParamobjects would see the mismatch.
Reviews (1): Last reviewed commit: "fix(guardrails): make fail-open log mess..." | Re-trigger Greptile
…ilToolParam 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.
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 653f0ab. Configure here.
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
make test-unit@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewType
🐛 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 itTests. 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 mutatedCredit
Adopted from #31286 by @itayov. Mirrored onto a
litellm_branch so CircleCI and the internal lint workflow run. All commits preserve the original author metadataLinear ticket
Note
Medium Risk
Opt-in fail_on_error=false weakens enforcement on guardrail outages/errors; default behavior is unchanged. Tool schema change is localized to the guardrail request path.
Overview
Fixes 500s when requests include built-in tools (
code_interpreter,file_search, etc.) by replacing strictChatCompletionToolParamvalidation withGuardrailToolParam(requiredtype,extra="allow") so full tool payloads reach the external guardrail unchanged.Adds
fail_on_errorsupport forgeneric_guardrail_api(same knob as Model Armor): default fail closed; withfail_on_error: false, any guardrail failure (HTTP errors, serialization/validation, not only unreachable network) logs critically and passthrough proceeds—valid BLOCKED responses still raise. Request build + HTTP call now share one try block so pre-call validation errors are covered. Config/docs updated on sharedLitellmParamsand Generic Guardrail optional params; regression tests cover tools forwarding and fail-open paths on request/response.Reviewed by Cursor Bugbot for commit 653f0ab. Bugbot is set up for automated code reviews on this repo. Configure here.