Welcome, Developer.
In the previous post, we built an AI agent in TypeScript in about 50 lines of code, with no framework. It called two tools, it answered the question, and it worked. However, one question was left open: how do we know it works? And, more importantly, when we change one line of the prompt tomorrow, how do we know we did not break something else?
This post answers that question with evals, which is simply the name the AI world gives to tests for models and agents. We are going to move the system prompt into a template, write a small golden set of questions with known answers, and build an eval harness that runs everything and reports a pass rate. As before, no framework, only TypeScript and the Anthropic SDK.
Introduction
What makes an agent hard to test? With regular code, we call a function and compare the result with the value we expect. With an agent, two things get in the way.
First, the model rarely writes the same sentence twice, so comparing the full text of the answer is not an option. Second, our tools call the internet and read the real clock, so the correct answer to “what’s the weather in Tokyo?” changes every few minutes.
The approach we take is to test the behavior instead of the exact words. For this agent, we check three things:
- Did it call the right tools with the right input?
- Does the final answer contain the facts the tools returned?
- Did it finish within a reasonable number of steps?
These three checks are simple, but they catch most of the problems you will see in practice.
Before We Start
This post continues from where the previous one finished, so you need the agent with both tools, get_weather and get_time, calling the Open-Meteo API. That was the exercise at the end of the last post. If you skipped it, the full code is on GitHub.
No new packages are needed. We use the same @anthropic-ai/sdk, typescript and tsx from before, and the same ANTHROPIC_API_KEY environment variable.
Making the Agent Testable
The current agent has three issues when it comes to testing. It runs the question as soon as the file is imported, it returns only the final text, and it always calls the real tools. Let’s fix each one in agent.ts.
The imports, the client, the tools array and the findCity function stay exactly as they are.
First, the agent needs to report what it did, not only what it answered. Add these types after the tools array:
// a tool runner receives the tool name and the input, and gives back text
export type ToolRunner = (name: string, input: any) => Promise<string>;
// this is what we keep about each tool the model asked for
export type ToolCall = { name: string; input: any };
// now the agent gives back more than the answer, we need this to test it
export type AgentResult = {
answer: string;
toolCalls: ToolCall[];
steps: number;
stoppedEarly: boolean;
};Next, replace the old runTool function with realRunTool. The logic is the same, but now it has a type, so we can swap it for a fake implementation later. There is also one small fix: the tool name is checked before calling the geocoding API, so an unknown tool no longer wastes a request.
// this is the real runner, it talks to the internet
export const realRunTool: ToolRunner = async (name, input) => {
console.log(`Calling ${name}`, input);
// we check the tool name first, so we don't call the API for nothing
if (name !== "get_weather" && name !== "get_time") return "Unknown tool";
const place = await findCity(input.city);
if (!place) return `City not found: ${input.city}`;
if (name === "get_weather") {
const url = `https://api.open-meteo.com/v1/forecast?latitude=${place.latitude}&longitude=${place.longitude}¤t=temperature_2m`;
const data = await fetch(url).then((r) => r.json());
return `It is ${data.current.temperature_2m}°C in ${place.name}`;
}
const time = new Date().toLocaleTimeString("en-US", {
timeZone: place.timezone,
hour: "2-digit",
minute: "2-digit",
});
return `It is ${time} in ${place.name}`;
};Finally, update runAgent, as highlighted in the following code:
export async function runAgent(
question: string,
options: { system: string; runTool?: ToolRunner }
): Promise<AgentResult> {
// in the tests we pass a fake runner, in real life we use the real one
const runTool = options.runTool ?? realRunTool;
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: question },
];
const toolCalls: ToolCall[] = [];
for (let step = 1; step <= 5; step++) {
const response = await client.messages.create({
model: "claude-sonnet-5-5",
max_tokens: 1024,
system: options.system,
tools,
messages,
});
messages.push({ role: "assistant", content: response.content });
// no tool asked, so the model has the final answer
if (response.stop_reason !== "tool_use") {
const text = response.content.find((b) => b.type === "text");
return {
answer: text?.type === "text" ? text.text : "",
toolCalls,
steps: step,
stoppedEarly: false,
};
}
// the model asked for tools, so we save each call, run it and send the result back
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type === "tool_use") {
toolCalls.push({ name: block.name, input: block.input });
results.push({
type: "tool_result",
tool_use_id: block.id,
content: await runTool(block.name, block.input),
});
}
}
messages.push({ role: "user", content: results });
}
return { answer: "", toolCalls, steps: 5, stoppedEarly: true };
}There are three changes here. The function receives the system prompt, and it can optionally receive a different tool runner. When none is passed, it falls back to the real one. It also records every tool call and counts the steps, where one step is one call to the model.
Then, delete the last line of the old file, the one that calls runAgent when the file loads. We are moving it to a separate file shortly.
The most important change is options.runTool. In the evals, we pass a fake runner that returns fixed data. That way, when a case fails, we know to look at the model and the prompt, not at a slow or unavailable API.
Prompt Templates
The agent from the previous post had no system prompt, so the model made every decision on its own. Now we want to give it some rules.
We could write the prompt as a long string inside the code, but that becomes hard to maintain quickly. A better option is to keep it in its own file, with placeholders for the values that change. Create a prompts folder and a file called prompts/system.v1.md:
You are a small assistant that answers questions about the weather and the local time in cities.
Today is {{today}}. If the user does not say a city, use {{default_city}}.
Rules:
1. Only use the numbers that the tools return. Never guess a temperature or a time.
2. If a tool says the city was not found, tell the user and ask for another city.
3. If the question is not about weather or time, answer it directly and do not use a tool.
4. Keep the answer short, one or two sentences.The placeholders are {{today}} and {{default_city}}. Next, we need a function that fills them in. Create a file called prompt.ts:
import { readFileSync } from "node:fs";
// we replace each {{name}} with its value, and we fail loud if a value is missing
export function renderPrompt(
template: string,
vars: Record<string, string>
): string {
return template.replace(/\{\{(\w+)\}\}/g, (_, name: string) => {
if (!(name in vars)) throw new Error(`Missing prompt variable: ${name}`);
return vars[name];
});
}
// the prompts live in files, one file for each version
export function loadPrompt(
version: string,
vars: Record<string, string>
): string {
const template = readFileSync(`prompts/system.${version}.md`, "utf-8");
return renderPrompt(template, vars);
}Note the error thrown in renderPrompt. Without it, a typo in a variable name would send the literal text {{default_city}} to the model, and nothing would tell us. It is better to fail early and clearly.
Now, let’s create the file that runs the agent, main.ts:
import { runAgent } from "./agent";
import { loadPrompt } from "./prompt";
const system = loadPrompt("v1", {
today: new Date().toISOString().slice(0, 10),
default_city: "Christchurch",
});
runAgent("What's the weather and the time in Tokyo?", { system }).then(
(result) => console.log(result.answer)
);Run it with npx tsx main.ts. The behavior should be the same as before, now guided by the rules in the prompt.
Why use placeholders instead of hardcoding the values? Because today changes every day. In the evals, we set it to a fixed date, so the prompt sent to the model is identical on every run.
It is also worth noting that the rules in this prompt were chosen on purpose. Each one is something we can test. Rule 2 covers the unknown city, rule 3 covers questions that need no tool, and the default city sentence gets its own case too.
The Golden Set
A golden set is a list of inputs where we already know what a good result looks like. It is written by hand, once, and reused every time something changes. Create an evals folder and a file called evals/golden.json:
[
{
"id": "weather-tokyo",
"question": "What's the weather in Tokyo?",
"expectedCalls": [{ "name": "get_weather", "city": "Tokyo" }],
"mustInclude": ["21"],
"mustNotInclude": [],
"maxSteps": 3
},
{
"id": "time-tokyo",
"question": "What time is it in Tokyo?",
"expectedCalls": [{ "name": "get_time", "city": "Tokyo" }],
"mustInclude": ["2:30"],
"mustNotInclude": [],
"maxSteps": 3
},
{
"id": "weather-and-time",
"question": "What's the weather and the time in Tokyo?",
"expectedCalls": [
{ "name": "get_weather", "city": "Tokyo" },
{ "name": "get_time", "city": "Tokyo" }
],
"mustInclude": ["21", "2:30"],
"mustNotInclude": [],
"maxSteps": 3
},
{
"id": "two-cities",
"question": "Is it warmer in Paris or in London right now?",
"expectedCalls": [
{ "name": "get_weather", "city": "Paris" },
{ "name": "get_weather", "city": "London" }
],
"mustInclude": ["21"],
"mustNotInclude": [],
"maxSteps": 3
},
{
"id": "no-tool",
"question": "What is 2 + 2?",
"expectedCalls": [],
"mustInclude": ["4"],
"mustNotInclude": [],
"maxSteps": 1
},
{
"id": "unknown-city",
"question": "What's the weather in Port Kelmar?",
"expectedCalls": [{ "name": "get_weather", "city": "Port Kelmar" }],
"mustInclude": [],
"mustNotInclude": ["°", "21"],
"maxSteps": 3
},
{
"id": "default-city",
"question": "What's the weather like?",
"expectedCalls": [{ "name": "get_weather", "city": "Christchurch" }],
"mustInclude": ["21"],
"mustNotInclude": [],
"maxSteps": 3
}
]Each case has a question and the expected result. expectedCalls is the exact list of tools the agent must call, no more and no less. mustInclude lists text that must appear in the answer, and mustNotInclude lists text that must not. maxSteps is the maximum number of calls to the model.
Our fake tools always return 21°C and 02:30 PM, which is why the cases look for “21” and “2:30”. I used “2:30” instead of “02:30” because the model may write “2:30 PM”, and that is still a correct answer.
Let’s look at how the cases were chosen:
- The first three are the common questions. The third one is the same question from the previous post.
- The two cities case checks that the model calls the weather tool once for each city.
- The no tool case checks the opposite situation. An agent that calls tools for everything is also wrong.
- The unknown city case is the most important one. The tool returns “City not found”, and the agent must not invent a temperature. I used a made up name, Port Kelmar, on purpose. Atlantis was my first choice, but the model knows Atlantis is a myth and may answer without calling the tool at all, so the case would test the wrong thing.
- The last case has no city, so the agent should use the default one from the prompt.
Seven cases are enough to start. Over time, the most valuable cases come from real bugs. Every time the agent does something unexpected, add that question to the golden set.
The Eval Harness
The eval harness is a script that, for each case, runs the agent, checks the result, and counts the passes. Create a file called evals/run.ts. We will go through it in three parts. The first part has the settings, the fake tools and the prompt:
import { readFileSync } from "node:fs";
import { runAgent } from "../agent";
import type { AgentResult, ToolRunner } from "../agent";
import { loadPrompt } from "../prompt";
type Case = {
id: string;
question: string;
expectedCalls: { name: string; city: string }[];
mustInclude: string[];
mustNotInclude: string[];
maxSteps: number;
};
// how many times we run each case, the model can answer different each time
const RUNS = Number(process.env.RUNS ?? 3);
// below this pass rate the script exits with an error
const THRESHOLD = Number(process.env.THRESHOLD ?? 0.9);
// the model can write "Tokyo" or "Tokyo, Japan", for us both are the same city
function normalizeCity(city: unknown): string {
return String(city).split(",")[0].trim().toLowerCase();
}
// fake tools with fixed data, so the right answer never changes
const stubRunTool: ToolRunner = async (name, input) => {
if (normalizeCity(input.city) === "port kelmar") {
return `City not found: ${input.city}`;
}
if (name === "get_weather") return `It is 21°C in ${input.city}`;
if (name === "get_time") return `It is 02:30 PM in ${input.city}`;
return "Unknown tool";
};
// we use a fixed date too, so the prompt is always the same
const system = loadPrompt(process.env.PROMPT ?? "v1", {
today: "2026-01-15",
default_city: "Christchurch",
});Each case runs 3 times, as defined in RUNS, because the model can respond differently each time. A case that passes 3 out of 3 is stable. A case that passes 2 out of 3 is flaky, which usually means the prompt is not clear enough.
THRESHOLD is the minimum pass rate we accept. I use 90% instead of 100% because an occasional bad run is normal when working with a model, and the script should not fail because of it. A real problem usually fails every run of a case, so it still pulls the rate below 90%.
stubRunTool and the system constant are both fixed, so everything apart from the model stays the same between runs. normalizeCity exists because the model sometimes asks for “Tokyo, Japan” instead of “Tokyo”. Both are valid, so we compare only the city name.
The second part checks a single run. It returns a list of problems, and an empty list means the run passed:
// we check one run, a list of problems is the result, empty list means it passed
function check(c: Case, result: AgentResult): string[] {
const problems: string[] = [];
const called = result.toolCalls
.map((t) => `${t.name}(${normalizeCity(t.input.city)})`)
.sort();
const expected = c.expectedCalls
.map((t) => `${t.name}(${normalizeCity(t.city)})`)
.sort();
if (called.join(", ") !== expected.join(", ")) {
problems.push(
`tools: wanted [${expected.join(", ")}] got [${called.join(", ")}]`
);
}
for (const text of c.mustInclude) {
if (!result.answer.includes(text))
problems.push(`answer is missing "${text}"`);
}
for (const text of c.mustNotInclude) {
if (result.answer.includes(text))
problems.push(`answer should not have "${text}"`);
}
if (result.stoppedEarly || result.steps > c.maxSteps) {
problems.push(`too many steps: ${result.steps}`);
}
return problems;
}Note that the tool calls are sorted before the comparison. The model can request the weather and the time in any order, and both orders are correct.
The last part runs all the cases and prints the results:
async function main() {
const cases: Case[] = JSON.parse(readFileSync("evals/golden.json", "utf-8"));
let passed = 0;
let total = 0;
for (const c of cases) {
// all the runs of one case go at the same time
const results = await Promise.all(
Array.from({ length: RUNS }, () =>
runAgent(c.question, { system, runTool: stubRunTool })
)
);
const failures = results
.map((r) => check(c, r))
.filter((p) => p.length > 0);
const ok = RUNS - failures.length;
passed += ok;
total += RUNS;
console.log(
`${failures.length === 0 ? "PASS" : "FAIL"} ${c.id} ${ok}/${RUNS}`
);
// we show only the first problem, it is enough to start looking
if (failures.length > 0) console.log(` ${failures[0].join("; ")}`);
}
const rate = passed / total;
console.log(`\nPass rate: ${Math.round(rate * 100)}% (${passed}/${total})`);
if (rate < THRESHOLD) process.exit(1);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});When the pass rate is below the threshold, the script exits with an error code. For now, that simply gives us a clear failure in the terminal. Later on, the same script can run in your CI pipeline and block a change that makes the agent worse.
At this point, the project structure should look like this:
agent.ts
main.ts
prompt.ts
prompts/system.v1.md
evals/golden.json
evals/run.tsRunning the Evals
Time to run it:
npx tsx evals/run.tsYou should see an output similar to this:
PASS weather-tokyo 3/3
PASS time-tokyo 3/3
PASS weather-and-time 3/3
PASS two-cities 3/3
PASS no-tool 3/3
PASS unknown-city 3/3
PASS default-city 3/3
Pass rate: 100% (21/21)Keep in mind that this run makes 21 agent runs (7 cases times 3 runs each), and each one calls the model at least once, so it uses API credits. While you are still building, RUNS=1 npx tsx evals/run.ts makes it faster and cheaper.
Breaking It on Purpose
How do we know the harness actually catches problems? Let’s break the agent on purpose and find out.
Copy prompts/system.v1.md to prompts/system.v2.md and remove the sentence about the default city. Then, run the same harness against the new version:
PROMPT=v2 npx tsx evals/run.tsOn Windows PowerShell, run $env:PROMPT="v2" first and then npx tsx evals/run.ts. The same applies to RUNS.
The output should be similar to this:
PASS weather-tokyo 3/3
PASS time-tokyo 3/3
PASS weather-and-time 3/3
PASS two-cities 3/3
PASS no-tool 3/3
PASS unknown-city 3/3
FAIL default-city 0/3
tools: wanted [get_weather(christchurch)] got []; answer is missing "21"
Pass rate: 86% (18/21)Without a default city, the model most likely asks the user which city they mean. For a person, that is a reasonable reply, but it is not the behavior we defined for this agent. Notice also that the other six cases still pass. Without the harness, this regression would only show up when a user reported it.
This is the core idea of evals. Change one thing, run the harness, and compare the numbers. When the pass rate drops, you know exactly what broke. When it goes up, you have evidence that the change was an improvement, not only a feeling.
Exercises
If you want to practice further, here are three exercises:
- In
agent.ts, change the description ofget_timeto something vague, such as “Get information for a city”, and run the harness. Which cases fail? This shows in practice why the tool description matters, as we discussed in the previous post. - Add your own cases to
golden.json. Try a city with a space, such as “New York”, a city with an accent, such as “São Paulo”, or a question in another language. - Write a
system.v3.mdwith a different style, for example a friendlier tone, and compare the pass rates usingPROMPT=v3. Is the new version better, or only different?
Next Steps
Have we covered everything about evaluating agents? Not at all. This golden set checks facts and tool usage, but it does not check the quality of the writing, the tone, or how clear the explanation is. For that, a common approach is to use a second model as a judge, which is a natural next step after this post.
Also, because the harness uses fake tools, it never tests the real APIs. Run npx tsx main.ts from time to time to confirm the full flow still works end to end.
If you are working with more than one agent, the same approach applies to multi-agent systems. There are simply more behaviors to check.
Resources
- Post’s code on GitHub
- How to Build an AI Agent in TypeScript (No Framework), the previous post
- Anthropic tool use documentation
Conclusion
An agent is a loop, and an eval is another loop around it: run the cases, check the results, count the passes. It does not need a framework or a large dataset to be useful. Seven cases and a short script are enough to stop guessing whether a prompt change helped.
Once this is in place, you can change your prompts and tools with confidence, because the numbers will tell you when something goes wrong.
Stay focused, Developer!