Workers AI Model Run, API Endpoints, Streaming and Tools
How to call Cloudflare Workers AI catalog models from env.AI.run or account REST—endpoints, payloads, streaming, search, tools, and vision.
This page summarizes how Cloudflare Workers AI documents invoking catalog models from a Worker with env.AI.run or from the account AI REST API. The same model id (for example anthropic/claude-sonnet-5.5 or google/gemini-3.5-flash) appears in both paths; what changes is the HTTP route and the JSON body shape for that provider.
env.AI.run: how to call a catalog model from a Worker
Section titled “env.AI.run: how to call a catalog model from a Worker”From a Worker bound to AI, Cloudflare’s examples use a single entry point:
const response = await env.AI.run('<provider>/<model-slug>', { /* payload */ })The first argument is the catalog slug exactly as on the model page (for example GPT-5.4 nano, AssemblyAI Universal-3 Pro, Inkling). The second argument is the same JSON the matching REST example sends in the body—not always wrapped in { "input": … } (see below).
For REST, examples share:
- Base:
https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/... - Headers:
Authorization: Bearer $CLOUDFLARE_API_TOKEN,Content-Type: application/json
Responses often include gatewayMetadata.keySource as Unified or BYOK; the model pages in this cluster show the field but do not define when each value applies.
/ai/run vs /ai/v1/messages vs chat completions vs Responses — which path for which model
Section titled “/ai/run vs /ai/v1/messages vs chat completions vs Responses — which path for which model”Cloudflare routes inference through four account-level patterns. Pick the one shown on the model’s Examples page; mixing paths is a common failure mode.
| Surface | Typical REST path | Model families in this cluster | Worker second argument |
|---|---|---|---|
| Generic run | POST .../ai/run |
Google Gemini; AssemblyAI speech; Grok TTS; MiniMax Music 2.6; many Muse Spark 1.x curls | Gemini: contents, generationConfig, optional systemInstruction (not { input } on Workers). REST: { "model", "input": { … } } |
| Messages (Anthropic-shaped) | POST .../ai/v1/messages |
Claude models, Inkling | system, messages, max_tokens, plus Anthropic options |
| Chat completions (OpenAI-shaped) | POST .../ai/v1/chat/completions |
OpenAI, Grok chat, DeepSeek, Beam, Ember, MiniMax, Qwen, Muse Spark Open, o3 | messages array with role / content |
| Responses | POST .../ai/v1/responses |
OpenAI web search; GPT-5.4 pro; Grok 4.20 Multi-Agent; Muse Wonder 1.0 | input (string or structured), instructions or tools—not messages on chat completions |
The response object type should match the route: chat.completion for chat, Anthropic message for Messages, response with an output[] array for Responses, and Gemini/AssemblyAI-style envelopes with result and state: "Completed" where Examples show that shape.
messages, system context, and multi-turn chat
Section titled “messages, system context, and multi-turn chat”Anthropic on Workers AI uses a top-level system string plus messages (user / assistant), as on Claude Sonnet 5.5. Longer threads repeat the full history; multi-turn examples use max_tokens and prior assistant turns (road-trip style prompts appear across many model pages).
OpenAI-style chat (including GPT-5, Grok 4.20 Reasoning, DeepSeek V4 Pro) puts the system prompt in messages with role: 'system'. Multi-turn and creative examples commonly set max_completion_tokens (often 8192).
Gemini uses systemInstruction: { parts: [{ text: '...' }] } and turns in contents with role: 'user' | 'model' and parts: [{ text: '...' }], as on Gemini 2.5 Flash. Output length uses generationConfig.maxOutputTokens.
Responses API models use instructions for persona (GPT-5.4 pro) or a single input string (Muse Wonder 1.0). Multi-turn on Responses uses input as an array of { role, content } messages.
Workers do not retain chat memory; you must resend the full thread on every call.
Output caps and truncation signals
Section titled “Output caps and truncation signals”| Parameter | Where documented | Note |
|---|---|---|
max_completion_tokens |
OpenAI/Grok/MiniMax chat, Spark Open | Chat completions |
max_output_tokens |
Responses, web search | Not interchangeable with max_completion_tokens |
max_tokens |
unbiased/pareto, some Qwen search examples | Pareto may return finish_reason: "length" when the cap is tight |
maxOutputTokens |
Gemini generationConfig |
Gemini 2.5 samples sometimes show finishReason: "MAX_TOKENS" with short visible text while thoughtsTokenCount is large—internal thinking can consume budget |
stream: true — streaming and usage on the last chunk
Section titled “stream: true — streaming and usage on the last chunk”Chat streaming examples set:
{ messages: [/* ... */], stream: true, stream_options: { include_usage: true },}Documented on GPT-4.1, GPT-5, Claude Sonnet 5.5, and others. Chunks use object: "chat.completion.chunk" with delta.content; the final chunk may have empty choices but includes usage when include_usage is true.
Anthropic streaming with stream: true yields SSE-style events (message_start, content_block_start, message_stop) on Claude pages. Qwen streaming may emit delta.reasoning_content before answer text (Qwen3.7 Max).
Web search and grounded answers: not one API
Section titled “Web search and grounded answers: not one API”Built-in search differs by provider on the same Cloudflare account API.
| Provider pattern | Mechanism | Example doc |
|---|---|---|
| OpenAI o-series / GPT (subset) | POST .../ai/v1/responses, input, tools: [{ type: 'web_search_preview' }] |
GPT-4.1 mini, o4-mini |
| Anthropic Claude | tools: [{ name: 'web_search', type: 'web_search_20250305', max_uses: 3 }] on Messages |
Claude Sonnet 5.5 |
| xAI Grok multi-agent | tools: [{ type: 'web_search' }] on Responses |
Grok 4.20 Multi-Agent |
| Meta Muse Spark | tools: [{ type: 'web_search' }] with input string |
Muse Spark 1.1 |
| Alibaba Qwen | enable_search: true on chat completions |
Qwen3 Max |
Web Search — Letting the model use OpenAI’s built-in web search tool to answer with current information
— Cloudflare, GPT-4.1 mini
Web Search — Letting Qwen use DashScope’s built-in web search via enable_search
— Cloudflare, Qwen3 Max
Responses-style search output often includes output[] items such as web_search_call and a message with output_text and url_citation annotations. Example bullet text and third-party URLs in docs are sample model output, not guaranteed live results.
Not every catalog page includes web search (for example GPT-4.1 nano and o3-mini lack it in these Examples).
Function tools, structured JSON, and speech or music on ai/run
Section titled “Function tools, structured JSON, and speech or music on ai/run”OpenAI-style function tools
Section titled “OpenAI-style function tools”Ember-1, Beam 1.0, and Grok 4.5 use tools with type: 'function', optional tool_choice: 'required', and strict: true on schemas. A required tool call returns finish_reason: "tool_calls" and tool_calls[].function.arguments as JSON text.
Beam documents strict structured output via response_format: { type: 'json_schema', json_schema: { strict: true, … } }.
Muse Spark 1.2 shows the full tool loop: assistant message with tool_calls, then role: 'tool' with matching tool_call_id.
Anthropic-style tools (Messages)
Section titled “Anthropic-style tools (Messages)”Claude Sonnet 5.5 uses native tools with input_schema. Inkling uses tool_use / tool_result content blocks on /ai/v1/messages, not OpenAI tool_calls.
AssemblyAI Universal-3 Pro on /ai/run
Section titled “AssemblyAI Universal-3 Pro on /ai/run”Speech uses POST .../ai/run with { "model": "assemblyai/universal-3-pro", "input": { … } }. Examples cover:
Speaker Diarization — Identify different speakers in the audio
— Cloudflare, Universal-3 Pro
Inputs include audio_url, optional language_code, keyterms_prompt (domain terms), and speaker_labels: true (populates utterances and per-word speaker). Completed jobs return state: "Completed", transcript text, and words[] timing fields.
Grok TTS and MiniMax Music
Section titled “Grok TTS and MiniMax Music”Grok TTS passes text, voice_id, and output_format in Workers; REST wraps the same fields under input. MiniMax Music 2.6 returns result.audio as a URL when state is "Completed".
Vision and multimodal messages
Section titled “Vision and multimodal messages”| API shape | Image input | Example |
|---|---|---|
| Chat completions | content: [{ type: 'image_url', image_url: { url } }, { type: 'text', text }] |
Ember-1, Grok 4.5, Muse Spark Open, Qwen3.7 Plus |
Gemini ai/run |
parts with inlineData (mimeType, base64 data) |
Gemini 3.5 Flash |
| MiniMax M3.1 Flash | image_url or video_url with optional fps |
M3.1 Flash |
Use the part type the model page shows; image_url vs inlineData is not interchangeable across families.
thinking, output_config.effort, and temperature
Section titled “thinking, output_config.effort, and temperature”Controls are model-specific:
- Claude Fable 5 documents adaptive thinking with effort:
Adaptive thinking is always on for Claude Fable 5; use the
effortparameter to control depth.— Cloudflare, Claude Fable 5
Use output_config: { effort: 'high' } and thinking: { type: 'adaptive' }. Claude Opus 4.7 titles creative examples with adaptive thinking as the recommended replacement for the deprecated temperature parameter; older examples still show temperature: 0.8 for creative writing on other Claude pages.
-
Gemini 4 Argon spatial reasoning uses
generationConfig.thinkingConfig.thinkingLevel: 'HIGH'(Gemini 4 Argon). -
GPT-5.4 / 5.5 pro (Responses) use
reasoning: { effort: 'medium' | 'high' }(GPT-5.5 pro). -
Beam uses
reasoning_effort: 'medium'on chat completions (Beam 1.0). -
Grok reasoning models expose
reasoning_contenton the assistant message or in stream deltas; Grok 4.5+ may setreasoning_effort: 'low'for faster coding answers. -
MiniMax / DeepSeek / Qwen often return
reasoning_contentandusage.completion_tokens_details.reasoning_tokens.
Check usage and finish reasons when answers look truncated despite a high max-token setting.
AI Gateway: one OpenAI-compatible client, many backends
Section titled “AI Gateway: one OpenAI-compatible client, many backends”For routing multiple providers through a single compat surface (separate from direct env.AI.run on a Worker), AI Gateway chat completion documents:
https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/compat/chat/completions
with model strings such as openai/gpt-6-luna, google/gemini-4-argon, or workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast. Authentication may use a Cloudflare API token as apiKey, or BYOK with vendor tokens plus cf-aig-authorization where shown.
The Workers prompting base template states:
Workers AI as the default AI API for inference requests. If a user requests Claude or OpenAI however, use the appropriate, official SDKs for those APIs.
— Cloudflare, Prompting
That page is for generating Worker code with external assistants, not for substituting catalog env.AI.run calls.
Common mistakes
Section titled “Common mistakes”- Sending chat
messagesto a model documented on/ai/run(Gemini REST) or Responses-only bodies to/chat/completions. - Calling OpenAI web search without
/ai/v1/responsesandinput. - Using
max_output_tokenson chat completions ormax_completion_tokenson Responses where the example uses the other name. - Expecting
gatewayMetadata.keySource: "BYOK"on every model—many examples showUnified. - Omitting
stream_options: { include_usage: true }when billing or debugging from streamed calls. - For unbiased/pareto, tiny
max_tokensvalues producefinish_reason: "length"mid-sentence by design in examples. - Confusing catalog slugs (
meta/muse-spark-open) with routed ids in responses (for exampleaccounts/fireworks/models/muse-spark-openon Muse Spark Open).
How to check this on your site
Section titled “How to check this on your site”-
Open the model’s page under Workers AI models and copy the Workers snippet and matching
curlfor one Example (system message or minimal user prompt). -
Run
curlagainsthttps://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/...withAuthorization: Bearer $CLOUDFLARE_API_TOKENand confirm the top-levelobjectorstatematches the documented route (chat.completion,message,response, orCompletedrun result). -
For streaming examples, set
stream: trueandstream_options: { include_usage: true }as on GPT-5 or o3; verify the final chunk includesusage. -
If you use search or tools, reproduce the exact tool type from that model page (
web_search_preview,web_search_20250305,web_search, orenable_search) and confirmweb_search_callor citations appear only on the documented endpoint. -
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 disagrees with the linked Cloudflare docs or your live API responses, email yimasynthetic@gmail.com with the page URL and the exact statement you think is wrong so it can be corrected.