Module contents
Lesson 27 of 31Core 110 min

Agent evaluation I: environments, tasks and state-based checking

Construct agent evaluations with stateful environments, actions and long trajectories. Study benchmark anatomy, reproducible environments, state-based and trajectory checking, simulated users and function-call evaluation, survey established benchmarks and build a 40-task benchmark.

After this lesson you can

  • Describe an agent benchmark’s anatomy and classify reference benchmarks.
  • Build resettable, isolated environments and measure residual nondeterminism.
  • Write robust final-state checkers and compare them with trajectory and function-call AST evaluation.
  • Implement a simulated user with a local model and quantify the variance it introduces.
  • Run a 40-task benchmark with several module agents and report accuracy, pass^k and cost.

Before you start

Evaluation is an experiment on a system

The anatomy of an agent benchmark includes the environment, its initial state, instruction, allowed actions, horizon, budget and success rule. It also needs a sampling protocol, held-out test data and a report including failures and costs. A model can know the answer and fail to execute an operation; an agent can reach a correct state through several different trajectories.

InteractiveInside a task

Reset

input.json = [3, -1, 3, 0]; output.json = []

The alternative trajectory performs an extra write. The checker accepts both by verifying final state and preservation of the original file; literal action comparison could reject the alternative.

Trajectory
Step
StepReset
Final statepending
Compare two reference trajectories that reach the same final file.

The state-based checker compares the environment outcome with required properties. It also checks that data meant to be preserved were not altered. An exact-trajectory check is useful when order or authorization is part of the requirement, but can reject valid alternatives. Hidden tests help avoid solutions fitted to visible examples, although a finite test set does not prove equivalence on all inputs. An exact answer works when there is a clear canonical form; a language judge requires calibration and control of false positives and negatives.

Environment and harness

A reproducible environment resets files and database for each attempt, pins versions and seeds, and declares network, clock and external effects. A temporary directory avoids mixing files from two attempts, but is not itself a security isolation boundary for arbitrary code. Running untrusted code requires appropriate isolation and resource limits. Repeatedly check that initial state is identical; a correct reset does not eliminate nondeterminism from model, hardware or external services.

The harness logs task, agent version, observations, actions, seeds, tokens, time and stopping reason. Distinguish agent failure from confirmed infrastructure failure, such as an environment failing to start. Report how many infrastructure attempts failed, why and the retry policy; do not silently turn them into agent errors or omit them without counting. An agent timeout and a service outage are not automatically the same case.

This laboratory harness accepts an injected environment for other task types. If environment creation fails with a system or SQLite error, it records infrastructure and leaves success undefined; an unexpected adapter error is recorded separately. This initialization classification was added after the 400 attempts, in which no infrastructure or adapter failures were observed.

Capability and reliability

With success probability pip_i on task ii and attempts independent conditional on the task, the probability of at least one success in kk attempts is 1−(1−pi)k1-(1-p_i)^k and that of succeeding on all is pikp_i^k. These are averaged by task. With nn attempts and cc observed successes, an unbiased estimate for k≤nk\le n uses 1−(n−ck)/(nk)1-\binom{n-c}{k}/\binom nk for pass@k and (ck)/(nk)\binom ck/\binom nk for pass^k, with impossible coefficients equal to zero. These formulas require the assumed repetition protocol; if attempts share failures or seeds, they do not automatically predict independent repetitions.

InteractiveCapable versus reliable
  • At least one success
  • All attempts

Qwen2.5-0.5B GGUF on CPU, 40 tasks and five attempts per adapter. For each task with c successes out of five, curves average 1 − C(5 − c, k)/C(5, k) and C(c, k)/C(5, k). We do not extrapolate k beyond five. These are similar toy tasks; infrastructure errors are recorded separately.

Data
Agent
Attempts k
pass@k4.00 %
pass^k0.00 %
pass@11.00 %
Compare measured agents and estimators for up to five attempts; use the theoretical model to explore eight.

With five attempts per task, pass^8 is not directly estimated by those estimators. Cluster the bootstrap by task and keep its attempts together; if task families come from a template, also assess dependence between families. Show distribution by type, cost and latency as well as the overall rate. τ-bench uses database state and studies repeated-attempt reliability.

