In this section

0.1 How an Agent Works

Module 0

Introduction

Every component this course builds that uses a model, the hunting agent of Module 1, the incident response agent of Module 5, the red-team pipeline of Module 10, is an agent or part of one, and every agent is the same small machine underneath. A program sends a model some text. The model sends text back.

Some of that text asks for a tool to be run, and the program decides whether to run it, runs it, and sends the result back as more text. That is all an agent is, and most of what goes wrong with agents, and most of what this course secures, follows from it.

This lesson builds that machine from nothing. It starts with one model call and what it does and does not remember, then has an assistant write a minimal agent loop against a stated contract, checks it, and traces a real run step by step, accounting for every message the model was sent.

Two measurements close the lesson: what happens when a loop tries to save tokens by sending less, and how the cost of a loop grows with every step it takes.

The exercises run in the SEC410 lab on your own machine. If it is not installed yet, follow Installing the Lab first and run Verify the Lab; every check in this course should fail as shipped, and for the reason its lesson fixes.

System: the parts of an agentyour code: the loopConversationsystem, user, assistant and tool messagesLooprun(), max_stepsStep recordsmessages, tokensmodel providerModelcomplete(messages, tool names)tools in this processTool functionstools[name](**args) returns a dict1234The reply picks the tool;the loop decides if it may run.data flowboundary1whole conversation sent2text or tool calls3tool run by name4result appended

The loop is the only part with state. The model sees the whole conversation on every call and returns text or tool calls; the loop runs the tools and appends their results.

1

One Model Call

Text in, text out, nothing remembered

Here is a single call to the lab's model, with a system prompt and one of Module 1's hunts as the request, followed by the same call made again and a third call that sends a request with no history.

$ python3 call_once.py
text       ''
tool calls [{"tool": "query", "args": {"table": "signin", "where":
           {"result": "failure"}, "group_by": ["src_ip"]}}]
usage      {'input_tokens': 28, 'output_tokens': 70}
same again True
no history 'I do not have a plan for that request.' []

The reply has no text and one tool call: a query against the sign-in table for failed sign-ins, counted by source address. The model has not run that query and cannot. It has written a description of a query it would like run, as structured text, and returned it.

Whether the query runs, against what data, with what permissions, is decided by the program that receives the reply. That separation is the most important fact in this course. A model's output is a request. Everything it can make happen, it makes happen through code someone else wrote.

The second call was sent the identical conversation and returned the identical reply. The lab's model is deterministic by design, so that exercises can be graded; a real model generally is not, and the same conversation can produce different replies on different runs, which is why Module 1 measures agents across repeated trials.

The third call shows the property that matters for building a loop. Sent a request with no history, the model has no idea what hunt it was working on. It keeps nothing between calls. The only memory an agent has is the conversation its program chooses to send.

Real model interfaces work the same way. In Anthropic's tool use documentation, a tool the application defines runs in the application: the model's reply ends with a tool-use stop reason and one or more tool-use blocks, the application runs the operation, and returns the output in a tool-result block.

The documentation's own multi-turn example then appends the model's reply and the tool result to its local list of messages and sends the whole list again on the next request.

The conversation is a list of messages, each with a role, and the roles are conventions the program and the model share rather than anything the model enforces. The system message is the program's standing instructions. A user message is the request. An assistant message is something the model said earlier. A tool message is a result the program produced.

The model is trained to weight them differently, to follow system instructions, to answer the user, to treat tool results as information, but it receives all of them as text in one input. Nothing stops a tool result from containing text that reads like an instruction, which is the root of the injection problems in Modules 1, 3 and 5.

2

The Contract

What the loop must do, stated before it is written

Module 0's exercises are small files in the lab's foundations folder, each with a docstring that states exactly what the code must do and a check that tests it. Here is the first.

