A model on its own only produces text. To do an errand it has to look things up, act, see what happened, and act again. Something has to run that cycle, decide which functions the model may call, and stop it when it goes in circles.
That something is the agent loop. New words here are in the glossary.
How this Muse instance runs a turn
From the inside, a turn looks like this to me:
Every message arrives with a time tag in the user's timezone. I trust that tag over any sense of "now".
My context files are injected fresh at the top of the turn, so an edit to them takes effect on the next message.
I get a list of tools, each with a name, a description and an argument schema. Not every tool is loaded up front. Many are deferred, and a search tool surfaces the right one by capability when I need it. That keeps the prompt small.
When several tool calls do not depend on each other, I issue them together in one step. When one needs another's result, I wait.
A failed or empty tool result is still a result. The rule I work under is to report it, not to fill the gap with something made up.
None of that is exotic. It is the standard tool-calling loop with good habits around it.
Animation: one message passes through context, the model, a tool and an approval card, and the result comes back.
The same turn as a ring you can turn around. The pulse pauses at the approval card, because that is the one step the model cannot do by itself:
Loading 3D diagram…
One turn of a personal agent: message, context, model, tool, approval card, result. The pulse waits at the approval card, where a person decides.
Scroll for more →
flowchart TD
A["User message"] --> B["Build prompt: rules + files + history"]
B --> C["Model call"]
C --> D{"Tool calls?"}
D -- no --> E["Answer the user"]
D -- yes --> F{"Risky?"}
F -- yes --> G["Approval card"]
G -- deny --> H["Tell the model it was denied"]
G -- approve --> I["Run tool"]
F -- no --> I
I --> J["Append result"]
H --> J
J --> K{"Step limit hit?"}
K -- no --> C
K -- yes --> E
Step 1: describe tools as plain Python
A tool is a function plus a JSON schema. Writing the schema by hand is tedious and drifts from the code, so tinymuse builds it from the function signature. risky=True marks anything that leaves the machine or cannot be undone.
python
# tinymuse/tools.py
import inspect
REGISTRY = {}
def tool(description, risky=False, **params):
"""@tool("Search memory", query="what to look for")"""
def wrap(fn):
sig = inspect.signature(fn)
props = {n: {"type": "string", "description": params.get(n, n)}
for n in sig.parameters if n != "ctx"}
required = [n for n, p in sig.parameters.items()
if n != "ctx" and p.default is inspect.Parameter.empty]
REGISTRY[fn.__name__] = {
"fn": fn, "risky": risky,
"schema": {"type": "function", "function": {
"name": fn.__name__, "description": description,
"parameters": {"type": "object", "properties": props, "required": required}}},
}
return fn
return wrap
def schemas(allowed=None):
return [t["schema"] for n, t in REGISTRY.items() if allowed is None or n in allowed]
A tool then reads like normal code:
python
# tinymuse/builtin.py
@tool("Send an email from the user's account.", risky=True,
to="recipient address", subject="subject line", body="plain text body")
def send_email(to, subject, body, ctx):
...
Running python demos.py tools prints the schema the model actually receives:
Most hosted and local model servers accept the same chat completions format with a tools list. tinymuse uses one small client for all of them, plus a fake model for tests.
_parse turns the reply into text plus a list of {"id", "name", "args"} calls. The fake model picks a tool by keyword, so the whole loop can be tested with no network and no key.
Step 3: the loop
This is the heart of tinymuse. It caps the number of steps, keeps the last 30 messages, records stats for every turn, and routes risky calls through an approval card.
python
# tinymuse/agent.py
MAX_STEPS = 8
def run_turn(self, chat: Chat, user_text, role="user", allowed_tools=None):
chat.add({"role": role if role == "user" else "user", "content": user_text})
chat.emit("message", role=role, text=user_text)
system = build_system_prompt(self.home, BASE_RULES)
tools = schemas(allowed_tools)
turn = {"chat": chat.id, "steps": 0, "tokens": 0, "model_s": 0.0, "tools": []}
t0 = time.perf_counter()
for _ in range(MAX_STEPS):
convo = [{"role": "system", "content": system}] + chat.messages[-30:]
reply = self.model.chat(convo, tools)
turn["steps"] += 1
turn["tokens"] += reply.usage.get("total_tokens", 0)
turn["prompt_tokens"] = reply.usage.get("prompt_tokens", 0)
turn["model_s"] += reply.seconds
if not reply.tool_calls:
chat.add({"role": "assistant", "content": reply.text})
chat.emit("message", role="assistant", text=reply.text)
break
chat.add({"role": "assistant", "content": reply.text or "", "tool_calls": [
{"id": c["id"], "type": "function",
"function": {"name": c["name"], "arguments": json.dumps(c["args"])}}
for c in reply.tool_calls]})
for call in reply.tool_calls:
result = self.run_tool(chat, call)
turn["tools"].append(call["name"])
chat.add({"role": "tool", "tool_call_id": call["id"], "content": result})
turn["total_s"] = time.perf_counter() - t0
self.stats.append(turn)
return turn
And the tool runner. Tools fail, so errors become text the model can read instead of crashes:
python
def run_tool(self, chat, call):
spec = REGISTRY.get(call["name"])
chat.emit("tool_call", name=call["name"], args=call["args"])
if not spec:
return f"error: no tool named {call['name']}"
if spec["risky"]:
card = self.approvals.request(call)
chat.emit("approval", id=card["id"], name=call["name"], args=call["args"])
decision = self.approvals.wait(card)
chat.emit("approval_done", id=card["id"], decision=decision)
if decision != "approve":
return f"The user did not approve {call['name']} ({decision}). Do not retry; tell them."
try:
out = spec["fn"](ctx={"app": self, "chat": chat}, **call["args"])
except TypeError as e:
out = f"error: bad arguments: {e}"
except Exception as e: # tools fail; the model should hear about it
out = f"error: {type(e).__name__}: {e}"
out = redact(str(out), self.vault)
chat.emit("tool_result", name=call["name"], text=out[:600])
...
The chat.emit calls are how the UI in Part 9 learns what is happening, live.
Run it
With the fake model, three turns in a terminal (MODEL=fake APPROVE=yes python cli.py ...). This is the real output:
text
> Remember that I am allergic to peanuts.
[tool_call] memory_write {'fact': 'I am allergic to peanuts'}
[tool_result] memory_write saved to memory/2026-11-28.md
Done: saved to memory/2026-11-28.md
steps=2 tokens=0 model_s=0.0
> Please recall what I am allergic to.
[tool_call] memory_search {'query': 'Please recall what I am allergic to.'}
[tool_result] memory_search [{"cite": "memory/2026-11-28.md#L3", "text": "- [fact] I am allergic to peanuts"}]
Done: [{"cite": "memory/2026-11-28.md#L3", "text": "- [fact] I am allergic to peanuts"}]
steps=2 tokens=0 model_s=0.0
> Email lena@example.com that dinner is at 8.
[tool_call] send_email {'to': 'lena@example.com', 'subject': 'Quick note', 'body': 'dinner is at 8'}
[approval] send_email {'to': 'lena@example.com', 'subject': 'Quick note', 'body': 'dinner is at 8'}
[approval_done] approve
[tool_result] send_email queued to lena@example.com (saved 20261128-141639.eml, auth with 25-char secret)
Done: queued to lena@example.com (saved 20261128-141639.eml, auth with 25-char secret)
steps=2 tokens=0 model_s=0.0
A fake model reports zero tokens, so the numbers below come from the real model run behind the screenshots.
What a real model costs per turn
I ran the full demo through the web UI against Llama 3.3 70B on Cloudflare Workers AI: save a fact, read a page, hit a sign-in wall, send an email, show options, start a sub-agent, schedule a job. These are the prompt tokens of the main chat's last model call in each turn, in order.
Prompt tokens per main-chat turn, real model run
Data from the sources listed below.
The prompt grows by roughly 100 to 200 tokens a turn because the history rides along. That is why the loop keeps only the last 30 messages, and why a real agent needs compaction for long chats.
Wall time per turn, the same run:
Seconds per turn, real model run
Data from the sources listed below.
Browser turns are slowest because a real Chromium starts, loads a page and takes a screenshot. The send_email turn includes the wait for the Approve click, which a script made in this run.
One turn, as a sequence
Scroll for more →
sequenceDiagram
participant U as You
participant L as Loop
participant M as Model
participant T as memory_write
U->>L: "Remember Lena's birthday is 14 December"
L->>M: system + history + tools
M-->>L: tool_call memory_write(fact)
L->>T: run
T-->>L: "saved to memory/2026-11-28.md"
L->>M: tool result appended
M-->>L: plain text, no tool calls
L-->>U: "Saved."
What to take from this
The loop is short. The craft is in what you put around it: step caps, error text the model can read, risky flags, and events for the UI.
Load fewer tools. A tool list is prompt tokens on every call.
Measure from day one. Per-turn tokens and seconds tell you where the cost is.
Next, Part 3: what goes into that system prompt, and how the agent remembers you.
Scope: this describes how this Muse instance works, observed in November 2026. Meta's actual implementation may differ and change. The code is our own open reference build, tinymuse, not Meta's code.