Get an API key
api.models

turn · streaming

api.models.turn({ onText })

Pass onText and the answer arrives in fragments as it is written. The promise still resolves with the whole turn.

onText switches to SSEsame return valueno deadline
Using Python?

Switch any code block to Python: the choice applies to every page. Python SDK guide and resource reference.

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 always
import 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 always

What arrives

FrameMeans
textA fragment. onText is called with it.
turnThe complete turn. The promise resolves with it.
errorThe 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)
Aborting stops you listening, not the server working

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")
Do not forward the error straight through

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

CodeStatusWhen
turn_incomplete502The stream ended with no turn frame.
turn_failed502The provider refused mid-stream.
not_enough_credits402Raised 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.