AI streaming
Show an AI answer word by word in your app while a task generates it on a worker.
Stream a model's answer to the browser as it is written. The task runs on a worker, not in your web request. The run keeps every part, so a page refresh or a dropped connection picks up where it left off, and long answers never hit a request timeout.
model ── tokens ──► task ── context.stream('answer').pipe() ──► storage
│
browser ◄── parts, live ── realtime handler ◄─────────────────────┘The Runlane calls below are real. The marked streamAnswer() call is pseudocode for your model client. It returns the same shape as the AI SDK's streamText(): a textStream to read parts from, and a text promise for the full answer.
1. Stream from the task
Declare a stream on the task, pipe the model's text into it, and return the full answer as the output:
import { task } from '@runlane/core'
import * as z from 'zod'
export const answerQuestion = task({
id: 'ai.answer',
schema: z.object({ question: z.string().min(1) }),
output: z.object({ text: z.string() }),
streams: { answer: z.string() },
async run({ question }, context) {
//////////////////////////////////
// MAKE YOUR API CALLS HERE
//////////////////////////////////
const result = streamAnswer({ question, signal: context.signal })
await context.stream('answer').pipe(result.textStream)
return { text: await result.text }
},
})streams: { answer: z.string() }declares a stream namedanswer. Each part is a string.pipe()saves parts in small batches as they arrive. A slow model doesn't hold back parts that are already saved.context.signallets a cancel stop the model call too.- The returned
textis the run's final output. Readers that only need the result can skip the stream.
2. Start the run
Trigger the task from your server, the same way you trigger any task. Tag it with the user, so your realtime handler can check who may read it:
'use server'
import { runlane } from '@/runlane'
import { answerQuestion } from '@/tasks/answer-question'
import { getSession } from './auth'
export async function askQuestion(question: string) {
const session = await getSession()
const { run } = await runlane.trigger(answerQuestion, { question }, { tags: [`user:${session.userId}`] })
return { runId: run.id }
}getSession stands for your app's own session check. If you haven't mounted the realtime handler yet, follow set up realtime first.
3. Show it in React
'use client'
import { useRun, useRunStream } from '@runlane/react'
import type { answerQuestion } from '@/tasks/answer-question'
export function Answer({ runId }: { runId: string }) {
const { run } = useRun<typeof answerQuestion>(runId)
const answer = useRunStream<typeof answerQuestion>(runId, 'answer')
if (answer.error) return <p>Could not load the answer.</p>
return (
<section>
<p>{run?.output ? 'Done' : 'Writing…'}</p>
<p>{answer.parts.join('')}</p>
</section>
)
}The text grows as the model writes. If the page reloads, the hook reads the saved parts first, then follows new ones. Nothing repeats and nothing is lost.
What happens when things go wrong
| Situation | What the user sees |
|---|---|
| The connection drops | The client reconnects and continues from the last part |
| The user reloads the page | Saved parts appear at once, then new ones keep coming |
| The model call fails and the task retries | The text clears and the new attempt's answer streams in. Two answers never mix. |
| The user leaves the page | The task keeps running. The full answer is saved on the run. |
| You cancel the run | context.signal stops the model call. Parts saved so far stay readable. |
Before you ship
- Check access. Every reader goes through your realtime
authorizecheck or a token. See authorize readers. - Pass
context.signalto your model client, so cancels and deploys stop the call quickly. - Decide on retries. A retry calls the model again and streams a new answer. If a finished answer must never be regenerated, save it with a step. A replayed step returns the saved answer without streaming it again.
- Keep parts small. Each part must fit
contractDefaults.streams.maxChunkBytes, and a run has a total stream budget. See stream limits. - Use a durable lane in production. The local lane requires
runlane devand keeps parts only while dev runs. Without dev, the trigger fails. UsecreateTestLane()for in-process streaming tests. Postgres keeps them until the run is pruned.