# All files / src llm.ts

85.18% Statements 92/108
90.8% Branches 79/87
57.14% Functions 12/21
85.04% Lines 91/107

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

    61x

    135x
    135x

    135x
    135x
    135x
    135x

    135x
    135x
    135x

    14x

    14x

    3x

    59x
    1x

    58x
    2x

    56x

    56x
    1x

    55x
    56x
    56x

    6x
    6x

    6x

    6x

    7x

    7x
    7x

    7x
    1x
    6x

    1x

    6x

    5x

    16x

    16x
    16x
    16x
    1x
    14x

    2x

    13x

    13x

    13x

    13x
    13x
    13x
    1x
    12x
    1x

    12x

    10x

    17x

    17x
    17x

    17x

    17x
    1x
    14x

    2x

    13x
    12x

    135x
    4x

    131x
    131x
    131x

    135x

    135x
    135x
    135x

    135x
    1x

    135x
    84x
    84x
    84x
    51x
    32x

    135x

    135x

    61x

    9x
    4x
    4x

    9x

    9x
    9x

    61x

     import { Chat } from "./chat/Chat.js";
    import { ChatOptions } from "./chat/ChatOptions.js";
    import { Provider, ModelInfo } from "./providers/Provider.js";
    import {
      providerRegistry,
      ensureOpenAIRegistered,
      registerAnthropicProvider,
      registerGeminiProvider,
      registerDeepSeekProvider,
      registerOllamaProvider,
      registerOpenRouterProvider
    } from "./providers/registry.js";
    import { GeneratedImage } from "./image/GeneratedImage.js";
    import { ModelRegistry } from "./models/ModelRegistry.js";
    import { PricingRegistry } from "./models/PricingRegistry.js";
    import { Model } from "./models/types.js";
    import { Transcription } from "./transcription/Transcription.js";
    import { Moderation } from "./moderation/Moderation.js";
    import { Embedding } from "./embedding/Embedding.js";
    import { EmbeddingRequest } from "./providers/Provider.js";
    import {
      ProviderNotConfiguredError,
      UnsupportedFeatureError,
      ModelCapabilityError
    } from "./errors/index.js";
    import { resolveModelAlias } from "./model_aliases.js";
    import { logger } from "./utils/logger.js";

    import { config, NodeLLMConfig, Configuration } from "./config.js";

    export interface RetryOptions {
      attempts?: number;
      delayMs?: number;
    }

    type LLMConfig = {
      provider?: Provider | string;
      retry?: RetryOptions;
      defaultChatModel?: string;
      defaultTranscriptionModel?: string;
      defaultModerationModel?: string;
      defaultEmbeddingModel?: string;
    } & Omit<Partial<NodeLLMConfig>, "provider">;

    // Provider registration map
    const PROVIDER_REGISTRARS: Record<string, () => void> = {
      openai: ensureOpenAIRegistered,
      gemini: registerGeminiProvider,
      anthropic: registerAnthropicProvider,
      deepseek: registerDeepSeekProvider,
      ollama: registerOllamaProvider,
      openrouter: registerOpenRouterProvider
    };

    export class NodeLLMCore {
      public readonly models = ModelRegistry;
      public readonly pricing = PricingRegistry;

      constructor(
        public readonly config: NodeLLMConfig,
        public readonly provider?: Provider,
        public readonly retry: Required<RetryOptions> = { attempts: 1, delayMs: 0 },
        private readonly defaults: {
          chat?: string;
          transcription?: string;
          moderation?: string;
          embedding?: string;
        } = {}
      ) {
        Object.freeze(this.config);
        Object.freeze(this.retry);
        Object.freeze(this.defaults);
      }

      get defaultChatModel(): string | undefined {
        return this.defaults.chat;
      }
      get defaultTranscriptionModel(): string | undefined {
        return this.defaults.transcription;
      }
      get defaultModerationModel(): string | undefined {
        return this.defaults.moderation;
      }
      get defaultEmbeddingModel(): string | undefined {
        return this.defaults.embedding;
      }

      /**
       * Returns a scoped LLM instance configured for a specific provider.
       * This returns a NEW immutable instance.
       */
      withProvider(providerName: string, scopedConfig?: Partial<NodeLLMConfig>): NodeLLMCore {
        const baseConfig =
          this.config instanceof Configuration ? this.config.toPlainObject() : this.config;
        // We leverage createLLM to handle the resolution of the new provider string
        return createLLM({
          ...baseConfig,
          ...scopedConfig,
          provider: providerName,
          // Preserve defaults unless overridden (conceptually, though createLLM takes specific keys)
          defaultChatModel: this.defaults.chat,
          defaultTranscriptionModel: this.defaults.transcription,
          defaultModerationModel: this.defaults.moderation,
          defaultEmbeddingModel: this.defaults.embedding
        });
      }

      /**
       * Register a custom LLM provider.
       * Note: This modifies the global provider registry.
       */
      registerProvider(name: string, factory: () => Provider): void {
        providerRegistry.register(name, factory);
      }

      getRetryConfig() {
        return this.retry;
      }

      private ensureProviderSupport<K extends keyof Provider>(
        method: K
      ): Provider & Record<K, NonNullable<Provider[K]>> {
        if (!this.provider) {
          throw new ProviderNotConfiguredError();
        }
        if (!this.provider[method]) {
          throw new UnsupportedFeatureError("Provider", String(method));
        }
        return this.provider as Provider & Record<K, NonNullable<Provider[K]>>;
      }

      chat(model?: string, options?: ChatOptions): Chat {
        if (!this.provider) {
          throw new ProviderNotConfiguredError();
        }

        const rawModel = model || this.defaults.chat || this.provider.defaultModel("chat");
        const resolvedModel = resolveModelAlias(rawModel, this.provider.id);
        return new Chat(this.provider, resolvedModel, options, this.retry);
      }

      async listModels(): Promise<ModelInfo[]> {
        const provider = this.ensureProviderSupport("listModels");
        const models = await provider.listModels();

        // Dynamically update the model registry with the fetched info
        ModelRegistry.save(models as unknown as Model[]);

        return models;
      }

      async paint(
        prompt: string,
        options?: {
          model?: string;
          size?: string;
          quality?: string;
          assumeModelExists?: boolean;
          requestTimeout?: number;
        }
      ): Promise<GeneratedImage> {
        const provider = this.ensureProviderSupport("paint");

        const rawModel = options?.model;
        const model = resolveModelAlias(rawModel || "", provider.id);

        if (options?.assumeModelExists) {
          logger.warn(`Skipping validation for model ${model}`);
        } else if (
          model &&
          provider.capabilities &&
          !provider.capabilities.supportsImageGeneration(model)
        ) {
          throw new ModelCapabilityError(model, "image generation");
        }

        const response = await provider.paint({
          prompt,
          ...options,
          model,
          requestTimeout: options?.requestTimeout ?? this.config.requestTimeout
        });

        return new GeneratedImage(response);
      }

      async transcribe(
        file: string,
        options?: {
          model?: string;
          prompt?: string;
          language?: string;
          speakerNames?: string[];
          speakerReferences?: string[];
          assumeModelExists?: boolean;
          requestTimeout?: number;
        }
      ): Promise<Transcription> {
        const provider = this.ensureProviderSupport("transcribe");

        const rawModel = options?.model || this.defaults.transcription || "";
        const model = resolveModelAlias(rawModel, provider.id);
        if (options?.assumeModelExists) {
          logger.warn(`Skipping validation for model ${model}`);
        } else if (
          model &&
          provider.capabilities &&
          !provider.capabilities.supportsTranscription(model)
        ) {
          throw new ModelCapabilityError(model, "transcription");
        }

        const response = await provider.transcribe({
          file,
          ...options,
          model,
          requestTimeout: options?.requestTimeout ?? this.config.requestTimeout
        });

        return new Transcription(response);
      }

      async moderate(
        input: string | string[],
        options?: { model?: string; assumeModelExists?: boolean; requestTimeout?: number }
      ): Promise<Moderation> {
        const provider = this.ensureProviderSupport("moderate");

        const rawModel = options?.model || this.defaults.moderation || "";
        const model = resolveModelAlias(rawModel, provider.id);
        if (options?.assumeModelExists) {
          logger.warn(`Skipping validation for model ${model}`);
        } else if (model && provider.capabilities && !provider.capabilities.supportsModeration(model)) {
          throw new ModelCapabilityError(model, "moderation");
        }

        const response = await provider.moderate({
          input,
          ...options,
          model,
          requestTimeout: options?.requestTimeout ?? this.config.requestTimeout
        });

        return new Moderation(response);
      }

      async embed(
        input: string | string[],
        options?: {
          model?: string;
          dimensions?: number;
          assumeModelExists?: boolean;
          requestTimeout?: number;
        }
      ): Promise<Embedding> {
        const provider = this.ensureProviderSupport("embed");

        const rawModel = options?.model || this.defaults.embedding || "";
        const model = resolveModelAlias(rawModel, provider.id);

        const request: EmbeddingRequest = {
          input,
          model,
          dimensions: options?.dimensions,
          requestTimeout: options?.requestTimeout ?? this.config.requestTimeout
        };

        if (options?.assumeModelExists) {
          logger.warn(`Skipping validation for model ${request.model}`);
        } else if (
          request.model &&
          provider.capabilities &&
          !provider.capabilities.supportsEmbeddings(request.model)
        ) {
          throw new ModelCapabilityError(request.model, "embeddings");
        }

        const response = await provider.embed(request);
        return new Embedding(response);
      }
    }

    export { Transcription, Moderation, Embedding, ModelRegistry, PricingRegistry };

    /**
     * Creates a new immutable LLM instance.
     */
    export function createLLM(options: LLMConfig = {}): NodeLLMCore {
      // 1. Resolve Configuration
      // We must ensure we are working with a SNAPSHOT of the configuration,
      // not a live reference to the global mutable Configuration instance.
      let configSnapshot: NodeLLMConfig;

      if (options instanceof Configuration) {
        configSnapshot = options.toPlainObject();
      } else {
        // If it's a plain object, we merge it into a fresh Configuration to handle
        // defaults and environment variable fallbacks correctly, then snapshot it.
        const tempConfig = new Configuration();
        Object.assign(tempConfig, options);
        configSnapshot = tempConfig.toPlainObject();
      }

      // Use the snapshot for the rest of the logic
      const baseConfig = configSnapshot;

      // 2. Resolve Retry
      let retry: Required<RetryOptions> = { attempts: 1, delayMs: 0 };
      Eif (baseConfig.maxRetries !== undefined) {
        retry.attempts = baseConfig.maxRetries + 1;
      }
      if (options.retry) {
        retry = {
          attempts: options.retry.attempts ?? retry.attempts,
          delayMs: options.retry.delayMs ?? retry.delayMs
        };
      }

      // 3. Resolve Provider
      let providerInstance: Provider | undefined;
      if (typeof options.provider === "string") {
        const registrar = PROVIDER_REGISTRARS[options.provider];
        if (registrar) registrar();
        providerInstance = providerRegistry.resolve(options.provider, baseConfig);
      } else if (options.provider) {
        providerInstance = options.provider;
      }

      // 4. Resolve Defaults
      const defaults = {
        chat: options.defaultChatModel,
        transcription: options.defaultTranscriptionModel,
        moderation: options.defaultModerationModel,
        embedding: options.defaultEmbeddingModel
      };

      return new NodeLLMCore(baseConfig, providerInstance, retry, defaults);
    }

    /**
     * DEFAULT IMMUTABLE INSTANCE
     *
     * NodeLLM is a default immutable instance created at startup.
     *
     * **Architectural Contract**:
     * - Configuration is captured from environment variables at module load time
     * - The instance is frozen and cannot be mutated
     * - Runtime provider switching is achieved via `withProvider()`, not mutation
     * - Model names do NOT imply provider selection (provider must be explicit)
     *
     * **Usage Patterns**:
     *
     * 1. Using the default instance (if env vars are set):
     * ```typescript
     * import { NodeLLM } from '@node-llm/core';
     * const chat = NodeLLM.chat("gpt-4");
     * ```
     *
     * 2. Runtime provider switching (recommended):
     * ```typescript
     * const llm = NodeLLM.withProvider("openai", {
     *   openaiApiKey: process.env.OPENAI_API_KEY
     * });
     * const chat = llm.chat("gpt-4");
     * ```
     *
     * 3. Creating custom instances:
     * ```typescript
     * import { createLLM } from '@node-llm/core';
     * const llm = createLLM({ provider: "anthropic", anthropicApiKey: "..." });
     * ```
     *
     * @see ARCHITECTURE.md for full contract details
     */
    let _defaultInstance: NodeLLMCore | undefined;

    /**
     * The global, immutable NodeLLM instance.
     *
     * DESIGN: Lazy Initialization
     * To support 'import "dotenv/config"' patterns in ESM, this instance
     * does NOT snapshot the environment until its first property access.
     * Once accessed, it is frozen and becomes a stable, immutable contract.
     *
     * @see ARCHITECTURE.md for full contract details
     */
    export const NodeLLM: NodeLLMCore = new Proxy({} as NodeLLMCore, {
      get: (target, prop) => {
        if (!_defaultInstance) {
          _defaultInstance = createLLM(config);
          Object.freeze(_defaultInstance);
        }
        const val = Reflect.get(_defaultInstance, prop);
        // Only bind if it's a function AND it exists on the prototype (is a method)
        // This avoids binding properties like 'models' which is a Class.
        Eif (typeof val === "function" && prop in NodeLLMCore.prototype) {
          return val.bind(_defaultInstance);
        }
        return val;
      },
      getPrototypeOf: () => NodeLLMCore.prototype,
      getOwnPropertyDescriptor: (target, prop) => {
        if (!_defaultInstance) {
          _defaultInstance = createLLM(config);
          Object.freeze(_defaultInstance);
        }
        return Object.getOwnPropertyDescriptor(_defaultInstance, prop);
      },
      ownKeys: () => {
        if (!_defaultInstance) {
          _defaultInstance = createLLM(config);
          Object.freeze(_defaultInstance);
        }
        return Reflect.ownKeys(_defaultInstance);
      }
    });

    /**
     * LEGACY BOOTSTRAPPER (DEPRECATED)
     *
     * Provided to ease migration from the mutable singleton pattern.
     * configure() will warn and no-op, as the global instance is now immutable.
     */
    export const LegacyNodeLLM = {
      configure(_options: LLMConfig | ((config: NodeLLMConfig) => void)) {
        console.warn(
          "NodeLLM.configure() is deprecated and currently a NO-OP. " +
            "The global NodeLLM instance is now immutable. " +
            "Use createLLM() for instance-based LLMs or NodeLLM.withProvider() for runtime switching."
        );
      }
    };