req.env.AI in every handler once you add the binding to your Env type. You get access to a broad catalog of model families — text generation, embeddings, image classification, speech recognition, and more — with optional streaming for real-time output.
Configure the binding
1
Add the AI binding to wrangler.toml
wrangler.toml
2
Define the Env type
src/types/env.ts
3
Pass Env to createApp
src/index.ts
Text generation
Callreq.env.AI.run(model, inputs) to run inference synchronously. Pass a messages array in the OpenAI chat format and set stream: false to receive the complete response in one go.
Streaming responses
Setstream: true to receive a ReadableStream of server-sent events. Pipe it directly to the client using res.stream() so tokens appear in the browser as they are generated — with no buffering in your Worker.
EventSource API or fetch with a ReadableStream reader:
Available models
Workers AI supports multiple model families. Browse the full catalog — including model IDs, input/output schemas, and benchmark scores — at developers.cloudflare.com/workers-ai/models/.Error handling
AI inference can fail due to upstream model errors, invalid inputs, or capacity limits. Wrap everyreq.env.AI.run() call in a try/catch and throw a BlazeError(502) so your global error handler can return a consistent error shape.
BlazeError instances are serialized consistently:
Workers AI usage is metered by Neurons — Cloudflare’s unit of inference
compute. Costs and rate limits vary by model and plan. Monitor your
consumption and configure spending limits in the Cloudflare dashboard →
Workers AI section. Streaming responses consume the same number of Neurons
as non-streaming calls for the same input and output length.