Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(llm): use vercel/AI instead
Elian Doran88295f246234
diff --git a/apps/server/src/routes/api/llm_chat.ts b/apps/server/src/routes/api/llm_chat.tsindex 357717e4cc..9e1eca04f6 100644--- a/apps/server/src/routes/api/llm_chat.ts+++ b/apps/server/src/routes/api/llm_chat.ts@@ -2,6 +2,7 @@ import type { Request, Response } from "express";import type { LlmMessage } from "@triliumnext/commons";import { getProvider, type LlmProviderConfig } from "../../services/llm/index.js";+import { streamToChunks } from "../../services/llm/stream.js";interface ChatRequest {messages: LlmMessage[];@@ -43,8 +44,9 @@ async function streamChat(req: Request, res: Response) {try {const provider = getProvider(config.provider || "anthropic");+ const result = provider.chat(messages, config);- for await (const chunk of provider.streamCompletion(messages, config)) {+ for await (const chunk of streamToChunks(result)) {res.write(`data: ${JSON.stringify(chunk)}\n\n`);// Flush immediately to ensure real-time streamingif (typeof flushableRes.flush === "function") {diff --git a/apps/server/src/services/llm/providers/anthropic.ts b/apps/server/src/services/llm/providers/anthropic.tsindex 2b1f9d2e92..9e6db7e380 100644--- a/apps/server/src/services/llm/providers/anthropic.ts+++ b/apps/server/src/services/llm/providers/anthropic.ts@@ -1,8 +1,8 @@import { anthropic } from "@ai-sdk/anthropic";import { streamText, type CoreMessage } from "ai";-import type { LlmMessage, LlmStreamChunk } from "@triliumnext/commons";+import type { LlmMessage } from "@triliumnext/commons";-import type { LlmProvider, LlmProviderConfig } from "../types.js";+import type { LlmProvider, LlmProviderConfig, StreamResult } from "../types.js";const DEFAULT_MODEL = "claude-sonnet-4-20250514";const DEFAULT_MAX_TOKENS = 8096;@@ -18,10 +18,7 @@ export class AnthropicProvider implements LlmProvider {// The anthropic provider reads ANTHROPIC_API_KEY from env automatically}- async *streamCompletion(- messages: LlmMessage[],- config: LlmProviderConfig- ): AsyncIterable<LlmStreamChunk> {+ chat(messages: LlmMessage[], config: LlmProviderConfig): StreamResult {const systemPrompt = config.systemPrompt || messages.find(m => m.role === "system")?.content;const chatMessages = messages.filter(m => m.role !== "system");@@ -31,106 +28,43 @@ export class AnthropicProvider implements LlmProvider {content: m.content}));- try {- const model = anthropic(config.model || DEFAULT_MODEL);-- // Build options for streamText- const streamOptions: Parameters<typeof streamText>[0] = {- model,- messages: coreMessages,- maxOutputTokens: config.maxTokens || DEFAULT_MAX_TOKENS,- system: systemPrompt- };-- // Enable extended thinking for deeper reasoning- if (config.enableExtendedThinking) {- const thinkingBudget = config.thinkingBudget || 10000;- // Vercel AI SDK handles thinking via providerOptions- streamOptions.providerOptions = {- anthropic: {- thinking: {- type: "enabled",- budgetTokens: thinkingBudget- }+ const model = anthropic(config.model || DEFAULT_MODEL);++ // Build options for streamText+ const streamOptions: Parameters<typeof streamText>[0] = {+ model,+ messages: coreMessages,+ maxOutputTokens: config.maxTokens || DEFAULT_MAX_TOKENS,+ system: systemPrompt+ };++ // Enable extended thinking for deeper reasoning+ if (config.enableExtendedThinking) {+ const thinkingBudget = config.thinkingBudget || 10000;+ streamOptions.providerOptions = {+ anthropic: {+ thinking: {+ type: "enabled",+ budgetTokens: thinkingBudget}- };- // Ensure max tokens accommodates thinking budget- streamOptions.maxOutputTokens = Math.max(- streamOptions.maxOutputTokens || DEFAULT_MAX_TOKENS,- thinkingBudget + 4000- );- console.log(`[LLM] Extended thinking enabled with budget: ${thinkingBudget} tokens`);- }-- // Enable web search if configured- if (config.enableWebSearch) {- const webSearchTool = anthropic.tools.webSearch_20250305({- maxUses: 5- });- streamOptions.tools = {- web_search: webSearchTool- };- }-- const result = streamText(streamOptions);-- // Stream the response- for await (const part of result.fullStream) {- switch (part.type) {- case "text-delta":- yield { type: "text", content: part.text };- break;-- case "reasoning-delta":- // Extended thinking content- yield { type: "thinking", content: part.text };- break;-- case "tool-call":- yield {- type: "tool_use",- toolName: part.toolName,- toolInput: part.input as Record<string, unknown>- };- break;-- case "tool-result":- yield {- type: "tool_result",- toolName: part.toolName,- result: typeof part.output === "string"- ? part.output- : JSON.stringify(part.output)- };- break;-- case "source":- // Citation from web search (only URL sources have url property)- if (part.sourceType === "url") {- yield {- type: "citation",- citation: {- url: part.url,- title: part.title- }- };- }- break;-- case "error":- yield { type: "error", error: String(part.error) };- break;-- case "finish":- // Stream finished- break;}- }+ };+ streamOptions.maxOutputTokens = Math.max(+ streamOptions.maxOutputTokens || DEFAULT_MAX_TOKENS,+ thinkingBudget + 4000+ );+ }- yield { type: "done" };- } catch (error) {- const message = error instanceof Error ? error.message : "Unknown error";- yield { type: "error", error: message };+ // Enable web search if configured+ if (config.enableWebSearch) {+ const webSearchTool = anthropic.tools.webSearch_20250305({+ maxUses: 5+ });+ streamOptions.tools = {+ web_search: webSearchTool+ };}++ return streamText(streamOptions);}}diff --git a/apps/server/src/services/llm/stream.ts b/apps/server/src/services/llm/stream.tsnew file mode 100644index 0000000000..8e548fa26e--- /dev/null+++ b/apps/server/src/services/llm/stream.ts@@ -0,0 +1,66 @@+/**+ * Shared streaming utilities for converting AI SDK streams to SSE chunks.+ */++import type { LlmStreamChunk } from "@triliumnext/commons";+import type { StreamResult } from "./types.js";++/**+ * Convert an AI SDK StreamResult to an async iterable of LlmStreamChunk.+ * This is provider-agnostic - works with any AI SDK provider.+ */+export async function* streamToChunks(result: StreamResult): AsyncIterable<LlmStreamChunk> {+ try {+ for await (const part of result.fullStream) {+ switch (part.type) {+ case "text-delta":+ yield { type: "text", content: part.text };+ break;++ case "reasoning-delta":+ yield { type: "thinking", content: part.text };+ break;++ case "tool-call":+ yield {+ type: "tool_use",+ toolName: part.toolName,+ toolInput: part.input as Record<string, unknown>+ };+ break;++ case "tool-result":+ yield {+ type: "tool_result",+ toolName: part.toolName,+ result: typeof part.output === "string"+ ? part.output+ : JSON.stringify(part.output)+ };+ break;++ case "source":+ // Citation from web search (only URL sources have url property)+ if (part.sourceType === "url") {+ yield {+ type: "citation",+ citation: {+ url: part.url,+ title: part.title+ }+ };+ }+ break;++ case "error":+ yield { type: "error", error: String(part.error) };+ break;+ }+ }++ yield { type: "done" };+ } catch (error) {+ const message = error instanceof Error ? error.message : "Unknown error";+ yield { type: "error", error: message };+ }+}diff --git a/apps/server/src/services/llm/types.ts b/apps/server/src/services/llm/types.tsindex 38f64ea61e..a7f080fa86 100644--- a/apps/server/src/services/llm/types.ts+++ b/apps/server/src/services/llm/types.ts@@ -4,7 +4,8 @@* should be imported from @triliumnext/commons.*/-import type { LlmChatConfig, LlmMessage, LlmStreamChunk } from "@triliumnext/commons";+import type { LlmChatConfig, LlmMessage } from "@triliumnext/commons";+import type { streamText } from "ai";/*** Extended provider config with server-specific options.@@ -14,15 +15,20 @@ export interface LlmProviderConfig extends LlmChatConfig {temperature?: number;}+/**+ * Result type from streamText - the AI SDK's unified streaming interface.+ */+export type StreamResult = ReturnType<typeof streamText>;+export interface LlmProvider {name: string;/**- * Stream a chat completion response.- * Yields chunks as they arrive from the LLM.+ * Create a streaming chat completion.+ * Returns the AI SDK StreamResult which is provider-agnostic.*/- streamCompletion(+ chat(messages: LlmMessage[],config: LlmProviderConfig- ): AsyncIterable<LlmStreamChunk>;+ ): StreamResult;}