Blog Post

Microsoft Developer Community Blog
4 MIN READ

How to Test AI Agents with LangSmith: A Complete Guide

syedarshad's avatar
syedarshad
Icon for Microsoft rankMicrosoft
May 13, 2026

Testing AI agents is crucial for ensuring reliability and accuracy in production.
Evaluation is a technique to evaluate your agents. Different type of evaluation are

#

Evaluation Type

1

Task Success (Pass / Fail)

2

Instruction Adherence

3

Correctness / Accuracy

4

Relevance

5

Groundedness (Hallucination)

6

Coherence / Fluency

7

Tool‑Use Accuracy

8

Safety / Harmfulness

LangSmith provides powerful tools for creating datasets, running evaluations, and using LLM-as-judge techniques. This guide walks through the complete workflow using a practical example.

Prerequistes :

1) create your account under langsmith.

2) generate langsmith key and store in .env file and load whenever a reference made for datacreation or doing evaluation or from command prompt use set LANGCHAIN_API_KEY = <your_api_key_here>

Part 1: Creating Your Test Dataset
The foundation of any good evaluation is a quality dataset. LangSmith allows you to create datasets programmatically with input-output pairs that serve as ground truth.

 

from langsmith import Client

def create_evaluation_dataset():
    client = Client()
    
    # Create a new dataset
    dataset = client.create_dataset(
        dataset_name="Sample dataset",
        description="A sample dataset in LangSmith."
    )
    
    # Define your test examples
    examples = [
        {
            "inputs": {"question": "Which country is Mount Kilimanjaro located in?"},
            "outputs": {"answer": "Mount Kilimanjaro is located in Tanzania."},
        },
        {
            "inputs": {"question": "What is Earth's lowest point?"},
            "outputs": {"answer": "Earth's lowest point is The Dead Sea."},
        },
    ]
    
    # Add examples to the dataset
    client.create_examples(dataset_id=dataset.id, examples=examples)
    print(f"Created dataset: {dataset.name}")
    
    return dataset

 Best Practices for Dataset Creation

  • Diverse Examples: Include edge cases and various question types
  • Clear Ground Truth: Ensure reference answers are accurate and complete
  • Sufficient Volume: Create enough examples to get statistically meaningful results
  • Consistent Format: Maintain consistent input/output structure

 

Part 2: Setting Up LLM-as-Judge Evaluation
LLM-as-judge is a powerful technique where you use a language model to evaluate the quality of another model's responses. This approach scales well and can assess subjective qualities like correctness and hallucinations.

import os
from dotenv import load_dotenv
from langsmith import Client, wrappers
from openai import AzureOpenAI
from openevals.llm import create_llm_as_judge
from openevals.prompts import CORRECTNESS_PROMPT

load_dotenv()

# Wrap your AI client for LangSmith tracing
openai_client = wrappers.wrap_openai(AzureOpenAI(
    azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
    api_key=os.environ["AZURE_OPENAI_API_KEY"],
    api_version="2025-04-01-preview",
))

DEPLOYMENT_NAME = os.environ.get("AZURE_OPENAI_DEPLOYMENT", "gpt-5-mini")

Defining Your Target Function
The target function represents the AI agent you want to test:

def target(inputs: dict) -> dict:
    """The AI agent being evaluated"""
    response = openai_client.chat.completions.create(
        model=DEPLOYMENT_NAME,
        messages=[
            {"role": "system", "content": "Answer the following question accurately"},
            {"role": "user", "content": inputs["question"]},
        ],
    )
    return {"answer": response.choices[0].message.content.strip()}

 

Creating Custom Evaluators
1. Correctness Evaluator

def correctness_evaluator(inputs: dict, outputs: dict, reference_outputs: dict):
    """Evaluates how correct the answer is compared to the reference"""
    evaluator = create_llm_as_judge(
        prompt=CORRECTNESS_PROMPT,  # Pre-built prompt for correctness
        model="azure_openai:" + DEPLOYMENT_NAME,
        feedback_key="correctness",
    )
    return evaluator(
        inputs=inputs,
        outputs=outputs,
        reference_outputs=reference_outputs
    )

2. Hallucination Evaluator

def hallucination_evaluator(inputs: dict, outputs: dict, reference_outputs: dict):
    """Detects if the answer contains unsupported claims"""
    evaluator = create_llm_as_judge(
        prompt="""You are an expert judge evaluating AI responses for hallucinations.

<question>
{inputs}
</question>

<answer>
{outputs}
</answer>

<reference_answer>
{reference_outputs}
</reference_answer>

Does the answer contain any claims or information that are not supported by the question or reference answer? 
Respond with true if the answer is free of hallucinations, false if it contains hallucinated information.
You must also provide a brief explanation of your reasoning.""",
        model="azure_openai:" + DEPLOYMENT_NAME,
        feedback_key="hallucination",
    )
    return evaluator(
        inputs=inputs,
        outputs=outputs,
        reference_outputs=reference_outputs
    )

Part 3: Running the Evaluation
Execute the Complete Evaluation Pipeline

def run_evaluation():
    client = Client()
    
    # Run the evaluation
    experiment_results = client.evaluate(
        target,                    # Function to test
        data="Sample dataset",     # Dataset name
        evaluators=[               # List of evaluators
            correctness_evaluator,
            hallucination_evaluator,
        ],
        experiment_prefix="first-eval-in-langsmith",
        max_concurrency=2,         # Control API rate limits
    )
    
    print("Evaluation Results:")
    print(experiment_results)
    
    return experiment_results

if __name__ == "__main__":
    run_evaluation()

Understanding Your Results
When the evaluation completes, you'll get detailed metrics including:

  • Individual Scores: Per-example results for each evaluator
  • Aggregate Metrics: Overall performance across the dataset
  • Trace Links: Deep links to view exact model interactions
  • Comparison Views: Side-by-side comparisons of outputs vs. references

Key Benefits of This Approach

  • Automated Testing: Run comprehensive evaluations without manual review
  • Scalable Assessment: Evaluate subjective qualities at scale
  • Continuous Monitoring: Track performance changes over time
  • Rich Analytics: Get detailed insights into failure modes
Updated May 13, 2026
Version 2.0
No CommentsBe the first to comment