Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

cloudflare.md

580 lines17.5 KB

1---
2title: Cloudflare
3id: cloudflare-adapter
4description: "Run Workers AI chat, embeddings, images, speech, transcription, and evaluate from a Cloudflare Worker or any server, and send other providers through AI Gateway, with TanStack AI."
5keywords:
6 - tanstack ai
7 - cloudflare
8 - workers ai
9 - ai gateway
10 - env.AI
11 - edge inference
12 - adapter
13 - evaluate
14 - jev
15---
16​
17The Cloudflare adapter calls Workers AI, and it can put AI Gateway in front of another provider.
18​
19- You have a Cloudflare Worker and want an AI route with no API keys to manage.
20- You have a server somewhere else and want to call Workers AI models.
21- You use OpenAI or Anthropic and want AI Gateway caching and logs in front of them.
22​
23## 1. Install
24​
25<!-- ::start:tabs variant="package-manager" mode="install" -->
26​
27react: @tanstack/ai-cloudflare
28vue: @tanstack/ai-cloudflare
29solid: @tanstack/ai-cloudflare
30svelte: @tanstack/ai-cloudflare
31preact: @tanstack/ai-cloudflare
32angular: @tanstack/ai-cloudflare
33vanilla: @tanstack/ai-cloudflare
34octane: @tanstack/ai-cloudflare
35​
36<!-- ::end:tabs -->
37​
38## 2. Connect to Cloudflare
39​
40Inside a Worker, use the `env.AI` binding. You need no token and no account id. Add the binding to `wrangler.jsonc`:
41​
42```jsonc
44 "ai": { "binding": "AI" },
46```
47​
48On any other server, the adapter calls the Cloudflare REST API. Put your account id and an API token with Workers AI access in the environment of your server:
49​
50```bash
51CLOUDFLARE_ACCOUNT_ID=your-account-id
52CLOUDFLARE_API_TOKEN=your-api-token
53```
54​
55Get the account id from `wrangler whoami`. Create the token in the Cloudflare dashboard, under Workers AI, then Use REST API.
56​
57## 3. Stream a chat from the server
58​
59From a Worker, pass `env.AI` as the binding:
60​
61```typescript
62import {
63 chat,
64 chatParamsFromRequest,
65 toServerSentEventsResponse,
66} from "@tanstack/ai";
67import { createCloudflareText } from "@tanstack/ai-cloudflare";
68import type { Ai } from "@cloudflare/workers-types";
69​
70interface Env {
71 AI: Ai;
73​
74export default {
75 async fetch(request: Request, env: Env) {
76 const { messages, threadId, runId } = await chatParamsFromRequest(request);
77​
78 const stream = chat({
79 adapter: createCloudflareText("@cf/zai-org/glm-5.3-flash", {
80 binding: env.AI,
81 }),
82 messages,
83 threadId,
84 runId,
85 });
86​
87 return toServerSentEventsResponse(stream);
88 },
89};
90```
91​
92Run `wrangler dev` to start the route.
93​
94From any other server, `cloudflareText` reads `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`:
95​
96```typescript
97import {
98 chat,
99 chatParamsFromRequest,
100 toServerSentEventsResponse,
101} from "@tanstack/ai";
102import { cloudflareText } from "@tanstack/ai-cloudflare";
103​
104export async function POST(request: Request) {
105 const { messages, threadId, runId } = await chatParamsFromRequest(request);
106​
107 const stream = chat({
108 adapter: cloudflareText("@cf/zai-org/glm-5.3-flash"),
109 messages,
110 threadId,
111 runId,
112 });
113​
114 return toServerSentEventsResponse(stream);
116```
117​
118To pass the values in code, use `createCloudflareText`:
119​
120```typescript
121import { createCloudflareText } from "@tanstack/ai-cloudflare";
122​
123const adapter = createCloudflareText("@cf/zai-org/glm-5.3-flash", {
124 accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
125 apiKey: process.env.CLOUDFLARE_API_TOKEN!,
126});
127```
128​
129## 4. Render the chat
130​
131The client is the same for every provider. Point `useChat` at your route:
132​
133```tsx
134import { useState } from "react";
135import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
136​
137export function Chat() {
138 const [input, setInput] = useState("");
139 const { messages, sendMessage } = useChat({
140 connection: fetchServerSentEvents("/api/chat"),
141 threadId: "support-chat",
142 });
143​
144 return (
145 <form
146 onSubmit={(event) => {
147 event.preventDefault();
148 sendMessage(input);
149 setInput("");
150 }}
151 >
152 {messages.map((message) => (
153 <p key={message.id}>
154 {message.parts
155 .map((part) => (part.type === "text" ? part.content : ""))
156 .join("")}
157 </p>
158 ))}
159 <input value={input} onChange={(event) => setInput(event.target.value)} />
160 </form>
161 );
163```
164​
165For Vue, Solid, Svelte, Angular, and the other frameworks, see [Quick Start](../getting-started/quick-start#3-render-the-chat).
166​
167You now have a streaming chat on Workers AI. [Tools](../tools/tools) and [Structured Outputs](../structured-outputs/overview) work the same as with every adapter.
168​
169## Route through AI Gateway
170​
171AI Gateway gives you caching, logs, rate limits, and one bill for all providers. To send requests through it, add `gateway` to any config. Use `"default"` for the gateway that Cloudflare makes for your account:
172​
173```typescript
174import { createCloudflareText } from "@tanstack/ai-cloudflare";
175import type { Ai } from "@cloudflare/workers-types";
176​
177interface Env {
178 AI: Ai;
180​
181export function makeAdapter(env: Env) {
182 return createCloudflareText("@cf/zai-org/glm-5.3-flash", {
183 binding: env.AI,
184 gateway: { id: "default", cacheTtl: 3600, skipCache: false },
185 });
187```
188​
189With a gateway, you can also run third-party models by their catalog id. Cloudflare bills them:
190​
191```typescript
192import { createCloudflareText } from "@tanstack/ai-cloudflare";
193​
194const adapter = createCloudflareText("openai/gpt-5.5", {
195 accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
196 apiKey: process.env.CLOUDFLARE_API_TOKEN!,
197 gateway: { id: "default" },
198});
199```
200​
201### Keep your existing provider adapter
202​
203Do you use `@tanstack/ai-openai` with your own OpenAI key? `cloudflareGateway()` returns the `baseURL` and the headers that point that adapter at your gateway. The rest of your code stays the same:
204​
205```typescript
206import { createOpenaiChat } from "@tanstack/ai-openai";
207import { cloudflareGateway } from "@tanstack/ai-cloudflare";
208​
209const gateway = cloudflareGateway("openai", {
210 accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
211 gatewayId: "prod",
212 cacheTtl: 300,
213});
214​
215const adapter = createOpenaiChat("gpt-6.1-sol", process.env.OPENAI_API_KEY!, {
216 baseURL: gateway.baseURL,
217 defaultHeaders: gateway.headers,
218});
219```
220​
221- The first argument is the provider slug from your gateway dashboard, for example `openai`, `anthropic`, or `groq`.
222- If the gateway has authentication on, also pass `cfApiKey`. That token needs the `AI Gateway Run` permission.
223​
224The `ts-react-chat` example does this. Set `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN`, and `CLOUDFLARE_AI_GATEWAY_ID` in its `.env`. Then the Cloudflare, OpenAI, Anthropic, and Groq models in its picker all go through your gateway.
225​
226### Claude and GPT from a Worker
227​
228Inside a Worker, the AI Gateway `anthropic/...` and `openai/...` models use the API of their own provider, not Chat Completions. Keep the provider adapter, and give it `cloudflareBindingFetch` as its `fetch`. The binding signs the requests, so the Worker needs no provider key:
229​
230```typescript
231import {
232 chat,
233 chatParamsFromRequest,
234 toServerSentEventsResponse,
235} from "@tanstack/ai";
236import { createAnthropicChat } from "@tanstack/ai-anthropic";
237import { cloudflareBindingFetch } from "@tanstack/ai-cloudflare";
238import type { Ai } from "@cloudflare/workers-types";
239​
240interface Env {
241 AI: Ai;
243​
244export default {
245 async fetch(request: Request, env: Env) {
246 const { messages, threadId, runId } = await chatParamsFromRequest(request);
247​
248 // The SDK needs a key value. The binding does not use it.
249 const adapter = createAnthropicChat("claude-opus-5-5", "cloudflare-binding", {
250 fetch: cloudflareBindingFetch({
251 binding: env.AI,
252 vendor: "anthropic",
253 gateway: { id: "default" },
254 }),
255 });
256​
257 const stream = chat({ adapter, messages, threadId, runId, reasoning: "high" });
258 return toServerSentEventsResponse(stream);
259 },
260};
261```
262​
263- `vendor: "anthropic"` sends Anthropic Messages requests to `anthropic/<model>`. Use it with `createAnthropicChat`.
264- `vendor: "openai"` sends OpenAI Responses requests to `openai/<model>`. Use it with `createOpenaiChat`.
265- The adapter keeps all of its options: `chat({ reasoning })`, tools, `cache_control` for prompt caching, and Anthropic betas (sent as the `anthropic-beta` header).
266- For `@cf/...` models and other gateway vendors, keep `createCloudflareText` with `binding: env.AI`.
267​
268## Bring your own key
269​
270Two different things have this name. Both work.
271​
272### Cloudflare credentials of a user, from the browser
273​
274A user brings two values: the API token, and the account that it belongs to.
275​
276- `cloudflareByok` and `cloudflareAccountByok` are two entries in the TanStack BYOK store. Each one has its own env fallback.
277- `cloudflareByok` declares the account id as a companion. Register both, and a send for `cloudflare` carries both headers.
278- Import them from `@tanstack/ai-cloudflare/byok`, not from the main entry.
279​
280On the client:
281​
282```typescript
283import { defineByok, defaultByokStorage } from "@tanstack/ai-client/byok";
284import {
285 cloudflareAccountByok,
286 cloudflareByok,
287} from "@tanstack/ai-cloudflare/byok";
288​
289export const byok = defineByok({
290 storage: defaultByokStorage(),
291 providers: [cloudflareByok, cloudflareAccountByok],
292});
293```
294​
295On the relay, read both values in one call:
296​
297```typescript
298import {
299 chat,
300 chatParamsFromRequest,
301 toServerSentEventsResponse,
302} from "@tanstack/ai";
303import { createCloudflareText } from "@tanstack/ai-cloudflare";
304import {
305 cloudflareAccountByok,
306 cloudflareByok,
307} from "@tanstack/ai-cloudflare/byok";
308import { byokMissing, getByokKeys } from "@tanstack/ai/byok/server";
309​
310export async function POST(request: Request) {
311 const { apiKey, accountId } = getByokKeys(request, {
312 apiKey: cloudflareByok,
313 accountId: cloudflareAccountByok,
314 });
315 if (!apiKey) return byokMissing(cloudflareByok);
316 if (!accountId) return byokMissing(cloudflareAccountByok);
317​
318 const { messages, threadId, runId } = await chatParamsFromRequest(request);
319 const stream = chat({
320 adapter: createCloudflareText("@cf/zai-org/glm-5.3-flash", {
321 accountId,
322 apiKey,
323 }),
324 messages,
325 threadId,
326 runId,
327 });
328 return toServerSentEventsResponse(stream);
330```
331​
332See [Bring Your Own Key](../advanced/byok) for the client store and the save dialog.
333​
334### Your provider keys stored in AI Gateway
335​
336Add an OpenAI or Anthropic key under Provider Keys in the gateway dashboard, with the alias `default`. Then a `provider/model` id with `gateway: { id }` uses that key, not Unified Billing. You change no code.
337​
338## Evaluate
339​
340Sometimes you need an answer that your code can branch on, not chat text. Use `cloudflareDecider("typesafe/jev")` with `decide()`. To send the run through AI Gateway, add `gateway: { id: "default" }` to the adapter config.
341​
342From a Worker, pass the binding:
343​
344```typescript
345import { decide, choice, score, boolean } from "@tanstack/ai";
346import { createCloudflareDecider } from "@tanstack/ai-cloudflare";
347import type { Ai } from "@cloudflare/workers-types";
348​
349interface Env {
350 AI: Ai;
352​
353const ticket = {
354 subject: "Charged twice for the same invoice",
355 body: "Please refund the extra payment.",
356};
357​
358export async function evaluateTicket(env: Env) {
359 const result = await decide({
360 adapter: createCloudflareDecider("typesafe/jev", {
361 binding: env.AI,
362 gateway: { id: "default" },
363 }),
364 state: ticket,
365 questions: {
366 queue: choice({
367 instructions: "Which team should handle this ticket?",
368 options: {
369 billing: "Payments, invoices, refunds",
370 tech: "Bugs, outages, integrations",
371 sales: "Pricing, upgrades, new accounts",
372 },
373 }),
374 urgency: score({
375 instructions: "How urgent is this ticket?",
376 levels: ["low", "medium", "high"],
377 }),
378 refund: boolean({
379 instructions: "Is the customer asking for a refund?",
380 }),
381 },
382 });
383​
384 return result;
386```
387​
388From any other server, `cloudflareDecider` reads `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`:
389​
390```typescript
391import { decide, boolean } from "@tanstack/ai";
392import { cloudflareDecider } from "@tanstack/ai-cloudflare";
393​
394const result = await decide({
395 adapter: cloudflareDecider("typesafe/jev"),
396 state: "Please refund the extra payment.",
397 questions: {
398 refund: boolean({
399 instructions: "Is the customer asking for a refund?",
400 }),
401 },
402});
403​
404console.log(result.refund.value);
405```
406​
407See the [Evaluate guide](../evaluate/evaluate) for the question helpers, the result shape, abort, and middleware.
408​
409## Summarize, embed, and media
410​
411Every activity takes the same config as chat:
412​
413- Inside a Worker: `{ binding }`.
414- On any other server: `{ accountId, apiKey }`.
415- Both take an optional `gateway`.
416​
417The samples below use the factories that read the environment.
418​
419### Summarize
420​
421```typescript
422import { summarize } from "@tanstack/ai";
423import { cloudflareSummarize } from "@tanstack/ai-cloudflare";
424​
425const result = await summarize({
426 adapter: cloudflareSummarize("@cf/zai-org/glm-5.3-flash"),
427 text: "Long article text...",
428 threadId: "thread-1",
429 stream: false,
430});
431​
432console.log(result.summary);
433```
434​
435### Embeddings
436​
437```typescript
438import { embed } from "@tanstack/ai";
439import { cloudflareEmbedding } from "@tanstack/ai-cloudflare";
440​
441const result = await embed({
442 adapter: cloudflareEmbedding("@cf/baai/bge-m3"),
443 input: ["a story about a llama", "a story about a cloud"],
444});
445​
446console.log(result.embeddings[0]?.vector);
447```
448​
449### Images
450​
451```typescript
452import { generateImage } from "@tanstack/ai";
453import { cloudflareImage } from "@tanstack/ai-cloudflare";
454​
455const result = await generateImage({
456 adapter: cloudflareImage("@cf/black-forest-labs/flux-1-schnell"),
457 prompt: "a red bicycle on a beach",
458 threadId: "thread-1",
459 modelOptions: { steps: 4 },
460});
461​
462console.log(result.images[0]?.b64Json);
463```
464​
465### Text to speech
466​
467```typescript
468import { generateSpeech } from "@tanstack/ai";
469import { cloudflareTTS } from "@tanstack/ai-cloudflare";
470​
471const result = await generateSpeech({
472 adapter: cloudflareTTS("@cf/deepgram/aura-2-en"),
473 text: "Hello from the edge.",
474 threadId: "thread-1",
475 voice: "luna",
476});
477​
478console.log(result.audio); // base64 MP3
479```
480​
481### Transcription
482​
483```typescript
484import { generateTranscription } from "@tanstack/ai";
485import { cloudflareTranscription } from "@tanstack/ai-cloudflare";
486import { audioBuffer } from "./audio";
487​
488const result = await generateTranscription({
489 adapter: cloudflareTranscription("@cf/openai/whisper-large-v3-turbo"),
490 audio: audioBuffer,
491 threadId: "thread-1",
492});
493​
494console.log(result.text, result.segments, result.words);
495```
496​
497Pass the audio as a `File`, a `Blob`, an `ArrayBuffer`, or a base64 string. Whisper models take base64, and `@cf/deepgram/nova-3` takes the raw bytes. The adapter sends each model the format that it needs.
498​
499## Models and options
500​
501### Models
502​
503These ids work:
504​
505- Any id from the [Workers AI catalog](https://developers.cloudflare.com/workers-ai/models/).
506- Any `provider/model` id from the [AI Gateway catalog](https://developers.cloudflare.com/ai/models/), when a gateway is set.
507​
508Ids in the bundled catalog get editor autocomplete.
509​
510### Model options
511​
512Sampling options go in `modelOptions`. The thinking level goes in `reasoning`:
513​
514```typescript
515import { chat } from "@tanstack/ai";
516import { cloudflareText } from "@tanstack/ai-cloudflare";
517​
518const stream = chat({
519 adapter: cloudflareText("@cf/zai-org/glm-5.3-flash"),
520 messages: [{ role: "user", content: "Summarize this in one sentence." }],
521 threadId: "thread-1",
522 modelOptions: {
523 temperature: 0.3,
524 max_tokens: 512,
525 },
526 reasoning: "low",
527});
528```
529​
530### Reasoning
531​
532`reasoning` goes out as `reasoning_effort`. `off` sends `null`, which turns thinking off. Reasoning models stream their thinking as `reasoning_content`, which you get as `REASONING_*` events.
533​
534Some models and their levels:
535​
536| Model | Levels |
537| --- | --- |
538| `@cf/zai-org/glm-5.3`, `@cf/zai-org/glm-5.3-flash` | `low`, `high`, `max` |
539| `@cf/deepseek-ai/deepseek-v4-pro-0813`, `@cf/deepseek-ai/deepseek-v4-flash-0731` | `off`, `low`, `high`, `max` |
540| `@cf/qwen/qwen3.8-27b` | `off`, `low`, `medium`, `xhigh` |
541| `@cf/openai/gpt-oss-120b`, `@cf/openai/gpt-oss-20b` | `low`, `medium`, `high` |
542​
543The types know the levels of each model. A model with no reasoning data takes no `reasoning`. See [Reasoning](../chat/reasoning).
544​
545## Advanced
546​
547### Client options on the REST path
548​
549- The text and summarize adapters also take the OpenAI SDK client options: `baseURL`, `defaultHeaders`, `fetch`, `timeout`, and `maxRetries`.
550- The other adapters call the native `/ai/run` endpoint and take only `fetch`.
551​
552### Change the HTTP requests
553​
554Need a header on each request, or a log of each model call? The chat adapter supports [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call) on the REST path. In binding mode, the wrapper still runs. But the binding reads only the request body, so it drops the URL and the headers that the wrapper sets.
555​
556### Tools and prompts added during a conversation
557​
558Two kinds of adapter send the full tools and system prompts on every call:
559​
560- An adapter with a gateway `baseURL` from `cloudflareGateway()`.
561- An adapter with `cloudflareBindingFetch`.
562​
563This is also true on a model with a [mid-conversation channel](../advanced/mid-conversation-changes). So AI Gateway gets the same request as on any other model. To send tools and prompts added during a conversation through the channel, set `midConversationChannels: true`:
564​
565```typescript
566import { createAnthropicChat } from "@tanstack/ai-anthropic";
567import { cloudflareBindingFetch } from "@tanstack/ai-cloudflare";
568import type { Ai } from "@cloudflare/workers-types";
569​
570export function gatewayClaude(env: { AI: Ai }) {
571 return createAnthropicChat("claude-opus-5-5", "cloudflare-binding", {
572 fetch: cloudflareBindingFetch({
573 binding: env.AI,
574 vendor: "anthropic",
575 gateway: { id: "default" },
576 }),
577 midConversationChannels: true,
578 });
580```