All files / backend/dist/utils llm-service.js

0.91% Statements 2/219
0% Branches 0/131
0% Functions 0/26
0.92% Lines 2/217

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                                                          1x                                                                                                                                                                                                                                                                                                                                                                                                                                           1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
/**
 * LLM Service
 *
 * Handles LLM provider configuration, initialization, and API calls.
 * Supports multiple providers via connection string configuration.
 *
 * Configuration:
 * Use environment variables QUIQR_LLM_PROVIDER_0 through QUIQR_LLM_PROVIDER_9
 *
 * Format: provider://credentials@endpoint?params
 *
 * Examples:
 * - QUIQR_LLM_PROVIDER_0="openai://sk-abc123"
 * - QUIQR_LLM_PROVIDER_1="bedrock://token?region=eu-central-1"
 * - QUIQR_LLM_PROVIDER_2="anthropic://sk-ant-xyz"
 * - QUIQR_LLM_PROVIDER_3="google://api-key?location=us-central1"
 * - QUIQR_LLM_PROVIDER_4="azure://key@endpoint.openai.azure.com?deployment=gpt4"
 */
import { generateText } from 'ai';
import { createAnthropic } from '@ai-sdk/anthropic';
import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock';
import { createOpenAI } from '@ai-sdk/openai';
import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { createAzure } from '@ai-sdk/azure';
import { createMistral } from '@ai-sdk/mistral';
import { createCohere } from '@ai-sdk/cohere';
/**
 * Model patterns for each provider type
 */
