Week 1: The internals of coding agents
Learning objectives
By the end of this week, you can:
- LO1: explain a coding agent's loop, system prompt and tool definitions;
- LO1: predict a failure caused by missing context, invalid tool arguments or a stop condition, then test that prediction; and
- LO9: label a claim as observed or inferred, cite its evidence and revise your decision when a check supplies new information.
You need Python functions, dictionaries, basic tests and a terminal. The first session builds a minimal agent live and inspects a request. The second session is a studio using your own coding agent. A1 is due this week.
Minimal example
The course team wrote the examples in this lesson. The supplied session was written by hand. Your studio capture is the evidence from your own real agent run.
One repair from contract to regression
The requirement says to ignore surrounding whitespace and ASCII letter case, map
ok to passed, fail to failed, and other strings to unknown. A plausible
candidate is:
def status_label(raw):
return {"ok": "passed", "fail": "failed"}.get(raw.lower(), "unknown")
Generate: propose the smallest patch. Verify: before editing, derive the
expected result for " OK " from the requirement. It must be passed; the candidate
returns unknown. Adding .strip() before .lower() repairs that case. Keep the
checks for ordinary and unknown statuses as well. A patch that looks right still
needs a check that has run on the changed code.
Build the agent around a proposer
Open loop.py. It already contains checked, tool
and last_check. The function run() is left unfinished on purpose. To type along,
first make your draft copy with the two setup lines under
Finish and check the live loop. Then edit
week01-loop/loop.py, not the original. The model only proposes tool calls. The
controller runs the calls it permits and puts each result (an observation) into the
next request. In the live build, a scripted proposer stands in for the model. This
lets us inspect the loop without making a model request.
| Tool | Accepted arguments | What actually happens |
|---|---|---|
read |
path: result.txt |
Return the file's text |
write |
That path, plus text of at most 32 characters | Replace the file; return written |
bash |
command: verify |
Run a fixed check for the exact bytes 4\n |
Despite its name, bash does not accept arbitrary shell commands. For example,
echo 4 > result.txt is refused. This restriction is in the tool's code; a prompt
asking the model to be careful would not enforce it.
In class the instructor builds steps 1-3 of run() on screen, and you type along in
your copy. Steps 4 and 5 are yours. These are the five public steps that run() must
follow:
- Begin with a user message that holds the task, and an empty set of used call IDs.
- On each turn, send a copy of the history to the proposer. Before you execute any
call from its reply, apply
checked()and reject any call ID that was already used. - Append the assistant reply. If it has no tool calls, return the history and
final. - For every call, in order, execute
tool()and append onerole: toolmessage with that call's owntool_call_id. If a file is missing or a call times out, record a failed observation, so that the next request receives it. - When the turn budget runs out, return the history and
step_limit.
Generate: the scripted proposer reads the file, writes 4\n, asks for
verification and then sends a reply with no calls. Verify: the public checks
test what the controller actually did, separately from what the proposer said. A
successful scripted demonstration has this sequence:
| Proposed action | Tool observation |
|---|---|
c1: read result.txt |
5\n |
c2: write 4\n |
written |
c3: verify |
verified |
| final reply with no calls | Controller stops with final |
A second run writes 5\n instead. Its write still returns written, but the check
returns check_failed. The proposer can still stop with final. Whether the loop
finished and whether the change is correct are separate questions. A later write
also makes an earlier passing check stale (out of date). After that write,
last_check reports not_run until another check runs.
Read a real agent's instructions and your visible request
A request can carry system or developer instructions, user context, assistant calls and tool results. Tool definitions travel beside these messages. A tool definition names the operation, describes what it is for and declares the shape of its arguments. A system prompt describes the agent's role and workflow; it does not execute tests.
Source 1 and Source 2 are instruction and tool files that open-source agents have published, fixed at one version. Read one stopping instruction and one schema constraint. Then find the same parts in the requests that your own agent sends. In the studio, a small course recorder runs on 127.0.0.1 between your agent and its model service. It logs each request body. From this log you can count the requests, measure the system text and group the tools by kind. Source files describe the parts an agent can send. Only a captured request shows which parts one particular run actually sent. A transcript alone may leave out system messages or the request itself. If your agent cannot use the recorder, follow the A1 fallback and record that limit.
Practice the request-reading method with the supplied sample:
python3 lectures/week-02/session/show_session.py \
lectures/week-02/session/sample-session.jsonl --request 4
Change the number to read another request. Without --request, the same command
prints a short summary of all ten requests. Its first line says that the record is a
course-made sample, not a recording of a product.
Identify a role/goal instruction, a tool argument rule, a stopping rule and a request for caution. Find each call and the result that carries the same call ID. Request 4 proposes an edit, and request 5 carries its failed result. Request 6 shows a retry, and request 7 carries a failing test. Before you reveal each response, predict the next action. Finally, find the verification that supports the last response.
Observed: the record contains a particular call, result or instruction at a location you can cite. Inferred: you explain why it happened or what might happen next. An error message is observed. An explanation of the model's private reasoning is inferred. For this reading, use the questions in the request dissection and the prompt dissection. Both are optional Week 2 practice pages, and you only borrow their questions. This week's work is the studio and A1.
Hands-on exercise
Finish and check the live loop
Work from the root of your course checkout (the folder that holds lectures/ and
practice/) and make a fresh draft copy. demo.py imports a small model client from
the same folder. Even so, these commands run only scripted practice and make no
model request. Run these two lines once:
mkdir week01-loop
cp lectures/week-02/fixture/*.py week01-loop/
Do not run them again after you start editing. The cp line would copy the
unfinished starter back over your loop.py and demo.py.
The check is one command. Of the three commands, it is the only one you run again:
python3 week01-loop/verify_loop.py
Before you implement run(), expect a nonzero exit with the message Write run() in loop.py
first. Edit only the run() in your copy, following the five steps above. Then run
the check again. When the controller is complete, expect Ran 15 tests and OK.
Until then, the named failures tell you which behavior still needs work.
If the controller still fails at the class help checkpoint, trace one call/result pair on paper. Then complete the missing behavior and rerun the checks. After that, run the demonstration:
(cd week01-loop && python3 demo.py)
Expect a first line with generation: scripted-practice, stop_reason: final,
check: verified and eight messages. The two COURSE_ARTIFACT lines after it (one
of them long) are encoded copies of the two output files. You can ignore them.
Inspect completion.json and result.txt in your copy. In the copied demo.py,
change only CANDIDATE to "5\n". Predict the result, then rerun. Expect a nonzero
exit and check: check_failed. Save that result. Then restore "4\n" and rerun.
Do not use the fixture's hosted mode for this demonstration.
Studio: capture and read your own session
Follow the studio to create a fresh status-label task, record the requests of a real coding-agent session with a forced failing check, and verify the repair. Keep the original failure, the later check and a short explanation. At the revision checkpoint, check one observed claim against its citation and revise it if needed.
Use the safety practices in Tools and model access. Run the agent in a dedicated draft directory or container without employer or cloud credentials. The course provides seats or credit, so you do not pay. Treat the recorder's log like a file that holds credentials until you have checked it (setup).
Verification
Keep the verification tied to the candidate it tested:
- Loop: all public checks pass in your copied controller; wrong writes fail, denied calls have no effect, and every result matches its call ID.
- Request: from the capture, give the number of model requests, the size of the system text and the tools grouped by kind, and point to an instruction, a tool schema, a returned result and a stop. If a fallback record omits one, state that it was not visible.
- Studio: retain the baseline failure, the repaired check and a bounded diff (the studio page shows the command). A test on the untouched original fixture cannot verify your studio candidate.
- Decision: end A1 with accept, narrow, recheck or stop and the specific evidence supporting it. Keep one AI-use note with the work and reuse its ID.
The loop's turn budget guarantees a bound on requests. It does not prove that the agent made progress. It does not check that the result means what the task asked for. It also does not put a secure process boundary around Python code that can be edited. Keep these properties apart when you interpret a trace.
Common mistakes
| Mistake | Detection | Correction |
|---|---|---|
Treating written or final as correctness |
No current passing check | Run the check after the latest write |
| Losing a refused call | Next request has no result under that ID | Return the refusal as an observation |
| Reusing a call ID | Two different actions have the same identifier | Reject before effects and use fresh IDs |
| Treating a prompt rule as enforcement | No schema, tool check or runtime check stops a violation | Name the enforcing component or say it only asks |
| Claiming invisible system prompts were observed | Fallback record has only visible chat messages | Mark the request content unavailable |
| Sharing the capture log | Log file or a screenshot of it leaves your private directory | Cite the summary and checked excerpts |
| Counting calls as model requests | A response has several calls | Count request blocks separately |
| Calling scripted practice a real model run | Proposer is demo.scripted |
Preserve the actual generation mode |
| Accepting a stale passing test | Another write occurred afterward | Verify the current revision |