All files / modules/ai/services ai.service.ts

52.38% Statements 33/63
20% Branches 2/10
88.88% Functions 8/9
51.66% Lines 31/60

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 1941x 1x 1x 1x 1x                   1x 14x       14x   14x 14x           7x         7x 1x               1x     7x       3x     3x 3x   3x                   2x   2x 2x                                                                                                                                             1x           2x 2x 2x   2x                         2x                             2x             2x           2x      
import { Injectable, Logger, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, MoreThanOrEqual } from 'typeorm';
import { AIConfig, AIUsage, UsageStatus, AIProvider } from '../entities';
import { OpenRouterClient } from '../clients';
import {
  ChatRequestDto,
  ChatResponseDto,
  UpdateAIConfigDto,
  UsageStatsDto,
  AIModelDto,
} from '../dto';
 
@Injectable()
export class AIService {
  private readonly logger = new Logger(AIService.name);
 
  constructor(
    @InjectRepository(AIConfig)
    private readonly configRepository: Repository<AIConfig>,
    @InjectRepository(AIUsage)
    private readonly usageRepository: Repository<AIUsage>,
    private readonly openRouterClient: OpenRouterClient,
  ) {}
 
  // ==================== Configuration ====================
 
  async getConfig(tenantId: string): Promise<AIConfig> {
    let config = await this.configRepository.findOne({
      where: { tenant_id: tenantId },
    });
 
    // Create default config if not exists
    if (!config) {
      config = this.configRepository.create({
        tenant_id: tenantId,
        provider: AIProvider.OPENROUTER,
        default_model: 'anthropic/claude-3-haiku',
        temperature: 0.7,
        max_tokens: 2048,
        is_enabled: true,
      });
      await this.configRepository.save(config);
    }
 
    return config;
  }
 
  async updateConfig(tenantId: string, dto: UpdateAIConfigDto): Promise<AIConfig> {
    let config = await this.getConfig(tenantId);
 
    // Update fields
    Object.assign(config, dto);
    config.updated_at = new Date();
 
    return this.configRepository.save(config);
  }
 
  // ==================== Chat Completion ====================
 
  async chat(
    tenantId: string,
    userId: string,
    dto: ChatRequestDto,
  ): Promise<ChatResponseDto> {
    const config = await this.getConfig(tenantId);
 
    if (!config.is_enabled) {
      throw new BadRequestException('AI features are disabled for this tenant');
    }
 
    Iif (!this.openRouterClient.isReady()) {
      throw new BadRequestException('AI service is not configured');
    }
 
    // Create usage record
    const usage = this.usageRepository.create({
      tenant_id: tenantId,
      user_id: userId,
      provider: config.provider,
      model: dto.model || config.default_model,
      status: UsageStatus.PENDING,
      started_at: new Date(),
    });
    await this.usageRepository.save(usage);
 
    try {
      // Apply system prompt if configured and not provided
      let messages = [...dto.messages];
      Iif (config.system_prompt && !messages.some((m) => m.role === 'system')) {
        messages = [{ role: 'system', content: config.system_prompt }, ...messages];
      }
 
      const startTime = Date.now();
 
      const response = await this.openRouterClient.chatCompletion(
        { ...dto, messages },
        config.default_model,
        config.temperature,
        config.max_tokens,
      );
 
      const latencyMs = Date.now() - startTime;
 
      // Calculate costs
      const costs = this.openRouterClient.calculateCost(
        response.model,
        response.usage.prompt_tokens,
        response.usage.completion_tokens,
      );
 
      // Update usage record
      usage.status = UsageStatus.COMPLETED;
      usage.model = response.model;
      usage.input_tokens = response.usage.prompt_tokens;
      usage.output_tokens = response.usage.completion_tokens;
      usage.cost_input = costs.input;
      usage.cost_output = costs.output;
      usage.latency_ms = latencyMs;
      usage.completed_at = new Date();
      usage.request_id = response.id;
      usage.endpoint = 'chat';
      await this.usageRepository.save(usage);
 
      return response;
    } catch (error) {
      // Record failure
      usage.status = UsageStatus.FAILED;
      usage.error_message = error.message;
      usage.completed_at = new Date();
      await this.usageRepository.save(usage);
 
      throw error;
    }
  }
 
  // ==================== Models ====================
 
  async getModels(): Promise<AIModelDto[]> {
    return this.openRouterClient.getModels();
  }
 
  // ==================== Usage Stats ====================
 
  async getCurrentMonthUsage(tenantId: string): Promise<UsageStatsDto> {
    const startOfMonth = new Date();
    startOfMonth.setDate(1);
    startOfMonth.setHours(0, 0, 0, 0);
 
    const result = await this.usageRepository
      .createQueryBuilder('usage')
      .select('COUNT(*)', 'request_count')
      .addSelect('COALESCE(SUM(usage.input_tokens), 0)', 'total_input_tokens')
      .addSelect('COALESCE(SUM(usage.output_tokens), 0)', 'total_output_tokens')
      .addSelect('COALESCE(SUM(usage.input_tokens + usage.output_tokens), 0)', 'total_tokens')
      .addSelect('COALESCE(SUM(usage.cost_input + usage.cost_output), 0)', 'total_cost')
      .addSelect('COALESCE(AVG(usage.latency_ms), 0)', 'avg_latency_ms')
      .where('usage.tenant_id = :tenantId', { tenantId })
      .andWhere('usage.status = :status', { status: UsageStatus.COMPLETED })
      .andWhere('usage.created_at >= :startOfMonth', { startOfMonth })
      .getRawOne();
 
    return {
      request_count: parseInt(result.request_count, 10),
      total_input_tokens: parseInt(result.total_input_tokens, 10),
      total_output_tokens: parseInt(result.total_output_tokens, 10),
      total_tokens: parseInt(result.total_tokens, 10),
      total_cost: parseFloat(result.total_cost),
      avg_latency_ms: parseFloat(result.avg_latency_ms),
    };
  }
 
  async getUsageHistory(
    tenantId: string,
    page = 1,
    limit = 20,
  ): Promise<{ data: AIUsage[]; total: number }> {
    const [data, total] = await this.usageRepository.findAndCount({
      where: { tenant_id: tenantId },
      order: { created_at: 'DESC' },
      skip: (page - 1) * limit,
      take: limit,
    });
 
    return { data, total };
  }
 
  // ==================== Health Check ====================
 
  isServiceReady(): boolean {
    return this.openRouterClient.isReady();
  }
}