Skip to content

feat(topic_relevance_llm): skip validator when its LLM is unreachable - #200

Merged
AkhileshNegi merged 6 commits into
mainfrom
feat/skip-validator-on-error
Dec 3, 2026
Merged

AkhileshNegi merged 6 commits into
mainfrom
feat/skip-validator-on-error

Conversation

@AkhileshNegi

@AkhileshNegi AkhileshNegi commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

What Changed

  • topic_relevance_llm: when the LLM can't be reached, outcome is SKIPPED instead of FAIL. Text passes through unchanged, rest of the chain runs.
  • Only infrastructure errors skip: AuthenticationError, PermissionDeniedError, APIConnectionError, Timeout, ServiceUnavailableError, InternalServerError, and a plain BadRequestError (what OpenAI returns for a revoked / wrong-project key; matched with type(e) is, not isinstance).
  • Errors the caller's input can cause still FAIL, so nobody can trigger a skip on purpose: ContextWindowExceededError, ContentPolicyViolationError (and other BadRequestError subclasses), encoding errors, and anything unexpected. RateLimitError also fails, so one tenant flooding the shared key can't switch the check off for everyone. The error holds only the exception type ("LLM call failed: ContextWindowExceededError"), not the provider message.
  • An LLM reply that can't be parsed (no choices, bad JSON, out-of-range score, content=None) still returns FAIL, as on main.
  • ValidatorOutcome: PASS | FAIL → PASS | FAIL | SKIPPED; migration 012 adds the value to the validatoroutcome Postgres enum
  • validator_results[].error on a skip = "Validator skipped: LLM call failed (<ExceptionType>)"; exception text (truncated to 500 chars) stored only in validator_log.meta.result_metadata.skip_detail
  • suppress_pass_logs still writes SKIPPED rows (only PASS is suppressed)

Summary

Why validators failed closed: in #71 (Mar 2026), the first topic_relevance, built on LLMCritic, wrapped any error in FailResult("LLM critic returned an invalid response: ..."). That's the common guardrails convention: if a validator can't check a message, it fails it rather than letting it through.

 guard.validate(text)
   topic_relevance_llm._validate
     completion() raises
-    return FailResult("LLM call failed: …")       # any error → fallback reply to every user
+    if not (isinstance(e, _SKIP_ERRORS) or type(e) is litellm.BadRequestError):
+        return FailResult("LLM call failed: <Type>")   # input-caused / 429 / unexpected
+    return PassResult(metadata={"skipped": "Validator skipped: LLM call failed (<Type>)"})
   next validator                                   # still runs
 _summarize_validator_results / add_validator_logs
-  outcome = result.outcome.upper()                 # PASS / FAIL
+  outcome, error = _outcome_and_error(result)      # PASS / FAIL / SKIPPED

Evidence

  • Before: completion raising → FailResult, error="LLM call failed: litellm.AuthenticationError: … Incorrect API key provided: sk-proj-****1234 …"; with on_fail=rephrase and no fallback that string reached the end user in safe_text.
    After: test_erroring_validator_is_skipped_and_chain_continues — real Guard with TopicRelevanceLLM (completion raising) + LexicalSlur:
    validated_output == "How do I bake bread?"
    outcomes == ["SKIPPED", "PASS"]
    error == "Validator skipped: LLM call failed (Exception)"
    
  • Live, with the local (revoked) key: topic_relevance_llm skipped: LLM call failed with BadRequestError → {'skipped': 'Validator skipped: LLM call failed (BadRequestError)', 'skip_detail': 'litellm.BadRequestError: OpenAIException - You do not have access to the project tied to the API key.'}
  • Tests are parametrized over both sides: 6 infrastructure errors skip; context window, content policy, rate limit, lone surrogate and a bare Exception fail; a reply with empty choices fails.
  • Suite: 376 passed, 14 skipped (excluding test_topic_relevance_llm_live.py, which needs a working OpenAI key).

Merge Danger

Door: one-way

ALTER TYPE validatoroutcome ADD VALUE 'SKIPPED' can't be dropped; downgrade() is a no-op. Rolling back the code after SKIPPED rows exist leaves the old ValidatorOutcome unable to load them, so anything reading validator_log breaks.

