Sub topic 9
Finish reasons and token usage
This chapter assumes you can already read a streamed response and accumulate deltas into text, as covered in the previous chapters. It uses the OpenAI-style chat completions stream. Other providers use different field names but follow the same idea.
Why the end of the stream matters
Text deltas tell you what the model said. They don't tell you why it stopped or what the call cost. Two pieces of metadata arrive near the end of the stream and answer those questions:
- The finish reason says why generation ended.
- The usage object reports how many tokens the request consumed.
If you ignore both, you can't tell a complete answer from a truncated one, and you can't track cost.
Finish reasons
Every chunk carries a finish_reason field, but it is null until the final content chunk. That chunk has an empty or missing delta.content and a non-null finish_reason.
| Value | Meaning | What to do |
|---|---|---|
| `stop` | The model reached a natural end or a stop sequence. | Treat the message as complete. |
| `length` | The output hit `max_tokens` or the context limit. | Warn the user, or continue the request. |
| `tool_calls` | The model wants to call a tool. | Run the tool and send the result back. |
| `content_filter` | A safety filter cut the output off. | Show a notice and don't present the text as complete. |
Providers differ in naming. Anthropic, for example, uses end_turn, max_tokens, and tool_use. Map provider values to your own small set so the rest of your code doesn't depend on one vendor.
Usage in a stream
Usage is not included in a stream by default. With the OpenAI API you request it with stream_options. The API then sends one extra chunk after the finish-reason chunk. That chunk has an empty choices list and a populated usage field.
from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="MODEL_NAME",
messages=[{"role": "user", "content": "Name three colors."}],
stream=True,
stream_options={"include_usage": True},
)
parts = []
finish_reason = None
usage = None
for chunk in stream:
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
if chunk.usage:
usage = chunk.usage
print("".join(parts))
print("finish:", finish_reason)
if usage:
print("prompt:", usage.prompt_tokens, "completion:", usage.completion_tokens)The loop guards chunk.choices before indexing it. The usage chunk has no choices, so chunk.choices[0] would raise an IndexError.
Common errors
- Reading usage too early. Usage arrives after the finish reason. If you stop reading at
finish_reason, you never see it. - Assuming
stop. Code that treats every ended stream as success shows truncated answers without any warning. - Losing usage on cancel. If the user aborts the stream, the usage chunk usually never arrives. Estimate tokens from the text you received, or check the provider's usage dashboard.
- Trusting a stream with no finish reason. If the connection closes before any
finish_reasonappears, the response was cut off. Handle it as an error, as the later chapter on mid-stream failures describes.
Exercise
A streamed response ends with finish_reason "length". What does that tell you, and why might your usage variable still be None after the loop?
Show answer
"length" means generation stopped because it hit the token limit, so the answer is probably incomplete. Usage can be None because it is only sent when you set streamoptions includeusage to true, and it arrives in a separate chunk after the finish-reason chunk, which your loop would miss if it stopped early.