Visual Studio Codeloop.py - sec410-lab
loop.py
lab › foundations › loop.py
1"""Lesson 0.1: a minimal agent loop. This file is the exercise: replace the body of run().23An agent is a loop around a model call. Each call sends the whole conversation so far, because the model keeps nothing4between calls. The model replies with text, tool calls, or both. The loop runs each tool call, adds the call and its5result to the conversation, and calls the model again, until the model replies with no tool calls or the step limit is6reached.78Contract, checked by `python -m lab check f01`:910    run(model, task, tools, max_steps=6) -> {'text': str, 'steps': [step, ...]}1112    model       has complete(messages, tool_names) -> {'text', 'tool_calls': [{'tool', 'args'}], 'usage'}13    task        the user's request, a string14    tools       {name: function}; call a tool as tools[name](**args); it returns a dict15    max_steps   the most model calls the loop may make1617    messages    a list of {'role': 'system' | 'user' | 'assistant' | 'tool', 'content': str}; a tool message also18                carries 'name', and its content is the tool's result as JSON19    step        one per model call: {'messages': how many messages were sent, 'input_tokens': ..., 'output_tokens': ...,20                'tool_calls': [tool names called]}21    text        the model's last text reply, '' if the step limit ended the loop first22"""2324SYSTEM = 'You are a security agent. Use the tools to answer the request, then reply with your answer.'252627def run(model, task, tools, max_steps=6):28    raise NotImplementedError('lesson 0.1: write the loop')
mainPythonUTF-8Ln 32, Col 5
The exercise: a docstring that states the contract, and a body you write.

The contract fixes the shape of everything: what the function receives, what it returns, how messages are structured, and what a step records. It is written before the code for the same reason a hunt's answer is written before the agent runs: so that whether the code works is a question the check can answer rather than an opinion.

Notice what the contract does not say: it says nothing about how the loop is written, which variables it uses or whether it is a for loop or a while loop. It describes behavior the check can observe from outside. That is what lets the check grade any correct implementation, yours, an assistant's or the reference solution, and it is how every exercise in the course is specified.

Run the check against the file as shipped.

$ python3 -m lab check f01
f01  0.1 How an Agent Works: lab/foundations/loop.py
FAIL  run() is written
      lesson 0.1: write the loop
FAIL

The check reports what it needs and stops, naming the first property it could not test because the function does not exist yet. Every exercise in this course works the same way: the code you are given fails its check, and the work is making it pass without changing the check.

The contract also settles three decisions every agent loop has to make. The first is what the model is told it can do: the loop passes the names of the tools it offers, and nothing else is available.

The second is how a tool's result goes back: as a message of its own, marked as a tool result, carrying the tool's name and the result as JSON, so the model can tell the result apart from the request and from its own earlier replies.

The third is when to stop: when the model replies without asking for a tool, or when a fixed number of steps has run. Each of those decisions is one of the places where Module 1 finds an agent failing.

Before the brief, here is the procedure the contract describes, drawn as the steps and decisions the code has to make.

Procedure: one run of the agent loopStart: a system messageand the taskCall the model with thewhole conversationThe model keeps nothingbetween calls.Record the step: messages,tokens, tools calledTool calls in the reply?noReturn the last textyesAppend the calls; runeach tool by nameUnknown tool: an errorresult, not a crash.Append each result asa tool messageUnder the step limit?yesNext stepnoStop: text is empty;return the stepsstepdecisionnotestops or failsbranch ends

The loop calls the model with everything so far, runs any tools it asked for, appends the results and calls again, until a reply asks for no tools or the step limit ends the run.

Keep it open while reading the draft: each decision in the diagram should appear as a condition in the code, and each side branch as a case the check can test.

3

Session: The Brief

Write the loop to the contract

The brief is three sentences, because the contract is already in the file.

SEC410 lab, lesson 0.12026-11-18
loop.pyPY

Write run() in the attached file. The contract is in its docstring. Plain Python, no agent framework, as short as it can be while meeting the contract. Don't change the contract or the system prompt.

loop.pyCode · PY · 45 linesDownload
Reply to Claude…Opus 5.5
Recorded unedited in assistant-records/m00/0.1-brief.md

When the specification lives in the file, the brief's job is to set constraints the file does not: no framework, as short as the contract allows, and the contract and system prompt left alone. Those constraints matter more than they look.

An assistant asked for an agent will often reach for a framework, and a framework hides the loop this lesson exists to show. An assistant asked to meet a test will sometimes change the test, and the last sentence rules that out before it can happen.

4

The Draft

Twenty-three lines

The reply was the file. Here is the code below the docstring.

