Day 06: Tool calling, hand-rolled: what the API actually sends

The first tool call worked, and so did the rest. The model asked for a listing, then for seven files in a single turn, and answered correctly from what it had read: four requests, thirteen thousand tokens in.
Then I tried to break it. I sent the transcript back with "content": null on the assistant turn, then with one tool result missing, then with the assistant message deleted. All three came back 200.
That is the uncomfortable part. The protocol has rules, and the provider in front of you may not enforce them. Break one and nothing fails; the model just answers a transcript that no longer makes sense.
Which is the argument for building this once with no SDK. It is a couple of hundred lines, you watch the exact bytes, and your own tests become the thing that enforces the rules.
The Short Version
Code for this day: cartographer at day-06
- A tool call is not a function call. The model emits a name and a string; nothing runs until your code decides to run it.
- The
argumentsfield is a string containing JSON, not an object — generated text, so it can be truncated, double-escaped, or name a parameter you never defined. - Send the assistant message back verbatim,
tool_callsand all, before any result. Results reference call ids; without the message that issued them the ids point at nothing. - One
toolmessage pertool_call_id, all in the same round. Drop one and the model reasons over a call with no answer, and the provider I tested did not object. contentis usuallynullon a tool-calling turn. Coerce it to""anyway; an empty string is accepted everywhere.- Every tool failure is a message, not an exception. Unknown tool, unparseable arguments, a parameter you do not have, a tool that raised — all four go back as text the model can route around.
- Bound the loop twice: a turn cap, and a final call that forbids tools so hitting the cap still produces an answer.
A tool call is a request, not an invocation
You send a list of tool schemas alongside your messages. If the model decides one is relevant, it replies with a structured request instead of an answer:
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {
"name": "read_file",
"arguments": "{\"path\": \"src/app.py\", \"start\": 1, \"end\": 40}"
}
}
]
}
Two things in there catch everybody. content is null, not absent and not empty. And arguments is a string, not an object — the model generated those characters one token at a time, and they are JSON only by intention. Nothing guarantees they parse.
Both tools live in a new module, src/cartographer/tools.py. list_files(pattern) returns the paths matching a glob, skipping virtual environments and caches, capped at 200. read_file(path, start, end) returns a slice of one file with every line numbered, because the model has to cite line numbers and cannot count, capped at 400 lines. Both return plain strings, since everything the model receives is text. The schema you sent is what the model was working from, and it looks like this:
{
"type": "function",
"function": {
"name": "read_file",
"description": (
"Read one slice of one file, returned as numbered lines. Ask for the "
"narrowest slice that answers your question. Returns at most 400 lines."
),
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Relative to the repository root."},
"start": {"type": "integer", "description": "First line, counting from 1."},
"end": {"type": "integer", "description": "Last line, inclusive."},
},
"required": ["path", "start", "end"],
"additionalProperties": False,
},
},
}
end is required here and has a Python default of None on the function behind it. That mismatch is deliberate: the schema is what you tell the model, and the default is what saves you when it ignores what it was told. In my runs it always did: no read passed start or end, and every one got the whole file.
Three rules of the wire
The loop is short, and the lines in it that look arbitrary are the ones that matter.
def explore(task: str, max_turns: int = 12) -> list[Message]:
messages: list[Message] = [
{"role": "system", "content": EXPLORER},
{"role": "user", "content": task},
]
for _ in range(max_turns):
reply = post(messages, tools=TOOL_SCHEMAS)["choices"][0]["message"]
calls = reply.get("tool_calls") or []
assistant: Message = {"role": "assistant", "content": reply.get("content") or ""}
if calls:
assistant["tool_calls"] = calls
messages.append(assistant)
if not calls:
return messages
for call in calls:
result = dispatch(call["function"]["name"], call["function"].get("arguments") or "{}")
messages.append({"role": "tool", "tool_call_id": call["id"], "content": result})
messages.append({"role": "user", "content": OUT_OF_TURNS})
final = post(messages, tools=TOOL_SCHEMAS, tool_choice="none")["choices"][0]["message"]
messages.append({"role": "assistant", "content": final.get("content") or ""})
return messages
This is explore, new in src/cartographer/agent.py, compressed: the repo version adds two print calls for a per-call trace on stderr. It starts the transcript with a brief and your task. Each round posts the transcript with the tools attached, appends the assistant message, and returns if there were no tool calls. Otherwise it runs each call through dispatch and appends one tool message carrying the call's id and the result. Message is a new alias, dict[str, Any], because a message can now hold a list of tool calls rather than only strings.
The assistant message goes back before any result. The tool messages you are about to append refer to call ids, and those ids are only defined by the message that issued them. Append the results without it and the request is a set of answers to questions nobody asked.
One tool message per id, all in the same round. Two calls in means two tool messages out, in order, before the next post. Parallel calls are the normal case: on click the model read ten example pyproject.toml files in one turn.
content is reply.get("content") or "", never reply["content"]. The provider here accepted null back, along with the other two mistakes from the opening. A stricter one may not, and an empty string costs nothing. Since no error will tell you a rule broke, tests/test_agent.py asserts the exact sequence of roles and call ids instead.
Every failure is a message, not an exception
The dispatcher is the other half, and its contract is that it never raises.
def dispatch(name: str, arguments: str) -> str:
handler = HANDLERS.get(name)
if handler is None:
return f"error: there is no tool named {name!r}. Tools: {', '.join(sorted(HANDLERS))}"
try:
parsed = json.loads(arguments or "{}")
except json.JSONDecodeError as error:
return f"error: the arguments for {name} were not valid JSON: {error}"
if not isinstance(parsed, dict):
return f"error: the arguments for {name} must be a JSON object"
try:
return handler(**parsed)
except TypeError as error:
return f"error: wrong arguments for {name}: {error}"
except ToolError as error:
return f"error: {error}"
except Exception as error:
return f"error: {name} raised {type(error).__name__}: {error}"
Every branch returns a string, and four of them describe things a model can do: it invents a tool that would be convenient, it truncates a JSON argument string, it passes lines to a function whose parameter is end, and it asks for a file that is not there.
Each one comes back as a tool message the model reads and works around, usually on the next turn. Raise instead and one misspelled parameter throws away everything already read.
The bare except Exception is deliberate and it is the one place in this repo where it belongs. A glob the model invented can make the filesystem walk itself raise, and the correct response to any tool failure is identical: tell the model, keep the loop alive. The error message is prompt text, so name the tool and say what was wrong.
What is reachable at all is not the dispatcher's call either. It belongs in resolve, four lines in the tool module that join the requested path onto a sandbox root, resolve symlinks and .., and refuse anything that lands outside. A sandbox root is a boundary. A prompt asking the model to stay inside the repo is a preference. tests/test_tools.py checks the boundary and each dispatcher failure offline, and today's dev notes explain every line.
The loop has to be bounded twice
max_turns caps the round trips. That alone is not enough, because a run that hits the cap has read a great deal and produced nothing, which is the worst possible outcome per token spent.
So the exit is a final post with tool_choice="none". The schemas stay attached, because a history full of tool_calls with no tools defined is not a coherent request, but the model is required to emit text. You get the best answer available from what it managed to read.
while True |
A hard cap that raises | A cap, then one forced-text turn | |
|---|---|---|---|
| Stops when | the model decides to stop, or never | the counter hits the limit | the counter hits the limit |
| Leaves you with | an answer, or a rate-limit ban and a bill | an exception and nothing to show | the best answer from what it read |
| Right when | never | a batch job you will rerun and inspect | anything a person is waiting for |
Write a test that asserts the sequence of tool_choice values across a capped run — auto, auto, auto, none. Somebody will later simplify this loop into a while True, and that assertion is what stops them.
What I'd do
- Build the exchange by hand once. Two round trips, three rules. After that, every tool-calling library reads as a wrapper rather than a mystery.
- Echo the assistant message back verbatim,
tool_callsand all. Never reconstruct it from parts. - Test the protocol yourself. The provider may accept a broken transcript with a
200; only your test will notice. - Make the dispatcher total. Four error strings, nothing raises past it, and every string written to be read by a model.
- Let the schema require what your function makes optional. Tell the model everything is mandatory; keep the default for when it disagrees.
- Bound the loop twice and test the bound. A cap that produces an exception is only half a bound.
If this was useful, a clap helps other people find it. I would like to hear the wire-level ones: what is the strangest thing you have found in a tool_calls payload, and did anything ever tell you it was wrong?
All views in this post are my own. The scenarios are illustrative composites, and code examples are not drawn from any specific codebase.
Comments
Join the discussionNo comments yet. Be the first to comment.
Cartographer: learn AI agents by building one, in 30 days
One concept per day, taught by building an agent that maps an unfamiliar codebase



