Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): source model pricing from a bundled LiteLLM table

Elian Doran3169513ab2f2
diff --git a/.github/workflows/update-model-prices.yml b/.github/workflows/update-model-prices.yml
new file mode 100644
index 0000000000..c89292f690
--- /dev/null
+++ b/.github/workflows/update-model-prices.yml
@@ -0,0 +1,48 @@
+name: Update model prices
+
+# Refreshes the committed LLM price table (apps/server/src/services/llm/providers/model_prices.json)
+# from LiteLLM's upstream data. Runs weekly and on demand; opens a PR only when the
+# pruned output actually changes, so a human reviews price movements before they ship.
+# The build never fetches this itself — it imports the committed JSON and stays hermetic.
+on:
+ schedule:
+ - cron: "0 6 * * 1" # Mondays 06:00 UTC
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ update-model-prices:
+ name: Refresh model_prices.json
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ pull-requests: write
+ steps:
+ - uses: actions/checkout@v7
+ - uses: pnpm/action-setup@v6
+ - name: Set up node & dependencies
+ uses: actions/setup-node@v7
+ with:
+ node-version: 24
+ cache: "pnpm"
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+ - name: Regenerate the price table
+ run: pnpm --filter server update-model-prices
+ - name: Open a PR if the table changed
+ uses: peter-evans/create-pull-request@v7
+ with:
+ add-paths: apps/server/src/services/llm/providers/model_prices.json
+ branch: chore/update-model-prices
+ commit-message: "chore(llm): refresh model price table from LiteLLM"
+ title: "chore(llm): refresh model price table"
+ body: |
+ Automated refresh of the committed LLM price/context table
+ (`apps/server/src/services/llm/providers/model_prices.json`) from
+ [LiteLLM](https://github.com/BerriAI/litellm)'s upstream data, via
+ `pnpm --filter server update-model-prices`.
+
+ Review the diff for notable price movements before merging.
+ labels: dependencies
diff --git a/apps/client/src/services/llm_chat.spec.ts b/apps/client/src/services/llm_chat.spec.ts
index 02e8216c9a..a1026ec4cf 100644
--- a/apps/client/src/services/llm_chat.spec.ts
+++ b/apps/client/src/services/llm_chat.spec.ts
@@ -61,6 +61,18 @@ describe("fetchProviderModels", () => {
server.post = vi.fn(async () => ({})) as typeof server.post;
await expect(fetchProviderModels({ provider: "openai" })).resolves.toEqual([]);
});
+
+ it("surfaces the server error message when the request fails", async () => {
+ // server.post rejects with the raw response body (a { message } JSON string).
+ server.post = vi.fn(async () => { throw '{"message":"Authentication failed (HTTP 401) — check the API key."}'; }) as typeof server.post;
+ await expect(fetchProviderModels({ provider: "openai", apiKey: "bad" }))
+ .rejects.toThrow("Authentication failed (HTTP 401) — check the API key.");
+ });
+
+ it("falls back to the raw rejection when it isn't a JSON error body", async () => {
+ server.post = vi.fn(async () => { throw "rejected by browser"; }) as typeof server.post;
+ await expect(fetchProviderModels({ provider: "openai" })).rejects.toThrow("rejected by browser");
+ });
});
describe("streamChatCompletion", () => {
diff --git a/apps/client/src/services/llm_chat.ts b/apps/client/src/services/llm_chat.ts
index 7c6b4a03d0..62cd1d6019 100644
--- a/apps/client/src/services/llm_chat.ts
+++ b/apps/client/src/services/llm_chat.ts
@@ -12,11 +12,35 @@ export interface ProviderModelsQuery {
/**
* Fetch the live model list for a provider from its credentials. Used by the
* model-selection screen while adding or editing a provider — the config need
- * not be saved yet.
+ * not be saved yet. A server-side failure (e.g. a bad API key) rejects with a
+ * clean message the screen can display.
*/
export async function fetchProviderModels(query: ProviderModelsQuery): Promise<LlmModelInfo[]> {
- const response = await server.post<{ models?: LlmModelInfo[] }>("llm-chat/provider-models", query);
- return response.models ?? [];
+ try {
+ const response = await server.post<{ models?: LlmModelInfo[] }>("llm-chat/provider-models", query);
+ return response.models ?? [];
+ } catch (error) {
+ throw new Error(serverErrorMessage(error));
+ }
+}
+
+/**
+ * Extract a human-readable message from a rejected `server.post`, which surfaces
+ * the raw response body (a `{ "message": … }` JSON string) rather than an Error.
+ */
+function serverErrorMessage(error: unknown): string {
+ if (typeof error === "string") {
+ try {
+ const parsed = JSON.parse(error);
+ if (parsed && typeof parsed.message === "string") {
+ return parsed.message;
+ }
+ } catch {
+ // Not JSON — the raw string is the best message we have.
+ }
+ return error;
+ }
+ return error instanceof Error ? error.message : String(error);
}
export interface StreamCallbacks {
diff --git a/apps/client/src/services/llm_model_cost.ts b/apps/client/src/services/llm_model_cost.ts
new file mode 100644
index 0000000000..b1345e958e
--- /dev/null
+++ b/apps/client/src/services/llm_model_cost.ts
@@ -0,0 +1,20 @@
+import type { LlmModelInfo } from "@triliumnext/commons";
+
+import { t } from "./i18n.js";
+
+/**
+ * Human-readable per-model cost hint for the model pickers: "Subscription" for
+ * subscription-covered models, "$3 / $15 per Mtok" (input / output, USD per
+ * million tokens) for metered ones, and undefined when pricing is unknown —
+ * dynamically discovered models the price table doesn't cover. Replaces the old
+ * relative "Nx" multiplier, which was only comparable within a single provider.
+ */
+export function formatModelCost(model: Pick<LlmModelInfo, "isSubscription" | "pricing">): string | undefined {
+ if (model.isSubscription) {
+ return t("llm_chat.model_cost_included");
+ }
+ if (!model.pricing) {
+ return undefined;
+ }
+ return t("llm.model_cost_per_mtok", { input: model.pricing.input, output: model.pricing.output });
+}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 20bdd3e311..aad9378fe6 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3147,6 +3147,7 @@
"models_load_failed": "Could not load models: {{error}}",
"models_none_available": "This provider returned no models.",
"models_selected_count": "{{count}} of {{total}} selected",
+ "model_cost_per_mtok": "${{input}} / ${{output}} per Mtok",
"models_select_all": "Select all",
"models_select_none": "Select none",
"models_reset_defaults": "Reset to defaults",
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx
index cd9266aa10..4a96db9dfd 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx
@@ -39,7 +39,7 @@ const PROVIDERS = [
{ id: "sonnet", name: "Sonnet", isDefault: true, isSubscription: true }
] },
{ id: "a_1", name: "Anthropic", provider: "anthropic", selectedModels: [
- { id: "opus", name: "Opus", costMultiplier: 5 }
+ { id: "opus", name: "Opus", pricing: { input: 3, output: 15 } }
] },
{ id: "o_1", name: "OpenAI", provider: "openai", selectedModels: [
{ id: "mini", name: "Mini" }
@@ -105,8 +105,8 @@ describe("useLlmChat", () => {
const costById = new Map(api().availableModels.map((m) => [m.id, m.costDescription]));
expect(costById.get("sonnet")).toBe("llm_chat.model_cost_included"); // subscription → "included" label
- expect(costById.get("opus")).toBe("5x"); // metered multiplier
- expect(costById.get("mini")).toBeUndefined(); // baseline cost — no annotation
+ expect(costById.get("opus")).toBe("llm.model_cost_per_mtok"); // metered → per-Mtok price label (key echoed by the i18n mock)
+ expect(costById.get("mini")).toBeUndefined(); // unknown pricing — no annotation
});
it("groups models per provider, keeping a provider with no selected models as an empty group", async () => {
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
index a2a58549b8..f3102cbc72 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -2,8 +2,8 @@ import type { LlmCitation, LlmMessage, LlmMessagePart, LlmModelInfo, LlmUsage }
import { RefObject } from "preact";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
-import { t } from "../../../services/i18n.js";
import { streamChatCompletion } from "../../../services/llm_chat.js";
+import { formatModelCost } from "../../../services/llm_model_cost.js";
import options from "../../../services/options.js";
import { randomString } from "../../../services/utils.js";
import { useTriliumEvent } from "../../react/hooks.js";
@@ -975,9 +975,7 @@ function readSelectedModels(): { models: ModelOption[]; groups: ModelProviderGro
provider: config.provider,
providerId: config.id,
providerName: config.name,
- costDescription: model.isSubscription
- ? t("llm_chat.model_cost_included")
- : model.costMultiplier ? `${model.costMultiplier}x` : undefined
+ costDescription: formatModelCost(model)
}))
}));
const models = groups.flatMap(g => g.models);
diff --git a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.spec.tsx b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.spec.tsx
index d9b2a22ae4..d9513bf503 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.spec.tsx
@@ -23,8 +23,8 @@ import ModelSelection from "./ModelSelection";
// `recommended` is set by the server (listProviderModels); the picker only honours it.
const MODELS: LlmModelInfo[] = [
- { id: "gpt-4.1", name: "GPT-4.1", pricing: { input: 2, output: 8 }, isDefault: true, costMultiplier: 1, recommended: true },
- { id: "gpt-4o", name: "GPT-4o", pricing: { input: 2.5, output: 10 }, isLegacy: true, costMultiplier: 1.2, recommended: false },
+ { id: "gpt-4.1", name: "GPT-4.1", pricing: { input: 2, output: 8 }, isDefault: true, recommended: true },
+ { id: "gpt-4o", name: "GPT-4o", pricing: { input: 2.5, output: 10 }, isLegacy: true, recommended: false },
{ id: "custom", name: "Custom", recommended: true }
];
diff --git a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx
index 9ab33c9c0e..cd35448890 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { t } from "../../../../services/i18n";
import { fetchProviderModels, type ProviderModelsQuery } from "../../../../services/llm_chat";
+import { formatModelCost } from "../../../../services/llm_model_cost";
import FormCheckbox from "../../../react/FormCheckbox";
import NoItems from "../../../react/NoItems";
@@ -114,11 +115,9 @@ function defaultSelectedModels(models: LlmModelInfo[]): LlmModelInfo[] {
return models.filter(model => model.recommended);
}
-/** Row label: model name plus curated cost hint when available. */
+/** Row label: model name plus a cost hint (per-Mtok price / subscription) when known. */
function ModelLabel({ model }: { model: LlmModelInfo }) {
- const cost = model.isSubscription
- ? t("llm_chat.model_cost_included")
- : model.costMultiplier ? `${model.costMultiplier}x` : undefined;
+ const cost = formatModelCost(model);
return (
<span className="model-selection-label">
<span className="model-selection-name">{model.name}</span>
diff --git a/apps/server/package.json b/apps/server/package.json
index d28a41fde4..8808c575f7 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -28,6 +28,7 @@
"docker-start-rootless-debian": "pnpm docker-build-rootless-debian && docker run -p 8081:8080 triliumnext-rootless-debian",
"docker-start-rootless-alpine": "pnpm docker-build-rootless-alpine && docker run -p 8081:8080 triliumnext-rootless-alpine",
"generate-document": "cross-env TRILIUM_ENV=dev TRILIUM_DATA_DIR=data TRILIUM_RESOURCE_DIR=src tsx ./scripts/generate_document.ts",
+ "update-model-prices": "tsx ./scripts/update-model-prices.ts",
"proxy-traefik": "docker run --name trilium-traefik --rm --network=host -v ./docker/traefik/traefik.yml:/etc/traefik/traefik.yml:ro -v ./docker/traefik/dynamic:/etc/traefik/dynamic traefik:latest",
"proxy-nginx-subdir": "docker run --name trilium-nginx-subdir --rm --network=host -v ./docker/nginx.conf:/etc/nginx/conf.d/default.conf:ro nginx:latest"
},
diff --git a/apps/server/scripts/update-model-prices.ts b/apps/server/scripts/update-model-prices.ts
new file mode 100644
index 0000000000..3742f8b58f
--- /dev/null
+++ b/apps/server/scripts/update-model-prices.ts
@@ -0,0 +1,132 @@
+/**
+ * Regenerates `src/services/llm/providers/model_prices.json` — the committed,
+ * pruned pricing/context table that is the single source of truth for LLM model
+ * cost metadata (the hand-curated per-provider model arrays were removed).
+ *
+ * Source: LiteLLM's community-maintained `model_prices_and_context_window.json`
+ * (MIT). We keep only the bare, unprefixed ids that Trilium's own `/models`
+ * endpoints return for the three metered providers we support, projected down to
+ * `{ input, output, ctx }` (USD per **million** tokens; LiteLLM stores per-token).
+ *
+ * Not run at build time — the build imports the committed JSON directly and stays
+ * hermetic. This runs on demand (or from the weekly `update-model-prices.yml`
+ * workflow, which opens a PR when the output changes). Usage:
+ *
+ * pnpm --filter server update-model-prices
+ */
+
+import { writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+
+import type { ModelPrice, ModelPriceTable, ProviderPrices } from "../src/services/llm/providers/model_listing.js";
+
+const SOURCE_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
+
+const OUTPUT_PATH = fileURLToPath(
+ new URL("../src/services/llm/providers/model_prices.json", import.meta.url)
+);
+
+/**
+ * Match a LiteLLM entry to one of our provider names by *bare key shape*, not by
+ * its `litellm_provider` tag — the tag is unreliable (Google's bare `gemini-*`
+ * keys, which are exactly what the generativelanguage endpoint returns, are
+ * tagged `vertex_ai-language-models`, while the `gemini`-tagged entries are the
+ * `gemini/…`-prefixed duplicates we don't want). Prefixed keys (`bedrock/…`,
+ * `vertex_ai/…`, `azure/…`) never match our endpoints, so they are excluded.
+ */
+function classify(key: string, provider: string | undefined): string | null {
+ if (key.includes("/")) {
+ return null; // prefixed vendor route — never what our endpoints return
+ }
+ if (/^claude-/.test(key) && provider === "anthropic") {
+ return "anthropic";
+ }
+ if (/^(gpt-|o\d|chatgpt-)/.test(key) && provider === "openai") {
+ return "openai";
+ }
+ if (/^gemini-/.test(key)) {
+ return "google"; // provider tag is unreliable here; key shape is not
+ }
+ return null;
+}
+
+/** LiteLLM stores costs per token; we display per million tokens. */
+const PER_MILLION = 1_000_000;
+
+/** At least this many models per provider, or the upstream file is assumed broken. */
+const SANITY_FLOOR: Record<string, number> = { anthropic: 5, openai: 10, google: 5 };
+
+interface LiteLlmEntry {
+ litellm_provider?: string;
+ mode?: string;
+ input_cost_per_token?: number;
+ output_cost_per_token?: number;
+ max_input_tokens?: number;
+ max_tokens?: number;
+}
+
+async function main() {
+ const response = await fetch(SOURCE_URL);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch LiteLLM price list: HTTP ${response.status}`);
+ }
+ const raw = (await response.json()) as Record<string, LiteLlmEntry>;
+
+ const table: ModelPriceTable = {};
+ for (const [key, entry] of Object.entries(raw)) {
+ if (!entry || typeof entry !== "object" || entry.mode !== "chat") {
+ continue;
+ }
+ const provider = classify(key, entry.litellm_provider);
+ if (!provider) {
+ continue;
+ }
+ const input = entry.input_cost_per_token;
+ if (typeof input !== "number" || input <= 0) {
+ continue; // no meaningful price → skip (leaves the model unpriced, not $0)
+ }
+ const price: ModelPrice = {
+ input: round(input * PER_MILLION),
+ output: round((entry.output_cost_per_token ?? 0) * PER_MILLION)
+ };
+ const ctx = entry.max_input_tokens ?? entry.max_tokens;
+ if (typeof ctx === "number" && ctx > 0) {
+ price.ctx = ctx;
+ }
+ (table[provider] ??= {})[key] = price;
+ }
+
+ for (const [provider, floor] of Object.entries(SANITY_FLOOR)) {
+ const count = Object.keys(table[provider] ?? {}).length;
+ if (count < floor) {
+ throw new Error(`Only ${count} ${provider} models parsed (expected >= ${floor}); refusing to overwrite. Upstream format may have changed.`);
+ }
+ }
+
+ writeFileSync(OUTPUT_PATH, `${JSON.stringify(sortTable(table), null, 2)}\n`);
+ const summary = Object.entries(table).map(([p, m]) => `${p}: ${Object.keys(m).length}`).join(", ");
+ console.log(`Wrote ${OUTPUT_PATH}\n ${summary}`);
+}
+
+/** Round to 4 decimals (sub-cent per-MTok granularity), dropping float noise. */
+function round(value: number): number {
+ return Number(value.toFixed(4));
+}
+
+/** Sort providers and their model ids so refreshes produce minimal, reviewable diffs. */
+function sortTable(table: ModelPriceTable): ModelPriceTable {
+ const sorted: ModelPriceTable = {};
+ for (const provider of Object.keys(table).sort()) {
+ const models: ProviderPrices = {};
+ for (const id of Object.keys(table[provider]).sort()) {
+ models[id] = table[provider][id];
+ }
+ sorted[provider] = models;
+ }
+ return sorted;
+}
+
+main().catch(err => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/apps/server/src/routes/api/llm_chat.spec.ts b/apps/server/src/routes/api/llm_chat.spec.ts
index ce564c0462..ce5ddf9dd8 100644
--- a/apps/server/src/routes/api/llm_chat.spec.ts
+++ b/apps/server/src/routes/api/llm_chat.spec.ts
@@ -15,7 +15,9 @@ const state = vi.hoisted(() => ({
providerIdRequested: undefined as string | undefined,
providerTypeRequested: undefined as string | undefined,
// Records the credentials passed to listProviderModels by the provider-models route.
- providerModelsArgs: undefined as unknown[] | undefined
+ providerModelsArgs: undefined as unknown[] | undefined,
+ // When set, listProviderModels rejects with this (simulates a bad key).
+ providerModelsThrows: undefined as unknown
}));
vi.mock("../../services/llm/index.js", () => {
@@ -32,7 +34,11 @@ vi.mock("../../services/llm/index.js", () => {
});
return {
hasConfiguredProviders: () => state.configured,
- listProviderModels: async (...args: unknown[]) => { state.providerModelsArgs = args; return state.models; },
+ listProviderModels: async (...args: unknown[]) => {
+ state.providerModelsArgs = args;
+ if (state.providerModelsThrows !== undefined) throw state.providerModelsThrows;
+ return state.models;
+ },
getSelectedModel: () => undefined,
getProvider: (id: string) => { state.providerIdRequested = id; return makeProvider(); },
getProviderByType: (type: string) => { state.providerTypeRequested = type; return makeProvider(); }
@@ -87,7 +93,8 @@ describe("LLM chat API", () => {
chunkSignal: undefined,
providerIdRequested: undefined,
providerTypeRequested: undefined,
- providerModelsArgs: undefined
+ providerModelsArgs: undefined,
+ providerModelsThrows: undefined
});
generateChatTitle.mockClear();
});
@@ -105,6 +112,12 @@ describe("LLM chat API", () => {
await expect(llmChatRoute.getProviderModels(req, {} as Response)).rejects.toThrow(/provider is required/);
});
+ it("surfaces a listing failure (e.g. a bad API key) instead of masking it", async () => {
+ state.providerModelsThrows = new Error("Authentication failed (HTTP 401) — check the API key.");
+ const req = { body: { provider: "openai", apiKey: "bad-key" } } as unknown as Request;
+ await expect(llmChatRoute.getProviderModels(req, {} as Response)).rejects.toThrow(/Authentication failed \(HTTP 401\)/);
+ });
+
it("defaults a missing apiKey to an empty string", async () => {
const req = { body: { provider: "claude-agent" } } as unknown as Request;
await llmChatRoute.getProviderModels(req, {} as Response);
diff --git a/apps/server/src/routes/api/llm_chat.ts b/apps/server/src/routes/api/llm_chat.ts
index ab9b1c5995..1bdc1474b3 100644
--- a/apps/server/src/routes/api/llm_chat.ts
+++ b/apps/server/src/routes/api/llm_chat.ts
@@ -1,5 +1,5 @@
import type { LlmMessage, LlmStreamChunk } from "@triliumnext/commons";
-import { getLog } from "@triliumnext/core";
+import { getLog, ValidationError } from "@triliumnext/core";
import type { Request, Response } from "express";
import { generateChatTitle } from "../../services/llm/chat_title.js";
@@ -136,9 +136,16 @@ interface ProviderModelsRequest {
async function getProviderModels(req: Request, _res: Response) {
const { provider, apiKey, baseURL } = req.body as ProviderModelsRequest;
if (!provider) {
- throw new Error("provider is required");
+ throw new ValidationError("provider is required");
+ }
+ try {
+ return { models: await listProviderModels(provider, apiKey ?? "", baseURL) };
+ } catch (error) {
+ // A live-listing failure is almost always a bad credential or an
+ // unreachable endpoint the user just entered — surface it as a 400 so
+ // the model-selection screen shows the reason instead of a generic 500.
+ throw new ValidationError(error instanceof Error ? error.message : String(error));
}
- return { models: await listProviderModels(provider, apiKey ?? "", baseURL) };
}
export default {
diff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.ts
index 486c5eeeef..d11a18b2e6 100644
--- a/apps/server/src/services/llm/index.ts
+++ b/apps/server/src/services/llm/index.ts
@@ -127,8 +127,10 @@ export function hasConfiguredProviders(): boolean {
* List the models available for a provider described by raw credentials —
* used by the model-selection screen during the add/edit flow, where the
* provider config isn't necessarily persisted yet. Instantiates the provider
- * ad-hoc (bypassing the config cache) and queries it live, falling back to its
- * curated list when it doesn't support dynamic listing.
+ * ad-hoc (bypassing the config cache) and queries it live — a listing failure
+ * (bad credentials, unreachable endpoint) propagates so the caller can surface
+ * it — falling back to the curated list only when the provider doesn't support
+ * dynamic listing.
*/
export async function listProviderModels(provider: string, apiKey: string, baseURL?: string): Promise<ModelInfo[]> {
const factory = providerFactories[provider];
diff --git a/apps/server/src/services/llm/providers/anthropic.spec.ts b/apps/server/src/services/llm/providers/anthropic.spec.ts
index 5869b6052a..5d41932d41 100644
--- a/apps/server/src/services/llm/providers/anthropic.spec.ts
+++ b/apps/server/src/services/llm/providers/anthropic.spec.ts
@@ -319,8 +319,11 @@ describe("AnthropicProvider model listing", () => {
})
);
expect(models.map((m) => m.id)).toEqual(["claude-sonnet-5", "claude-omega-6"]);
- // Curated entry keeps its metadata; the unknown one uses the API's display name.
- expect(models[0]).toMatchObject({ isDefault: true, pricing: { input: 3, output: 15 } });
+ // Known model is flagged default and carries price-table pricing (exact
+ // values live in the committed model_prices.json, so only assert presence);
+ // the unknown one uses the API's display name and has no pricing.
+ expect(models[0]).toMatchObject({ isDefault: true });
+ expect(models[0].pricing).toBeDefined();
expect(models[1]).toMatchObject({ name: "Claude Omega 6" });
expect(models[1].pricing).toBeUndefined();
});
@@ -332,10 +335,9 @@ describe("AnthropicProvider model listing", () => {
expect(fetchMock).toHaveBeenCalledWith("https://proxy.example/v1/models?limit=1000", expect.anything());
});
- it("falls back to the curated list when the fetch fails", async () => {
+ it("propagates a failed fetch so the modal can surface it", async () => {
fetchMock.mockRejectedValue(new Error("offline"));
const provider = new AnthropicProvider("sk-ant");
- const models = await provider.listModels();
- expect(models.map((m) => m.id)).toContain("claude-opus-4-8");
+ await expect(provider.listModels()).rejects.toThrow("offline");
});
});
diff --git a/apps/server/src/services/llm/providers/anthropic.ts b/apps/server/src/services/llm/providers/anthropic.ts
index 9598539638..2119634ecd 100644
--- a/apps/server/src/services/llm/providers/anthropic.ts
+++ b/apps/server/src/services/llm/providers/anthropic.ts
@@ -3,7 +3,7 @@ import type { LlmMessage } from "@triliumnext/commons";
import { type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type ToolSet } from "ai";
import type { LlmProviderConfig, StreamResult } from "../types.js";
-import { BaseProvider, buildModelList, buildModelMessage } from "./base_provider.js";
+import { BaseProvider, buildModelMessage } from "./base_provider.js";
import type { RemoteModel } from "./model_listing.js";
const OFFICIAL_BASE_URL = "https://api.anthropic.com/v1";
@@ -20,102 +20,10 @@ const CACHE_CONTROL = { anthropic: { cacheControl: { type: "ephemeral" as const
*/
const ADAPTIVE_THINKING_MODELS = /^claude-(?:opus-4-[678]|sonnet-(?:4-6|5))/;
-/**
- * Available Anthropic models with pricing (USD per million tokens).
- * Source: https://docs.anthropic.com/en/docs/about-claude/models
- */
-const { models: AVAILABLE_MODELS, pricing: MODEL_PRICING } = buildModelList([
- // ===== Current Models =====
- {
- id: "claude-fable-5",
- name: "Claude Fable 5",
- pricing: { input: 10, output: 50 },
- contextWindow: 1000000
- },
- {
- id: "claude-opus-4-8",
- name: "Claude Opus 4.8",
- pricing: { input: 5, output: 25 },
- contextWindow: 1000000
- },
- {
- id: "claude-opus-4-7",
- name: "Claude Opus 4.7",
- pricing: { input: 5, output: 25 },
- contextWindow: 1000000
- },
- {
- id: "claude-sonnet-5",
- name: "Claude Sonnet 5",
- // Standard pricing. Introductory $2/$10 per MTok applies through 2026-08-31.
- pricing: { input: 3, output: 15 },
- contextWindow: 1000000,
- isDefault: true
- },
- {
- id: "claude-haiku-4-5-20251001",
- name: "Claude Haiku 4.5",
- pricing: { input: 1, output: 5 },
- contextWindow: 200000
- },
- // ===== Legacy Models =====
- {
- id: "claude-sonnet-4-6",
- name: "Claude Sonnet 4.6",
- pricing: { input: 3, output: 15 },
- contextWindow: 1000000,
- isLegacy: true
- },
- {
- id: "claude-opus-4-6",
- name: "Claude Opus 4.6",
- pricing: { input: 5, output: 25 },
- contextWindow: 1000000,
- isLegacy: true
- },
- {
- id: "claude-sonnet-4-5-20250929",
- name: "Claude Sonnet 4.5",
- pricing: { input: 3, output: 15 },
- contextWindow: 200000,
- isLegacy: true
- },
- {
- id: "claude-opus-4-5-20251101",
- name: "Claude Opus 4.5",
- pricing: { input: 5, output: 25 },
- contextWindow: 200000,
- isLegacy: true
- },
- {
- id: "claude-opus-4-1-20250805",
- name: "Claude Opus 4.1",
- pricing: { input: 15, output: 75 },
- contextWindow: 200000,
- isLegacy: true
- },
- {
- id: "claude-sonnet-4-20250514",
- name: "Claude Sonnet 4.0",
- pricing: { input: 3, output: 15 },
- contextWindow: 200000,
- isLegacy: true
- },
- {
- id: "claude-opus-4-20250514",
- name: "Claude Opus 4.0",
- pricing: { input: 15, output: 75 },
- contextWindow: 200000,
- isLegacy: true
- }
-]);
-
export class AnthropicProvider extends BaseProvider {
name = "anthropic";
protected defaultModel = "claude-sonnet-5";
protected titleModel = "claude-haiku-4-5-20251001";
- protected availableModels = AVAILABLE_MODELS;
- protected modelPricing = MODEL_PRICING;
private anthropic: AnthropicSDKProvider;
diff --git a/apps/server/src/services/llm/providers/base_provider.spec.ts b/apps/server/src/services/llm/providers/base_provider.spec.ts
index 563ea0878c..1a849177ad 100644
--- a/apps/server/src/services/llm/providers/base_provider.spec.ts
+++ b/apps/server/src/services/llm/providers/base_provider.spec.ts
@@ -44,7 +44,7 @@ vi.mock("../tools/index.js", () => ({
}));
import { BaseProvider, buildModelList, buildModelMessage } from "./base_provider.js";
-import type { RemoteModel } from "./model_listing.js";
+import type { ProviderPrices, RemoteModel } from "./model_listing.js";
const TEST_MODELS: Parameters<typeof buildModelList>[0] = [
{ id: "cheap", name: "Cheap", pricing: { input: 1, output: 2 } },
@@ -52,14 +52,22 @@ const TEST_MODELS: Parameters<typeof buildModelList>[0] = [
{ id: "spendy", name: "Spendy", pricing: { input: 10, output: 30 } }
];
-const { models: BUILT_MODELS, pricing: BUILT_PRICING } = buildModelList(TEST_MODELS);
+const { pricing: BUILT_PRICING } = buildModelList(TEST_MODELS);
+
+/** Injected price-table slice — the base class reads this instead of the JSON file. */
+const TEST_PRICES: ProviderPrices = {
+ cheap: { input: 1, output: 2 },
+ mid: { input: 2, output: 4, ctx: 1000 },
+ spendy: { input: 10, output: 30 }
+};
class TestProvider extends BaseProvider {
name = "test";
protected defaultModel = "mid";
protected titleModel = "cheap";
- protected availableModels = BUILT_MODELS;
- protected modelPricing = BUILT_PRICING;
+ protected override getProviderPrices(): ProviderPrices {
+ return TEST_PRICES;
+ }
public createdModelIds: string[] = [];
public fetchRemoteModelsMock = vi.fn<() => Promise<RemoteModel[] | null>>(async () => null);
@@ -94,25 +102,6 @@ function makeAttachment(over: Partial<Record<string, unknown>> = {}) {
}
describe("buildModelList", () => {
- it("derives cost multipliers relative to the default (baseline) model", () => {
- // Baseline = mid: effective = (2 + 3*4)/4 = 3.5
- const byId = Object.fromEntries(BUILT_MODELS.map((m) => [m.id, m]));
- expect(byId.mid.costMultiplier).toBe(1);
- // cheap: (1 + 3*2)/4 = 1.75 → 1.75/3.5 = 0.5
- expect(byId.cheap.costMultiplier).toBe(0.5);
- // spendy: (10 + 3*30)/4 = 25 → 25/3.5 = 7.14 → rounded to 7.1
- expect(byId.spendy.costMultiplier).toBe(7.1);
- });
-
- it("falls back to the first model as baseline when none is marked default", () => {
- const { models } = buildModelList([
- { id: "a", name: "A", pricing: { input: 2, output: 4 } },
- { id: "b", name: "B", pricing: { input: 4, output: 8 } }
- ]);
- expect(models[0].costMultiplier).toBe(1);
- expect(models[1].costMultiplier).toBe(2);
- });
-
it("maps each model id to its pricing", () => {
expect(BUILT_PRICING).toMatchObject({
cheap: { input: 1, output: 2 },
@@ -122,19 +111,37 @@ describe("buildModelList", () => {
});
});
-describe("listModels", () => {
- it("returns the curated list when the provider has no dynamic listing", async () => {
+describe("getAvailableModels / getModelPricing (from the price table)", () => {
+ it("builds the model list from the price table, sorted, with the default flagged", () => {
+ const models = new TestProvider().getAvailableModels();
+ expect(models.map((m) => m.id)).toEqual(["cheap", "mid", "spendy"]);
+ expect(models[1]).toMatchObject({ id: "mid", pricing: { input: 2, output: 4 }, contextWindow: 1000, isDefault: true });
+ // Non-default models carry no isDefault flag.
+ expect(models[0].isDefault).toBeUndefined();
+ });
+
+ it("looks pricing up by model id, undefined for unknown", () => {
const provider = new TestProvider();
- await expect(provider.listModels()).resolves.toBe(BUILT_MODELS);
+ expect(provider.getModelPricing("spendy")).toEqual({ input: 10, output: 30 });
+ expect(provider.getModelPricing("nope")).toBeUndefined();
});
+});
- it("merges the remote list with curated metadata and caches the result", async () => {
+describe("listModels", () => {
+ it("returns the price-table list when the provider has no dynamic listing", async () => {
+ const models = await new TestProvider().listModels();
+ expect(models.map((m) => m.id)).toEqual(["cheap", "mid", "spendy"]);
+ });
+
+ it("merges the remote list with price-table metadata and caches the result", async () => {
const provider = new TestProvider();
provider.fetchRemoteModelsMock.mockResolvedValue([{ id: "mid" }, { id: "brand-new" }]);
const models = await provider.listModels();
expect(models.map((m) => m.id)).toEqual(["mid", "brand-new"]);
- expect(models[0]).toMatchObject({ name: "Mid", isDefault: true });
+ // Known model keeps its price-table pricing + default flag...
+ expect(models[0]).toMatchObject({ id: "mid", pricing: { input: 2, output: 4 }, isDefault: true });
+ // ...unknown one has no pricing.
expect(models[1].pricing).toBeUndefined();
// Second call is served from the cache — no second fetch.
@@ -151,20 +158,16 @@ describe("listModels", () => {
expect(provider.fetchRemoteModelsMock).toHaveBeenCalledTimes(1);
});
- it("falls back to the curated list on fetch failure and cools down before retrying", async () => {
+ it("propagates a fetch failure (e.g. a bad API key) so the add/edit modal can surface it", async () => {
const provider = new TestProvider();
- provider.fetchRemoteModelsMock.mockRejectedValue(new Error("boom"));
-
- await expect(provider.listModels()).resolves.toBe(BUILT_MODELS);
- // Within the failure cooldown the endpoint is not probed again.
- await expect(provider.listModels()).resolves.toBe(BUILT_MODELS);
- expect(provider.fetchRemoteModelsMock).toHaveBeenCalledTimes(1);
+ provider.fetchRemoteModelsMock.mockRejectedValue(new Error("HTTP 401"));
+ await expect(provider.listModels()).rejects.toThrow("HTTP 401");
});
- it("falls back to the curated list when the remote list is empty", async () => {
+ it("falls back to the price-table list when the remote list is empty", async () => {
const provider = new TestProvider();
provider.fetchRemoteModelsMock.mockResolvedValue([]);
- await expect(provider.listModels()).resolves.toBe(BUILT_MODELS);
+ expect((await provider.listModels()).map((m) => m.id)).toEqual(["cheap", "mid", "spendy"]);
});
});
@@ -427,17 +430,6 @@ describe("BaseProvider chat / pricing / models / title", () => {
expect(provider2.createdModelIds).toContain("spendy");
});
- it("getModelPricing returns known pricing and undefined for unknown models", () => {
- const provider = new TestProvider();
- expect(provider.getModelPricing("mid")).toEqual({ input: 2, output: 4 });
- expect(provider.getModelPricing("nope")).toBeUndefined();
- });
-
- it("getAvailableModels returns the configured model list", () => {
- const provider = new TestProvider();
- expect(provider.getAvailableModels().map((m) => m.id)).toEqual(["cheap", "mid", "spendy"]);
- });
-
it("generateTitle uses the title model and trims the result", async () => {
const provider = new TestProvider();
const title = await provider.generateTitle("Some long first message");
diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.ts
index 6f00667d7c..c58f4621d1 100644
--- a/apps/server/src/services/llm/providers/base_provider.ts
+++ b/apps/server/src/services/llm/providers/base_provider.ts
@@ -4,34 +4,31 @@
*/
import { type LlmMessage, type LlmMessagePart } from "@triliumnext/commons";
-import { getLog } from "@triliumnext/core";
import { type FilePart, generateText, type ImagePart, type LanguageModel, type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type TextPart, type ToolSet } from "ai";
import { allToolRegistries } from "../tools/index.js";
import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";
import { resolveAttachmentPart } from "./attachment_content.js";
-import { mergeModelLists, type RemoteModel } from "./model_listing.js";
+import { mergeModelLists, type ModelPriceTable, type ProviderPrices, type RemoteModel } from "./model_listing.js";
+import MODEL_PRICES_JSON from "./model_prices.json" with { type: "json" };
import { buildNoteHint } from "./note_hint.js";
import { buildSystemPrompt as composeSystemPrompt } from "./system_prompt.js";
const DEFAULT_MAX_TOKENS = 8096;
const TITLE_MAX_TOKENS = 30;
+/**
+ * The committed pricing/context table — the single source of truth for cost
+ * metadata now that per-provider model arrays are gone. Keyed by provider name
+ * then model id; regenerated from LiteLLM by `scripts/update-model-prices.ts`.
+ */
+const MODEL_PRICES = MODEL_PRICES_JSON as ModelPriceTable;
+
/** How long a successfully fetched dynamic model list is served from cache. */
const MODEL_LIST_TTL_MS = 60 * 60 * 1000;
-/** After a failed fetch, don't retry for this long — avoids re-stalling the UI on a dead endpoint. */
-const MODEL_LIST_FAILURE_COOLDOWN_MS = 60 * 1000;
/** Timeout for a single models-endpoint request. */
const MODEL_LIST_TIMEOUT_MS = 10_000;
-/**
- * Calculate effective cost for comparison (weighted average: 1 input + 3 output).
- * Output is weighted more heavily as it's typically the dominant cost factor.
- */
-function effectiveCost(pricing: ModelPricing): number {
- return (pricing.input + 3 * pricing.output) / 4;
-}
-
/**
* Resolve a single LlmMessagePart to its AI SDK ModelMessage part form, mapping
* the provider-neutral {@link resolveAttachmentPart} result into `ai`'s block
@@ -74,31 +71,22 @@ export function buildModelMessage(m: LlmMessage): ModelMessage {
}
/**
- * A curated (hard-coded) model definition. Unlike dynamically discovered
- * models, curated entries always carry pricing.
+ * A hard-coded model definition that always carries pricing. Used only by the
+ * Claude Agent (subscription) provider, whose fixed catalog and zero pricing
+ * come from the CLI rather than the metered LiteLLM price table.
*/
-type CuratedModel = Omit<ModelInfo, "costMultiplier"> & { pricing: ModelPricing };
+type CuratedModel = ModelInfo & { pricing: ModelPricing };
/**
- * Build the model list with cost multipliers from a base model definition array.
+ * Split a curated model array into the `{ models, pricing }` pair the subscription
+ * provider needs (the model list plus an id → pricing lookup).
*/
export function buildModelList(baseModels: CuratedModel[]): {
models: ModelInfo[];
pricing: Record<string, ModelPricing>;
} {
- const baselineModel = baseModels.find(m => m.isDefault) || baseModels[0];
- const baselineCost = effectiveCost(baselineModel.pricing);
-
- const models = baseModels.map(m => ({
- ...m,
- costMultiplier: Math.round((effectiveCost(m.pricing) / baselineCost) * 10) / 10
- }));
-
- const pricing = Object.fromEntries(
- models.map(m => [m.id, m.pricing])
- );
-
- return { models, pricing };
+ const pricing = Object.fromEntries(baseModels.map(m => [m.id, m.pricing]));
+ return { models: baseModels, pricing };
}
export abstract class BaseProvider implements LlmProvider {
@@ -106,8 +94,6 @@ export abstract class BaseProvider implements LlmProvider {
protected abstract defaultModel: string;
protected abstract titleModel: string;
- protected abstract availableModels: ModelInfo[];
- protected abstract modelPricing: Record<string, ModelPricing>;
protected apiKey: string;
/** Custom endpoint override (self-hosted Ollama/vLLM, proxies). Normalized without a trailing slash. */
@@ -115,7 +101,6 @@ export abstract class BaseProvider implements LlmProvider {
private modelListCache?: { models: ModelInfo[]; fetchedAt: number };
private modelListInFlight?: Promise<ModelInfo[]>;
- private modelListFailedAt?: number;
constructor(apiKey = "", baseURL?: string) {
this.apiKey = apiKey;
@@ -128,7 +113,7 @@ export abstract class BaseProvider implements LlmProvider {
/**
* Fetch the raw model list from the provider's models endpoint. Returns
* null when the provider doesn't support dynamic listing. Overridden by
- * providers that do; errors are handled by {@link listModels}.
+ * providers that do; a fetch failure propagates to {@link listModels}' caller.
*/
protected async fetchRemoteModels(): Promise<RemoteModel[] | null> {
return null;
@@ -136,11 +121,16 @@ export abstract class BaseProvider implements LlmProvider {
/**
* GET a JSON document with the standard model-listing timeout. Shared
- * helper for {@link fetchRemoteModels} implementations.
+ * helper for {@link fetchRemoteModels} implementations. An auth failure is
+ * reported as such so the add/edit-provider screen can tell the user their
+ * API key (or base URL) is wrong rather than a generic HTTP error.
*/
protected async fetchJson(url: string, headers: Record<string, string>): Promise<unknown> {
const response = await fetch(url, { headers, signal: AbortSignal.timeout(MODEL_LIST_TIMEOUT_MS) });
if (!response.ok) {
+ if (response.status === 401 || response.status === 403) {
+ throw new Error(`Authentication failed (HTTP ${response.status}) — check the API key${this.baseURL ? " and base URL" : ""}.`);
+ }
throw new Error(`HTTP ${response.status} from ${url}`);
}
return await response.json();
@@ -148,18 +138,17 @@ export abstract class BaseProvider implements LlmProvider {
/**
* Dynamic model listing: the live endpoint list merged with curated
- * metadata, cached for {@link MODEL_LIST_TTL_MS}. Falls back to the curated
- * list when the provider doesn't support listing or the fetch fails (with a
- * cooldown so a dead endpoint isn't re-probed on every dropdown open).
+ * metadata, cached for {@link MODEL_LIST_TTL_MS}. Returns the curated list
+ * when the provider doesn't support dynamic listing, but a listing *failure*
+ * (bad API key, unreachable endpoint) propagates — the sole caller is the
+ * add/edit-provider screen, which must surface a bad credential instead of
+ * masking it as success by quietly showing the curated defaults.
*/
async listModels(): Promise<ModelInfo[]> {
const now = Date.now();
if (this.modelListCache && now - this.modelListCache.fetchedAt < MODEL_LIST_TTL_MS) {
return this.modelListCache.models;
}
- if (this.modelListFailedAt && now - this.modelListFailedAt < MODEL_LIST_FAILURE_COOLDOWN_MS) {
- return this.availableModels;
- }
if (!this.modelListInFlight) {
this.modelListInFlight = this.fetchAndMergeModels().finally(() => {
this.modelListInFlight = undefined;
@@ -169,20 +158,15 @@ export abstract class BaseProvider implements LlmProvider {
}
private async fetchAndMergeModels(): Promise<ModelInfo[]> {
- try {
- const remote = await this.fetchRemoteModels();
- if (!remote || remote.length === 0) {
- return this.availableModels;
- }
- const merged = mergeModelLists(this.availableModels, remote);
- this.modelListCache = { models: merged, fetchedAt: Date.now() };
- this.modelListFailedAt = undefined;
- return merged;
- } catch (e) {
- this.modelListFailedAt = Date.now();
- getLog().info(`Dynamic model listing failed for provider ${this.name}, falling back to the curated list: ${e}`);
- return this.availableModels;
+ const remote = await this.fetchRemoteModels();
+ if (!remote || remote.length === 0) {
+ // The provider doesn't support dynamic listing, or the endpoint
+ // returned nothing — the price-table catalog is the answer, not an error.
+ return this.getAvailableModels();
}
+ const merged = mergeModelLists(this.getAvailableModels(), remote);
+ this.modelListCache = { models: merged, fetchedAt: Date.now() };
+ return merged;
}
/**
@@ -308,12 +292,43 @@ export abstract class BaseProvider implements LlmProvider {
return streamText(streamOptions);
}
+ /**
+ * This provider's slice of the committed price table. Overridable so tests
+ * can inject a table without a real JSON file.
+ */
+ protected getProviderPrices(): ProviderPrices {
+ return MODEL_PRICES[this.name] ?? {};
+ }
+
+ /**
+ * Friendly display name for a model id when the endpoint doesn't supply one
+ * (offline fallback / OpenAI, whose `/models` has no names). Defaults to the
+ * raw id; overridden per provider.
+ */
+ protected modelName(id: string): string {
+ return id;
+ }
+
getModelPricing(model: string): ModelPricing | undefined {
- return this.modelPricing[model];
+ const price = this.getProviderPrices()[model];
+ return price ? { input: price.input, output: price.output } : undefined;
}
+ /**
+ * The static, offline-safe model list, built from the price table. Also the
+ * base list {@link listModels} merges the live endpoint against. The model
+ * matching {@link defaultModel} is flagged so `find(m => m.isDefault)` works.
+ */
getAvailableModels(): ModelInfo[] {
- return this.availableModels;
+ return Object.entries(this.getProviderPrices())
+ .map(([id, price]) => ({
+ id,
+ name: this.modelName(id),
+ pricing: { input: price.input, output: price.output },
+ contextWindow: price.ctx,
+ ...(id === this.defaultModel ? { isDefault: true } : {})
+ }))
+ .sort((a, b) => a.id.localeCompare(b.id));
}
async generateTitle(firstMessage: string): Promise<string> {
diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.ts
index 5476edd74c..1694697de3 100644
--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts
@@ -875,9 +875,9 @@ describe("transcript helpers", () => {
describe("buildSubscriptionModelList", () => {
const curated = [
- { id: "claude-sonnet-5", name: "Claude Sonnet 5", pricing: { input: 0, output: 0 }, contextWindow: 1000000, isDefault: true, isSubscription: true, costMultiplier: 1 },
- { id: "claude-opus-4-6", name: "Claude Opus 4.6", pricing: { input: 0, output: 0 }, contextWindow: 1000000, isLegacy: true, isSubscription: true, costMultiplier: 1 },
- { id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5", pricing: { input: 0, output: 0 }, contextWindow: 200000, isSubscription: true, costMultiplier: 1 }
+ { id: "claude-sonnet-5", name: "Claude Sonnet 5", pricing: { input: 0, output: 0 }, contextWindow: 1000000, isDefault: true, isSubscription: true },
+ { id: "claude-opus-4-6", name: "Claude Opus 4.6", pricing: { input: 0, output: 0 }, contextWindow: 1000000, isLegacy: true, isSubscription: true },
+ { id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5", pricing: { input: 0, output: 0 }, contextWindow: 200000, isSubscription: true }
];
it("resolves aliases to canonical ids, dedupes, and keeps curated metadata", () => {
@@ -888,8 +888,8 @@ describe("buildSubscriptionModelList", () => {
], curated);
expect(merged.map(m => m.id)).toEqual(["claude-sonnet-5", "claude-opus-4-6"]);
- // Curated name wins over the CLI's display name; flags/context window survive.
- expect(merged[0]).toMatchObject({ name: "Claude Sonnet 5", isDefault: true, isSubscription: true, contextWindow: 1000000, pricing: { input: 0, output: 0 } });
+ // The CLI's display name wins; curated flags/context window survive.
+ expect(merged[0]).toMatchObject({ name: "Sonnet 5", isDefault: true, isSubscription: true, contextWindow: 1000000, pricing: { input: 0, output: 0 } });
expect(merged[1]).toMatchObject({ id: "claude-opus-4-6", isLegacy: true });
// Haiku is curated but absent from the live catalog → dropped.
expect(merged.some(m => m.id === "claude-haiku-4-5-20251001")).toBe(false);
@@ -951,24 +951,19 @@ describe("ClaudeAgentProvider.listModels", () => {
expect(queryMock).toHaveBeenCalledTimes(1);
});
- it("falls back to the curated list when the probe fails, then honors the cooldown", async () => {
+ it("propagates the probe failure so the modal can surface it (e.g. not authenticated)", async () => {
scriptSupportedModels(async () => {
throw new Error("Claude Code is not authenticated");
});
const provider = new ClaudeAgentProvider();
-
- const models = await provider.listModels();
- expect(models).toBe(provider.getAvailableModels());
- // Cooldown: the immediate retry returns curated without re-probing.
- expect(await provider.listModels()).toBe(provider.getAvailableModels());
- expect(queryMock).toHaveBeenCalledTimes(1);
+ await expect(provider.listModels()).rejects.toThrow("not authenticated");
});
- it("falls back to the curated list when Claude Code isn't installed (no probe spawned)", async () => {
+ it("propagates when Claude Code isn't installed, without spawning a probe", async () => {
resolveClaudeBinaryMock.mockRejectedValueOnce(new Error("Claude Code CLI not found"));
const provider = new ClaudeAgentProvider();
- expect(await provider.listModels()).toBe(provider.getAvailableModels());
+ await expect(provider.listModels()).rejects.toThrow("not found");
expect(queryMock).not.toHaveBeenCalled();
});
});
diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.ts
index 8c9213656e..74672136b2 100644
--- a/apps/server/src/services/llm/providers/claude_agent.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.ts
@@ -136,8 +136,6 @@ const MAX_TURNS = 25;
/** How long a successfully probed subscription model list is served from cache. */
const SUBSCRIPTION_MODEL_TTL_MS = 60 * 60 * 1000;
-/** After a failed probe, don't re-spawn Claude Code for this long. */
-const SUBSCRIPTION_MODEL_FAILURE_COOLDOWN_MS = 60 * 1000;
/** Upper bound on how long the init handshake may take to surface the catalog. */
const SUBSCRIPTION_MODEL_PROBE_TIMEOUT_MS = 15_000;
@@ -149,7 +147,6 @@ const SUBSCRIPTION_MODEL_PROBE_TIMEOUT_MS = 15_000;
* correct and avoids re-spawning the CLI subprocess on each dropdown open.
*/
let subscriptionModelCache: { models: ModelInfo[]; fetchedAt: number } | undefined;
-let subscriptionModelFailedAt: number | undefined;
let subscriptionModelInFlight: Promise<ModelInfo[]> | undefined;
/** Session mappings kept per chat note; bounded to avoid unbounded growth. */
@@ -199,18 +196,17 @@ export class ClaudeAgentProvider implements LlmProvider {
* the logged-in account (tier, version, any managed `availableModels`
* allowlist), which the Agent SDK hands over via the `initialize` handshake.
*
- * Cached for {@link SUBSCRIPTION_MODEL_TTL_MS}; falls back to the curated
- * list (with a cooldown) when Claude Code isn't installed, isn't logged in,
- * or the probe otherwise fails.
+ * Cached for {@link SUBSCRIPTION_MODEL_TTL_MS}. A probe *failure* (Claude
+ * Code not installed, not logged in, or timed out) propagates so the
+ * add/edit-provider screen surfaces an actionable error rather than masking
+ * it as success with the curated defaults. The curated list stays available
+ * via {@link getAvailableModels} as the static catalog used elsewhere.
*/
async listModels(): Promise<ModelInfo[]> {
const now = Date.now();
if (subscriptionModelCache && now - subscriptionModelCache.fetchedAt < SUBSCRIPTION_MODEL_TTL_MS) {
return subscriptionModelCache.models;
}
- if (subscriptionModelFailedAt && now - subscriptionModelFailedAt < SUBSCRIPTION_MODEL_FAILURE_COOLDOWN_MS) {
- return AVAILABLE_MODELS;
- }
if (!subscriptionModelInFlight) {
subscriptionModelInFlight = this.fetchAndMergeModels().finally(() => {
subscriptionModelInFlight = undefined;
@@ -220,16 +216,17 @@ export class ClaudeAgentProvider implements LlmProvider {
}
private async fetchAndMergeModels(): Promise<ModelInfo[]> {
+ let sdkModels: SubscriptionModelSource[];
try {
- const merged = buildSubscriptionModelList(await this.probeSupportedModels(), AVAILABLE_MODELS);
- subscriptionModelCache = { models: merged, fetchedAt: Date.now() };
- subscriptionModelFailedAt = undefined;
- return merged;
+ sdkModels = await this.probeSupportedModels();
} catch (error) {
- subscriptionModelFailedAt = Date.now();
- getLog().info(`Dynamic model listing failed for the Claude subscription provider, falling back to the curated list: ${describeAgentError(error)}`);
- return AVAILABLE_MODELS;
+ // Report why the probe failed (missing binary, not logged in, timeout)
+ // so the caller can show an actionable message.
+ throw new Error(describeAgentError(error));
}
+ const merged = buildSubscriptionModelList(sdkModels, AVAILABLE_MODELS);
+ subscriptionModelCache = { models: merged, fetchedAt: Date.now() };
+ return merged;
}
/**
@@ -657,10 +654,9 @@ export function resetAgentCwdForTests(): void {
agentCwd = undefined;
}
-/** For tests: forget the cached/failed dynamic model list so the next call re-probes. */
+/** For tests: forget the cached dynamic model list so the next call re-probes. */
export function resetSubscriptionModelCacheForTests(): void {
subscriptionModelCache = undefined;
- subscriptionModelFailedAt = undefined;
subscriptionModelInFlight = undefined;
}
@@ -680,10 +676,11 @@ interface SubscriptionModelSource {
* The canonical wire id (`resolvedModel`) is preferred over the picker alias
* (`value`) so a chat stores a stable, concrete model id that matches the
* metered Anthropic provider's ids; aliases resolving to the same model are
- * deduped. Curated entries supply names, context windows and the legacy flag
- * for models they know; unknown models come through with whatever the CLI
- * reported. Every row is a subscription model, so the plan-covered invariants
- * (zero pricing, no metered cost) are re-asserted across the merged list.
+ * deduped. The CLI's display name wins; curated entries supply the context
+ * window and legacy flag for models they know, and unknown models come through
+ * with whatever the CLI reported. Every row is a subscription model, so the
+ * plan-covered invariants (zero pricing, no metered cost) are re-asserted
+ * across the merged list.
*/
export function buildSubscriptionModelList(sdkModels: SubscriptionModelSource[], curated: ModelInfo[]): ModelInfo[] {
const remote: RemoteModel[] = [];
diff --git a/apps/server/src/services/llm/providers/google.spec.ts b/apps/server/src/services/llm/providers/google.spec.ts
index 614ec073a8..f448283e5e 100644
--- a/apps/server/src/services/llm/providers/google.spec.ts
+++ b/apps/server/src/services/llm/providers/google.spec.ts
@@ -206,10 +206,9 @@ describe("GoogleProvider model listing", () => {
expect(models[1]).toMatchObject({ name: "Gemini 3 Pro", contextWindow: 2097152 });
});
- it("falls back to the curated list when the fetch fails", async () => {
+ it("propagates a failed fetch as an authentication error the modal can surface", async () => {
fetchMock.mockResolvedValue({ ok: false, status: 403 });
const provider = new GoogleProvider("g-key");
- const models = await provider.listModels();
- expect(models.map((m) => m.id)).toContain("gemini-2.5-pro");
+ await expect(provider.listModels()).rejects.toThrow(/Authentication failed/);
});
});
diff --git a/apps/server/src/services/llm/providers/google.ts b/apps/server/src/services/llm/providers/google.ts
index 61f1f0985c..708c23d2cc 100644
--- a/apps/server/src/services/llm/providers/google.ts
+++ b/apps/server/src/services/llm/providers/google.ts
@@ -4,7 +4,7 @@ import { getLog } from "@triliumnext/core";
import { stepCountIs, streamText, type ToolSet } from "ai";
import type { LlmProviderConfig, StreamResult } from "../types.js";
-import { BaseProvider, buildModelList } from "./base_provider.js";
+import { BaseProvider } from "./base_provider.js";
import { isGoogleChatModel, type RemoteModel } from "./model_listing.js";
const OFFICIAL_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
@@ -21,46 +21,10 @@ function geminiHasToolConflict(config: LlmProviderConfig): boolean {
return !!(config.enableWebSearch && config.enableNoteTools);
}
-/**
- * Available Google Gemini models with pricing (USD per million tokens).
- * Source: https://ai.google.dev/gemini-api/docs/pricing
- */
-const { models: AVAILABLE_MODELS, pricing: MODEL_PRICING } = buildModelList([
- // ===== Current Models =====
- {
- id: "gemini-2.5-pro",
- name: "Gemini 2.5 Pro",
- pricing: { input: 1.25, output: 10 },
- contextWindow: 1048576
- },
- {
- id: "gemini-2.5-flash",
- name: "Gemini 2.5 Flash",
- pricing: { input: 0.3, output: 2.5 },
- contextWindow: 1048576,
- isDefault: true
- },
- {
- id: "gemini-2.5-flash-lite",
- name: "Gemini 2.5 Flash-Lite",
- pricing: { input: 0.1, output: 0.4 },
- contextWindow: 1048576
- },
- {
- id: "gemini-2.0-flash",
- name: "Gemini 2.0 Flash",
- pricing: { input: 0.1, output: 0.4 },
- contextWindow: 1048576,
- isLegacy: true
- }
-]);
-
export class GoogleProvider extends BaseProvider {
name = "google";
protected defaultModel = "gemini-2.5-flash";
protected titleModel = "gemini-2.5-flash-lite";
- protected availableModels = AVAILABLE_MODELS;
- protected modelPricing = MODEL_PRICING;
private google: GoogleGenerativeAIProvider;
diff --git a/apps/server/src/services/llm/providers/model_listing.spec.ts b/apps/server/src/services/llm/providers/model_listing.spec.ts
index 72dee0497e..304ce4e140 100644
--- a/apps/server/src/services/llm/providers/model_listing.spec.ts
+++ b/apps/server/src/services/llm/providers/model_listing.spec.ts
@@ -4,13 +4,13 @@ import type { ModelInfo } from "../types.js";
import { isGoogleChatModel, isOpenAiChatModel, mergeModelLists, openAiModelName, recommendedModelIds } from "./model_listing.js";
const CURATED: ModelInfo[] = [
- { id: "gpt-4.1", name: "GPT-4.1", pricing: { input: 2, output: 8 }, contextWindow: 1047576, isDefault: true, costMultiplier: 1 },
- { id: "gpt-4.1-mini", name: "GPT-4.1 Mini", pricing: { input: 0.4, output: 1.6 }, contextWindow: 1047576, costMultiplier: 0.2 },
- { id: "gpt-4o", name: "GPT-4o", pricing: { input: 2.5, output: 10 }, contextWindow: 128000, isLegacy: true, costMultiplier: 1.2 }
+ { id: "gpt-4.1", name: "GPT-4.1", pricing: { input: 2, output: 8 }, contextWindow: 1047576, isDefault: true },
+ { id: "gpt-4.1-mini", name: "GPT-4.1 Mini", pricing: { input: 0.4, output: 1.6 }, contextWindow: 1047576 },
+ { id: "gpt-4o", name: "GPT-4o", pricing: { input: 2.5, output: 10 }, contextWindow: 128000, isLegacy: true }
];
describe("mergeModelLists", () => {
- it("keeps curated metadata for known models and appends unknown ones alphabetically", () => {
+ it("keeps base metadata for known models and appends unknown ones alphabetically", () => {
const merged = mergeModelLists(CURATED, [
{ id: "gpt-9" },
{ id: "gpt-4.1-mini" },
@@ -18,12 +18,20 @@ describe("mergeModelLists", () => {
{ id: "gpt-4.1" }
]);
expect(merged.map(m => m.id)).toEqual(["gpt-4.1", "gpt-4.1-mini", "gpt-5", "gpt-9"]);
- // Curated entries keep their full metadata...
- expect(merged[0]).toMatchObject({ name: "GPT-4.1", pricing: { input: 2, output: 8 }, isDefault: true, costMultiplier: 1 });
- // ...unknown ones carry no pricing/cost badge data.
+ // Base entries keep their pricing/default metadata...
+ expect(merged[0]).toMatchObject({ name: "GPT-4.1", pricing: { input: 2, output: 8 }, isDefault: true });
+ // ...unknown ones carry no pricing.
expect(merged[2]).toEqual({ id: "gpt-5", name: "gpt-5", contextWindow: undefined });
});
+ it("prefers the endpoint's display name over the base list's for known models", () => {
+ const merged = mergeModelLists(
+ [{ id: "gpt-4.1", name: "gpt-4.1", pricing: { input: 2, output: 8 } }],
+ [{ id: "gpt-4.1", name: "GPT-4.1 (from endpoint)" }]
+ );
+ expect(merged[0].name).toBe("GPT-4.1 (from endpoint)");
+ });
+
it("drops curated models absent from the remote list", () => {
const merged = mergeModelLists(CURATED, [{ id: "gpt-4.1" }]);
expect(merged.map(m => m.id)).toEqual(["gpt-4.1"]);
diff --git a/apps/server/src/services/llm/providers/model_listing.ts b/apps/server/src/services/llm/providers/model_listing.ts
index 1f6becf69c..37e82899d9 100644
--- a/apps/server/src/services/llm/providers/model_listing.ts
+++ b/apps/server/src/services/llm/providers/model_listing.ts
@@ -20,18 +20,42 @@ export interface RemoteModel {
}
/**
- * Merge a live-fetched model list with the curated metadata list.
+ * Per-model pricing/metadata, sourced from the committed `model_prices.json`
+ * (pruned from LiteLLM — see `scripts/update-model-prices.ts`). This is the
+ * single source of truth for cost/context data now that the hand-curated
+ * per-provider model arrays are gone; the endpoint (dynamic listing) remains the
+ * source of truth for which models exist and their display names.
+ */
+export interface ModelPrice {
+ /** USD per million input tokens. */
+ input: number;
+ /** USD per million output tokens. */
+ output: number;
+ /** Context window in tokens, when known. */
+ ctx?: number;
+}
+
+/** One provider's pricing, keyed by model id. */
+export type ProviderPrices = Record<string, ModelPrice>;
+
+/** The whole committed price table: provider name → model id → pricing. */
+export type ModelPriceTable = Record<string, ProviderPrices>;
+
+/**
+ * Merge a live-fetched model list with a base metadata list (the provider's
+ * price-table slice, see {@link BaseProvider.getAvailableModels}).
*
- * The remote list is the source of truth for *availability*: curated models
- * absent from it are dropped, remote models unknown to the curated list are
- * included with whatever metadata the endpoint reported (no pricing, no cost
- * multiplier). Curated entries supply name, pricing, context window and the
- * legacy flag for models they know.
+ * The remote list is the source of truth for *availability* and *display name*:
+ * base entries absent from it are dropped, remote models unknown to the base
+ * list are included with whatever metadata the endpoint reported (no pricing).
+ * The base list supplies pricing and context window (and, offline, a fallback
+ * name) for the models it knows; the endpoint's display name always wins when
+ * present.
*
- * Ordering: curated-known models first (in curated order), then unknown remote
- * models alphabetically. The curated default keeps its flag when present;
- * otherwise the first merged model becomes the default so callers relying on
- * `find(m => m.isDefault)` keep working.
+ * Ordering: base-known models first (in base order), then unknown remote models
+ * alphabetically. An existing default keeps its flag; otherwise the first merged
+ * model becomes the default so callers relying on `find(m => m.isDefault)` keep
+ * working.
*/
export function mergeModelLists(curated: ModelInfo[], remote: RemoteModel[]): ModelInfo[] {
const remoteById = new Map(remote.map(m => [m.id, m]));
@@ -40,7 +64,13 @@ export function mergeModelLists(curated: ModelInfo[], remote: RemoteModel[]): Mo
.filter(m => remoteById.has(m.id))
.map(m => {
const remoteModel = remoteById.get(m.id);
- return { ...m, contextWindow: m.contextWindow ?? remoteModel?.contextWindow };
+ return {
+ ...m,
+ // The endpoint is authoritative for display names (e.g. Anthropic's
+ // `display_name`); the base name is only an offline fallback.
+ name: remoteModel?.name ?? m.name,
+ contextWindow: m.contextWindow ?? remoteModel?.contextWindow
+ };
});
const curatedIds = new Set(curated.map(m => m.id));
diff --git a/apps/server/src/services/llm/providers/model_prices.json b/apps/server/src/services/llm/providers/model_prices.json
new file mode 100644
index 0000000000..1707f9b0e2
--- /dev/null
+++ b/apps/server/src/services/llm/providers/model_prices.json
@@ -0,0 +1,663 @@
+{
+ "anthropic": {
+ "claude-3-7-sonnet-20250219": {
+ "input": 3,
+ "output": 15,
+ "ctx": 200000
+ },
+ "claude-3-haiku-20240307": {
+ "input": 0.25,
+ "output": 1.25,
+ "ctx": 200000
+ },
+ "claude-3-opus-20240229": {
+ "input": 15,
+ "output": 75,
+ "ctx": 200000
+ },
+ "claude-4-opus-20250514": {
+ "input": 15,
+ "output": 75,
+ "ctx": 200000
+ },
+ "claude-4-sonnet-20250514": {
+ "input": 3,
+ "output": 15,
+ "ctx": 1000000
+ },
+ "claude-fable-5": {
+ "input": 10,
+ "output": 50,
+ "ctx": 1000000
+ },
+ "claude-haiku-4-5": {
+ "input": 1,
+ "output": 5,
+ "ctx": 200000
+ },
+ "claude-haiku-4-5-20251001": {
+ "input": 1,
+ "output": 5,
+ "ctx": 200000
+ },
+ "claude-opus-4-1": {
+ "input": 15,
+ "output": 75,
+ "ctx": 200000
+ },
+ "claude-opus-4-1-20250805": {
+ "input": 15,
+ "output": 75,
+ "ctx": 200000
+ },
+ "claude-opus-4-20250514": {
+ "input": 15,
+ "output": 75,
+ "ctx": 200000
+ },
+ "claude-opus-4-5": {
+ "input": 5,
+ "output": 25,
+ "ctx": 200000
+ },
+ "claude-opus-4-5-20251101": {
+ "input": 5,
+ "output": 25,
+ "ctx": 200000
+ },
+ "claude-opus-4-6": {
+ "input": 5,
+ "output": 25,
+ "ctx": 1000000
+ },
+ "claude-opus-4-6-20260205": {
+ "input": 5,
+ "output": 25,
+ "ctx": 1000000
+ },
+ "claude-opus-4-7": {
+ "input": 5,
+ "output": 25,
+ "ctx": 1000000
+ },
+ "claude-opus-4-7-20260416": {
+ "input": 5,
+ "output": 25,
+ "ctx": 1000000
+ },
+ "claude-opus-4-8": {
+ "input": 5,
+ "output": 25,
+ "ctx": 1000000
+ },
+ "claude-sonnet-4-20250514": {
+ "input": 3,
+ "output": 15,
+ "ctx": 1000000
+ },
+ "claude-sonnet-4-5": {
+ "input": 3,
+ "output": 15,
+ "ctx": 200000
+ },
+ "claude-sonnet-4-5-20250929": {
+ "input": 3,
+ "output": 15,
+ "ctx": 200000
+ },
+ "claude-sonnet-4-6": {
+ "input": 3,
+ "output": 15,
+ "ctx": 1000000
+ },
+ "claude-sonnet-5": {
+ "input": 2,
+ "output": 10,
+ "ctx": 1000000
+ }
+ },
+ "google": {
+ "gemini-2.0-flash": {
+ "input": 0.1,
+ "output": 0.4,
+ "ctx": 1048576
+ },
+ "gemini-2.0-flash-001": {
+ "input": 0.15,
+ "output": 0.6,
+ "ctx": 1048576
+ },
+ "gemini-2.0-flash-lite": {
+ "input": 0.075,
+ "output": 0.3,
+ "ctx": 1048576
+ },
+ "gemini-2.0-flash-lite-001": {
+ "input": 0.075,
+ "output": 0.3,
+ "ctx": 1048576
+ },
+ "gemini-2.5-computer-use-preview-10-2025": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gemini-2.5-flash": {
+ "input": 0.3,
+ "output": 2.5,
+ "ctx": 1048576
+ },
+ "gemini-2.5-flash-lite": {
+ "input": 0.1,
+ "output": 0.4,
+ "ctx": 1048576
+ },
+ "gemini-2.5-flash-lite-preview-06-17": {
+ "input": 0.1,
+ "output": 0.4,
+ "ctx": 1048576
+ },
+ "gemini-2.5-flash-lite-preview-09-2025": {
+ "input": 0.1,
+ "output": 0.4,
+ "ctx": 1048576
+ },
+ "gemini-2.5-flash-native-audio-latest": {
+ "input": 0.3,
+ "output": 2.5,
+ "ctx": 1048576
+ },
+ "gemini-2.5-flash-native-audio-preview-09-2025": {
+ "input": 0.3,
+ "output": 2.5,
+ "ctx": 1048576
+ },
+ "gemini-2.5-flash-native-audio-preview-12-2025": {
+ "input": 0.3,
+ "output": 2.5,
+ "ctx": 1048576
+ },
+ "gemini-2.5-flash-preview-09-2025": {
+ "input": 0.3,
+ "output": 2.5,
+ "ctx": 1048576
+ },
+ "gemini-2.5-pro": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 1048576
+ },
+ "gemini-2.5-pro-preview-tts": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 1048576
+ },
+ "gemini-3-flash-preview": {
+ "input": 0.5,
+ "output": 3,
+ "ctx": 1048576
+ },
+ "gemini-3-pro-preview": {
+ "input": 2,
+ "output": 12,
+ "ctx": 1048576
+ },
+ "gemini-3.1-flash-lite": {
+ "input": 0.25,
+ "output": 1.5,
+ "ctx": 1048576
+ },
+ "gemini-3.1-flash-lite-preview": {
+ "input": 0.25,
+ "output": 1.5,
+ "ctx": 1048576
+ },
+ "gemini-3.1-flash-live-preview": {
+ "input": 0.75,
+ "output": 4.5,
+ "ctx": 131072
+ },
+ "gemini-3.1-pro-preview": {
+ "input": 2,
+ "output": 12,
+ "ctx": 1048576
+ },
+ "gemini-3.1-pro-preview-customtools": {
+ "input": 2,
+ "output": 12,
+ "ctx": 1048576
+ },
+ "gemini-3.5-flash": {
+ "input": 1.5,
+ "output": 9,
+ "ctx": 1048576
+ },
+ "gemini-3.5-flash-lite": {
+ "input": 0.3,
+ "output": 2.5,
+ "ctx": 1048576
+ },
+ "gemini-3.6-flash": {
+ "input": 1.5,
+ "output": 7.5,
+ "ctx": 1048576
+ },
+ "gemini-exp-1206": {
+ "input": 0.3,
+ "output": 2.5,
+ "ctx": 1048576
+ },
+ "gemini-flash-latest": {
+ "input": 0.3,
+ "output": 2.5,
+ "ctx": 1048576
+ },
+ "gemini-flash-lite-latest": {
+ "input": 0.1,
+ "output": 0.4,
+ "ctx": 1048576
+ },
+ "gemini-omni-flash-preview": {
+ "input": 1.5,
+ "output": 9,
+ "ctx": 1048576
+ },
+ "gemini-pro-latest": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 1048576
+ },
+ "gemini-robotics-er-1.5-preview": {
+ "input": 0.3,
+ "output": 2.5,
+ "ctx": 1048576
+ }
+ },
+ "openai": {
+ "chatgpt-4o-latest": {
+ "input": 5,
+ "output": 15,
+ "ctx": 128000
+ },
+ "gpt-3.5-turbo": {
+ "input": 0.5,
+ "output": 1.5,
+ "ctx": 16385
+ },
+ "gpt-3.5-turbo-0125": {
+ "input": 0.5,
+ "output": 1.5,
+ "ctx": 16385
+ },
+ "gpt-3.5-turbo-1106": {
+ "input": 1,
+ "output": 2,
+ "ctx": 16385
+ },
+ "gpt-3.5-turbo-16k": {
+ "input": 3,
+ "output": 4,
+ "ctx": 16385
+ },
+ "gpt-4": {
+ "input": 30,
+ "output": 60,
+ "ctx": 8192
+ },
+ "gpt-4-0125-preview": {
+ "input": 10,
+ "output": 30,
+ "ctx": 128000
+ },
+ "gpt-4-0314": {
+ "input": 30,
+ "output": 60,
+ "ctx": 8192
+ },
+ "gpt-4-0613": {
+ "input": 30,
+ "output": 60,
+ "ctx": 8192
+ },
+ "gpt-4-1106-preview": {
+ "input": 10,
+ "output": 30,
+ "ctx": 128000
+ },
+ "gpt-4-turbo": {
+ "input": 10,
+ "output": 30,
+ "ctx": 128000
+ },
+ "gpt-4-turbo-2024-04-09": {
+ "input": 10,
+ "output": 30,
+ "ctx": 128000
+ },
+ "gpt-4-turbo-preview": {
+ "input": 10,
+ "output": 30,
+ "ctx": 128000
+ },
+ "gpt-4.1": {
+ "input": 2,
+ "output": 8,
+ "ctx": 1047576
+ },
+ "gpt-4.1-2025-04-14": {
+ "input": 2,
+ "output": 8,
+ "ctx": 1047576
+ },
+ "gpt-4.1-mini": {
+ "input": 0.4,
+ "output": 1.6,
+ "ctx": 1047576
+ },
+ "gpt-4.1-mini-2025-04-14": {
+ "input": 0.4,
+ "output": 1.6,
+ "ctx": 1047576
+ },
+ "gpt-4.1-nano": {
+ "input": 0.1,
+ "output": 0.4,
+ "ctx": 1047576
+ },
+ "gpt-4.1-nano-2025-04-14": {
+ "input": 0.1,
+ "output": 0.4,
+ "ctx": 1047576
+ },
+ "gpt-4o": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-4o-2024-05-13": {
+ "input": 5,
+ "output": 15,
+ "ctx": 128000
+ },
+ "gpt-4o-2024-08-06": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-4o-2024-11-20": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-4o-audio-preview": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-4o-audio-preview-2024-12-17": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-4o-audio-preview-2025-06-03": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-4o-mini": {
+ "input": 0.15,
+ "output": 0.6,
+ "ctx": 128000
+ },
+ "gpt-4o-mini-2024-07-18": {
+ "input": 0.15,
+ "output": 0.6,
+ "ctx": 128000
+ },
+ "gpt-4o-mini-audio-preview": {
+ "input": 0.15,
+ "output": 0.6,
+ "ctx": 128000
+ },
+ "gpt-4o-mini-audio-preview-2024-12-17": {
+ "input": 0.15,
+ "output": 0.6,
+ "ctx": 128000
+ },
+ "gpt-4o-mini-search-preview": {
+ "input": 0.15,
+ "output": 0.6,
+ "ctx": 128000
+ },
+ "gpt-4o-mini-search-preview-2025-03-11": {
+ "input": 0.15,
+ "output": 0.6,
+ "ctx": 128000
+ },
+ "gpt-4o-search-preview": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-4o-search-preview-2025-03-11": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-5": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 272000
+ },
+ "gpt-5-2025-08-07": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 272000
+ },
+ "gpt-5-chat": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-5-chat-latest": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-5-mini": {
+ "input": 0.25,
+ "output": 2,
+ "ctx": 272000
+ },
+ "gpt-5-mini-2025-08-07": {
+ "input": 0.25,
+ "output": 2,
+ "ctx": 272000
+ },
+ "gpt-5-nano": {
+ "input": 0.05,
+ "output": 0.4,
+ "ctx": 272000
+ },
+ "gpt-5-nano-2025-08-07": {
+ "input": 0.05,
+ "output": 0.4,
+ "ctx": 272000
+ },
+ "gpt-5-search-api": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 272000
+ },
+ "gpt-5-search-api-2025-10-14": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 272000
+ },
+ "gpt-5.1": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 272000
+ },
+ "gpt-5.1-2025-11-13": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 272000
+ },
+ "gpt-5.1-chat-latest": {
+ "input": 1.25,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-5.2": {
+ "input": 1.75,
+ "output": 14,
+ "ctx": 272000
+ },
+ "gpt-5.2-2025-12-11": {
+ "input": 1.75,
+ "output": 14,
+ "ctx": 272000
+ },
+ "gpt-5.2-chat-latest": {
+ "input": 1.75,
+ "output": 14,
+ "ctx": 128000
+ },
+ "gpt-5.3-chat-latest": {
+ "input": 1.75,
+ "output": 14,
+ "ctx": 128000
+ },
+ "gpt-5.4": {
+ "input": 2.5,
+ "output": 15,
+ "ctx": 1050000
+ },
+ "gpt-5.4-2026-03-05": {
+ "input": 2.5,
+ "output": 15,
+ "ctx": 1050000
+ },
+ "gpt-5.4-mini": {
+ "input": 0.75,
+ "output": 4.5,
+ "ctx": 1050000
+ },
+ "gpt-5.4-mini-2026-03-17": {
+ "input": 0.75,
+ "output": 4.5,
+ "ctx": 1050000
+ },
+ "gpt-5.4-nano": {
+ "input": 0.2,
+ "output": 1.25,
+ "ctx": 1050000
+ },
+ "gpt-5.4-nano-2026-03-17": {
+ "input": 0.2,
+ "output": 1.25,
+ "ctx": 1050000
+ },
+ "gpt-5.5": {
+ "input": 5,
+ "output": 30,
+ "ctx": 1050000
+ },
+ "gpt-5.5-2026-04-23": {
+ "input": 5,
+ "output": 30,
+ "ctx": 1050000
+ },
+ "gpt-5.6": {
+ "input": 5,
+ "output": 30,
+ "ctx": 1050000
+ },
+ "gpt-5.6-luna": {
+ "input": 1,
+ "output": 6,
+ "ctx": 1050000
+ },
+ "gpt-5.6-sol": {
+ "input": 5,
+ "output": 30,
+ "ctx": 1050000
+ },
+ "gpt-5.6-terra": {
+ "input": 2.5,
+ "output": 15,
+ "ctx": 1050000
+ },
+ "gpt-audio": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-audio-1.5": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-audio-2025-08-28": {
+ "input": 2.5,
+ "output": 10,
+ "ctx": 128000
+ },
+ "gpt-audio-mini": {
+ "input": 0.6,
+ "output": 2.4,
+ "ctx": 128000
+ },
+ "gpt-audio-mini-2025-10-06": {
+ "input": 0.6,
+ "output": 2.4,
+ "ctx": 128000
+ },
+ "gpt-audio-mini-2025-12-15": {
+ "input": 0.6,
+ "output": 2.4,
+ "ctx": 128000
+ },
+ "o1": {
+ "input": 15,
+ "output": 60,
+ "ctx": 200000
+ },
+ "o1-2024-12-17": {
+ "input": 15,
+ "output": 60,
+ "ctx": 200000
+ },
+ "o3": {
+ "input": 2,
+ "output": 8,
+ "ctx": 200000
+ },
+ "o3-2025-04-16": {
+ "input": 2,
+ "output": 8,
+ "ctx": 200000
+ },
+ "o3-mini": {
+ "input": 1.1,
+ "output": 4.4,
+ "ctx": 200000
+ },
+ "o3-mini-2025-01-31": {
+ "input": 1.1,
+ "output": 4.4,
+ "ctx": 200000
+ },
+ "o4-mini": {
+ "input": 1.1,
+ "output": 4.4,
+ "ctx": 200000
+ },
+ "o4-mini-2025-04-16": {
+ "input": 1.1,
+ "output": 4.4,
+ "ctx": 200000
+ }
+ }
+}
diff --git a/apps/server/src/services/llm/providers/openai.spec.ts b/apps/server/src/services/llm/providers/openai.spec.ts
index 96166710a9..9b79d64978 100644
--- a/apps/server/src/services/llm/providers/openai.spec.ts
+++ b/apps/server/src/services/llm/providers/openai.spec.ts
@@ -130,17 +130,21 @@ describe("OpenAiProvider model listing", () => {
expect(models[0].isDefault).toBe(true);
});
- it("falls back to the curated list on HTTP errors", async () => {
+ it("propagates HTTP errors so a bad key/endpoint surfaces in the modal", async () => {
fetchMock.mockResolvedValue({ ok: false, status: 500 });
const provider = new OpenAiProvider("sk-test");
- const models = await provider.listModels();
- expect(models.map((m) => m.id)).toContain("gpt-4.1-mini");
+ await expect(provider.listModels()).rejects.toThrow("HTTP 500");
});
- it("falls back to the curated list on a malformed response body", async () => {
+ it("reports a friendly authentication error on a 401", async () => {
+ fetchMock.mockResolvedValue({ ok: false, status: 401 });
+ const provider = new OpenAiProvider("sk-test");
+ await expect(provider.listModels()).rejects.toThrow(/Authentication failed/);
+ });
+
+ it("propagates a malformed response body", async () => {
fetchMock.mockResolvedValue(okJson({ nope: true }));
const provider = new OpenAiProvider("sk-test");
- const models = await provider.listModels();
- expect(models.map((m) => m.id)).toContain("gpt-4.1");
+ await expect(provider.listModels()).rejects.toThrow(/Unexpected .* response shape/);
});
});
diff --git a/apps/server/src/services/llm/providers/openai.ts b/apps/server/src/services/llm/providers/openai.ts
index 6ab483ebf6..e6968a771a 100644
--- a/apps/server/src/services/llm/providers/openai.ts
+++ b/apps/server/src/services/llm/providers/openai.ts
@@ -1,71 +1,20 @@
import { createOpenAI, type OpenAIProvider as OpenAISDKProvider } from "@ai-sdk/openai";
import type { ToolSet } from "ai";
-import { BaseProvider, buildModelList } from "./base_provider.js";
+import { BaseProvider } from "./base_provider.js";
import { isOpenAiChatModel, openAiModelName, type RemoteModel } from "./model_listing.js";
const OFFICIAL_BASE_URL = "https://api.openai.com/v1";
-/**
- * Available OpenAI models with pricing (USD per million tokens).
- * Source: https://platform.openai.com/docs/pricing
- */
-const { models: AVAILABLE_MODELS, pricing: MODEL_PRICING } = buildModelList([
- // ===== Current Models =====
- {
- id: "gpt-4.1",
- name: "GPT-4.1",
- pricing: { input: 2, output: 8 },
- contextWindow: 1047576,
- isDefault: true
- },
- {
- id: "gpt-4.1-mini",
- name: "GPT-4.1 Mini",
- pricing: { input: 0.4, output: 1.6 },
- contextWindow: 1047576
- },
- {
- id: "gpt-4.1-nano",
- name: "GPT-4.1 Nano",
- pricing: { input: 0.1, output: 0.4 },
- contextWindow: 1047576
- },
- {
- id: "o3",
- name: "o3",
- pricing: { input: 2, output: 8 },
- contextWindow: 200000
- },
- {
- id: "o4-mini",
- name: "o4-mini",
- pricing: { input: 1.1, output: 4.4 },
- contextWindow: 200000
- },
- // ===== Legacy Models =====
- {
- id: "gpt-4o",
- name: "GPT-4o",
- pricing: { input: 2.5, output: 10 },
- contextWindow: 128000,
- isLegacy: true
- },
- {
- id: "gpt-4o-mini",
- name: "GPT-4o Mini",
- pricing: { input: 0.15, output: 0.6 },
- contextWindow: 128000,
- isLegacy: true
- }
-]);
-
export class OpenAiProvider extends BaseProvider {
name = "openai";
protected defaultModel = "gpt-4.1";
protected titleModel = "gpt-4.1-mini";
- protected availableModels = AVAILABLE_MODELS;
- protected modelPricing = MODEL_PRICING;
+
+ /** The `/models` endpoint returns no display names, so derive friendly ones. */
+ protected override modelName(id: string): string {
+ return openAiModelName(id);
+ }
private openai: OpenAISDKProvider;
diff --git a/apps/server/src/services/llm/types.ts b/apps/server/src/services/llm/types.ts
index 976ed52ecd..20ffdc9e75 100644
--- a/apps/server/src/services/llm/types.ts
+++ b/apps/server/src/services/llm/types.ts
@@ -48,8 +48,6 @@ export interface ModelInfo {
pricing?: ModelPricing;
/** Whether this is the default model */
isDefault?: boolean;
- /** Cost multiplier relative to the cheapest model (1x = cheapest) */
- costMultiplier?: number;
/** Maximum context window size in tokens */
contextWindow?: number;
/** Whether this is a legacy/older model */
@@ -106,8 +104,10 @@ export interface LlmProvider {
* where known. Optional — providers with a fixed catalog (agent/subscription
* providers) omit it and callers fall back to {@link getAvailableModels}.
*
- * Implementations must degrade gracefully: on fetch failure they return
- * the curated list rather than throwing.
+ * Returns the curated list when dynamic listing is unsupported, but a
+ * listing *failure* (bad credentials, unreachable endpoint) rejects so the
+ * add/edit-provider screen can surface it instead of masking a bad
+ * credential as success.
*/
listModels?(): Promise<ModelInfo[]>;
diff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.ts
index 498250bd3e..1fff9f7903 100644
--- a/packages/commons/src/lib/llm_api.ts
+++ b/packages/commons/src/lib/llm_api.ts
@@ -133,8 +133,6 @@ export interface LlmModelInfo {
isLegacy?: boolean;
/** Whether this model is pre-selected by default when adding a provider (e.g. excludes legacy and, for Gemini, preview models) */
recommended?: boolean;
- /** Cost multiplier relative to the cheapest model (1x = cheapest) */
- costMultiplier?: number;
/** Maximum context window size in tokens */
contextWindow?: number;
/** Whether usage is covered by a subscription plan rather than metered per token */