Okay, let's break down how to run LLM evaluations using LangSmith. The core idea is to test your LLM application (whether it's a simple LLM call, a chain, or an agent) against a predefined set of inputs (a dataset) and score the outputs using various criteria (evaluators).
API Key: Generate an API key from your LangSmith account settings.
LangSmith & LangChain SDKs: Install or update the necessary Python libraries:
bash
pip install -U langsmith langchain langchain_openai # Or other model provider
Environment Variables: Set up your LangSmith API key and other necessary keys (like OpenAI API key) as environment variables. This is the recommended way to handle keys securely.
bash
export LANGSMITH_API_KEY="YOUR_LANGSMITH_API_KEY"
export LANGSMITH_TRACING_V2="true" # Enables LangSmith tracing
export LANGSMITH_PROJECT="Your-Project-Name" # Optional: Default project for runs
export OPENAI_API_KEY="YOUR_OPENAI_API_KEY" # Or your specific LLM provider key
Setting LANGSMITH_TRACING_V2="true" automatically configures LangChain to log runs to LangSmith.
2. Core Workflow:
The general process involves these steps:
Define/Upload a Dataset: Create a collection of test cases (inputs and optional reference outputs).
Define Your System Under Test (SUT): This is the LangChain Runnable (LLM, Chain, Agent) you want to evaluate.
Choose/Define Evaluators: Select or create the metrics/criteria you want to use to score the outputs.
Run the Evaluation: Use the LangSmith client to run your SUT over the dataset using the chosen evaluators.
Analyze Results: Review the scores and traces in the LangSmith UI.
3. Step-by-Step Implementation:
Step 3.1: Prepare Your Dataset
A dataset in LangSmith consists of examples, each typically having inputs (a dictionary) and optional outputs (a dictionary, often used for reference answers).
Option A: Create via UI:
Go to your LangSmith project.
Navigate to the "Datasets & Testing" tab.
Click "New Dataset".
You can upload a CSV file (with columns matching your input/output keys) or add examples manually. Ensure your input/output keys are consistent. Common input keys are input, question, etc. Common output keys are output, answer, reference.
Option B: Create via SDK:
python
from langsmith import Client
client = Client() # Assumes API key is set via environment variable
dataset_name = "My Simple QA Dataset"
dataset_description = "A dataset with simple questions and reference answers."
# Check if dataset exists, create if not
try:
dataset = client.read_dataset(dataset_name=dataset_name)
print(f"Dataset '{dataset_name}' already exists.")
except Exception: # More specific exceptions can be caught if needed
dataset = client.create_dataset(dataset_name=dataset_name, description=dataset_description)
print(f"Dataset '{dataset_name}' created.")
# Add examples
client.create_examples(
inputs=[
{"question": "What is the capital of France?"},
{"question": "What is 2 + 2?"},
{"question": "Who wrote 'Hamlet'?"}
],
outputs=[
{"answer": "Paris"},
{"answer": "4"},
{"answer": "William Shakespeare"}
],
dataset_id=dataset.id,
)
print("Examples added to the dataset.")
Step 3.2: Define Your System Under Test (SUT)
This is typically a LangChain Runnable object.
python
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
# Example 1: Simple LLM call
# llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
# Example 2: A simple chain
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("user", "{question}")
])
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
chain = prompt | llm | StrOutputParser()
# This 'chain' object is our System Under Test (SUT)
# It needs to accept the input keys defined in your dataset (e.g., 'question')
Step 3.3: Choose/Define Evaluators
LangSmith offers various built-in and custom evaluation methods.
Built-in String/Criteria Evaluators: Check for correctness, helpfulness, relevance, etc., often using an LLM-as-judge approach.
Exact Match: Check if the output exactly matches the reference output.
Regex Match: Check if the output matches a regular expression.
Embedding Distance: Measure semantic similarity between the output and reference output.
Custom Evaluators: Define your own Python functions for scoring.
python
from langsmith.evaluation import evaluate, LangChainStringEvaluator, EvaluationResult, run_evaluator
# Example Evaluators:
# 1. Using built-in criteria (LLM-as-judge)
eval_config_criteria = {
"criteria": {
"correctness": """
Score 1: The answer is completely incorrect or irrelevant.
Score 3: The answer is partially correct but contains significant errors or omissions.
Score 5: The answer is mostly correct but may have minor inaccuracies.
Score 7: The answer is correct and accurate.
Score 10: The answer is correct, accurate, and comprehensive.
Is the submitted answer correct, accurate, and factual based on the reference answer?
"""
}
# You can add more criteria like "helpfulness", "conciseness", etc.
}
# 2. Using specific built-in evaluators (needs reference output in dataset)
qa_evaluator = LangChainStringEvaluator("qa") # Checks correctness against reference answer
# embedding_evaluator = LangChainStringEvaluator("embedding_distance") # Needs reference
# 3. Custom Evaluator Function (Example: Check length)
def check_output_length(run, example) -> EvaluationResult:
"""Checks if the output length is within a certain range."""
output = run.outputs.get('output') if run.outputs else None
if output is None:
return EvaluationResult(key="output_length_check", score=0, comment="No output found")
length = len(output)
score = 1 if 10 < length < 500 else 0
comment = f"Output length: {length}. Score: {score} (1 if 10 < len < 500, else 0)"
return EvaluationResult(key="output_length_check", score=score, comment=comment)
# Choose the evaluators you want to run
evaluators = [
qa_evaluator, # Requires 'answer' or 'output' key in dataset outputs
check_output_length, # Custom function
# You can also pass the criteria config directly, but often it's combined with evaluate function arguments
]
Note: The way evaluators are specified can vary slightly depending on whether you use the high-level evaluate function or lower-level methods.
Step 3.4: Run the Evaluation
Use the evaluate function (recommended high-level approach) or client.run_on_dataset.
python
from langsmith.evaluation import evaluate
from langsmith import Client
client = Client() # Ensure client is initialized
# Define a factory function for your SUT if it has state or needs configuration per run
# For simple chains/LLMs like above, you can often pass the object directly.
# If your chain requires complex setup, a factory is better.
def chain_factory():
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("user", "{question}")
])
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.1) # Maybe test a different temp
return prompt | llm | StrOutputParser()
# Run the evaluation
# Using evaluate (recommended)
results = evaluate(
chain_factory, # Your SUT or a factory function returning it
data=dataset_name, # Name or ID of your LangSmith dataset
evaluators=evaluators, # List of evaluator functions or configs
evaluation_config=eval_config_criteria, # Pass criteria config here
experiment_prefix="Simple QA Eval - GPT3.5", # A name for this test run
metadata={ # Optional metadata for the experiment
"model": "gpt-3.5-turbo",
"temperature": 0.1,
"revision_id": "v1.1-alpha",
},
# concurrency_level=5, # Control parallel runs
# client=client # Pass client explicitly if needed
)
# OR Using client.run_on_dataset (lower level)
# test_run = client.run_on_dataset(
# dataset_name=dataset_name,
# llm_or_chain_factory=chain_factory,
# evaluation=evaluation_config, # Slightly different structure needed here sometimes
# project_name="Simple QA Eval - GPT3.5 - run_on_dataset",
# concurrency_level=5,
# )
# print(test_run)
Find Your Project: Select the project you specified (or the default one).
Go to "Datasets & Testing": Click this tab.
View Experiments: You'll see your evaluation run listed under the dataset, prefixed with the experiment_prefix you provided (e.g., "Simple QA Eval - GPT3.5").
Inspect Results: Click on the experiment run name. You'll see:
Overall Metrics: Average scores for each evaluator across the dataset.
Per-Example Results: A table showing each input, the generated output, reference output (if any), and the scores from each evaluator for that specific example.
Traces: Links to the full LangSmith trace for each example run, allowing you to debug exactly what happened within your chain/LLM call.
Comparison: If you run multiple experiments (e.g., with different models or prompts) on the same dataset, LangSmith provides excellent comparison views.
Key Considerations & Best Practices:
Dataset Quality: Your evaluation is only as good as your dataset. Ensure it covers diverse scenarios, edge cases, and is representative of real-world usage.
Reference Outputs: While not always required (e.g., for criteria-based evals like helpfulness), reference outputs are crucial for metrics like exact match, QA correctness, and embedding similarity.
Evaluator Choice: Select evaluators that measure what you actually care about (accuracy, tone, safety, conciseness, etc.). Combine different types for a holistic view.
LLM-as-Judge Nuances: Be aware that using an LLM to judge can be inconsistent, biased by the judge model, and sensitive to prompt wording in the criteria. Calibrate and review its judgments.
Iteration: Evaluation is not a one-off task. Run evaluations regularly as you modify prompts, models, or chain logic to track regressions or improvements.
Experiment Tracking: Use meaningful experiment_prefix and metadata to easily identify and compare different evaluation runs in the LangSmith UI.
Cost: Be mindful that evaluations, especially those using LLM-as-judge, consume LLM tokens and incur costs.
By following these steps, you can leverage LangSmith to systematically evaluate and improve your LLM applications. Remember to consult the official LangSmith documentation for the most up-to-date details and advanced features.