Skip to content

Lesson 1 of 9 · 5 min read

What a Model Call Returns to the Harness

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

TL;DR: Read four fields on every model call, never one: the content (text or tool calls), the stop reason, the usage, and any refusal or filter flag. A reply that stopped because it hit max_tokens looks finished and is not. A reply whose text is empty is often a tool call, not a blank answer. Usage is your bill and your context budget for the next turn. Normalise the three provider spellings into one shape at the boundary so the loop only ever sees one.

After this lesson, you should be able to name every field an agent needs from a model response, map each provider's spelling onto one normalised shape, detect a truncated reply from its stop reason rather than its text, and explain why a harness that reads only content has at least three latent bugs.

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. 1A model reply comes back with content set to null and no error. The harness returns an empty answer to the user. What did it most likely miss?

The response is a record, not a string

Most first harnesses do the equivalent of reply.choices[0].message.content and move on. That one line discards three facts the loop depends on.

Here is what a model call returns, in the shape most APIs share even when they spell it differently:

WhatWhy the harness needs itWhere it hides
Content: text, tool calls, or bothIt is the model's proposal for this turnText and tool calls live in different fields or different content blocks
Stop reasonSays whether the proposal is complete, wants tools, hit a limit, or was blockedfinish_reason, stop_reason, done_reason, depending on the provider
Usage: input and output tokensThe bill for this call and the size of the context the next call will resendA usage object, sometimes with cached-token and reasoning-token splits
Refusal or filter signalThe model declined, or a safety layer removed the outputA refusal field, a content_filter stop reason, or a block type

The content is the only one of the four a demo needs. The other three are the ones production needs.

ONE RESPONSE, FOUR FIELDS
What the harness reads before it acts
  1. 1

    1 · Content

    text, tool calls, or both

    • The proposal for this turn
    • Text may be empty when tools are requested
  2. 2

    2 · Stop reason

    why generation ended

    • finished, tool request, token limit, filtered
    • Decides what the loop does next
  3. 3

    3 · Usage

    input and output tokens

    • The bill for this call
    • The context size the next call resends
  4. 4

    4 · Refusal or filter

    when present

    • Do not retry blindly
    • Record it; the run may need a person
The loop branches on the stop reason, not on whether the text looks complete.

Stop reasons decide the branch

The stop reason is the field the loop should branch on. Four values cover every provider once you normalise the names:

NormalisedProvider spellings (checked November 2026)What the loop does
stopstop, end_turn, stop_sequenceTreat the content as the model's answer for this turn
tool_callstool_calls, tool_useDispatch the calls, append results, go round again
lengthlength, max_tokensThe reply is incomplete. Continue it or retry with more room. Never return it as an answer
filteredcontent_filter, a refusal block or fieldRecord it, do not retry the same request blindly, consider escalating

The length case is the one that bites. A reply cut off by max_tokens can end mid-sentence or, worse, mid-JSON. The prose version looks fine: "The capital of Australia" is a plausible fragment with no error marker. The JSON version fails to parse, which is lucky, because at least it fails loudly. The only reliable signal is the stop reason. A harness that treats length as stop will eventually return half an answer with full confidence.

The tool_calls case is the other common trap. When a model requests tools, several APIs set the text content to null or an empty string. A harness that checks if content: before anything else will conclude the model said nothing, append an empty assistant turn, and either stop the run with a blank answer or ask the model again and waste a turn.

Usage is the budget

Every response carries the token count the provider billed: input tokens (everything you sent: system prompt, tool definitions, history, tool results) and output tokens (what the model wrote, including tokens you never see such as the end-of-turn marker). Many providers also split out cached input tokens and, for reasoning models, hidden reasoning tokens that you pay for and do not receive.

Two reasons the harness must record this on every call rather than estimate it later. First, it is the bill, and an agent multiplies it by the number of steps. Second, the input count on turn t is the size of the context the model just read, which tells you how close the next turn is to the budget you set in The Context Window as a Budget. A harness that never reads usage cannot enforce a cost budget and cannot explain a bill.

Normalise at the boundary

Three providers, three spellings. The loop should see one shape. Here is a normaliser over scripted responses in the three common formats: an OpenAI-compatible chat completion, an Anthropic-style message with content blocks, and a native local-server reply. The responses are fixtures, so the example runs anywhere.

from dataclasses import dataclass, field

STOP = {
    "stop": "stop", "end_turn": "stop", "stop_sequence": "stop",
    "tool_calls": "tool_calls", "tool_use": "tool_calls",
    "length": "length", "max_tokens": "length",
    "content_filter": "filtered",
}

