Streaming LLM API Token Usage and Cost
Streaming LLM API token usage is null by default. Fix it with stream_options include_usage, then get the cost of a streamed completion from /v1/usage by id.
By OceanToken Team

Editor's note: Turning on
stream=Trueis the right call for anything a person reads as it arrives, and it quietly breaks two things most billing code relies on: theusageobject and the cost header. Neither is a bug. Both follow from how streams work, and both have a documented fix that takes about twenty lines. Skip it and your spend dashboard drifts away from your invoice.
Short answer: Streaming LLM API token usage is missing by default. Send stream_options={"include_usage": True} and the last chunk before [DONE] carries usage, with an empty choices list your loop must tolerate. For cost, a stream has no x-oceantoken-cost header, so look it up afterwards with GET /v1/usage/{id}, using the completion id every chunk carries.
We use OceanToken as the worked example because one key and one OpenAI-compatible base URL serve every chat model here, so the same usage code works whichever chat model you call. Every behavior below comes from our docs and model pages, read November 28, 2026. We have not measured your traffic, so the end of the article is a checklist to verify the fix on your own requests. For prices, see /pricing and /deepseek-api.
01 · Why streaming LLM API token usage comes back empty
A non-streamed chat completion arrives as one JSON body, and the server knows the token counts before it sends that body, so usage sits next to choices. A stream is different. The server sends headers first, then one small chunk per piece of text, and the totals only exist once the last token has been generated.
That ordering explains both symptoms people hit after switching base URLs and turning on streaming:
usageisNoneon every chunk. In the OpenAI Chat Completions format, a stream does not include token counts unless you ask for them. Our API reference says the same: to receive token counts at the end of a chat-completions stream, send"stream_options": {"include_usage": true}.- The cost header is missing. Our docs explain that a non-streamed response carries its cost in the
x-oceantoken-costheader, in US dollars rounded to four significant figures. A streamed chat completion cannot, because headers are sent before the first token and the cost is known only after the last.
Neither problem means the request was free or unrecorded. Every request appears in the console under Logs with what it was charged. The fix is about getting the same numbers into your own code.
02 · stream_options include_usage: the one-line fix
stream_options with include_usage set to true adds one extra chunk at the end of a chat-completions stream that carries usage. Every chat model's docs entry we checked lists it in the same words: "adds a last event with the token counts."
The catch is in the shape of that chunk. In the OpenAI format the usage chunk has an empty choices list, so a loop that reads chunk.choices[0].delta.content on every chunk will throw an IndexError on the last one. That is why the streaming sample in our text-generation guide guards with if chunk.choices. Your loop needs the same guard.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.oceantoken.ai/v1",
api_key=os.environ["OCEANTOKEN_API_KEY"])
stream = client.chat.completions.create(
model="deepseek/deepseek-v4.1-flash",
messages=[{"role": "user", "content": "Explain rate limits in three sentences."}],
stream=True,
stream_options={"include_usage": True},
)
request_id, usage, finish = None, None, None
for chunk in stream:
request_id = request_id or chunk.id # every chunk carries the completion id
if chunk.choices: # the usage chunk has no choices
c = chunk.choices[0]
if c.delta.content:
print(c.delta.content, end="", flush=True)
finish = c.finish_reason or finish
if chunk.usage:
usage = chunk.usage
print()
print(request_id, finish, usage)
Store request_id even when you get usage from the stream. You need it for the cost lookup in section 04, and it is what finds the request in Logs.
03 · Usage on the Responses and Messages endpoints
include_usage is a Chat Completions option. The two other request shapes our API accepts handle usage on their own, in their final events.
| Endpoint | Where streamed usage arrives | Id to store | What ends a complete stream |
|---|---|---|---|
/v1/chat/completions |
Last chunk before [DONE], only with include_usage |
Completion id (on every chunk) |
A chunk with finish_reason |
/v1/responses |
Its own final event | x-oceantoken-request-id header |
A response.completed event |
/v1/messages |
Its own final events | x-oceantoken-request-id header |
A stop_reason |
The "Id to store" column is the part people miss. For a streamed /v1/responses or /v1/messages call, our docs say the resp_ or msg_ id in the body is not always the one the cost is recorded under. The x-oceantoken-request-id response header always is, so log it on those two endpoints from the start.
The last column comes from our reliability docs: check that every stream ends with a finish reason. A stream without one is incomplete, and its usage, if any arrived, describes a partial answer.
04 · How to get the cost of a streamed chat completion
To get the cost of a streamed chat completion, wait until the stream ends, then call GET /v1/usage/{request_id} with the completion id. The answer has id, model, cost (US dollars, four significant figures), status, usage with prompt_tokens, completion_tokens and total_tokens, plus started_at, ended_at and duration_ms.
Three rules from our docs shape the code around it:
- Use the same key. With any other key the answer is
404. The endpoint never confirms that someone else's request exists, which also means a billing service with its own key cannot look up costs for requests your app made with a different key. - Expect a short delay. The cost is recorded a few seconds after the request finishes, and until then the answer is also
404. A 404 in the first seconds is normal; retry with a short backoff. - Fall back to the header id. The lookup accepts the body
idand also thex-oceantoken-request-idheader, for two days after the request. Use the header when the body id still answers 404 after a few seconds.

