Evaluations

Score model outputs for toxicity, hallucination, and bias using an LLM as judge. Results feed the evaluation counters on LLM Analytics.

import trail

detector = trail.evals.ToxicityDetector(api_key="sk-...")
result = detector.measure(text="…model output…")

Evaluators need the OpenAI or Anthropic SDK: pip install "trailai[evals]" (since trailai 1.7.0; earlier releases installed both unconditionally).

The four detectors

Class Detects
trail.evals.ToxicityDetector Harmful, abusive, or offensive content
trail.evals.Hallucination Claims unsupported by the provided context
trail.evals.BiasDetector Prejudiced or unfair treatment of groups
trail.evals.All All three in a single judge call

All four share the same constructor and measure() signature.


Constructor

Detector(
    provider="openai",         # "openai" or "anthropic"
    api_key=None,              # falls back to OPENAI_API_KEY / ANTHROPIC_API_KEY
    model=None,                # judge model
    base_url=None,             # for proxies or self-hosted endpoints
    custom_categories=None,    # extra categories to detect
    collect_metrics=False,     # emit OTel metrics for each evaluation
    threshold_score=0.5,       # score above which verdict becomes "yes"
)
Argument Notes
provider Only openai and anthropic are supported. Anything else raises ValueError
api_key If given, it's written into the provider's env var. Otherwise read from OPENAI_API_KEY / ANTHROPIC_API_KEY. Missing entirely → ValueError
model Pick a fast, cheap model — judging is classification, not generation
base_url Point at a proxy, gateway, or compatible self-hosted endpoint
custom_categories {"category_name": "description"} — extend the judge's taxonomy
collect_metrics True emits an OTel counter per evaluation, so results show up in analytics
threshold_score Score above this makes the verdict "yes"

measure()

detector.measure(
    prompt="",       # what the user asked
    contexts=[],     # reference context — essential for hallucination
    text=None,       # the model output being judged
) -> JsonOutput

Returns:

JsonOutput(
    verdict="yes",                       # "yes" = the issue was detected
    evaluation="Toxicity",               # which evaluation ran
    score=0.85,                          # 0.0–1.0
    classification="harmful_language",   # sub-category
    explanation="…",                     # why
)

As with guardrails, verdict: "yes" means the problem was found.

