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

cloudflare.md

615 lines18.7 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## Reuse the prompt cache
170​
171Every chat turn sends the whole conversation again. Workers AI can serve the repeated start of the prompt from its cache, but only when the turns of one conversation reach the same model instance. Send an `x-session-affinity` header with one value per conversation to keep them together. See [Workers AI prompt caching](https://developers.cloudflare.com/workers-ai/features/prompt-caching/).
172​
173Set the header with `defaultHeaders`:
174​
175```typescript
176import { chat, toServerSentEventsResponse } from "@tanstack/ai";
177import { createCloudflareText } from "@tanstack/ai-cloudflare";
178import type { Ai } from "@cloudflare/workers-types";
179​
180interface Env {
181 AI: Ai;
183​
184export default {
185 async fetch(request: Request, env: Env) {
186 const { messages, conversationId } = await request.json();
187​
188 const stream = chat({
189 adapter: createCloudflareText("@cf/zai-org/glm-5.3-flash", {
190 binding: env.AI,
191 defaultHeaders: { "x-session-affinity": `ses_${conversationId}` },
192 }),
193 messages,
194 threadId: conversationId,
195 });
196​
197 return toServerSentEventsResponse(stream);
198 },
199};
200```
201​
202The binding sends `defaultHeaders` as the `extraHeaders` run option, next to `gateway`. The REST config takes the same `defaultHeaders` field.
203​
204## Route through AI Gateway
205​
206AI 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:
207​
208```typescript
209import { createCloudflareText } from "@tanstack/ai-cloudflare";
210import type { Ai } from "@cloudflare/workers-types";
211​
212interface Env {
213 AI: Ai;
215​
216export function makeAdapter(env: Env) {
217 return createCloudflareText("@cf/zai-org/glm-5.3-flash", {
218 binding: env.AI,
219 gateway: { id: "default", cacheTtl: 3600, skipCache: false },
220 });
222```
223​
224With a gateway, you can also run third-party models by their catalog id. Cloudflare bills them:
225​
226```typescript
227import { createCloudflareText } from "@tanstack/ai-cloudflare";
228​
229const adapter = createCloudflareText("openai/gpt-5.5", {
230 accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
231 apiKey: process.env.CLOUDFLARE_API_TOKEN!,
232 gateway: { id: "default" },
233});
234```
235​
236### Keep your existing provider adapter
237​
238Do 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:
239​
240```typescript
241import { createOpenaiChat } from "@tanstack/ai-openai";
242import { cloudflareGateway } from "@tanstack/ai-cloudflare";
243​
244const gateway = cloudflareGateway("openai", {
245 accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
246 gatewayId: "prod",
247 cacheTtl: 300,
248});
249​
250const adapter = createOpenaiChat("gpt-6.1-sol", process.env.OPENAI_API_KEY!, {
251 baseURL: gateway.baseURL,
252 defaultHeaders: gateway.headers,
253});
254```
255​
256- The first argument is the provider slug from your gateway dashboard, for example `openai`, `anthropic`, or `groq`.
257- If the gateway has authentication on, also pass `cfApiKey`. That token needs the `AI Gateway Run` permission.
258​
259The `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.
260​
261### Claude and GPT from a Worker
262​
263Inside 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:
264​
265```typescript
266import {
267 chat,
268 chatParamsFromRequest,
269 toServerSentEventsResponse,
270} from "@tanstack/ai";
271import { createAnthropicChat } from "@tanstack/ai-anthropic";
272import { cloudflareBindingFetch } from "@tanstack/ai-cloudflare";
273import type { Ai } from "@cloudflare/workers-types";
274​
275interface Env {
276 AI: Ai;
278​
279export default {
280 async fetch(request: Request, env: Env) {
281 const { messages, threadId, runId } = await chatParamsFromRequest(request);
282​
283 // The SDK needs a key value. The binding does not use it.
284 const adapter = createAnthropicChat("claude-opus-5-5", "cloudflare-binding", {
285 fetch: cloudflareBindingFetch({
286 binding: env.AI,
287 vendor: "anthropic",
288 gateway: { id: "default" },
289 }),
290 });
291​
292 const stream = chat({ adapter, messages, threadId, runId, reasoning: "high" });
293 return toServerSentEventsResponse(stream);
294 },
295};
296```
297​
298- `vendor: "anthropic"` sends Anthropic Messages requests to `anthropic/<model>`. Use it with `createAnthropicChat`.
299- `vendor: "openai"` sends OpenAI Responses requests to `openai/<model>`. Use it with `createOpenaiChat`.
300- The adapter keeps all of its options: `chat({ reasoning })`, tools, `cache_control` for prompt caching, and Anthropic betas (sent as the `anthropic-beta` header).
301- For `@cf/...` models and other gateway vendors, keep `createCloudflareText` with `binding: env.AI`.
302​
303## Bring your own key
304​
305Two different things have this name. Both work.
306​
307### Cloudflare credentials of a user, from the browser
308​
309A user brings two values: the API token, and the account that it belongs to.
310​
311- `cloudflareByok` and `cloudflareAccountByok` are two entries in the TanStack BYOK store. Each one has its own env fallback.
312- `cloudflareByok` declares the account id as a companion. Register both, and a send for `cloudflare` carries both headers.
313- Import them from `@tanstack/ai-cloudflare/byok`, not from the main entry.
314​
315On the client:
316​
317```typescript
318import { defineByok, defaultByokStorage } from "@tanstack/ai-client/byok";
319import {
320 cloudflareAccountByok,
321 cloudflareByok,
322} from "@tanstack/ai-cloudflare/byok";
323​
324export const byok = defineByok({
325 storage: defaultByokStorage(),
326 providers: [cloudflareByok, cloudflareAccountByok],
327});
328```
329​
330On the relay, read both values in one call:
331​
332```typescript
333import {
334 chat,
335 chatParamsFromRequest,
336 toServerSentEventsResponse,
337} from "@tanstack/ai";
338import { createCloudflareText } from "@tanstack/ai-cloudflare";
339import {
340 cloudflareAccountByok,
341 cloudflareByok,
342} from "@tanstack/ai-cloudflare/byok";
343import { byokMissing, getByokKeys } from "@tanstack/ai/byok/server";
344​
345export async function POST(request: Request) {
346 const { apiKey, accountId } = getByokKeys(request, {
347 apiKey: cloudflareByok,
348 accountId: cloudflareAccountByok,
349 });
350 if (!apiKey) return byokMissing(cloudflareByok);
351 if (!accountId) return byokMissing(cloudflareAccountByok);
352​
353 const { messages, threadId, runId } = await chatParamsFromRequest(request);
354 const stream = chat({
355 adapter: createCloudflareText("@cf/zai-org/glm-5.3-flash", {
356 accountId,
357 apiKey,
358 }),
359 messages,
360 threadId,
361 runId,
362 });
363 return toServerSentEventsResponse(stream);
365```
366​
367See [Bring Your Own Key](../advanced/byok) for the client store and the save dialog.
368​
369### Your provider keys stored in AI Gateway
370​
371Add 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.
372​
373## Evaluate
374​
375Sometimes 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.
376​
377From a Worker, pass the binding:
378​
379```typescript
380import { decide, choice, score, boolean } from "@tanstack/ai";
381import { createCloudflareDecider } from "@tanstack/ai-cloudflare";
382import type { Ai } from "@cloudflare/workers-types";
383​
384interface Env {
385 AI: Ai;
387​
388const ticket = {
389 subject: "Charged twice for the same invoice",
390 body: "Please refund the extra payment.",
391};
392​
393export async function evaluateTicket(env: Env) {
394 const result = await decide({
395 adapter: createCloudflareDecider("typesafe/jev", {
396 binding: env.AI,
397 gateway: { id: "default" },
398 }),
399 state: ticket,
400 questions: {
401 queue: choice({
402 instructions: "Which team should handle this ticket?",
403 options: {
404 billing: "Payments, invoices, refunds",
405 tech: "Bugs, outages, integrations",
406 sales: "Pricing, upgrades, new accounts",
407 },
408 }),
409 urgency: score({
410 instructions: "How urgent is this ticket?",
411 levels: ["low", "medium", "high"],
412 }),
413 refund: boolean({
414 instructions: "Is the customer asking for a refund?",
415 }),
416 },
417 });
418​
419 return result;
421```
422​
423From any other server, `cloudflareDecider` reads `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`:
424​
425```typescript
426import { decide, boolean } from "@tanstack/ai";
427import { cloudflareDecider } from "@tanstack/ai-cloudflare";
428​
429const result = await decide({
430 adapter: cloudflareDecider("typesafe/jev"),
431 state: "Please refund the extra payment.",
432 questions: {
433 refund: boolean({
434 instructions: "Is the customer asking for a refund?",
435 }),
436 },
437});
438​
439console.log(result.refund.value);
440```
441​
442See the [Evaluate guide](../evaluate/evaluate) for the question helpers, the result shape, abort, and middleware.
443​
444## Summarize, embed, and media
445​
446Every activity takes the same config as chat:
447​
448- Inside a Worker: `{ binding }`.
449- On any other server: `{ accountId, apiKey }`.
450- Both take an optional `gateway`.
451​
452The samples below use the factories that read the environment.
453​
454### Summarize
455​
456```typescript
457import { summarize } from "@tanstack/ai";
458import { cloudflareSummarize } from "@tanstack/ai-cloudflare";
459​
460const result = await summarize({
461 adapter: cloudflareSummarize("@cf/zai-org/glm-5.3-flash"),
462 text: "Long article text...",
463 threadId: "thread-1",
464 stream: false,
465});
466​
467console.log(result.summary);
468```
469​
470### Embeddings
471​
472```typescript
473import { embed } from "@tanstack/ai";
474import { cloudflareEmbedding } from "@tanstack/ai-cloudflare";
475​
476const result = await embed({
477 adapter: cloudflareEmbedding("@cf/baai/bge-m3"),
478 input: ["a story about a llama", "a story about a cloud"],
479});
480​
481console.log(result.embeddings[0]?.vector);
482```
483​
484### Images
485​
486```typescript
487import { generateImage } from "@tanstack/ai";
488import { cloudflareImage } from "@tanstack/ai-cloudflare";
489​
490const result = await generateImage({
491 adapter: cloudflareImage("@cf/black-forest-labs/flux-1-schnell"),
492 prompt: "a red bicycle on a beach",
493 threadId: "thread-1",
494 modelOptions: { steps: 4 },
495});
496​
497console.log(result.images[0]?.b64Json);
498```
499​
500### Text to speech
501​
502```typescript
503import { generateSpeech } from "@tanstack/ai";
504import { cloudflareTTS } from "@tanstack/ai-cloudflare";
505​
506const result = await generateSpeech({
507 adapter: cloudflareTTS("@cf/deepgram/aura-2-en"),
508 text: "Hello from the edge.",
509 threadId: "thread-1",
510 voice: "luna",
511});
512​
513console.log(result.audio); // base64 MP3
514```
515​
516### Transcription
517​
518```typescript
519import { generateTranscription } from "@tanstack/ai";
520import { cloudflareTranscription } from "@tanstack/ai-cloudflare";
521import { audioBuffer } from "./audio";
522​
523const result = await generateTranscription({
524 adapter: cloudflareTranscription("@cf/openai/whisper-large-v3-turbo"),
525 audio: audioBuffer,
526 threadId: "thread-1",
527});
528​
529console.log(result.text, result.segments, result.words);
530```
531​
532Pass 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.
533​
534## Models and options
535​
536### Models
537​
538These ids work:
539​
540- Any id from the [Workers AI catalog](https://developers.cloudflare.com/workers-ai/models/).
541- Any `provider/model` id from the [AI Gateway catalog](https://developers.cloudflare.com/ai/models/), when a gateway is set.
542​
543Ids in the bundled catalog get editor autocomplete.
544​
545### Model options
546​
547Sampling options go in `modelOptions`. The thinking level goes in `reasoning`:
548​
549```typescript
550import { chat } from "@tanstack/ai";
551import { cloudflareText } from "@tanstack/ai-cloudflare";
552​
553const stream = chat({
554 adapter: cloudflareText("@cf/zai-org/glm-5.3-flash"),
555 messages: [{ role: "user", content: "Summarize this in one sentence." }],
556 threadId: "thread-1",
557 modelOptions: {
558 temperature: 0.3,
559 max_tokens: 512,
560 },
561 reasoning: "low",
562});
563```
564​
565### Reasoning
566​
567`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.
568​
569Some models and their levels:
570​
571| Model | Levels |
572| --- | --- |
573| `@cf/zai-org/glm-5.3`, `@cf/zai-org/glm-5.3-flash` | `low`, `high`, `max` |
574| `@cf/deepseek-ai/deepseek-v4-pro-0813`, `@cf/deepseek-ai/deepseek-v4-flash-0731` | `off`, `low`, `high`, `max` |
575| `@cf/qwen/qwen3.8-27b` | `off`, `low`, `medium`, `xhigh` |
576| `@cf/openai/gpt-oss-120b`, `@cf/openai/gpt-oss-20b` | `low`, `medium`, `high` |
577​
578The types know the levels of each model. A model with no reasoning data takes no `reasoning`. See [Reasoning](../chat/reasoning).
579​
580## Advanced
581​
582### Client options on the REST path
583​
584- The text and summarize adapters also take the OpenAI SDK client options: `baseURL`, `defaultHeaders`, `fetch`, `timeout`, and `maxRetries`.
585- The other adapters call the native `/ai/run` endpoint and take only `fetch`.
586​
587### Change the HTTP requests
588​
589Need 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.
590​
591### Tools and prompts added during a conversation
592​
593Two kinds of adapter send the full tools and system prompts on every call:
594​
595- An adapter with a gateway `baseURL` from `cloudflareGateway()`.
596- An adapter with `cloudflareBindingFetch`.
597​
598This 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`:
599​
600```typescript
601import { createAnthropicChat } from "@tanstack/ai-anthropic";
602import { cloudflareBindingFetch } from "@tanstack/ai-cloudflare";
603import type { Ai } from "@cloudflare/workers-types";
604​
605export function gatewayClaude(env: { AI: Ai }) {
606 return createAnthropicChat("claude-opus-5-5", "cloudflare-binding", {
607 fetch: cloudflareBindingFetch({
608 binding: env.AI,
609 vendor: "anthropic",
610 gateway: { id: "default" },
611 }),
612 midConversationChannels: true,
613 });
615```