Here is the lookup with backoff, written to run after the user already has their answer:
import os, time, httpx
BASE = "https://api.oceantoken.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['OCEANTOKEN_API_KEY']}"} # same key as the request
def lookup_cost(request_id, fallback_id=None, tries=6):
delay = 2.0
for attempt in range(tries):
for rid in filter(None, [request_id, fallback_id]):
r = httpx.get(f"{BASE}/usage/{rid}", headers=HEADERS, timeout=10)
if r.status_code == 200:
return r.json() # id, model, cost, status, usage, started_at, ended_at, duration_ms
if r.status_code != 404:
r.raise_for_status()
time.sleep(delay) # cost is recorded a few seconds after the request ends
delay = min(delay * 2, 30)
return None # leave it for a later sweep; Logs still has it
Run this in a background worker or a queue, not inside the request handler. The user does not need to wait for your bookkeeping, and a lookup that is still 404 can simply go back on the queue.
To capture the header id with the OpenAI SDK, open the stream with client.chat.completions.with_streaming_response.create(...); the response object exposes .headers before you iterate .parse().
05 · Reasoning tokens in streaming usage
Reasoning tokens in streaming usage are already inside completion_tokens. Each chat model's docs entry describes usage.completion_tokens as "output tokens, reasoning included," and lists usage.completion_tokens_details.reasoning_tokens as the part spent reasoning.
This matters for two reasons. First, billing: our text-generation guide says reasoning tokens are billed as output tokens. If your dashboard estimates cost from the visible answer length, it will undercount on any reasoning model, sometimes by a lot on short answers to hard questions. Read the number from usage or from the lookup instead.
Second, debugging. Models that return their reasoning stream it in reasoning_content, separately from content. A user can see a pause where nothing appears while the model is thinking, and your code may count zero visible tokens for a while. That is expected. The reasoning still counts. An attempt that fails before the model has produced any output is not billed; a stream that breaks after output has started is billed for its prompt and for the output streamed up to that point, reasoning included.
max_tokens interacts with this. On the models we checked, including deepseek/deepseek-v4.1-flash, max_tokens is "the most tokens to write, reasoning included." A low limit can be used up by thinking, leaving finish_reason: length and an empty answer. If reasoning_tokens is close to max_tokens in the final usage chunk, raise the limit.
06 · Cached tokens and what else the usage chunk tells you
The same usage chunk tells you how much of the prompt came from cache. On chat completions, usage.prompt_tokens_details.cached_tokens is the number of prompt tokens read from the cache, and our API reference adds cache_creation_tokens next to it for tokens written. On /v1/messages the equivalents are cache_read_input_tokens and cache_creation_input_tokens.
Logging cached tokens per request is the quickest way to see whether a long system prompt is actually being reused. Our docs say GPT, DeepSeek, Qwen and GLM models cache a repeated prompt start on their own, while Claude caches only when the request marks it with cache_control. Cached input is billed at each model's Cached input price, shown on its page. For a deeper look at structuring prompts so the cache hits, see our guide to prompt caching for coding agents.
One caveat from our reliability docs: cached input is kept per channel, so a request that moves to another channel can miss the cache once. A sudden drop in cached_tokens on a single request is not necessarily a bug in your prompt.
07 · Symptom, cause and fix
| Symptom | Cause | Fix |
|---|---|---|
usage is None on every chunk |
No stream_options |
Send {"include_usage": true} |
IndexError on the last chunk |
Usage chunk has empty choices |
Guard with if chunk.choices |
No x-oceantoken-cost header |
Headers sent before the first token | GET /v1/usage/{id} after the stream |
/v1/usage/{id} returns 404 right away |
Cost not recorded yet | Retry after a few seconds |
| 404 that never clears | Different key, or a resp_/msg_ id |
Same key; use x-oceantoken-request-id |
| Cost higher than visible text suggests | Reasoning billed as output | Read reasoning_tokens |
| Non-streamed long answer fails with 504 | 240-second limit on synchronous requests | Stream it |
Stream ends without finish_reason |
Incomplete stream | Retry the request |
The 504 row deserves a sentence. Our limits page says a synchronous request is held open for at most 240 seconds, after which the client sees 504 timeout, while a stream stays open as long as tokens keep flowing. That is why the advice is to stream long answers, and why getting usage right on streams matters more than it first appears.
08 · Where this fits in a billing pipeline
For most apps, a sensible flow is: stream to the user with include_usage, write the token counts and request id to your own table as soon as the stream ends, then let a background job fill in cost from /v1/usage. If you only need totals per day, the console's Activity and Logs pages may be enough, and you can skip the lookup entirely.
If you need to stop spending before it happens rather than measure it afterwards, a per-key credit limit is the better tool; our guide to budget guardrails with a prepaid balance covers that. Our docs also document POST /oceantoken/billing/summary, which returns the balance your requests are charged to, readable with the same key and at no charge.

