AI Model Run: Bindings, REST API, Streaming, and Embeddings
How to call hosted AI models from Workers bindings, HTTP, and OpenAI-compatible APIs—with prompts, streaming, LoRA, and batch queue.
This page summarizes Cloudflare Workers AI documentation on running models: the same patterns appear on every model page (for example llama-3.1-8b-instruct-fp8 and bge-base-en-v1.5). You pick a model id such as @cf/meta/llama-3.1-8b-instruct, pass inputs that match the model type, and read JSON or a stream back.
Workers AI binding: how env.AI.run() calls a model
Section titled “Workers AI binding: how env.AI.run() calls a model”Workers AI is exposed as an AI binding on Workers and Pages Functions. In a Worker you call async env.AI.run() with the model id as the first argument and an input object as the second.
async env.AI.run() runs a model. Takes a model as the first parameter, and an object as the second parameter.
— Cloudflare, Workers Bindings
On Pages, the binding lives on context.env:
To use Workers AI in your Pages Function, you can access your Workers AI binding in your Pages Function code.
— Cloudflare, Use Workers AI bindings
Declare AI: Ai in your environment type so TypeScript knows the binding exists.
Chat and text generation: messages and optional stream
Section titled “Chat and text generation: messages and optional stream”Instruction-tuned chat models expect a scoped prompt: an array of messages with role and content. Set stream: true when you want tokens as they are generated; return the body with content-type: text/event-stream when you pipe that stream to the client (as in apertus-v1.5-8b).
For a one-shot question without building messages, the binding also accepts a simple prompt string on some models (see Workers Bindings).
Embeddings: text as a string or array
Section titled “Embeddings: text as a string or array”Embedding models take text, which may be a single string or an array of strings. The comment in the docs applies across BGE, Gemma embedding, and similar models:
// Can be a string or array of strings]
(The trailing ] is reproduced from the source examples on bge-base-en-v1.5.)
Reranking, classification, and translation inputs
Section titled “Reranking, classification, and translation inputs”Model input shape follows the task, not the brand name:
| Task | Typical input keys | Example model doc |
|---|---|---|
| Rerank | query, contexts (objects with text) |
bge-reranker-base |
| Sentiment / classification | text |
distilbert-sst-2-int8 |
| Translation | text, source_lang, target_lang |
m2m100-1.2b |
| Indic translation | text, target_language |
indictrans2-en-indic-1B |
Always open the model’s own usage section for required fields; the HTTP path is the same for all of them.
REST API and curl: run a model without a Worker
Section titled “REST API and curl: run a model without a Worker”From a server or script, POST to:
https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/{MODEL_ID}
Send Authorization: Bearer {API_TOKEN} and a JSON body that matches the model (for example messages for chat or text for embeddings). Python and curl examples on deepseek-r1-distill-qwen-32b and bge-m3 use the same URL pattern; only the model segment and JSON body change.
OpenAI-compatible /v1 endpoints: SDKs and chat completions
Section titled “OpenAI-compatible /v1 endpoints: SDKs and chat completions”Many text models support the OpenAI Chat Completions shape; embedding models support the Embeddings API.
Most Workers AI text generation models support the OpenAI Chat Completions API. Embedding models support the OpenAI Embeddings API.
— Cloudflare, OpenAI compatible API endpoints
Point the OpenAI client at:
https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1
Use your Cloudflare API token as apiKey and pass Workers AI model ids (for example @cf/meta/llama-3.1-8b-instruct) as model. The same page documents POST .../ai/v1/chat/completions for raw HTTP.
Individual model pages also note:
Workers AI also supports OpenAI compatible API endpoints for /v1/chat/completions and /v1/embeddings.
— Cloudflare, bge-large-en-v1.5
The Vercel AI SDK wraps the binding via createAI({ binding: env.AI }) for generateText, streamText, embedMany, reranking, and other modalities.
Scoped prompts vs unscoped prompt and raw
Section titled “Scoped prompts vs unscoped prompt and raw”Cloudflare recommends scoped prompts so you do not hand-roll each model’s chat template:
This is the recommended method. With scoped prompts, Workers AI takes the burden of knowing and using different chat templates for different models and provides a unified interface to developers when building prompts and creating text generation tasks.
— Cloudflare, Prompting
Roles:
system— behavior and rulesuser— the question or instructionassistant— prior turns or format hints (not every model supports this role)
Unscoped { prompt: "..." } is converted internally to a reasonable default scoped prompt. For full control of a vendor template (for example Mistral [INST] blocks), pass raw: true with a handcrafted prompt string.
Function calling, LoRA adapters, and batch inference
Section titled “Function calling, LoRA adapters, and batch inference”Traditional function calling — You pass a tools array; the model returns tool_calls with arguments you execute yourself:
With traditional function calling, you define an array of tools with the name, description, and tool arguments.
— Cloudflare, Traditional function calling
Embedded function calling — runWithTools from @cloudflare/ai-utils runs tool functions inside the Worker (for example fetch() to an external API or KV put). The function calling overview states embedded calling reduced example code from 77 to 31 lines versus the traditional loop.
LoRA — On supported base models, pass lora with a finetune id or public adapter name; use raw: true when the adapter expects a specific template (Using LoRA adapters, Public LoRA adapters).
Batch queue — For large or offline workloads, send many sub-requests in one payload. REST uses ?queueRequest=true on the run URL (REST API batch); the binding passes { queueRequest: true } as a third argument to env.AI.run() (Workers Binding batch). Poll with request_id until status is no longer queued or running. Keep total payload under 10 MB per the Workers Binding batch docs.
Embeddings for search: Vectorize and query shape
Section titled “Embeddings for search: Vectorize and query shape”Embeddings from env.AI.run() are numeric vectors suitable for similarity search. Vector databases explains that a text embedding is a one-way numeric representation of how the model understands the input.
When querying a Vectorize index, pass the vector array itself, not the full API wrapper object (query vectors best practices — same idea applies when the embedding came from Workers AI run()).
A minimal RAG-style flow: embed with bge-m3 or bge-reranker-base for reranking, store vectors in Vectorize, then call a chat model with retrieved context in messages.
Common mistakes
Section titled “Common mistakes”- Using
messageson an embedding model ortexton a chat-only model — match the model doc’s usage section. - Forgetting
stream: truein the input but expecting a stream, or omittingtext/event-streamon theResponseheaders when returning a stream. - Calling Vectorize with the whole JSON response instead of the embedding vector array.
- Mixing unscoped
promptwith chat models that expect multi-turnmessageswithout reading Prompting. - Batch jobs: losing
request_idor exceeding the 10 MB batch payload limit.
How to check this on your site
Section titled “How to check this on your site”- In the Cloudflare dashboard, confirm the account has Workers AI enabled and create an API token with permission to run models. Use that token in the examples on Workers Bindings.
- Deploy a minimal Worker with an
AIbinding and callenv.AI.run()with a model from the catalog (for example llama-3.1-8b-instruct-fp8); confirm JSON or streamed text in the response. - From your machine, run the curl example on any model page (for example bge-small-en-v1.5) and check HTTP 200 and a non-empty
result. - If you use OpenAI client libraries, point
baseURLat OpenAI compatible API endpoints and run one chat and one embeddings call. - You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match the official docs or your setup, email yimasynthetic@gmail.com with the page URL and the exact sentence you think is wrong.