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
14 changes: 14 additions & 0 deletions .baseline/product/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,20 @@ model. 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.

To add Hugging Face's open models (Kimi K3, GLM 5.3, DeepSeek V4.1 Flash,
Qwen3.8 27B), create a Hugging Face token with the "Make calls to Inference
Providers" permission (https://huggingface.co/settings/tokens) and set it per
environment:

```bash
wrangler secret put HF_TOKEN --name ai-chatbot-web-stage
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.

## Other optional secrets

- **`AUTH_SECRET`.** The session cookie needs no secret from you: unless you
Expand Down
9 changes: 8 additions & 1 deletion BOOTSTRAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,14 @@ orun new --blueprint repo-blueprint.yaml \
wrangler secret put AI_GATEWAY_API_KEY --name <reponame>-web-<env>
```

Without it the picker offers only the Workers AI models. The product's
Hugging Face's open models are the same with `HF_TOKEN` (a token with
"Make calls to Inference Providers"):

```bash
wrangler secret put HF_TOKEN --name <reponame>-web-<env>
```

Without either the picker offers only the Workers AI models. The product's
README, "Models", is the owner's copy of this.
- **The session key** needs nothing: the database generated one per
environment when the migrations first ran. `AUTH_SECRET` as a Worker secret
Expand Down
3 changes: 2 additions & 1 deletion ai/context/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,9 @@ orun integrations list --org <ws> --json && orun cloud check --org <ws>
|---|---|
| deploy a change | merge to `main`; watch the run; failed lanes → `gh run rerun --failed` |
| change the schema | add the table to `apps/web/lib/db/schema.ts` with `.enableRLS()`, `pnpm --filter @app/web db:generate`, copy the SQL into a new `packages/db/src/migrations/<nnn>_<name>/up.sql` and the manifest (`pnpm --filter @saas/db run manifest:fix` for its checksum), merge — db-migrate applies it before the app deploys. `pnpm test` fails on a table in `public` without row-level security |
| add or change a model | `apps/web/lib/ai/models.ts`: a Workers AI model in `workersAiModels` with its capabilities, a gateway model in `gatewayModels` |
| add or change a model | `apps/web/lib/ai/models.ts`: a Workers AI model in `workersAiModels` with its capabilities, a Hugging Face model (its Hub id, served with tools on router.huggingface.co/v1/models) in `huggingFaceModels` with its capabilities, a gateway model in `gatewayModels` |
| turn the AI Gateway on | `wrangler secret put AI_GATEWAY_API_KEY --name ai-chatbot-web-<env>` |
| turn Hugging Face on | `wrangler secret put HF_TOKEN --name ai-chatbot-web-<env>` (a token with "Make calls to Inference Providers") |
| redeploy without a change | edit the last line of the component's `component.yaml` (`# orun: redeploy <reason> <stamp>`) and merge — it is a deploy trigger, nothing reads it |
| rotate the session key | `wrangler secret put AUTH_SECRET --name ai-chatbot-web-<env>` (32+ random bytes); every session ends |
| serve a custom domain | attach it to the Worker in Cloudflare (Workers & Pages → the Worker → Settings → Domains & Routes), then set `SITE_URL` under the environment's `env:` in `intent.yaml` (the Open Graph images' origin), replace the placeholder `ai-chatbot.example.com` in its `BASE_DOMAIN` with the domain, and merge |
Expand Down
5 changes: 5 additions & 0 deletions apps/web/.dev.vars.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
# The Vercel AI Gateway: adds upstream's gateway models to the picker.
# AI_GATEWAY_API_KEY=

# 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
# Providers" (https://huggingface.co/settings/tokens).
# HF_TOKEN=

# Redis: resumable streams and the per-IP rate limit.
# REDIS_URL=

Expand Down
4 changes: 4 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ AUTH_SECRET=
# (https://vercel.com/ai-gateway) adds upstream's gateway models.
AI_GATEWAY_API_KEY=

# Optional. A Hugging Face token with "Make calls to Inference Providers"
# (https://huggingface.co/settings/tokens) adds Hugging Face's open models.
HF_TOKEN=

# Optional. Cloudflare Web Analytics beacon token (stands in for Vercel
# Analytics). Unset → no script is rendered.
NEXT_PUBLIC_CF_BEACON_TOKEN=
Expand Down
4 changes: 2 additions & 2 deletions apps/web/app/(chat)/api/models/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {
} from "@/lib/ai/models";