const MODEL_PATTERNS = {
    openai: [/^gpt-/, /^o1-/, /^text-/],
    anthropic: [/^claude-/],
    bedrock: [/anthropic\.claude/, /^eu\.anthropic\.claude/, /^us\.anthropic\.claude/, /amazon\.titan/, /meta\.llama/, /cohere\.command/, /ai21\./, /mistral\./],
    google: [/^gemini-/, /^models\/gemini/],
    azure: [/^azure\//, /^deployment\//],
    mistral: [/^mistral-/, /^open-mistral/],
    cohere: [/^command-/, /^embed-/],
};
/**
 * Parse a connection string into components
 *
 * Format: provider://credentials@endpoint?params
 *
 * @param connectionString - The connection string to parse
 * @returns Parsed components
 */
export function parseConnectionString(connectionString) {
    try {
        // For simple format provider://credentials, the credentials come after ://
        // For endpoint format provider://credentials@endpoint, parse normally
        let hasEndpoint = connectionString.includes('@');
        if (!hasEndpoint) {
            // Format: provider://credentials?params
            // Extract parts manually
            const protocolEnd = connectionString.indexOf('://');
            if (protocolEnd === -1) {
                throw new Error('Invalid URL');
            }
            const type = connectionString.substring(0, protocolEnd).toLowerCase();
            const afterProtocol = connectionString.substring(protocolEnd + 3);
            // Split by ? to separate credentials from params
            const questionIndex = afterProtocol.indexOf('?');
            let credentials;
            let queryString = '';
            if (questionIndex !== -1) {
                credentials = afterProtocol.substring(0, questionIndex);
                queryString = afterProtocol.substring(questionIndex + 1);
            }
            else {
                credentials = afterProtocol;
            }
            // Decode credentials
            credentials = decodeURIComponent(credentials);
            if (!type) {
                throw new Error('Missing provider type in connection string');
            }
            if (!credentials) {
                throw new Error('Missing credentials in connection string');
            }
            // Parse query parameters
            const params = {};
            if (queryString) {
                const searchParams = new URLSearchParams(queryString);
                searchParams.forEach((value, key) => {
                    params[key] = value;
                });
            }
            return {
                type,
                credentials,
                endpoint: undefined,
                params,
            };
        }
        // Format: provider://credentials@endpoint?params
        // Extract manually to handle properly
        const protocolEnd = connectionString.indexOf('://');
        if (protocolEnd === -1) {
            throw new Error('Invalid URL');
        }
        const type = connectionString.substring(0, protocolEnd).toLowerCase();
        const afterProtocol = connectionString.substring(protocolEnd + 3);
        // Find the @ separator
        const atIndex = afterProtocol.indexOf('@');
        if (atIndex === -1) {
            throw new Error('Expected @ for endpoint format');
        }
        // Credentials are before @
        let credentials = afterProtocol.substring(0, atIndex);
        credentials = decodeURIComponent(credentials);
        // Everything after @ is endpoint and params
        const afterAt = afterProtocol.substring(atIndex + 1);
        // Split by ? to separate endpoint from params
        const questionIndex = afterAt.indexOf('?');
        let endpoint;
        let queryString = '';
        if (questionIndex !== -1) {
            endpoint = afterAt.substring(0, questionIndex);
            queryString = afterAt.substring(questionIndex + 1);
        }
        else {
            endpoint = afterAt;
        }
        // Parse query parameters
        const params = {};
        if (queryString) {
            const searchParams = new URLSearchParams(queryString);
            searchParams.forEach((value, key) => {
                params[key] = value;
            });
        }
        if (!type) {
            throw new Error('Missing provider type in connection string');
        }
        if (!credentials) {
            throw new Error('Missing credentials in connection string');
        }
        return {
            type,
            credentials,
            endpoint: endpoint || undefined,
            params,
        };
    }
    catch (error) {
        if (error instanceof Error && (error.message.includes('Invalid URL') || error.message.includes('Expected @'))) {
            throw new Error(`Invalid connection string format: "${connectionString}". ` +
                `Expected format: provider://credentials@endpoint?params ` +
                `Example: openai://sk-abc123 or bedrock://token?region=eu-central-1`);
        }
        throw error;
    }
}
/**
 * Create an OpenAI provider instance
 */
function createOpenAIProvider(config) {
    const options = {
        apiKey: config.credentials,
    };
    if (config.endpoint) {
        options.baseURL = `https://${config.endpoint}`;
    }
    return createOpenAI(options);
}
/**
 * Create an AWS Bedrock provider instance
 * Bedrock provides access to multiple foundation models from various providers
 *
 * Supports two authentication methods:
 * 1. API Key authentication (recommended) - pass API key as credentials
 * 2. AWS SigV4 authentication (fallback) - uses AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
 */
function createBedrockProvider(config) {
    const region = config.params.region;
    if (!region) {
        throw new Error('AWS Bedrock configuration requires "region" parameter. ' +
            'Example: bedrock://api-key?region=eu-central-1');
    }
    return createAmazonBedrock({
        region,
        // API key authentication (uses AWS_BEARER_TOKEN_BEDROCK internally)
        apiKey: config.credentials,
    });
}
/**
 * Create a direct Anthropic provider instance
 */
function createAnthropicProvider(config) {
    return createAnthropic({
        apiKey: config.credentials,
    });
}
/**
 * Create a Google Gemini provider instance
 */
function createGoogleProvider(config) {
    const options = {
        apiKey: config.credentials,
    };
    // Optional location parameter
    if (config.params.location) {
        options.location = config.params.location;
    }
    return createGoogleGenerativeAI(options);
}
/**
 * Create an Azure OpenAI provider instance
 */
function createAzureProvider(config) {
    if (!config.endpoint) {
        throw new Error('Azure OpenAI configuration requires endpoint. ' +
            'Example: azure://key@endpoint.openai.azure.com?deployment=gpt4');
    }
    const deployment = config.params.deployment;
    if (!deployment) {
        throw new Error('Azure OpenAI configuration requires "deployment" parameter. ' +
            'Example: azure://key@endpoint.openai.azure.com?deployment=gpt4');
    }
    return createAzure({
        apiKey: config.credentials,
        resourceName: config.endpoint.split('.')[0], // Extract resource name from endpoint
    });
}
/**
 * Create a Mistral provider instance
 */
function createMistralProvider(config) {
    return createMistral({
        apiKey: config.credentials,
    });
}
/**
 * Create a Cohere provider instance
 */
function createCohereProvider(config) {
    return createCohere({
        apiKey: config.credentials,
    });
}
/**
 * Provider factory registry
 */
const PROVIDER_FACTORIES = {
    openai: createOpenAIProvider,
    anthropic: createAnthropicProvider,
    bedrock: createBedrockProvider,
    google: createGoogleProvider,
    azure: createAzureProvider,
    mistral: createMistralProvider,
    cohere: createCohereProvider,
};
/**
 * Provider Registry - Singleton class managing all configured providers
 */
export class ProviderRegistry {
    static instance = null;
    providers = new Map();
    initialized = false;
    constructor() { }
    /**
     * Get the singleton instance
     */
    static getInstance() {
        if (!ProviderRegistry.instance) {
            ProviderRegistry.instance = new ProviderRegistry();
        }
        return ProviderRegistry.instance;
    }
    /**
     * Initialize providers from environment variables
     * Reads QUIQR_LLM_PROVIDER_0 through QUIQR_LLM_PROVIDER_9
     */
    initialize() {
        if (this.initialized) {
            return;
        }
        this.providers.clear();
        // Read up to 10 provider configurations
        for (let i = 0; i < 10; i++) {
            const envVar = `QUIQR_LLM_PROVIDER_${i}`;
            const connectionString = process.env[envVar];
            if (!connectionString) {
                continue;
            }
            try {
                const parsed = parseConnectionString(connectionString);
                const factory = PROVIDER_FACTORIES[parsed.type];
                if (!factory) {
                    console.warn(`⚠ Unknown provider type "${parsed.type}" in ${envVar}. ` +
                        `Supported types: ${Object.keys(PROVIDER_FACTORIES).join(', ')}`);
                    continue;
                }
                // Create the provider instance
                const providerInstance = factory(parsed);
                // Create model factory function
                const createModel = (modelName) => {
                    return providerInstance(modelName);
                };
                // Get model patterns for this provider type
                const modelPatterns = MODEL_PATTERNS[parsed.type] || [];
                // Create display name
                let name = parsed.type.charAt(0).toUpperCase() + parsed.type.slice(1);
                if (parsed.endpoint) {
                    name += ` (${parsed.endpoint})`;
                }
                if (parsed.params.region) {
                    name += ` [${parsed.params.region}]`;
                }
                const config = {
                    id: `provider-${i}`,
                    type: parsed.type,
                    name,
                    credentials: parsed.credentials,
                    endpoint: parsed.endpoint,
                    params: parsed.params,
                    modelPatterns,
                    createModel,
                };
                this.providers.set(config.id, config);
                console.log(`✓ Registered ${config.id}: ${config.name}`);
            }
            catch (error) {
                console.error(`✗ Failed to configure ${envVar}:`, error instanceof Error ? error.message : error);
            }
        }
        this.initialized = true;
    }
    /**
     * Get a provider by ID or by matching model string
     *
     * @param modelOrProviderId - Provider ID (e.g., "provider-0") or model string (e.g., "gpt-4")
     * @returns Provider configuration
     */
    getProvider(modelOrProviderId) {
        if (!this.initialized) {
            this.initialize();
        }
        // Check if it's a direct provider ID
        if (this.providers.has(modelOrProviderId)) {
            return this.providers.get(modelOrProviderId);
        }
        // Try to match by model pattern
        const matched = this.matchByModel(modelOrProviderId);
        if (matched) {
            return matched;
        }
        // No match found - provide helpful error
        const availableProviders = Array.from(this.providers.values())
            .map(p => `${p.id} (${p.type})`)
            .join(', ');
        throw new Error(`No provider found for model "${modelOrProviderId}". ` +
            `Available providers: ${availableProviders || 'none configured'}. ` +
            `Configure providers using QUIQR_LLM_PROVIDER_0, QUIQR_LLM_PROVIDER_1, etc.`);
    }
    /**
     * Match a model string against provider patterns
     * Returns the first matching provider (registration order)
     */
    matchByModel(model) {
        for (const provider of this.providers.values()) {
            for (const pattern of provider.modelPatterns) {
                if (pattern.test(model)) {
                    return provider;
                }
            }
        }
        return null;
    }
    /**
     * List all configured providers
     */
    listProviders() {
        if (!this.initialized) {
            this.initialize();
        }
        return Array.from(this.providers.values());
    }
    /**
     * Check if a provider exists
     */
    hasProvider(providerId) {
        if (!this.initialized) {
            this.initialize();
        }
        return this.providers.has(providerId);
    }
    /**
     * Get provider count
     */
    getProviderCount() {
        if (!this.initialized) {
            this.initialize();
        }
        return this.providers.size;
    }
}
/**
 * Call LLM with the given request
 *
 * @param request - LLM request parameters
 * @returns LLM response with text and metadata
 */
export async function callLLM(request) {
    const registry = ProviderRegistry.getInstance();
    // Get provider (either explicit or by model matching)
    const providerConfig = registry.getProvider(request.provider || request.model);
    console.log(`\nUsing provider: ${providerConfig.id} (${providerConfig.name})`);
    console.log(`Model: ${request.model}`);
    // Get the model instance
    const model = providerConfig.createModel(request.model);
    // Set default values
    const temperature = request.temperature ?? 0.7;
    const maxTokens = request.maxTokens ?? 4096;
    console.log(`Temperature: ${temperature}, Max tokens: ${maxTokens}`);
    try {
        // Call the LLM using generateText (non-streaming)
        // For OpenAI models, use maxCompletionTokens (newer parameter name)
        // For other providers, use maxTokens
        const generateOptions = {
            model,
            prompt: request.prompt,
            temperature,
            ...(providerConfig.type === 'openai'
                ? { maxCompletionTokens: maxTokens }
                : { maxTokens }),
        };
        const result = await generateText(generateOptions);
        // Extract response data
        const response = {
            text: result.text,
            model: request.model,
            provider: providerConfig.type,
            providerId: providerConfig.id,
            finishReason: result.finishReason,
        };
        // Add usage stats if available
        if (result.usage) {
            response.usage = {
                promptTokens: result.usage.inputTokens || 0,
                completionTokens: result.usage.outputTokens || 0,
                totalTokens: result.usage.totalTokens || 0,
            };
        }
        return response;
    }
    catch (error) {
        console.error('LLM call failed:', error);
        if (!(error instanceof Error)) {
            throw new Error(`Failed to call ${providerConfig.name}: ${error}`);
        }
        // Provide more helpful error messages
        if (error.message.includes('401') || error.message?.includes('authentication')) {
            throw new Error(`Authentication failed for ${providerConfig.name}. ` +
                `Please check your API credentials in ${providerConfig.id}.`);
        }
        else if (error.message.includes('rate limit')) {
            throw new Error(`Rate limit exceeded for ${providerConfig.name}. ` +
                `Please try again later.`);
        }
        else if (error.message.includes('timeout')) {
            throw new Error(`Request timed out while calling ${providerConfig.name}. ` +
                `Please try again.`);
        }
        // Re-throw with provider context
        throw new Error(`Failed to call ${providerConfig.name}: ${error.message}`);
    }
}
/**
 * Initialize and validate LLM provider configuration at startup
 *
 * @returns Summary of configured providers
 */
export function initializeLLMProviders() {
    const warnings = [];
    const registry = ProviderRegistry.getInstance();
    console.log('\n' + '='.repeat(60));
    console.log('Initializing LLM Providers');
    console.log('='.repeat(60));
    // Initialize registry (reads environment variables)
    registry.initialize();
    const configuredProviders = registry.listProviders();
    if (configuredProviders.length === 0) {
        warnings.push('No LLM providers configured. Set QUIQR_LLM_PROVIDER_0, QUIQR_LLM_PROVIDER_1, etc.');
        console.warn('⚠ No LLM providers configured');
        console.warn('   Set environment variables QUIQR_LLM_PROVIDER_0 through QUIQR_LLM_PROVIDER_9');
        console.warn('   Format: provider://credentials@endpoint?params');
        console.warn('   Example: QUIQR_LLM_PROVIDER_0="openai://sk-abc123"');
    }
    else {
        console.log(`\n✓ ${configuredProviders.length} provider(s) configured:\n`);
        configuredProviders.forEach((provider) => {
            // Generate example models based on patterns
            const modelExamples = [];
            if (provider.type === 'openai') {
                modelExamples.push('gpt-4', 'gpt-3.5-turbo');
            }
            else if (provider.type === 'anthropic') {
                modelExamples.push('claude-3-5-sonnet', 'claude-3-opus');
            }
            else if (provider.type === 'bedrock') {
                modelExamples.push('anthropic.claude-3-5-sonnet', 'meta.llama3', 'amazon.titan-text');
            }
            else if (provider.type === 'google') {
                modelExamples.push('gemini-pro', 'gemini-1.5-pro');
            }
            else if (provider.type === 'azure') {
                modelExamples.push('azure/gpt-4');
            }
            else if (provider.type === 'mistral') {
                modelExamples.push('mistral-large', 'mistral-medium');
            }
            else if (provider.type === 'cohere') {
                modelExamples.push('command-r-plus', 'command-r');
            }
            console.log(`  ${provider.id}: ${provider.name}`);
            console.log(`    Type: ${provider.type}`);
            console.log(`    Example models: ${modelExamples.join(', ')}`);
            console.log('');
        });
    }
    console.log('='.repeat(60) + '\n');
    return {
        count: configuredProviders.length,
        providers: configuredProviders.map((p) => {
            const modelExamples = [];
            if (p.type === 'openai') {
                modelExamples.push('gpt-4', 'gpt-3.5-turbo');
            }
            else if (p.type === 'anthropic') {
                modelExamples.push('claude-3-5-sonnet');
            }
            else if (p.type === 'bedrock') {
                modelExamples.push('anthropic.claude-3-5-sonnet');
            }
            else if (p.type === 'google') {
                modelExamples.push('gemini-pro');
            }
            else if (p.type === 'azure') {
                modelExamples.push('azure/gpt-4');
            }
            else if (p.type === 'mistral') {
                modelExamples.push('mistral-large');
            }
            else if (p.type === 'cohere') {
                modelExamples.push('command-r-plus');
            }
            return {
                id: p.id,
                type: p.type,
                name: p.name,
                modelExamples,
            };
        }),
        warnings,
    };
}
/**
 * Get provider display name (for backward compatibility)
 * @deprecated Use ProviderRegistry instead
 */
export function getProviderDisplayName(providerType) {
    const registry = ProviderRegistry.getInstance();
    const providers = registry.listProviders();
    const provider = providers.find(p => p.type === providerType);
    return provider ? provider.name : providerType;
}