How to Build an Agentic Evaluation Pipeline
Step-by-step technical tutorial on building and maintaining a solid agentic evaluation pipeline using Python and modern LLM harnesses.

Evaluating autonomous agents is nothing like running standard unit tests against deterministic code. When your system relies on multi-step reasoning loops and tool calls, traditional assertion-based testing breaks down completely. I spent the last three weeks building a production evaluation suite for a customer support agent using LangGraph and GPT-5.6 Sol, and my initial test runner failed silently on fifty percent of edge cases because I treated agent outputs like static string matches. If you want to ship reliable autonomous workflows without waking up to hallucinated database deletions, you need a programmatic evaluation pipeline that scores behavior, tool selection, and semantic correctness.
Agent Evaluation Architecture and Core Components
Before writing any code, you need to understand the structural divide between traditional software testing and agentic evaluation. An agentic evaluation pipeline consists of three primary layers: the execution tap, the trajectory recorder, and the LLM-as-a-judge scoring engine. When your agent executes a task, it generates a full execution trace containing user inputs, intermediate thought steps, raw tool outputs, and final responses. Our goal is to inspect this trajectory rather than just the final answer.
The system we are building takes a dataset of golden test cases, feeds them into your agent implementation, captures the full execution graph, and runs parallel judge prompts to grade faithfulness, tool selection accuracy, and step efficiency. You can expect a complete run over 100 test cases to take roughly four minutes and cost about twelve cents in API tokens when using a fast evaluation model.
Environment Setup and Required Dependencies
To follow along with this tutorial, ensure your local development environment meets these specific requirements. We will use Python 3.12 running inside a virtual environment on an Apple Silicon or Linux host with at least 16GB of RAM.
- Python Version: 3.12.3 or higher
- Package Manager: pip 24.0+
- Core Libraries: langgraph==0.2.50, pydantic==2.8.2, pytest==8.2.0, openai==1.35.0
- API Keys Required:
OPENAI_API_KEYfor GPT-5.6 Sol judge calls
Initialize your workspace and install the required dependencies by executing the following commands in your terminal:
python3 -m venv venv
source venv/bin/activate
pip install langgraph pydantic pytest openai httpx
Implementing the Agent Execution Put to work
We need a standardized way to invoke our agent and serialize its execution trajectory into a structured JSON format. Below is the implementation of our test runner tap. This script executes a target agent against a specific prompt and captures every state transition into a trace object.
import json
import time
from typing import List, Dict, Any
from pydantic import BaseModel, Field
class ExecutionTrace(BaseModel):
test_id: str
input_prompt: str
steps: List[Dict[str, Any]] = Field(default_factory=list)
final_output: str
execution_time_seconds: float
token_count: int
class AgentHarness:
def __init__(self, agent_callable):
self.agent = agent_callable
def run_test(self, test_id: str, prompt: str) -> ExecutionTrace:
start_time = time.time()
trace_steps = []
try:
# Simulate agent execution capturing intermediate steps
result = self.agent(prompt, callback=lambda step: trace_steps.append(step))
final_output = result.get('output', '')
tokens = result.get('tokens_used', 0)
except Exception as e:
final_output = f'ERROR: {str(e)}'
tokens = 0
elapsed = time.time() - start_time
return ExecutionTrace(
test_id=test_id,
input_prompt=prompt,
steps=trace_steps,
final_output=final_output,
execution_time_seconds=round(elapsed, 2),
token_count=tokens
)
This tap abstracts the underlying agent framework, whether you are using CrewAI, LangGraph, or custom agent loops. The callback parameter captures tool calls and intermediate thoughts in real time without modifying your core agent logic.
Writing the LLM Judge Evaluation Scorers
Deterministic assertions fail when evaluating open-ended text generation. We must deploy an LLM-as-a-judge pattern to evaluate semantic correctness. We will construct a strict Pydantic-backed judge that returns binary pass/fail scores alongside reasoning strings.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))
class JudgeVerdict(BaseModel):
passed: bool
reasoning: str
confidence_score: float
class LLMJudge:
def __init__(self, model_name: str = 'gpt-5.6-sol'):
self.model = model_name
TOLERANCE_PROMPT = """You are an objective AI evaluation judge.
Evaluate if the agent output correctly satisfies the user prompt based on the provided execution trace.
User Prompt: {prompt}
Agent Output: {output}
Execution Steps: {steps}
Return a strict JSON object with fields: passed (boolean), reasoning (string), confidence_score (float 0-1)."""
def evaluate(self, prompt: str, output: str, steps: List[Dict[str, Any]]) -> JudgeVerdict:
formatted_prompt = self.TOLERANCE_PROMPT.format(
prompt=prompt,
output=output,
steps=json.dumps(steps)
)
response = client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": formatted_prompt}],
response_format={"type": "json_object"}
}
content = response.choices[0].message.content
data = json.loads(content)
return JudgeVerdict(
passed=data.get('passed', False),
reasoning=data.get('reasoning', 'No reasoning provided.'),
confidence_score=float(data.get('confidence_score', 0.0))
)
Always pin your judge model to a specific version. Using floating alias tags like gpt-5 in evaluation pipelines will introduce silent regression failures when providers update underlying weights.
Executing the End-to-End Evaluation Suite
Now we combine our use and judge into a functional test suite using pytest. This script loads a JSON dataset of golden test cases, executes the agent, evaluates each trajectory, and fails the CI build if the aggregate pass rate drops below ninety percent.
import pytest
# Sample test dataset
TEST_DATASET = [
{
"id": "test_01",
"prompt": "Retrieve user account balance for ID 4821 and format as USD.",
"expected_tool": "get_account_balance"
},
{
"id": "test_02",
"prompt": "Reset password for [email protected] and trigger security email.",
"expected_tool": "reset_user_password"
}
]
def mock_agent_runner(prompt, callback):
# Mock implementation of agent execution for demonstration
if "balance" in prompt:
callback({"tool": "get_account_balance", "args": {"id": "4821"}})
return {"output": "The account balance for ID 4821 is $1,450.00.", "tokens_used": 320}
else:
callback({"tool": "reset_user_password", "args": {"email": "[email protected]"}})
return {"output": "Password reset link sent successfully.", "tokens_used": 410}
@pytest.mark.parametrize("test_case", TEST_DATASET)
def test_agent_behavior(test_case):
harness = AgentHarness(mock_agent_runner)
judge = LLMJudge()
trace = harness.run_test(test_case["id"], test_case["prompt"])
verdict = judge.evaluate(test_case["prompt"], trace.final_output, trace.steps)
assert verdict.passed is True, f"Test {test_case['id']} failed. Reasoning: {verdict.reasoning}"
assert verdict.confidence_score >= 0.85, f"Low confidence score: {verdict.confidence_score}"
Run your test suite directly from the command line with verbose output enabled:
pytest -v test_evaluation.py
How to Fix Common Agent Evaluation Errors?
Building evaluation pipelines exposes hidden brittleness in agent state management. Here are three common errors you will encounter and how to resolve them immediately.
Error 1: JSONDecodeError during LLM Judge Parsing
When the judge model outputs conversational markdown blocks around its JSON payload, your evaluation script crashes with a parsing error. Fix this by enforcing structured outputs via API parameters or adding a fallback cleaning regex in your judge class:
cleaned_content = content.replace("```json", "").replace("```", "").strip()
data = json.loads(cleaned_content)
Error 2: Rate Limit Exhaustion (HTTP 429)
Running fifty concurrent agent evaluations will trigger provider rate limits instantly. Implement exponential backoff inside your judge invocation loop using the tenacity library or custom retry decorators with jitter.
Error 3: Flaky Judge Verdicts
If your judge score fluctuates across identical runs, lower the temperature parameter to 0.0 on your judge completion call. Never run evaluation judges with high temperatures.
Production Considerations and Security Hardening
Running agent evaluations inside a CI/CD pipeline introduces security vectors. Agents execute arbitrary tools that may interact with live databases or external APIs. You must mock all external side effects during evaluation runs. Never point an evaluation use at a production database without strict database transaction rollbacks.
Manage your evaluation credentials securely using environment secret stores such as GitHub Actions Secrets or AWS Secrets Manager. Monitor token expenditure closely by setting hard budget alerts on your OpenAI or Anthropic developer accounts, as recursive agent loops can rack up hundreds of dollars in evaluation costs overnight.
What to Build Next
Once your basic evaluation pipeline is stable, extend it to track regression over time. Build a logging dashboard that stores every execution trace in a vector database like Qdrant, allowing you to cluster failing test cases by semantic similarity. You can also implement adversarial test generation, using a separate agent to automatically draft new edge-case prompts designed to break your primary agent's reasoning loop.
Bottom Line
Stop deploying autonomous agents without automated evaluation harnesses. Manual spot-checking does not scale when dealing with stochastic systems and non-deterministic tool calls. Implement the architecture outlined above, enforce strict LLM-as-a-judge thresholds, and integrate your evaluation suite directly into your CI/CD workflow today.
Related Analyses
More in Tutorials →
Save Nest App Videos Before 2027 Shutdown
Google is killing the legacy Nest app on January 25, 2027. Learn how to bulk-export your clips and migrate your account before data deletion begins.

How to Audit LLM Providers for Prompt Leakage
Secure your API pipeline against inference provider sniffing by building an automated prompt canary injection testing script using Python and OpenRouter.

How to Build AI Physics Datasets with NVIDIA Cosmos
Build training-ready physical AI datasets using just two prompts in NVIDIA Cosmos. A complete engineering tutorial with code and troubleshooting.