The user varies too

A user simulation gives another model a profile, private information and a conversation policy. The simulated user should not automatically reveal information the agent ought to ask for. Document its model, instructions, temperature, seed and stopping criterion. Cross agent and user seeds to estimate variation along each dimension; variation between tasks and interaction can also matter. A simulator may share biases with the evaluator or fail to represent real users.

InteractiveSimulated-user noise

Requested field: preferred city. Synthetic profile value: Madrid.

User 1: My preferred city is Madrid.

  • Agent 1: FINAL: Madrid (success)
  • Agent 2: FINAL: Madrid (success)

User 2: My preferred city is Madrid.

  • Agent 1: FINAL: Madrid (success)
  • Agent 2: FINAL: Madrid (success)

The method-of-moments estimate averages between-user and within-user squares over ten tasks. With two replicates the between-user component may be negative and is shown unclipped. It does not separate user–agent interaction or estimate variation among real people.

Condition success1.000
Between-user variance0.000
Residual variance0.000
Compare synthetic answers and variance components measured in four conditions.

We ran ten simple tasks with two user responses and two agent responses per user response. The agent was Qwen2.5-7B GGUF Q4_K_M on CPU, temperature 0.7; the user was Qwen2.5-7B or 0.5B GGUF at temperatures 0.2 and 0.8. All four conditions scored 40/40; estimated between-user and agent-residual components were 0 in this sample. A task bootstrap of 2000 resamples gave [0, 0] for those components, a degenerate interval that does not prove absence of variation in real users or harder tasks. These are synthetic profiles, not people’s private data. Moment estimates can be negative and, with only two replicates per user, do not separate interaction.

Inspect the 160 runs and analysis. To reproduce them with the same CPU models, download the adapter, first condition and other three to the same directory; run python user-sim-cpu.py first, then python user-sim-compare-cpu.py. They retain seeds and answers in agent-bench.

Benchmarks and calls

The benchmark landscape includes SWE-bench, with repository problems and tests; WebArena, with reproducible web applications; OSWorld, with computer-environment tasks; GAIA, with questions that may require tools; and AgentBench, with several environments. BFCL evaluates function calls and also includes multi-turn variants. Their measures and environments answer different questions; do not universally rank systems using one score.

Syntax-tree evaluation compares function name and structured arguments rather than surface text. It can accept an omitted default or several valid forms, but must distinguish types and cases where no tool should be called. Check environment effects when a syntactically correct call could produce an incorrect result. AI Agents That Matter recommends considering cost alongside quality and maintaining separation between development and test.

We tested NF4-quantized Qwen2.5-7B-Instruct on the first ten simple Python cases of BFCL v4. A custom conservative checker parsed each call as an AST without executing it and accepted 10/10 names and arguments against published alternatives. This is a small sample and not the official BFCL score: it does not include all formats or test function effects. Inspect answers and judgments; the reproducible script downloads pinned files and retains answers and comparison criteria. The run shared a GPU with other work, so its times do not measure isolated latency.

We also ran the first ten BFCL irrelevance cases through the extensible harness using Qwen2.5-7B GGUF Q4_K_M on CPU. The checker required the exact answer NO_TOOL and accepted 10/10; this is another quantization and subset, not a paired comparison with the NF4 test. The harness creates a temporary environment per attempt, logs errors and checks output without executing calls. Neither metric is the official BFCL score. Review the ten traces; to reproduce them, download the harness, CPU adapter and BFCL runner to the same directory and run python bfcl-harness-cpu.py.

Local laboratory: a small benchmark and checkers

This benchmark has 40 toy instances generated from three families: 15 JSON list sorts, 15 SQLite updates and 10 arithmetic repairs. Variants in a family are not 40 independent problems and do not constitute a representative benchmark. Each attempt creates its temporary directory and the only exposed methods limit file and database operations. Repair interprets a narrow AST grammar without executing generated code and applies five tests: those tests can accept a function wrong on other inputs. Do not execute arbitrary agent code in the host process.

