All files / src/llm-provider openai-llm.provider.ts

77.72% Statements 178/229
67.74% Branches 84/124
85.71% Functions 12/14
77.16% Lines 169/219

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 5957x                   7x 7x     7x 39x 39x     39x 39x       6x   6x 1x     1x       5x   6x       5x 2x                             5x 1x     5x                   5x 5x   4x   4x 4x           3x 1x     1x     2x 2x 2x           1x     1x         25x 25x       18x 18x 1x         17x                       17x   17x 17x   17x 17x       17x     17x     17x 17x       17x 17x 17x   17x 17x                                           17x 17x         17x 4x 4x     17x                       17x             17x                   15x 3x 3x 3x   3x   3x 3x 1x   3x 3x 3x           3x               3x 3x 3x       12x 4x 4x       4x 4x 4x 4x 4x 4x         4x     4x   4x 4x 20x         20x 20x   16x 16x 16x   16x 28x 16x 16x 4x   12x 12x 12x 12x 4x 4x 4x 3x           12x   12x 2x 2x       12x 12x 2x 2x 2x 1x                   2x 2x 1x             12x 4x           4x                                 4x 4x 1x 1x                                   4x 4x       4x 4x 4x                                 4x 4x                                                                               8x 8x 8x   8x   8x       8x 1x                         8x 2x     2x 2x     6x 6x 6x       6x 6x 6x                             6x                                                                     7x       7x 4x   4x 4x 4x   4x 4x 1x   4x 4x 4x     4x                       7x 7x         3x 3x                                      
import { Injectable, Logger } from '@nestjs/common';
import {
  LlmProvider,
  LlmProviderRequest,
  LlmContent,
  LlmModel,
  LlmResponse,
  LlmFunctionTool,
  LlmToolCall,
} from './llm-provider.interface';
import { ApplicationStateService } from '../application-state/application-state.service';
import { LlmCallLogsService } from '../llm-call-logs/llm-call-logs.service';
 
@Injectable()
export class OpenaiLlmProvider implements LlmProvider {
  private readonly logger = new Logger(OpenaiLlmProvider.name);
  private activeStreams = new Map<string, AbortController>();
 
  constructor(
    private readonly applicationStateService: ApplicationStateService,
    private readonly llmCallLogsService: LlmCallLogsService,
  ) {}
 
  private mapHistory(history: LlmContent[]) {
    return history.map((turn) => {
      // Handle tool result messages
      if (turn.role === 'tool') {
        return {
          role: 'tool',
          tool_call_id: turn.tool_call_id,
          content: turn.parts.map((p) => p.text).join(''),
        };
      }
 
      const mappedTurn: any = {
        role: turn.role === 'model' ? 'assistant' : 'user',
        content: turn.parts.map((p) => p.text).join(''),
      };
 
      // OpenAI format for tool_calls in history
      if (turn.tool_calls) {
        mappedTurn.tool_calls = turn.tool_calls.map((tc) => ({
          id: tc.id,
          type: tc.type,
          function: {
            name: tc.function.name,
            // OpenAI API requires arguments to be a JSON string
            arguments:
              typeof tc.function.arguments === 'string'
                ? tc.function.arguments
                : JSON.stringify(tc.function.arguments),
          },
        }));
      }
 
      // Attach thoughts if they exist in history
      if (turn.thoughts) {
        mappedTurn.thoughts = turn.thoughts;
      }
 
      return mappedTurn;
    });
  }
 
  private mapTools(tools?: LlmFunctionTool[]): any[] | undefined {
    Iif (!tools || tools.length === 0) return undefined;
    return tools;
  }
 
  async getModels(): Promise<LlmModel[]> {
    const apiKey = await this.applicationStateService.getOpenaiApiKey();
    if (!apiKey) return [];
 
    const baseUrl = await this.getEffectiveBaseUrl();
 
    try {
      const response = await fetch(`${baseUrl}/models`, {
        headers: {
          Authorization: `Bearer ${apiKey}`,
        },
      });
 
      if (!response.ok) {
        this.logger.warn(
          `Failed to fetch models from ${baseUrl}/models: ${response.status} ${response.statusText}`,
        );
        return [];
      }
 
      const data = await response.json();
      const models = data.data || [];
      return models.map((m: any) => ({
        id: `openai/${m.id}`,
        name: m.id,
        provider: 'openai' as const,
      }));
    } catch (e) {
      this.logger.error(
        `Failed to fetch OpenAI compatible models: ${e.message}`,
      );
      return [];
    }
  }
 
