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): add support for PDF
Elian Doran63c2f3a04ddf
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 39186b2a9b..bc884b8dcd 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1814,10 +1814,10 @@"add_provider": "Add AI Provider","stop": "Stop","retry": "Retry",- "attach_image": "Attach image",+ "attach_file": "Attach image or PDF","remove_attachment": "Remove attachment",- "image_upload_failed": "Failed to upload image \"{{name}}\".",- "image_unsupported_type": "\"{{name}}\" isn't a supported image type. Use PNG, JPEG, GIF, or WebP."+ "attachment_upload_failed": "Failed to upload \"{{name}}\".",+ "attachment_unsupported_type": "\"{{name}}\" isn't a supported attachment type. Use PNG, JPEG, GIF, WebP, or PDF."},"sidebar_chat": {"title": "AI Chat",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.cssindex b0bddebd26..4aef898854 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css@@ -16,7 +16,6 @@.llm-chat-attachment-chip {position: relative;- width: 56px;height: 56px;border-radius: 6px;overflow: hidden;@@ -24,13 +23,42 @@background: var(--accented-background-color);}-.llm-chat-attachment-chip img {+.llm-chat-attachment-chip-image {+ width: 56px;+}++.llm-chat-attachment-chip-image img {width: 100%;height: 100%;object-fit: cover;display: block;}+.llm-chat-attachment-chip-file {+ max-width: 180px;+}++.llm-chat-attachment-file {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ height: 100%;+ padding: 0 1.75rem 0 0.5rem;+}++.llm-chat-attachment-file-icon {+ font-size: 1.5rem;+ color: var(--muted-text-color);+ flex-shrink: 0;+}++.llm-chat-attachment-file-name {+ font-size: 0.8rem;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.llm-chat-attachment-remove {position: absolute;top: 2px;diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 12a94869ae..36a10d356c 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -16,11 +16,14 @@ import Dropdown from "../../react/Dropdown.js";import { FormDropdownDivider, FormDropdownSubmenu, FormListItem, FormListToggleableItem } from "../../react/FormList.js";import { useLegacyImperativeHandlers } from "../../react/hooks.js";import AddProviderModal, { type LlmProviderConfig } from "../options/llm/AddProviderModal.js";-import type { ImageBlock } from "./llm_chat_types.js";-import type { UseLlmChatReturn } from "./useLlmChat.js";+import type { FileBlock, ImageBlock } from "./llm_chat_types.js";+import type { AttachmentBlock, UseLlmChatReturn } from "./useLlmChat.js";/** MIME types we accept for image upload — must match what the providers support as vision input. */const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp"];+/** Non-image MIME types we accept. PDFs are supported natively by Anthropic, OpenAI, and Google. */+const ACCEPTED_FILE_TYPES = ["application/pdf"];+const ACCEPTED_UPLOAD_TYPES = [...ACCEPTED_IMAGE_TYPES, ...ACCEPTED_FILE_TYPES];const READ_ONLY_LOCK = "llm-chat-streaming";@@ -56,12 +59,25 @@ function formatTokenCount(tokens: number): string {}/**- * Upload an image file as an attachment to the chat note and return a block- * describing it. The server's `notes/{id}/attachments/upload` endpoint already- * handles image-role classification and returns a stable URL we can render- * inline; we just feed it back as an `ImageBlock`.+ * Extract the Trilium attachment ID from one of the URLs returned by+ * `notes/{id}/attachments/upload`. Image roles return `api/attachments/<id>/image/<title>`;+ * file roles return `#root/<noteId>?viewMode=attachments&attachmentId=<id>`.*/-async function uploadImageAsAttachment(noteId: string, file: File): Promise<ImageBlock | null> {+function parseAttachmentIdFromUploadUrl(url: string): string | null {+ const imageMatch = url.match(/attachments\/([^/]+)\/image\//);+ if (imageMatch) return imageMatch[1];+ const fileMatch = url.match(/attachmentId=([^&]+)/);+ if (fileMatch) return fileMatch[1];+ return null;+}++/**+ * Upload a file as an attachment to the chat note and return a block describing+ * it. The server's `notes/{id}/attachments/upload` endpoint sorts images and+ * non-images into different attachment roles and returns different URL shapes;+ * we unify them back into a typed block here.+ */+async function uploadFileAsAttachment(noteId: string, file: File): Promise<AttachmentBlock | null> {let detail: string | undefined;try {const result = await server.upload(@@ -69,17 +85,24 @@ async function uploadImageAsAttachment(noteId: string, file: File): Promise<Imagfile, undefined, "POST") as { uploaded?: boolean; url?: string; message?: string };if (result?.uploaded && result.url) {- // The upload endpoint returns the URL as `api/attachments/<id>/image/<title>`.- // Pull the attachment ID back out so we can pass it to the server.- const match = result.url.match(/attachments\/([^/]+)\/image\//);- if (match) {+ const attachmentId = parseAttachmentIdFromUploadUrl(result.url);+ if (attachmentId) {+ if (ACCEPTED_IMAGE_TYPES.includes(file.type)) {+ return {+ type: "image",+ attachmentId,+ mime: file.type,+ title: file.name,+ url: result.url+ } satisfies ImageBlock;+ }return {- type: "image",- attachmentId: match[1],+ type: "file",+ attachmentId,mime: file.type,title: file.name,url: result.url- };+ } satisfies FileBlock;}}detail = result?.message;@@ -87,7 +110,7 @@ async function uploadImageAsAttachment(noteId: string, file: File): Promise<Imagdetail = e instanceof Error ? e.message : undefined;}- const base = t("llm_chat.image_upload_failed", { name: file.name });+ const base = t("llm_chat.attachment_upload_failed", { name: file.name });toast.showError(detail ? `${base} ${detail}` : base);return null;}@@ -153,14 +176,14 @@ export default function ChatInputBar({// Always-fresh submit handler for the editor's enter listener.const submitRef = useRef<(e: Event) => void>(() => {});- /** Upload an image file to the chat note and add the result to pending attachments. */+ /** Upload an image or PDF to the chat note and add the result to pending attachments. */const uploadFile = useCallback(async (file: File) => {if (!chat.chatNoteId) return;- if (!ACCEPTED_IMAGE_TYPES.includes(file.type)) {- toast.showError(t("llm_chat.image_unsupported_type", { name: file.name }));+ if (!ACCEPTED_UPLOAD_TYPES.includes(file.type)) {+ toast.showError(t("llm_chat.attachment_unsupported_type", { name: file.name }));return;}- const block = await uploadImageAsAttachment(chat.chatNoteId, file);+ const block = await uploadFileAsAttachment(chat.chatNoteId, file);if (block) {chat.addPendingAttachment(block);}@@ -180,19 +203,19 @@ export default function ChatInputBar({const handlePaste = useCallback(async (e: ClipboardEvent) => {const items = e.clipboardData?.items;if (!items) return;- const imageFiles: File[] = [];+ const pastedFiles: File[] = [];for (const item of Array.from(items)) {- if (item.kind === "file" && item.type.startsWith("image/")) {+ if (item.kind === "file" && ACCEPTED_UPLOAD_TYPES.includes(item.type)) {const file = item.getAsFile();- if (file) imageFiles.push(file);+ if (file) pastedFiles.push(file);}}- if (imageFiles.length === 0) return;- // Stop CKEditor from also pasting the image as an inline data URL — we- // want it as an attachment, not embedded markup.+ if (pastedFiles.length === 0) return;+ // Stop CKEditor from also pasting the file (e.g. an image as a base64+ // data URL) — we want it as an attachment, not embedded markup.e.preventDefault();e.stopPropagation();- for (const file of imageFiles) {+ for (const file of pastedFiles) {await uploadFile(file);}}, [uploadFile]);@@ -329,8 +352,19 @@ export default function ChatInputBar({{chat.pendingAttachments.length > 0 && (<div className="llm-chat-attachments">{chat.pendingAttachments.map((att) => (- <div key={att.attachmentId} className="llm-chat-attachment-chip">- <img src={att.url} alt={att.title} />+ <div+ key={att.attachmentId}+ className={`llm-chat-attachment-chip llm-chat-attachment-chip-${att.type}`}+ title={att.title}+ >+ {att.type === "image" ? (+ <img src={att.url} alt={att.title} />+ ) : (+ <div className="llm-chat-attachment-file">+ <span className="bx bxs-file-pdf llm-chat-attachment-file-icon" />+ <span className="llm-chat-attachment-file-name">{att.title}</span>+ </div>+ )}<buttontype="button"className="llm-chat-attachment-remove"@@ -380,7 +414,7 @@ export default function ChatInputBar({<inputref={fileInputRef}type="file"- accept={ACCEPTED_IMAGE_TYPES.join(",")}+ accept={ACCEPTED_UPLOAD_TYPES.join(",")}multipleonChange={handleFilePickerChange}style={{ display: "none" }}@@ -474,8 +508,8 @@ export default function ChatInputBar({)}</div><ActionButton- icon="bx bx-image-add"- text={t("llm_chat.attach_image")}+ icon="bx bx-paperclip"+ text={t("llm_chat.attach_file")}onClick={() => fileInputRef.current?.click()}disabled={chat.isStreaming || !chat.chatNoteId}className="llm-chat-attach-btn"diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.cssindex 969182cd19..55ac081d83 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css@@ -52,6 +52,37 @@border: 1px solid var(--main-border-color);}+.llm-chat-message-file {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ margin: 0.5rem 0;+ padding: 0.5rem 0.75rem;+ border-radius: 6px;+ border: 1px solid var(--main-border-color);+ background: var(--accented-background-color);+ color: var(--main-text-color);+ text-decoration: none;+ max-width: 100%;+}++.llm-chat-message-file:hover {+ background: var(--more-accented-background-color, var(--accented-background-color));+ text-decoration: none;+}++.llm-chat-message-file .bx {+ font-size: 1.5rem;+ color: var(--muted-text-color);+ flex-shrink: 0;+}++.llm-chat-message-file-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.llm-chat-cursor {display: inline-block;width: 8px;diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsxindex 138641f524..43483fd06e 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx@@ -11,7 +11,7 @@ import utils from "../../../services/utils.js";import Button from "../../react/Button.js";import { ReadOnlyTextContent } from "../text/ReadOnlyText.js";import { ExpandableCard, ExpandableSection } from "./ExpandableCard.js";-import { type ContentBlock, getMessageText, type ImageBlock, type StoredMessage, type TextBlock, type ToolCallBlock } from "./llm_chat_types.js";+import { type ContentBlock, type FileBlock, getMessageText, type ImageBlock, type StoredMessage, type TextBlock, type ToolCallBlock } from "./llm_chat_types.js";import ToolCallCard from "./ToolCallCard.js";function shortenNumber(n: number): string {@@ -66,7 +66,8 @@ interface Props {type ContentGroup =| { type: "text"; block: TextBlock; index: number }| { type: "tool_calls"; blocks: ToolCallBlock[]; index: number }- | { type: "image"; block: ImageBlock; index: number };+ | { type: "image"; block: ImageBlock; index: number }+ | { type: "file"; block: FileBlock; index: number };/** Extract domain + TLD from a hostname (e.g. "www.example.co.uk" → "example.co.uk"). */function extractDomain(hostname: string): string {@@ -256,6 +257,8 @@ function groupContentBlocks(blocks: ContentBlock[]): ContentGroup[] {}} else if (block.type === "image") {groups.push({ type: "image", block, index: i });+ } else if (block.type === "file") {+ groups.push({ type: "file", block, index: i });} else {groups.push({ type: "text", block, index: i });}@@ -291,6 +294,22 @@ function renderContentBlocks(blocks: ContentBlock[], isStreaming?: boolean) {);}+ if (group.type === "file") {+ return (+ <a+ key={group.index}+ href={group.block.url}+ target="_blank"+ rel="noopener noreferrer"+ className="llm-chat-message-file"+ title={group.block.title}+ >+ <span className="bx bxs-file-pdf" />+ <span className="llm-chat-message-file-name">{group.block.title}</span>+ </a>+ );+ }+return <ToolCallCard key={group.index} toolCalls={group.blocks.map((b) => b.toolCall)} />;});}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.tsindex e0a2c73516..898273db2e 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts@@ -41,8 +41,22 @@ export interface ImageBlock {url: string;}+/**+ * A non-image file attached to a user message (e.g. a PDF). Stored as a+ * reference to a Trilium attachment; the server resolves the bytes before+ * forwarding to the provider as an AI SDK `FilePart`.+ */+export interface FileBlock {+ type: "file";+ attachmentId: string;+ mime: string;+ title: string;+ /** URL pointing back at the attachment's note view. */+ url: string;+}+/** An ordered content block in a chat message. */-export type ContentBlock = TextBlock | ToolCallBlock | ImageBlock;+export type ContentBlock = TextBlock | ToolCallBlock | ImageBlock | FileBlock;/*** Extract the plain text from message content (works for both legacy string and block formats).diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex 103d31c5e7..5550aa75f9 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@ -4,7 +4,10 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { getAvailableModels, streamChatCompletion } from "../../../services/llm_chat.js";import { randomString } from "../../../services/utils.js";-import type { ContentBlock, ImageBlock, LlmChatContent, StoredMessage } from "./llm_chat_types.js";+import type { ContentBlock, FileBlock, ImageBlock, LlmChatContent, StoredMessage } from "./llm_chat_types.js";++/** A user-supplied attachment waiting to be sent with the next message. */+export type AttachmentBlock = ImageBlock | FileBlock;/*** Flatten a stored message's content into the wire format the server expects.@@ -21,6 +24,8 @@ function flattenToApiContent(content: string | ContentBlock[]): string | LlmMessif (block.content) parts.push({ type: "text", text: block.content });} else if (block.type === "image") {parts.push({ type: "image", attachmentId: block.attachmentId, mime: block.mime });+ } else if (block.type === "file") {+ parts.push({ type: "file", attachmentId: block.attachmentId, mime: block.mime, filename: block.title });}// tool_call blocks belong to assistant history rendering only — they// are reconstructed from the model's own tool-use turns and must not@@ -57,8 +62,8 @@ export interface UseLlmChatReturn {streamingBlocks: ContentBlock[];streamingThinking: string;pendingCitations: LlmCitation[];- /** Images the user has attached but not yet sent. */- pendingAttachments: ImageBlock[];+ /** Images or files the user has attached but not yet sent. */+ pendingAttachments: AttachmentBlock[];availableModels: ModelOption[];selectedModel: string;enableWebSearch: boolean;@@ -84,8 +89,8 @@ export interface UseLlmChatReturn {setEnableExtendedThinking: (value: boolean) => void;setContextNoteId: (noteId: string | undefined) => void;setChatNoteId: (noteId: string | undefined) => void;- /** Append a freshly uploaded image to the pending-attachments list. */- addPendingAttachment: (attachment: ImageBlock) => void;+ /** Append a freshly uploaded image or file to the pending-attachments list. */+ addPendingAttachment: (attachment: AttachmentBlock) => void;/** Remove a pending attachment by its attachment ID. */removePendingAttachment: (attachmentId: string) => void;@@ -116,7 +121,7 @@ export function useLlmChat(const [streamingBlocks, setStreamingBlocks] = useState<ContentBlock[]>([]);const [streamingThinking, setStreamingThinking] = useState("");const [pendingCitations, setPendingCitations] = useState<LlmCitation[]>([]);- const [pendingAttachments, setPendingAttachments] = useState<ImageBlock[]>([]);+ const [pendingAttachments, setPendingAttachments] = useState<AttachmentBlock[]>([]);const [availableModels, setAvailableModels] = useState<ModelOption[]>([]);const [selectedModel, setSelectedModel] = useState<string>("");const [enableWebSearch, setEnableWebSearch] = useState(true);@@ -154,7 +159,7 @@ export function useLlmChat(const pendingAttachmentsRef = useRef(pendingAttachments);pendingAttachmentsRef.current = pendingAttachments;- const addPendingAttachment = useCallback((attachment: ImageBlock) => {+ const addPendingAttachment = useCallback((attachment: AttachmentBlock) => {setPendingAttachments(prev => [...prev, attachment]);}, []);const removePendingAttachment = useCallback((attachmentId: string) => {diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.tsindex 9bd144a674..d3154f161f 100644--- a/apps/server/src/services/llm/providers/base_provider.ts+++ b/apps/server/src/services/llm/providers/base_provider.ts@@ -4,7 +4,7 @@*/import type { LlmMessage, LlmMessagePart } from "@triliumnext/commons";-import { generateText, type ImagePart, type LanguageModel, type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type TextPart, type ToolSet } from "ai";+import { type FilePart, generateText, type ImagePart, type LanguageModel, type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type TextPart, type ToolSet } from "ai";import yaml from "js-yaml";import becca from "../../../becca/becca.js";@@ -46,14 +46,14 @@ function buildNoteHint(noteId: string): string | null {/*** Resolve a single LlmMessagePart to its AI SDK ModelMessage part form.- * For image parts, this reads the attachment bytes out of Becca; failures are- * logged and the part is dropped so the rest of the message still goes through.+ * For image/file parts, this reads the attachment bytes out of Becca; failures+ * are logged and the part is dropped so the rest of the message still goes+ * through.*/-function resolveMessagePart(part: LlmMessagePart): TextPart | ImagePart | null {+function resolveMessagePart(part: LlmMessagePart): TextPart | ImagePart | FilePart | null {if (part.type === "text") {return { type: "text", text: part.text };}- // type === "image"const attachment = becca.getAttachment(part.attachmentId);if (!attachment) {log.error(`LLM message references missing attachment ${part.attachmentId}`);@@ -63,16 +63,25 @@ function resolveMessagePart(part: LlmMessagePart): TextPart | ImagePart | null {log.error(`LLM message references protected attachment ${part.attachmentId} without an unlocked session`);return null;}+ if (part.type === "image") {+ return {+ type: "image",+ image: attachment.getContent(),+ mediaType: part.mime || attachment.mime+ };+ }+ // type === "file"return {- type: "image",- image: attachment.getContent(),- mediaType: part.mime || attachment.mime+ type: "file",+ data: attachment.getContent(),+ mediaType: part.mime || attachment.mime,+ filename: part.filename || attachment.title};}/*** Build a single ModelMessage from an LlmMessage. Plain string content stays- * as-is; multimodal content is resolved into AI SDK text/image parts.+ * as-is; multimodal content is resolved into AI SDK text/image/file parts.*/export function buildModelMessage(m: LlmMessage): ModelMessage {const role = m.role as "user" | "assistant";@@ -81,9 +90,9 @@ export function buildModelMessage(m: LlmMessage): ModelMessage {}const resolved = m.content.map(resolveMessagePart)- .filter((p): p is TextPart | ImagePart => p !== null);+ .filter((p): p is TextPart | ImagePart | FilePart => p !== null);// Assistant turns can only carry TextParts (per the AI SDK type), so- // strip any stray images — they only make sense on user turns anyway.+ // strip any stray attachments — they only make sense on user turns anyway.if (role === "assistant") {const textOnly: TextPart[] = resolved.filter((p): p is TextPart => p.type === "text");return { role: "assistant", content: textOnly };diff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.tsindex d8f1ec7572..d8fdea9fcb 100644--- a/packages/commons/src/lib/llm_api.ts+++ b/packages/commons/src/lib/llm_api.ts@@ -24,7 +24,20 @@ export interface LlmImagePart {mime: string;}-export type LlmMessagePart = LlmTextPart | LlmImagePart;+/**+ * File segment of a multimodal message (e.g. a PDF). Like image parts, the+ * file is referenced by its Trilium attachment ID and resolved to bytes+ * server-side. Provider support varies by MIME type — PDFs (`application/pdf`)+ * are handled natively by Anthropic, OpenAI, and Google.+ */+export interface LlmFilePart {+ type: "file";+ attachmentId: string;+ mime: string;+ filename: string;+}++export type LlmMessagePart = LlmTextPart | LlmImagePart | LlmFilePart;/*** A chat message in the conversation. `content` may be a plain string (the