Skip to content

Read everything the library assistant's first model call returns

Make the assistant's first model call against a scripted model and read all four things it returns: the content, the stop reason, the usage and any refusal. Branch on the stop reason, not the text, so a truncated reply is never shown to a reader as an answer and a tool request is never mistaken for silence.

15 MIN

By AIAgentInterviews · Updated

TL;DR: A model call returns a record with four parts, and the assistant reads all of them before it does anything: the content, which may be text or a tool request; the stop reason, which says whether the model finished, hit the token limit, asked for tools or was filtered; the usage, which is the bill and the size of the next call; and any refusal. The code branches on the stop reason. Text that looks complete is not evidence that it is.

Where you are. Module one, lesson one. There is no loop yet. You make one call, read it properly, and build the habit every later lesson relies on.

The assistant you are building

Linden Library is an invented public library. Its catalogue assistant will answer three kinds of request from readers: is a title available, place a hold on it, renew a loan. By the end of the course it will call two services, stream its progress to a page and pass a release check. Today it makes one model call and reads the reply.

Nothing here needs a real model. A scripted fake returns fixed replies in the shapes a real provider uses, which is how you will test the assistant for the rest of the course. The fake proves the harness handles each shape; a real model's behaviour is measured separately in the seventh lesson.

In plain language. A model call sends a list of messages to a model and gets one reply back. The reply is a record with several fields, not a string. The stop reason is the field that says why the model stopped writing. Usage is how many tokens the provider counted going in and coming out, which is what you pay for and what the next call will have to resend.

One call, four fields

Most first programs do the equivalent of "take the text and move on". That single line throws away three facts the assistant needs: whether the reply was cut off, whether the model asked for a tool instead of answering, and what the call cost. Here is a call against the scripted model, with the reply read as the record it is:

import json

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

def scripted(replies):
    """A fake provider: returns the next scripted reply on each call."""
    queue = list(replies)
    def call(messages, tools=None, max_tokens=256):
        return queue.pop(0)
    return call

def read(reply):
    """Normalise one provider shape into the four fields the assistant uses."""
    msg = reply["choices"][0]["message"]
    return {
        "text": msg.get("content") or "",                 # None on tool turns
        "tool_calls": msg.get("tool_calls") or [],
        "stop": STOP[reply["choices"][0]["finish_reason"]],
        "tokens_in": reply["usage"]["prompt_tokens"],
        "tokens_out": reply["usage"]["completion_tokens"],
    }

def decide(r):
    if r["stop"] == "tool_calls":
        return "dispatch the tool calls"
    if r["stop"] == "length":
        return "incomplete: retry with more room, never show this"
    if r["stop"] == "filtered":
        return "declined: record it, do not retry blindly"
    return "answer" if r["text"].strip() else "empty answer: retry once"

model = scripted([
    {"choices": [{"message": {"content": "The Lighthouse is on the shelf at "
                  "Linden Central."}, "finish_reason": "stop"}],
     "usage": {"prompt_tokens": 180, "completion_tokens": 14}},
    {"choices": [{"message": {"content": None, "tool_calls": [{"id": "c1",
                  "function": {"name": "catalogue_lookup",
                               "arguments": "{\"title\": \"The Lighthouse\"}"}}]},
                  "finish_reason": "tool_calls"}],
     "usage": {"prompt_tokens": 180, "completion_tokens": 22}},
    {"choices": [{"message": {"content": "{\"title\": \"The Lighthouse\", \"cop"},
                  "finish_reason": "length"}],
     "usage": {"prompt_tokens": 180, "completion_tokens": 12}},
])

for _ in range(3):
    r = read(model([{"role": "user", "content": "Is The Lighthouse available?"}]))
    print(r["stop"], "|", decide(r))
stop | answer
tool_calls | dispatch the tool calls
length | incomplete: retry with more room, never show this

Three replies to the same question, three different correct reactions. The first is an answer. The second has no text at all, and a program that tested the text first would conclude the model said nothing; the stop reason says it asked for a tool. The third is a JSON fragment cut off by the output limit; the text would fail to parse or, worse, be repaired into a wrong object, and only the stop reason says it is incomplete.

A worked case: the reply that looked finished

Here is the failure this lesson prevents, as it would appear in Linden's logs. A reader asked for the three branches holding a title. The model started a JSON list, hit a small output allowance after the second entry, and stopped. The first version of the assistant parsed what it had, failed, ran a repair that closed the brackets, and told the reader two branches held the book. Three did. Nothing errored, and the reader went to the wrong branch.

Walk the reasoning. The observation is a reply whose text ends mid-structure. The question is not "can we make this parse" but "did the model finish". The stop reason answers it: length. The decision follows: treat the reply as absent, retry with a larger allowance or a smaller request, and record that it happened. The repair step never runs on a length stop. That is one branch in decide, and it is the branch that keeps a confident wrong answer away from a reader.

ONE REPLY, FOUR FIELDS
What the assistant reads before it acts
  1. 1

    1 · Content

    text, tool calls, or both

    • The model's proposal for this turn
    • Text can be empty when tools are requested
  2. 2

    2 · Stop reason

    why generation ended

    • stop, tool_calls, length, filtered
    • The field the code branches on
  3. 3

    3 · Usage

    tokens in and out

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

    4 · Refusal or filter

    when present

    • Not retried blindly
    • Recorded for the run
Providers spell these fields differently. The read function normalises them once so the rest of the assistant sees one shape.

Usage is a number you keep

The usage on every reply is the bill, and in a loop it is also the size of the context the next call will resend. The assistant stores it per call from the first lesson onward, because the fourth lesson's budgets and the seventh lesson's cost report are built on it. A harness that never reads usage cannot say what a conversation cost or why it ran out of room.

What if · interview follow-ups

Change one condition

Linden's assistant now reads all four fields. The branch librarian asks what each one buys her.

  1. Start here

    A reply arrives with empty text and a stop reason of tool_calls. The old code returned an empty answer. What does the new code do?

Do this before moving on

Take the read function and add a second parser for a block-based reply shape, where text and tool requests arrive as typed items in one list rather than two fields. Feed both parsers the three scripted replies rewritten in that shape and check that decide gives the same three answers.

Review your result. Keep a table of reply shape, stop reason and decision. The decisions should match across shapes; if they do not, the parser dropped a field, and that is the bug this lesson exists to prevent.

Go deeper

Key takeaways

  • A model reply is a record with four parts; the code branches on the stop reason, not the text.
  • Empty text on a tool turn is a request, not silence; a length stop is an incomplete reply, never an answer.
  • Usage is recorded on every call because budgets and cost reports are built from it.
  • One normalising read function keeps provider spellings out of the rest of the assistant.

Check yourself

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

  1. 1The assistant shows a reader a reply whose stop reason was length. What has gone wrong?

  2. 2Why does the read function use `msg.get("content") or ""` rather than `msg["content"]`?

  3. 3What does the assistant store from every reply besides the content, and why?

Sign in to track which lessons you have finished.