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
fix(llm): give a title model room to think before answering
Elian Dorancd0b2f546273
diff --git a/packages/trilium-core/src/services/llm/chat.ts b/packages/trilium-core/src/services/llm/chat.tsindex 19657bea93..9cbd814caa 100644--- a/packages/trilium-core/src/services/llm/chat.ts+++ b/packages/trilium-core/src/services/llm/chat.ts@@ -67,6 +67,10 @@ export async function* runChat(for await (const chunk of chunks) {if (abortSignal?.aborted) {+ // Naming the chat is downstream of this loop, so a stopped turn+ // leaves the note on its timestamp. Said out loud, since from the+ // outside it is indistinguishable from naming having failed.+ getLog().info("Chat turn stopped by the user; leaving the chat note unnamed.");return;}if (chunk.type === "error") {@@ -92,7 +96,14 @@ export async function* runChat(*/async function generateTitleForFirstTurn(messages: LlmMessage[], config: LlmProviderConfig): Promise<void> {const userMessages = messages.filter(m => m.role === "user");- if (userMessages.length !== 1 || !config.chatNoteId) {+ // Later turns are not a naming opportunity at all, so they pass without a word.+ if (userMessages.length !== 1) {+ return;+ }+ // Whereas a first turn that names no chat note is one: the chat is somewhere+ // the caller never told us about, and it will keep its timestamp forever.+ if (!config.chatNoteId) {+ getLog().info("Not naming this chat: the request carried no chatNoteId.");return;}@@ -103,9 +114,11 @@ async function generateTitleForFirstTurn(messages: LlmMessage[], config: LlmProvconst firstText = typeof firstContent === "string"? firstContent: firstContent.filter(p => p.type === "text").map(p => p.text).join("\n").trim();- if (firstText) {- await generateChatTitle(config.chatNoteId, firstText);+ if (!firstText) {+ getLog().info(`Not naming chat note ${config.chatNoteId}: the opening message carries no text.`);+ return;}+ await generateChatTitle(config.chatNoteId, firstText);} catch (err) {getLog().error(`Failed to generate chat title: ${safeExtractMessageAndStackFromError(err)}`);}diff --git a/packages/trilium-core/src/services/llm/chat_title.ts b/packages/trilium-core/src/services/llm/chat_title.tsindex 4a6e81968a..7df6de3cee 100644--- a/packages/trilium-core/src/services/llm/chat_title.ts+++ b/packages/trilium-core/src/services/llm/chat_title.ts@@ -19,20 +19,34 @@ function hasDefaultTitle(title: string): boolean {* then rename the note. Only renames if the note still has a default title.*/export async function generateChatTitle(chatNoteId: string, firstMessage: string): Promise<void> {+ const log = getLog();+const note = becca.getNote(chatNoteId);if (!note) {+ log.info(`Not naming chat ${chatNoteId}: no such note.`);return;}+ // Every way out of here is silent from the user's side — the chat keeps the+ // timestamp it was created with — so each one says which it was.if (!hasDefaultTitle(note.title)) {+ log.info(`Not naming chat note ${chatNoteId}: "${note.title}" is neither `+ + `"${t("special_notes.llm_chat_prefix")} …" nor "${t("notes.new-note")}", so it was named deliberately.`);return;}+ // Whichever provider is configured first, which is not necessarily the one+ // the chat itself is talking to.const provider = getProvider();+ log.info(`Naming chat note ${chatNoteId} with the ${provider.name} provider.`);+const title = await provider.generateTitle(firstMessage);- if (title) {- note.title = title;- note.save();- getLog().info(`Auto-renamed chat note ${chatNoteId} to "${title}"`);+ if (!title) {+ log.info(`Not naming chat note ${chatNoteId}: the ${provider.name} provider returned an empty title.`);+ return;}++ note.title = title;+ note.save();+ log.info(`Auto-renamed chat note ${chatNoteId} to "${title}"`);}diff --git a/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts b/packages/trilium-core/src/services/llm/providers/base_provider.spec.tsindex 0bff68a2da..94abfc7d2d 100644--- a/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts+++ b/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts@@ -598,6 +598,44 @@ describe("BaseProvider chat / pricing / models / title", () => {expect(args.maxOutputTokens).toBe(30);expect(args.messages[0].content).toContain("Some long first message");});++ it("generateTitle buys a second, larger attempt when the first went entirely on thinking", async () => {+ // What a reasoning model does to a 30-token budget: spends it all before+ // writing a word, so the answer is empty and the call ends on "length".+ generateTextMock+ .mockResolvedValueOnce({+ text: "",+ finishReason: "length",+ usage: { outputTokens: 30, outputTokenDetails: { reasoningTokens: 30 } }+ } as any)+ .mockResolvedValueOnce({ text: " Considered Title ", finishReason: "stop", usage: {} } as any);++ const provider = new TestProvider();+ expect(await provider.generateTitle("Some long first message")).toBe("Considered Title");+ expect(generateTextMock).toHaveBeenCalledTimes(2);+ expect((generateTextMock.mock.calls[0][0] as any).maxOutputTokens).toBe(30);+ expect((generateTextMock.mock.calls[1][0] as any).maxOutputTokens).toBe(2000);++ // Having learned that this model thinks, the next chat skips the attempt+ // that cannot finish and asks for the room outright.+ generateTextMock.mockResolvedValueOnce({ text: "Second Title", finishReason: "stop", usage: {} } as any);+ expect(await provider.generateTitle("Another message")).toBe("Second Title");+ expect(generateTextMock).toHaveBeenCalledTimes(3);+ expect((generateTextMock.mock.calls[2][0] as any).maxOutputTokens).toBe(2000);+ });++ it("generateTitle takes an empty answer at its word when the budget was not what stopped it", async () => {+ // Finished of its own accord with nothing to say: a bigger budget would buy+ // the same silence twice.+ generateTextMock.mockResolvedValueOnce({+ text: " ",+ finishReason: "stop",+ usage: { outputTokens: 1, outputTokenDetails: { reasoningTokens: 0 } }+ } as any);++ expect(await new TestProvider().generateTitle("hi")).toBe("");+ expect(generateTextMock).toHaveBeenCalledOnce();+ });});describe("BaseProvider default buildSystemMessage", () => {diff --git a/packages/trilium-core/src/services/llm/providers/base_provider.ts b/packages/trilium-core/src/services/llm/providers/base_provider.tsindex cf0dfa86cc..ade2b2e16f 100644--- a/packages/trilium-core/src/services/llm/providers/base_provider.ts+++ b/packages/trilium-core/src/services/llm/providers/base_provider.ts@@ -6,6 +6,7 @@import { type LlmMessage, type LlmMessagePart } from "@triliumnext/commons";import { type FilePart, generateText, type ImagePart, type LanguageModel, type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type TextPart, type ToolSet } from "ai";+import { getLog } from "../../log.js";import { resolveAttachmentPart } from "../attachment_content.js";import { buildNoteHint } from "../note_hint.js";import { buildSystemPrompt as composeSystemPrompt } from "../system_prompt.js";@@ -14,8 +15,19 @@ import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResimport MODEL_PRICES_JSON from "./model_prices.json" with { type: "json" };const DEFAULT_MAX_TOKENS = 8096;++/** Room for the title and nothing else: six words, so a model that answers straight away never needs more. */const TITLE_MAX_TOKENS = 30;+/**+ * The second attempt's budget, for a model that thinks before it answers. Its+ * reasoning spends the tight budget above and the call is cut off having written+ * nothing, so the retry has to cover the thinking as well as the six words. Far+ * more than a title costs, but it is one call per chat, and a title nobody gets+ * is worth less than the tokens it saves.+ */+const REASONING_TITLE_MAX_TOKENS = 2000;+/*** Turns the AI SDK's telemetry off, on every call into it.*@@ -460,10 +472,56 @@ export abstract class BaseProvider implements LlmProvider {return new Set(models.filter(m => !m.isLegacy && !/preview/i.test(m.id)).map(m => m.id));}+ /**+ * Name a chat after its opening message, in at most six words.+ *+ * Asked for twice at most. A model that reasons first spends the tight budget+ * thinking and is cut off before writing any of the answer, which arrives as+ * an empty text with a `length` finish — indistinguishable, to the caller,+ * from a model that had nothing to say. That case buys one retry with room+ * for the thinking too; everything else is taken at its word.+ */async generateTitle(firstMessage: string): Promise<string> {- const { text } = await generateText({+ const budget = this.titleNeedsRoomToThink ? REASONING_TITLE_MAX_TOKENS : TITLE_MAX_TOKENS;+ const attempt = await this.requestTitle(firstMessage, budget);+ if (attempt.title) {+ return attempt.title;+ }++ // Only a first attempt is worth repeating: run out of the larger budget and+ // the model is not going to fit a title into a larger one either.+ const log = getLog();+ const cutOffThinking = attempt.finishReason === "length" && budget === TITLE_MAX_TOKENS;+ if (cutOffThinking) {+ this.titleNeedsRoomToThink = true;+ log.info(`${this.name} wrote no title within ${TITLE_MAX_TOKENS} tokens; retrying with ${REASONING_TITLE_MAX_TOKENS}.`);+ }+ const result = cutOffThinking+ ? await this.requestTitle(firstMessage, REASONING_TITLE_MAX_TOKENS)+ : attempt;++ if (!result.title) {+ const { outputTokens, outputTokenDetails } = result.usage;+ log.info(`${this.name} produced no title with ${this.titleModel}: finished as `+ + `"${result.finishReason}" after ${outputTokens ?? "?"} output tokens, `+ + `${outputTokenDetails?.reasoningTokens ?? 0} of them reasoning.`);+ }+ return result.title;+ }++ /**+ * Set the first time a title call is cut off mid-thought: this model reasons,+ * so every chat after it starts on the larger budget instead of paying a round+ * trip for an attempt that cannot finish. Kept on the instance, which is+ * cached for as long as the provider configuration stands.+ */+ private titleNeedsRoomToThink = false;++ /** One title call, with whatever the caller is willing to spend on it. */+ private async requestTitle(firstMessage: string, maxOutputTokens: number) {+ const { text, finishReason, usage } = await generateText({model: this.createModel(this.titleModel),- maxOutputTokens: TITLE_MAX_TOKENS,+ maxOutputTokens,telemetry: TELEMETRY_OFF,messages: [{@@ -473,6 +531,6 @@ export abstract class BaseProvider implements LlmProvider {]});- return text.trim();+ return { title: text.trim(), finishReason, usage };}}