  private async getEffectiveBaseUrl(): Promise<string> {
    const customBaseUrl = await this.applicationStateService.getOpenaiBaseUrl();
    return (customBaseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
  }
 
  async generateContent(request: LlmProviderRequest): Promise<LlmResponse> {
    const apiKey = await this.applicationStateService.getOpenaiApiKey();
    if (!apiKey) {
      throw new Error(
        'OpenAI Compatible API Key is not configured in settings.',
      );
    }
 
    const baseUrl = await this.getEffectiveBaseUrl();
 
    const {
      prompt,
      systemInstruction,
      history,
      modelId,
      generationConfig,
      tools,
      tool_choice,
      onToken,
      abortController,
    } = request;
 
    const model = modelId ? modelId.replace(/^openai\//, '') : 'gpt-4o';
    const requestId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
 
    const messages = [];
    Iif (systemInstruction) {
      messages.push({ role: 'system', content: systemInstruction });
    }
 
    Iif (history && history.length > 0) {
      messages.push(...this.mapHistory(history));
    } else {
      messages.push({ role: 'user', content: prompt });
    }
 
    await this.applicationStateService.trackUsedModel(modelId);
    this.logger.log(
      `Calling OpenAI Compatible API at ${baseUrl} with model: ${model}`,
    );
 
    const startTime = Date.now();
    let llmCallLogId: string | null = null;
    let logAlreadyUpdated = false;
 
    try {
      llmCallLogId = (
        await this.llmCallLogsService.createLog({
          session_input_id: 'pending',
          provider: 'openai',
          model_id: model,
          request_body: JSON.stringify({
            model,
            messages,
            tools,
            tool_choice,
            stream: !!onToken,
            temperature: generationConfig?.temperature,
            max_tokens: generationConfig?.maxOutputTokens,
            top_p: generationConfig?.topP,
            reasoning: generationConfig?.reasoning,
          }),
        })
      ).id;
    } catch (logError) {
      this.logger.warn(`Failed to create LLM call log: ${logError.message}`);
    }
 
    try {
      const body: any = {
        model,
        messages,
      };
 
      if (onToken) {
        body.stream = true;
        body.stream_options = { include_usage: true };
      }
 
      Iif (generationConfig) {
        Iif (generationConfig.temperature !== undefined)
          body.temperature = generationConfig.temperature;
        Iif (generationConfig.maxOutputTokens !== undefined)
          body.max_tokens = generationConfig.maxOutputTokens;
        Iif (generationConfig.topP !== undefined)
          body.top_p = generationConfig.topP;
        Iif (generationConfig.reasoning !== undefined)
          body.reasoning = generationConfig.reasoning;
      }
 
      // Add tools if provided
      Iif (tools && tools.length > 0) {
        body.tools = this.mapTools(tools);
        Iif (tool_choice) {
          body.tool_choice = tool_choice;
        }
      }
 
      const response = await fetch(`${baseUrl}/chat/completions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${apiKey}`,
        },
        body: JSON.stringify(body),
        signal: abortController?.signal,
      });
 
      if (!response.ok) {
        const errorText = await response.text();
        const errorData = this.tryParseJson(errorText);
        const errorObj = errorData?.error;
        let errorMessage =
          errorObj?.message ||
          `OpenAI Compatible API error: ${response.statusText}`;
        if (errorObj?.code) errorMessage = `[${errorObj.code}] ${errorMessage}`;
        if (errorObj?.metadata)
          errorMessage += `\nMetadata: ${JSON.stringify(errorObj.metadata)}`;
 
        if (llmCallLogId) {
          try {
            await this.llmCallLogsService.updateLog(llmCallLogId, {
              status_code: response.status,
              latency_ms: Date.now() - startTime,
              error_message: errorMessage,
              response_body: errorText,
            });
            logAlreadyUpdated = true;
          } catch (updateError) {
            this.logger.warn(
              `Failed to update LLM call log: ${updateError.message}`,
            );
          }
        }
 
        const error = new Error(errorMessage) as Error & { status: number };
        error.status = response.status;
        throw error;
      }
 
      // Handle streaming response
      if (onToken && response.body) {
        let accumulatedResponseBody = '';
        Iif (abortController) {
          this.activeStreams.set(requestId, abortController);
        }
 
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        let accumulatedResponse = '';
        let accumulatedReasoning = '';
        let isFirst = true;
        let usageData: {
          prompt_tokens: number;
          completion_tokens: number;
          cached_tokens?: number;
        } | null = null;
 
        // Accumulate tool calls across streaming chunks
        const accumulatedToolCalls = new Map<number, LlmToolCall>();
 
        try {
          while (true) {
            Iif (abortController?.signal?.aborted) {
              this.activeStreams.delete(requestId);
              throw new DOMException('The operation was aborted', 'AbortError');
            }
 
            const { done, value } = await reader.read();
            if (done) break;
 
            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop() || '';
 
            for (const line of lines) {
              if (line.startsWith('data: ')) {
                const dataStr = line.substring(6);
                if (dataStr.trim() === '[DONE]') {
                  break;
                }
                try {
                  const parsed = JSON.parse(dataStr);
                  const chunk = parsed.choices?.[0]?.delta?.content;
                  if (chunk) {
                    accumulatedResponse += chunk;
                    onToken(chunk, isFirst);
                    if (isFirst) {
                      isFirst = false;
                    }
                  }
 
                  // Capture reasoning content from streaming
                  const reasoningChunk =
                    parsed.choices?.[0]?.delta?.reasoning_content ||
                    parsed.choices?.[0]?.delta?.reasoning;
                  if (reasoningChunk) {
                    accumulatedReasoning += reasoningChunk;
                    onToken?.('', false, reasoningChunk);
                  }
 
                  // Handle streaming tool_calls
                  const deltaToolCalls = parsed.choices?.[0]?.delta?.tool_calls;
                  if (deltaToolCalls) {
                    for (const deltaCall of deltaToolCalls) {
                      const index = deltaCall.index;
                      if (!accumulatedToolCalls.has(index)) {
                        accumulatedToolCalls.set(index, {
                          id: deltaCall.id,
                          type: deltaCall.type,
                          function: {
                            name: deltaCall.function?.name || '',
                            arguments: '',
                          },
                        });
                      }
 
                      const existing = accumulatedToolCalls.get(index)!;
                      if (deltaCall.function?.arguments) {
                        existing.function.arguments +=
                          deltaCall.function.arguments;
                      }
                    }
                  }
 
                  // Extract usage from streaming response
                  if (parsed.usage && !usageData) {
                    usageData = {
                      prompt_tokens: parsed.usage.prompt_tokens,
                      completion_tokens: parsed.usage.completion_tokens,
                      cached_tokens:
                        parsed.usage.prompt_tokens_details?.cached_tokens || 0,
                    };
                    accumulatedResponseBody += dataStr + '\n';
                  }
                } catch (e) {
                  this.logger.warn(`Error parsing stream chunk: ${dataStr}`, e);
                }
              }
            }
          }
        } catch (readError) {
          Iif (abortController?.signal?.aborted) {
            this.activeStreams.delete(requestId);
            throw new DOMException('The operation was aborted', 'AbortError');
          }
          throw readError;
        }
 
        // Parse accumulated tool call arguments from JSON string to object
        const finalToolCalls: LlmToolCall[] = [];
        for (const toolCall of accumulatedToolCalls.values()) {
          try {
            finalToolCalls.push({
              ...toolCall,
              function: {
                ...toolCall.function,
                arguments:
                  typeof toolCall.function.arguments === 'string'
                    ? JSON.parse(toolCall.function.arguments as string)
                    : toolCall.function.arguments,
              },
            });
          } catch (e) {
            this.logger.warn(
              `Failed to parse tool call arguments: ${toolCall.function.arguments}`,
              e,
            );
          }
        }
 
        if (usageData) {
          this.logger.log(
            `OpenAI Compatible stream finished. Usage: ${usageData.prompt_tokens} prompt (${usageData.cached_tokens} cached), ${usageData.completion_tokens} completion tokens`,
          );
 
          if (llmCallLogId) {
            try {
              await this.llmCallLogsService.updateLog(llmCallLogId, {
                status_code: 200,
                latency_ms: Date.now() - startTime,
                response_body:
                  accumulatedResponseBody ||
                  JSON.stringify({ usage: usageData, stream_chunks: '...' }),
                input_tokens: usageData.prompt_tokens,
                output_tokens: usageData.completion_tokens,
                cached_tokens: usageData.cached_tokens,
              });
            } catch (updateError) {
              this.logger.warn(
                `Failed to update LLM call log: ${updateError.message}`,
              );
            }
          }
 
          this.activeStreams.delete(requestId);
          return {
            text: accumulatedResponse,
            usage: {
              inputTokens: usageData.prompt_tokens,
              outputTokens: usageData.completion_tokens,
              cachedTokens: usageData.cached_tokens,
            },
            tool_calls: finalToolCalls.length > 0 ? finalToolCalls : undefined,
            thoughts: accumulatedReasoning || undefined,
          };
        }
 
        // Fallback if usage not returned
        this.logger.warn('Usage data not returned from streaming response');
 
        Iif (llmCallLogId) {
          try {
            await this.llmCallLogsService.updateLog(llmCallLogId, {
              status_code: 200,
              latency_ms: Date.now() - startTime,
              response_body:
                accumulatedResponseBody ||
                JSON.stringify({ stream_chunks: '...' }),
            });
          } catch (updateError) {
            this.logger.warn(
              `Failed to update LLM call log: ${updateError.message}`,
            );
          }
        }
 
        this.activeStreams.delete(requestId);
        return {
          text: accumulatedResponse,
          tool_calls: finalToolCalls.length > 0 ? finalToolCalls : undefined,
          thoughts: accumulatedReasoning || undefined,
        };
      }
 
      // Handle non-streaming response
      const data = await response.json();
      const content = data.choices?.[0]?.message?.content;
      const rawToolCalls = data.choices?.[0]?.message?.tool_calls;
      const reasoningContent =
        data.choices?.[0]?.message?.reasoning ||
        data.choices?.[0]?.message?.reasoning_content;
      const usage = data.usage;
 
      // Parse tool calls if present
      let parsedToolCalls: LlmToolCall[] | undefined;
      if (rawToolCalls && rawToolCalls.length > 0) {
        parsedToolCalls = rawToolCalls.map((tc: any) => ({
          id: tc.id,
          type: tc.type,
          function: {
            name: tc.function.name,
            arguments:
              typeof tc.function.arguments === 'string'
                ? JSON.parse(tc.function.arguments)
                : tc.function.arguments,
          },
        }));
      }
 
      if (!content && !parsedToolCalls) {
        const error = new Error(
          'OpenAI Compatible API returned an empty response.',
        ) as Error & { status: number };
        error.status = response.status || 0;
        throw error;
      }
 
      if (usage) {
        const cachedTokens = usage.prompt_tokens_details?.cached_tokens || 0;
        this.logger.log(
          `OpenAI Compatible response. Usage: ${usage.prompt_tokens} prompt (${cachedTokens} cached), ${usage.completion_tokens} completion tokens`,
        );
 
        if (llmCallLogId) {
          try {
            await this.llmCallLogsService.updateLog(llmCallLogId, {
              status_code: 200,
              latency_ms: Date.now() - startTime,
              response_body: JSON.stringify(data),
              input_tokens: usage.prompt_tokens,
              output_tokens: usage.completion_tokens,
              cached_tokens: cachedTokens,
            });
          } catch (updateError) {
            this.logger.warn(
              `Failed to update LLM call log: ${updateError.message}`,
            );
          }
        }
 
        return {
          text: content || '',
          usage: {
            inputTokens: usage.prompt_tokens,
            outputTokens: usage.completion_tokens,
            cachedTokens: cachedTokens,
          },
          tool_calls: parsedToolCalls,
          thoughts: reasoningContent || undefined,
        };
      }
 
      // Fallback without usage data
      this.logger.warn('Usage data not returned from response');
 
      Iif (llmCallLogId) {
        try {
          await this.llmCallLogsService.updateLog(llmCallLogId, {
            status_code: 200,
            latency_ms: Date.now() - startTime,
            response_body: JSON.stringify(data),
          });
        } catch (updateError) {
          this.logger.warn(
            `Failed to update LLM call log: ${updateError.message}`,
          );
        }
      }
 
      return {
        text: content || '',
        tool_calls: parsedToolCalls,
        thoughts: reasoningContent || undefined,
      };
    } catch (error) {
      this.logger.error(
        `OpenAI Compatible generation failed: ${error.message}`,
      );
 
      if (llmCallLogId && !logAlreadyUpdated) {
        try {
          const errorName =
            error instanceof Error ? error.name : 'UnknownError';
          let errorMessage = `[${errorName}] ${error.message}`;
          if (error.status) errorMessage += `\nHTTP Status: ${error.status}`;
          const errorCause =
            error instanceof Error ? (error as any).cause : undefined;
          if (errorCause) {
            errorMessage += `\nCause: ${errorCause instanceof Error ? errorCause.message : String(errorCause)}`;
          }
          if (error instanceof Error && error.stack) {
            const stackLines = error.stack.split('\n').slice(1, 4).join('\n');
            errorMessage += `\n${stackLines}`;
          }
 
          await this.llmCallLogsService.updateLog(llmCallLogId, {
            status_code: error.status || null,
            latency_ms: Date.now() - startTime,
            error_message: errorMessage,
          });
        } catch (updateError) {
          this.logger.warn(
            `Failed to update LLM call log: ${updateError.message}`,
          );
        }
      }
 
      this.activeStreams.delete(requestId);
      throw error;
    }
  }
 
  private tryParseJson(text: string): any {
    try {
      return JSON.parse(text);
    } catch {
      return null;
    }
  }
 
  abortBySessionId(_sessionId: string): boolean {
    for (const [reqId, controller] of this.activeStreams.entries()) {
      try {
        controller.abort();
        this.activeStreams.delete(reqId);
        return true;
      } catch (e) {
        this.logger.warn(`Failed to abort stream ${reqId}: ${e.message}`);
      }
    }
    return false;
  }
}