# How an AI agent works: build a tiny agent loop yourself

- Author: RomanMotion (https://wurk.fun/user/RomanMotion)
- Published: 2026-10-31
- Updated: 2026-11-03
- Canonical (HTML): https://wurk.fun/blog/how-an-ai-agent-works-build-a-tiny-agent-loop-yourself
- Cover image: https://ik.imagekit.io/wurk/browser-uploads/f1c626b5c17e7f0a61dfbbe7a20d85ae7b33a20527243aeec2ee1d0a8b87562a/badbb30b-9646-42f5-acb7-966c76b14ea4/cover-agent-loop-1031.jpg?wurkUpload=v1.zazDt4YCce0WlnjfHuJlKDv-DMelUoER1ME1ljtqS-M

---

You hand an agent a task, walk away, and come back to either a finished fix or an afternoon gone while the thing circled the same file four times. The gap between those two outcomes usually isn't the model. It's the loop around it, and once you've built that loop by hand, you can tell in seconds whether an agent is stuck, burning your tokens, or quietly doing something you never asked for.

Strip away the marketing and an agent is a model plus a small loop. You call the model. If it answers with a request to run a tool, you run the tool and hand the result back. Repeat until it gives a plain answer or you hit a step limit. Below is a sketch in about 40 lines of Python that runs against any chat API with tool calling, two deliberately safe tools, and the three failure modes you'll hit first.

## The loop in one paragraph

A model on its own can only produce text. It can't look at your files, and it has no memory of what it did a minute ago. The loop supplies both. Each call sends the whole conversation back in: your task, the model's replies, every tool result so far. When the model decides it needs a file, it doesn't read anything itself. It emits a structured request: run `read_file` on this path. Your code executes that and appends the output to the conversation. Next turn, the model sees the file's contents and reasons about them. That's the entire trick. When the model stops requesting tools and answers in plain text, that's your exit condition.

## Two safe tools before any cleverness

Every tool is a JSON schema: a name, a description, and its parameters. Descriptions matter more than you'd expect, because the model picks tools based on them alone.

```json
[
  {
    "type": "function",
    "function": {
      "name": "list_dir",
      "description": "List files in the project folder",
      "parameters": {
        "type": "object",
        "properties": {
          "path": { "type": "string", "description": "Subfolder, '' for root" }
        },
        "required": ["path"]
      }
    }
  },
  {
    "type": "function",
    "function": {
      "name": "read_file",
      "description": "Read one text file from the project folder",
      "parameters": {
        "type": "object",
        "properties": {
          "path": { "type": "string", "description": "Relative path" }
        },
        "required": ["path"]
      }
    }
  }
]
```

These two are safe on purpose: read-only, rooted in one project folder, no shell, no network. Once the loop runs cleanly with them, adding a write tool is a policy decision you make deliberately, not a coding one.

## The loop, with a hard stop

`chat()` below is a stand-in for any chat API that supports tool calling. The response shape differs slightly between providers, but the four moving parts are always the same: the message, its optional tool calls, the tool call id, and the arguments string.

```python
import json, os

ROOT = "/home/you/sandbox-project"   # the only folder tools can touch
MAX_STEPS = 12                       # hard stop, no exceptions

TOOLS = [...]                        # the two schemas above

def safe_path(rel):
    # refuse anything that resolves outside ROOT, e.g. "../../.ssh"
    p = os.path.realpath(os.path.join(ROOT, rel))
    if os.path.commonpath([p, os.path.realpath(ROOT)]) != os.path.realpath(ROOT):
        raise ValueError("path outside project folder")
    return p

def run_tool(name, args):
    try:
        if name == "list_dir":
            return "\n".join(sorted(os.listdir(safe_path(args["path"]))))
        if name == "read_file":
            with open(safe_path(args["path"])) as f:
                return f.read()
    except Exception as e:
        return f"error: {e}"
    return f"error: unknown tool '{name}'. Available: list_dir, read_file"

messages = [
    {"role": "system", "content": "You are a code explorer. Use the tools to answer. Be brief."},
    {"role": "user", "content": "Where is the payment logic handled?"},
]

for step in range(MAX_STEPS):
    msg = chat(messages, tools=TOOLS).message
    messages.append(msg)

    if not msg.tool_calls:           # stop condition: a plain answer
        print(msg.content)
        break

    for call in msg.tool_calls:
        result = run_tool(call.name, json.loads(call.arguments))
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": result[:4000],  # truncate before it enters context
        })
else:
    print("Stopped at step limit. Last request:", msg.tool_calls)
```

`MAX_STEPS` is the seatbelt. The `break` on a message with no tool calls is the stop condition. `safe_path` keeps a path like `../../.ssh/id_rsa` from walking out of the sandbox, because a model will happily ask for one. And notice what `run_tool` does with a bad name or a missing file: it returns an error string instead of raising. The model reads that error on the next turn and usually corrects itself, which works far better than crashing the whole run.

## What breaks first

**Endless loops.** The model requests the same file ten times, or ping-pongs between two calls forever. The step limit catches the worst case, but you can do better: log each call, and when you see an identical repeat, append a tool result that says "you already read this file" or force one text-only turn so it has to commit to an answer.

**Tools that don't exist.** The model confidently invents `search_web` or `delete_branch`. The error-string fix above usually gets it back on track. The deeper fix is a short tool list with plain, specific descriptions: every tool you add is one more thing the model has to choose between and fill in correctly.

**Huge outputs.** A 200 KB log file comes back from `read_file`, gets appended whole, and now every remaining turn pays to carry it. That's money and quality, because context stuffed with log noise makes the model worse at the actual task. Truncate in `run_tool` (the `[:4000]` above), teach the model to request line ranges, and once a tool result has served its purpose, consider dropping or summarizing it in later turns. Every loop step resends the whole conversation, so this is where an agent's bill comes from; if you'd rather pay one subscription for heavy agent use than a per-request meter, there's [a referral discount on GLM coding plans with our referral link](https://z.ai/subscribe?ic=R0K78RJKNW) (first subscription only, per the [campaign rules](https://docs.z.ai/devpack/credit-campaign-rules)).

## What real harnesses add

Your 40 lines have none of the layers that make commercial agents feel good, and those layers are the difference. Permissions: approval gates before anything writes a file or runs a command. Planning: the agent breaks a task into steps and tracks them instead of freelancing. Verification: run the tests, read the diff, retry when something fails, rather than declaring victory. Memory: project context that survives between sessions.

This is why the same model feels sharp in one tool and useless in another. The harness, not the model, decides how often the agent gets caught and corrected before it reaches you. If you want to feel that difference firsthand, give the same task to your 40-line loop and to a full harness; you can [try the ZCode agent harness free](https://zcode.z.ai/invite/ALWM9JUA) (full disclosure: that's our invite link; the app is free and you bring your own model plan or key, per its [FAQ](https://zcode.z.ai/en/newdocs/qa)).

## The safety checklist

Screenshot this. It's the minimum bar before you let any agent loop near real files.

```
[ ] No shell tool without a confirmation step. Read-only tools first.
[ ] Every tool is rooted in one sandbox folder, never your home directory.
[ ] Hard step limit and hard output truncation, both in code, not in the prompt.
[ ] Log every call: tool name, arguments, result size.
[ ] Dry-run with a fake tool that returns fixed text before wiring real ones.
```

The fake-tool dry run is the one people skip and regret. It proves your loop, message history, and truncation all work before a real model starts making real decisions about your real files.

That's an agent. Everything else you see in commercial tools is scaffolding, and you can now name each piece when you spot it. More pieces like this [on our blog](https://jackgross-five.vercel.app), and for the layer on top, read [What is an agent harness? Why the same model feels smart or useless](https://wurk.fun/blog/what-is-an-agent-harness-why-the-same-model-feels-smart-or-useless).

If this saved you an hour of guessing, a small tip on this post keeps these guides coming.
