Skip to content

An AI answer as a stream

A model writes its answer token by token. createEventStream sends each token to the browser as a server-sent event while the model is still writing, so the page shows the answer as it grows instead of after the last token. This recipe combines Workers AI, which streams when you pass stream: true, with the generator form of createEventStream.

jsonc
{
  "name": "my-app",
  "ai": { "binding": "AI" },
  "vectorize": [{ "binding": "VECTORIZE", "index_name": "docs" }],
  "browser": { "binding": "BROWSER" },
}

With stream: true, AI.run resolves a ReadableStream of server-sent events: lines of data: {"response":"<token>"}, then data: [DONE]. The tokens generator reads that stream, splits it into lines and yields each token; the handler hands it to createEventStream:

ts
import { createError, createEventStream, defineHandler, getQuery } from "hamur/server"
import type { HamurEvent } from "hamur/server"

interface Env {
  AI: {
    run(
      model: string,
      inputs: { messages: Array<{ role: "system" | "user"; content: string }>; stream: true },
    ): Promise<ReadableStream<Uint8Array>>
  }
}

const bindings = (event: HamurEvent): Env => {
  const env = event.runtime.env as unknown as Partial<Env> | undefined
  if (!env?.AI) throw createError({ status: 501, message: "The AI binding is not configured" })
  return env as Env
}

async function* tokens(body: ReadableStream<Uint8Array>, signal: AbortSignal): AsyncGenerator<string> {
  const reader = body.getReader()
  const decoder = new TextDecoder()
  let pending = ""
  try {
    while (!signal.aborted) {
      const { done, value } = await reader.read()
      if (done) return
      pending += decoder.decode(value, { stream: true })
      const lines = pending.split("\n")
      pending = lines.pop() ?? ""
      for (const line of lines) {
        if (!line.startsWith("data: ")) continue
        const data = line.slice(6).trim()
        if (data === "[DONE]") return
        const { response } = JSON.parse(data) as { response?: string }
        if (response) yield response
      }
    }
  } finally {
    await reader.cancel().catch(() => {})
  }
}

export const answer = defineHandler({
  route: "/api/answer",
  method: "GET",
  raw: true,
  async handler(_, { event }) {
    const { AI } = bindings(event)
    const question = String(getQuery(event).q ?? "")
    const body = await AI.run("@cf/meta/llama-3.1-8b-instruct", {
      messages: [
        { role: "system", content: "Answer in two sentences." },
        { role: "user", content: question },
      ],
      stream: true,
    })
    return createEventStream(event, async function* (signal) {
      for await (const token of tokens(body, signal)) yield { data: token, event: "token" }
    })
  },
})
  • createEventStream(event, source) with a function returns the Response itself. Each value the generator yields is one event, and the next token is pulled only after the previous push resolved, so a slow reader slows the model's stream instead of filling a buffer. The end of the generator writes event: end.
  • The signal is aborted when the client leaves. The generator stops and its finally cancels the model's stream, so an abandoned request stops reading.
  • Server-sent events are streamed on cloudflare; the streaming level of the preset says whether a streamed answer reaches the client as it is written (see Preset features).

The browser side reads the events with $fetch.stream, which yields each event with its event name and its text:

ts
import { $fetch } from "hamur/app"

export async function ask(question: string, onToken: (token: string) => void, signal: AbortSignal): Promise<void> {
  for await (const message of $fetch.stream(`/api/answer?q=${encodeURIComponent(question)}`, { signal })) {
    if (message.event === "token") onToken(message.text)
  }
}

An EventSource works as well for a GET route: listen for the token event and close the source on end. See Server-sent events.