OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat: support Anthropic for ai
Carl-Gerhard Lindesvärd268c17282360
diff --git a/apps/api/src/agents/models.ts b/apps/api/src/agents/models.tsindex 5a55b3678..f13ec84e0 100644--- a/apps/api/src/agents/models.ts+++ b/apps/api/src/agents/models.ts@@ -1,7 +1,8 @@+import { createAnthropic } from '@better-agent/providers/anthropic';import { createOpenAI } from '@better-agent/providers/openai';import { CHAT_MODELS, type ChatModelEntry } from '@openpanel/validation';-export { CHAT_MODELS as ALLOWED_MODELS, DEFAULT_MODEL_ID } from '@openpanel/validation';+export { CHAT_MODELS as ALLOWED_MODELS } from '@openpanel/validation';export type { ChatModelEntry } from '@openpanel/validation';// ────────────────────────────────────────────────────────────────────@@ -31,6 +32,16 @@ function openai() {return _openai;}+let _anthropic: ReturnType<typeof createAnthropic> | null = null;+function anthropic() {+ if (!_anthropic) {+ _anthropic = createAnthropic({+ apiKey: requireEnv('ANTHROPIC_API_KEY', 'Anthropic'),+ });+ }+ return _anthropic;+}+/*** Exposed for the titler agent in `app.ts`. Same singleton as the one* used by the chat agents so we don't duplicate API-key wiring.@@ -40,15 +51,14 @@ export const openaiProvider = openai;/*** Resolve a model entry to the provider's model instance.* Used by the agent factory.- *- * NB: Anthropic support has been removed. Re-add `createAnthropic`- * from `@better-agent/providers/anthropic` + a switch arm here when- * an Anthropic model is added to the whitelist.*/export function resolveModel(entry: ChatModelEntry) {switch (entry.group) {case 'OpenAI':// biome-ignore lint/suspicious/noExplicitAny: OpenAI model id union is openreturn openai().model(entry.modelId as any);+ case 'Anthropic':+ // biome-ignore lint/suspicious/noExplicitAny: Anthropic model id union is open+ return anthropic().model(entry.modelId as any);}}diff --git a/apps/public/content/docs/self-hosting/deploy-coolify.mdx b/apps/public/content/docs/self-hosting/deploy-coolify.mdxindex 720a9cb34..6ef7dbbdf 100644--- a/apps/public/content/docs/self-hosting/deploy-coolify.mdx+++ b/apps/public/content/docs/self-hosting/deploy-coolify.mdx@@ -45,8 +45,7 @@ Coolify will automatically configure most settings, but you may want to customiz- `ALLOW_INVITATION`: Set to `true` to allow user invitations- `RESEND_API_KEY`: Your Resend API key for email features- `EMAIL_SENDER`: Email sender address- - `OPENAI_API_KEY`: OpenAI API key for AI features (optional)- - `AI_MODEL`: AI model to use (`gpt-4o-mini`, `gpt-4o`, or `claude-3-5`)+ - `OPENAI_API_KEY` and/or `ANTHROPIC_API_KEY`: API keys for the in-app AI chat assistant (optional — set either or both)<Callout>Coolify automatically handles:diff --git a/apps/public/content/docs/self-hosting/deploy-kubernetes.mdx b/apps/public/content/docs/self-hosting/deploy-kubernetes.mdxindex fe33a7c0f..19bc20ee1 100644--- a/apps/public/content/docs/self-hosting/deploy-kubernetes.mdx+++ b/apps/public/content/docs/self-hosting/deploy-kubernetes.mdx@@ -239,20 +239,16 @@ Get your Resend API key from [resend.com](https://resend.com). Make sure to veri#### AI Features-Enable AI-powered features:+Enable the in-app AI chat assistant by setting one or both provider API keys:```yaml-config:- aiModel: "gpt-4o-mini" # Options: gpt-4o, gpt-4o-mini, claude-3-5-secrets:- openaiApiKey: "sk-xxxxxxxxxxxxx" # For OpenAI models- anthropicApiKey: "" # For Claude models (leave empty if not using)- geminiApiKey: "" # For Gemini models (leave empty if not using)+ openaiApiKey: "sk-xxxxxxxxxxxxx" # For GPT-4.1 / 4.1 mini / 5.4 mini+ anthropicApiKey: "sk-ant-xxxxxxxxxxxxx" # For Claude Haiku 4.5 / Sonnet 4.6 / Opus 4.6```<Callout>-You only need to configure the API key for the model you choose. Leave other API keys as empty strings (`""`) if not using them.+The chat's model picker only shows models whose provider has a key configured — set either or both. Without any key, the chat drawer still opens but shows a setup hint.</Callout>#### Google OAuthdiff --git a/apps/public/content/docs/self-hosting/environment-variables.mdx b/apps/public/content/docs/self-hosting/environment-variables.mdxindex df823f0dd..cf69981e1 100644--- a/apps/public/content/docs/self-hosting/environment-variables.mdx+++ b/apps/public/content/docs/self-hosting/environment-variables.mdx@@ -262,26 +262,20 @@ ALLOW_INVITATION=false## AI Features-### AI_MODEL+The in-app AI chat supports **OpenAI** and **Anthropic** models. Set one or both provider keys on the API service — the model picker in the chat UI automatically shows only the models whose provider has a key configured. If neither is set, the chat drawer still opens but shows setup instructions instead of suggestions.-**Type**: `string`-**Required**: No-**Default**: `gpt-4.1-mini`+Available models:-AI model to use for the analytics assistant. Options: `gpt-4o`, `gpt-4o-mini`, `claude-3-5`.--**Example**:-```bash-AI_MODEL=gpt-4o-mini-```+- **OpenAI** — `GPT-4.1`, `GPT-4.1 mini`, `GPT-5.4 mini`+- **Anthropic** — `Claude Haiku 4.5`, `Claude Sonnet 4.6`, `Claude Opus 4.6`### OPENAI_API_KEY**Type**: `string`-**Required**: No (required if using OpenAI models)+**Required**: No**Default**: None-OpenAI API key for AI features. Required if `AI_MODEL` is set to `gpt-4o` or `gpt-4o-mini`.+OpenAI API key. When set, the OpenAI models appear in the chat model picker.**Example**:```bash@@ -290,32 +284,19 @@ OPENAI_API_KEY=sk-your-openai-api-key-here### ANTHROPIC_API_KEY-**Type**: `string`-**Required**: No (required if using Claude models)-**Default**: None--Anthropic API key for Claude AI models. Required if `AI_MODEL` is set to `claude-3-5`.--**Example**:-```bash-ANTHROPIC_API_KEY=your-anthropic-api-key-here-```--### GEMINI_API_KEY-**Type**: `string`**Required**: No**Default**: None-Google Gemini API key for Gemini AI models. Currently not used but reserved for future support.+Anthropic API key. When set, the Claude models appear in the chat model picker.**Example**:```bash-GEMINI_API_KEY=your-gemini-api-key-here+ANTHROPIC_API_KEY=sk-ant-your-anthropic-api-key-here```<Callout type="info">-The AI assistant is optional. Without an API key configured, the AI chat feature will not be available, but all other OpenPanel features will continue to work normally.+The AI assistant is optional. Without `OPENAI_API_KEY` or `ANTHROPIC_API_KEY` set, every other OpenPanel feature continues to work normally.</Callout>@@ -855,8 +836,7 @@ For a basic self-hosted installation, these variables are required:- `RESEND_API_KEY` - For email features- `EMAIL_SENDER` - Email sender address-- `OPENAI_API_KEY` or `ANTHROPIC_API_KEY` - For AI features-- `AI_MODEL` - AI model selection+- `OPENAI_API_KEY` and/or `ANTHROPIC_API_KEY` - For the in-app AI chat assistant### See Alsodiff --git a/apps/public/content/docs/self-hosting/self-hosting.mdx b/apps/public/content/docs/self-hosting/self-hosting.mdxindex 9a53825ed..0a581e4f1 100644--- a/apps/public/content/docs/self-hosting/self-hosting.mdx+++ b/apps/public/content/docs/self-hosting/self-hosting.mdx@@ -116,41 +116,27 @@ For email configuration details, see the [Environment Variables documentation](/### AI integration-OpenPanel includes an AI-powered analytics assistant that can help you analyze data, create reports, and answer questions about your analytics. To enable this feature, you need to configure an API key for either OpenAI or Anthropic.+OpenPanel includes an AI-powered analytics assistant that can help you analyze data, create reports, and answer questions about your analytics. It supports both OpenAI and Anthropic — set one or both keys and the model picker in the chat will only show models whose provider has a key configured.#### Supported Models-- **OpenAI** (default)- - `gpt-4o` - More powerful but higher cost- - `gpt-4o-mini` - Default model, good balance of performance and cost-- **Anthropic**- - `claude-3-5-haiku-latest` - Fast and cost-effective+- **OpenAI** — `GPT-4.1`, `GPT-4.1 mini`, `GPT-5.4 mini`+- **Anthropic** — `Claude Haiku 4.5`, `Claude Sonnet 4.6`, `Claude Opus 4.6`#### Configuration-Add the following environment variables to your `.env` file in the `self-hosting` directory:--**For OpenAI (default):**+Add one or both of the following to your `.env` file in the `self-hosting` directory, then restart the API service:```bash title=".env"+# OpenAI — get a key at platform.openai.com/api-keysOPENAI_API_KEY=sk-your-openai-api-key-here-AI_MODEL=gpt-4o-mini # Optional: defaults to gpt-4o-mini-```--**For Anthropic:**-```bash title=".env"-ANTHROPIC_API_KEY=your-anthropic-api-key-here-AI_MODEL=claude-3-5+# Anthropic — get a key at console.anthropic.com+ANTHROPIC_API_KEY=sk-ant-your-anthropic-api-key-here```-#### Getting API Keys--- **OpenAI**: Get your API key from [platform.openai.com/api-keys](https://platform.openai.com/api-keys)-- **Anthropic**: Get your API key from [console.anthropic.com](https://console.anthropic.com)-<Callout type="info">-The AI assistant is optional. Without an API key configured, the AI chat feature will not be available, but all other OpenPanel features will continue to work normally.+The AI assistant is optional. Without either key set, the chat drawer still opens but shows a setup hint — every other OpenPanel feature continues to work normally.</Callout><Callout type="warn">diff --git a/apps/start/src/agents/models.ts b/apps/start/src/agents/models.tsindex 36a86688f..0397422ab 100644--- a/apps/start/src/agents/models.ts+++ b/apps/start/src/agents/models.ts@@ -1,9 +1,10 @@-// Re-export the shared model whitelist from `@openpanel/validation`.+// Re-export the shared model whitelist helpers from `@openpanel/validation`.// Server + client consume the same source, so drift is a compile error// rather than a silent "agent not found at runtime".+//+// The *available* model list is fetched at runtime via `trpc.chat.models` —+// it filters by which provider API keys the API process has configured.export {- CHAT_MODELS,- DEFAULT_MODEL_ID,MODEL_STORAGE_KEY,getModelLabel,isValidModelId,diff --git a/apps/start/src/components/chat/chat-context.tsx b/apps/start/src/components/chat/chat-context.tsxindex bc22e5990..b3345a144 100644--- a/apps/start/src/components/chat/chat-context.tsx+++ b/apps/start/src/components/chat/chat-context.tsx@@ -1,10 +1,11 @@import {- CHAT_MODELS,type ChatModelOption,- DEFAULT_MODEL_ID,isValidModelId,MODEL_STORAGE_KEY,} from '@/agents/models';+import { useAppContext } from '@/hooks/use-app-context';+import { useTRPC } from '@/integrations/trpc/react';+import { useQuery } from '@tanstack/react-query';import {createContext,type ReactNode,@@ -89,13 +90,26 @@ type ChatStateValue = {const ChatContext = createContext<ChatStateValue | null>(null);-function readStoredAgent(): string {- if (typeof window === 'undefined') return DEFAULT_MODEL_ID;+function readStoredAgent(): string | null {+ if (typeof window === 'undefined') return null;const raw = window.localStorage.getItem(MODEL_STORAGE_KEY);- return isValidModelId(raw) ? raw : DEFAULT_MODEL_ID;+ return isValidModelId(raw) ? raw : null;}export function ChatStateProvider({ children }: { children: ReactNode }) {+ const { isAiEnabled } = useAppContext();+ const trpc = useTRPC();++ // Fetch the list of models the API can actually serve. When the user has+ // no AI env vars set, `isAiEnabled` is false and we skip the query — the+ // drawer's empty state shows setup instructions instead.+ const modelsQuery = useQuery({+ ...trpc.chat.models.queryOptions(),+ enabled: isAiEnabled,+ staleTime: Number.POSITIVE_INFINITY,+ });+ const models = modelsQuery.data?.models ?? [];+ const defaultModelId = modelsQuery.data?.defaultModelId ?? null;// URL is the source of truth for the active conversation + drawer// open state. `chatParam`:// - null → drawer closed@@ -145,17 +159,33 @@ export function ChatStateProvider({ children }: { children: ReactNode }) {const newConversation = openNewChat;- // Model selection — persisted to localStorage.- const [agentName, setAgentNameState] = useState<string>(() =>- readStoredAgent(),+ // Model selection — persisted to localStorage. Initial value is the+ // stored preference (if any); resolves to the server-provided default+ // once the models query loads.+ const [agentName, setAgentNameState] = useState<string>(+ () => readStoredAgent() ?? '',);- const setAgent = useCallback((id: string) => {- if (!isValidModelId(id)) return;- setAgentNameState(id);- if (typeof window !== 'undefined') {- window.localStorage.setItem(MODEL_STORAGE_KEY, id);- }- }, []);+ const setAgent = useCallback(+ (id: string) => {+ if (!models.some((m) => m.id === id)) return;+ setAgentNameState(id);+ if (typeof window !== 'undefined') {+ window.localStorage.setItem(MODEL_STORAGE_KEY, id);+ }+ },+ [models],+ );++ // Once the models query resolves, make sure `agentName` points at a+ // model the server can actually serve. Covers:+ // - first render (no stored preference) → pick `defaultModelId`+ // - stored preference from a provider that's no longer configured+ // (e.g. ANTHROPIC_API_KEY was removed) → fall back to default+ useEffect(() => {+ if (!defaultModelId) return;+ if (agentName && models.some((m) => m.id === agentName)) return;+ setAgentNameState(defaultModelId);+ }, [agentName, defaultModelId, models]);// Transient session state.const [streamingTitle, setStreamingTitle] = useState<string | null>(null);@@ -184,7 +214,7 @@ export function ChatStateProvider({ children }: { children: ReactNode }) {switchConversation,newConversation,agentName,- models: CHAT_MODELS,+ models,setAgent,streamingTitle,setStreamingTitle,@@ -201,6 +231,7 @@ export function ChatStateProvider({ children }: { children: ReactNode }) {switchConversation,newConversation,agentName,+ models,setAgent,streamingTitle,pendingMessage,diff --git a/apps/start/src/components/chat/chat-drawer-body.tsx b/apps/start/src/components/chat/chat-drawer-body.tsxindex d16d0e6ea..103f7614f 100644--- a/apps/start/src/components/chat/chat-drawer-body.tsx+++ b/apps/start/src/components/chat/chat-drawer-body.tsx@@ -1,7 +1,7 @@import { Button } from '@/components/ui/button';import { usePageContextValue } from '@/contexts/page-context';import { cn } from '@/utils/cn';-import { ArrowDownIcon } from 'lucide-react';+import { AlertCircleIcon, ArrowDownIcon } from 'lucide-react';import {StickToBottom,useStickToBottomContext,@@ -20,7 +20,7 @@ import { useChatRuntime } from './chat-runtime';* up — courtesy of `use-stick-to-bottom`. Zero refs, zero effects.*/export function ChatDrawerBody() {- const { messages, isLoading, isStreaming } = useChatRuntime();+ const { messages, isLoading, isStreaming, status, error } = useChatRuntime();const hasContext = usePageContextValue();@@ -69,6 +69,14 @@ export function ChatDrawerBody() {<span className="op-shimmer font-medium">Thinking…</span></div>)}+ {status === 'error' && (+ <div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">+ <AlertCircleIcon className="size-4 shrink-0 mt-0.5" />+ <span className="leading-[1.5]">+ {error?.message ?? 'Something went wrong. Try again.'}+ </span>+ </div>+ )}</StickToBottom.Content><ScrollToBottomButton /></StickToBottom>diff --git a/apps/start/src/components/chat/chat-drawer-empty.tsx b/apps/start/src/components/chat/chat-drawer-empty.tsxindex 952462abe..dd4001a76 100644--- a/apps/start/src/components/chat/chat-drawer-empty.tsx+++ b/apps/start/src/components/chat/chat-drawer-empty.tsx@@ -1,14 +1,14 @@+import CopyInput from '@/components/forms/copy-input';import { usePageContextValue } from '@/contexts/page-context';-import { SparklesIcon } from 'lucide-react';+import { ExternalLinkIcon, KeyRoundIcon, SparklesIcon } from 'lucide-react';import { useChatRuntime } from './chat-runtime';/**- * Empty-state panel shown when a chat has no messages yet. Headline,- * description, and example prompts are tailored to the current page- * so the user gets ideas relevant to what they're looking at. The- * prompts are clickable — they fire the same `send()` as typing and- * pressing Enter, so the user can kick off the conversation in one- * tap.+ * Empty-state panel shown inside the drawer body when a chat has no+ * messages yet — page-aware suggestion prompts. The "AI not configured"+ * variant is a separate component (`ChatDrawerNotConfigured` below)+ * rendered directly from `<ChatDrawer>` without the runtime, since+ * it doesn't depend on an agent being available.*/export function ChatDrawerEmpty() {const ctx = usePageContextValue();@@ -42,6 +42,38 @@ export function ChatDrawerEmpty() {);}+export function ChatDrawerNotConfigured() {+ return (+ <div className="flex flex-1 flex-col items-center justify-center gap-5 px-6 py-8 text-center">+ <div className="flex size-10 items-center justify-center rounded-full bg-muted text-muted-foreground">+ <KeyRoundIcon className="size-5" />+ </div>+ <div className="max-w-xs">+ <h3 className="font-semibold text-xl mb-2">AI chat isn't configured</h3>+ <p className="mt-1.5 text-muted-foreground leading-[1.5]">+ Set <code className="font-mono text-sm">OPENAI_API_KEY</code> and/or{' '}+ <code className="font-mono text-sm">ANTHROPIC_API_KEY</code> on the+ API service to enable AI chat, then restart it. The model picker+ shows only providers with a configured key.+ </p>+ </div>+ <div className="flex w-full max-w-xs flex-col gap-2">+ <CopyInput label="OpenAI" value="OPENAI_API_KEY=sk-..." />+ <CopyInput label="Anthropic" value="ANTHROPIC_API_KEY=sk-ant-..." />+ </div>+ <a+ href="https://openpanel.dev/docs/self-hosting/environment-variables#ai-features"+ target="_blank"+ rel="noopener"+ className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"+ >+ View setup docs+ <ExternalLinkIcon className="size-3.5" />+ </a>+ </div>+ );+}+type Suggestions = {headline: string;description: string;diff --git a/apps/start/src/components/chat/chat-drawer.tsx b/apps/start/src/components/chat/chat-drawer.tsxindex 1c18380bd..fc3f7c7bc 100644--- a/apps/start/src/components/chat/chat-drawer.tsx+++ b/apps/start/src/components/chat/chat-drawer.tsx@@ -1,8 +1,10 @@+import { useAppContext } from '@/hooks/use-app-context';import { useAppParams } from '@/hooks/use-app-params';import { useResizableDrawer } from '@/hooks/use-resizable-drawer';import { useEffect } from 'react';import { useChatState } from './chat-context';import { ChatDrawerBody } from './chat-drawer-body';+import { ChatDrawerNotConfigured } from './chat-drawer-empty';import { ChatDrawerFooter } from './chat-drawer-footer';import { ChatDrawerHeader } from './chat-drawer-header';import { ChatRuntimeProvider } from './chat-runtime';@@ -25,7 +27,8 @@ const MAX_WIDTH = 720;*/export function ChatDrawer() {const { projectId } = useAppParams();- const { conversationId, isOpen, closeChat, openChatForContext } =+ const { isAiEnabled } = useAppContext();+ const { agentName, conversationId, isOpen, closeChat, openChatForContext } =useChatState();const { width, dragHandleProps } = useResizableDrawer({defaultWidth: DEFAULT_WIDTH,@@ -80,16 +83,27 @@ export function ChatDrawer() {/><ChatDrawerHeader projectId={projectId} onClose={closeChat} />{/*- Remount the runtime provider (and the `useAgent` controller- inside it) whenever `conversationId` changes. The controller- caches the id in a ref and only loads from the server on- `init()`, so without this key a switch wouldn't trigger the- hydrate fetch.+ Three states here:+ 1. `!isAiEnabled` — neither `OPENAI_API_KEY` nor+ `ANTHROPIC_API_KEY` is set on the API. Skip the runtime+ entirely and render the setup-instructions empty state.+ 2. `isAiEnabled` but `agentName` is still empty — the+ `trpc.chat.models` query is in flight. Render a brief+ placeholder so we don't crash `useAgent({ agent: '' })`.+ 3. `agentName` resolved — mount the runtime as normal.+ `key={conversationId}` remounts the `useAgent` controller+ on conversation switches to force a fresh hydrate.*/}- <ChatRuntimeProvider key={conversationId}>- <ChatDrawerBody />- <ChatDrawerFooter />- </ChatRuntimeProvider>+ {!isAiEnabled ? (+ <ChatDrawerNotConfigured />+ ) : agentName ? (+ <ChatRuntimeProvider key={conversationId}>+ <ChatDrawerBody />+ <ChatDrawerFooter />+ </ChatRuntimeProvider>+ ) : (+ <div className="flex-1" />+ )}</aside></>);diff --git a/apps/start/src/hooks/use-app-context.ts b/apps/start/src/hooks/use-app-context.tsindex b01c6123d..b36030598 100644--- a/apps/start/src/hooks/use-app-context.ts+++ b/apps/start/src/hooks/use-app-context.ts@@ -18,5 +18,6 @@ export function useAppContext() {isSelfHosted: params.isSelfHosted,isMaintenance: params.isMaintenance ?? false,isDemo: params.isDemo ?? false,+ isAiEnabled: params.isAiEnabled ?? false,};}diff --git a/apps/start/src/routes/api/config.tsx b/apps/start/src/routes/api/config.tsxindex 0b1b1d08a..508348d01 100644--- a/apps/start/src/routes/api/config.tsx+++ b/apps/start/src/routes/api/config.tsx@@ -7,6 +7,7 @@ export interface ConfigResonse {isSelfHosted: boolean;isMaintenance: boolean;isDemo: boolean;+ isAiEnabled: boolean;}// Nothing sensitive here, its client environment variables which is good for debuggingexport const Route = createFileRoute('/api/config')({diff --git a/apps/start/src/server/get-envs.ts b/apps/start/src/server/get-envs.tsindex f1202c096..26f7cc0fb 100644--- a/apps/start/src/server/get-envs.ts+++ b/apps/start/src/server/get-envs.ts@@ -10,6 +10,9 @@ export const getServerEnvs = createServerFn().handler(() => {isSelfHosted: process.env.SELF_HOSTED !== undefined,isMaintenance: process.env.MAINTENANCE === '1',isDemo: process.env.DEMO_USER_ID !== undefined,+ isAiEnabled: Boolean(+ process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY,+ ),};return envs;diff --git a/packages/trpc/src/root.ts b/packages/trpc/src/root.tsindex 2579322ad..657fb7ada 100644--- a/packages/trpc/src/root.ts+++ b/packages/trpc/src/root.ts@@ -1,5 +1,6 @@import { authRouter } from './routers/auth';import { chartRouter } from './routers/chart';+import { chatRouter } from './routers/chat';import { clientRouter } from './routers/client';import { conversationRouter } from './routers/conversation';import { dashboardRouter } from './routers/dashboard';@@ -51,6 +52,7 @@ export const appRouter = createTRPCRouter({subscription: subscriptionRouter,overview: overviewRouter,realtime: realtimeRouter,+ chat: chatRouter,conversation: conversationRouter,insight: insightRouter,widget: widgetRouter,diff --git a/packages/trpc/src/routers/chat.ts b/packages/trpc/src/routers/chat.tsnew file mode 100644index 000000000..9228934f2--- /dev/null+++ b/packages/trpc/src/routers/chat.ts@@ -0,0 +1,26 @@+import { getAvailableChatModels } from '@openpanel/validation';++import { createTRPCRouter, protectedProcedure } from '../trpc';++/**+ * Chat config — provider availability is derived from the API process's env+ * vars and returned to the client so the model picker only shows models the+ * server can actually serve.+ *+ * The Better Agent app still registers every model in the whitelist (it's+ * built eagerly at import time); this filter only governs what the UI offers.+ */+export const chatRouter = createTRPCRouter({+ models: protectedProcedure.query(() => {+ const providers = {+ openai: Boolean(process.env.OPENAI_API_KEY),+ anthropic: Boolean(process.env.ANTHROPIC_API_KEY),+ };+ const models = getAvailableChatModels(providers);+ return {+ providers,+ models,+ defaultModelId: models[0]?.id ?? null,+ };+ }),+});diff --git a/packages/validation/src/chat.ts b/packages/validation/src/chat.tsindex 9288169c7..b890f89b7 100644--- a/packages/validation/src/chat.ts+++ b/packages/validation/src/chat.ts@@ -87,13 +87,15 @@ export type ChatAgentContext = z.infer<typeof chatContextSchema>;// Adding a new model = add an entry here. No other changes required.// ────────────────────────────────────────────────────────────────────+export type ChatProvider = 'OpenAI' | 'Anthropic';+export type ChatModelEntry = {/** URL-safe agent name (no colons, slashes, or percent-encoding needed). */id: string;/** Native model id passed to the provider client. */modelId: string;label: string;- group: 'OpenAI';+ group: ChatProvider;/*** When true, the agent is configured with the provider's `reasoning`* options so the model returns reasoning tokens as streamed text@@ -118,12 +120,28 @@ export const CHAT_MODELS = [group: 'OpenAI',reasoning: true,},+ {+ id: 'claude-haiku-4-5',+ modelId: 'claude-haiku-4-5',+ label: 'Claude Haiku 4.5',+ group: 'Anthropic',+ },+ {+ id: 'claude-sonnet-4-6',+ modelId: 'claude-sonnet-4-6',+ label: 'Claude Sonnet 4.6',+ group: 'Anthropic',+ },+ {+ id: 'claude-opus-4-6',+ modelId: 'claude-opus-4-6',+ label: 'Claude Opus 4.6',+ group: 'Anthropic',+ },] as const satisfies readonly ChatModelEntry[];export type ChatModelId = (typeof CHAT_MODELS)[number]['id'];-export const DEFAULT_MODEL_ID: ChatModelId = CHAT_MODELS[0].id;-export const MODEL_STORAGE_KEY = 'op-chat-model';export function isValidModelId(id: string | null | undefined): id is ChatModelId {@@ -134,6 +152,22 @@ export function getModelLabel(id: string): string {return CHAT_MODELS.find((m) => m.id === id)?.label ?? id;}+/**+ * Filter the whitelist to models whose provider has an API key configured.+ * Returned in the same order as `CHAT_MODELS` (OpenAI first, then Anthropic)+ * so the first entry is a stable default.+ */+export function getAvailableChatModels(providers: {+ openai: boolean;+ anthropic: boolean;+}): ChatModelEntry[] {+ return CHAT_MODELS.filter((m) => {+ if (m.group === 'OpenAI') return providers.openai;+ if (m.group === 'Anthropic') return providers.anthropic;+ return false;+ });+}+// ────────────────────────────────────────────────────────────────────// Client-side tool schemas — the three URL-param mutators the LLM can// call on the page. Defined here because both the server (wraps them