How to test this on your workload
We have not run your traffic through this code, so here is how we would verify it in an afternoon:
- Stream one request without
stream_optionsand confirmusageisNoneon every chunk, so you know the baseline. - Add
include_usageand confirm the last chunk hasusageand an emptychoiceslist. - Call
/v1/usage/{id}immediately after the stream ends and record whether it answers 404, then how many seconds it takes to answer 200. - Call it with a different key and confirm 404.
- Compare the lookup's
usagewith the usage chunk from the stream for the same request. - Stream a
/v1/responsesrequest, try the lookup with theresp_id, then withx-oceantoken-request-id, and record which one works. - Ask a reasoning model a hard question and check that
completion_tokensincludesreasoning_tokens. - Send the same long system prompt twice and check
cached_tokenson the second request.
Our take: Stream every answer a person waits on, always with include_usage, and treat the cost lookup as background bookkeeping rather than part of the response. Store the completion id on chat completions and the x-oceantoken-request-id header everywhere else. Read reasoning and cache numbers from usage, never from answer length.
Running it on OceanToken
From our docs, as of November 28, 2026:
- One base URL for every chat model.
https://api.oceantoken.ai/v1works with the OpenAI SDK; switching fromdeepseek/deepseek-v4.1-flashto another model is a change of themodelid, and the same usage code applies. - Cost from code. Non-streamed responses carry
x-oceantoken-cost; streamed ones are looked up by id at/v1/usage. - Every request in Logs. The console lists what each request was charged, with cache Hit or Miss.
- Three request shapes. Chat Completions, Responses and Anthropic Messages on every text model.
Price: see the current rate on /pricing, per model on /models, and for DeepSeek on /deepseek-api. For the wider switch from OpenAI, see our guides to the DeepSeek API with the OpenAI SDK, model switching gotchas and a unified API for chat, image and video apps.
FAQ
Why is usage null when streaming? Chat-completions streams leave out token counts unless you send stream_options with include_usage: true. Then the last chunk before [DONE] carries them.
How do I get the cost of a streamed response? Call GET /v1/usage/{id} with the completion id after the stream ends, using the same key. Retry if it answers 404 in the first few seconds.
Why does the usage lookup return 404? Either the cost is not recorded yet, the key is different from the one that made the request, or the id is a resp_ or msg_ id. Use x-oceantoken-request-id in the last case.
Are reasoning tokens included in completion_tokens? Yes. completion_tokens includes reasoning, and completion_tokens_details.reasoning_tokens shows that part separately.
Do I pay for a stream I cancel? Our errors page says a stream that ends early is billed for its prompt and the output streamed so far, and a cancelled stream can be billed for some output the channel kept generating. See the errors page for the exact rule.
Sources
- OceanToken docs: Text generation (checked 2026-11-28)
- OceanToken docs: API reference, Streaming and What a request cost (checked 2026-11-28)
- OceanToken docs: Errors (checked 2026-11-28)
- OceanToken docs: Limits (checked 2026-11-28)
- OceanToken docs: Reliability (checked 2026-11-28)
- OceanToken docs: DeepSeek V4.1 Flash model spec (checked 2026-11-28)
Get your OceanToken API key
- Create an OceanToken account and an API key.
- Copy the snippet below, paste your key, and run it.
- Check the current rate on /deepseek-api.
curl https://api.oceantoken.ai/v1/chat/completions \
-H "Authorization: Bearer $OCEANTOKEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "deepseek/deepseek-v4.1-flash", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "Count from one to five."}]}'
More from the blog
LLM API Request Timeout: Fix 504 and 408
Why an LLM API request timeout happens after switching to a reasoning model or long output: the 240-second 504, the 120-second silent-stream 408, and the fixes.
Speech to Text API Accuracy: Fix Names
Improve speech to text API accuracy: set language as an ISO-639-1 code, pass names in prompt, upload the file rather than a URL, and measure on your audio.
Hailuo Video Problems: 10 Fixes by Symptom
Hailuo video problems sorted by symptom: morphing faces, static or frantic motion, ignored camera moves, refused requests. Causes, fixes and a triage table.