Skip to content

autoevals

autoevals (pip install autoevals) provides LLM-based and heuristic scorers. Each returns a Score with a .score between 0 and 1. Wrap a scorer in OutputGuardrail and compare the score to a threshold.

Terminal window
pip install pydantic-ai-guardrails autoevals

autoevals scorers are not pydantic-evals Evaluators, so pass them to OutputGuardrail directly rather than to pydantic_ai_guardrails.evals.evaluator_guardrail.

from typing import Any
from pydantic_ai import RunContext
from pydantic_ai_guardrails import OnOutputFail, OutputGuardrail
def autoevals_guardrail(
scorer: Any,
*,
threshold: float = 0.7,
on_fail: OnOutputFail = 'retry',
**scorer_kwargs: Any,
) -> OutputGuardrail:
name = type(scorer).__name__
async def guard(ctx: RunContext, output: Any) -> bool | str:
prompt = ctx.prompt if isinstance(ctx.prompt, str) else ''
result = await scorer.eval_async(output=str(output), input=prompt, **scorer_kwargs)
score = result.score or 0.0
if score >= threshold:
return True
rationale = (result.metadata or {}).get('rationale', '')
return f'{name} score {score:.2f} below {threshold}. {rationale}'.strip()
return OutputGuardrail(context_guard=guard, on_fail=on_fail, label=f'autoevals {name}')

Moderation uses the OpenAI moderation endpoint and scores 1 when the text is not flagged:

from autoevals import Moderation
from pydantic_ai import Agent
agent = Agent(
'openai:gpt-4o',
capabilities=[autoevals_guardrail(Moderation(), threshold=1.0, on_fail='raise')],
)

Factuality compares the output to a known-good answer, so it suits RAG or FAQ agents where you have reference text:

from autoevals import Factuality
from pydantic_ai import Agent
agent = Agent(
'openai:gpt-4o',
capabilities=[
autoevals_guardrail(
Factuality(model='gpt-4o-mini'),
threshold=0.6,
expected='World War II ended in 1945.',
),
],
)
print(agent.run_sync('What year did World War II end?').output)

With the default on_fail='retry', the scorer’s rationale goes back to the model as feedback.

LLM-based scorers make an extra model call per run. Keep cheap checks (length, regex) ahead of them, and cap total spend with LimitCost. For a built-in judge, see LlmJudge.