Streaming changes when you see the text, not what you get. The call still resolves with the complete turn — fragments are an addition, not a replacement.
const turn = await api.models.turn({
model: "gemini-3.5-flash",
messages: [{ role: "user", content: "Explain backpressure in three paragraphs." }],
onText: (delta) => process.stdout.write(delta),
});
turn.message.content; // the whole text, assembled
turn.usage.credits; // the cost, as alwaysimport sys
turn = api.models.turn(
model="gemini-3.5-flash",
messages=[{"role": "user", "content": "Explain backpressure in three paragraphs."}],
on_text=lambda delta: sys.stdout.write(delta),
)
turn["message"]["content"] # the whole text, assembled
turn["usage"]["credits"] # the cost, as alwaysWhat arrives
| Frame | Means |
|---|---|
| text | A fragment. onText is called with it. |
| turn | The complete turn. The promise resolves with it. |
| error | The turn failed. The promise rejects. |
Fragments are pieces of text, not whole words or sentences — concatenate them, never treat one as a unit. A stream that ends without a turn frame rejects with turn_incomplete.
Tool calls do not stream
Text streams; a decision to call a tool arrives whole, in the final frame. So a turn that goes straight to a tool call may emit no fragments at all — which is normal, and worth handling in a UI that shows « thinking » until the first one.
let started = false;
const turn = await api.models.turn({
model, messages, tools,
onText: (delta) => { started = true; ui.append(delta); },
});
if (!started && turn.stopReason === "tool_use") {
ui.status(`Running ${turn.message.toolCalls.map((c) => c.name).join(", ")}…`);
}started = False
def on_text(delta):
global started
started = True
ui.append(delta)
turn = api.models.turn(model=model, messages=messages, tools=tools, on_text=on_text)
if not started and turn["stopReason"] == "tool_use":
ui.status(f"Running {', '.join(c['name'] for c in turn['message']['toolCalls'])}…")A streaming call has no deadline
A non-streaming turn gives up after five minutes. A streaming one does not, because a long answer is exactly what streaming is for. Bound it yourself with an AbortSignal when you need an upper limit.
const controller = new AbortController();
const stopAfter = setTimeout(() => controller.abort(), 120_000);
try {
await api.models.turn({ model, messages, onText, signal: controller.signal });
} finally {
clearTimeout(stopAfter);
}# Python bounds a turn with timeout= (seconds) instead of an AbortSignal
api.models.turn(model=model, messages=messages, on_text=on_text, timeout=120)The turn continues to completion and is billed. Abort to free your side and to stop waiting — not as a way to avoid paying for something you asked for.
Forwarding to a browser
The usual shape: your server holds the key and streams to the page. Send the fragments as they arrive, then a final event with what the page needs — cost, stop reason, anything you want shown.
export async function POST(request) {
const { question } = await request.json();
const stream = new ReadableStream({
async start(controller) {
const send = (event, data) =>
controller.enqueue(new TextEncoder().encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));
try {
const turn = await api.models.turn({
model: "gemini-3.5-flash",
messages: [{ role: "user", content: question }],
onText: (delta) => send("text", { delta }),
});
send("done", { credits: turn.usage.credits, stopReason: turn.stopReason });
} catch (err) {
send("error", { message: "The answer could not be completed." });
} finally {
controller.close();
}
},
});
return new Response(stream, { headers: { "Content-Type": "text/event-stream" } });
}# FastAPI: forward the deltas as server-sent events
import json, queue, threading
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
@app.post("/answer")
def answer(body: dict):
events = queue.Queue()
send = lambda event, data: events.put(f"event: {event}\ndata: {json.dumps(data)}\n\n")
def run():
try:
turn = api.models.turn(
model="gemini-3.5-flash",
messages=[{"role": "user", "content": body["question"]}],
on_text=lambda delta: send("text", {"delta": delta}),
)
send("done", {"credits": turn["usage"]["credits"], "stopReason": turn["stopReason"]})
except Exception:
send("error", {"message": "The answer could not be completed."})
finally:
events.put(None)
threading.Thread(target=run, daemon=True).start()
return StreamingResponse(iter(events.get, None), media_type="text/event-stream")A provider's message can name things your users have no business seeing. Log it on your side, send a short one to the page.
Errors
| Code | Status | When |
|---|---|---|
| turn_incomplete | 502 | The stream ended with no turn frame. |
| turn_failed | 502 | The provider refused mid-stream. |
| not_enough_credits | 402 | Raised as NotEnoughCredits, even inside the stream. |
A failure can arrive after fragments have already been shown. Decide what your interface does with half an answer — keeping it with a visible failure is usually kinder than making it disappear.