Sub topic 6
Tool calls: the model asks, the harness acts
This chapter covers what happens between "the model wants to read a file" and "the model sees the file's contents." It assumes you know basic Python, JSON, and HTTP APIs, and that you have read the earlier chapters on messages, roles, and tool definitions.
The core idea: a model cannot do anything by itself
A language model produces text. It cannot open a file, run a command, or call a web service. A tool call is a structured piece of text in the model's reply that says, in effect, "please run this function with these arguments."
The harness is the program around the model. It does four jobs:
- Reads the model's reply and finds any tool calls.
- Checks that each call is valid and allowed.
- Runs the matching function.
- Sends the output back to the model as a new message.
The model never sees your code. It sees only the tool definitions you provided and the text results you return. All side effects happen in the harness.
Anatomy of a tool call
Provider formats differ in field names, but a tool call always carries the same three pieces of information:
| Field | Purpose | Example |
|---|---|---|
| id | Lets the harness match a result to the call that caused it | `call_01` |
| name | Which tool to run | `read_file` |
| arguments | The input, as a JSON object that should match the tool's schema | `{"path": "src/app.py"}` |
A reply that contains a call might look like this (generic shape):
{
"text": "I'll look at the entry point first.",
"tool_calls": [
{"id": "call_01", "name": "read_file", "arguments": {"path": "src/app.py"}}
]
}Note that the reply can contain ordinary text and tool calls together. The text is the model's running commentary. The harness acts on the calls.
The result goes back as a message with its own role (often tool, or a content block inside a user message, depending on the provider). It carries the call's id:
{"role": "tool", "tool_call_id": "call_01", "content": "import flask\n..."}The id matters because a reply can contain several calls. Without it, the model could not tell which output belongs to which request.
Executing a call safely
The model's arguments are untrusted input. The model can misspell a tool name, omit a required field, or pass the wrong type. A harness should treat the arguments like input from a web form.
The loop from the spine does the minimum: it looks up the name in a registry and calls the function with the arguments. A more careful dispatcher separates the failure cases so each one produces a clear message the model can act on.
import json
import subprocess
from pathlib import Path
def read_file(path):
return Path(path).read_text()[:20000]
def run_command(command):
r = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
return (r.stdout + r.stderr)[-5000:]
TOOLS = {"read_file": read_file, "run_command": run_command}
REQUIRED = {"read_file": ["path"], "run_command": ["command"]}
def execute_call(call):
name = call["name"]
args = call["arguments"]
if name not in TOOLS:
return f"error: unknown tool '{name}'. Available: {', '.join(TOOLS)}"
if not isinstance(args, dict):
return "error: arguments must be a JSON object"
missing = [k for k in REQUIRED[name] if k not in args]
if missing:
return f"error: missing required argument(s): {', '.join(missing)}"
try:
return str(TOOLS[name](**args))
except TypeError as e:
return f"error: bad arguments: {e}"
except subprocess.TimeoutExpired:
return "error: command timed out after 30 seconds"
except Exception as e:
return f"error: {type(e).__name__}: {e}"
if __name__ == "__main__":
print(execute_call({"id": "1", "name": "read_file", "arguments": {}}))
print(execute_call({"id": "2", "name": "delete_all", "arguments": {}}))
print(execute_call({"id": "3", "name": "run_command", "arguments": {"command": "echo hi"}}))Running this prints:
error: missing required argument(s): path
error: unknown tool 'delete_all'. Available: read_file, run_command
hiEach error string names the problem and, where useful, the valid options. The model reads this text on its next turn and usually corrects itself.
Why not use `eval` or build the name dynamically?
Always dispatch through an explicit registry. Never use getattr(module, name) or eval on a model-supplied name. The registry is an allowlist: if a function is not in TOOLS, the model cannot reach it, however it phrases its request.
Parallel calls
Many providers let the model return several tool calls in one reply. For example, it may ask to read three files at once. Rules to follow:
- Return one result for every call, each with the matching
id. Most APIs reject a conversation where a call has no result. - Run independent, read-only calls concurrently if you want speed. Run calls that change state one at a time, in the order given.
- Keep results in the same order as the calls. It makes traces easier to read.
from concurrent.futures import ThreadPoolExecutor
def execute_all(calls, read_only_names):
if all(c["name"] in read_only_names for c in calls):
with ThreadPoolExecutor() as pool:
outputs = list(pool.map(execute_call, calls))
else:
outputs = [execute_call(c) for c in calls]
return [
{"role": "tool", "tool_call_id": c["id"], "content": out}
for c, out in zip(calls, outputs)
]pool.map returns results in input order, so the zip pairs each output with the right call.
What the model sees after a call
The model has no memory of the call except what is in the messages. After the harness appends the result, the whole conversation is sent again, including the original task, the earlier reply, the call, and the result. That is why tool output counts against the context window, and why the chapter on context management matters.
Three practical consequences:
- Results are text. Binary data, large tables, and images must be converted or summarized, unless the provider supports image results.
- Results should be bounded. The
[:20000]and[-5000:]slices in the tools above keep one call from filling the window. Note the different ends: file reads keep the beginning, command output keeps the end, because errors and test summaries usually appear last. - Results should be informative. An empty string tells the model nothing. Return something like
"(no output, exit code 0)"so the model knows the command ran.
Designing results the model can use
A good result answers "what happened?" without extra guessing. Compare these two outputs from a failed command:
| Weak result | Better result |
|---|---|
| `""` | `exit code 1` followed by the last lines of stderr |
| `"Error"` | `error: FileNotFoundError: src/main.py does not exist. Did you mean src/app.py?` |
| Full 40,000-character log | The last 5,000 characters, plus a note that output was truncated |
A small improvement to run_command includes the exit code and marks truncation:
import subprocess
def run_command(command, limit=5000):
r = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
out = r.stdout + r.stderr
note = ""
if len(out) > limit:
out = out[-limit:]
note = f"[output truncated to last {limit} characters]\n"
if not out:
out = "(no output)"
return f"{note}{out}\nexit code: {r.returncode}"
if __name__ == "__main__":
print(run_command("python3 -c 'import sys; sys.exit(3)'"))This prints (no output) and exit code: 3. The exit code is a strong signal: a model can distinguish "ran and printed nothing" from "failed."
Common errors
- Hallucinated tool names or arguments. The model calls
search_fileswhen onlygrepexists. Return an error that lists the valid names. - Invalid JSON arguments. Some providers return arguments as a string. Parse with
json.loads, and return a parse error rather than crashing if it fails. - Missing results. If an exception escapes the dispatcher, the loop dies without appending a result, and the next API request is rejected. Catch exceptions inside
execute_call. - Mismatched ids. Returning a result with the wrong
idconfuses the model or triggers an API error. - Unbounded output. One
catof a large log can consume most of the window. - Shell injection through the model.
shell=Trueruns whatever string the model sends. That is why the permissions chapter covers approvals and sandboxes.
Handling string arguments
Some APIs deliver arguments as a JSON string instead of an object. A small normalizing step keeps the rest of the code simple:
import json
def parse_arguments(raw):
if isinstance(raw, dict):
return raw
try:
value = json.loads(raw)
except (TypeError, json.JSONDecodeError) as e:
raise ValueError(f"arguments are not valid JSON: {e}")
if not isinstance(value, dict):
raise ValueError("arguments must be a JSON object")
return value
if __name__ == "__main__":
print(parse_arguments('{"path": "a.txt"}'))
print(parse_arguments({"path": "b.txt"}))Call parse_arguments inside the try block of your dispatcher so a ValueError becomes an error result instead of a crash.
Summary of responsibilities
| Party | Responsibility |
|---|---|
| Model | Choose a tool, produce arguments that fit the schema |
| Harness | Validate, authorize, execute, bound the output, return a result with the right id |
| Tool function | Do one narrow job and fail with a clear message |
Exercise
A model reply contains two tool calls with ids "a1" and "a2". Your harness runs "a1", then an exception escapes while running "a2", and the loop ends without appending any result for "a2". What happens on the next API request, and how do you prevent it?
Show answer
Most provider APIs reject a conversation in which a tool call has no matching result, so the next request fails (or the model is left confused). Prevent it by catching every exception inside the dispatcher and returning an error string as the result for that call's id, so each call always gets exactly one result.
Exercise
Why does runcommand keep the last 5,000 characters of output while readfile keeps the first 20,000?
Show answer
A file's useful content, such as imports and definitions, tends to be at the start. Command output, such as stack traces, test failures, and summaries, tends to appear at the end. Each tool keeps the end of the text where the information the model needs is most likely to be.
Exercise
Extend executecall so a call with an argument that is not in the tool's allowed list (for example readfile with an extra key "mode") returns a clear error instead of a TypeError message. Describe the check you would add.
Show answer
Define the allowed argument names per tool (for example ALLOWED = {"readfile": {"path"}, "runcommand": {"command"}}). Before calling, compute extra = set(args) - ALLOWED[name]. If extra is not empty, return f"error: unexpected argument(s): {', '.join(sorted(extra))}". This gives the model a precise message and lists the offending keys.