| 1 | import { Writable } from "stream"; |
| 2 | import { |
| 3 | AssistantChatMessage, |
| 4 | ChatMessage, |
| 5 | LLMInteractionCancel, |
| 6 | LLMInteractionError, |
| 7 | LLMInteractionItem, |
| 8 | LLMInteractionStartChat, |
| 9 | LLMInteractionStartComplete, |
| 10 | LLMInteractionStartFim, |
| 11 | LLMInteractionSuccess, |
| 12 | ThinkingChatMessage, |
| 13 | ToolCallDelta, |
| 14 | UserChatMessage, |
| 15 | } from ".."; |
| 16 | import { LLMLogger } from "./logger"; |
| 17 | |
| 18 | // Markers for different overlapping interactions. |
| 19 | const LOG_PREFIXES = [" ", "|", "&", "%", "#"]; |
| 20 | // Wrap wide to avoid messing up code |
| 21 | const DEFAULT_WRAP_WIDTH = 100; |
| 22 | |
| 23 | interface InteractionData { |
| 24 | prefix: string; |
| 25 | startItem: LLMInteractionItem; |
| 26 | lastItem: LLMInteractionItem | null; |
| 27 | } |
| 28 | |
| 29 | function formatTimestamp(timestamp: number) { |
| 30 | const date = new Date(timestamp); |
| 31 | |
| 32 | const hours = date.getUTCHours().toString().padStart(2, "0"); |
| 33 | const minutes = date.getUTCMinutes().toString().padStart(2, "0"); |
| 34 | const seconds = date.getUTCSeconds(); |
| 35 | const milliseconds = date.getUTCMilliseconds(); |
| 36 | |
| 37 | // Format seconds with one decimal place |
| 38 | const secondsFormatted = `${seconds}.${Math.floor(milliseconds / 100)}`; |
| 39 | |
| 40 | return `${hours}:${minutes}:${secondsFormatted.padStart(4, "0")}`; |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * A class that formats LLM log output as a human-readable stream. |
| 45 | * The general appearance of the output is something like: |
| 46 | * |
| 47 | * 01:23:45.6 [Chat] |
| 48 | * Options: { |
| 49 | * "maxTokens": 1000, |
| 50 | * } |
| 51 | * Role: system |
| 52 | * | You are a helpful assistant. |
| 53 | * Role: user |
| 54 | * | Who are you? |
| 55 | * +0.2 Role: assistant |
| 56 | * | How can I help you today? |
| 57 | * +0.3 | I can tell you about the weather or the stock mark |
| 58 | * +0.4 . et. [THIS LINE IS WRAPPED] |
| 59 | * |01:23:46.1 [Complete] |
| 60 | * | Options: { |
| 61 | * | "maxTokens": 1000, |
| 62 | * | } |
| 63 | * | Prefix: |
| 64 | * | | COMPLETE THIS |
| 65 | * +0.6 Success |
| 66 | * PromptTokens: 50 |
| 67 | * GeneratedTokens: 30 |
| 68 | * | +0.2 Result: |
| 69 | * | | COMPLETION |
| 70 | * |
| 71 | * The lines with | are a second interaction that starts while the |
| 72 | * first one is still in progress; every interaction starts with |
| 73 | * an absolute timestamp, and relative timestamps are included for |
| 74 | * separately received results in the same interaction. |
| 75 | */ |
| 76 | export class LLMLogFormatter { |
| 77 | // Current active interactions |
| 78 | private interactions: Record<string, InteractionData> = {}; |
| 79 | private lastItem: LLMInteractionItem | null = null; |
| 80 | // Item that started the current line; we use this to determine |
| 81 | // if the next line needs a timestamp. |
| 82 | private lastLineStartItem: LLMInteractionItem | null = null; |
| 83 | private openLine: boolean = false; |
| 84 | private openLineChars: number = 0; |
| 85 | private lastFreedPrefix: string | null = null; |
| 86 | |
| 87 | /** |
| 88 | * Creates a new LLMLogWriter. |
| 89 | * @param logger - The LLMLogger instance to listen to for log items |
| 90 | * @param output - Stream to write formatted output to |
| 91 | * @param wrapWidth - Maximum width of a line before wrapping |
| 92 | */ |
| 93 | constructor( |
| 94 | private logger: LLMLogger, |
| 95 | private output: Writable, |
| 96 | private wrapWidth: number = DEFAULT_WRAP_WIDTH, |
| 97 | ) { |
| 98 | this.logger.onLogItem((item) => { |
| 99 | this.logItem(item); |
| 100 | }); |
| 101 | } |
| 102 | |
| 103 | private getInteractionData(item: LLMInteractionItem) { |
| 104 | let interaction = this.interactions[item.interactionId]; |
| 105 | if (interaction !== undefined) { |
| 106 | return interaction; |
| 107 | } |
| 108 | |
| 109 | let usedPrefixes = Object.values(this.interactions).map( |
| 110 | (interaction) => interaction.prefix, |
| 111 | ); |
| 112 | |
| 113 | // Select a prefix that is not currently in use, and is |
| 114 | // also not the last retired prefix - but with the |
| 115 | // exception that we can reuse the empty prefix " " |
| 116 | // immediately - this isn't confusing. |
| 117 | let i = 0; |
| 118 | let prefix; |
| 119 | while (true) { |
| 120 | const candidate = i < LOG_PREFIXES.length ? LOG_PREFIXES[i] : `X`; |
| 121 | if ( |
| 122 | !usedPrefixes.includes(candidate) && |
| 123 | (candidate === " " || candidate !== this.lastFreedPrefix) |
| 124 | ) { |
| 125 | prefix = candidate; |
| 126 | break; |
| 127 | } |
| 128 | i++; |
| 129 | } |
| 130 | |
| 131 | this.interactions[item.interactionId] = { |
| 132 | prefix, |
| 133 | startItem: item, |
| 134 | lastItem: null, |
| 135 | }; |
| 136 | |
| 137 | return this.interactions[item.interactionId]; |
| 138 | } |
| 139 | |
| 140 | private formatTimestamp( |
| 141 | interaction: InteractionData, |
| 142 | item: LLMInteractionItem, |
| 143 | ) { |
| 144 | if (item !== this.lastLineStartItem) { |
| 145 | if (item === interaction.startItem) { |
| 146 | return formatTimestamp(item.timestamp); |
| 147 | } else { |
| 148 | const delta = (item.timestamp - interaction.startItem.timestamp) / 1000; |
| 149 | return ("+" + delta.toFixed(1)).padStart(10, " "); |
| 150 | } |
| 151 | } else { |
| 152 | return " "; |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // the implementation behind logLines and logMessageText |
| 157 | private logFragment( |
| 158 | item: LLMInteractionItem, |
| 159 | fragment: string, |
| 160 | startAt: number, |
| 161 | marker: string = "", |
| 162 | joinBefore: boolean = false, |
| 163 | joinAfter: boolean = false, |
| 164 | wrap: boolean = false, |
| 165 | ) { |
| 166 | const interaction = this.getInteractionData(item); |
| 167 | |
| 168 | if ( |
| 169 | this.openLine && |
| 170 | (!joinBefore || item.interactionId !== this.lastItem?.interactionId) |
| 171 | ) { |
| 172 | this.openLine = false; |
| 173 | this.openLineChars = 0; |
| 174 | this.output.write("\n"); |
| 175 | } |
| 176 | |
| 177 | let continueAt = null; |
| 178 | if ( |
| 179 | wrap && |
| 180 | fragment.length - startAt > this.wrapWidth - this.openLineChars |
| 181 | ) { |
| 182 | continueAt = startAt + this.wrapWidth - this.openLineChars; |
| 183 | |
| 184 | // Look for a better line-breaking point at whitespace |
| 185 | const searchBackwardLimit = Math.max(startAt, continueAt - 20); // Don't look back too far |
| 186 | for (let i = continueAt; i > searchBackwardLimit; i--) { |
| 187 | if (/\s/.test(fragment.charAt(i))) { |
| 188 | continueAt = i + 1; // Break after the whitespace |
| 189 | break; |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | // When there's whitespace immediately after the wrap width, |
| 194 | // the above will result in breaking *after* that, so we exceed |
| 195 | // the wrap width. The trimEnd() avoids that. |
| 196 | fragment = fragment.substring(startAt, continueAt).trimEnd(); |
| 197 | joinAfter = false; |
| 198 | } else if (startAt > 0) { |
| 199 | fragment = fragment.substring(startAt); |
| 200 | } |
| 201 | |
| 202 | if (!this.openLine || !this.openLine) { |
| 203 | let timestamp = this.formatTimestamp(interaction, item); |
| 204 | this.output.write(`${interaction.prefix}${timestamp} ${marker}`); |
| 205 | this.lastLineStartItem = item; |
| 206 | } |
| 207 | |
| 208 | this.output.write(fragment); |
| 209 | this.openLine = joinAfter; |
| 210 | this.lastItem = item; |
| 211 | if (!this.openLine) { |
| 212 | this.output.write("\n"); |
| 213 | this.openLineChars = 0; |
| 214 | } else { |
| 215 | this.openLineChars += fragment.length; |
| 216 | } |
| 217 | |
| 218 | return continueAt; |
| 219 | } |
| 220 | |
| 221 | // Use for everything but text content; a newline is |
| 222 | // implicitly added at the end of content |
| 223 | private logLines( |
| 224 | item: LLMInteractionItem, |
| 225 | content: string, |
| 226 | marker: string = "", |
| 227 | ) { |
| 228 | for (const line of content.split("\n")) { |
| 229 | this.logFragment(item, line, 0, marker); |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | // This logs text context - as compared to logLines: |
| 234 | // - No newline is appended to the end of content |
| 235 | // - consecutive calls to logMessageText for the same interaction |
| 236 | // will join onto a single line |
| 237 | // - It will wrap text at the wrap width |
| 238 | private logMessageText(item: LLMInteractionItem, content: string) { |
| 239 | const lines = content.split("\n"); |
| 240 | for (let i = 0; i < lines.length; i++) { |
| 241 | let startAt: number | null = 0; |
| 242 | let marker = "| "; |
| 243 | while (startAt !== null) { |
| 244 | // When wrapping, the next start position is turned; |
| 245 | // null means we've written everything |
| 246 | startAt = this.logFragment( |
| 247 | item, |
| 248 | lines[i], |
| 249 | startAt, |
| 250 | marker, |
| 251 | true, |
| 252 | i === lines.length - 1, |
| 253 | true, |
| 254 | ); |
| 255 | marker = ". "; |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | private logToolcalls(item: LLMInteractionItem, toolsCalls: ToolCallDelta[]) { |
| 261 | for (const toolCall of toolsCalls) { |
| 262 | this.logLines( |
| 263 | item, |
| 264 | `Tool call: ${JSON.stringify(toolCall, undefined, 2)}`, |
| 265 | ); |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | private logMessageContent( |
| 270 | item: LLMInteractionItem, |
| 271 | message: AssistantChatMessage | UserChatMessage | ThinkingChatMessage, |
| 272 | ) { |
| 273 | if (typeof message.content === "string") { |
| 274 | this.logMessageText(item, message.content); |
| 275 | } else { |
| 276 | for (const part of message.content) { |
| 277 | if (part.type === "text") { |
| 278 | this.logMessageText(item, part.text); |
| 279 | } else { |
| 280 | this.logLines(item, `Image: ${part.imageUrl.url}`); |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | private logMessage( |
| 287 | item: LLMInteractionItem, |
| 288 | message: ChatMessage, |
| 289 | forceRole: boolean = false, |
| 290 | ) { |
| 291 | let showRole = true; |
| 292 | if ( |
| 293 | !forceRole && |
| 294 | (message.role === "assistant" || message.role === "thinking") |
| 295 | ) { |
| 296 | const interaction = this.getInteractionData(item); |
| 297 | const lastMessage = |
| 298 | interaction.lastItem?.kind === "message" |
| 299 | ? interaction.lastItem.message |
| 300 | : null; |
| 301 | if (message.role === lastMessage?.role) { |
| 302 | showRole = false; |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | if (showRole) { |
| 307 | this.logLines(item, "Role: " + message.role); |
| 308 | } |
| 309 | |
| 310 | switch (message.role) { |
| 311 | case "assistant": |
| 312 | if (message.toolCalls) { |
| 313 | this.logToolcalls(item, message.toolCalls); |
| 314 | } |
| 315 | this.logMessageContent(item, message); |
| 316 | break; |
| 317 | case "thinking": |
| 318 | if (message.toolCalls) { |
| 319 | this.logToolcalls(item, message.toolCalls); |
| 320 | } |
| 321 | this.logMessageContent(item, message); |
| 322 | if (message.redactedThinking) { |
| 323 | this.logLines(item, `Redacted Thinking: ${message.redactedThinking}`); |
| 324 | } |
| 325 | if (message.signature) { |
| 326 | this.logLines(item, `Signature: ${message.signature}`); |
| 327 | } |
| 328 | break; |
| 329 | case "user": |
| 330 | this.logMessageContent(item, message); |
| 331 | break; |
| 332 | case "system": |
| 333 | this.logMessageText(item, message.content); |
| 334 | break; |
| 335 | case "tool": |
| 336 | this.logLines(item, `Tool Call ID: ${message.toolCallId}`); |
| 337 | this.logMessageText(item, message.content); |
| 338 | break; |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | private logTokens( |
| 343 | item: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel, |
| 344 | ) { |
| 345 | this.logLines(item, `Prompt Tokens: ${item.promptTokens}`); |
| 346 | this.logLines(item, `Generated Tokens: ${item.generatedTokens}`); |
| 347 | if (item.thinkingTokens > 0) { |
| 348 | this.logLines(item, `Thinking Tokens: ${item.thinkingTokens}`); |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | private logOptions( |
| 353 | item: |
| 354 | | LLMInteractionStartChat |
| 355 | | LLMInteractionStartComplete |
| 356 | | LLMInteractionStartFim, |
| 357 | ) { |
| 358 | this.logLines( |
| 359 | item, |
| 360 | "Options: " + JSON.stringify(item.options, undefined, 2), |
| 361 | ); |
| 362 | } |
| 363 | |
| 364 | private logItem(item: LLMInteractionItem) { |
| 365 | const interaction = this.getInteractionData(item); |
| 366 | |
| 367 | switch (item.kind) { |
| 368 | case "startChat": |
| 369 | this.logLines(item, "[Chat]"); |
| 370 | this.logOptions(item); |
| 371 | let lastMessage = null; |
| 372 | for (let message of item.messages) { |
| 373 | this.logMessage(item, message, true); |
| 374 | } |
| 375 | break; |
| 376 | case "startComplete": |
| 377 | this.logLines(item, "[Complete]"); |
| 378 | this.logOptions(item); |
| 379 | this.logLines(item, "Prompt:"); |
| 380 | this.logLines(item, item.prompt, "| "); |
| 381 | break; |
| 382 | case "startFim": |
| 383 | this.logLines(item, "[Fim]"); |
| 384 | this.logOptions(item); |
| 385 | this.logLines(item, "Prefix:"); |
| 386 | this.logLines(item, item.prefix, "| "); |
| 387 | this.logLines(item, "Suffix:"); |
| 388 | this.logLines(item, item.suffix, "| "); |
| 389 | break; |
| 390 | case "chunk": |
| 391 | if (interaction.lastItem?.kind !== "chunk") { |
| 392 | this.logLines(item, "Result:"); |
| 393 | } |
| 394 | this.logMessageText(item, item.chunk); |
| 395 | break; |
| 396 | case "message": |
| 397 | this.logMessage(item, item.message); |
| 398 | break; |
| 399 | case "cancel": |
| 400 | this.logLines(item, "Cancelled"); |
| 401 | this.logTokens(item); |
| 402 | break; |
| 403 | case "error": |
| 404 | this.logLines(item, "Error"); |
| 405 | this.logTokens(item); |
| 406 | break; |
| 407 | case "success": |
| 408 | this.logLines(item, "Success"); |
| 409 | this.logTokens(item); |
| 410 | break; |
| 411 | } |
| 412 | |
| 413 | if ( |
| 414 | item.kind === "cancel" || |
| 415 | item.kind === "error" || |
| 416 | item.kind === "success" |
| 417 | ) { |
| 418 | if (interaction.prefix !== " ") { |
| 419 | this.lastFreedPrefix = interaction.prefix; |
| 420 | } |
| 421 | delete this.interactions[item.interactionId]; |
| 422 | } else { |
| 423 | interaction.lastItem = item; |
| 424 | } |
| 425 | } |
| 426 | } |