docs: token-usage callback cookbook never consumes its stream
Description
The first onEnd example in Record Token Usage After Streaming Object constructs a streamText result but never consumes it. Copying this standalone Node example starts generation but does not reach onEnd, so the promised token-usage log is absent. This is a documentation example problem; stream backpressure itself is expected.
Pinned current-main source: https://github.com/vercel/ai/blob/3216f06d0d892b03ad607b4716bbf04056cbfe3d/content/cookbook/05-node/45-stream-object-record-token-usage.mdx#L17-L37
Reproduction
Run this as an ES module with ai and zod installed. It uses the SDK's deterministic mock, requires no API key, and makes no provider requests. The finite source already contains the finish event. The first assertion verifies that the cookbook's unconsumed result never logs usage during the observation window; explicitly draining that same result completes it and fires the callback exactly once.
import assert from 'node:assert/strict';
import { setTimeout as delay } from 'node:timers/promises';
import { streamText, Output } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
import { z } from 'zod';
let callbacks = 0;
const text = JSON.stringify({ recipe: { name: 'Lasagna', ingredients: ['pasta'], steps: ['Bake'] } });
const model = new MockLanguageModelV4({
doStream: async () => ({
stream: new ReadableStream({
start(controller) {
for (const part of [
{ type: 'stream-start', warnings: [] },
{ type: 'text-start', id: 't' },
{ type: 'text-delta', id: 't', delta: text },
{ type: 'text-end', id: 't' },
{ type: 'finish', finishReason: { unified: 'stop', raw: 'stop' }, usage: {
inputTokens: { total: 10, noCache: 10 },
outputTokens: { total: 20, text: 20 },
} },
]) controller.enqueue(part);
controller.close();
},
}),
}),
});
const result = streamText({
model,
output: Output.object({ schema: z.object({ recipe: z.object({
name: z.string(), ingredients: z.array(z.string()), steps: z.array(z.string()),
}) }) }),
prompt: 'Generate a lasagna recipe.',
onEnd({ usage }) {
callbacks++;
console.log('Token usage:', usage.totalTokens);
},
});
// The cookbook's first example ends here, without reading the result.
await delay(100);
assert.equal(model.doStreamCalls.length, 1);
assert.equal(callbacks, 0);
// Proposed addition to the example:
await result.consumeStream();
assert.equal(callbacks, 1);
assert.deepEqual(await result.output, JSON.parse(text));
console.log('PASS: usage callback runs once only after the stream is consumed.');
I also extracted and executed the entire first TypeScript block from the pinned MDX with its actual schema and callback, substituting only the provider identifier with the mock and capturing console output. Both a single text delta and character-by-character deltas reproduce the missing callback. Adding await result.consumeStream() to the extracted block records exactly one callback with 10 input / 20 output / 30 total tokens and preserves the valid structured output.
Suggested correction
After constructing result in the first example, add:
// Consume the stream so onEnd can record usage.
await result.consumeStream();
A sentence explaining that the stream must be consumed (for example by iterating partialOutputStream, piping it, or using consumeStream) would make the dependency clear. The second example already accesses result.usage and iterates the partial output; this report concerns the first callback-only block.
AI SDK Version
- Current documentation snapshot:
3216f06d0d892b03ad607b4716bbf04056cbfe3d, file blob1a9b6a5250aa382ec8c30a591ed929968d13fc97. - Behavior validated with locally built
ai7.0.147, Zod 3.25.76, Node.js 24.18.0 on Windows. Current main's manifest is 7.0.155; I have not claimed execution against that newer runtime. - Current-main stream source was inspected for the streamText execution path; no runtime fix is requested.
Related historical #15721 renames lifecycle callbacks on this page but leaves the missing stream consumption unchanged; it is closed and is not an adequate fix for this behavior. Searches for the page, callback consumption and token-usage cookbook fixes found no matching current fix.
AI assistance: investigated and validated with Codex. I agree to follow the project's Code of Conduct.
Identify issue type
Identified as Documentation
Confidence: High
Rationale
This requests a correction to a documentation example and its explanation, not a change to SDK behavior or a runnable example project.
Evidence
- The issue targets the first code block in a cookbook MDX documentation page, which omits stream consumption before expecting onEnd to log usage.
- The requested correction adds await result.consumeStream() and explains the consumption requirement.
- The reporter states that backpressure is expected and no SDK runtime fix is requested.
Thanks for the detailed report and the mock-based reproduction! I've opened a PR adding await result.consumeStream() to the first example along with a sentence explaining that onEnd only fires once the stream is consumed (via partialOutputStream, piping, or consumeStream). The second example is unchanged since it already consumes the stream.
Thanks for the fix. I independently executed the first code block from the exact proposed MDX at 20eb3e18c04da6c59ff6913f46ae3b4e603e3272, without adding a drain in the harness. With both a single text delta and character-by-character deltas, it records usage once (10 input / 20 output / 30 total) and preserves the valid structured output. The unchanged baseline still reproduces the missing callback. This uses real streamText/Output, Zod and MockLanguageModelV4 on ai 7.0.147, with no provider calls; it is targeted example validation, not full CI or maintainer approval.
One remaining merge prerequisite: GitHub currently reports that commit as verified: false, reason unsigned. The contribution guide requires signed commits and says unsigned PR history cannot be merged. Please ensure the submitted commit is signed. Required fork CI also currently awaits maintainer approval.
I'll track the existing PR #24198 rather than open a competing implementation. AI assistance: validation performed with Codex.