Sub topic 4
Reading the response: content, finish reason and usage
This chapter assumes you can send a chat-completions request (the previous chapter), parse JSON in Python, and read HTTP status codes. It covers what comes back from a successful call and which fields you should check before trusting it.
The shape of a response
A successful chat-completions call returns HTTP 200 with a JSON body. Field names differ between providers, so check your provider's documentation. The common shape looks like this:
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1767000000,
"model": "example-model-2026-01",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "An API key is a secret string that identifies and authorizes your program."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 24,
"completion_tokens": 16,
"total_tokens": 40
}
}Four parts matter in daily work:
| Field | What it tells you |
|---|---|
| `choices[0].message.content` | The generated text |
| `choices[0].finish_reason` | Why generation stopped |
| `usage` | How many tokens the call consumed |
| `model` and `id` | Which model version answered, and an identifier to quote in support requests or logs |
Reading the generated text
The choices field is a list because the API can return several alternative completions for one request, usually when you ask for more than one. With the default setting there is exactly one element, so code reads index 0.
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"])Three points about this code:
raise_for_status()turns 4xx and 5xx responses into exceptions, so the lines after it only see a success body. Error bodies have a different shape, covered in a later chapter.message["content"]is a string in the simple case. It can benull(PythonNone) when the model answered with a tool call instead of text, or when the provider refused the request. Do not call string methods on it without checking.- The message also has a
role, always"assistant"for a reply. This is the value you append to your history when you continue the conversation.
The finish reason
finish_reason explains why the model stopped writing. It is the field most often ignored and most often responsible for subtle bugs.
| Value | Meaning | What to do |
|---|---|---|
| `stop` | The model reached a natural end, or hit one of your stop sequences | Normal. Use the text. |
| `length` | Generation hit the output token limit or the context window | The text is cut off. Raise the limit, shorten the prompt, or ask for a shorter answer. |
| `tool_calls` | The model wants you to run a tool | Handle the tool request (a later chapter). |
| `content_filter` | The provider's safety system withheld or truncated output | Treat the text as incomplete. Log it and handle it. |
Other providers use other names. For example, some call the truncated case max_tokens, and some have extra values such as refusal. Read your provider's list and map it to your own small set of states.
A truncated answer looks valid on the surface. If you ask for JSON and the reply stops at length, you get a string like {"name": "Sam", "items": [1, 2 that fails to parse. If you ask for a summary, you get a summary that ends mid-sentence with no error raised. Check the reason before using the text:
def extract_text(data):
choice = data["choices"][0]
reason = choice["finish_reason"]
text = choice["message"].get("content")
if reason == "length":
raise ValueError("Reply was truncated; raise the output limit or shorten the prompt")
if reason == "content_filter":
raise ValueError("Reply was withheld or cut by a content filter")
if reason == "tool_calls" or text is None:
raise ValueError(f"No text in reply (finish_reason={reason})")
return textWhether to raise, retry with a larger limit, or return the partial text depends on your application. A chat window can show partial text with a "continue" button. A pipeline that parses the output usually cannot.
Usage: counting tokens
The usage object reports what the call consumed:
prompt_tokens: tokens in everything you sent, including the system message, the full history, and any tool definitions.completion_tokens: tokens in the generated reply.total_tokens: the sum of the two.
Providers bill separately for input and output tokens, usually at different prices, so keep the two counts apart rather than storing only the total. Some providers add detail fields, such as cached prompt tokens or reasoning tokens that count toward output. These fields are optional, so read them with .get().
A small helper that records usage safely:
def summarize_usage(data):
usage = data.get("usage") or {}
return {
"prompt": usage.get("prompt_tokens", 0),
"completion": usage.get("completion_tokens", 0),
"total": usage.get("total_tokens", 0),
"model": data.get("model"),
"request_id": data.get("id"),
}Logging this summary for every call gives you the data needed for the cost and latency chapter. It also tells you when prompts are growing, which is the first sign that a conversation is heading toward the context limit.
Edge cases and gotchas
- The model name can differ from what you sent. If you request an alias such as a "latest" name, the
modelfield usually reports the concrete version that answered. Log it, because behavior changes between versions. - An empty string is a valid reply. A
stopwithcontentof""can happen, for example when a stop sequence matches immediately. Decide whether your code treats that as an error. choicescan be empty in some modes. In streaming responses with usage reporting enabled, the last chunk may have an emptychoiceslist. The streaming chapter returns to this.- Missing
usage. Some compatible servers omit it. Code that indexesdata["usage"]directly will raiseKeyErroragainst those servers. - Do not rely on field order or extra fields. Providers add new fields over time. Read only what you need and ignore the rest.
- Success status does not mean a good answer. HTTP 200 means the server completed the request. Whether the content is correct, complete, and in the format you wanted is your code's job to check.
Putting it together
A defensive reader combines the three checks: the status code (already handled by raise_for_status()), the finish reason, and the usage record.
def read_response(data):
text = extract_text(data)
usage = summarize_usage(data)
print(f"{usage['model']} used {usage['prompt']} in, {usage['completion']} out")
return text, usageSeparating "get text safely" from "record usage" keeps each function small and testable. You can test both without any network access by passing in hand-written dictionaries that look like responses, including ones with finish_reason set to length and content set to None.
Exercise
Your program asks the model for a JSON object and calls json.loads on message.content. It works in testing but occasionally raises a JSONDecodeError in production, even though the HTTP status is always 200. Which response field should you check first, and what value would explain the failure?
Show answer
Check choices[0].finishreason. A value of "length" means the output hit the token limit and was cut off mid-object, so the JSON is incomplete. Fix it by raising the output limit, shortening the prompt, or asking for a shorter object, and make the code check finishreason before parsing.
Exercise
A response has prompttokens 1200 and completiontokens 300. Input costs 2 units per million tokens and output costs 8 units per million tokens. What is the cost of this call in units, and why is total_tokens alone not enough to compute it?
Show answer
Input cost is 1200 / 1,000,000 × 2 = 0.0024 units. Output cost is 300 / 1,000,000 × 8 = 0.0024 units. The total is 0.0048 units. total_tokens (1500) cannot give this result because input and output tokens have different prices, so you need the two counts separately.