// What the model picker shows: `available` is exactly what this deployment
// can run — the Workers AI models always, the AI Gateway's only when its key
// is set — and `capabilities` says what each supports. In the demo mode
// 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.
export async function GET() {
Expand Down
9 changes: 8 additions & 1 deletion apps/web/app/api/health/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { sql } from "drizzle-orm";
import { connection } from "next/server";
import { DEFAULT_CHAT_MODEL, isGatewayConfigured } from "@/lib/ai/models";
import {
DEFAULT_CHAT_MODEL,
isGatewayConfigured,
isHuggingFaceConfigured,
} from "@/lib/ai/models";
import { getDb } from "@/lib/db/queries";

// Not upstream's: the deploy's smoke check and the bootstrap's probes read
Expand Down Expand Up @@ -30,6 +34,9 @@ export async function GET() {
models: {
default: DEFAULT_CHAT_MODEL,
gateway: isGatewayConfigured() ? "connected" : "not connected",
huggingface: isHuggingFaceConfigured()
? "connected"
: "not connected",
provider: "workers-ai",
},
ok,
Expand Down
84 changes: 73 additions & 11 deletions apps/web/lib/ai/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
// 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), and the picker shows exactly
// what is available (`getAvailableModels`), never a model that would fail.
// 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.
export const DEFAULT_CHAT_MODEL = "@cf/moonshotai/kimi-k2.6";

export type ModelCapabilities = {
Expand All @@ -18,10 +19,11 @@ export type ChatModel = {
name: string;
provider: string;
description: string;
// `workers-ai`: the AI binding; `gateway`: the AI Gateway (needs its key).
via?: "workers-ai" | "gateway";
// Workers AI models' capabilities are known here; the gateway's are looked
// up from the gateway (getCapabilities).
// `workers-ai`: the AI binding; `gateway`: the AI Gateway (needs its key);
// `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).
capabilities?: ModelCapabilities;
gatewayOrder?: string[];
reasoningEffort?: "none" | "minimal" | "low" | "medium" | "high";
Expand Down Expand Up @@ -105,8 +107,51 @@ export const gatewayModels: ChatModel[] = [
},
];

// Open models on Hugging Face's Inference Providers router, each one served
// with tool calling by at least two providers (router.huggingface.co/v1/models).
// The router picks the provider; the id is the model's Hub id. Offered only
// with HF_TOKEN set.
export const huggingFaceModels: ChatModel[] = [
{
capabilities: { reasoning: true, tools: true, vision: false },
description: "Moonshot AI's Kimi K3 on Hugging Face — tools, reasoning",
id: "moonshotai/Kimi-K3",
name: "Kimi K3",
provider: "huggingface",
via: "huggingface",
},
{
capabilities: { reasoning: true, tools: true, vision: false },
description: "Z.ai's GLM 5.3 on Hugging Face — tools, reasoning",
id: "zai-org/GLM-5.3",
name: "GLM 5.3",
provider: "huggingface",
via: "huggingface",
},
{
capabilities: { reasoning: true, tools: true, vision: false },
description: "Fast DeepSeek on Hugging Face — tools, reasoning",
id: "deepseek-ai/DeepSeek-V4.1-Flash",
name: "DeepSeek V4.1 Flash",
provider: "huggingface",
via: "huggingface",
},
{
capabilities: { reasoning: true, tools: true, vision: false },
description: "Compact Qwen on Hugging Face — tools, reasoning",
id: "Qwen/Qwen3.8-27B",
name: "Qwen3.8 27B",
provider: "huggingface",
via: "huggingface",
},
];

// Every model this app knows, in picker order.
export const chatModels: ChatModel[] = [...workersAiModels, ...gatewayModels];
export const chatModels: ChatModel[] = [
...workersAiModels,
...huggingFaceModels,
...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
Expand All @@ -115,10 +160,22 @@ export function isGatewayConfigured(): boolean {
return Boolean(process.env.AI_GATEWAY_API_KEY);
}

// 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.
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), the gateway's models only with its key.
// wrangler config), Hugging Face's and the gateway's models only with their
// keys.
export function getAvailableModels(): ChatModel[] {
return isGatewayConfigured() ? chatModels : workersAiModels;
return [
...workersAiModels,
...(isHuggingFaceConfigured() ? huggingFaceModels : []),
...(isGatewayConfigured() ? gatewayModels : []),
];
}

export function isAvailableModel(modelId: string): boolean {
Expand All @@ -129,6 +186,10 @@ export function isWorkersAiModel(modelId: string): boolean {
return workersAiModels.some((m) => m.id === modelId);
}

export function isHuggingFaceModel(modelId: string): boolean {
return huggingFaceModels.some((m) => m.id === modelId);
}

export async function getCapabilities(): Promise<
Record<string, ModelCapabilities>
> {
Expand Down Expand Up @@ -269,8 +330,9 @@ export async function getModelAvailability(
): Promise<ModelAvailability> {
const model = chatModels.find((item) => item.id === modelId);

// Workers AI reports no per-model health the way the gateway does.
if (!model || model.via === "workers-ai") {
// 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";
}

Expand Down
20 changes: 18 additions & 2 deletions apps/web/lib/ai/providers.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { getCloudflareContext } from "@opennextjs/cloudflare";
import { customProvider, gateway, type LanguageModel } from "ai";
import { createWorkersAI } from "workers-ai-provider";
import { isTestEnvironment } from "../constants";
import {
DEFAULT_CHAT_MODEL,
isAvailableModel,
isHuggingFaceModel,
isWorkersAiModel,
titleModel,
} from "./models";
Expand Down Expand Up @@ -37,8 +39,19 @@ function workersAi() {
return createWorkersAI({ binding: env.AI });
}

// A model id the request may not use — a gateway model with no gateway key,
// or one nobody lists — falls back to the default Workers AI model rather
// 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).
function huggingFace() {
return createOpenAICompatible({
apiKey: process.env.HF_TOKEN,
baseURL: "https://router.huggingface.co/v1",
name: "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
// than failing the chat (lib/ai/models.ts, getAvailableModels).
export function resolveModelId(modelId: string): string {
return isAvailableModel(modelId) ? modelId : DEFAULT_CHAT_MODEL;
Expand All @@ -53,6 +66,9 @@ export function getLanguageModel(modelId: string): LanguageModel {
if (isWorkersAiModel(id)) {
return workersAi()(id);
}
if (isHuggingFaceModel(id)) {
return huggingFace()(id);
}
return gateway.languageModel(id);
}

Expand Down
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"wire:fixture": "node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json --env stage"
},
"dependencies": {
"@ai-sdk/openai-compatible": "3.0.5",
"@ai-sdk/provider": "4.0.2",
"@ai-sdk/react": "4.0.16",
"@codemirror/lang-python": "^6.2.1",
Expand Down
8 changes: 4 additions & 4 deletions apps/web/wrangler.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@
"ai": {
"binding": "AI"
}
// AUTH_SECRET and AI_GATEWAY_API_KEY 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 only the Workers AI models are offered. REDIS_URL is absent
// AUTH_SECRET, AI_GATEWAY_API_KEY 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
// 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.
}
8 changes: 4 additions & 4 deletions apps/web/wrangler.template.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@
"ai": {
"binding": "AI"
}
// AUTH_SECRET and AI_GATEWAY_API_KEY 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 only the Workers AI models are offered. REDIS_URL is absent
// AUTH_SECRET, AI_GATEWAY_API_KEY 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
// 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.
}
18 changes: 18 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion tests/web/src/health.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ describe("GET /api/health", () => {
vi.resetModules();
execute.mockReset();
delete process.env.AI_GATEWAY_API_KEY;
delete process.env.HF_TOKEN;
});

it("is ok when the database is reachable and migrated, and names the model provider", async () => {
Expand All @@ -30,7 +31,12 @@ describe("GET /api/health", () => {
expect(status).toBe(200);
expect(body).toEqual({
database: "reachable",
models: { default: "@cf/moonshotai/kimi-k2.6", gateway: "not connected", provider: "workers-ai" },
models: {
default: "@cf/moonshotai/kimi-k2.6",
gateway: "not connected",
huggingface: "not connected",
provider: "workers-ai",
},
ok: true,
schema: "migrated",
});
Expand Down
Loading
Loading