From 36c9b2093ae621c2437016adf3901ad61b21db05 Mon Sep 17 00:00:00 2001 From: vijayakrishnans Date: Fri, 27 Nov 2026 15:14:38 +0700 Subject: [PATCH] Other providers' models go through Cloudflare AI Gateway, not Vercel's The optional gateway models called Vercel's AI Gateway with an AI_GATEWAY_API_KEY. They now run on the Worker's own AI binding through Cloudflare AI Gateway: workers-ai-provider sends a catalogue id as env.AI.run(id, inputs, { gateway }), and the gateway bills the account's AI Gateway credits, so no provider key reaches the Worker. - AI_GATEWAY_ID (the gateway's name; default is the account's own) replaces AI_GATEWAY_API_KEY as the setting that offers these models. - The list is three models from Cloudflare's catalogue: GPT-5.4 mini, Grok 4.3 and DeepSeek V4 Pro, with their capabilities declared. - The per-model health lookup and the demo catalogue, which only Vercel's gateway served, are removed. - A request the gateway cannot bill opens a dialog linking to the gateway's page, in place of Vercel's add-a-credit-card dialog. Co-Authored-By: Claude Fable 5.2 --- .baseline/product/README.md | 29 +- BOOTSTRAP.md | 12 +- README.md | 13 +- apps/web/.dev.vars.example | 7 +- apps/web/.env.example | 7 +- apps/web/README.md | 5 +- apps/web/app/(chat)/api/chat/route.ts | 38 +-- apps/web/app/(chat)/api/models/route.ts | 38 +-- apps/web/components/chat/multimodal-input.tsx | 2 +- apps/web/components/chat/shell.tsx | 13 +- apps/web/hooks/use-active-chat.tsx | 4 +- apps/web/lib/ai/models.ts | 260 +++++------------- apps/web/lib/ai/providers.ts | 25 +- apps/web/lib/errors.ts | 23 +- apps/web/wrangler.jsonc | 4 +- apps/web/wrangler.template.jsonc | 4 +- blueprint.yaml | 2 +- docs/phases/01-product.md | 2 +- docs/phases/README.md | 4 +- hooks/render-deployment-docs.sh | 10 +- repo-blueprint.yaml | 4 +- .../epics/ai-chatbot/IMPLEMENTATION-STATUS.md | 12 + testing/e2e.test.sh | 8 +- tests/web/src/health.test.ts | 2 +- tests/web/src/models.test.ts | 61 +++- tests/web/src/wrangler-config.test.ts | 2 +- 26 files changed, 258 insertions(+), 333 deletions(-) diff --git a/.baseline/product/README.md b/.baseline/product/README.md index 7515ca0..362677f 100644 --- a/.baseline/product/README.md +++ b/.baseline/product/README.md @@ -27,7 +27,7 @@ and how to operate it is in |---|---| | The product's name | `apps/web/lib/site.ts` | | The chat, auth, artifacts, tools, components and hooks | `apps/web/app`, `apps/web/components`, `apps/web/artifacts`, `apps/web/lib`, `apps/web/hooks` | -| The models: Workers AI by default, the AI Gateway when its key is set | `apps/web/lib/ai/models.ts`, `apps/web/lib/ai/providers.ts` | +| The models: Workers AI by default, Cloudflare AI Gateway when `AI_GATEWAY_ID` is set | `apps/web/lib/ai/models.ts`, `apps/web/lib/ai/providers.ts` | | Postgres through Hyperdrive (`getDb()`), the schema for drizzle-kit | `apps/web/lib/db/queries.ts`, `apps/web/lib/db/schema.ts`, `apps/web/lib/db/migrations` | | The session key (AUTH_SECRET, or the database's own) | `apps/web/lib/auth-secret.ts`, `apps/web/app/(auth)`, `apps/web/proxy.ts` | | Attachments on R2 (upload, serve) | `apps/web/app/(chat)/api/files/upload`, `apps/web/app/(chat)/api/files/[...key]` | @@ -127,18 +127,27 @@ allocation. The picker offers Kimi K2.6 (the default: tools, vision, reasoning) and GLM 4.7 Flash (fast; also the title model); both are listed in `apps/web/lib/ai/models.ts`. -To add upstream's **Vercel AI Gateway** models (DeepSeek, Kimi K2.5, GPT OSS, -Grok), set the gateway's key per environment: +To add other providers' models (GPT-5.4 mini, Grok 4.3, DeepSeek V4 Pro) +through **Cloudflare AI Gateway**, on the same `AI` binding: + +1. In the Cloudflare dashboard, under AI → AI Gateway, load credits (Unified + Billing) and turn on **authentication** for the gateway you will use. Every + account has one named `default`. +2. Name that gateway per environment: ```bash -wrangler secret put AI_GATEWAY_API_KEY --name ai-chatbot-web-stage -wrangler secret put AI_GATEWAY_API_KEY --name ai-chatbot-web-prod +wrangler secret put AI_GATEWAY_ID --name ai-chatbot-web-stage +wrangler secret put AI_GATEWAY_ID --name ai-chatbot-web-prod ``` -Worker secrets survive every later deploy; the next request sees them, and -the picker lists the gateway's models from then on. Without the key they are -not offered, and a request naming one is answered by the default Workers AI -model. A model that fails says so in the chat (Workers AI's own message); +The value is the gateway's name (`default`), not a key: no provider key +reaches the Worker, and the models are billed to the account's AI Gateway +credits. It is stored as a Worker secret because secrets survive every later +deploy; the next request sees it, and the picker lists the gateway's models +from then on. Without it they are not offered, and a request naming one is +answered by the default Workers AI model. If the gateway cannot bill a +request (no credits, or authentication off), the chat says so and links to +the gateway's page. A model that fails says so in the chat (Workers AI's own message); the writing-suggestions tool needs structured output, and a model that cannot give it answers that the suggestions could not be made. @@ -154,7 +163,7 @@ wrangler secret put HF_TOKEN --name ai-chatbot-web-prod They run on Hugging Face's Inference Providers router, billed to the token's Hugging Face account, and the picker lists them from the next request on — -the same rules as the gateway's key. `/api/health` reports both keys. +the same rules as the gateway's id. `/api/health` reports both. ## Other optional secrets diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index eb7e55d..fbacc7d 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -54,8 +54,8 @@ and deploys the app, infra before app, then a short docs landing. repos), unless the credential can write links. `01-product`'s `link` step stops and names the fix if it is not. - **No AI vendor key.** No platform brokers one: the chat runs on Workers AI, - and the Vercel AI Gateway's models are an optional key the owner adds - afterwards (§3). + and other providers' models through Cloudflare AI Gateway are an optional + setting the owner adds afterwards (§3). - **A known platform risk (R2).** The R2 bucket is applied with its own `r2-data` key, but the Worker's `BLOB` binding is attached by the deploy, which runs with the `workers-deploy` token (Workers Scripts and KV). @@ -161,11 +161,13 @@ orun new --blueprint repo-blueprint.yaml \ - **The models** need nothing: the chat, the titles and the artifact tools run on Workers AI through the Worker's `AI` binding, billed to the - Cloudflare account. To add the Vercel AI Gateway's models (upstream's - list), set its key per environment: + Cloudflare account. To add other providers' models through Cloudflare AI + Gateway (load AI Gateway credits and turn on the gateway's authentication + first), name the gateway per environment — `default` is the one every + account has: ```bash - wrangler secret put AI_GATEWAY_API_KEY --name -web- + wrangler secret put AI_GATEWAY_ID --name -web- ``` Hugging Face's open models are the same with `HF_TOKEN` (a token with diff --git a/README.md b/README.md index 956bb98..8daec86 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,9 @@ from the `HYPERDRIVE` binding, one per call; attachments go to the `BLOB` R2 binding and are served back at `/api/files/`; the Vercel-only modules — Blob, BotID, `@vercel/functions`, `@vercel/otel`, `@vercel/analytics` — are each replaced by their Cloudflare counterpart or a no-op; the models default -to Workers AI (so a fresh product chats with no model key, and the AI -Gateway's models appear only once its key is set); and the session key +to Workers AI (so a fresh product chats with no model key, and other +providers' models, through Cloudflare AI Gateway, appear only once the owner +names a gateway); and the session key defaults to one the database generates for itself (so no secret has to be set by hand). What the baseline adds is everything needed to make a copy of it somebody else's — built the way @@ -62,8 +63,8 @@ roots, the migrations, the tests, its CI, its tooling, a README of its own and its operating contract — renamed throughout to the product's name, repository, Worker, Supabase project, Hyperdrive config and bucket. None of this repository's machinery ships. **No AI vendor key is asked for**: the -platform brokers none, and the chat runs on Workers AI; the AI Gateway's key -is the owner's to add afterwards (the product's README, "Models"). The +platform brokers none, and the chat runs on Workers AI; Cloudflare AI Gateway +is the owner's to turn on afterwards (the product's README, "Models"). The Supabase organisation the build uses needs room for **two projects**, stage and prod — the free plan's limit. @@ -85,7 +86,7 @@ and prod — the free plan's limit. |---|---| | The product's name | `apps/web/lib/site.ts` | | The chat, auth, artifacts, tools, components and hooks | `apps/web/app`, `apps/web/components`, `apps/web/artifacts`, `apps/web/lib`, `apps/web/hooks` | -| The models (Workers AI by default; the AI Gateway when its key is set) | `apps/web/lib/ai/models.ts`, `apps/web/lib/ai/providers.ts` | +| The models (Workers AI by default; Cloudflare AI Gateway when `AI_GATEWAY_ID` is set) | `apps/web/lib/ai/models.ts`, `apps/web/lib/ai/providers.ts` | | Postgres through Hyperdrive (`getDb()`), the schema for drizzle-kit | `apps/web/lib/db/queries.ts`, `apps/web/lib/db/schema.ts`, `apps/web/lib/db/migrations` | | The session key: AUTH_SECRET, or the one the database generated | `apps/web/lib/auth-secret.ts` | | Attachments on R2 (upload, serve) | `apps/web/app/(chat)/api/files/upload`, `apps/web/app/(chat)/api/files/[...key]` | @@ -126,7 +127,7 @@ carries. | BotID | Removed; `lib/bot.ts` never flags a request — use Cloudflare Bot Management or Turnstile at the edge | | `@vercel/otel` + `@ai-sdk/otel` | Workers observability (`observability.enabled` in wrangler); `instrumentation.ts` registers nothing | | `@vercel/analytics` | Cloudflare Web Analytics beacon (`NEXT_PUBLIC_CF_BEACON_TOKEN` at build time; unset renders nothing) | -| Vercel AI Gateway (OIDC on Vercel) for every model call | Workers AI through the `AI` binding by default (`workers-ai-provider`); the gateway's models only with `AI_GATEWAY_API_KEY` as a Worker secret | +| Vercel AI Gateway (OIDC on Vercel) for every model call | Workers AI through the `AI` binding by default (`workers-ai-provider`); other providers' models through Cloudflare AI Gateway on the same binding, only with `AI_GATEWAY_ID` set (Unified Billing; no provider key) | | `AUTH_SECRET` set by the owner | Optional: unset, the session key is the one the environment's database generated (`app_private.secrets`) | | Redis resumable streams + IP rate limit (`REDIS_URL`) | Off without `REDIS_URL`, as upstream; per-user entitlements still apply | | A database created by hand | `infra/terraform/supabase` + `infra/terraform/cloudflare-hyperdrive` + `infra/terraform/cloudflare-r2`, ids and credentials as orun secrets | diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example index 2339209..a14d180 100644 --- a/apps/web/.dev.vars.example +++ b/apps/web/.dev.vars.example @@ -13,8 +13,11 @@ # (migration 020_app_secrets; lib/auth-secret.ts). # AUTH_SECRET= -# The Vercel AI Gateway: adds upstream's gateway models to the picker. -# AI_GATEWAY_API_KEY= +# Cloudflare AI Gateway: the name of a gateway on this account (`default` is +# the one every account has) adds other providers' models to the picker, +# billed to the account's AI Gateway credits. The gateway needs authentication +# turned on. +# AI_GATEWAY_ID= # Hugging Face's Inference Providers: adds open models (Kimi K3, GLM 5.3, # DeepSeek, Qwen) to the picker. A token with "Make calls to Inference diff --git a/apps/web/.env.example b/apps/web/.env.example index c867e98..7910614 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -12,9 +12,10 @@ POSTGRES_URL=postgres://postgres:postgres@localhost:5432/postgres AUTH_SECRET= # Optional. The models are Workers AI through the AI binding (remote under -# `next dev`: `wrangler login` first). A Vercel AI Gateway key -# (https://vercel.com/ai-gateway) adds upstream's gateway models. -AI_GATEWAY_API_KEY= +# `next dev`: `wrangler login` first). The name of a Cloudflare AI Gateway on +# the account (`default` is the one every account has) adds other providers' +# models, billed to the account's AI Gateway credits. +AI_GATEWAY_ID= # Optional. A Hugging Face token with "Make calls to Inference Providers" # (https://huggingface.co/settings/tokens) adds Hugging Face's open models. diff --git a/apps/web/README.md b/apps/web/README.md index 80b0166..e644e3b 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -7,8 +7,9 @@ A chatbot from Vercel's [Next.js AI Chatbot](https://github.com/vercel/ai-chatbo with the template's tools — the weather, and artifacts (text, code, spreadsheets) the model creates, edits and suggests changes to - Models on Workers AI through the Worker's `AI` binding by default - (`lib/ai/models.ts`, `lib/ai/providers.ts`); the Vercel AI Gateway's models - are offered only when `AI_GATEWAY_API_KEY` is set + (`lib/ai/models.ts`, `lib/ai/providers.ts`); other providers' models, through + Cloudflare AI Gateway on the same binding, are offered only when + `AI_GATEWAY_ID` is set - Auth.js (next-auth v5) with credentials and a guest flow: every page signs a visitor without a session in as a guest (`proxy.ts`, `app/(auth)`) - Chat history, votes, documents and suggestions in Postgres through Drizzle diff --git a/apps/web/app/(chat)/api/chat/route.ts b/apps/web/app/(chat)/api/chat/route.ts index b1a078c..c5c5f4c 100644 --- a/apps/web/app/(chat)/api/chat/route.ts +++ b/apps/web/app/(chat)/api/chat/route.ts @@ -38,7 +38,11 @@ import { updateMessage, } from "@/lib/db/queries"; import type { DBMessage } from "@/lib/db/schema"; -import { ChatbotError } from "@/lib/errors"; +import { + ChatbotError, + GATEWAY_BILLING_MESSAGE, + isGatewayBillingError, +} from "@/lib/errors"; import { geolocation, ipAddress } from "@/lib/geo"; import { checkIpRateLimit } from "@/lib/ratelimit"; import type { ChatMessage, WaitingStatusData } from "@/lib/types"; @@ -93,8 +97,8 @@ export async function POST(request: Request) { return new ChatbotError("unauthorized:chat").toResponse(); } - // Only a model this deployment can run: a gateway model without the - // gateway's key falls back to the default Workers AI model. + // Only a model this deployment can run: a gateway model with no gateway + // configured falls back to the default Workers AI model. const chatModel = resolveModelId(selectedChatModel); await checkIpRateLimit(ipAddress(request)); @@ -293,14 +297,6 @@ export async function POST(request: Request) { onError() { stopWaitingStatus(); }, - providerOptions: { - ...(modelConfig?.gatewayOrder && { - gateway: { order: modelConfig.gatewayOrder }, - }), - ...(modelConfig?.reasoningEffort && { - openai: { reasoningEffort: modelConfig.reasoningEffort }, - }), - }, stopWhen: isStepCount(5), telemetry: { functionId: "stream-text", @@ -388,13 +384,8 @@ export async function POST(request: Request) { } }, onError: (error) => { - if ( - error instanceof Error && - error.message?.includes( - "AI Gateway requires a valid credit card on file to service requests" - ) - ) { - return "AI Gateway requires a valid credit card on file to service requests. Please visit https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%3Fmodal%3Dadd-credit-card to add a card and unlock your free credits."; + if (isGatewayBillingError(error)) { + return GATEWAY_BILLING_MESSAGE; } // Workers AI's own error (a model it no longer serves, a quota, a // binding that is not there) is shown as it is, in the chat, rather @@ -429,22 +420,17 @@ export async function POST(request: Request) { stream, }); } catch (error) { - const vercelId = request.headers.get("x-vercel-id"); + const rayId = request.headers.get("cf-ray"); if (error instanceof ChatbotError) { return error.toResponse(); } - if ( - error instanceof Error && - error.message?.includes( - "AI Gateway requires a valid credit card on file to service requests" - ) - ) { + if (isGatewayBillingError(error)) { return new ChatbotError("bad_request:activate_gateway").toResponse(); } - console.error("Unhandled error in chat API:", error, { vercelId }); + console.error("Unhandled error in chat API:", error, { rayId }); return new ChatbotError("offline:chat").toResponse(); } } diff --git a/apps/web/app/(chat)/api/models/route.ts b/apps/web/app/(chat)/api/models/route.ts index 034b418..5dd131a 100644 --- a/apps/web/app/(chat)/api/models/route.ts +++ b/apps/web/app/(chat)/api/models/route.ts @@ -1,43 +1,17 @@ -import { - getAllGatewayModels, - getAvailableModels, - getCapabilities, - isDemo, - isGatewayConfigured, -} from "@/lib/ai/models"; +import { getAvailableModels, getCapabilities } from "@/lib/ai/models"; // What the model picker shows: `available` is exactly what this deployment -// can run — the Workers AI models always, Hugging Face's and the AI Gateway's -// only when their keys are set — and `capabilities` says what each supports. In the demo mode -// upstream ships (IS_DEMO=1, with a gateway key), `models` adds the -// gateway's whole catalogue, shown locked. +// can run — the Workers AI models always, Hugging Face's only with HF_TOKEN +// and Cloudflare AI Gateway's only with AI_GATEWAY_ID — and `capabilities` +// says what each supports. export async function GET() { const headers = { - // Per deployment, and it changes when a key is set: short-lived. + // Per deployment, and it changes when a setting is added: short-lived. "Cache-Control": "public, max-age=300, s-maxage=300", }; - const available = getAvailableModels(); - const curatedCapabilities = await getCapabilities(); - - if (isDemo && isGatewayConfigured()) { - const models = await getAllGatewayModels(); - const capabilities = Object.fromEntries( - models.map((m) => [m.id, curatedCapabilities[m.id] ?? m.capabilities]) - ); - - return Response.json( - { - available, - capabilities: { ...capabilities, ...curatedCapabilities }, - models, - }, - { headers } - ); - } - return Response.json( - { available, capabilities: curatedCapabilities }, + { available: getAvailableModels(), capabilities: await getCapabilities() }, { headers } ); } diff --git a/apps/web/components/chat/multimodal-input.tsx b/apps/web/components/chat/multimodal-input.tsx index 07dd28d..697ade7 100644 --- a/apps/web/components/chat/multimodal-input.tsx +++ b/apps/web/components/chat/multimodal-input.tsx @@ -801,7 +801,7 @@ function PureModelSelectorCompact({ const capabilities: Record | undefined = modelsData?.capabilities ?? modelsData; // What this deployment can run (app/(chat)/api/models): Workers AI's models - // always, the AI Gateway's only when its key is set. Until the answer + // always, the AI Gateway's only when AI_GATEWAY_ID is set. Until the answer // arrives, the Workers AI models, which every deployment has. const availableModels: ChatModel[] = modelsData?.available ?? workersAiModels; const dynamicModels: ChatModel[] | undefined = modelsData?.models; diff --git a/apps/web/components/chat/shell.tsx b/apps/web/components/chat/shell.tsx index 53c5567..be91e3e 100644 --- a/apps/web/components/chat/shell.tsx +++ b/apps/web/components/chat/shell.tsx @@ -17,6 +17,7 @@ import { useArtifact, useArtifactSelector, } from "@/hooks/use-artifact"; +import { GATEWAY_DASHBOARD_URL } from "@/lib/errors"; import type { Attachment, ChatMessage } from "@/lib/types"; import { cn } from "@/lib/utils"; import { Artifact } from "./artifact"; @@ -103,10 +104,7 @@ export function ChatShell() { }, [editingMessage, input, regenerate, setInput, setMessages]); const handleActivateGateway = useCallback(() => { - window.open( - "https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%3Fmodal%3Dadd-credit-card", - "_blank" - ); + window.open(GATEWAY_DASHBOARD_URL, "_blank"); window.location.href = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/`; }, []); @@ -196,17 +194,18 @@ export function ChatShell() { > - Activate AI Gateway + Set up AI Gateway billing This application requires{" "} {process.env.NODE_ENV === "production" ? "the owner" : "you"} to - activate Vercel AI Gateway. + add Cloudflare AI Gateway credits and turn on the gateway's + authentication. Cancel - Activate + Open AI Gateway diff --git a/apps/web/hooks/use-active-chat.tsx b/apps/web/hooks/use-active-chat.tsx index f3b9522..be831f8 100644 --- a/apps/web/hooks/use-active-chat.tsx +++ b/apps/web/hooks/use-active-chat.tsx @@ -24,7 +24,7 @@ import type { VisibilityType } from "@/components/chat/visibility-selector"; import { useAutoResume } from "@/hooks/use-auto-resume"; import { DEFAULT_CHAT_MODEL } from "@/lib/ai/models"; import type { Vote } from "@/lib/db/schema"; -import { ChatbotError } from "@/lib/errors"; +import { ChatbotError, isGatewayBillingMessage } from "@/lib/errors"; import type { ChatMessage } from "@/lib/types"; import { fetcher, fetchWithErrorHandlers, generateUUID } from "@/lib/utils"; @@ -118,7 +118,7 @@ export function ActiveChatProvider({ children }: { children: ReactNode }) { setDataStream((ds) => (ds ? [...ds, dataPart] : [])); }, onError: (error) => { - if (error.message?.includes("AI Gateway requires a valid credit card")) { + if (isGatewayBillingMessage(error.message)) { setShowCreditCardAlert(true); } else if (error instanceof ChatbotError) { toast({ description: error.message, type: "error" }); diff --git a/apps/web/lib/ai/models.ts b/apps/web/lib/ai/models.ts index 6a08b2c..9a24fba 100644 --- a/apps/web/lib/ai/models.ts +++ b/apps/web/lib/ai/models.ts @@ -1,11 +1,14 @@ -// WHERE THE MODELS COME FROM. Upstream sends every model call through the -// Vercel AI Gateway, which needs a key nobody brokers. Here the default is -// Workers AI, through the Worker's own `AI` binding (wrangler.jsonc): it needs -// no key, so a fresh deployment chats with nothing configured. The gateway's -// models — upstream's list, unchanged — are offered only when -// AI_GATEWAY_API_KEY is set (a Worker secret), Hugging Face's only when -// HF_TOKEN is, and the picker shows exactly what is available -// (`getAvailableModels`), never a model that would fail. +// WHERE THE MODELS COME FROM. Upstream sends every model call through +// Vercel's AI Gateway. Here everything runs on the Worker's own `AI` binding +// (wrangler.jsonc). The default is Workers AI: it needs no key, so a fresh +// deployment chats with nothing configured. Other providers' models go +// through Cloudflare AI Gateway on the same binding, billed to the Cloudflare +// account's AI Gateway credits (Unified Billing) — no provider key, but the +// account must hold credits and the gateway must have authentication on, so +// they are offered only when AI_GATEWAY_ID names the gateway to use. +// Hugging Face's models are offered only when HF_TOKEN is set, and the picker +// shows exactly what is available (`getAvailableModels`), never a model that +// would fail. export const DEFAULT_CHAT_MODEL = "@cf/moonshotai/kimi-k2.6"; export type ModelCapabilities = { @@ -19,14 +22,12 @@ export type ChatModel = { name: string; provider: string; description: string; - // `workers-ai`: the AI binding; `gateway`: the AI Gateway (needs its key); - // `huggingface`: Hugging Face's Inference Providers router (needs HF_TOKEN). + // `workers-ai`: the AI binding; `gateway`: Cloudflare AI Gateway, on the + // same binding (needs AI_GATEWAY_ID); `huggingface`: Hugging Face's + // Inference Providers router (needs HF_TOKEN). via?: "workers-ai" | "gateway" | "huggingface"; - // Workers AI and Hugging Face models' capabilities are known here; the - // gateway's are looked up from the gateway (getCapabilities). + // Every model's capabilities are declared here: nothing is looked up. capabilities?: ModelCapabilities; - gatewayOrder?: string[]; - reasoningEffort?: "none" | "minimal" | "low" | "medium" | "high"; }; // Current Workers AI text models with tool calling (OpenAI-compatible chat @@ -60,49 +61,32 @@ export const titleModel: ChatModel = { via: "workers-ai", }; -// Upstream's curated gateway models, as upstream lists them. Offered only -// with AI_GATEWAY_API_KEY set. +// Other providers' models from Cloudflare's AI Gateway catalogue +// (developers.cloudflare.com/ai/models), by their catalogue ids. Offered only +// with AI_GATEWAY_ID set. export const gatewayModels: ChatModel[] = [ { - description: "Fast and capable model with tool use", - gatewayOrder: ["bedrock", "deepinfra"], - id: "deepseek/deepseek-v3.2", - name: "DeepSeek V3.2", - provider: "deepseek", - via: "gateway", - }, - { - description: "Moonshot AI flagship model", - gatewayOrder: ["fireworks", "bedrock"], - id: "moonshotai/kimi-k2.5", - name: "Kimi K2.5", - provider: "moonshotai", - via: "gateway", - }, - { - description: "Compact reasoning model", - gatewayOrder: ["groq", "bedrock"], - id: "openai/gpt-oss-20b", - name: "GPT OSS 20B", + capabilities: { reasoning: true, tools: true, vision: true }, + description: "OpenAI's small GPT-5.4 — tools, vision, reasoning", + id: "openai/gpt-5.4-mini", + name: "GPT-5.4 mini", provider: "openai", - reasoningEffort: "low", via: "gateway", }, { - description: "Open-source 120B parameter model", - gatewayOrder: ["fireworks", "bedrock"], - id: "openai/gpt-oss-120b", - name: "GPT OSS 120B", - provider: "openai", - reasoningEffort: "low", + capabilities: { reasoning: true, tools: true, vision: true }, + description: "xAI's Grok 4.3 — tools, vision, reasoning", + id: "xai/grok-4.3", + name: "Grok 4.3", + provider: "xai", via: "gateway", }, { - description: "Fast non-reasoning model with tool use", - gatewayOrder: ["xai"], - id: "xai/grok-4.1-fast-non-reasoning", - name: "Grok 4.1 Fast", - provider: "xai", + capabilities: { reasoning: true, tools: true, vision: false }, + description: "DeepSeek's reasoning model — tools, reasoning", + id: "deepseek/deepseek-v4-pro", + name: "DeepSeek V4 Pro", + provider: "deepseek", via: "gateway", }, ]; @@ -153,23 +137,28 @@ export const chatModels: ChatModel[] = [ ...gatewayModels, ]; -// Whether the AI Gateway is configured. OpenNext copies the Worker's -// secrets and vars into process.env per request, so this is read at call -// time, never at module load. +// The Cloudflare AI Gateway the gateway's models run through: AI_GATEWAY_ID, +// the gateway's name (`default` is the one every account has). OpenNext +// copies the Worker's secrets and vars into process.env per request, so this +// is read at call time, never at module load. +export function getGatewayId(): string | undefined { + return process.env.AI_GATEWAY_ID?.trim() || undefined; +} + export function isGatewayConfigured(): boolean { - return Boolean(process.env.AI_GATEWAY_API_KEY); + return Boolean(getGatewayId()); } // Whether Hugging Face is configured: HF_TOKEN, a Hugging Face access token // with the "Make calls to Inference Providers" permission, as a Worker secret. -// Read at call time, like the gateway's key. +// Read at call time, like the gateway's id. export function isHuggingFaceConfigured(): boolean { return Boolean(process.env.HF_TOKEN); } // What a request may use: Workers AI always (the binding is in the committed -// wrangler config), Hugging Face's and the gateway's models only with their -// keys. +// wrangler config), Hugging Face's models only with HF_TOKEN and the +// gateway's only with AI_GATEWAY_ID. export function getAvailableModels(): ChatModel[] { return [ ...workersAiModels, @@ -190,95 +179,25 @@ export function isHuggingFaceModel(modelId: string): boolean { return huggingFaceModels.some((m) => m.id === modelId); } -export async function getCapabilities(): Promise< - Record -> { - const results = await Promise.all( - getAvailableModels().map(async (model) => { - if (model.capabilities) { - return [model.id, model.capabilities]; - } - try { - const res = await fetch( - `https://ai-gateway.vercel.sh/v1/models/${model.id}/endpoints`, - { next: { revalidate: 86_400 } } - ); - if (!res.ok) { - return [model.id, { reasoning: false, tools: false, vision: false }]; - } - - const json = await res.json(); - const endpoints = json.data?.endpoints ?? []; - const params = new Set( - endpoints.flatMap( - (e: { supported_parameters?: string[] }) => - e.supported_parameters ?? [] - ) - ); - const inputModalities = new Set( - json.data?.architecture?.input_modalities ?? [] - ); +const NO_CAPABILITIES: ModelCapabilities = { + reasoning: false, + tools: false, + vision: false, +}; - return [ - model.id, - { - reasoning: params.has("reasoning"), - tools: params.has("tools"), - vision: inputModalities.has("image"), - }, - ]; - } catch { - return [model.id, { reasoning: false, tools: false, vision: false }]; - } - }) +export function getCapabilities(): Promise> { + return Promise.resolve( + Object.fromEntries( + getAvailableModels().map((model) => [ + model.id, + model.capabilities ?? NO_CAPABILITIES, + ]) + ) ); - - return Object.fromEntries(results); } export const isDemo = process.env.IS_DEMO === "1"; -type GatewayModel = { - id: string; - name: string; - type?: string; - tags?: string[]; -}; - -export type GatewayModelWithCapabilities = ChatModel & { - capabilities: ModelCapabilities; -}; - -export async function getAllGatewayModels(): Promise< - GatewayModelWithCapabilities[] -> { - try { - const res = await fetch("https://ai-gateway.vercel.sh/v1/models", { - next: { revalidate: 86_400 }, - }); - if (!res.ok) { - return []; - } - - const json = await res.json(); - return (json.data ?? []) - .filter((m: GatewayModel) => m.type === "language") - .map((m: GatewayModel) => ({ - capabilities: { - reasoning: m.tags?.includes("reasoning") ?? false, - tools: m.tags?.includes("tool-use") ?? false, - vision: m.tags?.includes("vision") ?? false, - }, - description: "", - id: m.id, - name: m.name, - provider: m.id.split("/")[0], - })); - } catch { - return []; - } -} - export function getActiveModels(): ChatModel[] { return getAvailableModels(); } @@ -296,64 +215,11 @@ export const modelsByProvider = chatModels.reduce( export type ModelAvailability = "healthy" | "impacted" | "unknown"; -type GatewayEndpoint = { - provider_name?: string; - status?: number; - uptime_last_15m?: number; - uptime_last_1h?: number; - latency_last_1h?: { - p50?: number; - p95?: number; - }; -}; - -const PROVIDER_IMPACTED_UPTIME_THRESHOLD = 99; -const PROVIDER_IMPACTED_P50_MS = 10_000; -const PROVIDER_IMPACTED_P95_MS = 30_000; - -function isEndpointImpacted(endpoint: GatewayEndpoint) { - return ( - (endpoint.status !== undefined && endpoint.status !== 0) || - (endpoint.uptime_last_15m !== undefined && - endpoint.uptime_last_15m < PROVIDER_IMPACTED_UPTIME_THRESHOLD) || - (endpoint.uptime_last_1h !== undefined && - endpoint.uptime_last_1h < PROVIDER_IMPACTED_UPTIME_THRESHOLD) || - (endpoint.latency_last_1h?.p50 !== undefined && - endpoint.latency_last_1h.p50 > PROVIDER_IMPACTED_P50_MS) || - (endpoint.latency_last_1h?.p95 !== undefined && - endpoint.latency_last_1h.p95 > PROVIDER_IMPACTED_P95_MS) - ); -} - -export async function getModelAvailability( - modelId: string +// No provider here reports per-model health the way upstream's gateway did, +// so the chat's "may be slow right now" notice never fires: every model is +// "unknown". +export function getModelAvailability( + _modelId: string ): Promise { - const model = chatModels.find((item) => item.id === modelId); - - // Workers AI and Hugging Face report no per-model health the way the - // gateway does. - if (!model || model.via === "workers-ai" || model.via === "huggingface") { - return "unknown"; - } - - try { - const res = await fetch( - `https://ai-gateway.vercel.sh/v1/models/${model.id}/endpoints`, - { next: { revalidate: 60 } } - ); - if (!res.ok) { - return "unknown"; - } - - const json = await res.json(); - const endpoints = (json.data?.endpoints ?? []) as GatewayEndpoint[]; - - if (endpoints.length === 0) { - return "unknown"; - } - - return endpoints.some(isEndpointImpacted) ? "impacted" : "healthy"; - } catch { - return "unknown"; - } + return Promise.resolve("unknown"); } diff --git a/apps/web/lib/ai/providers.ts b/apps/web/lib/ai/providers.ts index 1f011fc..c9f4a8f 100644 --- a/apps/web/lib/ai/providers.ts +++ b/apps/web/lib/ai/providers.ts @@ -1,10 +1,11 @@ import { createOpenAICompatible } from "@ai-sdk/openai-compatible"; import { getCloudflareContext } from "@opennextjs/cloudflare"; -import { customProvider, gateway, type LanguageModel } from "ai"; +import { customProvider, type LanguageModel } from "ai"; import { createWorkersAI } from "workers-ai-provider"; import { isTestEnvironment } from "../constants"; import { DEFAULT_CHAT_MODEL, + getGatewayId, isAvailableModel, isHuggingFaceModel, isWorkersAiModel, @@ -39,6 +40,24 @@ function workersAi() { return createWorkersAI({ binding: env.AI }); } +// Another provider's model, through Cloudflare AI Gateway on the same `AI` +// binding: `workers-ai-provider` runs a catalogue id (`openai/gpt-5.4-mini`) +// as `env.AI.run(id, inputs, { gateway })`, and the gateway holds the +// credential — Unified Billing against the account's credits, or a key stored +// on the gateway. No provider key reaches this Worker. +function aiGateway() { + const { env } = getCloudflareContext(); + if (!env.AI) { + throw new Error( + 'The AI binding is missing: wrangler.jsonc must declare `"ai": { "binding": "AI" }`' + ); + } + return createWorkersAI({ + binding: env.AI, + gateway: { id: getGatewayId() ?? "default" }, + }); +} + // Hugging Face's Inference Providers router: OpenAI-compatible chat // completions, HF_TOKEN as the bearer. Built per call, like the binding — the // secret reaches process.env per request (lib/ai/models.ts). @@ -51,7 +70,7 @@ function huggingFace() { } // A model id the request may not use — a gateway or Hugging Face model with -// no key, or one nobody lists — falls back to the default Workers AI model rather +// nothing configured, or one nobody lists — falls back to the default Workers AI model rather // than failing the chat (lib/ai/models.ts, getAvailableModels). export function resolveModelId(modelId: string): string { return isAvailableModel(modelId) ? modelId : DEFAULT_CHAT_MODEL; @@ -69,7 +88,7 @@ export function getLanguageModel(modelId: string): LanguageModel { if (isHuggingFaceModel(id)) { return huggingFace()(id); } - return gateway.languageModel(id); + return aiGateway()(id); } export function getTitleModel(): LanguageModel { diff --git a/apps/web/lib/errors.ts b/apps/web/lib/errors.ts index 78ba498..fc8b6b9 100644 --- a/apps/web/lib/errors.ts +++ b/apps/web/lib/errors.ts @@ -89,7 +89,7 @@ export function getMessageByErrorCode(errorCode: ErrorCode): string { return "The request couldn't be processed. Please check your input and try again."; case "bad_request:activate_gateway": - return "AI Gateway requires a valid credit card on file to service requests. Please visit https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%3Fmodal%3Dadd-credit-card to add a card and unlock your free credits."; + return GATEWAY_BILLING_MESSAGE; case "unauthorized:auth": return "You need to sign in before continuing."; @@ -139,3 +139,24 @@ function getStatusCodeByType(type: ErrorType) { return 500; } } + +// Cloudflare AI Gateway bills other providers' models to the account's +// credits (Unified Billing). When it cannot — no credits, or the gateway's +// authentication is off — it answers with one of these (AI Gateway's +// troubleshooting reference, errors 2049, 2052 and 2021), and the chat tells +// the visitor what the owner has to do instead of "Oops". +export const GATEWAY_DASHBOARD_URL = + "https://dash.cloudflare.com/?to=/:account/ai/ai-gateway"; + +export const GATEWAY_BILLING_MESSAGE = `Cloudflare AI Gateway could not bill this request. The owner needs AI Gateway credits, and authentication turned on for the gateway: ${GATEWAY_DASHBOARD_URL}`; + +export function isGatewayBillingError(error: unknown): boolean { + return ( + error instanceof Error && + /unified billing|insufficient balance/i.test(error.message ?? "") + ); +} + +export function isGatewayBillingMessage(message: string | undefined): boolean { + return Boolean(message?.includes("Cloudflare AI Gateway could not bill")); +} diff --git a/apps/web/wrangler.jsonc b/apps/web/wrangler.jsonc index deaee8d..ee42866 100644 --- a/apps/web/wrangler.jsonc +++ b/apps/web/wrangler.jsonc @@ -42,10 +42,10 @@ "ai": { "binding": "AI" } - // AUTH_SECRET, AI_GATEWAY_API_KEY and HF_TOKEN are optional Worker secrets, + // AUTH_SECRET, AI_GATEWAY_ID and HF_TOKEN are optional Worker secrets, // never vars (`wrangler secret put`, README). Without AUTH_SECRET the session // key is the one the database generated (lib/auth-secret.ts); without the - // gateway key or HF_TOKEN only the Workers AI models are offered. REDIS_URL is absent + // gateway's id or HF_TOKEN only the Workers AI models are offered. REDIS_URL is absent // too: without it the chat skips resumable streams and the Redis IP rate // limit, as upstream does, and the per-user hourly limit still applies. } diff --git a/apps/web/wrangler.template.jsonc b/apps/web/wrangler.template.jsonc index fb39fcb..2974047 100644 --- a/apps/web/wrangler.template.jsonc +++ b/apps/web/wrangler.template.jsonc @@ -49,10 +49,10 @@ "ai": { "binding": "AI" } - // AUTH_SECRET, AI_GATEWAY_API_KEY and HF_TOKEN are optional Worker secrets, + // AUTH_SECRET, AI_GATEWAY_ID and HF_TOKEN are optional Worker secrets, // never vars (`wrangler secret put`, README). Without AUTH_SECRET the session // key is the one the database generated (lib/auth-secret.ts); without the - // gateway key or HF_TOKEN only the Workers AI models are offered. REDIS_URL is absent + // gateway's id or HF_TOKEN only the Workers AI models are offered. REDIS_URL is absent // too: without it the chat skips resumable streams and the Redis IP rate // limit, as upstream does, and the per-user hourly limit still applies. } diff --git a/blueprint.yaml b/blueprint.yaml index eaca27d..ac12622 100644 --- a/blueprint.yaml +++ b/blueprint.yaml @@ -50,7 +50,7 @@ spec: outcome: - Live on stage and prod, guests chatting on Workers AI - A Supabase project and an R2 bucket per environment, migrated on merge - - Other models through the AI Gateway when you add its key + - Other providers' models through Cloudflare AI Gateway when you turn it on requires: # GitHub arrives as the App installation plus the repo link; Cloudflare diff --git a/docs/phases/01-product.md b/docs/phases/01-product.md index 6675710..fbfabd6 100644 --- a/docs/phases/01-product.md +++ b/docs/phases/01-product.md @@ -85,7 +85,7 @@ runs beside it; `task` is the first that waits for it. the binding is reachable and migrated. No model key is in it: the models are Workers AI through the Worker's `AI` -binding. The AI Gateway's models turn on when the owner adds its key (the +binding. Cloudflare AI Gateway's models turn on when the owner names a gateway (the product's README, "Models"). **An open platform risk.** The deploy step binds the bucket with the diff --git a/docs/phases/README.md b/docs/phases/README.md index c27894c..cf7b5b2 100644 --- a/docs/phases/README.md +++ b/docs/phases/README.md @@ -117,8 +117,8 @@ must have room for both before `01-product` runs (BOOTSTRAP.md). The platform brokers no AI vendor, so nothing here mints, asks for or waits on a model key. The chatbot's models are Workers AI, reached through the Worker's own `AI` binding on the Cloudflare account the build already -deploys to: a fresh product chats with nothing else configured. The Vercel -AI Gateway's models are optional — the owner adds `AI_GATEWAY_API_KEY` as a +deploys to: a fresh product chats with nothing else configured. Cloudflare +AI Gateway's models are optional — the owner adds `AI_GATEWAY_ID` as a Worker secret afterwards (the product's README, "Models"), and re-running `02-docs` records it. diff --git a/hooks/render-deployment-docs.sh b/hooks/render-deployment-docs.sh index e48c52b..53e538d 100755 --- a/hooks/render-deployment-docs.sh +++ b/hooks/render-deployment-docs.sh @@ -56,7 +56,7 @@ stage_url="https://${brand}-web-stage.${sub}.workers.dev" prod_url="https://${brand}-web-prod.${sub}.workers.dev" # Which model provider serves: /api/health names the default Workers AI -# model and whether the AI Gateway's key is set (a yes/no, never the key). +# model and whether an AI Gateway is named (a yes/no, never the name). # Read only from an answer that is 200: anything else says nothing about it. models_state() { local page code @@ -127,9 +127,9 @@ environment is verify-only by design — no deployed URL. | prod | ${models_prod} | The chat runs on Workers AI through the Worker's own \`AI\` binding — no key. -The AI Gateway is not a provider the platform brokers: its key is an optional -Worker secret the owner adds per environment (README, "Models"), which adds -the gateway's models to the picker. +Other providers' models run through Cloudflare AI Gateway on the same binding, +billed to the account's AI Gateway credits: the owner names the gateway per +environment (README, "Models"), which adds its models to the picker. ## Secrets (names only) @@ -146,7 +146,7 @@ the gateway's models to the picker. | \`WIRING_CLOUDFLARE_R2\` | \`${repo}\` on stage and on prod | written by the R2 root's apply: the bucket's name, not a credential | Brokered secrets are minted per run, so no long-lived value is at rest. The -optional keys (\`AI_GATEWAY_API_KEY\`, \`REDIS_URL\`, \`AUTH_SECRET\`) are Worker +optional settings (\`AI_GATEWAY_ID\`, \`REDIS_URL\`, \`AUTH_SECRET\`) are Worker secrets the owner adds, not workspace secrets (above). What the workspace holds right now (every secret by name, and its integrations and their health) is on the console's Secrets and Integrations pages for \`${ws}\`. diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml index 336c80b..5afe7d7 100644 --- a/repo-blueprint.yaml +++ b/repo-blueprint.yaml @@ -597,8 +597,8 @@ phases: # SUPABASE_ACCESS_TOKEN supabase's provider, db-migrate's runner # SUPABASE_ORG_ID supabase (TF_VAR_supabaseOrgId) # No model key is minted: the chat runs on Workers AI through the - # Worker's own AI binding, which needs none. The AI Gateway's key is - # optional and no connection brokers it (its README, "Models"). + # Worker's own AI binding, which needs none. Cloudflare AI Gateway + # is optional and runs on that binding too (its README, "Models"). - id: secrets-cloudflare uses: orun.integrations/reconcile@v1 with: diff --git a/specs/epics/ai-chatbot/IMPLEMENTATION-STATUS.md b/specs/epics/ai-chatbot/IMPLEMENTATION-STATUS.md index 661cfac..fbe8e17 100644 --- a/specs/epics/ai-chatbot/IMPLEMENTATION-STATUS.md +++ b/specs/epics/ai-chatbot/IMPLEMENTATION-STATUS.md @@ -89,6 +89,18 @@ returns its error to the model instead of failing the response. Workers AI model capabilities are declared rather than fetched, so a chat no longer makes five capability lookups to the gateway (AC-C). +**Since superseded for the gateway's models.** They no longer go to Vercel's +AI Gateway. `gatewayModels` is now three models from Cloudflare's AI Gateway +catalogue (`openai/gpt-5.4-mini`, `xai/grok-4.3`, `deepseek/deepseek-v4-pro`), +run by the same `workers-ai-provider` on the same `AI` binding +(`env.AI.run(id, inputs, { gateway })`) and billed to the account's AI +Gateway credits. They are offered only when `AI_GATEWAY_ID` names the gateway +(`AI_GATEWAY_API_KEY` is gone); their capabilities are declared, so nothing +is fetched; upstream's per-model health lookup and its demo catalogue, which +only Vercel's gateway served, are removed; and a request the gateway cannot +bill opens a dialog that links to the gateway's page. Not exercised against a +live gateway: unit tests cover the routing through the binding. + ### Dev-server bindings only in the dev server; no `populateCache` `initOpenNextCloudflareForDev()` runs only for `next dev` (the config is a diff --git a/testing/e2e.test.sh b/testing/e2e.test.sh index 8dac38c..f9eba1c 100755 --- a/testing/e2e.test.sh +++ b/testing/e2e.test.sh @@ -452,7 +452,7 @@ s, _, body = req("/api/models", cookies=guest_jar) models = json.loads(body) if s == 200 else {} ids = [m["id"] for m in models.get("available") or []] if s != 200 or not ids or not all(i.startswith("@cf/") for i in ids) or "@cf/moonshotai/kimi-k2.6" not in ids: - bad(f"/api/models answered {s} with {ids} — without a gateway key only Workers AI's models are available") + bad(f"/api/models answered {s} with {ids} — with no gateway named only Workers AI's models are available") # ── an attachment, into R2 and back ─────────────────────────────────────── def chunk(kind, data): @@ -509,12 +509,12 @@ if titles != ["Canned title from glm-4.7-flash"]: if not any(e.get("type") == "finish" for e in events): bad("the chat stream never finished") -# A gateway model, asked for with no gateway key: answered by the default +# A gateway model, asked for with no gateway named: answered by the default # Workers AI model, never failed. s, _, _, answer2 = chat(chat_id, "And again, with a model this deployment does not have.", - "xai/grok-4.1-fast-non-reasoning") + "xai/grok-4.3") if s != 200 or not answer2.startswith("Canned answer from @cf/moonshotai/kimi-k2.6"): - bad(f"a gateway model without its key answered {s} {answer2!r}, not the default Workers AI model") + bad(f"a gateway model with no gateway named answered {s} {answer2!r}, not the default Workers AI model") # ── persisted, and listed in the history ────────────────────────────────── for _ in range(20): diff --git a/tests/web/src/health.test.ts b/tests/web/src/health.test.ts index b31d4bb..5839f33 100644 --- a/tests/web/src/health.test.ts +++ b/tests/web/src/health.test.ts @@ -21,7 +21,7 @@ describe("GET /api/health", () => { beforeEach(() => { vi.resetModules(); execute.mockReset(); - delete process.env.AI_GATEWAY_API_KEY; + delete process.env.AI_GATEWAY_ID; delete process.env.HF_TOKEN; }); diff --git a/tests/web/src/models.test.ts b/tests/web/src/models.test.ts index b0cae5a..6e1b95a 100644 --- a/tests/web/src/models.test.ts +++ b/tests/web/src/models.test.ts @@ -2,8 +2,8 @@ import { generateText, streamText } from "ai"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; // The model provider (lib/ai/models.ts, lib/ai/providers.ts). Workers AI, -// through the Worker's AI binding, is the default and needs no key; the AI -// Gateway's models are offered only with AI_GATEWAY_API_KEY. The binding is a +// through the Worker's AI binding, is the default and needs no key; Cloudflare +// AI Gateway's models, on the same binding, are offered only with AI_GATEWAY_ID. The binding is a // stand-in here — it records what it was asked and answers the way Workers // AI's binding does: a JSON body, or a server-sent-event stream when the // inputs ask for `stream: true`. @@ -28,27 +28,27 @@ function sse(chunks: string[]): ReadableStream { describe("the models a deployment offers (lib/ai/models.ts)", () => { beforeEach(() => { vi.resetModules(); - delete process.env.AI_GATEWAY_API_KEY; + delete process.env.AI_GATEWAY_ID; delete process.env.HF_TOKEN; }); afterEach(() => { - delete process.env.AI_GATEWAY_API_KEY; + delete process.env.AI_GATEWAY_ID; delete process.env.HF_TOKEN; }); - it("offers only Workers AI with no gateway key, the default among them", async () => { + it("offers only Workers AI with no gateway named, the default among them", async () => { const models = await import("@/lib/ai/models"); const ids = models.getAvailableModels().map((m) => m.id); expect(ids.every((id) => id.startsWith("@cf/"))).toBe(true); expect(ids).toContain(models.DEFAULT_CHAT_MODEL); - expect(models.isAvailableModel("moonshotai/kimi-k2.5")).toBe(false); + expect(models.isAvailableModel("openai/gpt-5.4-mini")).toBe(false); }); - it("adds the gateway's models once its key is set", async () => { - process.env.AI_GATEWAY_API_KEY = "a-key"; + it("adds the gateway's models once a gateway is named", async () => { + process.env.AI_GATEWAY_ID = "default"; const models = await import("@/lib/ai/models"); const ids = models.getAvailableModels().map((m) => m.id); - expect(ids).toEqual(expect.arrayContaining(["@cf/moonshotai/kimi-k2.6", "moonshotai/kimi-k2.5"])); + expect(ids).toEqual(expect.arrayContaining(["@cf/moonshotai/kimi-k2.6", "openai/gpt-5.4-mini"])); }); it("adds Hugging Face's models once HF_TOKEN is set, and only then", async () => { @@ -59,7 +59,7 @@ describe("the models a deployment offers (lib/ai/models.ts)", () => { models = await import("@/lib/ai/models"); const ids = models.getAvailableModels().map((m) => m.id); expect(ids).toEqual(expect.arrayContaining(["@cf/moonshotai/kimi-k2.6", "moonshotai/Kimi-K3", "zai-org/GLM-5.3"])); - expect(ids).not.toContain("moonshotai/kimi-k2.5"); + expect(ids).not.toContain("openai/gpt-5.4-mini"); }); it("knows each Hugging Face model's capabilities without a network call", async () => { @@ -89,7 +89,7 @@ describe("the provider (lib/ai/providers.ts)", () => { beforeEach(() => { vi.resetModules(); run.mockReset(); - delete process.env.AI_GATEWAY_API_KEY; + delete process.env.AI_GATEWAY_ID; delete process.env.HF_TOKEN; }); afterEach(() => { @@ -97,13 +97,44 @@ describe("the provider (lib/ai/providers.ts)", () => { delete process.env.HF_TOKEN; }); - it("answers a gateway model with no key by the default Workers AI model", async () => { + it("answers a gateway model with no gateway named by the default Workers AI model", async () => { const { resolveModelId } = await import("@/lib/ai/providers"); const { DEFAULT_CHAT_MODEL } = await import("@/lib/ai/models"); - expect(resolveModelId("xai/grok-4.1-fast-non-reasoning")).toBe(DEFAULT_CHAT_MODEL); + expect(resolveModelId("xai/grok-4.3")).toBe(DEFAULT_CHAT_MODEL); expect(resolveModelId("@cf/zai-org/glm-4.7-flash")).toBe("@cf/zai-org/glm-4.7-flash"); - process.env.AI_GATEWAY_API_KEY = "a-key"; - expect(resolveModelId("xai/grok-4.1-fast-non-reasoning")).toBe("xai/grok-4.1-fast-non-reasoning"); + process.env.AI_GATEWAY_ID = "default"; + expect(resolveModelId("xai/grok-4.3")).toBe("xai/grok-4.3"); + }); + + it("runs a gateway model on the AI binding, through the named gateway", async () => { + process.env.AI_GATEWAY_ID = "my-gateway"; + run.mockResolvedValue({ + choices: [{ finish_reason: "stop", index: 0, message: { content: "Hello from the gateway", role: "assistant" } }], + usage: { completion_tokens: 4, prompt_tokens: 1, total_tokens: 5 }, + }); + const fetchSpy = vi.spyOn(globalThis, "fetch"); + const { getLanguageModel } = await import("@/lib/ai/providers"); + const { text } = await generateText({ model: getLanguageModel("openai/gpt-5.4-mini"), prompt: "hi" }); + expect(text).toBe("Hello from the gateway"); + expect(run).toHaveBeenCalledTimes(1); + expect(run.mock.calls[0]![0]).toBe("openai/gpt-5.4-mini"); + expect(run.mock.calls[0]![2]).toMatchObject({ gateway: { id: "my-gateway" } }); + expect(fetchSpy).not.toHaveBeenCalled(); + fetchSpy.mockRestore(); + delete process.env.AI_GATEWAY_ID; + }); + + it("knows each gateway model's capabilities without a network call", async () => { + process.env.AI_GATEWAY_ID = "default"; + const fetchSpy = vi.spyOn(globalThis, "fetch"); + const models = await import("@/lib/ai/models"); + const caps = await models.getCapabilities(); + for (const m of models.gatewayModels) { + expect(caps[m.id]).toEqual(m.capabilities); + } + expect(fetchSpy).not.toHaveBeenCalled(); + fetchSpy.mockRestore(); + delete process.env.AI_GATEWAY_ID; }); it("answers a Hugging Face model with no token by the default Workers AI model", async () => { diff --git a/tests/web/src/wrangler-config.test.ts b/tests/web/src/wrangler-config.test.ts index 45b0526..bfe717a 100644 --- a/tests/web/src/wrangler-config.test.ts +++ b/tests/web/src/wrangler-config.test.ts @@ -79,7 +79,7 @@ describe("apps/web wrangler config", () => { expect(committed).toMatch(/"binding":\s*"HYPERDRIVE"/); expect(committed).toMatch(/"binding":\s*"BLOB"/); expect(committed).not.toMatch(/"vars"/); - expect(committed).not.toMatch(/AI_GATEWAY_API_KEY"\s*:/); + expect(committed).not.toMatch(/AI_GATEWAY_ID"\s*:/); }); it("keeps every resource id and bucket in the template a wiring token", () => {