Skip to content

Workers AI

The Workers AI binding runs models on Cloudflare's network from a handler: event.runtime.env.AI.run(model, inputs). It needs the cloudflare preset and an ai entry in your wrangler config:

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

With that config, hamur typegen types event.runtime.env.AI as HamurAi, whose run(model, inputs, options?) returns Promise<unknown>: the shape of the result depends on the model, so you state it. The handler below does that with a small interface of its own, which also makes it compile without a wrangler config. event.runtime.env is where the binding lives on a Worker; on any other preset it has no AI, and the handler answers 501.

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

interface Env {
  AI: { run(model: string, inputs: { prompt: string; max_tokens?: number }): Promise<{ response?: string }> }
}

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
}

export const summarize = defineHandler({
  route: "/api/summarize",
  method: "GET",
  async handler(_, { event }) {
    const { AI } = bindings(event)
    const text = String(getQuery(event).text ?? "")
    const { response } = await AI.run("@cf/meta/llama-3.1-8b-instruct", {
      prompt: `Summarize in one sentence: ${text}`,
      max_tokens: 100,
    })
    return { summary: response ?? "" }
  },
})

Things to know:

  • The input shape belongs to the model: this one takes { prompt } and answers { response }; a chat model takes messages, an embedding model { text } and answers { data }. The Cloudflare model catalog lists each.
  • hamur dev does not call Cloudflare: bindings are local only (remoteBindings: false), so env.AI is absent in dev and the handler answers 501. Test a Workers AI handler on a deployed preview, or give dev a stand-in. See Dev bindings.
  • Workers AI is billed to your account on every call; a route that reaches AI.run needs the same guard as any paid endpoint, such as a rateLimit rule.
  • To send tokens as they are produced, see An AI answer as a stream.