Skip to content

feat(guardrails): make the Generic Guardrail resilient to built-in tools and errors (adopted from #31286) - #31461

Merged
yucheng-berri merged 7 commits into
litellm_internal_stagingfrom
litellm_guardrail_builtin_tools_adopted
Jun 26, 2026
Merged

yucheng-berri merged 7 commits into
litellm_internal_stagingfrom
litellm_guardrail_builtin_tools_adopted

Conversation

@yucheng-berri

@yucheng-berri yucheng-berri commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

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 it

Pre-Submission checklist

  • I have added meaningful tests
  • My PR passes all unit tests on make test-unit
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

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. Its tools field validated each tool against ChatCompletionToolParam, whose base TypedDict marks function as required. Built-in tools such as code_interpreter and file_search carry only a type and no function block, so Pydantic raised a ValidationError that surfaced as a generic 500 before the request was ever sent. The schema was also internally inconsistent: the tool type was already Union[Literal["function"], str], so it claimed to allow non-function tools while still mandating a function block. The field now uses a small GuardrailToolParam model that requires only type and sets extra="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 shared ChatCompletionToolParam

Complete 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 generic fail_on_error config (until now implemented only by Model Armor) for the Generic Guardrail. With fail_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 to true (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 with unreachable_fallback rather than replacing it

Tests. The tool change has a regression test that pushes a function tool, a code_interpreter, and a configured file_search through apply_guardrail and 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 when fail_on_error is 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

Credit

Adopted from #31286 by @itayov. Mirrored onto a litellm_ branch so CircleCI and the internal lint workflow run. All commits preserve the original author metadata

Linear 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 strict ChatCompletionToolParam validation with GuardrailToolParam (required type, extra="allow") so full tool payloads reach the external guardrail unchanged.

Adds fail_on_error support for generic_guardrail_api (same knob as Model Armor): default fail closed; with fail_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 shared LitellmParams and 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.

itayov added 6 commits June 26, 2026 09:38
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.
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@codecov

codecov Bot commented Jun 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR makes the Generic Guardrail API resilient to two failure classes: requests containing built-in tools (e.g., code_interpreter, file_search) that previously raised a Pydantic ValidationError and caused a 500, and a new opt-in fail_on_error: false mode that degrades any guardrail error to a critical-log warning instead of blocking the request.

  • Built-in tools fix: introduces GuardrailToolParam (Pydantic model, extra=\"allow\", only type required) and validates tools into it before building the guardrail request. Existing ChatCompletionToolParam constraint is preserved in the shared types; only the guardrail request model changes.
  • Fail-open (fail_on_error): moves the entire GenericGuardrailAPIRequest construction inside the try block and adds a catch-all except Exception that routes through _handle_guardrail_request_error(is_unreachable=False). GuardrailRaisedException (a valid BLOCK) is re-raised before the catch-all, so a guardrail that actively blocks still blocks under fail-open. Defaults to True (fail-closed), preserving existing behavior.
  • Tests: all new, mock-only, covering the tool regression, endpoint-error fail-open, construction-error fail-open, valid-block-still-blocks, and both request and response paths.

Confidence Score: 5/5

Safe 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 GuardrailRaisedException is already re-raised, and the fail_on_error=True default means no existing deployment is affected. The only findings are annotation inconsistencies with no runtime impact on the current call sites.

litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py — from_dict stores raw dicts for tools despite the annotation now saying List[GuardrailToolParam].

Important Files Changed

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-apps

greptile-apps Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR makes the Generic Guardrail resilient to two failure classes: built-in tools (code_interpreter, file_search) that lack a function block were causing a Pydantic ValidationError before the guardrail was ever called, and a new fail_on_error: false option lets any guardrail error degrade gracefully instead of returning a 500.

  • Built-in tool fix: Introduces GuardrailToolParam (type required, extra=\"allow\") and swaps the GenericGuardrailAPIRequest.tools field from List[ChatCompletionToolParam] to List[GuardrailToolParam], preserving extra keys like vector_store_ids. Request construction is moved inside the existing try block so serialization errors are also covered by fail_on_error.
  • fail_on_error: false: Wired through __init__.py → constructor → _handle_guardrail_request_error. GuardrailRaisedException (a valid BLOCKED decision) is always re-raised, so fail-open never silently drops a genuine block. Default is true (fail-closed), keeping existing behavior unchanged.
  • Tests: Regression test for built-in tool passthrough; six new tests covering the error/block matrix on both request and response paths, all mock-only.

Confidence Score: 4/5

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

Important Files Changed

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)

  1. litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py, line 113-114 (link)

    P2 Response-side tools type not updated to GuardrailToolParam

    The request model now correctly uses List[GuardrailToolParam] to accept built-in tools, but GenericGuardrailAPIResponse.tools is still annotated as List[ChatCompletionToolParam]. from_dict stores raw dicts (data.get("tools")), so there's no runtime crash, but if a guardrail modifies and returns built-in tools (e.g., a rewritten code_interpreter config), the annotation misleads type-checkers and any downstream code that inspects guardrail_response.tools as ChatCompletionToolParam objects 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.
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

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 653f0ab. Configure here.

@yucheng-berri
yucheng-berri enabled auto-merge (squash) June 26, 2026 17:21
@mateo-berri
mateo-berri self-requested a review June 26, 2026 18:23
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.

3 participants