The programmed reference passed all 40 instances and a no-action policy failed all 40. This checks harness reset and basic cases; these are not model results. To measure agents, we also ran Qwen2.5-0.5B GGUF Q4_K_M on CPU, five attempts per task and adapter: the lesson 13 ReAct engine and a single-call agent implemented here. This second adapter does not claim to be another lesson’s agent. All 400 attempts completed with no infrastructure or adapter errors classified by the harness.

With a 2000-sample bootstrap clustered by task, ReAct obtained pass@1 = 0.010 with interval [0, 0.025], pass@5 = 0.050 [0, 0.125] and pass^5 = 0. The single-call agent obtained 0.075 [0.035, 0.120], 0.275 [0.150, 0.425] and 0, respectively. Mean input plus output tokens were 742.4 for ReAct and 157.4 for single-call. Tasks are toys and share templates; intervals do not make those families independent or turn results into a general agent comparison. A bootstrap interval [0, 0] for pass^5 reflects that no task succeeded on all five observed attempts, not that population reliability is exactly zero. Times were recorded under shared load and do not serve as an isolated latency comparison.

In those same runs, mean wall-clock times were 3.93 s for ReAct, with clustered interval [2.60, 5.59], and 1.24 s for single-call, with interval [1.04, 1.47]. Corresponding token-count intervals were [603.85, 888.81] and [154.91, 160.27]. They describe this protocol and its shared load; they do not predict isolated service performance.

The per-attempt success breakdown shows where results concentrated: both scored 0/75 on file sorting; on SQLite, ReAct scored 2/75 and single-call 15/75; on repair both scored 0/50. An overall figure would hide that the observed difference comes from one task family.

As a supplementary task, the same harness tested two read-only SQLite queries with the lesson 13 ReAct engine and 7B GGUF on CPU: 0/2. In both cases the agent exhausted six steps by returning a JSON object as a tool argument where the contract requires a string; it never queried the database. A reference policy did query and passed both checkers. These two tasks neither replace nor mix with the 40-task benchmark. See trajectories or run the query test alongside the downloadable harness, CPU adapter and ReAct engine.

Inspect the 400 attempts and their clustered summary. To repeat the benchmark, download the harness, ReAct engine, runner and analysis to one directory. With llama-cpp-python 0.3.36, transformers and huggingface_hub installed, run python agent-benchmark.py followed by python analyze-runs.py cpu. Each attempt creates a new environment and is saved in agent-bench/agent_runs.json; the runner can resume. Tests use the bounded syntax tree; they do not execute arbitrary generated code.

[ ]Isolated environment and checkersLocal GPU
"""Banco reproducible de 40 tareas de juguete; las políticas reales son adaptadores externos."""
import ast,json,sqlite3,tempfile,time
from pathlib import Path
from dataclasses import dataclass

@dataclass(frozen=True)
class Task:
 id:str;kind:str;instruction:str;difficulty:int;seed:int

def tasks():
 out=[]
 for i in range(15):
  out.append(Task(f'file-{i:02}', 'file', 'Lee input.json y escribe output.json como una lista JSON con los números ordenados de menor a mayor. Conserva input.json.',1,i))
 for i in range(15):
  out.append(Task(f'db-{i:02}','db', 'En la tabla cuentas suma 3 al saldo de la cuenta 2 y conserva el resto. Usa db con un JSON {"op":"add","id":2,"amount":3}.',2,i))
 for i in range(10):
  out.append(Task(f'fix-{i:02}','fix', f'Repara calc.py: la función calc(x) debe devolver x + {i+2}. No cambies el nombre ni el argumento.',2,i))
 return out

