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
feat(llm): reduce consumption by having a stable system prompt
Elian Dorancda2a7e4ead1
diff --git a/apps/server/src/services/llm/providers/anthropic.spec.ts b/apps/server/src/services/llm/providers/anthropic.spec.tsindex 61c567a81e..825fb0f57b 100644--- a/apps/server/src/services/llm/providers/anthropic.spec.ts+++ b/apps/server/src/services/llm/providers/anthropic.spec.ts@@ -12,8 +12,9 @@ vi.mock("@ai-sdk/anthropic", () => ({}}));-const { streamTextMock } = vi.hoisted(() => ({- streamTextMock: vi.fn((..._args: any[]) => ({}) as any)+const { streamTextMock, noteMetaMock } = vi.hoisted(() => ({+ streamTextMock: vi.fn((..._args: any[]) => ({}) as any),+ noteMetaMock: vi.fn()}));vi.mock("ai", async (importOriginal) => {@@ -21,6 +22,18 @@ vi.mock("ai", async (importOriginal) => {return { ...actual, streamText: streamTextMock };});+// The note hint embeds live note metadata into the system prompt. Mock the+// becca lookup and metadata builder so the "current note" content is fully+// controllable from the tests below.+vi.mock("../../../becca/becca.js", () => ({+ default: { getNote: (noteId: string) => ({ noteId }) }+}));++vi.mock("../tools/helpers.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../tools/helpers.js")>();+ return { ...actual, getNoteMeta: noteMetaMock };+});+import { AnthropicProvider } from "./anthropic.js";describe("AnthropicProvider construction", () => {@@ -124,3 +137,82 @@ describe("AnthropicProvider message building", () => {expect(opts.system.content).toContain("BASE PROMPT");});});++/**+ * The system prompt carries the ephemeral cache breakpoint, so Anthropic can only+ * reuse the cached system+tools prefix when that string is byte-stable across turns.+ *+ * These tests assert the *desired* invariant: editing the context note must not+ * disturb the cached system prompt. They currently FAIL because the live note+ * metadata is embedded directly into the cache-controlled system string — that+ * red state is the confirmation that the note hint busts the prompt cache. Once+ * the hint is moved out of the cached prefix, they turn green.+ */+describe("AnthropicProvider prompt cache stability", () => {+ beforeEach(() => {+ streamTextMock.mockClear();+ noteMetaMock.mockReset();+ });++ /** Run a single chat() turn and return the `system.content` string sent to the model. */+ function systemContentFor(provider: AnthropicProvider, contextNoteId?: string): string {+ streamTextMock.mockClear();+ provider.chat(+ [+ { role: "system", content: "BASE PROMPT" },+ { role: "user", content: "hello" }+ ],+ contextNoteId ? { contextNoteId } : {}+ );+ return (streamTextMock.mock.calls[0][0] as any).system.content as string;+ }++ it("keeps the cache-controlled system prompt stable when the context note's content changes", () => {+ const provider = new AnthropicProvider("sk-ant-test");++ // Turn 1: the note holds its original content.+ noteMetaMock.mockReturnValue({ noteId: "scriptNote", contentPreview: "ORIGINAL_BODY" });+ const system1 = systemContentFor(provider, "scriptNote");++ // Turn 2: the model edited the note, so its metadata preview now differs.+ noteMetaMock.mockReturnValue({ noteId: "scriptNote", contentPreview: "EDITED_BODY" });+ const system2 = systemContentFor(provider, "scriptNote");++ // The system prompt carries the ephemeral cache breakpoint, so it must stay+ // byte-stable across turns — otherwise every note edit re-bills the entire+ // (~10K token) cached system+tools prefix. The volatile note metadata+ // therefore belongs outside this string, not embedded within it.+ expect(system2).toBe(system1);+ });++ it("keeps the system prompt stable across turns when no context note is attached", () => {+ const provider = new AnthropicProvider("sk-ant-test");+ // No note metadata in the prompt → the cached prefix stays byte-identical.+ expect(systemContentFor(provider)).toBe(systemContentFor(provider));+ });++ it("delivers the note hint on the last user message instead of the cached system prompt", () => {+ const provider = new AnthropicProvider("sk-ant-test");+ noteMetaMock.mockReturnValue({ noteId: "scriptNote", contentPreview: "SCRIPT_BODY" });++ streamTextMock.mockClear();+ provider.chat(+ [+ { role: "system", content: "BASE PROMPT" },+ { role: "user", content: "what does this do?" }+ ],+ { contextNoteId: "scriptNote" }+ );+ const opts = streamTextMock.mock.calls[0][0] as any;++ // The note metadata still reaches the model — attached to the (uncached)+ // last user message alongside the user's actual question...+ const lastMessage = opts.messages[opts.messages.length - 1];+ expect(lastMessage.role).toBe("user");+ expect(lastMessage.content).toContain("SCRIPT_BODY");+ expect(lastMessage.content).toContain("what does this do?");++ // ...but never leaks into the cache-controlled system prompt.+ expect(opts.system.content).not.toContain("SCRIPT_BODY");+ });+});diff --git a/apps/server/src/services/llm/providers/anthropic.ts b/apps/server/src/services/llm/providers/anthropic.tsindex aa18d78b2f..3e1393888f 100644--- a/apps/server/src/services/llm/providers/anthropic.ts+++ b/apps/server/src/services/llm/providers/anthropic.ts@@ -153,7 +153,7 @@ export class AnthropicProvider extends BaseProvider {}const systemPrompt = this.buildSystemPrompt(messages, config);- const chatMessages = messages.filter(m => m.role !== "system");+ const chatMessages = this.applyNoteHint(messages.filter(m => m.role !== "system"), config);const coreMessages = this.buildMessages(chatMessages);const thinkingBudget = config.thinkingBudget || 10000;diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.tsindex f1d71e391d..a077fce862 100644--- a/apps/server/src/services/llm/providers/base_provider.ts+++ b/apps/server/src/services/llm/providers/base_provider.ts@@ -89,14 +89,6 @@ export abstract class BaseProvider implements LlmProvider {parts.push(basePrompt);}- // Context note hint- if (config.contextNoteId) {- const noteHint = buildNoteHint(config.contextNoteId);- if (noteHint) {- parts.push(noteHint);- }- }-// Note tools hintif (config.enableNoteTools) {parts.push(@@ -168,6 +160,35 @@ export abstract class BaseProvider implements LlmProvider {}));}+ /**+ * Attach the current-note metadata hint to the last user message.+ *+ * The hint is deliberately kept OUT of the system prompt: it changes whenever+ * the context note changes, and the system prompt carries the provider's+ * prompt-cache breakpoint — embedding volatile content there would invalidate+ * the cached system+tools prefix on every note edit. The last user message is+ * regenerated every turn and never cached, so it is the right home for it.+ */+ protected applyNoteHint(chatMessages: LlmMessage[], config: LlmProviderConfig): LlmMessage[] {+ if (!config.contextNoteId) {+ return chatMessages;+ }++ const noteHint = buildNoteHint(config.contextNoteId);+ if (!noteHint) {+ return chatMessages;+ }++ const lastUserIndex = chatMessages.map(m => m.role).lastIndexOf("user");+ if (lastUserIndex === -1) {+ return chatMessages;+ }++ return chatMessages.map((m, i) =>+ i === lastUserIndex ? { ...m, content: `${noteHint}\n\n${m.content}` } : m+ );+ }+/*** Build the value for the `system` option of `streamText`. Subclasses can* override to attach provider-specific metadata (e.g. cache control).@@ -202,7 +223,7 @@ export abstract class BaseProvider implements LlmProvider {chat(messages: LlmMessage[], config: LlmProviderConfig): StreamResult {const systemPrompt = this.buildSystemPrompt(messages, config);- const chatMessages = messages.filter(m => m.role !== "system");+ const chatMessages = this.applyNoteHint(messages.filter(m => m.role !== "system"), config);const coreMessages = this.buildMessages(chatMessages);const streamOptions: Parameters<typeof streamText>[0] = {diff --git a/apps/server/src/services/llm/providers/google.ts b/apps/server/src/services/llm/providers/google.tsindex 2c509b1fe4..d879ab2ca8 100644--- a/apps/server/src/services/llm/providers/google.ts+++ b/apps/server/src/services/llm/providers/google.ts@@ -74,7 +74,7 @@ export class GoogleProvider extends BaseProvider {}const systemPrompt = this.buildSystemPrompt(messages, config);- const chatMessages = messages.filter(m => m.role !== "system");+ const chatMessages = this.applyNoteHint(messages.filter(m => m.role !== "system"), config);const coreMessages = this.buildMessages(chatMessages);const streamOptions: Parameters<typeof streamText>[0] = {