Skip to content

Lesson 2 of 9 · 6 min read

The Message List the Harness Builds

Free lessonReviewed By the AIAgentInterviews editorial team
Reading position
In this lesson

TL;DR: The harness builds a list of messages with roles, and the provider renders it into one string the model reads. The list has rules: instructions sit in the system or developer role, each tool result pairs with a call id from the assistant turn just before it, and a call and its result are one unit that is kept or dropped together. Validate the list before every send. Most "the model ignored the tool result" and "400 bad request" bugs in young harnesses are a broken pair, not a model problem.

After this lesson, you should be able to describe what the model actually receives from a list of messages, name the roles and what each one is for, keep tool calls and results paired when you trim history, and write a check that rejects a malformed list before it costs a request.

Before you read

Commit to an answer now. The lesson that follows explains it, and having guessed first, even wrongly, makes the explanation easier to remember.

  1. 1To save tokens, a harness keeps only the last ten messages. Occasionally the provider rejects the request, and occasionally the model answers as if a tool result never arrived. What is the shared cause?

What the model actually reads

You send a list. The model reads a string.

Between the two sits the provider's chat template: code that renders your messages and tool definitions into one token sequence with special markers for each role, then leaves an open assistant marker at the end so the model continues as the assistant. For hosted APIs you never see this string. For open-weight models served locally you can, and reading it once changes how you think about the list.

Three consequences follow. The order of roles matters, because the template expects it. Instructions you put in the system role are rendered first, which is why they carry weight and why their position is stable for caching. And a "message" is not a unit the model knows about. The model knows tokens with role markers between them. Everything else is your bookkeeping.

DiagramFrom a list of messages to one token sequence
Systeminstructions, tool definitionsUser turnthe requestAssistant turntext or tool callsChat templateprovider-side renderOne token sequencerole markers, open assistant headerrender
1/2

The list is yours

Roles are how you tell the template what each message is. The model never sees the list structure.

The roles

RoleWho writes itWhat it carriesAuthority
System (or developer)Your harness, onceStanding instructions, the authority line, tool guidance, output formatHighest the model gives to text; still only text
UserThe person, or your harness on their behalfThe request, later clarifications, sometimes tool results on APIs that put them in a user turnThe task
AssistantThe modelText, tool calls, or bothA proposal, never an action
ToolYour harness, after running a callThe result of one tool call, tied to its idData. The model should treat it as an observation, not an instruction

Two points interviewers listen for. First, the system role carries weight but it is not a control: a limit written there is advice the model usually follows, and the harness still enforces the limit in code (The Harness and the Authority Line). Second, a tool result is data from the world, and the harness should present it as data, which is why it has its own role rather than being pasted into a user turn as prose. Some APIs render tool results inside a user message as a typed block; the principle is the same.

The pairing rule

When the model requests tools, the assistant turn carries one or more tool calls, each with an id. The results you append each carry that id. The provider, and the model, use the id to know which result answers which request. That gives three rules:

  1. Every tool result must answer a call id in the assistant turn immediately before it.
  2. Every tool call in that assistant turn needs a result before the next assistant turn, even if the result is "the tool failed" or "skipped by policy".
  3. A call and its results are one unit. Keep both or drop both.

Break rule 1 and you have an orphaned result. Some providers reject the request with a 400. Others accept it, and the model reads a result it never asked for, which it may ignore or misattribute. Break rule 2 and some providers reject the request because a call is dangling; others let the model proceed as if the tool never ran. Break rule 3 when trimming and you get both problems at once.

Here is a validator and a trimmer that respects the units:

def units(messages):
    """Group messages into droppable units: a user turn, or an assistant
    turn plus every tool result that answers it."""
    out, i = [], 0
    while i < len(messages):
        m = messages[i]
        if m["role"] == "assistant" and m.get("tool_calls"):
            ids = {c["id"] for c in m["tool_calls"]}
            unit = [m]
            i += 1
            while i < len(messages) and messages[i]["role"] == "tool":
                unit.append(messages[i])
                i += 1
            got = {r["tool_call_id"] for r in unit[1:]}
            if got != ids:
                raise ValueError(f"unanswered calls {ids - got} "
                                 f"or orphan results {got - ids}")
            out.append(unit)
        elif m["role"] == "tool":
            raise ValueError(f"orphan tool result {m['tool_call_id']}")
        else:
            out.append([m])
            i += 1
    return out

