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): support streaming tool calls
Elian Doran219210f80df1
diff --git a/apps/client/src/services/llm_chat.ts b/apps/client/src/services/llm_chat.tsindex aecabba7aa..e5f48094fd 100644--- a/apps/client/src/services/llm_chat.ts+++ b/apps/client/src/services/llm_chat.ts@@ -13,8 +13,10 @@ export async function getAvailableModels(): Promise<LlmModelInfo[]> {export interface StreamCallbacks {onChunk: (text: string) => void;onThinking?: (text: string) => void;- onToolUse?: (toolName: string, input: Record<string, unknown>) => void;- onToolResult?: (toolName: string, result: string, isError?: boolean) => void;+ onToolInputStart?: (toolCallId: string, toolName: string) => void;+ onToolInputDelta?: (toolCallId: string, delta: string) => void;+ onToolUse?: (toolCallId: string, toolName: string, input: Record<string, unknown>) => void;+ onToolResult?: (toolCallId: string, toolName: string, result: string, isError?: boolean) => void;onCitation?: (citation: LlmCitation) => void;onUsage?: (usage: LlmUsage) => void;onError: (error: string) => void;@@ -89,14 +91,23 @@ export async function streamChatCompletion(case "thinking":callbacks.onThinking?.(data.content);break;+ case "tool_input_start":+ callbacks.onToolInputStart?.(data.toolCallId, data.toolName);+ // Yield to force Preact to commit the pending tool call+ // state before any deltas arrive.+ await new Promise((r) => setTimeout(r, 1));+ break;+ case "tool_input_delta":+ callbacks.onToolInputDelta?.(data.toolCallId, data.delta);+ break;case "tool_use":- callbacks.onToolUse?.(data.toolName, data.toolInput);+ callbacks.onToolUse?.(data.toolCallId, data.toolName, data.toolInput);// Yield to force Preact to commit the pending tool call// state before we process the result.await new Promise((r) => setTimeout(r, 1));break;case "tool_result":- callbacks.onToolResult?.(data.toolName, data.result, data.isError);+ callbacks.onToolResult?.(data.toolCallId, data.toolName, data.result, data.isError);await new Promise((r) => setTimeout(r, 1));break;case "citation":diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 6e756f400f..94408a0a04 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1795,6 +1795,7 @@"thought_process": "Thought process","tool_calls": "{{count}} tool call(s)","input": "Input",+ "input_streaming": "Input (streaming…)","edit_index": "Edit {{index}} of {{total}}","result": "Result","error": "Error",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.css b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.cssindex 4473e0d16d..489a92cdca 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.css@@ -119,3 +119,20 @@.llm-chat-tool-call-result-error pre {color: var(--danger-color, #dc3545);}++/* Streaming-input view: raw JSON arriving from the LLM, shown until it's parsed.+ The trailing block-caret hints that text is still landing. */+.llm-chat-tool-call-input-streaming pre {+ white-space: pre-wrap;+ word-break: break-word;+}++.llm-chat-tool-call-input-streaming pre::after {+ content: "▍";+ color: var(--muted-text-color);+ animation: llm-chat-tool-call-caret 1s steps(1) infinite;+}++@keyframes llm-chat-tool-call-caret {+ 50% { opacity: 0; }+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsxindex 80f9d0d646..561d29c267 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsx@@ -186,9 +186,11 @@ function ToolCallLabel({ toolCall }: { toolCall: ToolCall }) {/** A single tool call section within a ToolCallCard. */function ToolCallSection({ toolCall }: { toolCall: ToolCall }) {const hasError = toolCall.isError;+ const isStreamingInput = toolCall.inputStreaming !== undefined;// The `edit_note_content` tool gets a fancy unified diff instead of a raw input table.- const noteContentEdits = toolCall.toolName === "edit_note_content"+ // Suppress the diff view while input is still streaming — the partial JSON isn't parseable yet.+ const noteContentEdits = !isStreamingInput && toolCall.toolName === "edit_note_content"? parseNoteContentEdits(toolCall.input?.edits): null;@@ -197,10 +199,15 @@ function ToolCallSection({ toolCall }: { toolCall: ToolCall }) {icon={toolCallIcon(toolCall)}label={<ToolCallLabel toolCall={toolCall} />}className={hasError ? "llm-chat-tool-call-error" : ""}- open={noteContentEdits ? isSmallEdit(noteContentEdits) : undefined}+ open={noteContentEdits ? isSmallEdit(noteContentEdits) : isStreamingInput || undefined}>- <div className="llm-chat-tool-call-input">- {noteContentEdits ? (+ <div className={`llm-chat-tool-call-input ${isStreamingInput ? "llm-chat-tool-call-input-streaming" : ""}`}>+ {isStreamingInput ? (+ <>+ <strong>{t("llm_chat.input_streaming")}</strong>+ <pre>{toolCall.inputStreaming}</pre>+ </>+ ) : noteContentEdits ? (<EditNoteContentDiff edits={noteContentEdits} />) : (<>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 d05bf291b5..1fa74fe6af 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@@ -6,6 +6,11 @@ export interface ToolCall {id: string;toolName: string;input: Record<string, unknown>;+ /**+ * Raw JSON arguments accumulated from `tool_input_delta` chunks while the call's input+ * is still streaming. Cleared once the parsed `input` arrives via the `tool_use` chunk.+ */+ inputStreaming?: string;result?: string;isError?: boolean;}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex d04ff81a02..a391f0ff61 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@ -274,12 +274,18 @@ export function useLlmChat(/** Shared cleanup: finalize collected content and reset streaming state. */function finalizeStream() {- // Mark any in-progress tool calls as stopped so they don't show infinite spinners+ // Mark any in-progress tool calls as stopped so they don't show infinite spinners.+ // Also clear `inputStreaming` so a half-streamed JSON arg list doesn't render.for (const [i, block] of contentBlocks.entries()) {if (block.type === "tool_call" && !block.toolCall.result) {contentBlocks[i] = {type: "tool_call",- toolCall: { ...block.toolCall, result: "[Stopped]", isError: true }+ toolCall: {+ ...block.toolCall,+ inputStreaming: undefined,+ result: "[Stopped]",+ isError: true+ }};}}@@ -335,22 +341,64 @@ export function useLlmChat(thinkingContent += text;setStreamingThinking(thinkingContent);},- onToolUse: (toolName, toolInput) => {+ onToolInputStart: (toolCallId, toolName) => {contentBlocks.push({type: "tool_call",toolCall: {- id: randomString(),+ id: toolCallId,toolName,- input: toolInput+ input: {},+ inputStreaming: ""+ }+ });+ setStreamingBlocks([...contentBlocks]);+ },+ onToolInputDelta: (toolCallId, delta) => {+ for (let i = contentBlocks.length - 1; i >= 0; i--) {+ const block = contentBlocks[i];+ if (block.type === "tool_call" && block.toolCall.id === toolCallId) {+ contentBlocks[i] = {+ type: "tool_call",+ toolCall: {+ ...block.toolCall,+ inputStreaming: (block.toolCall.inputStreaming ?? "") + delta+ }+ };+ break;}+ }+ setStreamingBlocks([...contentBlocks]);+ },+ onToolUse: (toolCallId, toolName, toolInput) => {+ // Some providers skip tool-input-start/delta entirely and only emit+ // the final tool-call. In that case there's no pending block to update,+ // so push a fresh one.+ for (let i = contentBlocks.length - 1; i >= 0; i--) {+ const block = contentBlocks[i];+ if (block.type === "tool_call" && block.toolCall.id === toolCallId) {+ contentBlocks[i] = {+ type: "tool_call",+ toolCall: {+ ...block.toolCall,+ input: toolInput,+ inputStreaming: undefined+ }+ };+ setStreamingBlocks([...contentBlocks]);+ return;+ }+ }+ contentBlocks.push({+ type: "tool_call",+ toolCall: { id: toolCallId, toolName, input: toolInput }});setStreamingBlocks([...contentBlocks]);},- onToolResult: (toolName, result, isError) => {+ onToolResult: (toolCallId, _toolName, result, isError) => {// Replace the matching block with a new object so Preact sees the change.for (let i = contentBlocks.length - 1; i >= 0; i--) {const block = contentBlocks[i];- if (block.type === "tool_call" && block.toolCall.toolName === toolName && !block.toolCall.result) {+ if (block.type === "tool_call" && block.toolCall.id === toolCallId) {contentBlocks[i] = {type: "tool_call",toolCall: { ...block.toolCall, result, isError }diff --git a/apps/server/src/services/llm/stream.spec.ts b/apps/server/src/services/llm/stream.spec.tsindex 319ce43b13..a8fa3b2849 100644--- a/apps/server/src/services/llm/stream.spec.ts+++ b/apps/server/src/services/llm/stream.spec.ts@@ -112,6 +112,70 @@ describe("streamToChunks", () => {expect(errorsOf(chunks)[0].error).toContain("No output generated");expect(chunks.some(c => c.type === "done")).toBe(false);});++ it("streams tool input deltas with the same id used by the final tool-call", async () => {+ // The AI SDK emits the JSON arguments incrementally as `tool-input-delta` chunks+ // before the parsed `tool-call` arrives — clients use the shared id to attach+ // each delta to the right pending tool block.+ const chunks = await collect(fakeResult(+ [+ { type: "tool-input-start", id: "call_42", toolName: "search_notes" },+ { type: "tool-input-delta", id: "call_42", delta: "{\"query\":\"" },+ { type: "tool-input-delta", id: "call_42", delta: "trilium\"}" },+ { type: "tool-call", toolCallId: "call_42", toolName: "search_notes", input: { query: "trilium" } },+ { type: "tool-result", toolCallId: "call_42", toolName: "search_notes", output: "[]" }+ ],+ Promise.resolve({ inputTokens: 1, outputTokens: 1 })+ ));++ expect(chunks).toEqual([+ { type: "tool_input_start", toolCallId: "call_42", toolName: "search_notes" },+ { type: "tool_input_delta", toolCallId: "call_42", delta: "{\"query\":\"" },+ { type: "tool_input_delta", toolCallId: "call_42", delta: "trilium\"}" },+ {+ type: "tool_use",+ toolCallId: "call_42",+ toolName: "search_notes",+ toolInput: { query: "trilium" }+ },+ {+ type: "tool_result",+ toolCallId: "call_42",+ toolName: "search_notes",+ result: "[]",+ isError: false+ },+ {+ type: "usage",+ usage: { promptTokens: 1, completionTokens: 1, totalTokens: 2, cost: undefined, model: undefined }+ },+ { type: "done" }+ ]);+ });++ it("interleaves input deltas for parallel tool calls and forwards distinct ids", async () => {+ // Two parallel tool calls with the same name; without per-call ids the client+ // couldn't tell whose delta belonged to whom.+ const chunks = await collect(fakeResult(+ [+ { type: "tool-input-start", id: "a", toolName: "search_notes" },+ { type: "tool-input-start", id: "b", toolName: "search_notes" },+ { type: "tool-input-delta", id: "a", delta: "{\"query\":\"x\"}" },+ { type: "tool-input-delta", id: "b", delta: "{\"query\":\"y\"}" },+ { type: "tool-call", toolCallId: "a", toolName: "search_notes", input: { query: "x" } },+ { type: "tool-call", toolCallId: "b", toolName: "search_notes", input: { query: "y" } }+ ],+ Promise.resolve({ inputTokens: 1, outputTokens: 1 })+ ));++ const idsByType = chunks.reduce<Record<string, string[]>>((acc, c) => {+ if ("toolCallId" in c) (acc[c.type] ??= []).push(c.toolCallId);+ return acc;+ }, {});+ expect(idsByType.tool_input_start).toEqual(["a", "b"]);+ expect(idsByType.tool_input_delta).toEqual(["a", "b"]);+ expect(idsByType.tool_use).toEqual(["a", "b"]);+ });});describe("describeStreamError", () => {diff --git a/apps/server/src/services/llm/stream.ts b/apps/server/src/services/llm/stream.tsindex 82b4da168f..25848516e3 100644--- a/apps/server/src/services/llm/stream.ts+++ b/apps/server/src/services/llm/stream.ts@@ -94,9 +94,26 @@ export async function* streamToChunks(result: StreamResult, options: StreamOptioyield { type: "thinking", content: part.text };break;+ case "tool-input-start":+ yield {+ type: "tool_input_start",+ toolCallId: part.id,+ toolName: part.toolName+ };+ break;++ case "tool-input-delta":+ yield {+ type: "tool_input_delta",+ toolCallId: part.id,+ delta: part.delta+ };+ break;+case "tool-call":yield {type: "tool_use",+ toolCallId: part.toolCallId,toolName: part.toolName,toolInput: part.input as Record<string, unknown>};@@ -107,6 +124,7 @@ export async function* streamToChunks(result: StreamResult, options: StreamOptioconst isError = typeof output === "object" && output !== null && "error" in output;yield {type: "tool_result",+ toolCallId: part.toolCallId,toolName: part.toolName,result: typeof output === "string"? outputdiff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.tsindex 7554d9d40c..69fde290f5 100644--- a/packages/commons/src/lib/llm_api.ts+++ b/packages/commons/src/lib/llm_api.ts@@ -97,8 +97,10 @@ export interface LlmUsage {export type LlmStreamChunk =| { type: "text"; content: string }| { type: "thinking"; content: string }- | { type: "tool_use"; toolName: string; toolInput: Record<string, unknown> }- | { type: "tool_result"; toolName: string; result: string; isError?: boolean }+ | { type: "tool_input_start"; toolCallId: string; toolName: string }+ | { type: "tool_input_delta"; toolCallId: string; delta: string }+ | { type: "tool_use"; toolCallId: string; toolName: string; toolInput: Record<string, unknown> }+ | { type: "tool_result"; toolCallId: string; toolName: string; result: string; isError?: boolean }| { type: "citation"; citation: LlmCitation }| { type: "usage"; usage: LlmUsage }| { type: "error"; error: string }