All files / src/platform/ai/services ai.service.ts

0% Statements 0/66
0% Branches 0/42
0% Functions 0/12
0% Lines 0/62

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                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import {
  Injectable,
  Logger,
  NotFoundException,
  ForbiddenException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { AiProvider } from '../interfaces/ai-provider.interface';
import {
  AiPromptTemplate,
  AiExecution,
  AiTenantConfiguration,
} from '../schemas/ai.schema';
 
// PII patterns to redact from prompts before sending to external providers
const PII_PATTERNS: Array<{
  name: string;
  pattern: RegExp;
  replacement: string;
}> = [
  {
    name: 'email',
    pattern: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
    replacement: '[EMAIL_REDACTED]',
  },
  {
    name: 'phone',
    pattern: /(\+\d{1,3})?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}/g,
    replacement: '[PHONE_REDACTED]',
  },
  {
    name: 'aadhar',
    pattern: /\b\d{4}\s?\d{4}\s?\d{4}\b/g,
    replacement: '[ID_REDACTED]',
  },
  {
    name: 'pan',
    pattern: /\b[A-Z]{5}[0-9]{4}[A-Z]\b/g,
    replacement: '[PAN_REDACTED]',
  },
];
 
@Injectable()
export class AiService {
  private readonly logger = new Logger(AiService.name);
  private readonly providers = new Map<string, AiProvider>();
  private defaultProviderKey = 'mock';
 
  constructor(
    @InjectModel(AiPromptTemplate.name)
    private readonly promptModel: Model<AiPromptTemplate>,
    @InjectModel(AiExecution.name)
    private readonly executionModel: Model<AiExecution>,
    @InjectModel(AiTenantConfiguration.name)
    private readonly configModel: Model<AiTenantConfiguration>,
  ) {}
 
  registerProvider(provider: AiProvider, isDefault = false): void {
    this.providers.set(provider.providerKey, provider);
    if (isDefault) this.defaultProviderKey = provider.providerKey;
    this.logger.log(`AI Provider registered: ${provider.providerKey}`);
  }
 
  getProvider(key?: string): AiProvider {
    const k = key ?? this.defaultProviderKey;
    const provider = this.providers.get(k);
    if (!provider)
      throw new NotFoundException(`AI provider '${k}' not registered`);
    return provider;
  }
 
  /**
   * Redacts PII from a string before sending to any external AI provider.
   */
  redactPii(text: string): string {
    let result = text;
    for (const { pattern, replacement } of PII_PATTERNS) {
      result = result.replace(pattern, replacement);
    }
    return result;
  }
 
  private interpolatePrompt(
    template: string,
    variables: Record<string, string>,
  ): string {
    return template.replace(
      /\{\{(\w+)\}\}/g,
      (_, key) => variables[key] ?? `{{${key}}}`,
    );
  }
 
  private validateVariables(
    template: AiPromptTemplate,
    variables: Record<string, string>,
  ): void {
    const missing = template.requiredVariables.filter((v) => !(v in variables));
    if (missing.length > 0) {
      throw new Error(
        `Missing required prompt variables: ${missing.join(', ')}`,
      );
    }
  }
 
  async generateText(
    tenantId: string,
    promptKey: string,
    variables: Record<string, string> = {},
    modelKey?: string,
  ): Promise<string> {
    const config = await this.getTenantConfig(tenantId);
    if (!config.isEnabled)
      throw new ForbiddenException(
        'AI features are not enabled for this tenant',
      );
 
    const prompt = await this.promptModel
      .findOne({ key: promptKey, status: 'published' })
      .sort({ version: -1 })
      .exec();
    if (!prompt)
      throw new NotFoundException(
        `AI prompt template '${promptKey}' not found`,
      );
 
    this.validateVariables(prompt, variables);
    const interpolated = this.interpolatePrompt(
      prompt.promptTemplate,
      variables,
    );
    const safePrompt = config.piiRedactionEnabled
      ? this.redactPii(interpolated)
      : interpolated;
 
    const provider = this.getProvider(modelKey);
    const start = Date.now();
    let status: 'success' | 'failed' | 'timeout' = 'success';
    let result = { text: '', inputTokens: 0, outputTokens: 0 };
 
    try {
      result = await provider.generateText({
        model: modelKey ?? this.defaultProviderKey,
        userPrompt: safePrompt,
      });
    } catch (err) {
      status = 'failed';
      this.logger.error(`AI generation failed: ${err.message}`);
      throw err;
    } finally {
      await this.executionModel.create({
        tenantId,
        promptKey,
        modelKey: modelKey ?? this.defaultProviderKey,
        capability: prompt.capability,
        status,
        inputTokens: result.inputTokens,
        outputTokens: result.outputTokens,
        durationMs: Date.now() - start,
      });
    }
 
    return result.text;
  }
 
  async createEmbedding(
    tenantId: string,
    text: string,
    modelKey?: string,
  ): Promise<number[]> {
    const config = await this.getTenantConfig(tenantId);
    if (!config.isEnabled)
      throw new ForbiddenException(
        'AI features are not enabled for this tenant',
      );
 
    const provider = this.getProvider(modelKey);
    const { embedding } = await provider.createEmbedding({
      model: modelKey ?? 'text-embedding-3-small',
      text: this.redactPii(text),
    });
    return embedding;
  }
 
  async getUsage(tenantId: string): Promise<any> {
    const [totalExecs, failed] = await Promise.all([
      this.executionModel.countDocuments({ tenantId }),
      this.executionModel.countDocuments({ tenantId, status: 'failed' }),
    ]);
    const aggregated = await this.executionModel.aggregate([
      { $match: { tenantId } },
      {
        $group: {
          _id: null,
          totalTokens: { $sum: { $add: ['$inputTokens', '$outputTokens'] } },
          totalCost: { $sum: '$costUsd' },
        },
      },
    ]);
    return {
      totalExecs,
      failed,
      ...(aggregated[0] ?? { totalTokens: 0, totalCost: 0 }),
    };
  }
 
  private async getTenantConfig(
    tenantId: string,
  ): Promise<AiTenantConfiguration> {
    let config = await this.configModel.findOne({ tenantId }).exec();
    if (!config) {
      config = await new this.configModel({ tenantId }).save();
    }
    return config;
  }
}