All files / backend/src/utils llm-service.ts

76.71% Statements 168/219
58.01% Branches 76/131
84.61% Functions 22/26
76.95% Lines 167/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 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730                                                                                                                                                                              2x                                     44x       44x   44x     41x 41x 2x     39x 39x     39x   39x   39x 7x 7x   32x       39x   39x 1x     38x 1x       37x 37x 7x 7x 8x       37x                   3x 3x       3x 3x     3x 3x         3x 3x     3x     3x   3x   3x 2x 2x   1x       3x 3x 2x 2x 2x       3x       3x       3x             4x 2x           2x               13x       13x       13x                       4x 4x             4x                     3x                 4x         4x       4x             1x             1x 1x             1x                   2x                 1x               2x                           26x 26x 26x               24x 24x   24x               25x 1x     24x     24x 240x 240x   240x 210x     30x 30x 30x   30x 1x       1x       28x     28x         28x     240x 240x 1x   28x 4x     28x                     28x 28x   1x             240x                   32x 15x       32x 1x       31x 31x 29x       2x 2x     2x                       31x 31x 54x 29x       2x             5x     5x             8x     8x             7x     7x                                                                                                                                                                                                                               3x 3x   3x 3x 3x     3x   3x   3x 1x     1x 1x 1x 1x   2x   2x   5x 5x 2x 3x   3x 1x 2x 1x 1x   1x 1x         5x 5x 5x 5x       3x   3x     5x 5x 2x 3x   3x 1x 2x 1x 1x   1x 1x         5x                                          
/**
 * 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, LanguageModel } 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';
 
/**
 * Supported LLM provider types
 */
export type LLMProviderType = string;
 
/**
 * LLM request parameters
 */
export interface LLMRequest {
  model: string;
  prompt: string;
  temperature?: number;
  maxTokens?: number;
  provider?: string; // Optional explicit provider ID
}
 
/**
 * LLM response
 */
export interface LLMResponse {
  text: string;
  model: string;
  usage?: {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
  };
  finishReason?: string;
  provider: string;
  providerId: string;
}
 
/**
 * Parsed connection string components
 */
export interface ProviderConnectionString {
  type: string;           // Provider type (openai, anthropic, etc.)
  credentials: string;    // API key or token
  endpoint?: string;      // Optional custom endpoint
  params: Record<string, string>; // Query parameters
}
 
/**
 * Provider configuration
 */
export interface ProviderConfig {
  id: string;             // Unique ID (e.g., "provider-0")
  type: string;           // Provider type (openai, anthropic, etc.)
  name: string;           // Display name
  credentials: string;    // API key/token
  endpoint?: string;      // Optional custom endpoint
  params: Record<string, string>; // Provider-specific parameters
  modelPatterns: RegExp[]; // Patterns to match model strings
  createModel: (modelName: string) => LanguageModel; // Factory function
}
 
/**
 * Model patterns for each provider type
 */
const MODEL_PATTERNS: Record<string, RegExp[]> = {
  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: string): ProviderConnectionString {
  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: string;
      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: Record<string, string> = {};
      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('://');
    Iif (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('@');
    Iif (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: string;
    let queryString = '';
    
    if (questionIndex !== -1) {
      endpoint = afterAt.substring(0, questionIndex);
      queryString = afterAt.substring(questionIndex + 1);
    } else {
      endpoint = afterAt;
    }
    
    // Parse query parameters
    const params: Record<string, string> = {};
    if (queryString) {
      const searchParams = new URLSearchParams(queryString);
      searchParams.forEach((value, key) => {
        params[key] = value;
      });
    }
    
    Iif (!type) {
      throw new Error('Missing provider type in connection string');
    }
    
    Iif (!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: ProviderConnectionString) {
  const options: any = {
    apiKey: config.credentials,
  };
  
  Iif (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: ProviderConnectionString) {
  const region = config.params.region;
  Iif (!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: ProviderConnectionString) {
  return createAnthropic({
    apiKey: config.credentials,
  });
}
 
/**
 * Create a Google Gemini provider instance
 */
function createGoogleProvider(config: ProviderConnectionString) {
  const options: any = {
    apiKey: config.credentials,
  };
  
  // Optional location parameter
  Iif (config.params.location) {
    options.location = config.params.location;
  }
  
  return createGoogleGenerativeAI(options);
}
 
/**
 * Create an Azure OpenAI provider instance
 */
function createAzureProvider(config: ProviderConnectionString) {
  Iif (!config.endpoint) {
    throw new Error(
      'Azure OpenAI configuration requires endpoint. ' +
      'Example: azure://key@endpoint.openai.azure.com?deployment=gpt4'
    );
  }
  
  const deployment = config.params.deployment;
  Iif (!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: ProviderConnectionString) {
  return createMistral({
    apiKey: config.credentials,
  });
}
 
/**
 * Create a Cohere provider instance
 */
function createCohereProvider(config: ProviderConnectionString) {
  return createCohere({
    apiKey: config.credentials,
  });
}
 
/**
 * Provider factory registry
 */
const PROVIDER_FACTORIES: Record<string, (config: ProviderConnectionString) => any> = {
  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 {
  private static instance: ProviderRegistry | null = null;
  private providers: Map<string, ProviderConfig> = new Map();
  private initialized = false;
 
  private constructor() {}
 
  /**
   * Get the singleton instance
   */
  static getInstance(): ProviderRegistry {
    Eif (!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(): void {
    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: string): LanguageModel => {
          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: ProviderConfig = {
          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: string): ProviderConfig {
    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)
   */
  private matchByModel(model: string): ProviderConfig | null {
    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(): ProviderConfig[] {
    Iif (!this.initialized) {
      this.initialize();
    }
    return Array.from(this.providers.values());
  }
 
  /**
   * Check if a provider exists
   */
  hasProvider(providerId: string): boolean {
    Iif (!this.initialized) {
      this.initialize();
    }
    return this.providers.has(providerId);
  }
 
  /**
   * Get provider count
   */
  getProviderCount(): number {
    Iif (!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: LLMRequest): Promise<LLMResponse> {
  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: Parameters<typeof generateText>[0] = {
      model,
      prompt: request.prompt,
      temperature,
      ...(providerConfig.type === 'openai'
        ? { maxCompletionTokens: maxTokens }
        : { maxTokens }
      ),
    };
 
    const result = await generateText(generateOptions);
 
    // Extract response data
    const response: LLMResponse = {
      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: unknown) {
    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(): {
  count: number;
  providers: Array<{
    id: string;
    type: string;
    name: string;
    modelExamples: string[];
  }>;
  warnings: string[];
} {
  const warnings: string[] = [];
  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: string[] = [];
      if (provider.type === 'openai') {
        modelExamples.push('gpt-4', 'gpt-3.5-turbo');
      I} 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');
      I} else if (provider.type === 'azure') {
        modelExamples.push('azure/gpt-4');
      } else if (provider.type === 'mistral') {
        modelExamples.push('mistral-large', 'mistral-medium');
      E} 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: string[] = [];
      if (p.type === 'openai') {
        modelExamples.push('gpt-4', 'gpt-3.5-turbo');
      I} 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');
      I} else if (p.type === 'azure') {
        modelExamples.push('azure/gpt-4');
      } else if (p.type === 'mistral') {
        modelExamples.push('mistral-large');
      E} 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: string): string {
  const registry = ProviderRegistry.getInstance();
  const providers = registry.listProviders();
  const provider = providers.find(p => p.type === providerType);
  return provider ? provider.name : providerType;
}