Velamuvi AIAcademy

Lesson 4 of 8 · Basics

Reading the Response

What an AI API returns: the text as content blocks, why generation stopped, token usage, IDs and the model, parsed from three providers in Python, safely.

  • 6 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • The main parts of an AI API response
  • Why the text is often inside a list of content blocks
  • How to read the stop reason and token usage
  • How to write code that reads responses safely

More than just text

An AI API response is a JSON object with several useful parts:

PartWhat it tells youWhy it matters
The generated outputThe model's text (and sometimes tool calls or other content)The answer itself
Stop or finish reasonWhy generation ended: finished, hit the limit, stop sequence, tool useDetect cut-off answers
UsageInput and output tokens countedYour bill, and how close you are to limits
IDA unique ID for this responseLogging, debugging, support requests
ModelThe exact model version that answeredReproducing results, auditing

Same parts, different shapes

Here are made-up responses in the shapes used by two providers, and the code to read each.

Try it yourselfPython
import json

# A response in the shape of Anthropic's Messages API (the values are made up)
anthropic_reply = json.loads("""
{
  "id": "msg_01AbC",
  "type": "message",
  "role": "assistant",
  "model": "MODEL_NAME",
  "content": [{"type": "text", "text": "Recursion is when a function calls itself."}],
  "stop_reason": "end_turn",
  "usage": {"input_tokens": 21, "output_tokens": 9}
}
""")

# A response in the shape of OpenAI's Chat Completions API (values made up)
openai_reply = json.loads("""
{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "model": "MODEL_NAME",
  "choices": [{"index": 0,
               "message": {"role": "assistant", "content": "Recursion is when a function calls itself."},
               "finish_reason": "stop"}],
  "usage": {"prompt_tokens": 21, "completion_tokens": 9, "total_tokens": 30}
}
""")

def read_anthropic(reply):
    text = ""
    for block in reply["content"]:          # the content is a LIST of blocks
        if block["type"] == "text":
            text += block["text"]
    usage = reply["usage"]
    return text, reply["stop_reason"], usage["input_tokens"], usage["output_tokens"]

def read_openai(reply):
    choice = reply["choices"][0]
    usage = reply["usage"]
    return (choice["message"]["content"], choice["finish_reason"],
            usage["prompt_tokens"], usage["completion_tokens"])

for name, result in [("Anthropic", read_anthropic(anthropic_reply)),
                     ("OpenAI", read_openai(openai_reply))]:
    text, stop, tokens_in, tokens_out = result
    print(f"{name}: {text!r}")
    print(f"   stopped because: {stop}, tokens in/out: {tokens_in}/{tokens_out}")

Notice the differences: the text sits in content, a list of blocks, in one, and in choices[0].message.content in the other. The usage fields have different names. The stop reason is end_turn in one and stop in the other. SDKs turn these into objects (such as message.content[0].text), but the structure is the same.

Why a list of blocks?

Modern models do more than write text. One response might contain an explanation, then a request to run a tool, or (for reasoning models) a summary of the thinking followed by the answer. A list of typed blocks holds all of these in order. Your code should check each block's type rather than assuming the first block is text.

Reading safely

  • Check the HTTP status first. Only parse the body as a success if the request succeeded; error responses have a different shape.
  • Check the stop reason. If it says the token limit was hit, the text may be cut off.
  • Loop over content blocks and pick the types you need.
  • Record the usage with every call, so you always know what you spent and where.
  • Don't assume fields exist. Use the SDK's objects, or check before indexing, so an unusual response doesn't crash your program.

Common mistakes

Practice exercise

Read the text and token usage out of a response with a different shape.

Your solutionPython
import json

# A response in the shape of Google's Gemini API (values made up)
reply = json.loads("""
{
  "candidates": [
    {"content": {"role": "model", "parts": [{"text": "Bonjour!"}]},
     "finishReason": "STOP"}
  ],
  "usageMetadata": {"promptTokenCount": 9, "candidatesTokenCount": 3, "totalTokenCount": 12}
}
""")

# Print the text of the first part of the first candidate, and the total tokens:
# Text: Bonjour!
# Total tokens: 12
Knowledge check

Why should your code check the stop or finish reason of every response?

Summary

  • A response contains the output, the stop reason, usage, an ID and the model version.
  • Providers use different shapes and field names for the same parts.
  • Output is often a list of typed content blocks: text, tool calls and more.
  • Read safely: check the status, the stop reason and each block's type; record usage.

Next: streaming responses, so users see text as it is written.

Finished reading? Tick it off to track your progress.