class Environment:
 def __init__(self,task):
  self.task=task;self.temp=tempfile.TemporaryDirectory(prefix='agentbench-');self.root=Path(self.temp.name)
  self.files={}
  if task.kind=='file':
   values=[task.seed+3,task.seed-1,task.seed+3,0];self.values=values
   self.files={'input.json':json.dumps(values),'output.json':'[]'}
  elif task.kind=='fix':self.files={'calc.py':'def calc(x):\n    return x - '+str(task.seed+2)+'\n'}
  else:
   db=sqlite3.connect(self.root/'state.db');db.execute('CREATE TABLE cuentas(id INTEGER PRIMARY KEY, saldo INTEGER NOT NULL)')
   db.executemany('INSERT INTO cuentas VALUES (?,?)',[(1,10+task.seed),(2,20+task.seed),(3,30+task.seed)]);db.commit();db.close()
  for name,text in self.files.items():(self.root/name).write_text(text,encoding='utf8')
 def close(self):self.temp.cleanup()
 def read(self,arg):
  if arg not in self.files:raise ValueError('ruta no permitida')
  return (self.root/arg).read_text(encoding='utf8')
 def write(self,arg):
  obj=json.loads(arg);name=obj['path'];text=obj['content']
  if name not in self.files or not isinstance(text,str) or len(text)>10000:raise ValueError('escritura no permitida')
  (self.root/name).write_text(text,encoding='utf8');return 'ok'
 def db(self,arg):
  if self.task.kind!='db':raise ValueError('sin base')
  obj=json.loads(arg);conn=sqlite3.connect(self.root/'state.db')
  try:
   if obj=={'op':'list'}:return json.dumps(conn.execute('SELECT id,saldo FROM cuentas ORDER BY id').fetchall())
   if set(obj)=={'op','id','amount'} and obj['op']=='add' and type(obj['id']) is int and type(obj['amount']) is int and abs(obj['amount'])<=100:
    conn.execute('UPDATE cuentas SET saldo=saldo+? WHERE id=?',(obj['amount'],obj['id']));conn.commit();return 'ok'
   raise ValueError('operación no permitida')
  finally:conn.close()
 def check(self):
  if self.task.kind=='file':
   try:actual=json.loads((self.root/'output.json').read_text(encoding='utf8'))
   except (ValueError,OSError):return False,'salida JSON inválida o ausente'
   original=(self.root/'input.json').read_text(encoding='utf8')==self.files['input.json']
   return isinstance(actual,list) and all(type(x) is int for x in actual) and actual==sorted(self.values) and original,'comprobar lista y entrada conservada'
  if self.task.kind=='db':
   conn=sqlite3.connect(self.root/'state.db');actual=conn.execute('SELECT id,saldo FROM cuentas ORDER BY id').fetchall();conn.close()
   expected=[(1,10+self.task.seed),(2,23+self.task.seed),(3,30+self.task.seed)]
   return actual==expected,'comprobar todas las filas'
  try:
   source=(self.root/'calc.py').read_text(encoding='utf8');tree=ast.parse(source)
   # Gramática estrecha: una función de una variable con una expresión aritmética.
   allowed=(ast.Module,ast.FunctionDef,ast.arguments,ast.arg,ast.Return,ast.BinOp,ast.Add,ast.Sub,ast.Mult,ast.UnaryOp,ast.USub,ast.Name,ast.Load,ast.Constant)
   if any(not isinstance(n,allowed) for n in ast.walk(tree)):raise ValueError('nodo no permitido')
   fn=tree.body[0]
   if len(tree.body)!=1 or not isinstance(fn,ast.FunctionDef) or fn.name!='calc' or len(fn.args.args)!=1 or fn.args.args[0].arg!='x' or fn.args.posonlyargs or fn.args.kwonlyargs or fn.args.vararg or fn.args.kwarg or fn.args.defaults or fn.decorator_list or len(fn.body)!=1 or not isinstance(fn.body[0],ast.Return):raise ValueError('firma inválida')
   if any(isinstance(n,ast.Name) and n.id!='x' for n in ast.walk(tree)):raise ValueError('nombre no permitido')
   def interpret(node,x):
    if isinstance(node,ast.Name):return x
    if isinstance(node,ast.Constant) and type(node.value) is int and abs(node.value)<=1000:return node.value
    if isinstance(node,ast.UnaryOp) and isinstance(node.op,ast.USub):return -interpret(node.operand,x)
    if isinstance(node,ast.BinOp):
     a,b=interpret(node.left,x),interpret(node.right,x)
     if isinstance(node.op,ast.Add):result=a+b
     elif isinstance(node.op,ast.Sub):result=a-b
     elif isinstance(node.op,ast.Mult):result=a*b
     else:raise ValueError('operación no permitida')
     if abs(result)>1000000:raise ValueError('resultado fuera de límite')
     return result
    raise ValueError('expresión no permitida')
   if sum(1 for _ in ast.walk(tree))>100:raise ValueError('expresión demasiado grande')
   ok=all(interpret(fn.body[0].value,x)==x+self.task.seed+2 for x in [-7,0,1,8,19]);return ok,'pruebas ocultas de calc'
  except (ValueError,SyntaxError,TypeError,IndexError,OSError,OverflowError):return False,'archivo inválido o pruebas fallidas'