@dataclass
class Completion:
    text: str
    stop: str
    tokens_in: int
    tokens_out: int
    tool_calls: list = field(default_factory=list)

    @property
    def truncated(self):
        return self.stop == "length"

def from_openai_style(r):
    msg = r["choices"][0]["message"]
    calls = [
        {"id": c["id"], "name": c["function"]["name"],
         "args": c["function"]["arguments"]}
        for c in (msg.get("tool_calls") or [])
    ]
    return Completion(msg.get("content") or "",          # None when tools
                      STOP[r["choices"][0]["finish_reason"]],
                      r["usage"]["prompt_tokens"],
                      r["usage"]["completion_tokens"], calls)

def from_anthropic_style(r):
    text = "".join(b["text"] for b in r["content"] if b["type"] == "text")
    calls = [
        {"id": b["id"], "name": b["name"], "args": b["input"]}
        for b in r["content"] if b["type"] == "tool_use"
    ]
    return Completion(text, STOP[r["stop_reason"]],
                      r["usage"]["input_tokens"],
                      r["usage"]["output_tokens"], calls)

def from_local_style(r):
    return Completion(r["message"]["content"], STOP[r["done_reason"]],
                      r["prompt_eval_count"], r["eval_count"],
                      r["message"].get("tool_calls") or [])

def parse(r):
    if "choices" in r:
        return from_openai_style(r)
    if r.get("type") == "message":
        return from_anthropic_style(r)
    if "done_reason" in r:
        return from_local_style(r)
    raise ValueError("unknown response shape; refusing to guess")

a = parse({"choices": [{"message": {"content": None, "tool_calls": [
            {"id": "c1", "function": {"name": "orders_get",
                                      "arguments": "{\"id\": \"4471\"}"}}]},
           "finish_reason": "tool_calls"}],
           "usage": {"prompt_tokens": 412, "completion_tokens": 38}})
b = parse({"type": "message", "stop_reason": "max_tokens",
           "content": [{"type": "text", "text": "{\"city\": \"Pune\", \"temp"}],
           "usage": {"input_tokens": 90, "output_tokens": 12}})
c = parse({"message": {"content": "Order 4471 shipped on 3 November."},
           "done_reason": "stop", "prompt_eval_count": 220, "eval_count": 11})

print(a.stop, len(a.tool_calls), repr(a.text))  # => tool_calls 1 ''
print(b.stop, b.truncated)  # => length True
print(c.stop, c.tokens_in + c.tokens_out)  # => stop 231

Three details carry the lesson. The OpenAI-style parser uses or "" because content is None when the model only requested tools. The Anthropic-style parser joins text blocks and collects tool blocks separately, because that API interleaves them in one list. And parse refuses a shape it does not recognise instead of guessing, because a wrong guess here corrupts every later turn.

Response b is the dangerous one. Its text is a JSON fragment that a harness reading only content would hand to json.loads, which fails, or worse, to a lenient repair step, which might "fix" it into a wrong object. Its stop reason says length. That is the field to branch on.

A truncated reply, read as an answer

Trace
The harness read the text and not the stop reason
  1. 01userSummarise the three open tickets for account 2210 as JSON.
steps 0tool calls 0writes 0context 0 tok
1/4

user

Summarise the three open tickets for account 2210 as JSON.

The fix is one branch. On length, either continue the generation (send the partial content back and ask the model to carry on from where it stopped) or retry the step with a larger output allowance, and record that it happened. Timeouts, max_tokens and Deadlines per Step covers how to choose the allowance in the first place.

Terms you will hear

TermWhat people sayWhat it means in the harness
Stop reason"finish reason"Why generation ended; the field the loop branches on
Truncated"it got cut off"Stop reason length: the text is incomplete even when it reads as whole
Usage"token count"Input and output tokens billed for this call; the next turn's context is at least the input count
Tool call"function call"A structured request in its own field or block, often with empty text beside it
Refusal"it declined"A field or block saying the model would not do the task; not a retryable error

Say it in 30 seconds

"A model response has four parts and the harness reads all of them: the content, which may be text or tool calls or both; the stop reason, which says whether the model finished, wants tools, hit the token limit or was filtered; the usage, which is the bill and the context size for the next turn; and any refusal. The loop branches on the stop reason, not on the text. Providers spell these differently, so one adapter normalises them before the loop sees anything."

Check yourself

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

  1. 1Your loop treats any response with text as a final answer. Name the two stop reasons that make this wrong, and what should happen for each.

  2. 2Why does the harness record usage from every response rather than estimating tokens from the text it sent?

  3. 3The parse function refuses an unrecognised response shape instead of returning a best guess. Why is that the safer default inside a loop?

Practise it as an interviewer asks it

Course lessons that teach this

Related lessons