Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): encourage LLM to use reference links

Elian Doran4082328c2b32
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
index d0097c3bd7..f385339519 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
@@ -1,13 +1,14 @@
import "./ChatMessage.css";
-import { Marked } from "marked";
-import { useMemo } from "preact/hooks";
+import DOMPurify from "dompurify";
+import { Marked, type TokenizerAndRendererExtension } from "marked";
+import { useEffect, useMemo, useRef } from "preact/hooks";
import type { LlmCitation } from "@triliumnext/commons";
+import link from "../../../services/link.js";
import { t } from "../../../services/i18n.js";
import utils from "../../../services/utils.js";
-import { SanitizedHtml } from "../../react/RawHtml.js";
import { ExpandableCard, ExpandableSection } from "./ExpandableCard.js";
import { type ContentBlock, getMessageText, type StoredMessage, type TextBlock, type ToolCallBlock } from "./llm_chat_types.js";
import ToolCallCard from "./ToolCallCard.js";
@@ -18,17 +19,66 @@ function shortenNumber(n: number): string {
return n.toString();
}
+/** Wiki-link extension for internal note links: [[noteId]] */
+const wikiLinkExtension: TokenizerAndRendererExtension = {
+ name: "wikiLink",
+ level: "inline",
+ start(src) {
+ return src.indexOf("[[");
+ },
+ tokenizer(src) {
+ const match = /^\[\[([^\]]+?)\]\]/.exec(src);
+ if (match) {
+ return {
+ type: "wikiLink",
+ raw: match[0],
+ href: match[1].trim()
+ };
+ }
+ },
+ renderer(token) {
+ return `<a class="reference-link" href="#root/${token.href}">${token.href}</a>`;
+ }
+};
+
// Configure marked for safe rendering
const markedInstance = new Marked({
breaks: true, // Convert \n to <br>
gfm: true // GitHub Flavored Markdown
});
+markedInstance.use({ extensions: [wikiLinkExtension] });
-/** Parse markdown to HTML. Sanitization is handled by SanitizedHtml. */
+/** Parse markdown to HTML. */
function renderMarkdown(markdown: string): string {
return markedInstance.parse(markdown) as string;
}
+/** Renders markdown content with reference link title loading. */
+function MarkdownContent({ html, isStreaming }: { html: string; isStreaming?: boolean }) {
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!containerRef.current) return;
+
+ const referenceLinks = containerRef.current.querySelectorAll<HTMLAnchorElement>("a.reference-link");
+ for (const el of referenceLinks) {
+ link.loadReferenceLinkTitle($(el), el.href);
+ }
+ }, [html]);
+
+ return (
+ <>
+ <div
+ ref={containerRef}
+ className="llm-chat-markdown"
+ // eslint-disable-next-line react/no-danger
+ dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }}
+ />
+ {isStreaming && <span className="llm-chat-cursor" />}
+ </>
+ );
+}
+
interface Props {
message: StoredMessage;
isStreaming?: boolean;
@@ -144,10 +194,7 @@ export default function ChatMessage({ message, isStreaming }: Props) {
hasBlockContent ? (
renderContentBlocks(message.content as ContentBlock[], isStreaming)
) : (
- <>
- <SanitizedHtml className="llm-chat-markdown" html={renderedContent || ""} />
- {isStreaming && <span className="llm-chat-cursor" />}
- </>
+ <MarkdownContent html={renderedContent || ""} isStreaming={isStreaming} />
)
) : (
textContent
@@ -221,10 +268,10 @@ function renderContentBlocks(blocks: ContentBlock[], isStreaming?: boolean) {
return groupContentBlocks(blocks).map((group) => {
if (group.type === "text") {
const html = renderMarkdown(group.block.content);
+ const isLastBlock = group.index === blocks.length - 1;
return (
<div key={group.index}>
- <SanitizedHtml className="llm-chat-markdown" html={html} />
- {isStreaming && group.index === blocks.length - 1 && <span className="llm-chat-cursor" />}
+ <MarkdownContent html={html} isStreaming={isStreaming && isLastBlock} />
</div>
);
}
diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.ts
index 7302e5aaa3..125e0fd687 100644
--- a/apps/server/src/services/llm/providers/base_provider.ts
+++ b/apps/server/src/services/llm/providers/base_provider.ts
@@ -102,6 +102,9 @@ export abstract class BaseProvider implements LlmProvider {
parts.push(
`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()}`
);
+ parts.push(
+ `When referring to notes in your responses, use the wiki-link format [[noteId]] to create clickable internal links. Use the note ID (not the title) from tool results. For example: "You can find more details in [[ZjSfLhzlqNY6]]" or "See [[Rhw2szN2XMqH]] for the timeline."`
+ );
} else {
parts.push(
`You do not have access to the user's notes. If the user asks about their notes, inform them that "Note access" is disabled and they need to enable it in the chat settings (click on the model name dropdown and toggle "Note access").`