Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 19 additions & 10 deletions .baseline/product/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]` |
Expand Down Expand Up @@ -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.

Expand All @@ -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

Expand Down
12 changes: 7 additions & 5 deletions BOOTSTRAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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 <reponame>-web-<env>
wrangler secret put AI_GATEWAY_ID --name <reponame>-web-<env>
```

Hugging Face's open models are the same with `HF_TOKEN` (a token with
Expand Down
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<key>`; 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
Expand Down Expand Up @@ -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.

Expand All @@ -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]` |
Expand Down Expand Up @@ -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 |
Expand Down
7 changes: 5 additions & 2 deletions apps/web/.dev.vars.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 3 additions & 2 deletions apps/web/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 12 additions & 26 deletions apps/web/app/(chat)/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
}
}
Expand Down
38 changes: 6 additions & 32 deletions apps/web/app/(chat)/api/models/route.ts
Original file line number Diff line number Diff line change
@@ -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 }
);
}
2 changes: 1 addition & 1 deletion apps/web/components/chat/multimodal-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -801,7 +801,7 @@ function PureModelSelectorCompact({
const capabilities: Record<string, ModelCapabilities> | 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;
Expand Down
13 changes: 6 additions & 7 deletions apps/web/components/chat/shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 ?? ""}/`;
}, []);

Expand Down Expand Up @@ -196,17 +194,18 @@ export function ChatShell() {
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Activate AI Gateway</AlertDialogTitle>
<AlertDialogTitle>Set up AI Gateway billing</AlertDialogTitle>
<AlertDialogDescription>
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&apos;s
authentication.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleActivateGateway}>
Activate
Open AI Gateway
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
Expand Down
4 changes: 2 additions & 2 deletions apps/web/hooks/use-active-chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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" });
Expand Down
Loading
Loading