Skip to main content

The Problem

You have deployed a medical chatbot that answers patient questions using retrieved context from a knowledge base. During QA, you notice the bot sometimes makes up dosages or contradicts the source material. You need automated checks to catch this before the response reaches the patient. This cookbook shows how to build a local validation layer using the evaluate() function. Everything runs on your machine — no API keys, no network calls, sub-second latency.

What You Will Learn

  • How to check whether a response is faithful to source context
  • How to detect contradictions between output and reference material
  • How to verify specific claims (dosage numbers, drug names) are present
  • How to batch multiple checks into a single call
  • How to wrap everything into a reusable production validation function

Prerequisites

No API keys required. All metrics in this cookbook run locally.

Set Up the Knowledge Base

First, define the medical knowledge your chatbot draws from, and a function that simulates chatbot responses — some correct, some dangerously wrong.

Scenario 1: Validate a Correct Response

Start with a response that matches the source material. The evaluate() function accepts a metric name as the first argument, along with the text fields it needs.
Expected output:
You can pass a list of metric names to evaluate() to run them all at once. The result object lets you iterate over individual results or check the overall success_rate.

Scenario 2: Catch a Dangerous Hallucination

Now test a response that directly contradicts the source material. The context says “Do NOT combine with aspirin,” but the chatbot says the opposite.
Expected output:
The faithfulness score drops sharply because the response claims the opposite of what the context states. The contradiction detector confirms it.

Scenario 3: Catch a Wrong Dosage

The chatbot recommends 5000mg of metformin instead of the correct 500mg. You can combine faithfulness checking with the contains metric to flag specific incorrect values.

Scenario 4: Validate a Function Call

If your chatbot can call tools, you can verify it selects the right function with the correct arguments.

Scenario 5: Production Validation Pipeline

Wrap all checks into a single reusable function. In production, call this before every chatbot response is sent to the user.
Test the pipeline against multiple cases:
Expected output:
The correct response passes. Both hallucinated responses are blocked before reaching the patient.

What to Try Next

This cookbook uses fast local heuristics. For cases where paraphrasing fools the heuristic (e.g., “twice daily” vs “2x per day”), add an LLM judge for higher accuracy.

Next: LLM-as-Judge

Use augment=True to combine local speed with LLM intelligence for production-grade accuracy.