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

cloudflare.md

428 lines12.6 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 route 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​
17You have a Cloudflare Worker and want an AI route without managing API keys. Or you have a server elsewhere and want to call Workers AI models. Or you already use OpenAI or Anthropic and want AI Gateway caching and logs in front of them. This adapter does all three.
18​
19## Installation
20​
21<!-- ::start:tabs variant="package-manager" mode="install" -->
22​
23react: @tanstack/ai-cloudflare
24vue: @tanstack/ai-cloudflare
25solid: @tanstack/ai-cloudflare
26svelte: @tanstack/ai-cloudflare
27preact: @tanstack/ai-cloudflare
28angular: @tanstack/ai-cloudflare
29vanilla: @tanstack/ai-cloudflare
30octane: @tanstack/ai-cloudflare
31​
32<!-- ::end:tabs -->
33​
34## Chat from a Worker
35​
36Pass `env.AI` as the binding. No token, no account id.
37​
381. Add the binding to `wrangler.jsonc`:
39​
40```jsonc
42 "ai": { "binding": "AI" },
44```
45​
462. Stream a chat response from your Worker:
47​
48```typescript
49import { chat, toServerSentEventsResponse } from "@tanstack/ai";
50import { createCloudflareText } from "@tanstack/ai-cloudflare";
51import type { Ai } from "@cloudflare/workers-types";
52​
53interface Env {
54 AI: Ai;
56​
57export default {
58 async fetch(request: Request, env: Env) {
59 const { messages } = await request.json();
60​
61 const stream = chat({
62 adapter: createCloudflareText("@cf/zai-org/glm-5.3-flash", {
63 binding: env.AI,
64 }),
65 messages,
66 });
67​
68 return toServerSentEventsResponse(stream);
69 },
70};
71```
72​
73That is a working AI route. Run `wrangler dev` and post `{ "messages": [...] }` to it.
74​
75## Chat from anywhere else
76​
77Outside a Worker, the adapter talks to the Cloudflare REST API. You need your account id and an API token with Workers AI access.
78​
79```typescript
80import { chat } from "@tanstack/ai";
81import { createCloudflareText } from "@tanstack/ai-cloudflare";
82​
83const adapter = createCloudflareText("@cf/zai-org/glm-5.3-flash", {
84 accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
85 apiKey: process.env.CLOUDFLARE_API_TOKEN!,
86});
87​
88const stream = chat({
89 adapter,
90 messages: [{ role: "user", content: "Hello!" }],
91});
92```
93​
94`cloudflareText(model)` does the same and reads `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` from the environment for you.
95​
96The text and summarize REST config also accepts the OpenAI SDK client options (`baseURL`, `defaultHeaders`, `fetch`, `timeout`, `maxRetries`). The other adapters call the native `/ai/run` endpoint and take `fetch` only.
97​
98## Route through AI Gateway
99​
100AI Gateway gives you caching, logs, rate limits, and one bill across providers. Add `gateway` to any config to send requests through it. Use `"default"` for the gateway Cloudflare creates for your account.
101​
102```typescript
103import { createCloudflareText } from "@tanstack/ai-cloudflare";
104import type { Ai } from "@cloudflare/workers-types";
105​
106interface Env {
107 AI: Ai;
109​
110export function makeAdapter(env: Env) {
111 return createCloudflareText("@cf/zai-org/glm-5.3-flash", {
112 binding: env.AI,
113 gateway: { id: "default", cacheTtl: 3600, skipCache: false },
114 });
116```
117​
118With a gateway you can also run third-party models by their catalog id, billed through Cloudflare:
119​
120```typescript
121import { createCloudflareText } from "@tanstack/ai-cloudflare";
122​
123const adapter = createCloudflareText("openai/gpt-5.5", {
124 accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
125 apiKey: process.env.CLOUDFLARE_API_TOKEN!,
126 gateway: { id: "default" },
127});
128```
129​
130### Keep your existing provider adapter
131​
132Already using `@tanstack/ai-openai` with your own OpenAI key? `cloudflareGateway()` returns the `baseURL` and headers that point that adapter at your gateway. The rest of your code stays the same.
133​
134```typescript
135import { createOpenaiChat } from "@tanstack/ai-openai";
136import { cloudflareGateway } from "@tanstack/ai-cloudflare";
137​
138const gateway = cloudflareGateway("openai", {
139 accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
140 gatewayId: "prod",
141 cacheTtl: 300,
142});
143​
144const adapter = createOpenaiChat("gpt-5.5", process.env.OPENAI_API_KEY!, {
145 baseURL: gateway.baseURL,
146 defaultHeaders: gateway.headers,
147});
148```
149​
150The first argument is the provider slug from your gateway dashboard (`openai`, `anthropic`, `groq`, and so on). If the gateway has authentication turned on, pass `cfApiKey` too. That token needs the `AI Gateway Run` permission.
151​
152The `ts-react-chat` example does this. Set `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN`, and `CLOUDFLARE_AI_GATEWAY_ID` in its `.env`, and the Cloudflare, OpenAI, Anthropic, and Groq models in its picker all go through your gateway.
153​
154## Bring your own key
155​
156Two different things go by this name. Both work.
157​
158**A user's Cloudflare credentials from the browser.** A user brings two values: the API token and the account it belongs to. `cloudflareByok` and `cloudflareAccountByok` are two entries in the TanStack BYOK store, each with its own env fallback. `cloudflareByok` declares the account id as a companion, so register both and a send for `cloudflare` carries both headers. Import them from `@tanstack/ai-cloudflare/byok`, not from the main entry.
159​
160```typescript
161import { defineByok, defaultByokStorage } from "@tanstack/ai-client/byok";
162import {
163 cloudflareAccountByok,
164 cloudflareByok,
165} from "@tanstack/ai-cloudflare/byok";
166​
167export const byok = defineByok({
168 storage: defaultByokStorage(),
169 providers: [cloudflareByok, cloudflareAccountByok],
170});
171```
172​
173On the relay, read both values in one call:
174​
175```typescript
176import { chat, toServerSentEventsResponse } from "@tanstack/ai";
177import { createCloudflareText } from "@tanstack/ai-cloudflare";
178import {
179 cloudflareAccountByok,
180 cloudflareByok,
181} from "@tanstack/ai-cloudflare/byok";
182import { byokMissing, getByokKeys } from "@tanstack/ai/byok/server";
183​
184export async function POST(request: Request) {
185 const { apiKey, accountId } = getByokKeys(request, {
186 apiKey: cloudflareByok,
187 accountId: cloudflareAccountByok,
188 });
189 if (!apiKey) return byokMissing(cloudflareByok);
190 if (!accountId) return byokMissing(cloudflareAccountByok);
191​
192 const { messages } = await request.json();
193 const stream = chat({
194 adapter: createCloudflareText("@cf/zai-org/glm-5.3-flash", {
195 accountId,
196 apiKey,
197 }),
198 messages,
199 });
200 return toServerSentEventsResponse(stream);
202```
203​
204See [Bring Your Own Key](../advanced/byok) for the client store and the save dialog.
205​
206**Your provider keys stored in AI Gateway.** Add an OpenAI or Anthropic key under Provider Keys in the gateway dashboard, alias `default`. From then on, a `provider/model` id with `gateway: { id }` uses that key instead of Unified Billing. No code changes.
207​
208## Models
209​
210Any id from the [Workers AI catalog](https://developers.cloudflare.com/workers-ai/models/) works, and so does any `provider/model` id from the [AI Gateway catalog](https://developers.cloudflare.com/ai/models/) when a gateway is set. Ids in the bundled catalog get editor autocomplete.
211​
212## Tools and structured output
213​
214Tools and `outputSchema` work the same as with every other adapter:
215​
216```typescript
217import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
218import { createCloudflareText } from "@tanstack/ai-cloudflare";
219import { z } from "zod";
220import type { Ai } from "@cloudflare/workers-types";
221​
222interface Env {
223 AI: Ai;
225​
226const getWeather = toolDefinition({
227 name: "get_weather",
228 description: "Get the current weather",
229 inputSchema: z.object({ location: z.string() }),
230}).server(async ({ location }) => {
231 return { location, temperature: 21, conditions: "sunny" };
232});
233​
234export default {
235 async fetch(request: Request, env: Env) {
236 const { messages } = await request.json();
237​
238 const stream = chat({
239 adapter: createCloudflareText("@cf/zai-org/glm-5.3-flash", {
240 binding: env.AI,
241 }),
242 messages,
243 tools: [getWeather],
244 });
245​
246 return toServerSentEventsResponse(stream);
247 },
248};
249```
250​
251## Model options
252​
253Sampling and reasoning controls go in `modelOptions`. Reasoning models stream their thinking as `reasoning_content`, which shows up as `REASONING_*` events.
254​
255```typescript
256import { chat } from "@tanstack/ai";
257import { cloudflareText } from "@tanstack/ai-cloudflare";
258​
259const stream = chat({
260 adapter: cloudflareText("@cf/zai-org/glm-5.3-flash"),
261 messages: [{ role: "user", content: "Summarize this in one sentence." }],
262 modelOptions: {
263 temperature: 0.3,
264 max_tokens: 512,
265 reasoning_effort: "low",
266 chat_template_kwargs: { enable_thinking: false },
267 },
268});
269```
270​
271## Evaluate
272​
273Use `cloudflareDecider('typesafe/jev')` with `decide()`.
274Pass `gateway: { id: 'default' }` on the adapter config to send the run through AI Gateway.
275​
276From a Worker, pass the binding:
277​
278```typescript
279import { decide, choice, score, boolean } from "@tanstack/ai";
280import { createCloudflareDecider } from "@tanstack/ai-cloudflare";
281import type { Ai } from "@cloudflare/workers-types";
282​
283interface Env {
284 AI: Ai;
286​
287const ticket = {
288 subject: "Charged twice for the same invoice",
289 body: "Please refund the extra payment.",
290};
291​
292export async function evaluateTicket(env: Env) {
293 const result = await decide({
294 adapter: createCloudflareDecider("typesafe/jev", {
295 binding: env.AI,
296 gateway: { id: "default" },
297 }),
298 state: ticket,
299 questions: {
300 queue: choice({
301 instructions: "Which team should handle this ticket?",
302 options: {
303 billing: "Payments, invoices, refunds",
304 tech: "Bugs, outages, integrations",
305 sales: "Pricing, upgrades, new accounts",
306 },
307 }),
308 urgency: score({
309 instructions: "How urgent is this ticket?",
310 levels: ["low", "medium", "high"],
311 }),
312 refund: boolean({
313 instructions: "Is the customer asking for a refund?",
314 }),
315 },
316 });
317​
318 return result;
320```
321​
322From any other server, `cloudflareDecider` reads `CLOUDFLARE_ACCOUNT_ID` and
323`CLOUDFLARE_API_TOKEN`:
324​
325```typescript
326import { decide, boolean } from "@tanstack/ai";
327import { cloudflareDecider } from "@tanstack/ai-cloudflare";
328​
329const result = await decide({
330 adapter: cloudflareDecider("typesafe/jev"),
331 state: "Please refund the extra payment.",
332 questions: {
333 refund: boolean({
334 instructions: "Is the customer asking for a refund?",
335 }),
336 },
337});
338​
339console.log(result.refund.value);
340```
341​
342See the [Evaluate guide](../evaluate/evaluate) for question helpers, the result
343shape, abort, and middleware.
344​
345## Summarize, embed, and media
346​
347Every activity takes the same config as chat: `{ binding }` inside a Worker, `{ accountId, apiKey }` elsewhere, plus an optional `gateway`. The examples below use the env-reading factories.
348​
349Summarize:
350​
351```typescript
352import { summarize } from "@tanstack/ai";
353import { cloudflareSummarize } from "@tanstack/ai-cloudflare";
354​
355const result = await summarize({
356 adapter: cloudflareSummarize("@cf/zai-org/glm-5.3-flash"),
357 text: "Long article text...",
358 stream: false,
359});
360```
361​
362Embeddings:
363​
364```typescript
365import { embed } from "@tanstack/ai";
366import { cloudflareEmbedding } from "@tanstack/ai-cloudflare";
367​
368const result = await embed({
369 adapter: cloudflareEmbedding("@cf/baai/bge-m3"),
370 input: ["a story about a llama", "a story about a cloud"],
371});
372// result.embeddings[0].vector
373```
374​
375Images:
376​
377```typescript
378import { generateImage } from "@tanstack/ai";
379import { cloudflareImage } from "@tanstack/ai-cloudflare";
380​
381const result = await generateImage({
382 adapter: cloudflareImage("@cf/black-forest-labs/flux-1-schnell"),
383 prompt: "a red bicycle on a beach",
384 modelOptions: { steps: 4 },
385});
386// result.images[0].b64Json
387```
388​
389Text to speech:
390​
391```typescript
392import { generateSpeech } from "@tanstack/ai";
393import { cloudflareTTS } from "@tanstack/ai-cloudflare";
394​
395const result = await generateSpeech({
396 adapter: cloudflareTTS("@cf/deepgram/aura-2-en"),
397 text: "Hello from the edge.",
398 voice: "luna",
399});
400// result.audio is base64 MP3
401```
402​
403Transcription:
404​
405```typescript
406import { generateTranscription } from "@tanstack/ai";
407import { cloudflareTranscription } from "@tanstack/ai-cloudflare";
408import { audioBuffer } from "./audio";
409​
410const result = await generateTranscription({
411 adapter: cloudflareTranscription("@cf/openai/whisper-large-v3-turbo"),
412 audio: audioBuffer,
413});
414// result.text, result.segments, result.words
415```
416​
417Whisper models take the audio as base64. `@cf/deepgram/nova-3` takes the raw bytes. The adapter handles both, so pass a `File`, `Blob`, `ArrayBuffer`, or base64 string.
418​
419## Environment variables
420​
421For the REST path:
422​
423```bash
424CLOUDFLARE_ACCOUNT_ID=your-account-id
425CLOUDFLARE_API_TOKEN=your-api-token
426```
427​
428Get the account id from `wrangler whoami`. Create the token in the Cloudflare dashboard under Workers AI, then Use REST API.