Access fields as attributes (it's a Pydantic model): result.score, result.verdict.


Toxicity

import trail

detector = trail.evals.ToxicityDetector(
    provider="openai",
    model="gpt-4o-mini",
    threshold_score=0.6,
    collect_metrics=True,
)

result = detector.measure(
    prompt="What do you think of my competitor?",
    text=model_output,
)

if result.verdict == "yes":
    logger.warning("Toxic output (%.2f): %s", result.score, result.explanation)

Use it as a safety net on generated output, especially anything user-facing or published.


Hallucination

detector = trail.evals.Hallucination(provider="openai", model="gpt-4o-mini")

result = detector.measure(
    prompt="What is our refund window?",
    contexts=[
        "Refunds are available within 30 days of purchase.",
        "Digital goods are non-refundable.",
    ],
    text=model_output,
)

if result.verdict == "yes":
    logger.warning("Unsupported claim: %s", result.explanation)

contexts is essential here. Hallucination detection asks "is this claim supported by the given context?" — with no context, the judge has nothing to check against and the result is meaningless.

This is the highest-value evaluation for RAG systems. Pass exactly the retrieved passages you gave the model, and you get a direct measure of whether it stayed grounded.


Bias

detector = trail.evals.BiasDetector(provider="openai", model="gpt-4o-mini")

result = detector.measure(
    prompt="Describe a good software engineer.",
    text=model_output,
)

Most valuable where outputs influence decisions about people — hiring, lending, admissions, content moderation.


All three at once

detector = trail.evals.All(provider="openai", model="gpt-4o-mini", collect_metrics=True)

result = detector.measure(
    prompt=user_question,
    contexts=retrieved_docs,
    text=model_output,
)

One judge call instead of three — roughly a third of the cost and latency. Use it when you want broad coverage; use individual detectors when you want a specific score you can threshold independently.


Custom categories

Extend the judge's taxonomy with domain-specific concerns:

detector = trail.evals.ToxicityDetector(
    provider="openai",
    custom_categories={
        "medical_advice": "Providing specific medical diagnoses or treatment recommendations",
        "financial_advice": "Recommending specific investments or financial products",
    },
)

Write descriptions the way you'd brief a careful human reviewer — specific and testable. Vague descriptions produce vague, inconsistent judgements.


collect_metrics and the dashboard

detector = trail.evals.ToxicityDetector(..., collect_metrics=True)

With this on, each evaluation emits an OTel counter carrying the verdict, score, evaluation type, classification, and explanation. Those counters populate:

  • Total hallucination detected
  • Total bias detected
  • Total toxicity detected

on LLM Analytics. Leave it off and those cards stay at zero — which is the answer to "why are my evaluation counters empty?"


Cost and latency

Every measure() call is an LLM call. Evaluating every production response roughly doubles your model spend and adds meaningful latency.

Sensible strategies:

Strategy Approach
Sample Evaluate 1–5% of production traffic. Enough to detect regressions, cheap enough to run always
Offline Evaluate asynchronously after responding, so the user waits for nothing
Pre-release Evaluate a fixed test set before shipping a prompt or model change
Targeted Evaluate only high-risk paths — regulated topics, public-facing output

Sampled evaluation:

import random

SAMPLE_RATE = 0.02

def maybe_evaluate(prompt, contexts, output):
    if random.random() < SAMPLE_RATE:
        detector.measure(prompt=prompt, contexts=contexts, text=output)

Asynchronous evaluation:

import threading

def evaluate_async(prompt, contexts, output):
    threading.Thread(
        target=lambda: detector.measure(prompt=prompt, contexts=contexts, text=output),
        daemon=True,
    ).start()

Choose a small judge model. gpt-4o-mini or an equivalent handles classification well; a frontier model triples the cost for marginal gain.


Evaluations vs. guardrails

They look similar and serve different purposes:

Guardrails Evaluations
When Inline, before content moves on After the fact, usually sampled
Purpose Block bad content Measure output quality
Configured In the dashboard In code
Blocking Yes — that's the point No
Cost Per guarded request Per evaluated response
Judge The model registered in TrailAI A provider you configure here

Use both. Guardrails stop harmful content reaching users; evaluations tell you whether your system is getting better or worse over time.


Datasets

Datasets are collections of input / expected-output pairs for evaluation and benchmarking (trailai 1.7.0+). input, expected_output and metadata can be strings or any JSON-serializable value.

import trail

trail.init(application_name="evals")

trail.dataset.create_dataset("capitals", description="Country -> capital")
trail.dataset.create_dataset_item("capitals", input={"country": "France"}, expected_output="Paris")
trail.dataset.create_dataset_item("capitals", input={"country": "Japan"}, expected_output="Tokyo")

ds = trail.dataset.get_dataset("capitals")      # None if it doesn't exist
for item in ds.items:
    print(item.id, item.input, item.expected_output)

create_dataset() / create_dataset_item() return False (and log why) instead of raising, e.g. when a dataset name already exists.

Experiments

An experiment runs a task over every item, scores each output and records one trace per item (experiment-item-run), with the task's own LLM calls nested underneath.

def ask(*, item):                                   # sync or async
    return llm(f"Capital of {item.input['country']}? One word.")

def exact(*, output, expected_output, **_):
    return trail.Evaluation(name="exact", value=float(output.strip() == expected_output))

def accuracy(*, item_results, **_):                  # optional run-level score
    scores = [e.value for r in item_results for e in r.evaluations if e.name == "exact"]
    return trail.Evaluation(name="accuracy", value=sum(scores) / len(scores))

result = ds.run_experiment(
    name="capitals",
    task=ask,
    evaluators=[exact],
    run_evaluators=[accuracy],
    max_concurrency=10,
)
print(result.format(include_item_results=True))
  • Evaluators get input, output, expected_output and metadata as keyword arguments and return an Evaluation, a dict ({"name": ..., "value": ...}) or a list of them.
  • Scores are recorded on each item's span as trail.experiment.score.<name>; spans also carry trail.experiment.name, trail.experiment.run_name and trail.dataset.item.id.
  • Items whose task raises are logged and left out of result.item_results (their span is marked ERROR); a failing evaluator never drops the item.
  • trail.run_experiment(name=..., data=[{"input": ..., "expected_output": ...}], task=...) runs the same flow over local data without a stored dataset.
  • Works in scripts, notebooks and inside a running event loop.

Complete example

import logging, random, threading
import trail

logger = logging.getLogger(__name__)

evaluator = trail.evals.All(
    provider="openai",
    model="gpt-4o-mini",
    threshold_score=0.6,
    collect_metrics=True,
)

SAMPLE_RATE = 0.05

def evaluate_response(prompt: str, contexts: list, output: str):
    if random.random() >= SAMPLE_RATE:
        return

    def run():
        try:
            result = evaluator.measure(prompt=prompt, contexts=contexts, text=output)
            if result.verdict == "yes":
                logger.warning(
                    "Evaluation flagged %s (%.2f): %s",
                    result.evaluation, result.score, result.explanation,
                )
        except Exception:
            logger.exception("Evaluation failed")   # never break the request path

    threading.Thread(target=run, daemon=True).start()

@trail.trace(role="agent")
def answer(question: str) -> str:
    contexts = retrieve(question)
    output = generate(question, contexts)
    evaluate_response(question, contexts, output)
    return output

Related