def trim(messages, keep_units):
    """Pin the system message; keep the newest units whole."""
    system = [m for m in messages if m["role"] == "system"]
    rest = [m for m in messages if m["role"] != "system"]
    kept = units(rest)[-keep_units:]
    return system + [m for u in kept for m in u]

history = [
    {"role": "system", "content": "You are the support assistant."},
    {"role": "user", "content": "Where is order 4471?"},
    {"role": "assistant", "tool_calls": [{"id": "c1", "name": "orders_get"}]},
    {"role": "tool", "tool_call_id": "c1", "content": "shipped 3 Nov"},
    {"role": "assistant", "content": "It shipped on 3 November."},
    {"role": "user", "content": "And 4472?"},
    {"role": "assistant", "tool_calls": [{"id": "c2", "name": "orders_get"}]},
    {"role": "tool", "tool_call_id": "c2", "content": "processing"},
]

print(len(units(history[1:])))  # => 5
trimmed = trim(history, keep_units=2)
print([m["role"] for m in trimmed])  # => ['system', 'user', 'assistant', 'tool']

naive = history[3:]  # a slice that starts inside a unit
try:
    units(naive)
except ValueError as e:
    print("rejected:", e)  # => rejected: orphan tool result

The naive slice history[3:] starts on the result of call c1 with the call itself cut off, so the first thing the model would read is an answer to a question nobody asked. A slice one message later would happen to be valid, which is the trouble with slicing: whether it works depends on where the window lands. The validator catches the bad case before the request leaves the building; the trimmer never produces it, and it pins the system message so the stable prefix survives.

Where instructions go, and why it matters for caching

The system message is rendered first and changes rarely, which makes it the stable prefix that prompt caching depends on (Prompt Caching for Agents). Tool definitions are usually rendered next to it. Anything that changes every turn, such as the current time, a per-request id or a fresh retrieval, belongs after the stable part, or the cache misses on every call.

The same ordering protects against a subtler bug. Some harnesses rebuild the system prompt each turn from templates, and a template that interpolates a timestamp or a random example order silently defeats caching while looking identical to the eye. Render the system message once per run and reuse the string.

Prefill, and what it is for

Several APIs let you end the list with a partial assistant turn, so the model continues from text you wrote. That is prefill. It is useful for forcing a format (start the assistant turn with { and the model writes JSON) and risky for anything else, because text you put in the assistant's mouth is text the model will defend. Use it for shape, not for content, and prefer the provider's structured output mode where one exists (Structured Outputs and Constrained Decoding).

Terms you will hear

TermWhat people sayWhat it means in the harness
Chat template"prompt format"Provider code that renders your messages and tools into one token string with role markers
Role"message type"The label that tells the template how to render a message and the model how to weigh it
Tool result pairing"tool_call_id"Each result names the call it answers; call and results are one unit
Orphaned result"400 bad request"A tool result whose call is missing from the list; rejected or misread
Prefill"putting words in its mouth"Starting the assistant turn yourself so the model continues from it

Say it in 30 seconds

"The harness sends a list of messages with roles, and the provider renders it into one string with role markers that the model reads. System or developer carries standing instructions, user carries the task, assistant carries the model's proposals, and tool carries results tied by id to the calls they answer. A call and its results are one unit, kept or dropped together, which is why trimming by message count breaks requests. I validate the list before every send and pin the system message so the cache prefix stays stable."

Check yourself

Answer aloud or on paper before revealing. Producing the explanation unaided is exactly what a panel listens for.

  1. 1The model requested two tools in one turn. One tool failed and your harness appended only the successful result. What happens, and what should it have done?

  2. 2Which change most likely defeats prompt caching without anyone noticing?

  3. 3A teammate writes the refund limit only in the system prompt and calls it enforced. Where does the authority line say the limit belongs?

Practise it as an interviewer asks it

Course lessons that teach this

Related lessons