Skip to content

LlmJudge

Runs a second Pydantic AI agent (the judge) that scores the output against your criteria.

Parameter Type Default Description
criteria str | Sequence[str] required What a good answer looks like
judge_model Model | str 'openai:gpt-4o-mini' Any Pydantic AI model name or Model instance
threshold float 0.7 Passing score, between 0 and 1 (mode='score' only)
mode 'score' | 'binary' 'score' How to decide pass or fail
include_prompt bool True Show the user’s prompt to the judge
system_prompt str | None None Replace the judge’s instructions
on_error 'raise' | 'allow' 'raise' What to do when the judge itself fails
on_fail 'retry' | 'raise' | 'warn' 'retry' See below
  • mode='score': passes when the judge’s score is >= threshold.
  • mode='binary': uses the judge’s pass/fail decision only. threshold is ignored.

If the judge call fails (network error, rate limit, invalid response), the default on_error='raise' raises GuardrailFailed. Set on_error='allow' to log the error and let the output pass.

from pydantic_ai import Agent
from pydantic_ai_guardrails import LlmJudge
agent = Agent(
'openai:gpt-4o',
capabilities=[
LlmJudge(
criteria=[
'Answers the question that was asked',
'Does not promise refunds or discounts',
'Professional tone',
],
judge_model='openai:gpt-4o-mini',
threshold=0.8,
),
],
)
from pydantic_ai_guardrails import LlmJudge
LlmJudge('Contains no medical advice', mode='binary', on_error='allow', on_fail='raise')

Each check makes an extra model call, so it adds latency and cost to every run. Put cheaper guardrails first.

  • on_fail='retry' (default): raises ModelRetry with the judge’s score and reasoning, so the model can fix its answer.
  • on_fail='raise': raises OutputBlocked.
  • on_fail='warn': logs and returns the output.
  • Judge failure: GuardrailFailed with on_error='raise'; logged and passed with on_error='allow'.