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 | 1x 1x 1x | import { Injectable, Logger, OnModuleInit, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ChatRequestDto, ChatResponseDto, AIModelDto } from '../dto';
interface OpenRouterRequest {
model: string;
messages: { role: string; content: string }[];
temperature?: number;
max_tokens?: number;
top_p?: number;
stream?: boolean;
}
interface OpenRouterResponse {
id: string;
model: string;
choices: {
index: number;
message: { role: string; content: string };
finish_reason: string;
}[];
usage: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
created: number;
}
interface OpenRouterModel {
id: string;
name: string;
description?: string;
context_length: number;
pricing: {
prompt: string;
completion: string;
};
}
@Injectable()
export class OpenRouterClient implements OnModuleInit {
private readonly logger = new Logger(OpenRouterClient.name);
private apiKey: string;
private readonly baseUrl = 'https://openrouter.ai/api/v1';
private readonly timeout: number;
private isConfigured = false;
constructor(private readonly configService: ConfigService) {
this.timeout = this.configService.get<number>('AI_TIMEOUT_MS', 30000);
}
onModuleInit() {
this.apiKey = this.configService.get<string>('OPENROUTER_API_KEY', '');
Iif (!this.apiKey) {
this.logger.warn('OpenRouter API key not configured. AI features will be disabled.');
return;
}
this.isConfigured = true;
this.logger.log('OpenRouter client initialized');
}
isReady(): boolean {
return this.isConfigured;
}
private ensureConfigured(): void {
Iif (!this.isConfigured) {
throw new BadRequestException('AI service is not configured. Please set OPENROUTER_API_KEY.');
}
}
async chatCompletion(
dto: ChatRequestDto,
defaultModel: string,
defaultTemperature: number,
defaultMaxTokens: number,
): Promise<ChatResponseDto> {
this.ensureConfigured();
const requestBody: OpenRouterRequest = {
model: dto.model || defaultModel,
messages: dto.messages,
temperature: dto.temperature ?? defaultTemperature,
max_tokens: dto.max_tokens ?? defaultMaxTokens,
top_p: dto.top_p ?? 1.0,
stream: false, // For now, no streaming
};
const startTime = Date.now();
try {
const response = await fetch(`${this.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
'HTTP-Referer': this.configService.get<string>('APP_URL', 'http://localhost:3001'),
'X-Title': 'Template SaaS',
},
body: JSON.stringify(requestBody),
signal: AbortSignal.timeout(this.timeout),
});
Iif (!response.ok) {
const errorBody = await response.text();
this.logger.error(`OpenRouter API error: ${response.status} - ${errorBody}`);
throw new BadRequestException(`AI request failed: ${response.statusText}`);
}
const data: OpenRouterResponse = await response.json();
const latencyMs = Date.now() - startTime;
this.logger.debug(`Chat completion completed in ${latencyMs}ms, tokens: ${data.usage?.total_tokens}`);
return {
id: data.id,
model: data.model,
choices: data.choices.map((c) => ({
index: c.index,
message: {
role: c.message.role as 'system' | 'user' | 'assistant',
content: c.message.content,
},
finish_reason: c.finish_reason,
})),
usage: {
prompt_tokens: data.usage?.prompt_tokens || 0,
completion_tokens: data.usage?.completion_tokens || 0,
total_tokens: data.usage?.total_tokens || 0,
},
created: data.created,
};
} catch (error) {
Iif (error.name === 'AbortError') {
throw new BadRequestException('AI request timed out');
}
throw error;
}
}
async getModels(): Promise<AIModelDto[]> {
this.ensureConfigured();
try {
const response = await fetch(`${this.baseUrl}/models`, {
headers: {
Authorization: `Bearer ${this.apiKey}`,
},
signal: AbortSignal.timeout(10000),
});
Iif (!response.ok) {
throw new BadRequestException('Failed to fetch models');
}
const data = await response.json();
const models: OpenRouterModel[] = data.data || [];
// Filter to popular models
const popularModels = [
'anthropic/claude-3-haiku',
'anthropic/claude-3-sonnet',
'anthropic/claude-3-opus',
'openai/gpt-4-turbo',
'openai/gpt-4',
'openai/gpt-3.5-turbo',
'google/gemini-pro',
'meta-llama/llama-3-70b-instruct',
];
return models
.filter((m) => popularModels.some((p) => m.id.includes(p.split('/')[1])))
.slice(0, 20)
.map((m) => ({
id: m.id,
name: m.name,
provider: m.id.split('/')[0],
context_length: m.context_length,
pricing: {
prompt: parseFloat(m.pricing.prompt) * 1000000, // Per million tokens
completion: parseFloat(m.pricing.completion) * 1000000,
},
}));
} catch (error) {
this.logger.error('Failed to fetch models:', error);
// Return default models if API fails
return [
{
id: 'anthropic/claude-3-haiku',
name: 'Claude 3 Haiku',
provider: 'anthropic',
context_length: 200000,
pricing: { prompt: 0.25, completion: 1.25 },
},
{
id: 'openai/gpt-3.5-turbo',
name: 'GPT-3.5 Turbo',
provider: 'openai',
context_length: 16385,
pricing: { prompt: 0.5, completion: 1.5 },
},
];
}
}
// Calculate cost for a request
calculateCost(
model: string,
inputTokens: number,
outputTokens: number,
): { input: number; output: number; total: number } {
// Approximate pricing per million tokens (in USD)
const pricing: Record<string, { input: number; output: number }> = {
'anthropic/claude-3-haiku': { input: 0.25, output: 1.25 },
'anthropic/claude-3-sonnet': { input: 3.0, output: 15.0 },
'anthropic/claude-3-opus': { input: 15.0, output: 75.0 },
'openai/gpt-4-turbo': { input: 10.0, output: 30.0 },
'openai/gpt-4': { input: 30.0, output: 60.0 },
'openai/gpt-3.5-turbo': { input: 0.5, output: 1.5 },
default: { input: 1.0, output: 2.0 },
};
const modelPricing = pricing[model] || pricing.default;
const inputCost = (inputTokens / 1_000_000) * modelPricing.input;
const outputCost = (outputTokens / 1_000_000) * modelPricing.output;
return {
input: inputCost,
output: outputCost,
total: inputCost + outputCost,
};
}
}
|