# All files / src/chat Chat.ts

91.17% Statements 186/204
85.38% Branches 146/171
91.42% Functions 32/35
92% Lines 184/200

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699

    124x
    124x

    124x
    124x
    124x

    124x

    124x
    1x

    124x
    1x
    2x
    1x

    1x

    124x
    124x

    124x
    15x
    15x
    15x

    41x

    3x

    2x

    8x
    4x
    4x
    4x
    4x
    4x

    4x

    8x

    23x

    44x
    2x

    44x
    25x

    44x
    46x
    46x
    43x

    41x

    12x
    2x

    12x

    12x

    2x

    1x

    2x

    2x

    2x

    5x
    5x

    1x
    1x

    5x
    5x

    5x

    5x

    6x
    6x

    5x

    5x

    5x
    4x

    1x

    5x

    4x
    4x

    3x

    2x
    2x

    3x
    3x

    1x

    2x
    2x

    1x
    1x

    5x
    5x

    3x
    3x

    3x
    3x

    2x
    2x

    94x
    94x
    94x
    13x
    11x

    11x
    11x

    92x
    24x

    91x

    91x

    91x
    5x

    5x

    5x

    91x

    94x
    2x
    2x
    1x

    1x

    90x
    90x
    113x
    49x
    49x
    49x
    49x

    49x
    37x

    90x
    90x
    90x

    90x

    94x
    1x
    1x
    1x

    90x

    94x
    1x

    90x
    94x

    94x

    30x
    1x

    29x
    29x
    2x

    27x

    28x
    2x

    2x
    1x

    1x

    27x
    27x

    19x

    8x
    8x

    8x
    1x

    7x
    1x
    1x

    1x

    1x

    6x

    6x
    1x

    5x

    5x

    8x
    3x

    2x

    23x

    23x

    23x

    30x

    23x

    30x

    84x

    13x

    13x

    46x
    10x
    10x

    36x

    46x

    46x
    8x

    38x

    38x

    1x

    37x

    9x

    37x

    2x

    35x

     import { FileLoader } from "../utils/FileLoader.js";
    import { Message } from "./Message.js";
    import {
      ContentPart,
      isBinaryContent,
      formatMultimodalContent,
      MessageContent
    } from "./Content.js";
    import { ChatOptions } from "./ChatOptions.js";
    import {
      Provider,
      Usage,
      ChatChunk,
      ResponseFormat,
      ThinkingConfig
    } from "../providers/Provider.js";
    import { Executor } from "../executor/Executor.js";
    import { ChatStream } from "./ChatStream.js";
    import { Stream } from "../streaming/Stream.js";
    import { ToolDefinition, ToolResolvable } from "./Tool.js";
    import { Schema } from "../schema/Schema.js";
    import { toJsonSchema } from "../schema/to-json-schema.js";
    import { z } from "zod";
    import { config } from "../config.js";
    import { ToolExecutionMode } from "../constants.js";
    import { ConfigurationError } from "../errors/index.js";
    import { ChatValidator } from "./Validation.js";
    import { ToolHandler } from "./ToolHandler.js";
    import { logger } from "../utils/logger.js";

    export interface AskOptions {
      images?: string[];
      files?: string[];
      temperature?: number;
      maxTokens?: number;
      headers?: Record<string, string>;
      maxToolCalls?: number;
      requestTimeout?: number;
      thinking?: ThinkingConfig;
      signal?: AbortSignal;
    }

    import { ChatResponseString } from "./ChatResponse.js";

    export class Chat {
      private messages: Message[] = [];
      private systemMessages: Message[] = [];
      private executor: Executor;

      constructor(
        private readonly provider: Provider,
        private model: string,
        private readonly options: ChatOptions = {},
        retryConfig: { attempts: number; delayMs: number } = { attempts: 1, delayMs: 0 }
      ) {
        this.executor = new Executor(provider, retryConfig);

        if (options.systemPrompt) {
          this.withInstructions(options.systemPrompt);
        }

        if (options.messages) {
          for (const msg of options.messages) {
            if (msg.role === "system" || msg.role === "developer") {
              this.systemMessages.push(msg);
            } else {
              this.messages.push(msg);
            }
          }
        }

        Eif (!this.options.toolExecution) {
          this.options.toolExecution = config.toolExecution || ToolExecutionMode.AUTO;
        }

        if (options.tools) {
          const toolList = options.tools;
          this.options.tools = []; // Clear and re-add via normalized method
          this.withTools(toolList);
        }
      }

      /**
       * Read-only access to message history
       */
      get history(): readonly Message[] {
        return [...this.systemMessages, ...this.messages];
      }

      get modelId(): string {
        return this.model;
      }

      /**
       * Aggregate usage across the entire conversation
       */
      get totalUsage(): Usage {
        return this.messages.reduce(
          (acc, msg) => {
            if (msg.usage) {
              acc.input_tokens += msg.usage.input_tokens;
              acc.output_tokens += msg.usage.output_tokens;
              acc.total_tokens += msg.usage.total_tokens;
              acc.cached_tokens = (acc.cached_tokens ?? 0) + (msg.usage.cached_tokens ?? 0);
              acc.cache_creation_tokens =
                (acc.cache_creation_tokens ?? 0) + (msg.usage.cache_creation_tokens ?? 0);
              acc.cost = (acc.cost ?? 0) + (msg.usage.cost ?? 0);
            }
            return acc;
          },
          {
            input_tokens: 0,
            output_tokens: 0,
            total_tokens: 0,
            cached_tokens: 0,
            cache_creation_tokens: 0,
            cost: 0
          }
        );
      }

      /**
       * Add a tool to the chat session (fluent API)
       * Supports passing a tool instance or a tool class (which will be instantiated).
       */
      withTool(tool: ToolResolvable): this {
        return this.withTools([tool]);
      }

      /**
       * Add multiple tools to the chat session.
       * Supports passing Tool classes (which will be instantiated) or instances.
       * Can replace existing tools if options.replace is true.
       *
       * @example
       * chat.withTools([WeatherTool, new CalculatorTool()], { replace: true });
       */
      withTools(tools: ToolResolvable[], options?: { replace?: boolean }): this {
        if (options?.replace) {
          this.options.tools = [];
        }

        if (!this.options.tools) {
          this.options.tools = [];
        }

        for (const tool of tools) {
          const normalized = this.normalizeTool(tool);
          if (normalized) {
            this.options.tools.push(normalized);
          }
        }
        return this;
      }

      /**
       * Add instructions (system prompt) to the chat.
       * By default, it appends a new system message.
       * If { replace: true } is passed, it removes all previous system messages first.
       */
      withInstructions(instruction: string, options?: { replace?: boolean }): this {
        if (options?.replace) {
          this.systemMessages = [];
        }

        // Always push to isolated storage
        this.systemMessages.push({ role: "system", content: instruction });

        return this;
      }

      /**
       * Alias for withInstructions
       */
      withSystemPrompt(instruction: string, options?: { replace?: boolean }): this {
        return this.withInstructions(instruction, options);
      }

      /**
       * Alias for withInstructions
       */
      system(instruction: string, options?: { replace?: boolean }): this {
        return this.withInstructions(instruction, options);
      }

      /**
       * Add a message manually to the chat history.
       * Useful for rehydrating sessions from a database.
       */
      add(role: "user" | "assistant" | "system" | "developer", content: string): this {
        Iif (role === "system" || role === "developer") {
          this.systemMessages.push({ role, content });
        } else {
          this.messages.push({ role, content });
        }
        return this;
      }

      /**
       * Set the temperature for the chat session.
       * Controls randomness: 0.0 (deterministic) to 1.0 (creative).
       */
      withTemperature(temp: number): this {
        this.options.temperature = temp;
        return this;
      }

      /**
       * Switch the model used for this chat session.
       */
      withModel(model: string): this {
        this.model = model;
        return this;
      }

      /**
       * Set custom headers for the chat session.
       * Merges with existing headers.
       */
      withRequestOptions(options: {
        headers?: Record<string, string>;
        responseFormat?: unknown;
      }): this {
        Eif (options.headers) {
          this.options.headers = { ...this.options.headers, ...options.headers };
        }
        Iif (options.responseFormat) {
          this.options.responseFormat = options.responseFormat as { type: "json_object" | "text" };
        }
        return this;
      }

      /**
       * Set provider-specific parameters.
       * These will be merged into the final request payload.
       */
      withParams(params: Record<string, unknown>): this {
        this.options.params = { ...this.options.params, ...params };
        return this;
      }

      /**
       * Enforce a specific schema for the output.
       * Can accept a Schema object or a Zod schema/JSON Schema directly.
       */
      withSchema(schema: Schema | z.ZodType<unknown> | Record<string, unknown> | null): this {
        Iif (schema === null) {
          this.options.schema = undefined;
          return this;
        }

        Iif (schema instanceof Schema) {
          this.options.schema = schema;
        } else if (schema instanceof z.ZodType) {
          this.options.schema = Schema.fromZod("output", schema);
        } else {
          this.options.schema = Schema.fromJson("output", schema as Record<string, unknown>);
        }
        return this;
      }

      /**
       * Enable and configure extended thinking for reasoning models.
       */
      withThinking(config: ThinkingConfig): this {
        this.options.thinking = { ...this.options.thinking, ...config };
        return this;
      }

      /**
       * Shortcut to set thinking effort.
       */
      withEffort(effort: "low" | "medium" | "high" | "none"): this {
        return this.withThinking({ effort });
      }

      // --- Event Handlers ---

      onNewMessage(handler: () => void): this {
        this.options.onNewMessage = handler;
        return this;
      }

      onEndMessage(handler: (message: ChatResponseString) => void): this {
        this.options.onEndMessage = handler;
        return this;
      }

      onToolCall(handler: (toolCall: unknown) => void): this {
        return this.onToolCallStart(handler);
      }

      onToolResult(handler: (result: unknown) => void): this {
        return this.onToolCallEnd((_call, result) => handler(result));
      }

      /**
       * Called when a tool call starts.
       */
      onToolCallStart(handler: (toolCall: unknown) => void): this {
        this.options.onToolCallStart = handler;
        return this;
      }

      /**
       * Called when a tool call ends successfully.
       */
      onToolCallEnd(handler: (toolCall: unknown, result: unknown) => void): this {
        this.options.onToolCallEnd = handler;
        return this;
      }

      onToolCallError(
        handler: (
          toolCall: unknown,
          error: Error
        ) => "STOP" | "CONTINUE" | "RETRY" | void | Promise<"STOP" | "CONTINUE" | "RETRY" | void>
      ): this {
        this.options.onToolCallError = handler;
        return this;
      }

      /**
       * Set the tool execution mode.
       * - "auto": (Default) Automatically execute all tool calls.
       * - "confirm": Call onConfirmToolCall before executing each tool.
       * - "dry-run": Propose tool calls but do not execute them.
       */
      withToolExecution(mode: ToolExecutionMode): this {
        this.options.toolExecution = mode;
        return this;
      }

      /**
       * Hook for confirming tool execution in "confirm" mode.
       * Return true to proceed, false to cancel the specific call.
       */
      onConfirmToolCall(handler: (toolCall: unknown) => Promise<boolean> | boolean): this {
        this.options.onConfirmToolCall = handler;
        return this;
      }

      /**
       * Add a hook to process messages before sending to the LLM.
       * Useful for PII detection, redaction, and input moderation.
       */
      beforeRequest(handler: (messages: Message[]) => Promise<Message[] | void>): this {
        this.options.onBeforeRequest = handler;
        return this;
      }

      /**
       * Add a hook to process the response before returning it.
       * Useful for output redaction, compliance, and post-moderation.
       */
      afterResponse(
        handler: (response: ChatResponseString) => Promise<ChatResponseString | void>
      ): this {
        this.options.onAfterResponse = handler;
        return this;
      }

      /**
       * Ask the model a question
       */
      async ask(content: string | ContentPart[], options?: AskOptions): Promise<ChatResponseString> {
        let messageContent: unknown = content;
        const files = [...(options?.images ?? []), ...(options?.files ?? [])];
        if (files.length > 0) {
          const processedFiles = await Promise.all(files.map((f: string) => FileLoader.load(f)));
          const hasBinary = processedFiles.some(isBinaryContent);

          ChatValidator.validateVision(this.provider, this.model, hasBinary, this.options);
          messageContent = formatMultimodalContent(content, processedFiles);
        }

        if (this.options.tools && this.options.tools.length > 0) {
          ChatValidator.validateTools(this.provider, this.model, true, this.options);
        }

        this.messages.push({
          role: "user",
          content: messageContent as MessageContent
        });

        // Process Schema/Structured Output
        let responseFormat: ResponseFormat | undefined = this.options.responseFormat;

        if (this.options.schema) {
          ChatValidator.validateStructuredOutput(this.provider, this.model, true, this.options);

          const jsonSchema = toJsonSchema(this.options.schema.definition.schema);

          responseFormat = {
            type: "json_schema",
            json_schema: {
              name: this.options.schema.definition.name,
              description: this.options.schema.definition.description,
              strict: this.options.schema.definition.strict ?? true,
              schema: jsonSchema
            }
          };
        }

        const executeOptions = {
          model: this.model,
          messages: [...this.systemMessages, ...this.messages],
          tools: this.options.tools as ToolDefinition[],
          temperature: options?.temperature ?? this.options.temperature,
          max_tokens: options?.maxTokens ?? this.options.maxTokens ?? config.maxTokens,
          headers: { ...this.options.headers, ...options?.headers },
          response_format: responseFormat, // Pass to provider
          requestTimeout:
            options?.requestTimeout ?? this.options.requestTimeout ?? config.requestTimeout,
          thinking: options?.thinking ?? this.options.thinking,
          signal: options?.signal,
          ...this.options.params
        };

        // --- Content Policy Hooks (Input) ---
        if (this.options.onBeforeRequest) {
          const messagesToProcess = [...this.systemMessages, ...this.messages];
          const result = await this.options.onBeforeRequest(messagesToProcess);
          Eif (result) {
            // If the hook returned modified messages, use them for this request
            executeOptions.messages = result;
          }
        }

        const totalUsage: Usage = { input_tokens: 0, output_tokens: 0, total_tokens: 0 };
        const trackUsage = (u?: Usage) => {
          if (u) {
            totalUsage.input_tokens += u.input_tokens;
            totalUsage.output_tokens += u.output_tokens;
            totalUsage.total_tokens += u.total_tokens;
            Iif (u.cached_tokens) {
              totalUsage.cached_tokens = (totalUsage.cached_tokens ?? 0) + u.cached_tokens;
            }
            if (u.cost !== undefined) {
              totalUsage.cost = (totalUsage.cost ?? 0) + u.cost;
            }
          }
        };

        // First round
        if (this.options.onNewMessage) this.options.onNewMessage();
        let response = await this.executor.executeChat(executeOptions);
        trackUsage(response.usage);

        let assistantMessage = new ChatResponseString(
          response.content ?? "",
          response.usage ?? { input_tokens: 0, output_tokens: 0, total_tokens: 0 },
          this.model,
          this.provider.id,
          response.thinking,
          response.reasoning,
          response.tool_calls
        );

        // --- Content Policy Hooks (Output - Turn 1) ---
        if (this.options.onAfterResponse) {
          const result = await this.options.onAfterResponse(assistantMessage);
          Eif (result) {
            assistantMessage = result;
          }
        }

        this.messages.push({
          role: "assistant",
          content: assistantMessage?.toString() || null,
          tool_calls: response.tool_calls,
          usage: response.usage
        });

        if (this.options.onEndMessage && (!response.tool_calls || response.tool_calls.length === 0)) {
          this.options.onEndMessage(assistantMessage);
        }

        const maxToolCalls = options?.maxToolCalls ?? this.options.maxToolCalls ?? 5;
        let stepCount = 0;

        while (response.tool_calls && response.tool_calls.length > 0) {
          // Dry-run mode: stop after proposing tools
          if (!ToolHandler.shouldExecuteTools(response.tool_calls, this.options.toolExecution)) {
            break;
          }

          stepCount++;
          if (stepCount > maxToolCalls) {
            throw new Error(`[NodeLLM] Maximum tool execution calls (${maxToolCalls}) exceeded.`);
          }

          for (const toolCall of response.tool_calls) {
            // Human-in-the-loop: check for approval
            if (this.options.toolExecution === ToolExecutionMode.CONFIRM) {
              const approved = await ToolHandler.requestToolConfirmation(
                toolCall,
                this.options.onConfirmToolCall
              );
              if (!approved) {
                this.messages.push(
                  this.provider.formatToolResultMessage(toolCall.id, "Action cancelled by user.")
                );
                continue;
              }
            }

            try {
              const toolResult = await ToolHandler.execute(
                toolCall,
                this.options.tools as unknown as ToolDefinition[],
                this.options.onToolCallStart,
                this.options.onToolCallEnd
              );
              this.messages.push(
                this.provider.formatToolResultMessage(toolResult.tool_call_id, toolResult.content)
              );
            } catch (error: unknown) {
              let currentError: unknown = error;
              const directive = await this.options.onToolCallError?.(toolCall, currentError as Error);

              if (directive === "STOP") {
                throw currentError;
              }

              if (directive === "RETRY") {
                try {
                  const toolResult = await ToolHandler.execute(
                    toolCall,
                    this.options.tools as unknown as ToolDefinition[],
                    this.options.onToolCallStart,
                    this.options.onToolCallEnd
                  );
                  this.messages.push(
                    this.provider.formatToolResultMessage(toolResult.tool_call_id, toolResult.content)
                  );
                  continue;
                } catch (retryError: unknown) {
                  // If retry also fails, fall through to default logic
                  currentError = retryError;
                }
              }

              this.messages.push(
                this.provider.formatToolResultMessage(
                  toolCall.id,
                  `Fatal error executing tool '${toolCall.function.name}': ${(currentError as Error).message}`,
                  { isError: true }
                )
              );

              if (directive === "CONTINUE") {
                continue;
              }

              // Default short-circuit logic
              const errorObj = currentError as { fatal?: boolean; status?: number; message?: string };
              const isFatal =
                errorObj.fatal === true || errorObj.status === 401 || errorObj.status === 403;

              if (isFatal) {
                throw currentError;
              }

              logger.error(
                `Tool execution failed for '${toolCall.function.name}':`,
                currentError as Error
              );
            }
          }

          response = await this.executor.executeChat({
            model: this.model,
            messages: [...this.systemMessages, ...this.messages],
            tools: this.options.tools as ToolDefinition[],
            temperature: options?.temperature ?? this.options.temperature,
            max_tokens: options?.maxTokens ?? this.options.maxTokens ?? config.maxTokens,
            headers: this.options.headers,
            response_format: responseFormat,
            requestTimeout:
              options?.requestTimeout ?? this.options.requestTimeout ?? config.requestTimeout,
            signal: options?.signal,
            ...this.options.params
          });
          trackUsage(response.usage);

          assistantMessage = new ChatResponseString(
            response.content ?? "",
            response.usage ?? { input_tokens: 0, output_tokens: 0, total_tokens: 0 },
            this.model,
            this.provider.id,
            response.thinking,
            response.reasoning
          );

          // --- Content Policy Hooks (Output - Tool Turns) ---
          Iif (this.options.onAfterResponse) {
            const result = await this.options.onAfterResponse(assistantMessage);
            if (result) {
              assistantMessage = result;
            }
          }

          this.messages.push({
            role: "assistant",
            content: assistantMessage?.toString() || null,
            tool_calls: response.tool_calls,
            usage: response.usage
          });

          Iif (this.options.onEndMessage && (!response.tool_calls || response.tool_calls.length === 0)) {
            this.options.onEndMessage(assistantMessage);
          }
        }

        // For the final return, we might want to aggregate reasoning too if it happened in multiple turns?
        // Usually reasoning only happens once or we just want the last one.
        return new ChatResponseString(
          assistantMessage.toString() || "",
          totalUsage,
          this.model,
          this.provider.id,
          assistantMessage.thinking,
          assistantMessage.reasoning,
          response.tool_calls
        );
      }

      /**
       * Streams the model's response to a user question.
       */
      stream(content: string | ContentPart[], options: AskOptions = {}): Stream<ChatChunk> {
        const streamer = new ChatStream(
          this.provider,
          this.model,
          this.options,
          this.messages,
          this.systemMessages
        );
        return streamer.create(content, options);
      }

      /**
       * Normalizes a ToolResolvable into a ToolDefinition.
       */
      private normalizeTool(tool: ToolResolvable): ToolDefinition | null {
        let toolInstance: unknown;

        // Handle class constructor
        if (typeof tool === "function") {
          try {
            toolInstance = new (tool as new () => unknown)();
          } catch (e: unknown) {
            logger.error(
              `Failed to instantiate tool class: ${(tool as { name?: string }).name}`,
              e as Error
            );
            return null;
          }
        } else {
          toolInstance = tool;
        }

        Iif (!toolInstance) return null;

        // Normalized to standard ToolDefinition interface if it's a Tool class instance
        if (typeof (toolInstance as { toLLMTool?: unknown }).toLLMTool === "function") {
          return (toolInstance as { toLLMTool: () => ToolDefinition }).toLLMTool();
        }

        const toolObj = toolInstance as {
          function?: { name?: string };
          type?: string;
          handler?: unknown;
        };

        if (!toolObj.function || !toolObj.function.name) {
          // 1. Validate structure
          throw new ConfigurationError(
            `[NodeLLM] Tool validation failed: 'function.name' is required for raw tool objects.`
          );
        }

        if (toolObj.type !== "function") {
          // 2. Ensure 'type: function' exists (standardize for providers)
          (toolObj as { type: string }).type = "function";
        }

        if (typeof toolObj.handler !== "function") {
          // 3. Validate handler existence
          throw new ConfigurationError(
            `[NodeLLM] Tool validation failed: Tool '${toolObj.function.name}' must have a 'handler' function. (Note: Only Tool subclasses use 'execute()')`
          );
        }

        return toolInstance as ToolDefinition;
      }
    }