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): display usage info (prompt + completion)
Elian Doran89638e3f561f
diff --git a/apps/client/src/services/llm_chat.ts b/apps/client/src/services/llm_chat.tsindex a985683f7c..3a4c291468 100644--- a/apps/client/src/services/llm_chat.ts+++ b/apps/client/src/services/llm_chat.ts@@ -1,4 +1,4 @@-import type { LlmMessage, LlmCitation, LlmChatConfig } from "@triliumnext/commons";+import type { LlmMessage, LlmCitation, LlmChatConfig, LlmUsage } from "@triliumnext/commons";import server from "./server.js";export interface StreamCallbacks {@@ -7,6 +7,7 @@ export interface StreamCallbacks {onToolUse?: (toolName: string, input: Record<string, unknown>) => void;onToolResult?: (toolName: string, result: string) => void;onCitation?: (citation: LlmCitation) => void;+ onUsage?: (usage: LlmUsage) => void;onError: (error: string) => void;onDone: () => void;}@@ -76,6 +77,11 @@ export async function streamChatCompletion(callbacks.onCitation?.(data.citation);}break;+ case "usage":+ if (data.usage) {+ callbacks.onUsage?.(data.usage);+ }+ break;case "error":callbacks.onError(data.error);break;diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 64728311bd..ea2a6cb851 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1625,7 +1625,8 @@"thought_process": "Thought process","tool_calls": "{{count}} tool call(s)","input": "Input",- "result": "Result"+ "result": "Result",+ "tokens_used": "{{prompt}} prompt + {{completion}} completion = {{total}} tokens"},"shared_switch": {"shared": "Shared",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsxindex 0f700d6416..fa31ff7b67 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx@@ -1,4 +1,4 @@-import type { LlmCitation } from "@triliumnext/commons";+import type { LlmCitation, LlmUsage } from "@triliumnext/commons";import { useMemo } from "preact/hooks";import { marked } from "marked";import { t } from "../../../services/i18n.js";@@ -29,6 +29,8 @@ interface StoredMessage {type?: MessageType;/** Tool calls made during this response */toolCalls?: ToolCall[];+ /** Token usage for this response */+ usage?: LlmUsage;}interface Props {@@ -169,6 +171,18 @@ export default function ChatMessage({ message, isStreaming }: Props) {</ul></div>)}+ {message.usage && typeof message.usage.promptTokens === "number" && (+ <div className="llm-chat-usage">+ <span className="bx bx-chip" />+ <span className="llm-chat-usage-text">+ {t("llm_chat.tokens_used", {+ prompt: message.usage.promptTokens.toLocaleString(),+ completion: message.usage.completionTokens.toLocaleString(),+ total: message.usage.totalTokens.toLocaleString()+ })}+ </span>+ </div>+ )}</div>);}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.css b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.cssindex 66c42c8eac..5ce7947df2 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.css@@ -505,3 +505,23 @@max-height: 200px;overflow-y: auto;}++/* Token usage display */+.llm-chat-usage {+ display: flex;+ align-items: center;+ gap: 0.375rem;+ margin-top: 0.75rem;+ padding-top: 0.5rem;+ border-top: 1px solid var(--main-border-color);+ font-size: 0.75rem;+ color: var(--muted-text-color);+}++.llm-chat-usage .bx {+ font-size: 0.875rem;+}++.llm-chat-usage-text {+ font-family: var(--monospace-font-family, monospace);+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsxindex 6f4ed84d71..bc78f3a41c 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx@@ -1,4 +1,4 @@-import type { LlmCitation, LlmMessage } from "@triliumnext/commons";+import type { LlmCitation, LlmMessage, LlmUsage } from "@triliumnext/commons";import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n.js";import { streamChatCompletion } from "../../../services/llm_chat.js";@@ -27,6 +27,8 @@ interface StoredMessage {type?: MessageType;/** Tool calls made during this response */toolCalls?: ToolCall[];+ /** Token usage for this response */+ usage?: LlmUsage;}interface LlmChatContent {@@ -147,6 +149,7 @@ export default function LlmChat({ note, ntxId, noteContext }: TypeWidgetProps) {let thinkingContent = "";const citations: LlmCitation[] = [];const toolCalls: ToolCall[] = [];+ let usage: LlmUsage | undefined;const apiMessages: LlmMessage[] = newMessages.map(m => ({role: m.role,@@ -190,6 +193,9 @@ export default function LlmChat({ note, ntxId, noteContext }: TypeWidgetProps) {citations.push(citation);setPendingCitations([...citations]);},+ onUsage: (u) => {+ usage = u;+ },onError: (errorMsg) => {console.error("Chat error:", errorMsg);// Persist error as an assistant message@@ -228,7 +234,8 @@ export default function LlmChat({ note, ntxId, noteContext }: TypeWidgetProps) {content: assistantContent,createdAt: new Date().toISOString(),citations: citations.length > 0 ? citations : undefined,- toolCalls: toolCalls.length > 0 ? toolCalls : undefined+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,+ usage});}diff --git a/apps/server/src/services/llm/stream.ts b/apps/server/src/services/llm/stream.tsindex 8e548fa26e..dc7921d84c 100644--- a/apps/server/src/services/llm/stream.ts+++ b/apps/server/src/services/llm/stream.ts@@ -3,6 +3,7 @@*/import type { LlmStreamChunk } from "@triliumnext/commons";+import type { StreamResult } from "./types.js";/**@@ -58,6 +59,19 @@ export async function* streamToChunks(result: StreamResult): AsyncIterable<LlmSt}}+ // Get usage information after stream completes+ const usage = await result.usage;+ if (usage && typeof usage.inputTokens === "number" && typeof usage.outputTokens === "number") {+ yield {+ type: "usage",+ usage: {+ promptTokens: usage.inputTokens,+ completionTokens: usage.outputTokens,+ totalTokens: usage.inputTokens + usage.outputTokens+ }+ };+ }+yield { type: "done" };} catch (error) {const message = error instanceof Error ? error.message : "Unknown error";diff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.tsindex 881cfd2ecc..5e13b7a69c 100644--- a/packages/commons/src/lib/llm_api.ts+++ b/packages/commons/src/lib/llm_api.ts@@ -41,6 +41,15 @@ export interface LlmChatConfig {thinkingBudget?: number;}+/**+ * Token usage information from the LLM response.+ */+export interface LlmUsage {+ promptTokens: number;+ completionTokens: number;+ totalTokens: number;+}+/*** Stream chunk types for real-time SSE updates.* Defines the protocol between server and client.@@ -51,5 +60,6 @@ export type LlmStreamChunk =| { type: "tool_use"; toolName: string; toolInput: Record<string, unknown> }| { type: "tool_result"; toolName: string; result: string }| { type: "citation"; citation: LlmCitation }+ | { type: "usage"; usage: LlmUsage }| { type: "error"; error: string }| { type: "done" };