An agent is a loop. The model asks for a tool, your harness runs it and feeds the result back. Assignment 1 has you build every part of that loop, in 17 problems.
A lesson with a workbook. Each chapter explains one part of the assignment, then gives you exercises on our own toy data.
Press Play to send one request through the loop. Then switch off the stop rule, compaction or the guardrail and play again. Each part fails in its own way. Then we build the parts one by one.
You need some Python and the idea of a chat model call (messages in, text out). The exercises run JavaScript in your browser.
Based on Assignment 1 of Stanford CS 329Z: Engineering AI Agents (Fall 2026), designed and built by Michael Ryan. Starter repo and handout: cs329z/assignment1-harness (MIT licence). This page teaches the skills in our own words and toy data. It holds no solution to the assignment's problems.
An illustrative toy session. We made up the request, the token counts and the 4,000-token context budget for this page (the assignment's compaction tests also use 4,000). The parts and the rules are the assignment's.
Chapter 0
See the parts of the harness, follow one request through them, and learn the order to build them in
You start with a model call that turns a list of messages into a string, and nothing else. By the end you have built the code that turns that call into an agent. The assignment does it in two parts and 17 problems.
Part 1 builds pipelines: programs whose control flow lives in your code, with the model called only to classify, read or write. Part 2 builds an agent harness: the machinery around a model that decides for itself what to do next. Your Part 1 pipelines become tools of the Part 2 agent.
The course wrapper gives you one primitive. An LM takes a list of {role, content} messages and returns a string. It has no tool calling and no structured output. Everything on top of that string is yours.
| Part you build | Problems | What it does | Chapter |
|---|---|---|---|
| Pipelines | 1 priority, 2 daily_digest | Label one email; build a digest around many calls | 1 |
| Retriever | 3 bm25 | Rank documents for a query with no model | 2 |
| Multi-hop QA | 4 email_qa | Search, read, search again, under a hop budget | 3 |
| Registry and protocol | 5, 6 | Describe tools; write and parse calls as text | 4 |
| Agent loop | 7, 8 | Call, run, feed back, and stop for one of four reasons | 5 |
| Doc and terminal tools | 9, 10 | Return pointers and windows; tame huge outputs | 6 |
| Compaction | 11 | Fit every call in the context budget | 7 |
| Memory | 12 | Carry facts from one session to the next | 8 |
| Modes and guardrails | 13, 14 | Ask the user; block planted commands | 9 |
| Evaluation | 15 | Run simulated users against the whole agent | 10 |
The parts never run in a fixed order. Each request takes its own path through them. Pick a request and step through it.
The lit box is the part that handles the current step. Try the terminal task: three parts touch the command before it runs.
An illustrative toy trace. We made up the requests and the replies; the parts and the order they act in are the assignment's.
Worked number: the doc question makes 3 model calls, and each call sends the whole context so far. With contexts of 1,240, 1,900 and 3,360 tokens, the send spends 6,500 tokens, although the largest call is only 3,360. That gap is why Chapter 5 keeps a token budget beside the context budget.
Build each part, then check it twice. First run it against a scripted model, a fake LM that replays a fixed list of replies. It needs no network and costs nothing, so it tests your mechanics: the parser, the loop, the budgets. Then run it against the real model on a small slice of data, five items, and read every item it gets wrong.
The failure to expect: the real model writes a reply you never scripted, such as a label in lower case or a call with an extra space. Add that reply to your scripted list, fix the code, and run both checks again.
Chapter 1
Ask for a label you can parse, then let your code assemble a digest around many calls
Problem 1 gives you one email and asks for urgent, normal or ignore, plus a one-sentence reason, from one model call. You write run_priority(email, lm). The model returns free text, so you choose how the prompt asks for the label and how your code reads it. A reply that states no label gives unknown.
The labelling rule judges the email from the recipient's side, at the time it was sent. The wording does not decide: a mass mail that says "act now" is ignore. A good target is 85 percent agreement on 60 labelled emails, and no unknown at all.
The trap is in the parser. Search the reply for the word "urgent" and "This is not urgent" becomes urgent. Ask the model for a fixed label line and read only that line.
Each row is one toy reply. Switch the parser and watch which labels turn red.
The six replies and the LABEL: format are ours, made for this page. Your format is your choice.
Problem 2 builds a daily digest on top of Problem 1. Your code does the aggregation: classify each email, drop the ignore pile, keep one item per thread, order by urgency. One final call writes the text. Treat unknown like normal.
The tests check the model's text as written. It has at most 300 words, counted as len(digest.split()). It names every urgent item by its company, project or site. It mentions nothing from the ignore pile. Ask for the length in the prompt, since cutting the text loses content.
Worked number: say one call takes 1 second. A day of about 280 emails then takes 280 seconds in sequence and 28 seconds with ten calls at a time. The calls do not depend on each other, so classify them concurrently.
pythonfrom concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=10) as pool: labels = list(pool.map(classify_one, emails)) # results keep the order of emails
The failure to expect: the digest calls an urgent item "the pipeline project" and the test fails. Run show digest with --labels and compare. Tell the final call to name each urgent item's company, project or site.
MOOD:.MOOD: (any case), read the word after it.'unknown'.javascriptfunction parseMood(reply) {
const labels = ['happy', 'sad', 'neutral'];
for (const line of String(reply).split('\n')) {
const m = line.trim().match(/^mood\s*:\s*([a-z]+)/i);
if (m && labels.includes(m[1].toLowerCase())) return m[1].toLowerCase();
}
return 'unknown';
}
thread number, a level (high, low or skip) and a time.javascriptfunction briefing(items) {
const latest = {};
for (const it of items) {
const cur = latest[it.thread];
if (!cur || it.time > cur.time) latest[it.thread] = it;
}
const rank = { high: 0, low: 1 };
return Object.values(latest)
.filter(it => it.level !== 'skip')
.sort((a, b) => rank[a.level] - rank[b.level] || a.time - b.time)
.map(it => it.thread);
}
len(text.split()): Python splits on any run of spaces or newlines. How many words does this text have? "Pump 3 at Delta site:\nfix by 5 pm." (two spaces after "at", one newline).Chapter 2
Score three toy documents term by term, then see why an inverted index makes a rare term fast
Problem 3 asks for a retriever with no LLM and no search library. run_bm25_build(docs) indexes a list of strings. run_bm25_search(index, query, k) returns the top k (doc_id, score) pairs, best first, ties to the lower id.
BM25 adds one weight for each distinct query term. The weight grows when the term is rare in the corpus, when it repeats in the document, and when the document is short. Repeats have diminishing returns.
This IDF is Lucene's. The +1 inside the log keeps it positive for a term in more than half the documents, where the original formula goes negative.
Worked example, query "panel fault". Both terms sit in 2 of 3 documents, so each has IDF = ln(1.5 ⁄ 2.5 + 1) = ln 1.6 = 0.470.
Pick a query. Each bar stacks one block per matching term. Move k1 and b and watch the ranking.
The three documents are ours. The formula, k1 = 1.5, b = 0.75 and the Lucene IDF are the assignment's.
Build the index in one pass: for each term, the list of documents that hold it and the counts. A search reads only the lists of its query terms. That is how a term in 3 of 200,000 documents answers inside the 2 ms test, and why a document with no query term never appears.
The failure to expect: your scores are close to the expected ones but not equal. Score one toy document by hand, term by term. Then use the provided tokenize for documents and queries, count each distinct query term once, and use the Lucene IDF.
id, add its BM25 weight.javascriptfunction bm25Score(docs, query, id) {
const tokenize = s => s.toLowerCase().match(/[a-z0-9]+/g) || [];
const k1 = 1.5, b = 0.75;
const D = docs.map(tokenize), N = D.length;
const avgdl = D.reduce((a, d) => a + d.length, 0) / N;
let score = 0;
for (const t of new Set(tokenize(query))) {
const f = D[id].filter(x => x === t).length;
if (!f) continue;
const n = D.filter(d => d.includes(t)).length;
const idf = Math.log((N - n + 0.5) / (n + 0.5) + 1);
score += idf * f * (k1 + 1) / (f + k1 * (1 - b + b * D[id].length / avgdl));
}
return score;
}
function termScore(f, n, N, len, avgdl) { const k1 = 1.5, b = 0.75; const idf = Math.log((N - n + 0.5) / (n + 0.5)); const norm = k1 * (1 - b + b * len / avgdl); return idf * f * (k1 + 1) / (f + norm);}
Chapter 3
Let the model choose the next query, while your code holds the budget and checks the support
Problem 4 answers questions over the email archive with your retriever and the model in a loop. run_email_qa(question, search, lm) returns an answer, or None, and support: the ids of the emails the answer rests on. The caller builds search once from your BM25 index, so your pipeline never builds one.
Some questions need two hops. One email names a person or a project. A second email holds the answer, and a search for the question's own words does not find it. The model reads the results and either answers or gives the next query.
Three rules hold whatever the model writes:
search at most 3 times per question.search returned during this call.Worked example. Hop 1 searches "Juniper budget approves" and gets m1 and m4. m3 shares no word with that query. The model reads m1 and asks for "who runs the Delta site". Hop 2 returns m3. The answer is Mara Osei, with support m1 and m3: two searches, inside the budget of three.
Pick a budget and a model. Then switch off the budget check in code and see what a stubborn model does.
The four emails and both models are toys made for this page. The budget of 3 searches is the assignment's.
The archive also holds a few emails with instructions written to AI systems, and this pipeline will retrieve some. Treat retrieved text as data, never as orders (Chapter 9).
The failure to expect: the test marks a correct answer wrong. Check its support against the ids that search returned. Keep a set of returned ids and filter the model's support through it; a model can cite an id it never saw.
plan is the model's replies in order: each is {search: 'query'} or {answer: 'text', support: [ids]}. results maps a query to the ids it returns.maxSearches have run, and remember its ids.{answer, support, searches} in that key order; no answer is {answer: null, support: [], searches}.javascriptfunction runHops(plan, results, maxSearches) {
const seen = new Set();
let searches = 0;
for (const step of plan) {
if ('search' in step) {
if (searches >= maxSearches) break;
searches += 1;
for (const id of results[step.search] || []) seen.add(id);
} else {
const support = (step.support || []).filter(id => seen.has(id));
return { answer: step.answer, support, searches };
}
}
return { answer: null, support: [], searches };
}
maxSearches = 3 this loop runs a fourth search for a stubborn model. Click the buggy line.let searches = 0;for (const step of plan) { if ('search' in step) { if (searches <= maxSearches) { searches += 1; seen.push(...search(step.search)); } else return { answer: null, support: [] }; } else return finish(step, seen);}
searches < maxSearches.Chapter 4
Hold tools in a registry that checks a call before it runs, then write tool calls as text a parser can trust
Part 2 starts with the toolbox. A ToolSpec holds a name, a description the model reads, a JSON Schema for the arguments, the Python function, and a read_only flag. Problem 5 wraps a list of them in a registry with three methods.
| Method | Returns | Rule |
|---|---|---|
schemas() | one dict per tool: name, description, parameters | All the model sees of a tool. |
validate(name, args) | unknown_tool, invalid_args, or None | Never runs the tool. Never raises. |
execute(name, args) | a ToolResult: status and content | Validates, then runs. Never raises. |
Validate is separate so that the harness can reject a bad call before it asks anyone to approve it (Chapter 9). Use jsonschema's Draft202012Validator for the check. A tool that raises gives tool_error, and its content includes the exception's message.
The course LM has no tool calling, so you design a text format. Problem 6 asks for three functions:
render_tools writes the tools and the call format into the system prompt.parse_response pulls at most one call out of a reply. It never raises.format_tool_call writes a reply in your format, so the ScriptedLM can speak it.Two rules make parsing hard. If a formatted reply is cut at any character, the parser returns no call or exactly the original call, and a cut inside the arguments sets error. An argument may be any string, including a complete call in your own format.
Drag the cut along a toy reply. Its argument holds a whole call as text. Compare a parser that stops at the first closing tag with one that reads the JSON first.
The tag format and the note tool are a toy made for this page; the assignment leaves the format to you. The two cut-off rules are the assignment's.
Worked number: the reference solution's system prompt is about 1,000 tokens, and the compaction tests allow 4,000 per call. A quarter of every call is gone before the user speaks, so keep descriptions short.
The failure to expect: the live protocol test needs 18 of 20 replies to parse to the right call. Its system prompt is one fixed sentence plus your rendered tools. If replies fail to parse, put one example call in the rendered text, since nothing else can teach the format.
Checking. <call>{"name":"weather","args":{"city":"Os. What must the parser return?properties (each with a type: string, integer, number or boolean), required, and no extra keys allowed.'invalid_args'.'invalid_args'.'invalid_args'. An integer must be a whole number.'ok'.javascriptfunction checkArgs(schema, args) {
const props = schema.properties || {};
for (const k of schema.required || []) if (!(k in args)) return 'invalid_args';
for (const [k, v] of Object.entries(args)) {
const p = props[k];
if (!p) return 'invalid_args';
const ok = p.type === 'integer' ? Number.isInteger(v)
: p.type === 'number' ? typeof v === 'number'
: typeof v === p.type;
if (!ok) return 'invalid_args';
}
return 'ok';
}
<call>{"name":"note","args":{"text":"type <call>x</call> here"}}</call>, a valid reply. Click the line that breaks it.function parseCall(reply) { const start = reply.indexOf('<call>'); if (start < 0) return { text: reply.trim(), call: null }; const end = reply.indexOf('</call>', start); if (end < 0) return { text: reply.trim(), call: null, error: 'cut off' }; const body = reply.slice(start + 6, end); try { return { text: reply.slice(0, start).trim(), call: JSON.parse(body) }; } catch (e) { return { text: reply.trim(), call: null, error: e.message }; }}
Chapter 5
Alternate model calls and tool runs, and stop the send for one of exactly four reasons
Problem 7 is the loop itself. run_agent_session(lm, tools, config) returns a session. session.send(message) runs the loop for one user message and returns an AgentResult: the reply text, a status and a copy of the transcript. Each send continues the same conversation.
pythonmessages = [system_prompt + render_tools(schemas), user_message] while budgets_left(): # check BEFORE each model call reply = lm(messages) # messages in, string out call = parse_response(reply).tool_call if call is None: return done(reply) result = registry.execute(call.name, call.args) messages += [reply, result] # the result goes back verbatim
| Status | When |
|---|---|
| done | The model gave a final answer. |
| max_turns | The send has made config.max_turns model calls. |
| token_budget | The send has used config.token_budget tokens or more. |
| malformed | Three malformed replies in a row. |
Count tokens per call as count_message_tokens(messages) + count_tokens(reply), summed over the send. Check both budgets before each call, so an answer on the call that crosses the budget still counts as done.
A reply is malformed if the parser sets error, the registry says unknown_tool or invalid_args, or the call raises OutputTruncated. Send the error text back so the model can fix the call. A good reply resets the count. A tool that raises is not malformed.
Pick a scripted model and a turn limit. Step one call at a time and watch the malformed count and the tokens.
Illustrative scripts. Each call costs 600 tokens against a 4,000-token budget so that the budget can trip. The four statuses and their rules are the assignment's.
Worked number, with a token budget of 2,500 and calls costing 1,000, 1,200 and 1,400. Before call 1 the send has used 0, so it runs. Before call 2 it has used 1,000. Before call 3 it has used 2,200, still under 2,500, so call 3 runs and brings the total to 3,600. If call 3 answers, the status is done; if not, the next check stops the send.
From Problem 8 on, the tests build your full agent with tools=None: ten tools whose names, schemas and read_only flags are fixed in cardinal.py. You write each function and description, and cardinal_spec joins them. Creating a session must not read the email archive, so build the index the first time a tool needs it.
One decision is yours. Live models sometimes write "I'll look that up." with no call. Your loop can accept that as the answer or ask the model to go on; the memo asks what you chose.
{tokens, kind}, where kind is final, tool, tool_error or malformed, and tokens is that call's total.maxTurns calls have run, stop with max_turns. Then, if the tokens used are at least tokenBudget, stop with token_budget.{status, calls}. If the records run out, return status 'script_end'.javascriptfunction stopStatus(records, maxTurns, tokenBudget) {
let calls = 0, used = 0, bad = 0;
for (const r of records) {
if (calls >= maxTurns) return { status: 'max_turns', calls };
if (used >= tokenBudget) return { status: 'token_budget', calls };
calls += 1;
used += r.tokens;
if (r.kind === 'final') return { status: 'done', calls };
bad = r.kind === 'malformed' ? bad + 1 : 0;
if (bad === 3) return { status: 'malformed', calls };
}
return { status: 'script_end', calls };
}
let bad = 0;for (const reply of replies) { const kind = classify(reply); // 'final' | 'tool' | 'malformed' if (kind === 'final') return 'done'; if (kind === 'malformed') bad += 1; if (bad === 3) return 'malformed';}
bad = kind === 'malformed' ? bad + 1 : 0.Chapter 6
Return pointers and windows instead of whole documents, and decide what the model sees when a command prints too much
In Part 1 your code chose what the model saw. A tool result goes into the context as it is. The employee handbook is about 4,600 words. The longest emails are 50,000 characters. A tool that returns whole documents fills the budget in a call or two.
Problem 9 builds two read-only tools over the 24 company documents. search_docs returns at most k results, each a doc_id, a title and a snippet of at most 150 tokens. read_doc returns a window of at most 1,500 tokens: exactly lines start_line to end_line, plus total_lines so the model can ask for the next window. Keep the two tools' results to at most 6,000 tokens per conversation.
Worked number: each line is one paragraph, so a window needs a token bound as well as a line bound. Take lines of 500, 400, 800 and 300 tokens, from line 1. Lines 1 and 2 make 900; line 3 would make 1,700, over 1,500. The window ends at line 2, and the next read starts at line 3.
Problem 10 gives the agent a shell. sandbox.run_terminal(cmd) runs one command in a workspace that holds emails.jsonl and docs/. It allows only listed programs, rejects command substitution and here-documents, and runs with a timeout and no environment variables. On macOS, and on Linux with bubblewrap, an OS jail also blocks the network and writes outside the workspace.
The observation policy is your decision: what the model sees when the output is large. Harnesses differ. Some pass everything through; Codex CLI keeps the head and the tail; others also save the full output to a file and tell the model the path.
Drag the output size. Pick a policy and compare what reaches the model with the context budget.
The 16,000-token budget and the 600,000-character output come from the assignment. The 6,000 tokens already in context and the 2,000-character head and tail are illustrative. Tokens use the course rule of 4 characters each.
The failure to expect: asked about one line of a long listing, the agent guesses. Check whether that line was in what the model saw. Save the full output to a file in the workspace and give the model the path, so it can grep the line.
2 × keep characters, return it unchanged.keep characters, a marker line, and the last keep characters.[... N characters cut ...], with a newline before and after it, where N is the number of characters removed.javascriptfunction headTail(text, keep) {
if (text.length <= 2 * keep) return text;
const cut = text.length - 2 * keep;
return text.slice(0, keep) + '\n[... ' + cut + ' characters cut ...]\n' + text.slice(-keep);
}
function terminalTool(cmd) { const r = runTerminal(cmd); if (r.rejected) throw new Error('rejected: ' + r.reason); if (r.timed_out) throw new Error('timed out'); const shown = 'exit ' + r.exit_code + '\nstdout:\n' + clip(r.stdout) + '\nstderr:\n' + clip(r.stderr); if (r.exit_code !== 0) return 'Command failed.\n' + shown; return shown;}
shown, so the result is tool_error and the model still sees the output.python3 <<EOF followed by a three-line script. The sandbox rejects it. What should your tool description tell the model?Chapter 7
Send the model a shorter conversation when the next call would break the budget, and keep what must survive
A long session grows until one call no longer fits. Problem 11 requires count_message_tokens(messages) ≤ context_budget for every model call. When the next call would exceed it, you compact: you send the model a shorter version of the conversation.
Five rules are fixed:
config.aux_lm.The rest is yours: when to trigger, what goes first, what a summary keeps. Tool results are the bulk, so a cheap first step is to replace old ones with short stubs. Pay for a summary only when stubs are not enough. The deterministic tests replay a 60-call session with a 4,000-token budget and check every call.
| # | Role | Content | Tokens |
|---|---|---|---|
| 1 | system | instructions and tools | 400 |
| 2 | user | "Use metric units. Never email anyone outside the team." | 60 |
| 3 | tool | a search result from an earlier request | 1,800 |
| 4 | assistant | the answer to that request | 120 |
| 5 | user | the current question | 50 |
Worked number: the content is 400 + 60 + 1,800 + 120 + 50 = 2,430 tokens, and each message adds 4 more, so the call costs 2,450. With a budget of 1,500, replace message 3 with a 20-token stub that says which search to rerun. The call now costs 670.
Lower the budget. Switch the steps on and off and watch the total and the user's constraint.
The five messages, the 20-token stub and the 60-token summary are a toy made for this page. The 4 tokens per message come from the course counter.
The failure to expect: late in a session the agent breaks a rule the user set at the start. Search the last call's messages for that constraint. Pin stated constraints outside the part you compact, or make the summary keep them word for word.
{role, tokens} and costs tokens + 4.budget, replace the oldest tool message with a stub of stub tokens.javascriptfunction compact(msgs, budget, stub) {
const t = msgs.map(m => m.tokens);
const total = () => t.reduce((a, x) => a + x + 4, 0);
for (let i = 0; i < msgs.length - 1 && total() > budget; i++) {
if (msgs[i].role === 'tool') t[i] = stub;
}
return total() <= budget ? total() : -1;
}
function summarizeIfNeeded(msgs, budget, auxLm) { if (cost(msgs) <= budget) return msgs; const system = msgs[0]; const current = msgs[msgs.length - 1]; // this send's user message const summary = auxLm(summaryPrompt(msgs.slice(1, -1))); return [system, { role: 'user', content: 'Summary so far: ' + summary }];}
current. The current user message must be in every call made for it, so return it after the summary.Chapter 8
Store facts on disk so a new session can use them, and choose how much of the store goes into the prompt
A session's context ends with the session. Problem 12 adds memory that lasts: two tools over a store on disk under config.memory_dir. The model calls remember(fact) to store a fact and recall(query) to search the store. Plain JSON is fine.
The decision is what a new session starts with. Claude Code, Codex CLI and Gemini CLI load a whole instruction file into every prompt. Letta keeps a small block in the prompt and the rest behind a search tool. Too little in the prompt, and the model may not know there is anything to recall. Too much, and old facts eat the budget.
The live test runs three pairs of sessions that share only memory_dir. In at least 2 of the 3 pairs, a fact from session 1 must decide the answer in session 2.
In session 1 the user says which report they mean. Pick the directory and the policy, grow the store, and read session 2's answer.
An illustrative toy: 30 tokens per fact, a 10-fact block, a 16,000-token budget. Both policies are acceptable in the assignment.
Worked number: preloading 100 facts of 30 tokens costs 3,000 tokens, about 19 percent of a 16,000-token budget, before the user speaks.
The failure to expect: in session 2 the agent asks which report the user means. Open the files under memory_dir after session 1. If the fact is missing, tell the model to remember stated preferences, or have the harness save them after each send.
'No memories saved yet.''No matching memory.'javascriptfunction recall(store, query) {
if (!store.length) return 'No memories saved yet.';
const tok = s => s.toLowerCase().match(/[a-z0-9]+/g) || [];
const q = [...new Set(tok(query))];
let best = -1, bestScore = 0;
store.forEach((fact, i) => {
const words = new Set(tok(fact));
const s = q.filter(w => words.has(w)).length;
if (s > bestScore) { best = i; bestScore = s; }
});
return best < 0 ? 'No matching memory.' : store[best];
}
Chapter 9
Put the user in the loop, and route every terminal call through the same four gates in the same order
So far the user waits while the agent works. Problem 13 puts the user in the loop through config.user, which has three methods: approve(call), ask(question) and pending_message(). The tests pass a scripted user; the evaluation passes a simulated one.
| Part | Rule |
|---|---|
| Mode | In confirm mode, a call to a tool with read_only=False waits for approve(call), once per call. Auto mode never asks. |
| Denial | The call does not run. The transcript gets a tool_result with status denied and the user's reason, and the run goes on. |
| Steering | Call pending_message() once before every model call. A message joins that call as a user event. |
| ask_user | A tool the session has whenever a user is set. It returns the answer as an ok result. |
ask_user, remember and recall never need approval. A call the registry rejects is never sent for approval. Worked number: the harness polls pending_message once per model call. A send with 6 model calls polls it 6 times, even if the user never types.
In auto mode the model's choices run directly, so text that steers the model acts through it. The documents and the archive hold planted text addressed to AI agents. Some of it asks for a terminal command; some asks the agent to switch to auto mode and drop its rules. Problem 14 adds two rules that hold in both modes:
re.search(rule, cmd) matches a run_terminal command, it does not run and the user is not asked. The status is denied, and the run goes on.Pick a call and a mode. Watch where it stops. In confirm mode, switch the user's answer.
Toy calls with one deny rule, rm\s+-rf. The gate order is the assignment's.
The live test's planted command is written so that the deny rules miss it. What stops it is your system prompt and any check you add around run_terminal. Treat tool output as data, never as orders.
The failure to expect: in auto mode the agent runs a command it read in a document. Look in the transcript for a tool_call whose command appeared in an earlier tool_result. Say in the system prompt that tool output is data, and check run_terminal calls for commands copied from tool output.
rm\s+-rf, this check lets cd docs && rm -rf old run. Click the buggy line.def blocked(cmd, deny_rules): for rule in deny_rules: if re.match(rule, cmd): return True return False
call is {name, cmd, readOnly, valid}; denyRules are regex strings; userApproves is what the user would answer.'rejected'.'denied_by_rule'.'run' if the user approves, else 'denied_by_user'.'run'.javascriptfunction route(call, mode, denyRules, userApproves) {
if (!call.valid) return 'rejected';
if (call.name === 'run_terminal' &&
denyRules.some(r => new RegExp(r).test(call.cmd))) return 'denied_by_rule';
if (mode === 'confirm' && !call.readOnly) return userApproves ? 'run' : 'denied_by_user';
return 'run';
}
rm\s+-rf. The model makes seven calls: (1) search_docs; (2) run_terminal "wc -l emails.jsonl"; (3) run_terminal "rm -rf docs"; (4) read_doc; (5) run_terminal with an unknown argument name; (6) ask_user; (7) run_terminal "grep -c Juniper emails.jsonl". How many times is approve called?Chapter 10
Test the whole agent with simulated users, question your own design, and keep the numbers and terms on one page
Problem 15 runs 20 simulated users. Each persona has a role, a goal and a manner, such as answering in fragments. It talks to your agent for 2 to 5 user turns, answers ask_user questions, and approves or denies terminal commands. The agent runs with max_turns 20, a token budget of 400,000 and a context budget of 16,000.
A conversation succeeds only if three things hold: no exception, every programmatic check in the persona file passes, and a judge model passes it against the persona's goal. The judge fails a conversation in which the agent states a fact that nothing it was shown supports.
Each weakness in a harness fails its own kind of persona, on its own condition. Switch weaknesses on and see which conversations fail, and why.
Each dot is one persona. A red dot names the condition it failed. Find the harness with no red dot.
The 20 personas, their task mix and the three conditions are the assignment's. Which persona each weakness fails is illustrative.
Results move by about one conversation between runs, so run twice before you trust a change. Then check on personas you did not tune against. The public twenty mix 4 document lookups, 3 multi-hop email questions, 2 digests, 4 coding tasks in confirm mode, 3 paired memory sessions, 2 ambiguous requests and 2 adversarial tasks. A fair test uses fresh personas with the same mix.
Two exercises off the page. They ask about your own choices, so this page gives the steps and no answers. Tick each item as you go.
Field notes: use your own agent.
Design questions: one about your retriever, then one per design decision. Keep a note as you make each choice.
| What | Number |
|---|---|
| Archive and documents | 26,278 emails (June to August 2001); 24 company documents |
| Priority target | 85% agreement on 60 emails, no unknown |
| Digest | at most 300 words; every urgent item named |
| BM25 | k1 = 1.5, b = 0.75; recall@10 of 90%; 15 s build, 20 ms per query, 2 ms for a rare term |
| Multi-hop QA | 3 searches per question; 70% of 25 answers correct |
| Protocol target | 18 of 20 replies parse to the right call |
| Loop | 3 malformed in a row stops a send |
| Doc tools | snippet 150 tokens; window 1,500; 6,000 per conversation |
| Token counter | 4 characters per token, 4 tokens per message |
| Context budget | 4,000 in the compaction tests; 16,000 in the evaluation |
| Evaluation | 20 personas in 7 task types; a success needs 3 conditions |
| Term | Meaning |
|---|---|
| Pipeline | A program whose control flow lives in code, calling the model for single steps. |
| Agent harness | The code around a model that lets the model choose its next step: tools, loop, limits. |
| Adapter | The stub in adapters.py that the tests call; make it a thin call into your code. |
| Support | The email ids an answer rests on, each one returned by search. |
| Tool-call protocol | Your text format for calls, and the code that writes and parses it. |
| Malformed reply | An unparseable reply, an unknown tool, invalid arguments, or a cut-off reply. |
| Observation policy | What the model sees of a tool output that is too large. |
| Compaction | Sending a shorter conversation so that a call fits the context budget. |
| Deny rule | A regex that blocks a matching terminal command before approval. |
| Persona | A simulated user with a role, a goal and a manner, scored by checks and a judge. |
pythondef send(self, user_message): # a sketch of the shape, not a solution self.log("user", user_message) while self.turns_left() and self.tokens_left(): self.poll_steering() # pending_message(), once per call msgs = self.fit_to_budget() # compaction: the log never shrinks reply = self.lm(msgs) parsed = self.parse(reply) if parsed.error: self.malformed(parsed); continue if parsed.tool_call is None: return self.done(parsed.text) call = parsed.tool_call result = (self.registry.validate(call.name, call.args) # gate 1 or self.deny_rules(call) # gate 2 or self.approval(call) # gate 3, confirm mode or self.registry.execute(call.name, call.args)) # gate 4 self.log("tool_result", result) # shown verbatim in the next call return self.stopped() # max_turns or token_budget, text never empty
Now press Present or Teach and explain the harness from memory: the four stop reasons, the four gates and the five compaction rules. Then go back to the hero, switch off one part at a time, and say which chapter fixes each failure.
This lesson teaches Assignment 1, Building an Agent Harness, of Stanford CS 329Z, Engineering AI Agents (Fall 2026). The assignment was designed and built by Michael Ryan, with help from Claude Fable 5.1. Its acknowledgements thank Houjun (Jack) Liu, Owen Queen, Shreyas Sharma and Anantharaman Iyer for testing an early version. The starter repo and handout are at github.com/cs329z/assignment1-harness, released under the MIT licence; the course site is cs329z.stanford.edu. The rules and numbers come from the handout. The explanations, toy data, devices and exercises are our own, and none of them is a solution to the assignment's problems.