AI Hints
Home›LangChain Tutorial›Evaluation
LangChain · Lesson 88 of 120

Evaluating Answers

LLM as a judge.

⏱ 2 min read▶ Video at 1:39:51🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

How do you know your bot's answers are right? Reading them all yourself doesn't scale. And exact text matching fails, because there are many ways to say the same thing. A common trick is to ask a model to be the judge.

Evaluating Answers
From the video: Evaluating Answers
  • Are answers right?
  • Reading doesn't scale
  • A model as the judge

A judge with structured output

The judge returns a grade, with two fields. Correct, true or false, and a short reason. With structured output makes the model fill in exactly those fields. We give it a reference answer, and two candidate answers, one right and one wrong. Run it. The first is marked correct, and the second incorrect, each with a reason.

judge.pypython
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model

class Grade(BaseModel):
    correct: bool = Field(description="Does the answer agree with the reference?")
    reason: str = Field(description="One short sentence.")

judge = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0).with_structured_output(Grade)
reference = "Express delivery costs £5.99."

for answer in ["Express shipping is £5.99.", "Express shipping is £9.99."]:
    grade = judge.invoke(f"Reference: {reference}\nAnswer: {answer}\nGrade the answer.")
    print(f"{answer:<28} correct={grade.correct}  ({grade.reason})")
Output
Express shipping is £5.99.   correct=True  (The answer accurately conveys the same cost
for express delivery as the reference.)
Express shipping is £9.99.   correct=False  (The answer states a different cost for
express shipping than the reference.)

Judging well

Give the judge a reference answer whenever you can. It's far more reliable than asking, is this good? Ask for a simple verdict, like true or false, plus a reason. Use temperature zero. And check some of its grades yourself, because judges make mistakes too.

keyvalue
Referencemakes judging reliable
Simple verdicttrue / false
Reasonexplains the grade
Spot-checkjudges err too

Summary

An LLM judge compares answers with a reference, and returns a structured verdict. Next, running the same set of test questions every time.

Key takeaways
  • with_structured_output
  • Reference answers
  • Verdict + reason
Next up: Test Sets — the same questions every time