Blast Radius: fail-open, topic_relevance_llm only

  • While the LLM is unreachable (auth / network / provider 5xx), off-topic messages reach the LLM instead of getting the fallback reply. The only signal is an ERROR log line topic_relevance_llm skipped: LLM call failed with <Type> per message and SKIPPED rows in validator_log.
  • Companion change needed: glific-frontend GuardrailTrace.tsx uses isFlagged = outcome !== 'PASS', so SKIPPED renders as "Flagged" until a third "Skipped" badge is added. kaapi-backend summarize_validator_results passes outcome through as a string, no change needed.
  • Config errors (e.g. OPENAI_API_KEY unset at build time, missing prompt template) still fail as before.

🤖 Generated with Claude Code

content_safety, topic_relevance_llm, pii_remover and gender_assumption_bias
now share a SkipOnError mixin: any exception inside the validator (expired
OpenAI key, model load error, unparseable LLM output) returns a new SKIPPED
outcome, passes the text through unchanged, and lets the rest of the chain
run. Previously topic_relevance_llm turned an LLM error into a FailResult,
so with on_fail=rephrase every message got the fallback reply.

Adds SKIPPED to the validatoroutcome Postgres enum (migration 012).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are limited based on label configuration.

🏷️ Required labels (at least one): 1

  • ready-for-review

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Findings marked 🟡 are optional suggestions and need no follow-up push.

Drop the SkipOnError mixin. Only topic_relevance_llm's completion() call
now maps to SKIPPED; unparseable LLM replies still FAIL so users can't
prompt-inject the scorer into skipping. content_safety, pii_remover and
gender_assumption_bias run locally and are back to main; their failure
handling moves to a separate PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@AkhileshNegi AkhileshNegi changed the title feat(validators): skip validator on error instead of failing the request feat(topic_relevance_llm): skip validator when the LLM call fails Dec 3, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The latest push brings back an issue flagged in an earlier review; replied in that comment's thread.

Still open from earlier reviews (2):

  • Unresolved: 1 minor or pre-existing, 1 blocking on lines changed since (possibly already fixed).

If you have decided not to act on one of these findings, resolve its thread (a reply alone leaves it open) and the next review stops counting it. To review this commit again now, use Re-run on its "Claude Code Review" check.

The catch-all except let callers trigger a skip with their own input
(oversized message -> ContextWindowExceededError, content-filter trip,
lone surrogate). Now only auth, connection/timeout, provider 5xx and a
plain BadRequestError (OpenAI's revoked-key response) skip; input-caused
BadRequestError subclasses, rate limits and unexpected errors still fail.
Response extraction moved into the parse try so a malformed reply fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Still open from earlier reviews (1):

  • Unresolved: 1 minor or pre-existing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@AkhileshNegi AkhileshNegi changed the title feat(topic_relevance_llm): skip validator when the LLM call fails feat(topic_relevance_llm): skip validator when its LLM is unreachable Dec 3, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code review found no new issues

No new issues were found in this update; 2 findings from earlier reviews are still open above.

Still open from earlier reviews (2):

  • Unresolved: 1 minor or pre-existing, 1 blocking on lines changed since (possibly already fixed).

If you have decided not to act on one of these findings, resolve its thread (a reply alone leaves it open) and the next review stops counting it. To review this commit again now, use Re-run on its "Claude Code Review" check.

@AkhileshNegi AkhileshNegi self-assigned this Dec 3, 2026
@AkhileshNegi AkhileshNegi added the bug Something isn't working label Dec 3, 2026
@AkhileshNegi AkhileshNegi linked an issue Dec 3, 2026 that may be closed by this pull request
EMPTY_MESSAGE_ERROR = "Empty message."
TOPIC_OUT_OF_SCOPE_ERROR = "Input is outside the allowed topic scope."
# PassResult metadata key the route maps to outcome SKIPPED.
SKIPPED_METADATA_KEY = "skipped"

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.

This key needn't be put into a global variable. Can use the string directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code review found no issues

No high-confidence issues detected in this change.

@AkhileshNegi
AkhileshNegi merged commit 155901f into main Dec 3, 2026
3 checks passed
@AkhileshNegi
AkhileshNegi deleted the feat/skip-validator-on-error branch December 3, 2026 11:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sneha - Scope control Guardrail trigger issue

2 participants