Skip to content

Build your personal knowledge base with Trilium Notes

refactor(llm): deduplicate logic between providers

Elian Dorana45c1818a5a8
diff --git a/apps/server/src/services/llm/providers/anthropic.ts b/apps/server/src/services/llm/providers/anthropic.ts
index 688ef9afa4..d444b34a51 100644
--- a/apps/server/src/services/llm/providers/anthropic.ts
+++ b/apps/server/src/services/llm/providers/anthropic.ts
@@ -1,30 +1,15 @@
import { createAnthropic, type AnthropicProvider as AnthropicSDKProvider } from "@ai-sdk/anthropic";
-import { generateText, streamText, stepCountIs, type CoreMessage, type ToolSet } from "ai";
+import { stepCountIs, streamText, type CoreMessage, type ToolSet } from "ai";
import type { LlmMessage } from "@triliumnext/commons";
-import becca from "../../../becca/becca.js";
-import { getSkillsSummary } from "../skills/index.js";
-import { noteTools, attributeTools, hierarchyTools, skillTools, currentNoteTools } from "../tools/index.js";
-import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";
-
-const DEFAULT_MODEL = "claude-sonnet-4-6";
-const DEFAULT_MAX_TOKENS = 8096;
-const TITLE_MODEL = "claude-haiku-4-5-20251001";
-const TITLE_MAX_TOKENS = 30;
-
-/**
- * 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;
-}
+import type { LlmProviderConfig, StreamResult } from "../types.js";
+import { BaseProvider, buildModelList } from "./base_provider.js";
/**
* Available Anthropic models with pricing (USD per million tokens).
* Source: https://docs.anthropic.com/en/docs/about-claude/models
*/
-const BASE_MODELS: Omit<ModelInfo, "costMultiplier">[] = [
+const { models: AVAILABLE_MODELS, pricing: MODEL_PRICING } = buildModelList([
// ===== Current Models =====
{
id: "claude-sonnet-4-6",
@@ -50,7 +35,7 @@ const BASE_MODELS: Omit<ModelInfo, "costMultiplier">[] = [
id: "claude-sonnet-4-5-20250929",
name: "Claude Sonnet 4.5",
pricing: { input: 3, output: 15 },
- contextWindow: 200000, // 1M available with beta header
+ contextWindow: 200000,
isLegacy: true
},
{
@@ -71,7 +56,7 @@ const BASE_MODELS: Omit<ModelInfo, "costMultiplier">[] = [
id: "claude-sonnet-4-20250514",
name: "Claude Sonnet 4.0",
pricing: { input: 3, output: 15 },
- contextWindow: 200000, // 1M available with beta header
+ contextWindow: 200000,
isLegacy: true
},
{
@@ -81,77 +66,44 @@ const BASE_MODELS: Omit<ModelInfo, "costMultiplier">[] = [
contextWindow: 200000,
isLegacy: true
}
-];
-
-// Use default model (Sonnet) as baseline for cost multiplier
-const baselineModel = BASE_MODELS.find(m => m.isDefault) || BASE_MODELS[0];
-const baselineCost = effectiveCost(baselineModel.pricing);
-
-// Build models with cost multipliers
-const AVAILABLE_MODELS: ModelInfo[] = BASE_MODELS.map(m => ({
- ...m,
- costMultiplier: Math.round((effectiveCost(m.pricing) / baselineCost) * 10) / 10
-}));
-
-// Build pricing lookup from available models
-const MODEL_PRICING: Record<string, ModelPricing> = Object.fromEntries(
- AVAILABLE_MODELS.map(m => [m.id, m.pricing])
-);
-
-/**
- * Build a lightweight context hint about the current note (title + type only, no content).
- * The full content is available via the get_current_note tool.
- */
-function buildNoteHint(noteId: string): string | null {
- const note = becca.getNote(noteId);
- if (!note) {
- return null;
- }
+]);
- return `The user is currently viewing a ${note.type} note titled "${note.title}". Use the get_current_note tool to read its content if needed.`;
-}
-
-export class AnthropicProvider implements LlmProvider {
+export class AnthropicProvider extends BaseProvider {
name = "anthropic";
+ protected defaultModel = "claude-sonnet-4-6";
+ protected titleModel = "claude-haiku-4-5-20251001";
+ protected availableModels = AVAILABLE_MODELS;
+ protected modelPricing = MODEL_PRICING;
+
private anthropic: AnthropicSDKProvider;
constructor(apiKey: string) {
+ super();
if (!apiKey) {
throw new Error("API key is required for Anthropic provider");
}
this.anthropic = createAnthropic({ apiKey });
}
- chat(messages: LlmMessage[], config: LlmProviderConfig): StreamResult {
- let systemPrompt = config.systemPrompt || messages.find(m => m.role === "system")?.content;
- const chatMessages = messages.filter(m => m.role !== "system");
-
- // Add a lightweight hint about the current note (content available via tool)
- if (config.contextNoteId) {
- const noteHint = buildNoteHint(config.contextNoteId);
- if (noteHint) {
- systemPrompt = systemPrompt
- ? `${systemPrompt}\n\n${noteHint}`
- : noteHint;
- }
- }
+ protected createModel(modelId: string) {
+ return this.anthropic(modelId);
+ }
- // Add skills hint so the LLM knows to load skills before complex operations
- if (config.enableNoteTools) {
- const skillsHint = `You have access to skills that provide specialized instructions. Load a skill with the load_skill tool before performing complex operations.\n\nAvailable skills:\n${getSkillsSummary()}`;
- systemPrompt = systemPrompt
- ? `${systemPrompt}\n\n${skillsHint}`
- : skillsHint;
- }
+ /**
+ * Override chat to add Anthropic-specific features:
+ * - Prompt caching via providerOptions
+ * - Extended thinking
+ * - Web search tool
+ */
+ override chat(messages: LlmMessage[], config: LlmProviderConfig): StreamResult {
+ const systemPrompt = this.buildSystemPrompt(messages, config);
+ const chatMessages = messages.filter(m => m.role !== "system");
- // Convert to AI SDK message format with cache control breakpoints.
- // The system prompt and conversation history (all but the last user message)
- // are stable across turns, so we mark them for caching to reduce costs.
+ // Anthropic-specific: cache control breakpoints on system prompt and conversation history
const CACHE_CONTROL = { anthropic: { cacheControl: { type: "ephemeral" as const } } };
const coreMessages: CoreMessage[] = [];
- // System prompt as a cacheable message
if (systemPrompt) {
coreMessages.push({
role: "system",
@@ -160,29 +112,23 @@ export class AnthropicProvider implements LlmProvider {
});
}
- // Conversation messages
for (let i = 0; i < chatMessages.length; i++) {
const m = chatMessages[i];
const isLastBeforeNewTurn = i === chatMessages.length - 2;
coreMessages.push({
role: m.role as "user" | "assistant",
content: m.content,
- // Cache breakpoint on the second-to-last message:
- // everything up to here is identical across consecutive turns.
...(isLastBeforeNewTurn && { providerOptions: CACHE_CONTROL })
});
}
- const model = this.anthropic(config.model || DEFAULT_MODEL);
-
- // Build options for streamText
const streamOptions: Parameters<typeof streamText>[0] = {
- model,
+ model: this.createModel(config.model || this.defaultModel),
messages: coreMessages,
- maxOutputTokens: config.maxTokens || DEFAULT_MAX_TOKENS
+ maxOutputTokens: config.maxTokens || 8096
};
- // Enable extended thinking for deeper reasoning
+ // Anthropic-specific: extended thinking
if (config.enableExtendedThinking) {
const thinkingBudget = config.thinkingBudget || 10000;
streamOptions.providerOptions = {
@@ -194,13 +140,13 @@ export class AnthropicProvider implements LlmProvider {
}
};
streamOptions.maxOutputTokens = Math.max(
- streamOptions.maxOutputTokens || DEFAULT_MAX_TOKENS,
+ streamOptions.maxOutputTokens || 8096,
thinkingBudget + 4000
);
}
- // Build tools object
- const tools: ToolSet = {};
+ // Build tools (shared + Anthropic-specific web search)
+ const tools: ToolSet = this.buildTools(config);
if (config.enableWebSearch) {
tools.web_search = this.anthropic.tools.webSearch_20250305({
@@ -208,48 +154,12 @@ export class AnthropicProvider implements LlmProvider {
});
}
- if (config.contextNoteId) {
- Object.assign(tools, currentNoteTools(config.contextNoteId));
- }
-
- if (config.enableNoteTools) {
- Object.assign(tools, noteTools);
- Object.assign(tools, attributeTools);
- Object.assign(tools, hierarchyTools);
- Object.assign(tools, skillTools);
- }
-
if (Object.keys(tools).length > 0) {
streamOptions.tools = tools;
- // Allow multiple tool use cycles before final response
streamOptions.stopWhen = stepCountIs(5);
- // Let model decide when to use tools vs respond with text
streamOptions.toolChoice = "auto";
}
return streamText(streamOptions);
}
-
- getModelPricing(model: string): ModelPricing | undefined {
- return MODEL_PRICING[model];
- }
-
- getAvailableModels(): ModelInfo[] {
- return AVAILABLE_MODELS;
- }
-
- async generateTitle(firstMessage: string): Promise<string> {
- const { text } = await generateText({
- model: this.anthropic(TITLE_MODEL),
- maxOutputTokens: TITLE_MAX_TOKENS,
- messages: [
- {
- role: "user",
- content: `Summarize the following message as a very short chat title (max 6 words). Reply with ONLY the title, no quotes or punctuation at the end.\n\nMessage: ${firstMessage}`
- }
- ]
- });
-
- return text.trim();
- }
}
diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.ts
new file mode 100644
index 0000000000..bcc22bd3c0
--- /dev/null
+++ b/apps/server/src/services/llm/providers/base_provider.ts
@@ -0,0 +1,179 @@
+/**
+ * Base class for LLM providers. Handles shared logic for system prompt building,
+ * tool assembly, model pricing, and title generation.
+ */
+
+import { generateText, streamText, stepCountIs, type CoreMessage, type ToolSet } from "ai";
+import type { LanguageModel } from "ai";
+import type { LlmMessage } from "@triliumnext/commons";
+
+import becca from "../../../becca/becca.js";
+import { getSkillsSummary } from "../skills/index.js";
+import { noteTools, attributeTools, hierarchyTools, skillTools, currentNoteTools } from "../tools/index.js";
+import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";
+
+const DEFAULT_MAX_TOKENS = 8096;
+const TITLE_MAX_TOKENS = 30;
+
+/**
+ * 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;
+}
+
+/**
+ * Build a lightweight context hint about the current note (title + type only, no content).
+ */
+function buildNoteHint(noteId: string): string | null {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return null;
+ }
+
+ return `The user is currently viewing a ${note.type} note titled "${note.title}". Use the get_current_note tool to read its content if needed.`;
+}
+
+/**
+ * Build the model list with cost multipliers from a base model definition array.
+ */
+export function buildModelList(baseModels: Omit<ModelInfo, "costMultiplier">[]): {
+ 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 };
+}
+
+export abstract class BaseProvider implements LlmProvider {
+ abstract name: string;
+
+ protected abstract defaultModel: string;
+ protected abstract titleModel: string;
+ protected abstract availableModels: ModelInfo[];
+ protected abstract modelPricing: Record<string, ModelPricing>;
+
+ /** Create a language model instance for the given model ID. */
+ protected abstract createModel(modelId: string): LanguageModel;
+
+ /**
+ * Build the system prompt with note hints and skills summary.
+ */
+ protected buildSystemPrompt(messages: LlmMessage[], config: LlmProviderConfig): string | undefined {
+ let systemPrompt = config.systemPrompt || messages.find(m => m.role === "system")?.content;
+
+ if (config.contextNoteId) {
+ const noteHint = buildNoteHint(config.contextNoteId);
+ if (noteHint) {
+ systemPrompt = systemPrompt
+ ? `${systemPrompt}\n\n${noteHint}`
+ : noteHint;
+ }
+ }
+
+ if (config.enableNoteTools) {
+ const skillsHint = `You have access to skills that provide specialized instructions. Load a skill with the load_skill tool before performing complex operations.\n\nAvailable skills:\n${getSkillsSummary()}`;
+ systemPrompt = systemPrompt
+ ? `${systemPrompt}\n\n${skillsHint}`
+ : skillsHint;
+ }
+
+ return systemPrompt;
+ }
+
+ /**
+ * Build the CoreMessage array from LlmMessages (no provider-specific options).
+ */
+ protected buildMessages(chatMessages: LlmMessage[], systemPrompt: string | undefined): CoreMessage[] {
+ const coreMessages: CoreMessage[] = [];
+
+ if (systemPrompt) {
+ coreMessages.push({ role: "system", content: systemPrompt });
+ }
+
+ for (const m of chatMessages) {
+ coreMessages.push({
+ role: m.role as "user" | "assistant",
+ content: m.content
+ });
+ }
+
+ return coreMessages;
+ }
+
+ /**
+ * Build the tool set based on config.
+ */
+ protected buildTools(config: LlmProviderConfig): ToolSet {
+ const tools: ToolSet = {};
+
+ if (config.contextNoteId) {
+ Object.assign(tools, currentNoteTools(config.contextNoteId));
+ }
+
+ if (config.enableNoteTools) {
+ Object.assign(tools, noteTools);
+ Object.assign(tools, attributeTools);
+ Object.assign(tools, hierarchyTools);
+ Object.assign(tools, skillTools);
+ }
+
+ return tools;
+ }
+
+ chat(messages: LlmMessage[], config: LlmProviderConfig): StreamResult {
+ const systemPrompt = this.buildSystemPrompt(messages, config);
+ const chatMessages = messages.filter(m => m.role !== "system");
+ const coreMessages = this.buildMessages(chatMessages, systemPrompt);
+
+ const streamOptions: Parameters<typeof streamText>[0] = {
+ model: this.createModel(config.model || this.defaultModel),
+ messages: coreMessages,
+ maxOutputTokens: config.maxTokens || DEFAULT_MAX_TOKENS
+ };
+
+ const tools = this.buildTools(config);
+ if (Object.keys(tools).length > 0) {
+ streamOptions.tools = tools;
+ streamOptions.stopWhen = stepCountIs(5);
+ streamOptions.toolChoice = "auto";
+ }
+
+ return streamText(streamOptions);
+ }
+
+ getModelPricing(model: string): ModelPricing | undefined {
+ return this.modelPricing[model];
+ }
+
+ getAvailableModels(): ModelInfo[] {
+ return this.availableModels;
+ }
+
+ async generateTitle(firstMessage: string): Promise<string> {
+ const { text } = await generateText({
+ model: this.createModel(this.titleModel),
+ maxOutputTokens: TITLE_MAX_TOKENS,
+ messages: [
+ {
+ role: "user",
+ content: `Summarize the following message as a very short chat title (max 6 words). Reply with ONLY the title, no quotes or punctuation at the end.\n\nMessage: ${firstMessage}`
+ }
+ ]
+ });
+
+ return text.trim();
+ }
+}
diff --git a/apps/server/src/services/llm/providers/openai.ts b/apps/server/src/services/llm/providers/openai.ts
index c58399aa94..a44ac9505b 100644
--- a/apps/server/src/services/llm/providers/openai.ts
+++ b/apps/server/src/services/llm/providers/openai.ts
@@ -1,29 +1,12 @@
import { createOpenAI, type OpenAIProvider as OpenAISDKProvider } from "@ai-sdk/openai";
-import { generateText, streamText, stepCountIs, type CoreMessage, type ToolSet } from "ai";
-import type { LlmMessage } from "@triliumnext/commons";
-import becca from "../../../becca/becca.js";
-import { getSkillsSummary } from "../skills/index.js";
-import { noteTools, attributeTools, hierarchyTools, skillTools, currentNoteTools } from "../tools/index.js";
-import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";
-
-const DEFAULT_MODEL = "gpt-4.1";
-const DEFAULT_MAX_TOKENS = 8096;
-const TITLE_MODEL = "gpt-4.1-mini";
-const TITLE_MAX_TOKENS = 30;
-
-/**
- * Calculate effective cost for comparison (weighted average: 1 input + 3 output).
- */
-function effectiveCost(pricing: ModelPricing): number {
- return (pricing.input + 3 * pricing.output) / 4;
-}
+import { BaseProvider, buildModelList } from "./base_provider.js";
/**
* Available OpenAI models with pricing (USD per million tokens).
* Source: https://platform.openai.com/docs/pricing
*/
-const BASE_MODELS: Omit<ModelInfo, "costMultiplier">[] = [
+const { models: AVAILABLE_MODELS, pricing: MODEL_PRICING } = buildModelList([
// ===== Current Models =====
{
id: "gpt-4.1",
@@ -71,132 +54,26 @@ const BASE_MODELS: Omit<ModelInfo, "costMultiplier">[] = [
contextWindow: 128000,
isLegacy: true
}
-];
-
-const baselineModel = BASE_MODELS.find(m => m.isDefault) || BASE_MODELS[0];
-const baselineCost = effectiveCost(baselineModel.pricing);
+]);
-const AVAILABLE_MODELS: ModelInfo[] = BASE_MODELS.map(m => ({
- ...m,
- costMultiplier: Math.round((effectiveCost(m.pricing) / baselineCost) * 10) / 10
-}));
-
-const MODEL_PRICING: Record<string, ModelPricing> = Object.fromEntries(
- AVAILABLE_MODELS.map(m => [m.id, m.pricing])
-);
-
-/**
- * Build a lightweight context hint about the current note.
- */
-function buildNoteHint(noteId: string): string | null {
- const note = becca.getNote(noteId);
- if (!note) {
- return null;
- }
-
- return `The user is currently viewing a ${note.type} note titled "${note.title}". Use the get_current_note tool to read its content if needed.`;
-}
-
-export class OpenAiProvider implements LlmProvider {
+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;
+
private openai: OpenAISDKProvider;
constructor(apiKey: string) {
+ super();
if (!apiKey) {
throw new Error("API key is required for OpenAI provider");
}
this.openai = createOpenAI({ apiKey });
}
- chat(messages: LlmMessage[], config: LlmProviderConfig): StreamResult {
- let systemPrompt = config.systemPrompt || messages.find(m => m.role === "system")?.content;
- const chatMessages = messages.filter(m => m.role !== "system");
-
- // Add a lightweight hint about the current note
- if (config.contextNoteId) {
- const noteHint = buildNoteHint(config.contextNoteId);
- if (noteHint) {
- systemPrompt = systemPrompt
- ? `${systemPrompt}\n\n${noteHint}`
- : noteHint;
- }
- }
-
- // Add skills hint
- if (config.enableNoteTools) {
- const skillsHint = `You have access to skills that provide specialized instructions. Load a skill with the load_skill tool before performing complex operations.\n\nAvailable skills:\n${getSkillsSummary()}`;
- systemPrompt = systemPrompt
- ? `${systemPrompt}\n\n${skillsHint}`
- : skillsHint;
- }
-
- const coreMessages: CoreMessage[] = [];
-
- if (systemPrompt) {
- coreMessages.push({
- role: "system",
- content: systemPrompt
- });
- }
-
- for (const m of chatMessages) {
- coreMessages.push({
- role: m.role as "user" | "assistant",
- content: m.content
- });
- }
-
- const model = this.openai(config.model || DEFAULT_MODEL);
-
- const streamOptions: Parameters<typeof streamText>[0] = {
- model,
- messages: coreMessages,
- maxOutputTokens: config.maxTokens || DEFAULT_MAX_TOKENS
- };
-
- // Build tools object
- const tools: ToolSet = {};
-
- if (config.contextNoteId) {
- Object.assign(tools, currentNoteTools(config.contextNoteId));
- }
-
- if (config.enableNoteTools) {
- Object.assign(tools, noteTools);
- Object.assign(tools, attributeTools);
- Object.assign(tools, hierarchyTools);
- Object.assign(tools, skillTools);
- }
-
- if (Object.keys(tools).length > 0) {
- streamOptions.tools = tools;
- streamOptions.stopWhen = stepCountIs(5);
- streamOptions.toolChoice = "auto";
- }
-
- return streamText(streamOptions);
- }
-
- getModelPricing(model: string): ModelPricing | undefined {
- return MODEL_PRICING[model];
- }
-
- getAvailableModels(): ModelInfo[] {
- return AVAILABLE_MODELS;
- }
-
- async generateTitle(firstMessage: string): Promise<string> {
- const { text } = await generateText({
- model: this.openai(TITLE_MODEL),
- maxOutputTokens: TITLE_MAX_TOKENS,
- messages: [
- {
- role: "user",
- content: `Summarize the following message as a very short chat title (max 6 words). Reply with ONLY the title, no quotes or punctuation at the end.\n\nMessage: ${firstMessage}`
- }
- ]
- });
-
- return text.trim();
+ protected createModel(modelId: string) {
+ return this.openai(modelId);
}
}