Bird
Raised Fist0
LangChainframework~10 mins

Custom evaluation metrics in LangChain - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Custom evaluation metrics
Define metric function
Integrate metric into evaluation
Run evaluation with metric
Collect metric results
Analyze and use results
This flow shows how to create a custom metric, add it to LangChain evaluation, run it, and get results.
Execution Sample
LangChain
def custom_metric(prediction, reference):
    return 1 if prediction == reference else 0

from langchain.evaluation import Evaluation

result = Evaluation.evaluate(
    predictions=["yes", "no"],
    references=["yes", "yes"],
    metrics=[custom_metric]
)
Defines a simple metric that checks exact match, then runs evaluation with predictions and references.
Execution Table
StepActionInputMetric ResultNotes
1Call custom_metricprediction='yes', reference='yes'1Exact match returns 1
2Call custom_metricprediction='no', reference='yes'0Mismatch returns 0
3Aggregate results[1, 0]Average=0.5Average metric score computed
4Return evaluation resultmetrics=[custom_metric]0.5Final evaluation output
5End--Evaluation complete
💡 All predictions processed; evaluation returns average metric score
Variable Tracker
VariableStartAfter 1After 2Final
prediction-'yes''no'-
reference-'yes''yes'-
metric_result-10[1, 0]
final_score---0.5
Key Moments - 2 Insights
Why does the metric return 1 or 0 instead of a percentage?
The metric function returns 1 for exact match and 0 otherwise, so results are binary per item. The average is computed later as the overall score (see execution_table rows 1-3).
How does LangChain use the custom metric function?
LangChain calls the custom metric on each prediction-reference pair, collects results, then aggregates them (execution_table rows 1-3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the metric result when prediction='no' and reference='yes'?
A1
B0
C0.5
DUndefined
💡 Hint
Check step 2 in the execution_table where prediction='no' and reference='yes'
At which step does the evaluation compute the average metric score?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for 'Aggregate results' in the execution_table
If the predictions were all correct, what would the final_score be?
A1
B0.5
C0
DCannot tell
💡 Hint
Check variable_tracker final_score when all metric_results are 1
Concept Snapshot
Custom evaluation metrics in LangChain:
- Define a function taking prediction and reference
- Return a numeric score (e.g., 1 for match, 0 for no)
- Pass function in metrics list to Evaluation.evaluate
- LangChain runs metric on each pair and aggregates
- Use results to understand model performance
Full Transcript
This visual execution shows how to create and use custom evaluation metrics in LangChain. First, you define a metric function that compares a prediction to a reference and returns a score. Then, you pass this function to LangChain's Evaluation.evaluate method along with lists of predictions and references. LangChain calls your metric on each pair, collects the results, and computes an average score. The execution table traces each call and the aggregation step. The variable tracker shows how values change during evaluation. Key moments clarify why the metric returns 1 or 0 and how LangChain uses it. The quiz tests understanding of metric results and aggregation. This helps beginners see step-by-step how custom metrics work in LangChain evaluation.

Practice

(1/5)
1. What is the main purpose of creating a custom evaluation metric in Langchain?
easy
A. To speed up the AI model training process
B. To measure AI results in a way that fits your specific needs
C. To automatically fix errors in AI outputs
D. To replace the AI model with a simpler one

Solution

  1. Step 1: Understand the role of evaluation metrics

    Evaluation metrics measure how well an AI model performs its task.
  2. Step 2: Identify why custom metrics are used

    Custom metrics let you measure results in ways that standard metrics might not cover, fitting your unique needs.
  3. Final Answer:

    To measure AI results in a way that fits your specific needs -> Option B
  4. Quick Check:

    Custom metrics = tailored measurement [OK]
Hint: Custom metrics tailor scoring to your AI task [OK]
Common Mistakes:
  • Thinking custom metrics speed training
  • Believing they fix AI errors automatically
  • Confusing metrics with model replacement
2. Which of the following is the correct way to start defining a custom evaluation metric class in Langchain?
easy
A. class MyMetric(Evaluation):
B. def MyMetric():
C. class MyMetric():
D. function MyMetric extends Evaluation {}

Solution

  1. Step 1: Recall Langchain class inheritance syntax

    Custom metrics inherit from the Evaluation base class using Python class syntax.
  2. Step 2: Identify correct class definition

    class MyMetric(Evaluation): correctly defines a class inheriting from Evaluation, matching Langchain patterns.
  3. Final Answer:

    class MyMetric(Evaluation): -> Option A
  4. Quick Check:

    Class inherits Evaluation = correct syntax [OK]
Hint: Use class inheritance with Evaluation base [OK]
Common Mistakes:
  • Defining a function instead of a class
  • Missing inheritance from Evaluation
  • Using JavaScript syntax in Python
3. Given this custom metric class, what will metric.evaluate(['hello'], ['hello']) return?
class ExactMatch(Evaluation):
    def evaluate(self, predictions, references):
        return sum(p == r for p, r in zip(predictions, references)) / len(references)
medium
A. 1.0
B. 0.0
C. Error due to missing method
D. None

Solution

  1. Step 1: Understand the evaluate method logic

    It compares each prediction to the reference and counts matches, then divides by total references.
  2. Step 2: Apply inputs to the method

    With predictions=['hello'] and references=['hello'], the single pair matches, so sum is 1 and length is 1, result is 1/1 = 1.0.
  3. Final Answer:

    1.0 -> Option A
  4. Quick Check:

    Exact match count / total = 1.0 [OK]
Hint: Check if predictions equal references, then divide [OK]
Common Mistakes:
  • Forgetting to divide by length
  • Confusing sum with boolean values
  • Expecting method to return a list
4. What is wrong with this custom metric class that causes an error?
class LengthDiff(Evaluation):
    def evaluate(self, predictions, references):
        return abs(len(predictions) - len(references)) / len(references)
medium
A. It returns a number instead of a score between 0 and 1
B. It does not implement the evaluate method
C. It uses abs() incorrectly causing a syntax error
D. It does not handle empty lists causing runtime error

Solution

  1. Step 1: Analyze the evaluate method with empty references

    If references=[], len(references)=0 causes ZeroDivisionError in the division.
  2. Step 2: Identify the runtime error cause

    The code divides by len(references) without checking if references is empty, causing runtime error.
  3. Final Answer:

    It does not handle empty lists causing runtime error -> Option D
  4. Quick Check:

    len(references)==0 -> ZeroDivisionError [OK]
Hint: Check how method handles empty input lists [OK]
Common Mistakes:
  • Assuming abs() causes syntax error
  • Thinking evaluate method is missing
  • Ignoring empty list edge cases
5. You want to create a custom metric that scores AI answers higher if they contain more keywords from a reference list. Which approach fits best?
hard
A. Calculate the difference in length between prediction and reference
B. Check if prediction exactly matches the reference string
C. Count how many keywords appear in the prediction, divide by total keywords
D. Return a fixed score regardless of prediction content

Solution

  1. Step 1: Understand the goal of keyword-based scoring

    The metric should reward predictions containing more keywords from the reference list.
  2. Step 2: Identify the approach that measures keyword presence proportionally

    Counting keywords in prediction and dividing by total keywords gives a score reflecting keyword coverage.
  3. Final Answer:

    Count how many keywords appear in the prediction, divide by total keywords -> Option C
  4. Quick Check:

    Keyword coverage scoring = Count how many keywords appear in the prediction, divide by total keywords [OK]
Hint: Score by keyword matches divided by total keywords [OK]
Common Mistakes:
  • Using exact match instead of keyword count
  • Measuring length difference unrelated to keywords
  • Returning fixed scores ignoring content