Sub topic 9
Finish reasons and token usage
This chapter covers the two pieces of metadata that arrive at the end of a streamed response: the finish reason and the token usage. It assumes you can already read a stream of delta events and accumulate them into a message, as covered in the earlier chapters. It also assumes you know what a token is.
Why the end of the stream matters
Text deltas tell you what the model said. They don't tell you why it stopped, or how much the request cost. Both facts come in the last few events of the stream. If your client stops reading after the last text delta, or closes the connection early, you lose them.
Two questions are answered at the end of a stream:
- Why did generation stop? The answer is the finish reason. A reply that ended naturally and a reply that was cut off mid-sentence can look identical in the text, and your code should treat them differently.
- How many tokens were used? The answer is the usage data. You need it for billing, quota tracking, and spotting prompts that grow too large.
Finish reasons
A finish reason is a short string attached to the final choice of a response. It is null (or absent) on every earlier chunk. Providers use different names for the same ideas.
| Meaning | OpenAI Chat Completions | Anthropic Messages |
|---|---|---|
| Model finished naturally | `stop` | `end_turn` |
| Hit a stop sequence you supplied | `stop` | `stop_sequence` |
| Hit the output token limit | `length` | `max_tokens` |
| Model wants to call a tool | `tool_calls` | `tool_use` |
| Output blocked by a safety filter | `content_filter` | `refusal` |
Check your provider's current documentation, because these lists change as new features appear. Write your code so an unknown value is logged and handled as "unexpected", not ignored.
The two reasons that matter most:
- Length / max_tokens means the text is truncated. It may stop in the middle of a word or a JSON object. Show the user that the answer was cut off, and offer a way to continue or retry with a higher limit.
- Tool calls / tool_use means the message is not a final answer. Your code should run the requested tool and send the result back. A later chapter covers assembling the tool arguments.
Where the data appears in the stream
In an OpenAI-style stream, the finish reason arrives on the last content chunk, with an empty delta. Usage is not sent by default. If you set stream_options={"include_usage": True}, the API sends one extra chunk after the finish reason. That chunk has an empty choices list and a populated usage field. Then comes data: [DONE].
Anthropic splits the information differently. The message_start event carries the input token count. The message_delta event near the end carries stop_reason and an output_tokens count. That count is cumulative, so you keep the latest value and don't add values together. A final message_stop event closes the stream.
Capturing both values in Python
This example streams a reply with a deliberately small token limit. It records the finish reason and usage as they arrive. Replace MODEL_NAME with a model you can use.
from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="MODEL_NAME",
messages=[{"role": "user", "content": "Explain streaming in detail."}],
stream=True,
stream_options={"include_usage": True},
max_completion_tokens=30,
)
parts = []
finish_reason = None
usage = None
for chunk in stream:
if chunk.usage is not None:
usage = chunk.usage
if chunk.choices:
choice = chunk.choices[0]
if choice.delta.content:
parts.append(choice.delta.content)
if choice.finish_reason:
finish_reason = choice.finish_reason
text = "".join(parts)
print(text)
print("finish_reason:", finish_reason)
if usage:
print("prompt:", usage.prompt_tokens, "completion:", usage.completion_tokens)With a limit of 30 tokens, the finish reason should be length. If you raise the limit, a short question will end with stop.
Acting on the finish reason
Keep the decision in one function, so the rest of your code doesn't compare strings. This version runs as written and normalizes both providers' names.
def classify_finish(reason):
"""Map a provider finish reason to one of: complete, truncated, tool, blocked, unknown."""
if reason in ("stop", "end_turn", "stop_sequence"):
return "complete"
if reason in ("length", "max_tokens"):
return "truncated"
if reason in ("tool_calls", "tool_use"):
return "tool"
if reason in ("content_filter", "refusal"):
return "blocked"
return "unknown"
for r in ["stop", "length", "tool_use", None]:
print(r, "->", classify_finish(r))A None result is useful on its own. If the stream ended and you never saw a finish reason, the stream was cut short. That is a connection or server failure, not a normal ending. The next chapters on errors and cancellation build on this check.
Token usage
Usage data has three common fields: prompt (input) tokens, completion (output) tokens, and a total. Some providers add details, such as cached prompt tokens or reasoning tokens. Reasoning tokens count toward output cost even though you never see them in the text.
Three practical points:
- Usage is opt-in on some APIs. Without
include_usage, an OpenAI-style stream reports no usage at all. Anthropic always sends it. - Usage arrives last. You can't show the final cost until the stream completes. While streaming, you can only estimate from the text received.
- Usage is lost on early termination. If the user cancels the request, you may never receive the usage chunk. The provider may still bill for tokens already generated. Log your own estimate if exact accounting matters, and reconcile against the provider's dashboard or usage API.
Common mistakes
- Treating every finished stream as a successful answer. Check the finish reason before you save or display the message as complete.
- Stopping the read loop when
[DONE]is expected but the usage chunk comes first. Read until the stream actually ends. - Adding Anthropic's
output_tokensvalues from several events. Each value is the running total. - Assuming one finish reason vocabulary. Normalize at the edge of your code, as
classify_finishdoes.
Exercise
A streamed OpenAI-style request ends with data: [DONE]. Your code has the full text, but finish_reason is still None and usage is None. What are two possible explanations, and how would you tell them apart?
Show answer
One explanation is that the stream was cut short, for example by a dropped connection, so the final chunks never arrived. The other is that the stream finished normally but your loop skipped the final chunks, for example because you only read choices[0] and ignored chunks with empty choices, or because you never set stream_options={"include_usage": True}. To tell them apart, log every raw chunk. If a chunk with a non-null finish_reason appears in the log, your parsing code is at fault. If the log ends without one, and there is no [DONE], the stream was truncated. If [DONE] arrived but no usage chunk, check that include_usage was set.