class InfrastructureError(Exception):
 pass

def run(task,agent,environment_factory=Environment):
 started=time.perf_counter()
 try:env=environment_factory(task)
 except (InfrastructureError,OSError,sqlite3.Error) as exc:
  return {'task':task.id,'kind':task.kind,'success':None,'agent':None,'infrastructure_error':str(exc),'adapter_error':None,'seconds':time.perf_counter()-started}
 try:
  result=agent(task,{'read':env.read,'write':env.write,'db':env.db})
  if hasattr(env,'set_result'):env.set_result(result)
  ok,diff=env.check();return {'task':task.id,'kind':task.kind,'success':ok,'check':diff,'seconds':time.perf_counter()-started,'agent':result,'infrastructure_error':None}
 except InfrastructureError as exc:
  return {'task':task.id,'kind':task.kind,'success':None,'agent':None,'infrastructure_error':str(exc),'adapter_error':None,'seconds':time.perf_counter()-started}
 except Exception as exc:
  # Un error inesperado no se reclasifica como infraestructura sin evidencia.
  return {'task':task.id,'kind':task.kind,'success':None,'agent':None,'infrastructure_error':None,'adapter_error':type(exc).__name__,'seconds':time.perf_counter()-started}
 finally:env.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The repair checker tests five inputs; that does not prove the function correct for all. The following counterexample passes those five tests because its extra term vanishes on them, but returns 1840 when x=2 instead of 4. It does not execute generated code: the harness’s bounded interpreter parses the tree. Adding hidden tests and random cases reduces this risk, though it does not prove general equivalence. Run this cell after defining the harness above.

[ ]A checker false positiveLocal GPU
task=next(t for t in tasks() if t.id=='fix-00')
env=Environment(task)
try:
    source='def calc(x):\n    return x + 2 + (x + 7) * x * (x - 1) * (x - 8) * (x - 19)\n'
    (env.root/'calc.py').write_text(source,encoding='utf8')
    accepted,_=env.check()
    x=2; actual=x+2+(x+7)*x*(x-1)*(x-8)*(x-19); expected=x+2
    assert accepted and actual!=expected
    print('comprobador acepta:',accepted,'en x=2 devuelve',actual,'pero debería devolver',expected)
finally:env.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

CodeState diff
Implement check_state(expected, actual, rules) for flat field dictionaries. rules assigns each field 'exact', 'set', 'ignore' or a nonnegative numeric tolerance. Return a sorted list of distinct names for missing, unexpected or nonconforming fields; ignore fields marked ignore even if missing or extra. A tolerance compares real numbers without accepting booleans.
def check_state(expected, actual, rules):
  pass
Shift+Enter to run
CodeCompare calls
Implement ast_match(call, accepted). Each call is a dictionary with 'name' and 'args'; accepted is a list of specifications with 'name', 'args' (each value is a list of alternatives) and 'defaults' (optional default values). The call must have the correct name, no extra arguments and an accepted value for each argument after applying defaults. Treat int and float as equivalent for the same value, but never bool as a number. name=None and args={} represents calling no tool.
def ast_match(call, accepted):
  pass
Shift+Enter to run
NumericCapability and reliability
Half the tasks have p = 0.9 and the other half p = 0.5. With independent attempts, what is mean pass^4?
Quiz
A container fails to start before the agent acts. How should that attempt be treated?
Quiz
A task asks to change one row and preserve the others. Which checker fits best?
Key idea
An agent benchmark evaluates trajectories inside an environment, and its result must be interpreted alongside the checker, repetitions and costs.