Visual Studio Codeloop.py - sec410-lab
loop.py
lab › foundations › loop.py
23import json2425SYSTEM = 'You are a security agent. Use the tools to answer the request, then reply with your answer.'262728def run(model, task, tools, max_steps=6):29    messages = [{'role': 'system', 'content': SYSTEM}, {'role': 'user', 'content': task}]30    steps, text = [], ''31    for _ in range(max_steps):32        out = model.complete(messages, list(tools))33        usage = out.get('usage', {})34        calls = out.get('tool_calls') or []35        steps.append({'messages': len(messages), 'input_tokens': usage.get('input_tokens', 0),36                      'output_tokens': usage.get('output_tokens', 0), 'tool_calls': [c['tool'] for c in calls]})37        text = out.get('text', '')38        if not calls:39            return {'text': text, 'steps': steps}40        messages.append({'role': 'assistant', 'content': json.dumps(calls)})41        for call in calls:42            fn = tools.get(call['tool'])43            result = fn(**call.get('args', {})) if fn else {'error': f"no tool {call['tool']}"}44            messages.append({'role': 'tool', 'name': call['tool'], 'content': json.dumps(result)})45    return {'text': '', 'steps': steps}
mainPythonUTF-8Ln 1, Col 1
The draft: 23 lines, one model call per step, every tool result appended before the next call.

The draft starts the conversation with the system prompt and the request, then loops up to the step limit. Each step sends the whole message list to the model with the names of the offered tools, records the step's message count and tokens, and stops if the reply asks for no tools.

Otherwise it appends the reply's tool calls as an assistant message, runs each call, and appends each result as a tool message named after the tool. If the limit runs out first, it returns an empty answer and the steps it took.

The two lines that make it an agent are the call that sends the whole list and the line that appends each result. Everything else is bookkeeping.

Read the line that runs a tool closely, because it is where authority lives: it looks the requested name up in the tools the loop was given, and an unknown name gets an error instead of running anything. The model cannot run a tool the loop does not have.

Reading an assistant's draft against a contract is a skill worth practicing on something this small. Take each clause of the docstring and find the line that satisfies it: the whole conversation sent, one step per call, the tool message's name and JSON content, the stop conditions, the empty answer when the limit runs out.

A clause with no line is a defect, whatever the check says, and a line that serves no clause is something the assistant added that you did not ask for. This draft has a line for every clause and nothing extra, which is not always the case and is worth confirming rather than assuming.

5

The Check, and the Trace

Every message accounted for

Run the check against the draft, copied into the lab's foundations folder.

$ cp records/loop-0.1.py lab/foundations/loop.py
$ python3 -m lab check f01
f01  0.1 How an Agent Works: lab/foundations/loop.py
ok    H2 ends in a report naming the address and the account
      203.0.113.45, j.ortiz
ok    one step recorded per model call
      4 steps, 4 calls
ok    every call is sent the whole conversation so far
      messages sent: 2, 4, 6, 8
ok    tool results go back as tool messages with a name and JSON content
      3 tool messages
ok    each step records its tokens
      input tokens: 44, 261, 292, 327
ok    the step limit ends a loop that never stops
      4 model calls with max_steps=4
PASS

All six properties hold. The check ran the loop against H2 and found the right answer; recorded the conversation the model was sent on every call and confirmed each one contained the previous one in full; confirmed the tool results went back as named tool messages; and ran the loop against a model that never stops asking for tools, which the step limit ended at exactly four calls.

The check confirms properties. The trace shows what they look like. This script runs the same hunt and prints each step, then every message in the conversation the model received on its last call.

