Sub topic 4
Reading the response: content, finish reason and usage
This chapter assumes you can already send a chat request (the previous chapter) and are comfortable with JSON and Python dictionaries. It covers the three parts of the response you will use most: the generated text, the reason generation stopped, and the token counts.
The shape of a response
A successful chat-completions call returns a JSON object. Providers differ in details, so check your provider's documentation. The common shape looks like this:
{
"id": "chatcmpl-abc123",
"model": "example-model",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "A token is a small chunk of text."},
"finish_reason": "stop"
}
],
"usage": {"prompt_tokens": 24, "completion_tokens": 9, "total_tokens": 33}
}Three fields matter in daily work:
choices[0].message.contentholds the generated text.choices[0].finish_reasonsays why the model stopped.usagereports how many tokens the request consumed.
choices is a list because some APIs can return several candidate replies. With default settings you get one, so code usually reads index 0.
Reading the fields in code
This program sends a request and reads all three fields. It fails loudly on HTTP errors.
import os
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
payload = {
"model": os.environ["LLM_MODEL"],
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a token is in one sentence."},
],
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
resp.raise_for_status()
data = resp.json()
choice = data["choices"][0]
print(choice["message"]["content"])
print("finish_reason:", choice["finish_reason"])
print("usage:", data["usage"])Finish reason
The finish reason tells you whether the text is complete. Never assume it is.
| Value | Meaning | What to do |
|---|---|---|
| `stop` | The model ended naturally, or hit a stop sequence. | Use the text. |
| `length` | Generation hit the output token limit. | The text is cut off. Raise the limit or shorten the task. |
| `content_filter` | The provider's safety system halted output. | Handle as a refusal. Do not retry blindly. |
| `tool_calls` | The model wants you to run a tool. | Covered in a later chapter. |
Other providers use other names, so map them to your own categories. A truncated reply is the most common silent bug. A JSON answer cut off at length will fail to parse, and a summary may simply end mid-sentence with no error.
Usage
The usage object counts tokens, which are the units providers bill and limit by:
prompt_tokens: tokens in everything you sent.completion_tokens: tokens the model generated.total_tokens: the sum of the two.
Log these values for every call. Later chapters use them to estimate cost and to see how close you are to the context window.
A defensive reader
A small helper keeps checks in one place:
def read_reply(data):
choices = data.get("choices") or []
if not choices:
raise ValueError("response contained no choices")
choice = choices[0]
text = choice["message"].get("content")
reason = choice.get("finish_reason")
if reason == "length":
raise ValueError("reply was truncated at the token limit")
if text is None:
raise ValueError(f"no text returned (finish_reason={reason})")
return text, data.get("usage", {})content can be null when the model returns tool calls instead of text, so check for None before using it.
Flow of a response check
Exercise
A call returns status 200 with finish_reason: "length" and completion_tokens: 256. Your code expects valid JSON in content, and parsing fails. What is the likely cause, and what two changes could fix it?
Show answer
The reply was cut off at the output token limit (likely 256), so the JSON is incomplete. Raise the maximum output tokens setting, or make the prompt ask for a shorter answer. Also check finish_reason before parsing so the failure is reported clearly.