All files / src/llm-call-logs llm-call-logs.service.ts

100% Statements 58/58
100% Branches 14/14
100% Functions 7/7
100% Lines 52/52

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 18710x 10x 10x 10x                         10x                           10x 25x       25x           1x     1x 1x             2x 2x 2x 1x   1x             9x     9x 1x                 9x 1x           9x 1x           9x 1x             8x 1x                   9x     9x 1x   9x 1x       9x     9x   9x   9x               2x               2x   2x 2x   2x 2x               3x                     3x   3x 3x   3x 3x       2x 2x 1x   1x      
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { LlmCallLog } from '../core-entities/llm-call-log.entity';
import { CreateLlmCallLogDto } from './dto/llm-call-log.dto';
 
interface FindAllParams {
  sessionId?: string;
  sessionInputId?: string;
  provider?: string;
  status?: string;
  limit?: number;
  offset?: number;
}
 
// Light columns for list view (excludes heavy TEXT fields)
const LIST_SELECT_COLUMNS = [
  'llm_call_log.id',
  'llm_call_log.session_input_id',
  'llm_call_log.provider',
  'llm_call_log.model_id',
  'llm_call_log.status_code',
  'llm_call_log.latency_ms',
  'llm_call_log.input_tokens',
  'llm_call_log.output_tokens',
  'llm_call_log.cached_tokens',
  'llm_call_log.created_at',
];
 
@Injectable()
export class LlmCallLogsService {
  private readonly logger = new Logger(LlmCallLogsService.name);
 
  constructor(
    @InjectRepository(LlmCallLog)
    private llmCallLogsRepository: Repository<LlmCallLog>,
  ) {}
 
  async createLog(
    createLlmCallLogDto: CreateLlmCallLogDto,
  ): Promise<LlmCallLog> {
    this.logger.log(
      `Creating LLM call log for session input ${createLlmCallLogDto.session_input_id}`,
    );
    const newLog = this.llmCallLogsRepository.create(createLlmCallLogDto);
    return this.llmCallLogsRepository.save(newLog);
  }
 
  async updateLog(
    id: string,
    updates: Partial<CreateLlmCallLogDto>,
  ): Promise<LlmCallLog> {
    await this.llmCallLogsRepository.update(id, updates);
    const log = await this.llmCallLogsRepository.findOneBy({ id });
    if (!log) {
      throw new Error(`LlmCallLog with ID "${id}" not found`);
    }
    return log;
  }
 
  async findAll(
    params: FindAllParams,
  ): Promise<{ logs: LlmCallLog[]; total: number }> {
    const queryBuilder =
      this.llmCallLogsRepository.createQueryBuilder('llm_call_log');
 
    // Filter by session ID (need to join with session_inputs)
    if (params.sessionId) {
      queryBuilder.innerJoin(
        'llm_call_log.sessionInput',
        'session_input',
        'session_input.session_id = :sessionId',
        { sessionId: params.sessionId },
      );
    }
 
    // Filter by session input ID
    if (params.sessionInputId) {
      queryBuilder.andWhere('llm_call_log.session_input_id = :sessionInputId', {
        sessionInputId: params.sessionInputId,
      });
    }
 
    // Filter by provider
    if (params.provider) {
      queryBuilder.andWhere('llm_call_log.provider = :provider', {
        provider: params.provider,
      });
    }
 
    // Filter by status
    if (params.status === 'success') {
      queryBuilder.andWhere(
        'llm_call_log.status_code >= :minSuccess AND llm_call_log.status_code < :maxSuccess',
        {
          minSuccess: 200,
          maxSuccess: 300,
        },
      );
    } else if (params.status === 'error') {
      queryBuilder.andWhere(
        '(llm_call_log.status_code < :minSuccess OR llm_call_log.status_code >= :maxSuccess OR llm_call_log.status_code IS NULL)',
        {
          minSuccess: 200,
          maxSuccess: 300,
        },
      );
    }
 
    // Get total count
    const total = await queryBuilder.getCount();
 
    // Apply pagination
    if (params.offset) {
      queryBuilder.skip(params.offset);
    }
    if (params.limit) {
      queryBuilder.take(params.limit);
    }
 
    // Order by created_at descending
    queryBuilder.orderBy('llm_call_log.created_at', 'DESC');
 
    // Select only light columns for list view
    queryBuilder.select(LIST_SELECT_COLUMNS);
 
    const logs = await queryBuilder.getMany();
 
    return { logs, total };
  }
 
  async findBySessionInputId(
    sessionInputId: string,
    limit?: number,
    offset?: number,
  ): Promise<{ logs: LlmCallLog[]; total: number }> {
    const queryBuilder = this.llmCallLogsRepository
      .createQueryBuilder('llm_call_log')
      .where('llm_call_log.session_input_id = :sessionInputId', {
        sessionInputId,
      })
      .orderBy('llm_call_log.created_at', 'DESC')
      .select(LIST_SELECT_COLUMNS);
 
    const total = await queryBuilder.getCount();
 
    if (offset) queryBuilder.skip(offset);
    if (limit) queryBuilder.take(limit);
 
    const logs = await queryBuilder.getMany();
    return { logs, total };
  }
 
  async findBySessionId(
    sessionId: string,
    limit?: number,
    offset?: number,
  ): Promise<{ logs: LlmCallLog[]; total: number }> {
    const queryBuilder = this.llmCallLogsRepository
      .createQueryBuilder('llm_call_log')
      .innerJoin(
        'llm_call_log.sessionInput',
        'session_input',
        'session_input.session_id = :sessionId',
        { sessionId },
      )
      .orderBy('llm_call_log.created_at', 'DESC')
      .select(LIST_SELECT_COLUMNS);
 
    const total = await queryBuilder.getCount();
 
    if (offset) queryBuilder.skip(offset);
    if (limit) queryBuilder.take(limit);
 
    const logs = await queryBuilder.getMany();
    return { logs, total };
  }
 
  async findById(id: string): Promise<LlmCallLog> {
    const log = await this.llmCallLogsRepository.findOneBy({ id });
    if (!log) {
      throw new Error(`LlmCallLog with ID "${id}" not found`);
    }
    return log;
  }
}