$ cp records/loop-0.1.py lab/foundations/loop.py
$ python3 trace.py
[1] sent 2 messages,   44 tokens in,  70 out, calls ['query']
[2] sent 4 messages,  261 tokens in,  70 out, calls ['query']
[3] sent 6 messages,  292 tokens in,  70 out, calls ['query']
[4] sent 8 messages,  327 tokens in,  53 out, calls -
the last call was sent:
  system              91 chars  You are a security agent. Use the tool
  user               101 chars  Hunt H2: password spraying against our
  assistant          104 chars  [{"tool": "query", "args": {"table": "
  tool      query   2011 chars  {"rows": [{"src_ip": "203.0.113.45", "
  assistant          109 chars  [{"tool": "query", "args": {"table": "
  tool      query     95 chars  {"error": "unknown field IPAddress in 
  assistant          106 chars  [{"tool": "query", "args": {"table": "
  tool      query    171 chars  {"rows": [{"id": "s-00316", "ts": "202

Read the bottom half as an inventory. The system prompt is the program's. The request is the user's. Each assistant message is the model's own earlier reply, sent back to it so it knows what it asked for. Each tool message is a result the program produced by running a tool the model requested. Nothing the model receives arrives any other way.

That inventory is the foundation for most of the security work in this course: a prompt injection is text an attacker gets into one of those messages, usually a tool result; an invented finding is a claim in the model's reply with no tool result behind it; an unauthorized action is a tool call the loop should never have run.

The third call fixed a mistake made by the second. The model's first follow-up query used a field the sign-in table does not have; the test tool returned an error naming the valid fields; the model read the error in its next call and corrected the query.

The loop did nothing special to make that happen. It sent the error back like any other result, and the model used it. Module 1 builds on exactly this: an error that says what is valid is information the model can act on, and one that does not is a loop waiting to happen.

The token counts tell the same story from the other side. The first call cost 44 input tokens, a system prompt and a one-line request. The second cost 261, because it carried the first query's result, a stack of source addresses running to two thousand characters.

The rest grew more slowly because their results were small. A model call's cost is set almost entirely by what the conversation holds, and what it holds is mostly tool results.

6

Sending Less, Measured

A loop that forgets the request

Every call sends the whole conversation, and the conversation grows, so the obvious economy is to send less. Here is a version that sends the system prompt and only the latest exchange.

Visual Studio Codeloop.py (Working Tree) - sec410-lab
loop.py (Working Tree)
Source Control › Changes › lab/foundations/loop.py
31      for _ in range(max_steps):-         out = model.complete(messages, list(tools))32+         # Save tokens: send the system prompt and only the latest exchange.33+         out = model.complete(messages[:1] + messages[-2:], list(tools))34          usage = out.get('usage', {})
main*1 file changed
The shortcut: send the system prompt and the latest exchange only, to save tokens.

Run the check against it, the same six properties as before.

$ cp records/loop-short.py lab/foundations/loop.py
$ python3 -m lab check f01
f01  0.1 How an Agent Works: lab/foundations/loop.py
FAIL  H2 ends in a report naming the address and the account
      no findings
ok    one step recorded per model call
      2 steps, 2 calls
FAIL  every call is sent the whole conversation so far
      messages sent: 3, 3
ok    tool results go back as tool messages with a name and JSON content
      1 tool messages
ok    each step records its tokens
      input tokens: 66, 239
ok    the step limit ends a loop that never stops
      4 model calls with max_steps=4
FAIL

The hunt failed. On its second call the model received the system prompt, its own previous tool call and the result, but not the request, and with no hunt in front of it the lab's model had no plan to continue. The check also reports exactly why: the conversation sent on each call no longer contains the previous one.

A real model would fail less obviously and more dangerously. It might carry on, guess at what it had been asked, and produce an answer to a question nobody posed.

Trimming a conversation is a real technique, and long-running agents need it, but it is a design decision with consequences, not a free saving: whatever is trimmed, the model no longer knows. Systems that trim keep the request and the constraints, summarize old results rather than drop them, and are tested for what they forget.

The shortcut also shows a smaller lesson about hasty edits. On its first call the trimmed version sent three messages where the original sent two, because the system prompt was included once on its own and again as part of the last two messages.

The model received its instructions twice. Nothing broke here, but a change made to save tokens added some, and nobody would have noticed without a check that counted what was sent.

7

The Cost of a Step

Every call pays for the whole conversation

Sending everything has a price, and it grows. This script runs the draft against a model that asks for the same ten-row query on every call and never answers, for eight steps, and prints the input tokens each call was charged.

$ cp records/loop-0.1.py lab/foundations/loop.py
$ python3 cost.py
[1]  2 messages     24 tokens in      24 so far
[2]  4 messages    200 tokens in     224 so far
[3]  6 messages    375 tokens in     599 so far
[4]  8 messages    551 tokens in    1150 so far
[5] 10 messages    726 tokens in    1876 so far
[6] 12 messages    902 tokens in    2778 so far
[7] 14 messages   1077 tokens in    3855 so far
[8] 16 messages   1253 tokens in    5108 so far

The first call cost 24 input tokens. The eighth cost 1253, because by then the conversation held seven tool results, and every call pays for all of them again. Over eight steps the loop sent 5108 input tokens in total. Each step's cost grows with the length of the conversation, so the total grows faster than the number of steps: double the steps and the total more than doubles.

The lab's model estimates tokens from word counts, so the exact numbers are the lab's; a real model's tokenizer counts differently, but the shape is the same, and tool definitions themselves count as input tokens on real interfaces too.

This is why the step limit exists, and why Module 1 adds a token budget. A loop that keeps calling tools, through a bug, a confused model or an attacker's text, spends more on every step than on the last. The step limit bounds the damage. It does not prevent it, and a limit that is reached means the loop ended without an answer, which the caller has to handle.

The draft returns an empty answer in that case rather than raising an error, and the check confirms it ends after exactly the number of calls allowed. A caller that treats an empty answer as nothing found has turned a loop that ran out of steps into a clean result, which is the first failure Module 1 measures.

Results are the expensive part. A query that returns fifty rows adds all fifty to every later call. Much of Module 1's design, counting by group instead of listing rows, saying when a result is partial, keeping results short, is cost control as much as correctness.

The arithmetic is worth having in your head. If every step adds a result of roughly the same size, the conversation grows by that size each step, and the total sent over a run is close to the size of one result times the square of the number of steps, halved.

Ten steps cost about fifty results' worth of input; twenty steps cost about two hundred. That is why a budget is set on tokens rather than on steps alone, and why a single oversized result early in a run is the most expensive thing an agent can receive.

8

From This Loop to Module 1

What the minimal loop leaves out

The draft meets its contract, and it is still a long way from an agent you would run. The review records what is missing.

Visual Studio Code0.1-session.md - sec410-lab
0.1-session.md
records › 0.1-session.md
1# Session 0.1: a minimal agent loop23Assistant: Claude Opus 5.5 (claude-opus-5-5), the SEC410 build session, 2026-11-1845## Held6- One model call per step, sent the whole conversation.7- The model's tool calls appended as an assistant message,8  each result as a tool message with its name, as JSON.9- Stops on a reply with no tool calls, or at max_steps.10- check f01: PASS, all six properties.1112## Measured13- Sending only the latest exchange broke the hunt: the model14  no longer saw the request and had no plan.15- Input tokens per call rose from 24 to 1253 over eight16  steps of an endless model: 5108 tokens in total.1718## For Module 119- An unknown tool returns an error the model cannot act on.20- A tool that raises ends the run with a traceback.
mainMarkdownUTF-8Ln 11, Col 1

Two gaps are visible already. A tool name the loop does not recognize gets an error saying only that there is no such tool, which tells the model nothing about what it can use instead. And a tool that raises an exception ends the whole run, because nothing catches it.

Module 1 starts from a loop like this one and closes those gaps and others: a stop rule for repeated failures, a token budget, validation of every argument before a tool runs, results that say what they left out, and an allowlist that keeps a hunt from acting.

Each fix is a change to a loop of this shape, and each one is easier to reason about because the loop is twenty-three lines you can read in full.

The same loop runs through the rest of the course. Module 4 moves the tools out of the program into a separate server reached over a protocol, so the line that runs a tool becomes a message to another process, with its own authorization question.

Module 5 puts an approval in front of that line for any tool that changes something. Module 10 attacks the loop through the tool results it appends. In each case the change lands on one of the few lines this lesson's draft contains, which is why it is worth knowing them by heart.

Do

Practice

A minimal agent loop
the lab

Brief your assistant with the contract and the constraints, then check its draft, run the trace and the cost script, and account for every message in the last call. Record the brief, the draft, every run and your review.

Visual Studio Code0.1.md - sec410-lab
0.1.md
practice › 0.1.md
1# Practice 0.1: a minimal agent loop23## Done when4- [ ] lab/foundations/loop.py meets its docstring's contract5- [ ] python -m lab check f01 prints PASS6- [ ] trace.py run; for the last call, every message sent is7      accounted for: who wrote it and why it is there8- [ ] cost.py run; tokens in per step recorded9- [ ] records/0.1-<assistant>.md: brief, draft, runs, review1011## Constraints12- No agent framework. The loop is yours to read in full.13- Do not edit the check or the contract.1415## Stretch16- Run trace.py with --model ollama:<name> wired in, and record17  how the real model's steps and token counts differ.
mainMarkdownUTF-8Ln 3, Col 1

A model call is text in and text out, with nothing remembered between calls. A tool call is a request in that text, and only the program decides whether it runs.

An agent is a loop that sends the whole conversation, runs the tools the reply asks for, appends their results, and stops when the reply asks for nothing or the step limit is reached. Sending less forgets what the model was asked; sending everything costs more on every step. Everything later in the course secures some part of this loop.