Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): dynamically list models from provider endpoints

Elian Doranf3d7246f8c2f
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
index 24cb701a00..b9c0964ce7 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
@@ -182,6 +182,11 @@
color: var(--muted-text-color);
}
+.llm-chat-model-dropdown .dropdown-menu {
+ max-height: 80vh;
+ overflow: auto;
+}
+
/* Position legacy models submenu to open upward */
.llm-chat-model-dropdown .dropdown-submenu .dropdown-menu {
bottom: 0;
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
index 3f678dae8d..225f094937 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -154,9 +154,9 @@ export default function ChatInputBar({
onExtendedThinkingChange?.();
};
- const handleModelSelect = (model: string, provider?: string) => {
- chat.setSelectedModel(model, provider);
- onModelChange?.(model);
+ const handleModelSelect = (model: ModelOption) => {
+ chat.setSelectedModel(model.id, model.provider, model.providerId);
+ onModelChange?.(model.id);
};
const handleNoteContextToggle = () => {
@@ -178,14 +178,16 @@ export default function ChatInputBar({
const isNoteContextEnabled = !!chat.contextNoteId && !!activeNoteId;
- // Two providers can expose the same model ID (e.g. an Anthropic API key and
- // a Claude subscription both offering "claude-sonnet-5"), so identify the
- // active model by provider too. Mirror the sender's resolution: prefer the
- // recorded provider, else fall back to the first ID match (pre-existing chats).
- const effectiveProvider = chat.selectedProvider
- ?? chat.availableModels.find(m => m.id === chat.selectedModel)?.provider;
- const isSelectedModel = (m: ModelOption) => m.id === chat.selectedModel && m.provider === effectiveProvider;
- const currentModel = chat.availableModels.find(isSelectedModel);
+ // Several providers can expose the same model ID (e.g. an Anthropic API key
+ // and a Claude subscription both offering "claude-sonnet-5", or two
+ // OpenAI-compatible endpoints), so identify the active model by its provider
+ // config too. Mirror the sender's resolution: prefer the recorded provider
+ // id/type, else fall back to the first ID match (pre-existing chats).
+ const currentModel = chat.availableModels.find(m =>
+ m.id === chat.selectedModel
+ && (!chat.selectedProvider || m.provider === chat.selectedProvider)
+ && (!chat.selectedProviderId || m.providerId === chat.selectedProviderId));
+ const isSelectedModel = (m: ModelOption) => m === currentModel;
const currentModels = chat.availableModels.filter(m => !m.isLegacy);
const currentModelGroups = groupModelsByProvider(currentModels);
const legacyModels = chat.availableModels.filter(m => m.isLegacy);
@@ -361,8 +363,8 @@ export default function ChatInputBar({
{group.providerName && <FormListHeader text={group.providerName} />}
{group.models.map(model => (
<FormListItem
- key={`${model.provider}:${model.id}`}
- onClick={() => handleModelSelect(model.id, model.provider)}
+ key={`${model.providerId ?? model.provider}:${model.id}`}
+ onClick={() => handleModelSelect(model)}
checked={isSelectedModel(model)}
>
{model.name}{model.costDescription && <> <small>({model.costDescription})</small></>}
@@ -383,8 +385,8 @@ export default function ChatInputBar({
{group.providerName && <FormListHeader text={group.providerName} />}
{group.models.map(model => (
<FormListItem
- key={`${model.provider}:${model.id}`}
- onClick={() => handleModelSelect(model.id, model.provider)}
+ key={`${model.providerId ?? model.provider}:${model.id}`}
+ onClick={() => handleModelSelect(model)}
checked={isSelectedModel(model)}
>
{model.name}{model.costDescription && <> <small>({model.costDescription})</small></>}
@@ -468,30 +470,37 @@ export default function ChatInputBar({
}
interface ProviderModelGroup {
- /** Stable key for the group (the provider id). */
+ /** Stable key for the group (the provider config id, falling back to the type). */
key: string;
- /** Friendly provider name shown in the group header. */
+ /** Group header: the user-given config name, or the provider type's friendly name. */
providerName: string;
models: ModelOption[];
}
/**
- * Groups models by their owning provider, preserving the order in which each provider first
- * appears. The provider's friendly name (from {@link PROVIDER_TYPES}) heads each group.
+ * Groups models by their owning provider config, preserving the order in which each config
+ * first appears — so two configs of the same type (e.g. OpenAI and a self-hosted Ollama)
+ * get separate groups. The user-given config name heads each group, falling back to the
+ * provider type's friendly name (from {@link PROVIDER_TYPES}) for older servers that don't
+ * report it.
*/
function groupModelsByProvider(models: ModelOption[]): ProviderModelGroup[] {
const groups: ProviderModelGroup[] = [];
- const byProvider = new Map<string | undefined, ProviderModelGroup>();
+ const byProvider = new Map<string, ProviderModelGroup>();
for (const model of models) {
- let group = byProvider.get(model.provider);
+ const key = model.providerId ?? model.provider ?? "";
+ let group = byProvider.get(key);
if (!group) {
group = {
- key: model.provider ?? "",
- providerName: PROVIDER_TYPES.find(p => p.id === model.provider)?.name ?? model.provider ?? "",
+ key,
+ providerName: model.providerName
+ ?? PROVIDER_TYPES.find(p => p.id === model.provider)?.name
+ ?? model.provider
+ ?? "",
models: []
};
- byProvider.set(model.provider, group);
+ byProvider.set(key, group);
groups.push(group);
}
group.models.push(model);
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
index 086290041a..f3cbc3a0ac 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
@@ -158,6 +158,13 @@ export interface LlmChatContent {
* provider by model ID in that case.
*/
selectedProvider?: string;
+ /**
+ * ID of the provider configuration owning {@link selectedModel}. Stronger
+ * than {@link selectedProvider}: it also disambiguates multiple configs of
+ * the same type (e.g. OpenAI + a self-hosted Ollama endpoint). Absent in
+ * chats saved before this field existed.
+ */
+ selectedProviderId?: string;
enableWebSearch?: boolean;
enableNoteTools?: boolean;
enableExtendedThinking?: boolean;
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 839b623b2e..e1765010ee 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
@@ -28,9 +28,9 @@ type LlmChatApi = ReturnType<typeof useLlmChat>;
type LlmChatOptions = Parameters<typeof useLlmChat>[1];
const MODELS = [
- { id: "sonnet", name: "Sonnet", provider: "claude-agent", isDefault: true, isSubscription: true },
- { id: "opus", name: "Opus", provider: "anthropic", costMultiplier: 5 },
- { id: "mini", name: "Mini", provider: "openai" }
+ { id: "sonnet", name: "Sonnet", provider: "claude-agent", providerId: "ca_1", isDefault: true, isSubscription: true },
+ { id: "opus", name: "Opus", provider: "anthropic", providerId: "a_1", costMultiplier: 5 },
+ { id: "mini", name: "Mini", provider: "openai", providerId: "o_1" }
];
describe("useLlmChat", () => {
@@ -83,10 +83,11 @@ describe("useLlmChat", () => {
it("selects the default model with its provider and annotates model costs", async () => {
await mountChat();
- // The default model's provider is recorded alongside the model, so two
- // providers exposing the same model ID stay distinguishable.
+ // The default model's provider (type and config id) is recorded alongside
+ // the model, so two providers exposing the same model ID stay distinguishable.
expect(api().selectedModel).toBe("sonnet");
expect(api().selectedProvider).toBe("claude-agent");
+ expect(api().selectedProviderId).toBe("ca_1");
expect(api().hasProvider).toBe(true);
const costById = new Map(api().availableModels.map((m) => [m.id, m.costDescription]));
@@ -108,6 +109,7 @@ describe("useLlmChat", () => {
const options = streamChatCompletionMock.mock.calls[0][1];
expect(options.model).toBe("sonnet");
expect(options.provider).toBe("claude-agent");
+ expect(options.providerId).toBe("ca_1");
});
it("resolves the provider by model ID for chats saved before selectedProvider existed", async () => {
@@ -127,6 +129,7 @@ describe("useLlmChat", () => {
await api().handleSubmit(new Event("submit"));
});
expect(streamChatCompletionMock.mock.calls[0][1].provider).toBe("anthropic");
+ expect(streamChatCompletionMock.mock.calls[0][1].providerId).toBe("a_1");
});
it("round-trips the selected provider through getContent", async () => {
@@ -136,12 +139,12 @@ describe("useLlmChat", () => {
await act(async () => {
api().loadFromContent({ version: 1, messages: [], selectedModel: "opus" });
});
- expect(api().getContent()).toMatchObject({ selectedModel: "opus", selectedProvider: undefined });
+ expect(api().getContent()).toMatchObject({ selectedModel: "opus", selectedProvider: undefined, selectedProviderId: undefined });
- // Re-picking a model records its provider and persists it.
+ // Re-picking a model records its provider (type and config id) and persists both.
await act(async () => {
- api().setSelectedModel("mini", "openai");
+ api().setSelectedModel("mini", "openai", "o_1");
});
- expect(api().getContent()).toMatchObject({ selectedModel: "mini", selectedProvider: "openai" });
+ expect(api().getContent()).toMatchObject({ selectedModel: "mini", selectedProvider: "openai", selectedProviderId: "o_1" });
});
});
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 5f8247a76d..216674f2e5 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -105,6 +105,8 @@ export interface UseLlmChatReturn {
selectedModel: string;
/** Provider type owning {@link selectedModel}; undefined until a model is picked or in pre-existing chats. */
selectedProvider: string | undefined;
+ /** ID of the provider config owning {@link selectedModel}; undefined in chats saved before it existed. */
+ selectedProviderId: string | undefined;
enableWebSearch: boolean;
enableNoteTools: boolean;
enableExtendedThinking: boolean;
@@ -136,7 +138,7 @@ export interface UseLlmChatReturn {
// Setters
setInput: (value: string) => void;
setMessages: (messages: StoredMessage[]) => void;
- setSelectedModel: (model: string, provider?: string) => void;
+ setSelectedModel: (model: string, provider?: string, providerId?: string) => void;
setEnableWebSearch: (value: boolean) => void;
setEnableNoteTools: (value: boolean) => void;
setEnableExtendedThinking: (value: boolean) => void;
@@ -192,6 +194,7 @@ export function useLlmChat(
const [availableModels, setAvailableModels] = useState<ModelOption[]>([]);
const [selectedModel, setSelectedModel] = useState<string>("");
const [selectedProvider, setSelectedProvider] = useState<string | undefined>(undefined);
+ const [selectedProviderId, setSelectedProviderId] = useState<string | undefined>(undefined);
const [enableWebSearch, setEnableWebSearch] = useState(true);
const [enableNoteTools, setEnableNoteTools] = useState(defaultEnableNoteTools);
const [enableExtendedThinking, setEnableExtendedThinking] = useState(false);
@@ -223,6 +226,8 @@ export function useLlmChat(
selectedModelRef.current = selectedModel;
const selectedProviderRef = useRef(selectedProvider);
selectedProviderRef.current = selectedProvider;
+ const selectedProviderIdRef = useRef(selectedProviderId);
+ selectedProviderIdRef.current = selectedProviderId;
const enableWebSearchRef = useRef(enableWebSearch);
enableWebSearchRef.current = enableWebSearch;
const enableNoteToolsRef = useRef(enableNoteTools);
@@ -268,12 +273,14 @@ export function useLlmChat(
onMessagesChangeRef.current?.(newMessages);
}, []);
- // Selecting a model records its provider too, so a later send resolves the
- // right provider even when two providers expose the same model ID (e.g. an
- // Anthropic API key and a Claude subscription both offering "claude-sonnet-5").
- const selectModel = useCallback((model: string, provider?: string) => {
+ // Selecting a model records its provider (and provider config id) too, so a
+ // later send resolves the right provider even when two providers expose the
+ // same model ID (e.g. an Anthropic API key and a Claude subscription both
+ // offering "claude-sonnet-5", or two OpenAI-compatible endpoints).
+ const selectModel = useCallback((model: string, provider?: string, providerId?: string) => {
setSelectedModel(model);
setSelectedProvider(provider);
+ setSelectedProviderId(providerId);
}, []);
// Fetch available models on mount
@@ -292,7 +299,7 @@ export function useLlmChat(
if (!selectedModel) {
const defaultModel = models.find(m => m.isDefault) || models[0];
if (defaultModel) {
- selectModel(defaultModel.id, defaultModel.provider);
+ selectModel(defaultModel.id, defaultModel.provider, defaultModel.providerId);
}
}
}).catch(err => {
@@ -478,9 +485,10 @@ export function useLlmChat(
}
setMessagesInternal(content.messages || []);
if (content.selectedModel) {
- // selectedProvider may be absent in chats saved before it existed;
- // the sender then falls back to resolving the provider by model ID.
- selectModel(content.selectedModel, content.selectedProvider);
+ // selectedProvider/selectedProviderId may be absent in chats saved
+ // before they existed; the sender then falls back to resolving the
+ // provider by model ID.
+ selectModel(content.selectedModel, content.selectedProvider, content.selectedProviderId);
}
if (typeof content.enableWebSearch === "boolean") {
setEnableWebSearch(content.enableWebSearch);
@@ -503,6 +511,7 @@ export function useLlmChat(
messages: messagesRef.current,
selectedModel: selectedModelRef.current || undefined,
selectedProvider: selectedProviderRef.current || undefined,
+ selectedProviderId: selectedProviderIdRef.current || undefined,
enableWebSearch: enableWebSearchRef.current,
enableNoteTools: enableNoteToolsRef.current
};
@@ -555,11 +564,15 @@ export function useLlmChat(
// The fallback returns the first match, so it can pick the wrong provider
// when two share a model ID — but such chats predate the subscription
// provider entirely, so their IDs only ever match one provider.
- const selectedModelProvider = selectedProvider
- ?? availableModels.find(m => m.id === selectedModel)?.provider;
+ const matchedModel = availableModels.find(m =>
+ m.id === selectedModel && (!selectedProvider || m.provider === selectedProvider));
+ const selectedModelProvider = selectedProvider ?? matchedModel?.provider;
const streamOptions: Parameters<typeof streamChatCompletion>[1] = {
model: selectedModel || undefined,
provider: selectedModelProvider,
+ // The config id pins the exact provider instance when several of the
+ // same type are configured (e.g. OpenAI + self-hosted Ollama).
+ providerId: selectedProviderId ?? matchedModel?.providerId,
enableWebSearch,
enableNoteTools,
contextNoteId,
@@ -782,7 +795,7 @@ export function useLlmChat(
setIsStreaming(false);
abortControllerRef.current = null;
});
- }, [selectedModel, selectedProvider, availableModels, enableWebSearch, enableNoteTools, enableExtendedThinking, contextNoteId, supportsExtendedThinking, setMessages, smoothAppend, smoothDrain, smoothReset]);
+ }, [selectedModel, selectedProvider, selectedProviderId, availableModels, enableWebSearch, enableNoteTools, enableExtendedThinking, contextNoteId, supportsExtendedThinking, setMessages, smoothAppend, smoothDrain, smoothReset]);
const handleSubmit = useCallback(async (e: Event) => {
e.preventDefault();
@@ -881,6 +894,7 @@ export function useLlmChat(
availableModels,
selectedModel,
selectedProvider,
+ selectedProviderId,
enableWebSearch,
enableNoteTools,
enableExtendedThinking,
diff --git a/apps/server/src/routes/api/llm_chat.spec.ts b/apps/server/src/routes/api/llm_chat.spec.ts
index 2b6f84651f..319f08f928 100644
--- a/apps/server/src/routes/api/llm_chat.spec.ts
+++ b/apps/server/src/routes/api/llm_chat.spec.ts
@@ -10,13 +10,14 @@ const state = vi.hoisted(() => ({
// When true, the fake provider is chunk-native (implements chatChunks) and
// records the abort signal the route wires to the response lifecycle.
chunkNative: false,
- chunkSignal: undefined as AbortSignal | undefined
+ chunkSignal: undefined as AbortSignal | undefined,
+ // Records how streamChat resolved the provider.
+ providerIdRequested: undefined as string | undefined,
+ providerTypeRequested: undefined as string | undefined
}));
-vi.mock("../../services/llm/index.js", () => ({
- hasConfiguredProviders: () => state.configured,
- getAllModels: () => state.models,
- getProviderByType: () => ({
+vi.mock("../../services/llm/index.js", () => {
+ const makeProvider = () => ({
chat: () => { if (state.chatThrows !== undefined) throw state.chatThrows; return {}; },
chatChunks: state.chunkNative
? async function* (_messages: unknown, _config: unknown, signal?: AbortSignal) {
@@ -26,8 +27,14 @@ vi.mock("../../services/llm/index.js", () => ({
: undefined,
getAvailableModels: () => state.availableModels,
getModelPricing: () => ({ input: 0, output: 0 })
- })
-}));
+ });
+ return {
+ hasConfiguredProviders: () => state.configured,
+ getAllModels: async () => state.models,
+ getProvider: (id: string) => { state.providerIdRequested = id; return makeProvider(); },
+ getProviderByType: (type: string) => { state.providerTypeRequested = type; return makeProvider(); }
+ };
+});
vi.mock("../../services/llm/stream.js", () => ({
async *streamToChunks () { for (const c of state.chunks) yield c; }
@@ -74,20 +81,22 @@ describe("LLM chat API", () => {
availableModels: [{ id: "m1", name: "Model One", isDefault: true }],
chatThrows: undefined,
chunkNative: false,
- chunkSignal: undefined
+ chunkSignal: undefined,
+ providerIdRequested: undefined,
+ providerTypeRequested: undefined
});
generateChatTitle.mockClear();
});
describe("getModels", () => {
- it("returns no models when no provider is configured", () => {
+ it("returns no models when no provider is configured", async () => {
state.configured = false;
- expect(llmChatRoute.getModels({} as Request, {} as Response)).toEqual({ models: [] });
+ await expect(llmChatRoute.getModels({} as Request, {} as Response)).resolves.toEqual({ models: [] });
});
- it("returns all models when configured", () => {
+ it("returns all models when configured", async () => {
state.models = [{ id: "m1" }];
- expect(llmChatRoute.getModels({} as Request, {} as Response)).toEqual({ models: [{ id: "m1" }] });
+ await expect(llmChatRoute.getModels({} as Request, {} as Response)).resolves.toEqual({ models: [{ id: "m1" }] });
});
});
@@ -109,6 +118,27 @@ describe("LLM chat API", () => {
expect(r.ended).toBe(true);
});
+ it("routes by providerId when present, falling back to provider type", async () => {
+ state.chunks = [{ type: "done" }];
+ const r1 = fakeRes();
+ await llmChatRoute.streamChat(req({
+ messages: [{ role: "user", content: "hi" }],
+ config: { provider: "openai", providerId: "openai_123" }
+ }), r1.res);
+ expect(state.providerIdRequested).toBe("openai_123");
+ expect(state.providerTypeRequested).toBeUndefined();
+
+ // No providerId (chat saved before it existed) → type-based resolution.
+ state.providerIdRequested = undefined;
+ const r2 = fakeRes();
+ await llmChatRoute.streamChat(req({
+ messages: [{ role: "user", content: "hi" }],
+ config: { provider: "openai" }
+ }), r2.res);
+ expect(state.providerIdRequested).toBeUndefined();
+ expect(state.providerTypeRequested).toBe("openai");
+ });
+
it("emits an SSE error when no model can be resolved", async () => {
state.availableModels = [];
const r = fakeRes();
diff --git a/apps/server/src/routes/api/llm_chat.ts b/apps/server/src/routes/api/llm_chat.ts
index 66ef7f524f..8264e245a4 100644
--- a/apps/server/src/routes/api/llm_chat.ts
+++ b/apps/server/src/routes/api/llm_chat.ts
@@ -3,7 +3,7 @@ import { getLog } from "@triliumnext/core";
import type { Request, Response } from "express";
import { generateChatTitle } from "../../services/llm/chat_title.js";
-import { getAllModels, getProviderByType, hasConfiguredProviders, type LlmProviderConfig } from "../../services/llm/index.js";
+import { getAllModels, getProvider, getProviderByType, hasConfiguredProviders, type LlmProviderConfig } from "../../services/llm/index.js";
import { streamToChunks } from "../../services/llm/stream.js";
import { safeExtractMessageAndStackFromError } from "../../services/utils.js";
@@ -50,7 +50,12 @@ async function streamChat(req: Request, res: Response) {
return;
}
- const provider = getProviderByType(config.provider || "anthropic");
+ // Prefer routing by the provider config id — it disambiguates multiple
+ // configs of the same type (e.g. OpenAI + a self-hosted Ollama). Chats
+ // saved before providerId existed fall back to type-based resolution.
+ const provider = config.providerId
+ ? getProvider(config.providerId)
+ : getProviderByType(config.provider || "anthropic");
// Get pricing and display name for the model
const modelId = config.model || provider.getAvailableModels().find(m => m.isDefault)?.id;
@@ -112,14 +117,16 @@ async function streamChat(req: Request, res: Response) {
}
/**
- * Get available models from all configured providers.
+ * Get available models from all configured providers. Providers that support
+ * dynamic listing are queried live (with server-side caching); the rest report
+ * their curated list.
*/
-function getModels(_req: Request, _res: Response) {
+async function getModels(_req: Request, _res: Response) {
if (!hasConfiguredProviders()) {
return { models: [] };
}
- return { models: getAllModels() };
+ return { models: await getAllModels() };
}
export default {
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index c55babba2a..b10608f149 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -173,7 +173,7 @@ function register(app: express.Application) {
// LLM chat endpoints
asyncRoute(PST, "/api/llm-chat/stream", [auth.checkApiAuthOrElectron, csrfMiddleware], llmChatRoute.streamChat, null);
- apiRoute(GET, "/api/llm-chat/models", llmChatRoute.getModels);
+ asyncApiRoute(GET, "/api/llm-chat/models", llmChatRoute.getModels);
// no CSRF since this is called from android app
asyncRoute(PST, "/api/sender/login", [loginRateLimiter], loginApiRoute.token, apiResultHandler);
diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.ts
index 146eefd75a..be515ea1b2 100644
--- a/apps/server/src/services/llm/index.spec.ts
+++ b/apps/server/src/services/llm/index.spec.ts
@@ -103,6 +103,19 @@ describe("llm/index provider registry", () => {
setProviders([{ id: "x", name: "X", provider: "mystery", apiKey: "k" }]);
expect(() => getProvider("x")).toThrow(/Unknown LLM provider type: mystery/);
});
+
+ it("drops cached instances when the llmProviders option changes", () => {
+ setProviders(TWO);
+ const p1 = getProvider("a1");
+ // Same config → still cached.
+ setProviders(TWO);
+ expect(getProvider("a1")).toBe(p1);
+ // Edited config (e.g. new API key) → cache self-invalidates.
+ setProviders([{ ...TWO[0], apiKey: "new-key" }, TWO[1]]);
+ const p2 = getProvider("a1");
+ expect(p2).not.toBe(p1);
+ expect((p2.constructor as any).lastArgs).toEqual(["new-key", "https://proxy"]);
+ });
});
describe("getConfiguredProviders error handling (via hasConfiguredProviders)", () => {
@@ -137,29 +150,50 @@ describe("llm/index provider registry", () => {
});
describe("getAllModels", () => {
- it("aggregates models across provider types, tagged with the provider", () => {
+ it("aggregates models across providers, tagged with type and config id/name", async () => {
setProviders(TWO);
- const models = getAllModels();
+ const models = await getAllModels();
expect(models).toEqual([
- { id: "anthropic-model", name: "anthropic Model", provider: "anthropic" },
- { id: "openai-model", name: "openai Model", provider: "openai" }
+ { id: "anthropic-model", name: "anthropic Model", provider: "anthropic", providerId: "a1", providerName: "My Claude" },
+ { id: "openai-model", name: "openai Model", provider: "openai", providerId: "o1", providerName: "My GPT" }
]);
});
- it("includes each provider type only once even with duplicate configs", () => {
+ it("lists every config separately, even two of the same type", async () => {
+ // e.g. a real OpenAI key plus a self-hosted Ollama endpoint.
setProviders([
- { id: "a1", name: "A1", provider: "anthropic", apiKey: "k1" },
- { id: "a2", name: "A2", provider: "anthropic", apiKey: "k2" }
+ { id: "o1", name: "OpenAI", provider: "openai", apiKey: "k1" },
+ { id: "o2", name: "My Ollama", provider: "openai", apiKey: "k2", baseURL: "http://localhost:11434/v1" }
+ ]);
+ const models = await getAllModels();
+ expect(models.map(m => [m.providerId, m.providerName])).toEqual([
+ ["o1", "OpenAI"],
+ ["o2", "My Ollama"]
]);
- const models = getAllModels();
- expect(models).toHaveLength(1);
- expect(models[0].provider).toBe("anthropic");
});
- it("skips and logs a provider whose model lookup throws", () => {
- setProviders([{ id: "x", name: "X", provider: "mystery", apiKey: "k" }]);
+ it("prefers dynamic listModels() when the provider implements it", async () => {
+ setProviders(TWO);
+ const provider = getProvider("a1") as { listModels?: () => Promise<unknown> };
+ provider.listModels = vi.fn().mockResolvedValue([{ id: "dyn-model", name: "Dynamic Model" }]);
+ const models = await getAllModels();
+ expect(models[0]).toEqual({
+ id: "dyn-model",
+ name: "Dynamic Model",
+ provider: "anthropic",
+ providerId: "a1",
+ providerName: "My Claude"
+ });
+ });
+
+ it("skips and logs a provider whose model lookup throws, keeping the rest", async () => {
+ setProviders([
+ { id: "x", name: "X", provider: "mystery", apiKey: "k" },
+ { id: "o1", name: "My GPT", provider: "openai", apiKey: "k2" }
+ ]);
// Unknown type → getProvider throws inside getAllModels and is caught.
- expect(getAllModels()).toEqual([]);
+ const models = await getAllModels();
+ expect(models.map(m => m.providerId)).toEqual(["o1"]);
expect(errorMock).toHaveBeenCalled();
});
});
diff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.ts
index 5a0bf0d314..895a759a78 100644
--- a/apps/server/src/services/llm/index.ts
+++ b/apps/server/src/services/llm/index.ts
@@ -32,12 +32,23 @@ const providerFactories: Record<string, (apiKey: string, baseURL?: string) => Ll
/** Cache of instantiated providers by their config ID */
let cachedProviders: Record<string, LlmProvider> = {};
+/**
+ * The raw llmProviders JSON the cache was built from. When the option changes
+ * (provider added/edited/removed in the settings), the cache self-invalidates
+ * so stale instances — and their dynamic model-list caches — are dropped.
+ */
+let cachedProvidersSource: string | null = null;
+
/**
* Get configured providers from the options.
*/
function getConfiguredProviders(): LlmProviderSetup[] {
try {
const providersJson = optionService.getOptionOrNull("llmProviders");
+ if (providersJson !== cachedProvidersSource) {
+ cachedProviders = {};
+ cachedProvidersSource = providersJson;
+ }
if (!providersJson) {
return [];
}
@@ -106,32 +117,33 @@ export function hasConfiguredProviders(): boolean {
}
/**
- * Get all models from all configured providers, tagged with their provider type.
+ * Get all models from every configured provider instance, tagged with the
+ * provider type and the owning config's id/name. Each config is listed
+ * separately (not deduped by type) so e.g. a real OpenAI key and a self-hosted
+ * Ollama endpoint each contribute their own models. Providers that support
+ * dynamic listing are queried live (in parallel); the rest — and any provider
+ * whose lookup fails — contribute their curated list or are skipped.
*/
-export function getAllModels(): ModelInfo[] {
+export async function getAllModels(): Promise<ModelInfo[]> {
const configs = getConfiguredProviders();
- const seenProviderTypes = new Set<string>();
- const allModels: ModelInfo[] = [];
-
- for (const config of configs) {
- // Only include models once per provider type (not per config instance)
- if (seenProviderTypes.has(config.provider)) {
- continue;
- }
- seenProviderTypes.add(config.provider);
+ const modelsPerConfig = await Promise.all(configs.map(async config => {
try {
const provider = getProvider(config.id);
- const models = provider.getAvailableModels();
- for (const model of models) {
- allModels.push({ ...model, provider: config.provider });
- }
+ const models = await (provider.listModels?.() ?? provider.getAvailableModels());
+ return models.map(model => ({
+ ...model,
+ provider: config.provider,
+ providerId: config.id,
+ providerName: config.name
+ }));
} catch (e) {
- getLog().error(`Failed to get models from provider ${config.provider}: ${e}`);
+ getLog().error(`Failed to get models from provider ${config.provider} (${config.id}): ${e}`);
+ return [];
}
- }
+ }));
- return allModels;
+ return modelsPerConfig.flat();
}
/**
@@ -139,6 +151,7 @@ export function getAllModels(): ModelInfo[] {
*/
export function clearProviderCache(): void {
cachedProviders = {};
+ cachedProvidersSource = null;
}
export type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing } from "./types.js";
diff --git a/apps/server/src/services/llm/providers/anthropic.spec.ts b/apps/server/src/services/llm/providers/anthropic.spec.ts
index 0131eeb80d..5869b6052a 100644
--- a/apps/server/src/services/llm/providers/anthropic.spec.ts
+++ b/apps/server/src/services/llm/providers/anthropic.spec.ts
@@ -1,5 +1,5 @@
import type { LlmMessage } from "@triliumnext/commons";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const createAnthropicMock = vi.fn();
const webSearchMock = vi.fn(() => ({ kind: "anthropic_web_search" }));
@@ -288,3 +288,54 @@ describe("AnthropicProvider prompt cache stability", () => {
expect(opts.system.content).not.toContain("SCRIPT_BODY");
});
});
+
+describe("AnthropicProvider model listing", () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ const okJson = (body: unknown) => ({ ok: true, json: async () => body });
+
+ it("fetches /models with the API key headers and merges display names", async () => {
+ fetchMock.mockResolvedValue(okJson({
+ data: [
+ { id: "claude-sonnet-5", display_name: "Claude Sonnet 5" },
+ { id: "claude-omega-6", display_name: "Claude Omega 6" }
+ ]
+ }));
+ const provider = new AnthropicProvider("sk-ant");
+
+ const models = await provider.listModels();
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://api.anthropic.com/v1/models?limit=1000",
+ expect.objectContaining({
+ headers: { "x-api-key": "sk-ant", "anthropic-version": "2023-06-01" }
+ })
+ );
+ 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 } });
+ expect(models[1]).toMatchObject({ name: "Claude Omega 6" });
+ expect(models[1].pricing).toBeUndefined();
+ });
+
+ it("uses a custom baseURL when configured", async () => {
+ fetchMock.mockResolvedValue(okJson({ data: [{ id: "claude-sonnet-5" }] }));
+ const provider = new AnthropicProvider("sk-ant", "https://proxy.example/v1");
+ await provider.listModels();
+ expect(fetchMock).toHaveBeenCalledWith("https://proxy.example/v1/models?limit=1000", expect.anything());
+ });
+
+ it("falls back to the curated list when the fetch fails", 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");
+ });
+});
diff --git a/apps/server/src/services/llm/providers/anthropic.ts b/apps/server/src/services/llm/providers/anthropic.ts
index f771c8db79..9598539638 100644
--- a/apps/server/src/services/llm/providers/anthropic.ts
+++ b/apps/server/src/services/llm/providers/anthropic.ts
@@ -4,6 +4,9 @@ import { type ModelMessage, stepCountIs, streamText, type SystemModelMessage, ty
import type { LlmProviderConfig, StreamResult } from "../types.js";
import { BaseProvider, buildModelList, buildModelMessage } from "./base_provider.js";
+import type { RemoteModel } from "./model_listing.js";
+
+const OFFICIAL_BASE_URL = "https://api.anthropic.com/v1";
/** Anthropic ephemeral prompt-caching breakpoint. */
const CACHE_CONTROL = { anthropic: { cacheControl: { type: "ephemeral" as const } } };
@@ -117,7 +120,7 @@ export class AnthropicProvider extends BaseProvider {
private anthropic: AnthropicSDKProvider;
constructor(apiKey: string, baseURL?: string) {
- super();
+ super(apiKey, baseURL);
if (!apiKey) {
throw new Error("API key is required for Anthropic provider");
}
@@ -128,6 +131,21 @@ export class AnthropicProvider extends BaseProvider {
return this.anthropic(modelId);
}
+ /** List models from Anthropic's `/models` endpoint (all are chat models). */
+ protected override async fetchRemoteModels(): Promise<RemoteModel[] | null> {
+ const payload = await this.fetchJson(`${this.baseURL ?? OFFICIAL_BASE_URL}/models?limit=1000`, {
+ "x-api-key": this.apiKey,
+ "anthropic-version": "2023-06-01"
+ });
+ const data = (payload as { data?: unknown }).data;
+ if (!Array.isArray(data)) {
+ throw new Error("Unexpected /models response shape");
+ }
+ return data
+ .filter((m): m is { id: string; display_name?: string } => typeof (m as { id?: unknown }).id === "string")
+ .map(m => ({ id: m.id, name: m.display_name }));
+ }
+
protected override addWebSearchTool(tools: ToolSet): void {
tools.web_search = this.anthropic.tools.webSearch_20250305({
maxUses: 5
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 6ac27825e9..563ea0878c 100644
--- a/apps/server/src/services/llm/providers/base_provider.spec.ts
+++ b/apps/server/src/services/llm/providers/base_provider.spec.ts
@@ -3,7 +3,7 @@ import { encodeUtf8 } from "@triliumnext/core/src/services/utils/binary.js";
import type { LanguageModel } from "ai";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { LlmProviderConfig, ModelInfo } from "../types.js";
+import type { LlmProviderConfig } from "../types.js";
const { streamTextMock, generateTextMock, noteMetaMock, errorLogMock, beccaStub } = vi.hoisted(() => ({
streamTextMock: vi.fn((..._args: any[]) => ({}) as any),
@@ -28,7 +28,8 @@ vi.mock("@triliumnext/core", async (importOriginal) => {
return {
...actual,
becca: { ...actual.becca, ...beccaStub },
- getLog: () => ({ ...actual.getLog(), error: errorLogMock })
+ // Spreading the real logger loses prototype methods (e.g. info), so stub it too.
+ getLog: () => ({ ...actual.getLog(), error: errorLogMock, info: vi.fn() })
};
});
@@ -43,8 +44,9 @@ vi.mock("../tools/index.js", () => ({
}));
import { BaseProvider, buildModelList, buildModelMessage } from "./base_provider.js";
+import type { RemoteModel } from "./model_listing.js";
-const TEST_MODELS: Omit<ModelInfo, "costMultiplier">[] = [
+const TEST_MODELS: Parameters<typeof buildModelList>[0] = [
{ id: "cheap", name: "Cheap", pricing: { input: 1, output: 2 } },
{ id: "mid", name: "Mid", pricing: { input: 2, output: 4 }, isDefault: true },
{ id: "spendy", name: "Spendy", pricing: { input: 10, output: 30 } }
@@ -60,12 +62,17 @@ class TestProvider extends BaseProvider {
protected modelPricing = BUILT_PRICING;
public createdModelIds: string[] = [];
+ public fetchRemoteModelsMock = vi.fn<() => Promise<RemoteModel[] | null>>(async () => null);
protected createModel(modelId: string): LanguageModel {
this.createdModelIds.push(modelId);
return { modelId } as unknown as LanguageModel;
}
+ protected override fetchRemoteModels(): Promise<RemoteModel[] | null> {
+ return this.fetchRemoteModelsMock();
+ }
+
// Expose protected helpers for direct assertions.
public callApplyNoteHint(m: LlmMessage[], c: LlmProviderConfig) {
return this.applyNoteHint(m, c);
@@ -115,6 +122,52 @@ describe("buildModelList", () => {
});
});
+describe("listModels", () => {
+ it("returns the curated list when the provider has no dynamic listing", async () => {
+ const provider = new TestProvider();
+ await expect(provider.listModels()).resolves.toBe(BUILT_MODELS);
+ });
+
+ it("merges the remote list with curated 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 });
+ expect(models[1].pricing).toBeUndefined();
+
+ // Second call is served from the cache — no second fetch.
+ await expect(provider.listModels()).resolves.toBe(models);
+ expect(provider.fetchRemoteModelsMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("deduplicates concurrent calls into a single fetch", async () => {
+ const provider = new TestProvider();
+ provider.fetchRemoteModelsMock.mockResolvedValue([{ id: "mid" }]);
+
+ const [a, b] = await Promise.all([provider.listModels(), provider.listModels()]);
+ expect(a).toBe(b);
+ expect(provider.fetchRemoteModelsMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("falls back to the curated list on fetch failure and cools down before retrying", 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);
+ });
+
+ it("falls back to the curated list when the remote list is empty", async () => {
+ const provider = new TestProvider();
+ provider.fetchRemoteModelsMock.mockResolvedValue([]);
+ await expect(provider.listModels()).resolves.toBe(BUILT_MODELS);
+ });
+});
+
describe("buildModelMessage", () => {
beforeEach(() => {
beccaStub.getAttachment.mockReset();
diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.ts
index 536c412759..6f00667d7c 100644
--- a/apps/server/src/services/llm/providers/base_provider.ts
+++ b/apps/server/src/services/llm/providers/base_provider.ts
@@ -4,17 +4,26 @@
*/
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 { buildNoteHint } from "./note_hint.js";
import { buildSystemPrompt as composeSystemPrompt } from "./system_prompt.js";
const DEFAULT_MAX_TOKENS = 8096;
const TITLE_MAX_TOKENS = 30;
+/** 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.
@@ -64,10 +73,16 @@ export function buildModelMessage(m: LlmMessage): ModelMessage {
return { role: "user", content: resolved };
}
+/**
+ * A curated (hard-coded) model definition. Unlike dynamically discovered
+ * models, curated entries always carry pricing.
+ */
+type CuratedModel = Omit<ModelInfo, "costMultiplier"> & { pricing: ModelPricing };
+
/**
* Build the model list with cost multipliers from a base model definition array.
*/
-export function buildModelList(baseModels: Omit<ModelInfo, "costMultiplier">[]): {
+export function buildModelList(baseModels: CuratedModel[]): {
models: ModelInfo[];
pricing: Record<string, ModelPricing>;
} {
@@ -94,9 +109,82 @@ export abstract class BaseProvider implements LlmProvider {
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. */
+ protected baseURL?: string;
+
+ private modelListCache?: { models: ModelInfo[]; fetchedAt: number };
+ private modelListInFlight?: Promise<ModelInfo[]>;
+ private modelListFailedAt?: number;
+
+ constructor(apiKey = "", baseURL?: string) {
+ this.apiKey = apiKey;
+ this.baseURL = baseURL?.replace(/\/+$/, "") || undefined;
+ }
+
/** Create a language model instance for the given model ID. */
protected abstract createModel(modelId: string): LanguageModel;
+ /**
+ * 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}.
+ */
+ protected async fetchRemoteModels(): Promise<RemoteModel[] | null> {
+ return null;
+ }
+
+ /**
+ * GET a JSON document with the standard model-listing timeout. Shared
+ * helper for {@link fetchRemoteModels} implementations.
+ */
+ 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) {
+ throw new Error(`HTTP ${response.status} from ${url}`);
+ }
+ return await response.json();
+ }
+
+ /**
+ * 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).
+ */
+ 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;
+ });
+ }
+ return this.modelListInFlight;
+ }
+
+ 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;
+ }
+ }
+
/**
* Build the system prompt. Delegates to the shared `system_prompt` module;
* kept as an overridable method so providers can post-process the result
diff --git a/apps/server/src/services/llm/providers/google.spec.ts b/apps/server/src/services/llm/providers/google.spec.ts
index 6eb6027941..614ec073a8 100644
--- a/apps/server/src/services/llm/providers/google.spec.ts
+++ b/apps/server/src/services/llm/providers/google.spec.ts
@@ -1,5 +1,5 @@
import type { LlmMessage } from "@triliumnext/commons";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const createGoogleMock = vi.fn();
const googleSearchMock = vi.fn(() => ({ kind: "google_search" }));
@@ -169,3 +169,47 @@ describe("GoogleProvider tool handling", () => {
expect(opts.stopWhen).toBeDefined();
});
});
+
+describe("GoogleProvider model listing", () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ const okJson = (body: unknown) => ({ ok: true, json: async () => body });
+
+ it("keeps generateContent-capable chat models, stripping the models/ prefix", async () => {
+ fetchMock.mockResolvedValue(okJson({
+ models: [
+ { name: "models/gemini-2.5-flash", displayName: "Gemini 2.5 Flash", inputTokenLimit: 1048576, supportedGenerationMethods: ["generateContent"] },
+ { name: "models/gemini-3-pro", displayName: "Gemini 3 Pro", inputTokenLimit: 2097152, supportedGenerationMethods: ["generateContent"] },
+ { name: "models/text-embedding-004", supportedGenerationMethods: ["embedContent"] },
+ { name: "models/imagen-3.0-generate-002", supportedGenerationMethods: ["generateContent"] }
+ ]
+ }));
+ const provider = new GoogleProvider("g-key");
+
+ const models = await provider.listModels();
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000",
+ expect.objectContaining({ headers: { "x-goog-api-key": "g-key" } })
+ );
+ expect(models.map((m) => m.id)).toEqual(["gemini-2.5-flash", "gemini-3-pro"]);
+ // Curated entry keeps its metadata; the unknown one takes the API's
+ // display name and token limit.
+ expect(models[0]).toMatchObject({ name: "Gemini 2.5 Flash", isDefault: true });
+ expect(models[1]).toMatchObject({ name: "Gemini 3 Pro", contextWindow: 2097152 });
+ });
+
+ it("falls back to the curated list when the fetch fails", 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");
+ });
+});
diff --git a/apps/server/src/services/llm/providers/google.ts b/apps/server/src/services/llm/providers/google.ts
index 0560d0f701..61f1f0985c 100644
--- a/apps/server/src/services/llm/providers/google.ts
+++ b/apps/server/src/services/llm/providers/google.ts
@@ -1,10 +1,13 @@
import { createGoogleGenerativeAI, type GoogleGenerativeAIProvider } from "@ai-sdk/google";
-import { streamText, stepCountIs, type ToolSet } from "ai";
import type { LlmMessage } from "@triliumnext/commons";
-
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 { isGoogleChatModel, type RemoteModel } from "./model_listing.js";
+
+const OFFICIAL_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
/**
* Gemini 2.x models (every model we currently expose) cannot combine
@@ -62,7 +65,7 @@ export class GoogleProvider extends BaseProvider {
private google: GoogleGenerativeAIProvider;
constructor(apiKey: string, baseURL?: string) {
- super();
+ super(apiKey, baseURL);
if (!apiKey) {
throw new Error("API key is required for Google provider");
}
@@ -73,6 +76,31 @@ export class GoogleProvider extends BaseProvider {
return this.google(modelId);
}
+ /**
+ * List models from the Gemini API. Only `generateContent`-capable models
+ * are kept (the endpoint also lists embedding/imagen/veo models), and the
+ * `models/` id prefix is stripped to match what `createModel` expects.
+ */
+ protected override async fetchRemoteModels(): Promise<RemoteModel[] | null> {
+ const payload = await this.fetchJson(`${this.baseURL ?? OFFICIAL_BASE_URL}/models?pageSize=1000`, {
+ "x-goog-api-key": this.apiKey
+ });
+ const models = (payload as { models?: unknown }).models;
+ if (!Array.isArray(models)) {
+ throw new Error("Unexpected /models response shape");
+ }
+ return models
+ .filter((m): m is { name: string; displayName?: string; inputTokenLimit?: number; supportedGenerationMethods?: string[] } =>
+ typeof (m as { name?: unknown }).name === "string")
+ .filter(m => m.supportedGenerationMethods?.includes("generateContent"))
+ .map(m => ({
+ id: m.name.replace(/^models\//, ""),
+ name: m.displayName,
+ contextWindow: m.inputTokenLimit
+ }))
+ .filter(m => isGoogleChatModel(m.id));
+ }
+
protected override addWebSearchTool(tools: ToolSet): void {
tools.google_search = this.google.tools.googleSearch({});
}
diff --git a/apps/server/src/services/llm/providers/model_listing.spec.ts b/apps/server/src/services/llm/providers/model_listing.spec.ts
new file mode 100644
index 0000000000..8eb957107b
--- /dev/null
+++ b/apps/server/src/services/llm/providers/model_listing.spec.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from "vitest";
+
+import type { ModelInfo } from "../types.js";
+import { isGoogleChatModel, isOpenAiChatModel, mergeModelLists } 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 }
+];
+
+describe("mergeModelLists", () => {
+ it("keeps curated metadata for known models and appends unknown ones alphabetically", () => {
+ const merged = mergeModelLists(CURATED, [
+ { id: "gpt-9" },
+ { id: "gpt-4.1-mini" },
+ { id: "gpt-5" },
+ { 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.
+ expect(merged[2]).toEqual({ id: "gpt-5", name: "gpt-5", contextWindow: undefined });
+ });
+
+ 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"]);
+ });
+
+ it("uses the remote display name and context window when provided", () => {
+ const merged = mergeModelLists([], [{ id: "llama3.2", name: "Llama 3.2", contextWindow: 131072 }]);
+ expect(merged[0]).toMatchObject({ id: "llama3.2", name: "Llama 3.2", contextWindow: 131072, isDefault: true });
+ });
+
+ it("fills a curated model's missing context window from the remote data", () => {
+ const curated: ModelInfo[] = [{ id: "m", name: "M", pricing: { input: 1, output: 1 } }];
+ const merged = mergeModelLists(curated, [{ id: "m", contextWindow: 32000 }]);
+ expect(merged[0].contextWindow).toBe(32000);
+ });
+
+ it("promotes the first model to default when the curated default is unavailable", () => {
+ const merged = mergeModelLists(CURATED, [{ id: "gpt-4o" }, { id: "custom-model" }]);
+ expect(merged.map(m => [m.id, m.isDefault ?? false])).toEqual([
+ ["gpt-4o", true],
+ ["custom-model", false]
+ ]);
+ });
+
+ it("returns an empty list when the remote list shares nothing and is empty", () => {
+ expect(mergeModelLists(CURATED, [])).toEqual([]);
+ });
+});
+
+describe("isOpenAiChatModel", () => {
+ it("keeps chat model families, including unknown future ones", () => {
+ for (const id of ["gpt-4.1", "gpt-5", "o3", "o4-mini", "chatgpt-4o-latest"]) {
+ expect(isOpenAiChatModel(id), id).toBe(true);
+ }
+ });
+
+ it("drops non-chat families", () => {
+ for (const id of [
+ "text-embedding-3-large",
+ "whisper-1",
+ "tts-1-hd",
+ "dall-e-3",
+ "omni-moderation-latest",
+ "gpt-4o-realtime-preview",
+ "gpt-4o-audio-preview",
+ "gpt-4o-transcribe",
+ "gpt-image-1",
+ "babbage-002",
+ "davinci-002",
+ "gpt-4o-search-preview"
+ ]) {
+ expect(isOpenAiChatModel(id), id).toBe(false);
+ }
+ });
+});
+
+describe("isGoogleChatModel", () => {
+ it("keeps Gemini chat models", () => {
+ for (const id of ["gemini-2.5-pro", "gemini-2.5-flash", "gemini-3-pro"]) {
+ expect(isGoogleChatModel(id), id).toBe(true);
+ }
+ });
+
+ it("drops embedding and media-generation models", () => {
+ for (const id of ["text-embedding-004", "gemini-embedding-001", "aqa", "imagen-3.0-generate-002", "veo-2.0-generate-001", "gemini-2.5-flash-preview-tts"]) {
+ expect(isGoogleChatModel(id), id).toBe(false);
+ }
+ });
+});
diff --git a/apps/server/src/services/llm/providers/model_listing.ts b/apps/server/src/services/llm/providers/model_listing.ts
new file mode 100644
index 0000000000..5708110f9a
--- /dev/null
+++ b/apps/server/src/services/llm/providers/model_listing.ts
@@ -0,0 +1,85 @@
+/**
+ * Pure logic for dynamic model listing: merging a live-fetched model list with
+ * the curated (hard-coded) metadata, and filtering provider noise. Kept free of
+ * I/O so it can be unit-tested in isolation — the fetching itself lives in the
+ * individual providers.
+ */
+
+import type { ModelInfo } from "../types.js";
+
+/**
+ * A model as reported by a provider's models endpoint. Only what the listing
+ * APIs actually return — pricing is never part of it.
+ */
+export interface RemoteModel {
+ id: string;
+ /** Human-readable name, when the API provides one (e.g. Anthropic's `display_name`). */
+ name?: string;
+ /** Context window in tokens, when the API provides one (e.g. Google's `inputTokenLimit`). */
+ contextWindow?: number;
+}
+
+/**
+ * Merge a live-fetched model list with the curated metadata list.
+ *
+ * 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.
+ *
+ * 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.
+ */
+export function mergeModelLists(curated: ModelInfo[], remote: RemoteModel[]): ModelInfo[] {
+ const remoteById = new Map(remote.map(m => [m.id, m]));
+
+ const known = curated
+ .filter(m => remoteById.has(m.id))
+ .map(m => {
+ const remoteModel = remoteById.get(m.id);
+ return { ...m, contextWindow: m.contextWindow ?? remoteModel?.contextWindow };
+ });
+
+ const curatedIds = new Set(curated.map(m => m.id));
+ const unknown = remote
+ .filter(m => !curatedIds.has(m.id))
+ .sort((a, b) => a.id.localeCompare(b.id))
+ .map<ModelInfo>(m => ({
+ id: m.id,
+ name: m.name ?? m.id,
+ contextWindow: m.contextWindow
+ }));
+
+ const merged = [...known, ...unknown];
+ if (merged.length > 0 && !merged.some(m => m.isDefault)) {
+ merged[0] = { ...merged[0], isDefault: true };
+ }
+ return merged;
+}
+
+/**
+ * Model-id families returned by the official OpenAI `/models` endpoint that are
+ * not chat models (embeddings, audio, image, moderation, legacy completions).
+ * Only applied on the official endpoint — custom base URLs (Ollama, vLLM,
+ * LiteLLM, LM Studio) list exactly what the user installed, so nothing is
+ * filtered there.
+ */
+const OPENAI_NON_CHAT = /embedding|whisper|tts|dall-e|moderation|realtime|audio|transcribe|image|babbage|davinci|search/i;
+
+export function isOpenAiChatModel(id: string): boolean {
+ return !OPENAI_NON_CHAT.test(id);
+}
+
+/**
+ * Non-chat Gemini model families. The primary filter is the API's
+ * `supportedGenerationMethods` (must include `generateContent`), but a few
+ * non-conversational models pass that check too, so they are excluded by id.
+ */
+const GOOGLE_NON_CHAT = /embedding|aqa|imagen|veo|tts/i;
+
+export function isGoogleChatModel(id: string): boolean {
+ return !GOOGLE_NON_CHAT.test(id);
+}
diff --git a/apps/server/src/services/llm/providers/openai.spec.ts b/apps/server/src/services/llm/providers/openai.spec.ts
index 9161163d47..f1c00bde9a 100644
--- a/apps/server/src/services/llm/providers/openai.spec.ts
+++ b/apps/server/src/services/llm/providers/openai.spec.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
+import { afterEach, describe, expect, it, vi, beforeEach } from "vitest";
const createOpenAIMock = vi.fn();
const webSearchMock = vi.fn(() => ({ kind: "web_search" }));
@@ -81,3 +81,58 @@ describe("OpenAiProvider chat", () => {
expect(opts.stopWhen).toBeDefined();
});
});
+
+describe("OpenAiProvider model listing", () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ const okJson = (body: unknown) => ({ ok: true, json: async () => body });
+
+ it("fetches the official endpoint with the API key and filters non-chat models", async () => {
+ fetchMock.mockResolvedValue(okJson({ data: [{ id: "gpt-4.1" }, { id: "whisper-1" }, { id: "text-embedding-3-large" }, { id: "gpt-9" }] }));
+ const provider = new OpenAiProvider("sk-test");
+
+ const models = await provider.listModels();
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://api.openai.com/v1/models",
+ expect.objectContaining({ headers: { Authorization: "Bearer sk-test" } })
+ );
+ expect(models.map((m) => m.id)).toEqual(["gpt-4.1", "gpt-9"]);
+ // Curated metadata survives the merge; unknown models have none.
+ expect(models[0]).toMatchObject({ name: "GPT-4.1", isDefault: true });
+ expect(models[1].pricing).toBeUndefined();
+ });
+
+ it("lists a custom endpoint unfiltered (self-hosted Ollama/vLLM)", async () => {
+ fetchMock.mockResolvedValue(okJson({ data: [{ id: "llama3.2" }, { id: "nomic-embed-text" }] }));
+ // Trailing slash on the user-entered base URL is normalized away.
+ const provider = new OpenAiProvider("unused", "http://localhost:11434/v1/");
+
+ const models = await provider.listModels();
+ expect(fetchMock).toHaveBeenCalledWith("http://localhost:11434/v1/models", expect.anything());
+ expect(models.map((m) => m.id)).toEqual(["llama3.2", "nomic-embed-text"]);
+ // None of the curated models exist here → the first model becomes default.
+ expect(models[0].isDefault).toBe(true);
+ });
+
+ it("falls back to the curated list on HTTP errors", 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");
+ });
+
+ it("falls back to the curated list on 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");
+ });
+});
diff --git a/apps/server/src/services/llm/providers/openai.ts b/apps/server/src/services/llm/providers/openai.ts
index 1a48981ce5..ea7de44242 100644
--- a/apps/server/src/services/llm/providers/openai.ts
+++ b/apps/server/src/services/llm/providers/openai.ts
@@ -2,6 +2,9 @@ import { createOpenAI, type OpenAIProvider as OpenAISDKProvider } from "@ai-sdk/
import type { ToolSet } from "ai";
import { BaseProvider, buildModelList } from "./base_provider.js";
+import { isOpenAiChatModel, type RemoteModel } from "./model_listing.js";
+
+const OFFICIAL_BASE_URL = "https://api.openai.com/v1";
/**
* Available OpenAI models with pricing (USD per million tokens).
@@ -67,7 +70,7 @@ export class OpenAiProvider extends BaseProvider {
private openai: OpenAISDKProvider;
constructor(apiKey: string, baseURL?: string) {
- super();
+ super(apiKey, baseURL);
if (!apiKey) {
throw new Error("API key is required for OpenAI provider");
}
@@ -78,6 +81,26 @@ export class OpenAiProvider extends BaseProvider {
return this.openai(modelId);
}
+ /**
+ * List models from the OpenAI-compatible `/models` endpoint. On the
+ * official endpoint the list is full of non-chat models (embeddings,
+ * whisper, TTS, ...), which are filtered out; a custom baseURL (Ollama,
+ * vLLM, LM Studio, LiteLLM) lists exactly what the endpoint offers.
+ */
+ protected override async fetchRemoteModels(): Promise<RemoteModel[] | null> {
+ const payload = await this.fetchJson(`${this.baseURL ?? OFFICIAL_BASE_URL}/models`, {
+ Authorization: `Bearer ${this.apiKey}`
+ });
+ const data = (payload as { data?: unknown }).data;
+ if (!Array.isArray(data)) {
+ throw new Error("Unexpected /models response shape");
+ }
+ const models = data
+ .filter((m): m is { id: string } => typeof (m as { id?: unknown }).id === "string")
+ .map(m => ({ id: m.id }));
+ return this.baseURL ? models : models.filter(m => isOpenAiChatModel(m.id));
+ }
+
protected override addWebSearchTool(tools: ToolSet): void {
tools.web_search = this.openai.tools.webSearch();
}
diff --git a/apps/server/src/services/llm/types.ts b/apps/server/src/services/llm/types.ts
index 451f80ca5b..65b408322d 100644
--- a/apps/server/src/services/llm/types.ts
+++ b/apps/server/src/services/llm/types.ts
@@ -40,8 +40,12 @@ export interface ModelInfo {
name: string;
/** Provider type that owns this model (e.g., "anthropic", "openai") */
provider?: string;
- /** Pricing per million tokens */
- pricing: ModelPricing;
+ /** ID of the provider configuration this model was listed from */
+ providerId?: string;
+ /** User-given name of the provider configuration (e.g. "My Ollama") */
+ providerName?: string;
+ /** Pricing per million tokens. Absent for dynamically discovered models with unknown pricing. */
+ pricing?: ModelPricing;
/** Whether this is the default model */
isDefault?: boolean;
/** Cost multiplier relative to the cheapest model (1x = cheapest) */
@@ -87,9 +91,24 @@ export interface LlmProvider {
/**
* Get list of available models for this provider.
+ *
+ * This is the static, curated list — instant and offline-safe. Used for
+ * default-model and display-name lookups, and as the fallback when dynamic
+ * listing is unavailable or fails.
*/
getAvailableModels(): ModelInfo[];
+ /**
+ * Dynamically list the models actually available on the provider's
+ * endpoint, merged with curated metadata (names, pricing, context windows)
+ * 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.
+ */
+ listModels?(): Promise<ModelInfo[]>;
+
/**
* Generate a short title summarizing a message.
* Used for auto-renaming chat notes. Should use a fast, cheap model.
diff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.ts
index fd4a1b24b1..ee5f1aaa74 100644
--- a/packages/commons/src/lib/llm_api.ts
+++ b/packages/commons/src/lib/llm_api.ts
@@ -77,7 +77,14 @@ export interface LlmCitation {
* Configuration for LLM chat requests.
*/
export interface LlmChatConfig {
+ /** Provider type (e.g. "anthropic"). Kept for chats saved before {@link providerId} existed. */
provider?: string;
+ /**
+ * ID of the provider configuration to route through. Preferred over
+ * {@link provider} — it disambiguates multiple configs of the same type
+ * (e.g. a real OpenAI key plus a self-hosted Ollama endpoint).
+ */
+ providerId?: string;
model?: string;
systemPrompt?: string;
/** Enable web search tool */
@@ -114,8 +121,12 @@ export interface LlmModelInfo {
name: string;
/** Provider type that owns this model (e.g., "anthropic", "openai") */
provider?: string;
- /** Pricing per million tokens */
- pricing: LlmModelPricing;
+ /** ID of the provider configuration this model was listed from */
+ providerId?: string;
+ /** User-given name of the provider configuration (e.g. "My Ollama") */
+ providerName?: string;
+ /** Pricing per million tokens. Absent for dynamically discovered models with unknown pricing. */
+ pricing?: LlmModelPricing;
/** Whether this is the default model */
isDefault?: boolean;
/** Whether this is a legacy/older model */