Streaming answers
A model writes its answer a few words at a time. $llm.text.streamAsync() hands you each piece as it's written, so a page
can show the answer as it appears instead of after a wait:
const r: LlmTextAnswer = await $llm.text.streamAsync({ model: "vultr/glm-5.3", prompt: question }, (text) => {
// called with each piece, in order; return false to stop the answer there
})
// r is the whole answer, as $llm.text.completeAsync returns it
s, err := textv1.Contract.Must(app).Stream(ctx, extkit.Internal, textv1.CompleteInput{Model: "vultr/glm-5.3", Prompt: question})
if err != nil {
return err
}
var r *textv1.CompleteResult
err = s.Run(ctx, func(e any) error {
c := e.(textv1.Chunk) // a piece of text, in order; the last one is Done, with the whole answer
if c.Done {
r = c.Result
}
return nil // an error stops the answer there
})
A third argument, onReasoning, gets the model's thinking as it's written, when the provider sends it. The callbacks
run on the app's JS VM between pieces; the waiting for each piece doesn't, so other requests are served meanwhile.
In a page
A Pages API route forwards the pieces to the browser as server-sent events:
// pb_pages/ask.ts
module.exports = {
async post(ctx) {
const { question } = ctx.req.body()
const stream = ctx.res.sse()
try {
const r: LlmTextAnswer = await $llm.text.streamAsync({ model: "vultr/glm-5.3", prompt: question }, (text) => stream.send("text", JSON.stringify(text)))
stream.send("done", JSON.stringify({ usage: r.usage }))
} catch (err: any) {
stream.send("error", JSON.stringify(String(err.message || err)))
}
stream.close()
},
}
In the browser, read the response as it arrives:
// in the browser
const res = await fetch("/ask", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question }) })
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader()
let buf = "", answer = ""
for (;;) {
const { value, done } = await reader.read()
if (done) break
buf += value
let i
while ((i = buf.indexOf("\n\n")) >= 0) {
const block = buf.slice(0, i)
buf = buf.slice(i + 2)
const event = (block.match(/^event: (.*)$/m) || [])[1]
const data = (block.match(/^data: (.*)$/m) || [])[1]
if (event === "text") answer += JSON.parse(data) // show it
}
}
The browser's EventSource only makes GET requests, which is why this reads the stream with fetch.
Over HTTP
Outside your app's code, POST /api/_c/llm.text/v1/stream does the same, with the same body as complete, as a
superuser or with a token that has the llm scope. Each piece is an event: stream with {"text": "..."}, and the
last one is {"done": true, "result": {...}}.
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.