Sub topic 2
Messages and roles: how a conversation is sent
This chapter assumes you can read JSON and Python, and that you know a language model takes text in and returns text. Here you learn what the harness actually sends on each model call, and why that format matters for agents.
The request carries the whole conversation
A chat with a model feels like a continuing exchange. It isn't one. The model keeps no memory between calls. Each API request contains everything the model is allowed to know, and the model reads it from the top every time.
The harness is the program that runs the model in a loop. It keeps the conversation in an ordinary list in memory. Before each call it sends the full list. When the reply arrives, it appends the reply to the list and waits for the next event.
Two consequences follow. The model "remembers" only what the harness resends. Also, every call gets longer than the last, so cost and latency grow as the conversation grows. The next chapter covers the size limit.
Roles label who said what
A message is an object with a role and content. The role tells the model who produced the text. Providers use slightly different names and shapes, but most coding-agent APIs have these four roles.
| Role | Written by | Typical content |
|---|---|---|
| system | The developer of the harness | Behavior rules, tool-use guidance, project instructions |
| user | The human, or the harness on the human's behalf | The task, follow-up questions, approvals |
| assistant | The model | Text replies and requests to call tools |
| tool | The harness | The output of a tool the model asked for |
Treat the table as a working model. Providers differ in these ways:
- Some APIs take the system prompt as a separate top-level field instead of a message in the list.
- Some have no separate tool role. They put tool results inside a user message as typed content blocks.
- Some add a developer role, which is a system-like role for instructions from the application builder.
Check your provider's reference for exact field names. The ideas stay the same: the model needs to tell instructions, user requests, its own earlier output, and tool results apart.
What a message list looks like
This is a short conversation in a common JSON shape. It includes one tool call and its result.
[
{"role": "system", "content": "You are a coding assistant. Use tools to inspect files before editing them."},
{"role": "user", "content": "What does main.py print?"},
{
"role": "assistant",
"content": "I'll read the file.",
"tool_calls": [
{"id": "call_1", "name": "read_file", "arguments": {"path": "main.py"}}
]
},
{"role": "tool", "tool_call_id": "call_1", "content": "print('hello')\n"},
{"role": "assistant", "content": "main.py prints the word hello."}
]Three details matter here.
- The assistant message holds both text and a tool call. The text is optional. A message can contain only the tool call.
- The tool call has an
id. The tool message repeats it astool_call_id. This is how the model matches a result to a request when several calls are in flight. - The final assistant message has no tool calls. In an agent loop, that signals the model is done.
Statelessness in code
The next program uses a fake model that only reports how many messages it received. It shows that the model sees what you send and nothing more.
def fake_model(messages):
return f"I can see {len(messages)} message(s)."
history = [{"role": "system", "content": "You are a helpful coding assistant."}]
def send(user_text):
history.append({"role": "user", "content": user_text})
reply = fake_model(history)
history.append({"role": "assistant", "content": reply})
return reply
print(send("Hello"))
print(send("Are you still there?"))
# A call that forgets the history:
print(fake_model([{"role": "user", "content": "What did I say first?"}]))The output is:
I can see 2 message(s).
I can see 4 message(s).
I can see 1 message(s).The first call sends the system message and one user message. The second sends four, because the harness appended the first reply and the new question. The third call used a fresh list, so a real model would have no idea what you said first. It cannot recover what it was never sent.
Tool calls inside the message list
Tools add a rule to the format. When the assistant message contains tool calls, the next messages must be the matching results. Most providers reject, or behave badly on, a list where a tool call has no result.
A single model turn that requests tools therefore expands into several messages:
- The assistant message with one or more tool calls.
- One tool message per call, each carrying the matching id.
- The next assistant message, written after the model has read the results.
The model can request several calls in one assistant message. The harness may run them in any order, but it must return one result for each id. Some providers also require that the results come immediately after the assistant message, with no other message between them.
This helper finds calls that never received a result. It is a useful sanity check before sending a request.
def find_orphans(messages):
pending = set()
for m in messages:
if m["role"] == "assistant":
for call in m.get("tool_calls", []):
pending.add(call["id"])
elif m["role"] == "tool":
pending.discard(m["tool_call_id"])
return pending
messages = [
{"role": "user", "content": "Show me main.py"},
{"role": "assistant", "content": "",
"tool_calls": [{"id": "call_1", "name": "read_file",
"arguments": {"path": "main.py"}}]},
]
print(find_orphans(messages)) # {'call_1'}
messages.append({"role": "tool", "tool_call_id": "call_1", "content": "print('hello')"})
print(find_orphans(messages)) # set()Common errors with message lists
Most message-format bugs come from the harness and not from the model. These are the ones you will meet most often.
- Forgetting to append the assistant message. If you run the tool but skip saving the assistant's request, the next call contains a tool result with no matching call. Many APIs return a validation error. Others let it through, and the model gets confused about why it has an answer to a question it never asked.
- Orphaned tool calls. If a tool crashes and you append nothing, the call has no result. Always append something, even an error string. The chapter on error feedback covers this.
- Breaking role order. Some providers require the first non-system message to be from the user. Some require strict alternation between user and assistant turns, with tool results counted as part of the user side. A list that violates the rule returns an error before the model runs.
- Mutating old messages. Editing an earlier message changes what the model believes happened. This is sometimes deliberate, as in summarization. It is a bug when it happens by accident, for example when a function modifies a shared list in place.
- Putting instructions in the wrong role. Text in a tool message is output from a tool, and the model should treat it as data. Text in the system message is guidance from the harness developer. Mixing these up weakens both the model's behavior and your safety controls.
- Sending a stale copy. If two parts of the program each keep their own history list, one of them will be missing turns.
Why the format matters for agents
An agent is built from this list. The harness never stores "agent state" in a hidden place. The state is the message list, plus whatever files and processes the tools have touched. This has practical benefits.
- Debugging is reading. If you save the list, you can see exactly what the model saw on any step.
- Resuming is loading. You can restart an agent by loading a saved list and calling the model again.
- Branching is copying. You can copy the list and try a different next step.
- Cost follows length. Every step resends all earlier messages, so a 40-step task sends the first message 40 times. Providers that support prompt caching can reuse a repeated prefix at a lower price. That only works if the early messages stay byte-for-byte identical, which is another reason not to edit history casually.
| Step | Messages sent | What changed |
|---|---|---|
| 1 | system, user | Starting task |
| 2 | system, user, assistant (tool call), tool | One tool round trip |
| 3 | the four above, plus assistant (tool call), tool | A second round trip |
Each row contains the whole previous row. The list only grows unless the harness deliberately shortens it.
Exercises
Exercise
A harness calls the model with only the newest user message each time, and keeps the older messages in a variable it never sends. The user asks, "Rename the function we just discussed." What happens, and why?
Show answer
The model has no record of the earlier discussion, so it cannot know which function is meant. It will guess or ask. The model is stateless, so only the messages in the current request exist for it. The fix is to append every user, assistant, and tool message to one list and send the whole list on each call.
Exercise
The model's reply requests two tool calls with ids "a1" and "a2". The harness runs both, but a2 raises an exception and the harness appends only the result for a1. What is the likely outcome, and how should the harness behave instead?
Show answer
The next request has a tool call with no matching result, which many providers reject with a validation error, or the model may act on incomplete information. The harness should catch the exception and append a tool message for "a2" containing an error string, so every call id has exactly one result.
Exercise
Why does a task that takes 40 model calls usually cost more than 40 times the first call?
Show answer
Each call resends the whole message list, and the list grows with every assistant reply and tool result. The cost of call N is roughly the sum of everything before it, so total input grows faster than the number of calls. Prompt caching can reduce the price of the repeated prefix, but only if that prefix is unchanged.