@happyvertical/ai 0.102.6 → 0.102.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -471,6 +471,21 @@ instances created directly instead of through `getAI()`:
471
471
  Reasoning is opt-in. The 1,024-token default is a ceiling for explicitly
472
472
  requested reasoning, not an automatically enabled thinking budget.
473
473
 
474
+ Explicit `reasoning.effort` is forwarded as top-level `reasoning_effort` for
475
+ direct OpenAI and LiteLLM Chat Completions, including streaming and `none`.
476
+ Bifrost retains its nested `reasoning` envelope and budget/thoughts fields.
477
+ Omitted effort stays omitted; the upstream provider validates model support.
478
+
479
+ LiteLLM rejects caller-supplied `reasoning.maxTokens`,
480
+ `reasoning.includeThoughts`, and legacy `includeThoughts` before model discovery
481
+ or transport. Its Chat Completions protocol has no generic separate reasoning
482
+ budget/thoughts envelope: forwarding it as `reasoning` can reach an OpenAI route
483
+ as an unsupported parameter. Use effort plus `maxTokens` (the combined completion
484
+ limit on OpenAI routes); this is not a separately enforced reasoning-token cap.
485
+ The SDK's inferred local normalization budget does not trigger this rejection.
486
+ See [LiteLLM's Chat Completions examples](https://docs.litellm.ai/blog/gpt_6_sol_luna).
487
+
488
+
474
489
  An approved workload can raise a client-level ceiling explicitly. Prefer a
475
490
  workload-specific client so the wider limit is not shared accidentally.
476
491
 
@@ -1,5 +1,5 @@
1
1
  import { c as normalizeImageGenerationOptions, s as normalizeChatOptions } from "./usage-BaQKo8bc.js";
2
- import { d as OpenAIProvider } from "./src-B_NKcxc9.js";
2
+ import { d as OpenAIProvider } from "./src-nB7u5Xl0.js";
3
3
  import { i as BifrostAdmin, n as isSpeechModel, o as normalizeGatewayBaseUrl, r as isTranscriptionModel, s as resolveGatewayAdminBaseUrl, t as isAudioModel } from "./gateway-audio-models-BSZGgjd8.js";
4
4
  import { ValidationError } from "@happyvertical/utils";
5
5
  //#region src/shared/providers/bifrost.ts
@@ -199,4 +199,4 @@ var BifrostProvider = class extends OpenAIProvider {
199
199
  //#endregion
200
200
  export { BifrostProvider };
201
201
 
202
- //# sourceMappingURL=bifrost-C9MAwEDS.js.map
202
+ //# sourceMappingURL=bifrost-BXiXdyb8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bifrost-C9MAwEDS.js","names":[],"sources":["../../src/shared/providers/bifrost.ts"],"sourcesContent":["import { ValidationError } from '@happyvertical/utils';\n\nimport {\n normalizeChatOptions,\n normalizeImageGenerationOptions,\n} from '../safety';\nimport type {\n AICapabilities,\n AIMessage,\n AIModel,\n AIResponse,\n BifrostOptions,\n ChatOptions,\n EmbeddingOptions,\n EmbeddingResponse,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n} from '../types';\nimport {\n BifrostAdmin,\n normalizeGatewayBaseUrl,\n resolveGatewayAdminBaseUrl,\n} from './gateway-admin';\nimport {\n isAudioModel,\n isSpeechModel,\n isTranscriptionModel,\n} from './gateway-audio-models';\nimport { type OpenAICompatibleProfile, OpenAIProvider } from './openai';\n\nconst BIFROST_CAPABILITIES: AICapabilities = {\n chat: true,\n completion: true,\n embeddings: true,\n streaming: true,\n functions: true,\n vision: true,\n fineTuning: false,\n imageEmbeddings: true,\n imageGeneration: true,\n videoGeneration: false,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 128000,\n supportedOperations: [\n 'chat',\n 'completion',\n 'embedding',\n 'streaming',\n 'functions',\n 'vision',\n 'image_embedding',\n 'image_generation',\n ],\n};\n\nfunction isEmbeddingModel(modelId: string): boolean {\n return /embed/i.test(modelId);\n}\n\nfunction isImageEmbeddingModel(modelId: string): boolean {\n return /titan-embed-image|multimodalembedding|image[-_]?embed|clip/i.test(\n modelId,\n );\n}\n\nfunction isImageGenerationModel(modelId: string): boolean {\n return /gpt-image|dall-e|imagen|stable[-_ ]diffusion|sdxl|flux|titan-image|image-generator/i.test(\n modelId,\n );\n}\n\nfunction isFilteredBifrostModel(modelId: string): boolean {\n return /moderation|rerank/i.test(modelId);\n}\n\nfunction inferBifrostContextLength(modelId: string): number {\n if (isEmbeddingModel(modelId)) return 8192;\n if (/gemini-1\\.5|gemini-2\\.0|gemini-2\\.5|gemini-3/i.test(modelId)) {\n return 1000000;\n }\n if (/claude/i.test(modelId)) return 200000;\n if (/gpt-4o|gpt-4\\.1|o1|o3|o4|llama|mistral|qwen|deepseek/i.test(modelId)) {\n return 128000;\n }\n return 32768;\n}\n\nfunction inferBifrostFunctions(modelId: string): boolean {\n if (isEmbeddingModel(modelId) || isAudioModel(modelId)) return false;\n return /gpt|claude|gemini|command|llama|mistral|qwen|deepseek|o1|o3|o4/i.test(\n modelId,\n );\n}\n\nfunction inferBifrostVision(modelId: string): boolean {\n if (isAudioModel(modelId)) return false;\n return /gpt-4o|gpt-4\\.1|vision|claude-3|gemini|pixtral|llava|qwen.*vl|vl-/i.test(\n modelId,\n );\n}\n\nfunction inferBifrostCapabilities(modelId: string): string[] {\n if (isTranscriptionModel(modelId)) {\n return ['transcription'];\n }\n\n if (isSpeechModel(modelId)) {\n return ['speech'];\n }\n\n if (isImageGenerationModel(modelId)) {\n return ['image_generation'];\n }\n\n if (isImageEmbeddingModel(modelId)) {\n return ['embeddings', 'image_embedding'];\n }\n\n if (isEmbeddingModel(modelId)) {\n return ['embeddings'];\n }\n\n const capabilities = ['text', 'chat'];\n\n if (inferBifrostFunctions(modelId)) {\n capabilities.push('functions');\n }\n\n if (inferBifrostVision(modelId)) {\n capabilities.push('vision');\n }\n\n return capabilities;\n}\n\nfunction ensureBifrostOptions(options: BifrostOptions): BifrostOptions {\n if (!options.baseUrl?.trim()) {\n throw new ValidationError('Bifrost baseUrl is required', {\n provider: 'bifrost',\n hint: 'Pass baseUrl like http://localhost:8080, http://localhost:8080/openai, or http://localhost:8080/v1 and optionally adminBaseUrl for governance endpoints',\n });\n }\n\n const baseUrl = normalizeGatewayBaseUrl(options.baseUrl);\n const inferenceBaseUrl = /\\/(?:openai|v1|pydanticai\\/v1)$/.test(baseUrl)\n ? baseUrl\n : `${baseUrl}/openai`;\n const headers = options.apiKey\n ? {\n ...options.headers,\n 'x-bf-vk': options.apiKey,\n 'x-api-key': options.apiKey,\n }\n : options.headers;\n\n return {\n ...options,\n baseUrl: inferenceBaseUrl,\n headers,\n };\n}\n\nconst BIFROST_PROFILE: OpenAICompatibleProfile = {\n providerLabel: 'Bifrost',\n providerName: 'bifrost',\n defaultModel: 'openai/gpt-4o-mini',\n capabilities: BIFROST_CAPABILITIES,\n describeModel: (modelId) => `Bifrost model: ${modelId}`,\n getContextLength: inferBifrostContextLength,\n getModelCapabilities: inferBifrostCapabilities,\n shouldIncludeModel: (modelId) => !isFilteredBifrostModel(modelId),\n supportsFunctions: inferBifrostFunctions,\n supportsVision: inferBifrostVision,\n};\n\ntype BifrostResolvedCapability =\n | 'chat'\n | 'vision'\n | 'embeddings'\n | 'image_generation';\n\nfunction supportsCapability(\n model: AIModel,\n capability: BifrostResolvedCapability,\n): boolean {\n if (capability === 'vision') {\n return (\n model.capabilities.includes('vision') || model.supportsVision === true\n );\n }\n\n if (capability === 'embeddings') {\n return model.capabilities.includes('embeddings');\n }\n\n if (capability === 'image_generation') {\n return model.capabilities.includes('image_generation');\n }\n\n return model.capabilities.includes('chat');\n}\n\n/**\n * Bifrost provider implementation.\n *\n * Bifrost exposes OpenAI-compatible inference and governance admin APIs. This\n * provider reuses the OpenAI-compatible transport for inference and exposes\n * `admin` for tenant project and virtual-key provisioning.\n */\nexport class BifrostProvider extends OpenAIProvider {\n readonly admin: BifrostAdmin;\n private readonly configuredDefaultModel?: string;\n private readonly resolvedModelCache = new Map<\n BifrostResolvedCapability,\n Promise<string>\n >();\n\n constructor(options: BifrostOptions) {\n const normalized = ensureBifrostOptions(options);\n super(normalized, BIFROST_PROFILE);\n const adminKey = normalized.adminApiKey || normalized.apiKey;\n const adminUsername = normalized.adminUser || normalized.adminUsername;\n this.admin = new BifrostAdmin({\n provider: 'bifrost',\n baseUrl: resolveGatewayAdminBaseUrl(\n normalized.baseUrl,\n normalized.adminUrl || normalized.adminBaseUrl,\n 'bifrost',\n ),\n apiKey: adminKey,\n username: adminUsername,\n password: normalized.adminPassword,\n headers:\n adminKey && !(adminUsername && normalized.adminPassword)\n ? {\n ...normalized.adminHeaders,\n 'x-bf-vk': adminKey,\n 'x-api-key': adminKey,\n }\n : normalized.adminHeaders,\n timeout: normalized.timeout,\n });\n this.configuredDefaultModel = normalized.defaultModel;\n }\n\n private async resolveModel(\n capability: BifrostResolvedCapability,\n explicitModel?: string,\n ): Promise<string> {\n if (explicitModel) {\n return explicitModel;\n }\n\n if (\n this.configuredDefaultModel &&\n (capability === 'chat' || capability === 'vision')\n ) {\n return this.configuredDefaultModel;\n }\n\n const cached = this.resolvedModelCache.get(capability);\n if (cached) {\n return cached;\n }\n\n const pending = this.selectModel(capability).catch((error) => {\n this.resolvedModelCache.delete(capability);\n throw error;\n });\n this.resolvedModelCache.set(capability, pending);\n return pending;\n }\n\n private async selectModel(\n capability: BifrostResolvedCapability,\n ): Promise<string> {\n const models = await super.getModels();\n const model = models.find((candidate) =>\n supportsCapability(candidate, capability),\n );\n\n if (!model) {\n throw new ValidationError(\n `No ${capability} model is available from the Bifrost gateway`,\n {\n provider: 'bifrost',\n capability,\n hint: 'Pass defaultModel explicitly or ensure the gateway returns a compatible model for this key',\n },\n );\n }\n\n return model.id;\n }\n\n async chat(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): Promise<AIResponse> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'bifrost',\n options.model || this.options.defaultModel,\n );\n return super.chat(messages, {\n ...safe,\n model: await this.resolveModel('chat', safe.model),\n });\n }\n\n async *stream(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): AsyncIterable<string> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'bifrost',\n options.model || this.options.defaultModel,\n );\n yield* super.stream(messages, {\n ...safe,\n model: await this.resolveModel('chat', safe.model),\n });\n }\n\n async describeImage(\n image: string | Buffer,\n prompt?: string,\n options: ImageDescriptionOptions = {},\n ): Promise<string> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'bifrost',\n options.model || this.options.defaultModel,\n );\n return super.describeImage(image, prompt, {\n ...safe,\n model: await this.resolveModel('vision', safe.model),\n });\n }\n\n async embed(\n text: string | string[],\n options: EmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n return super.embed(text, {\n ...options,\n model: await this.resolveModel('embeddings', options.model),\n });\n }\n\n async embedImage(\n image: string | Buffer,\n options: ImageEmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n return super.embedImage(image, {\n ...options,\n model: await this.resolveModel('embeddings', options.model),\n });\n }\n\n async generateImage(\n prompt: string,\n options: ImageGenerationOptions = {},\n ): Promise<ImageGenerationResponse> {\n const safe = normalizeImageGenerationOptions(\n this.options,\n options,\n 'bifrost',\n options.model,\n );\n return super.generateImage(prompt, {\n ...safe,\n model: await this.resolveModel('image_generation', safe.model),\n });\n }\n}\n"],"mappings":";;;;;AAgCA,IAAM,uBAAuC;CAC3C,MAAM;CACN,YAAY;CACZ,YAAY;CACZ,WAAW;CACX,WAAW;CACX,QAAQ;CACR,YAAY;CACZ,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,KAAK;CACL,cAAc;CACd,aAAa;CACb,kBAAkB;CAClB,qBAAqB;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;AAEA,SAAS,iBAAiB,SAA0B;CAClD,OAAO,SAAS,KAAK,OAAO;AAC9B;AAEA,SAAS,sBAAsB,SAA0B;CACvD,OAAO,8DAA8D,KACnE,OACF;AACF;AAEA,SAAS,uBAAuB,SAA0B;CACxD,OAAO,sFAAsF,KAC3F,OACF;AACF;AAEA,SAAS,uBAAuB,SAA0B;CACxD,OAAO,qBAAqB,KAAK,OAAO;AAC1C;AAEA,SAAS,0BAA0B,SAAyB;CAC1D,IAAI,iBAAiB,OAAO,GAAG,OAAO;CACtC,IAAI,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7B,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,cAAc,QAAQ,KAAK;EAC5D,CAAC;CACH;CAEA,MAAM,cACJ,QACA,UAAkC,CAAC,GACD;EAClC,MAAM,OAAO,gCACX,KAAK,SACL,SACA,WACA,QAAQ,KACV;EACA,OAAO,MAAM,cAAc,QAAQ;GACjC,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,oBAAoB,KAAK,KAAK;EAC/D,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"bifrost-BXiXdyb8.js","names":[],"sources":["../../src/shared/providers/bifrost.ts"],"sourcesContent":["import { ValidationError } from '@happyvertical/utils';\n\nimport {\n normalizeChatOptions,\n normalizeImageGenerationOptions,\n} from '../safety';\nimport type {\n AICapabilities,\n AIMessage,\n AIModel,\n AIResponse,\n BifrostOptions,\n ChatOptions,\n EmbeddingOptions,\n EmbeddingResponse,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n} from '../types';\nimport {\n BifrostAdmin,\n normalizeGatewayBaseUrl,\n resolveGatewayAdminBaseUrl,\n} from './gateway-admin';\nimport {\n isAudioModel,\n isSpeechModel,\n isTranscriptionModel,\n} from './gateway-audio-models';\nimport { type OpenAICompatibleProfile, OpenAIProvider } from './openai';\n\nconst BIFROST_CAPABILITIES: AICapabilities = {\n chat: true,\n completion: true,\n embeddings: true,\n streaming: true,\n functions: true,\n vision: true,\n fineTuning: false,\n imageEmbeddings: true,\n imageGeneration: true,\n videoGeneration: false,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 128000,\n supportedOperations: [\n 'chat',\n 'completion',\n 'embedding',\n 'streaming',\n 'functions',\n 'vision',\n 'image_embedding',\n 'image_generation',\n ],\n};\n\nfunction isEmbeddingModel(modelId: string): boolean {\n return /embed/i.test(modelId);\n}\n\nfunction isImageEmbeddingModel(modelId: string): boolean {\n return /titan-embed-image|multimodalembedding|image[-_]?embed|clip/i.test(\n modelId,\n );\n}\n\nfunction isImageGenerationModel(modelId: string): boolean {\n return /gpt-image|dall-e|imagen|stable[-_ ]diffusion|sdxl|flux|titan-image|image-generator/i.test(\n modelId,\n );\n}\n\nfunction isFilteredBifrostModel(modelId: string): boolean {\n return /moderation|rerank/i.test(modelId);\n}\n\nfunction inferBifrostContextLength(modelId: string): number {\n if (isEmbeddingModel(modelId)) return 8192;\n if (/gemini-1\\.5|gemini-2\\.0|gemini-2\\.5|gemini-3/i.test(modelId)) {\n return 1000000;\n }\n if (/claude/i.test(modelId)) return 200000;\n if (/gpt-4o|gpt-4\\.1|o1|o3|o4|llama|mistral|qwen|deepseek/i.test(modelId)) {\n return 128000;\n }\n return 32768;\n}\n\nfunction inferBifrostFunctions(modelId: string): boolean {\n if (isEmbeddingModel(modelId) || isAudioModel(modelId)) return false;\n return /gpt|claude|gemini|command|llama|mistral|qwen|deepseek|o1|o3|o4/i.test(\n modelId,\n );\n}\n\nfunction inferBifrostVision(modelId: string): boolean {\n if (isAudioModel(modelId)) return false;\n return /gpt-4o|gpt-4\\.1|vision|claude-3|gemini|pixtral|llava|qwen.*vl|vl-/i.test(\n modelId,\n );\n}\n\nfunction inferBifrostCapabilities(modelId: string): string[] {\n if (isTranscriptionModel(modelId)) {\n return ['transcription'];\n }\n\n if (isSpeechModel(modelId)) {\n return ['speech'];\n }\n\n if (isImageGenerationModel(modelId)) {\n return ['image_generation'];\n }\n\n if (isImageEmbeddingModel(modelId)) {\n return ['embeddings', 'image_embedding'];\n }\n\n if (isEmbeddingModel(modelId)) {\n return ['embeddings'];\n }\n\n const capabilities = ['text', 'chat'];\n\n if (inferBifrostFunctions(modelId)) {\n capabilities.push('functions');\n }\n\n if (inferBifrostVision(modelId)) {\n capabilities.push('vision');\n }\n\n return capabilities;\n}\n\nfunction ensureBifrostOptions(options: BifrostOptions): BifrostOptions {\n if (!options.baseUrl?.trim()) {\n throw new ValidationError('Bifrost baseUrl is required', {\n provider: 'bifrost',\n hint: 'Pass baseUrl like http://localhost:8080, http://localhost:8080/openai, or http://localhost:8080/v1 and optionally adminBaseUrl for governance endpoints',\n });\n }\n\n const baseUrl = normalizeGatewayBaseUrl(options.baseUrl);\n const inferenceBaseUrl = /\\/(?:openai|v1|pydanticai\\/v1)$/.test(baseUrl)\n ? baseUrl\n : `${baseUrl}/openai`;\n const headers = options.apiKey\n ? {\n ...options.headers,\n 'x-bf-vk': options.apiKey,\n 'x-api-key': options.apiKey,\n }\n : options.headers;\n\n return {\n ...options,\n baseUrl: inferenceBaseUrl,\n headers,\n };\n}\n\nconst BIFROST_PROFILE: OpenAICompatibleProfile = {\n providerLabel: 'Bifrost',\n providerName: 'bifrost',\n defaultModel: 'openai/gpt-4o-mini',\n capabilities: BIFROST_CAPABILITIES,\n describeModel: (modelId) => `Bifrost model: ${modelId}`,\n getContextLength: inferBifrostContextLength,\n getModelCapabilities: inferBifrostCapabilities,\n shouldIncludeModel: (modelId) => !isFilteredBifrostModel(modelId),\n supportsFunctions: inferBifrostFunctions,\n supportsVision: inferBifrostVision,\n};\n\ntype BifrostResolvedCapability =\n | 'chat'\n | 'vision'\n | 'embeddings'\n | 'image_generation';\n\nfunction supportsCapability(\n model: AIModel,\n capability: BifrostResolvedCapability,\n): boolean {\n if (capability === 'vision') {\n return (\n model.capabilities.includes('vision') || model.supportsVision === true\n );\n }\n\n if (capability === 'embeddings') {\n return model.capabilities.includes('embeddings');\n }\n\n if (capability === 'image_generation') {\n return model.capabilities.includes('image_generation');\n }\n\n return model.capabilities.includes('chat');\n}\n\n/**\n * Bifrost provider implementation.\n *\n * Bifrost exposes OpenAI-compatible inference and governance admin APIs. This\n * provider reuses the OpenAI-compatible transport for inference and exposes\n * `admin` for tenant project and virtual-key provisioning.\n */\nexport class BifrostProvider extends OpenAIProvider {\n readonly admin: BifrostAdmin;\n private readonly configuredDefaultModel?: string;\n private readonly resolvedModelCache = new Map<\n BifrostResolvedCapability,\n Promise<string>\n >();\n\n constructor(options: BifrostOptions) {\n const normalized = ensureBifrostOptions(options);\n super(normalized, BIFROST_PROFILE);\n const adminKey = normalized.adminApiKey || normalized.apiKey;\n const adminUsername = normalized.adminUser || normalized.adminUsername;\n this.admin = new BifrostAdmin({\n provider: 'bifrost',\n baseUrl: resolveGatewayAdminBaseUrl(\n normalized.baseUrl,\n normalized.adminUrl || normalized.adminBaseUrl,\n 'bifrost',\n ),\n apiKey: adminKey,\n username: adminUsername,\n password: normalized.adminPassword,\n headers:\n adminKey && !(adminUsername && normalized.adminPassword)\n ? {\n ...normalized.adminHeaders,\n 'x-bf-vk': adminKey,\n 'x-api-key': adminKey,\n }\n : normalized.adminHeaders,\n timeout: normalized.timeout,\n });\n this.configuredDefaultModel = normalized.defaultModel;\n }\n\n private async resolveModel(\n capability: BifrostResolvedCapability,\n explicitModel?: string,\n ): Promise<string> {\n if (explicitModel) {\n return explicitModel;\n }\n\n if (\n this.configuredDefaultModel &&\n (capability === 'chat' || capability === 'vision')\n ) {\n return this.configuredDefaultModel;\n }\n\n const cached = this.resolvedModelCache.get(capability);\n if (cached) {\n return cached;\n }\n\n const pending = this.selectModel(capability).catch((error) => {\n this.resolvedModelCache.delete(capability);\n throw error;\n });\n this.resolvedModelCache.set(capability, pending);\n return pending;\n }\n\n private async selectModel(\n capability: BifrostResolvedCapability,\n ): Promise<string> {\n const models = await super.getModels();\n const model = models.find((candidate) =>\n supportsCapability(candidate, capability),\n );\n\n if (!model) {\n throw new ValidationError(\n `No ${capability} model is available from the Bifrost gateway`,\n {\n provider: 'bifrost',\n capability,\n hint: 'Pass defaultModel explicitly or ensure the gateway returns a compatible model for this key',\n },\n );\n }\n\n return model.id;\n }\n\n async chat(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): Promise<AIResponse> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'bifrost',\n options.model || this.options.defaultModel,\n );\n return super.chat(messages, {\n ...safe,\n model: await this.resolveModel('chat', safe.model),\n });\n }\n\n async *stream(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): AsyncIterable<string> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'bifrost',\n options.model || this.options.defaultModel,\n );\n yield* super.stream(messages, {\n ...safe,\n model: await this.resolveModel('chat', safe.model),\n });\n }\n\n async describeImage(\n image: string | Buffer,\n prompt?: string,\n options: ImageDescriptionOptions = {},\n ): Promise<string> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'bifrost',\n options.model || this.options.defaultModel,\n );\n return super.describeImage(image, prompt, {\n ...safe,\n model: await this.resolveModel('vision', safe.model),\n });\n }\n\n async embed(\n text: string | string[],\n options: EmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n return super.embed(text, {\n ...options,\n model: await this.resolveModel('embeddings', options.model),\n });\n }\n\n async embedImage(\n image: string | Buffer,\n options: ImageEmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n return super.embedImage(image, {\n ...options,\n model: await this.resolveModel('embeddings', options.model),\n });\n }\n\n async generateImage(\n prompt: string,\n options: ImageGenerationOptions = {},\n ): Promise<ImageGenerationResponse> {\n const safe = normalizeImageGenerationOptions(\n this.options,\n options,\n 'bifrost',\n options.model,\n );\n return super.generateImage(prompt, {\n ...safe,\n model: await this.resolveModel('image_generation', safe.model),\n });\n }\n}\n"],"mappings":";;;;;AAgCA,IAAM,uBAAuC;CAC3C,MAAM;CACN,YAAY;CACZ,YAAY;CACZ,WAAW;CACX,WAAW;CACX,QAAQ;CACR,YAAY;CACZ,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,KAAK;CACL,cAAc;CACd,aAAa;CACb,kBAAkB;CAClB,qBAAqB;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;AAEA,SAAS,iBAAiB,SAA0B;CAClD,OAAO,SAAS,KAAK,OAAO;AAC9B;AAEA,SAAS,sBAAsB,SAA0B;CACvD,OAAO,8DAA8D,KACnE,OACF;AACF;AAEA,SAAS,uBAAuB,SAA0B;CACxD,OAAO,sFAAsF,KAC3F,OACF;AACF;AA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G;GACH,OAAO,MAAM,KAAK,aAAa,cAAc,QAAQ,KAAK;EAC5D,CAAC;CACH;CAEA,MAAM,WACJ,OACA,UAAiC,CAAC,GACN;EAC5B,OAAO,MAAM,WAAW,OAAO;GAC7B,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,cAAc,QAAQ,KAAK;EAC5D,CAAC;CACH;CAEA,MAAM,cACJ,QACA,UAAkC,CAAC,GACD;EAClC,MAAM,OAAO,gCACX,KAAK,SACL,SACA,WACA,QAAQ,KACV;EACA,OAAO,MAAM,cAAc,QAAQ;GACjC,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,oBAAoB,KAAK,KAAK;EAC/D,CAAC;CACH;AACF"}
@@ -1,8 +1,12 @@
1
1
  import { c as normalizeImageGenerationOptions, s as normalizeChatOptions } from "./usage-BaQKo8bc.js";
2
- import { d as OpenAIProvider } from "./src-B_NKcxc9.js";
2
+ import { d as OpenAIProvider } from "./src-nB7u5Xl0.js";
3
3
  import { a as LiteLLMAdmin, n as isSpeechModel, r as isTranscriptionModel, s as resolveGatewayAdminBaseUrl, t as isAudioModel } from "./gateway-audio-models-BSZGgjd8.js";
4
4
  import { ValidationError } from "@happyvertical/utils";
5
5
  //#region src/shared/providers/litellm.ts
6
+ /** Chat Completions has effort, not a generic reasoning budget/thoughts envelope. */
7
+ function assertChatReasoningControls(options) {
8
+ if (options.reasoning?.maxTokens !== void 0 || options.reasoning?.includeThoughts !== void 0 || options.includeThoughts !== void 0) throw new ValidationError("LiteLLM Chat Completions does not support generic reasoning.maxTokens or includeThoughts controls; use reasoning.effort and an output token limit", { provider: "litellm" });
9
+ }
6
10
  var LITELLM_CAPABILITIES = {
7
11
  chat: true,
8
12
  completion: true,
@@ -143,6 +147,7 @@ var LiteLLMProvider = class extends OpenAIProvider {
143
147
  return model.id;
144
148
  }
145
149
  async chat(messages, options = {}) {
150
+ assertChatReasoningControls(options);
146
151
  const safe = normalizeChatOptions(this.options, options, "litellm", options.model || this.options.defaultModel);
147
152
  return super.chat(messages, {
148
153
  ...safe,
@@ -150,6 +155,7 @@ var LiteLLMProvider = class extends OpenAIProvider {
150
155
  });
151
156
  }
152
157
  async *stream(messages, options = {}) {
158
+ assertChatReasoningControls(options);
153
159
  const safe = normalizeChatOptions(this.options, options, "litellm", options.model || this.options.defaultModel);
154
160
  yield* super.stream(messages, {
155
161
  ...safe,
@@ -157,9 +163,11 @@ var LiteLLMProvider = class extends OpenAIProvider {
157
163
  });
158
164
  }
159
165
  async describeImage(image, prompt, options = {}) {
166
+ assertChatReasoningControls(options);
160
167
  const safe = normalizeChatOptions(this.options, options, "litellm", options.model || this.options.defaultModel);
161
168
  return super.describeImage(image, prompt, {
162
169
  ...safe,
170
+ reasoning: options.reasoning,
163
171
  model: await this.resolveModel("vision", safe.model)
164
172
  });
165
173
  }
@@ -186,4 +194,4 @@ var LiteLLMProvider = class extends OpenAIProvider {
186
194
  //#endregion
187
195
  export { LiteLLMProvider };
188
196
 
189
- //# sourceMappingURL=litellm-2ryTH2Ki.js.map
197
+ //# sourceMappingURL=litellm-rMCXClTb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"litellm-rMCXClTb.js","names":[],"sources":["../../src/shared/providers/litellm.ts"],"sourcesContent":["import { ValidationError } from '@happyvertical/utils';\n\nimport {\n normalizeChatOptions,\n normalizeImageGenerationOptions,\n} from '../safety';\nimport type {\n AICapabilities,\n AIMessage,\n AIModel,\n AIResponse,\n ChatOptions,\n EmbeddingOptions,\n EmbeddingResponse,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n LiteLLMOptions,\n} from '../types';\nimport { LiteLLMAdmin, resolveGatewayAdminBaseUrl } from './gateway-admin';\nimport {\n isAudioModel,\n isSpeechModel,\n isTranscriptionModel,\n} from './gateway-audio-models';\nimport { type OpenAICompatibleProfile, OpenAIProvider } from './openai';\n\n/** Chat Completions has effort, not a generic reasoning budget/thoughts envelope. */\nfunction assertChatReasoningControls(\n options: Pick<ChatOptions, 'reasoning' | 'includeThoughts'>,\n): void {\n if (\n options.reasoning?.maxTokens !== undefined ||\n options.reasoning?.includeThoughts !== undefined ||\n options.includeThoughts !== undefined\n ) {\n throw new ValidationError(\n 'LiteLLM Chat Completions does not support generic reasoning.maxTokens or includeThoughts controls; use reasoning.effort and an output token limit',\n { provider: 'litellm' },\n );\n }\n}\n\nconst LITELLM_CAPABILITIES: AICapabilities = {\n chat: true,\n completion: true,\n embeddings: true,\n streaming: true,\n functions: true,\n vision: true,\n fineTuning: false,\n imageEmbeddings: true,\n imageGeneration: true,\n videoGeneration: false,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 128000,\n supportedOperations: [\n 'chat',\n 'completion',\n 'embedding',\n 'streaming',\n 'functions',\n 'vision',\n 'image_embedding',\n 'image_generation',\n ],\n};\n\nfunction isEmbeddingModel(modelId: string): boolean {\n return /embed/i.test(modelId);\n}\n\nfunction isImageEmbeddingModel(modelId: string): boolean {\n return /titan-embed-image|multimodalembedding|image[-_]?embed|clip/i.test(\n modelId,\n );\n}\n\nfunction isImageGenerationModel(modelId: string): boolean {\n return /gpt-image|dall-e|imagen|stable[-_ ]diffusion|sdxl|flux|titan-image|image-generator/i.test(\n modelId,\n );\n}\n\nfunction isFilteredLiteLLMModel(modelId: string): boolean {\n return /moderation|rerank/i.test(modelId);\n}\n\nfunction inferLiteLLMContextLength(modelId: string): number {\n if (isEmbeddingModel(modelId)) return 8192;\n if (/gemini-1\\.5|gemini-2\\.0|gemini-2\\.5|gemini-3/i.test(modelId)) {\n return 1000000;\n }\n if (/claude/i.test(modelId)) return 200000;\n if (/gpt-4o|gpt-4\\.1|o1|o3|o4|llama|mistral|qwen|deepseek/i.test(modelId)) {\n return 128000;\n }\n return 32768;\n}\n\nfunction inferLiteLLMFunctions(modelId: string): boolean {\n if (isEmbeddingModel(modelId) || isAudioModel(modelId)) return false;\n return /gpt|claude|gemini|command|llama|mistral|qwen|deepseek|o1|o3|o4/i.test(\n modelId,\n );\n}\n\nfunction inferLiteLLMVision(modelId: string): boolean {\n if (isAudioModel(modelId)) return false;\n return /gpt-4o|gpt-4\\.1|vision|claude-3|gemini|pixtral|llava|qwen.*vl|vl-/i.test(\n modelId,\n );\n}\n\nfunction inferLiteLLMCapabilities(modelId: string): string[] {\n if (isTranscriptionModel(modelId)) {\n return ['transcription'];\n }\n\n if (isSpeechModel(modelId)) {\n return ['speech'];\n }\n\n if (isImageGenerationModel(modelId)) {\n return ['image_generation'];\n }\n\n if (isImageEmbeddingModel(modelId)) {\n return ['embeddings', 'image_embedding'];\n }\n\n if (isEmbeddingModel(modelId)) {\n return ['embeddings'];\n }\n\n const capabilities = ['text', 'chat'];\n\n if (inferLiteLLMFunctions(modelId)) {\n capabilities.push('functions');\n }\n\n if (inferLiteLLMVision(modelId)) {\n capabilities.push('vision');\n }\n\n return capabilities;\n}\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n return baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;\n}\n\nfunction ensureLiteLLMOptions(options: LiteLLMOptions): LiteLLMOptions {\n if (!options.baseUrl?.trim()) {\n throw new ValidationError('LiteLLM baseUrl is required', {\n provider: 'litellm',\n hint: 'Pass baseUrl like https://llm.happyvertical.com/v1 or set HAVE_AI_BASE_URL / LITELLM_BASE_URL',\n });\n }\n\n return {\n ...options,\n baseUrl: normalizeBaseUrl(options.baseUrl.trim()),\n };\n}\n\nconst LITELLM_PROFILE: OpenAICompatibleProfile = {\n providerLabel: 'LiteLLM',\n providerName: 'litellm',\n defaultModel: 'gpt-4',\n capabilities: LITELLM_CAPABILITIES,\n describeModel: (modelId) => `LiteLLM model: ${modelId}`,\n getContextLength: inferLiteLLMContextLength,\n getModelCapabilities: inferLiteLLMCapabilities,\n shouldIncludeModel: (modelId) => !isFilteredLiteLLMModel(modelId),\n supportsFunctions: inferLiteLLMFunctions,\n supportsVision: inferLiteLLMVision,\n};\n\ntype LiteLLMResolvedCapability =\n | 'chat'\n | 'vision'\n | 'embeddings'\n | 'image_generation';\n\nfunction supportsCapability(\n model: AIModel,\n capability: LiteLLMResolvedCapability,\n): boolean {\n if (capability === 'vision') {\n return (\n model.capabilities.includes('vision') || model.supportsVision === true\n );\n }\n\n if (capability === 'embeddings') {\n return model.capabilities.includes('embeddings');\n }\n\n if (capability === 'image_generation') {\n return model.capabilities.includes('image_generation');\n }\n\n return model.capabilities.includes('chat');\n}\n\n/**\n * LiteLLM provider implementation.\n *\n * LiteLLM exposes an OpenAI-compatible API surface, so this provider reuses the\n * OpenAI transport while customizing provider identity, model discovery, and\n * capability heuristics for gateway-backed deployments.\n */\nexport class LiteLLMProvider extends OpenAIProvider {\n readonly admin: LiteLLMAdmin;\n private readonly configuredDefaultModel?: string;\n private readonly resolvedModelCache = new Map<\n LiteLLMResolvedCapability,\n Promise<string>\n >();\n\n constructor(options: LiteLLMOptions) {\n const normalized = ensureLiteLLMOptions(options);\n super(normalized, LITELLM_PROFILE);\n this.admin = new LiteLLMAdmin({\n provider: 'litellm',\n baseUrl: resolveGatewayAdminBaseUrl(\n normalized.baseUrl,\n normalized.adminUrl || normalized.adminBaseUrl,\n 'litellm',\n ),\n apiKey: normalized.adminApiKey || normalized.apiKey,\n headers: normalized.adminHeaders,\n timeout: normalized.timeout,\n });\n this.configuredDefaultModel = normalized.defaultModel;\n }\n\n private async resolveModel(\n capability: LiteLLMResolvedCapability,\n explicitModel?: string,\n ): Promise<string> {\n if (explicitModel) {\n return explicitModel;\n }\n\n if (\n this.configuredDefaultModel &&\n (capability === 'chat' || capability === 'vision')\n ) {\n return this.configuredDefaultModel;\n }\n\n const cached = this.resolvedModelCache.get(capability);\n if (cached) {\n return cached;\n }\n\n const pending = this.selectModel(capability).catch((error) => {\n this.resolvedModelCache.delete(capability);\n throw error;\n });\n this.resolvedModelCache.set(capability, pending);\n return pending;\n }\n\n private async selectModel(\n capability: LiteLLMResolvedCapability,\n ): Promise<string> {\n const models = await super.getModels();\n const model = models.find((candidate) =>\n supportsCapability(candidate, capability),\n );\n\n if (!model) {\n throw new ValidationError(\n `No ${capability} model is available from the LiteLLM gateway`,\n {\n provider: 'litellm',\n capability,\n hint: 'Pass defaultModel explicitly or ensure /models returns a compatible model for this key',\n },\n );\n }\n\n return model.id;\n }\n\n async chat(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): Promise<AIResponse> {\n assertChatReasoningControls(options);\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'litellm',\n options.model || this.options.defaultModel,\n );\n return super.chat(messages, {\n ...safe,\n model: await this.resolveModel('chat', safe.model),\n });\n }\n\n async *stream(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): AsyncIterable<string> {\n assertChatReasoningControls(options);\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'litellm',\n options.model || this.options.defaultModel,\n );\n yield* super.stream(messages, {\n ...safe,\n model: await this.resolveModel('chat', safe.model),\n });\n }\n\n async describeImage(\n image: string | Buffer,\n prompt?: string,\n options: ImageDescriptionOptions = {},\n ): Promise<string> {\n assertChatReasoningControls(options);\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'litellm',\n options.model || this.options.defaultModel,\n );\n return super.describeImage(image, prompt, {\n ...safe,\n // The inherited image path calls this.chat(); do not reclassify the\n // normalization-inferred budget as an explicit caller control.\n reasoning: options.reasoning,\n model: await this.resolveModel('vision', safe.model),\n });\n }\n\n async embed(\n text: string | string[],\n options: EmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n return super.embed(text, {\n ...options,\n model: await this.resolveModel('embeddings', options.model),\n });\n }\n\n async embedImage(\n image: string | Buffer,\n options: ImageEmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n return super.embedImage(image, {\n ...options,\n model: await this.resolveModel('embeddings', options.model),\n });\n }\n\n async generateImage(\n prompt: string,\n options: ImageGenerationOptions = {},\n ): Promise<ImageGenerationResponse> {\n const safe = normalizeImageGenerationOptions(\n this.options,\n options,\n 'litellm',\n options.model,\n );\n return super.generateImage(prompt, {\n ...safe,\n model: await this.resolveModel('image_generation', safe.model),\n });\n }\n}\n"],"mappings":";;;;;;AA6BA,SAAS,4BACP,SACM;CACN,IACE,QAAQ,WAAW,cAAc,KAAA,KACjC,QAAQ,WAAW,oBAAoB,KAAA,KACvC,QAAQ,oBAAoB,KAAA,GAE5B,MAAM,IAAI,gBACR,qJACA,EAAE,UAAU,UAAU,CACxB;AAEJ;AAEA,IAAM,uBAAuC;CAC3C,MAAM;CACN,YAAY;CACZ,YAAY;CACZ,WAAW;CACX,WAAW;CACX,QAAQ;CACR,YAAY;CACZ,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,KAAK;CACL,cAAc;CACd,aAAa;CACb,kBAAkB;CAClB,qBAAqB;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;AAEA,SAAS,iBAAiB,SAA0B;CAClD,OAAO,SAAS,KAAK,OAAO;AAC9B;AAEA,SAAS,sBAAsB,SAA0B;CACvD,OAAO,8DAA8D,KACnE,OACF;AACF;AAEA,SAAS,uBAAuB,SAA0B;CACxD,OAAO,sFAAsF,KAC3F,OACF;AACF;AAEA,SAAS,uBAAuB,SAA0B;CACxD,OAAO,qBAAqB,KAAK,OAAO;AAC1C;AAEA,SAAS,0BAA0B,SAAyB;CAC1D,IAAI,iBAAiB,OAAO,GAAG,OAAO;CACtC,IAAI,gDAAgD,KAAK,OAAO,GAC9D,OAAO;CAET,IAAI,UAAU,KAAK,OAAO,GAAG,OAAO;CACpC,IAAI,wDAAwD,KAAK,OAAO,GACtE,OAAO;CAET,OAAO;AACT;AAEA,SAAS,sBAAsB,SAA0B;CACvD,IAAI,iBAAiB,OAAO,KAAK,aAAa,OAAO,GAAG,OAAO;CAC/D,OAAO,kEAAkE,KACvE,OACF;AACF;AAEA,SAAS,mBAAmB,SAA0B;CACpD,IAAI,aAAa,OAAO,GAAG,OAAO;CAClC,OAAO,qEAAqE,KAC1E,OACF;AACF;AAEA,SAAS,yBAAyB,SAA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OAAO;EACnC,MAAM,OAAO,qBACX,KAAK,SACL,SACA,WACA,QAAQ,SAAS,KAAK,QAAQ,YAChC;EACA,OAAO,MAAM,OAAO,UAAU;GAC5B,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,QAAQ,KAAK,KAAK;EACnD,CAAC;CACH;CAEA,MAAM,cACJ,OACA,QACA,UAAmC,CAAC,GACnB;EACjB,4BAA4B,OAAO;EACnC,MAAM,OAAO,qBACX,KAAK,SACL,SACA,WACA,QAAQ,SAAS,KAAK,QAAQ,YAChC;EACA,OAAO,MAAM,cAAc,OAAO,QAAQ;GACxC,GAAG;GAGH,WAAW,QAAQ;GACnB,OAAO,MAAM,KAAK,aAAa,UAAU,KAAK,KAAK;EACrD,CAAC;CACH;CAEA,MAAM,MACJ,MACA,UAA4B,CAAC,GACD;EAC5B,OAAO,MAAM,MAAM,MAAM;GACvB,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,cAAc,QAAQ,KAAK;EAC5D,CAAC;CACH;CAEA,MAAM,WACJ,OACA,UAAiC,CAAC,GACN;EAC5B,OAAO,MAAM,WAAW,OAAO;GAC7B,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,cAAc,QAAQ,KAAK;EAC5D,CAAC;CACH;CAEA,MAAM,cACJ,QACA,UAAkC,CAAC,GACD;EAClC,MAAM,OAAO,gCACX,KAAK,SACL,SACA,WACA,QAAQ,KACV;EACA,OAAO,MAAM,cAAc,QAAQ;GACjC,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,oBAAoB,KAAK,KAAK;EAC/D,CAAC;CACH;AACF"}
@@ -214,7 +214,8 @@ var OpenAIProvider = class {
214
214
  seed: options.seed,
215
215
  stream: false
216
216
  };
217
- if ((this.profile.providerName === "bifrost" || this.profile.providerName === "litellm") && (options.reasoning?.maxTokens || 0) > 0) request.reasoning = {
217
+ if ((this.profile.providerName === "openai" || this.profile.providerName === "litellm") && options.reasoning?.effort !== void 0) request.reasoning_effort = options.reasoning.effort;
218
+ if (this.profile.providerName === "bifrost" && (options.reasoning?.effort !== void 0 || (options.reasoning?.maxTokens || 0) > 0)) request.reasoning = {
218
219
  effort: options.reasoning?.effort,
219
220
  max_tokens: options.reasoning?.maxTokens,
220
221
  include_thoughts: options.reasoning?.includeThoughts
@@ -567,7 +568,8 @@ var OpenAIProvider = class {
567
568
  user: options.user,
568
569
  stream: true
569
570
  };
570
- if ((this.profile.providerName === "bifrost" || this.profile.providerName === "litellm") && (options.reasoning?.maxTokens || 0) > 0) request.reasoning = {
571
+ if ((this.profile.providerName === "openai" || this.profile.providerName === "litellm") && options.reasoning?.effort !== void 0) request.reasoning_effort = options.reasoning.effort;
572
+ if (this.profile.providerName === "bifrost" && (options.reasoning?.effort !== void 0 || (options.reasoning?.maxTokens || 0) > 0)) request.reasoning = {
571
573
  effort: options.reasoning?.effort,
572
574
  max_tokens: options.reasoning?.maxTokens,
573
575
  include_thoughts: options.reasoning?.includeThoughts
@@ -1209,10 +1211,10 @@ async function getAI(options = {}) {
1209
1211
  const { OpenAIProvider } = await Promise.resolve().then(() => openai_exports);
1210
1212
  client = new OpenAIProvider(options);
1211
1213
  } else if (isLiteLLMOptions(options)) {
1212
- const { LiteLLMProvider } = await import("./litellm-2ryTH2Ki.js");
1214
+ const { LiteLLMProvider } = await import("./litellm-rMCXClTb.js");
1213
1215
  client = new LiteLLMProvider(options);
1214
1216
  } else if (isBifrostOptions(options)) {
1215
- const { BifrostProvider } = await import("./bifrost-C9MAwEDS.js");
1217
+ const { BifrostProvider } = await import("./bifrost-BXiXdyb8.js");
1216
1218
  client = new BifrostProvider(options);
1217
1219
  } else if (isOllamaOptions(options)) {
1218
1220
  const { OllamaProvider } = await import("./ollama--y88p8Bz.js");
@@ -1522,4 +1524,4 @@ var PACKAGE_VERSION_INITIALIZED = true;
1522
1524
  //#endregion
1523
1525
  export { getAI as a, OpenAIClient as c, OpenAIProvider as d, factory_exports as i, getAIClient as l, AIThread as n, getAIAuto as o, AIMessage as r, AIClient as s, PACKAGE_VERSION_INITIALIZED as t, getOpenAI as u };
1524
1526
 
1525
- //# sourceMappingURL=src-B_NKcxc9.js.map
1527
+ //# sourceMappingURL=src-nB7u5Xl0.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-nB7u5Xl0.js","names":[],"sources":["../../src/shared/providers/openai.ts","../../src/shared/client.ts","../../src/shared/factory.ts","../../src/shared/message.ts","../../src/shared/thread.ts","../../src/index.ts"],"sourcesContent":["/**\n * OpenAI provider implementation\n *\n * Provides a standardized interface for interacting with OpenAI's GPT models,\n * including chat completions, text completions, embeddings, and streaming responses.\n * Supports all major OpenAI features including function calling, vision models,\n * and custom fine-tuned models.\n */\n\nimport OpenAI from 'openai';\nimport { rateLimitErrorFrom } from '../rate-limit';\nimport {\n normalizeBaseAIOptions,\n normalizeChatOptions,\n normalizeImageGenerationOptions,\n type PreparedRequestControls,\n prepareRequestControls,\n} from '../safety';\nimport type {\n AICapabilities,\n AIInterface,\n AIMessage,\n AIModel,\n AIResponse,\n BaseAIOptions,\n ChatOptions,\n CompletionOptions,\n ContentPart,\n EmbeddingOptions,\n EmbeddingResponse,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n MessageOptions,\n TokenUsage,\n TTSOptions,\n TTSResponse,\n VideoGenerationJob,\n VideoGenerationOptions,\n VideoGenerationResult,\n VideoGenerationStatusResult,\n Voice,\n VoiceCloneOptions,\n VoiceDesignOptions,\n VoiceListOptions,\n} from '../types';\nimport {\n AIError,\n AuthenticationError,\n ContentFilterError,\n ContextLengthError,\n ModelNotFoundError,\n} from '../types';\nimport { emitUsage } from './usage';\n\n/**\n * Determines whether a model uses OpenAI's newer reasoning-model request\n * shape: `max_completion_tokens` in place of `max_tokens`, and no\n * `temperature` parameter at all (a non-default `temperature` is rejected\n * with a 400 error).\n *\n * This applies to the `gpt-5` and `gpt-6` families (`gpt-5`, `gpt-5-mini`,\n * `gpt-6-astra`, and future `gpt-5*` / `gpt-6*` variants) and the o-series\n * reasoning models (`o1`,\n * `o3`, `o4`, and their variants such as `o1-mini`, `o3-mini`, `o4-mini`).\n * See OpenAI's reasoning models guide and the Chat Completions API\n * reference for `max_completion_tokens`:\n * https://platform.openai.com/docs/guides/reasoning\n * https://platform.openai.com/docs/api-reference/chat/create\n *\n * The match is a conservative prefix/family check so future `gpt-5*`,\n * `gpt-6*`, and `o1`/`o3`/`o4` variants are covered without needing an\n * allowlist update.\n * Models outside these families (`gpt-4.x`, `gpt-3.5`, etc.) are unaffected\n * and keep sending `max_tokens` and `temperature` as before.\n *\n * Gateway providers (`BifrostProvider`, some `LiteLLMProvider` deployments)\n * route with a vendor-prefixed model id, e.g. `openai/gpt-5-mini` — see\n * `BifrostProvider`'s own `defaultModel: 'openai/gpt-4o-mini'` convention in\n * `bifrost.ts`. Only the final path segment is matched against the family\n * checks so those gateway-routed ids are recognized the same as bare\n * `gpt-5-mini` or `gpt-6-astra` IDs.\n *\n * Internal request-shaping helper: exported at module level only so it can\n * be unit-tested directly. It is not re-exported from the package entry\n * point (`src/index.ts`) and is not part of the package's public API.\n *\n * @param model - The model identifier (e.g. `gpt-6-astra`, `openai/gpt-5-mini`, `gpt-4.1-mini`)\n * @returns `true` when the model requires `max_completion_tokens` and rejects `temperature`\n */\nexport function usesCompletionTokenLimit(model: string | undefined): boolean {\n if (!model) return false;\n const normalized = model.toLowerCase();\n const lastSegment = normalized.slice(normalized.lastIndexOf('/') + 1);\n return /^gpt-[56]/.test(lastSegment) || /^o[134](-|$)/.test(lastSegment);\n}\n\n/**\n * Builds the output-token-limit and temperature fields for a chat/completion\n * request body, shaped for the given model per {@link usesCompletionTokenLimit}.\n *\n * For models that require it: sends `max_completion_tokens` and omits\n * `max_tokens`, and omits `temperature` entirely (never sends a default\n * value in its place). For all other models: sends `max_tokens` and\n * `temperature` unchanged. Fields whose source value is `undefined` are\n * omitted rather than included as `undefined` keys.\n *\n * Internal request-shaping helper: exported at module level only so it can\n * be unit-tested directly. It is not re-exported from the package entry\n * point (`src/index.ts`) and is not part of the package's public API.\n */\nexport function buildTokenLimitRequestFields(\n model: string,\n maxTokens: number | undefined,\n temperature: number | undefined,\n): {\n max_tokens?: number;\n max_completion_tokens?: number;\n temperature?: number;\n} {\n if (usesCompletionTokenLimit(model)) {\n return maxTokens === undefined ? {} : { max_completion_tokens: maxTokens };\n }\n return {\n ...(maxTokens === undefined ? {} : { max_tokens: maxTokens }),\n ...(temperature === undefined ? {} : { temperature }),\n };\n}\n\n/**\n * Shared profile for OpenAI-compatible providers\n */\nexport interface OpenAICompatibleProfile {\n providerLabel: string;\n providerName: string;\n defaultModel: string;\n capabilities: AICapabilities;\n describeModel(modelId: string): string;\n getContextLength(modelId: string): number;\n getModelCapabilities(modelId: string): string[];\n shouldIncludeModel(modelId: string): boolean;\n supportsFunctions(modelId: string): boolean;\n supportsVision(modelId: string): boolean;\n}\n\nconst OPENAI_PROFILE: OpenAICompatibleProfile = {\n providerLabel: 'OpenAI',\n providerName: 'openai',\n defaultModel: 'gpt-4o',\n capabilities: {\n chat: true,\n completion: true,\n embeddings: true,\n streaming: true,\n functions: true,\n vision: true,\n fineTuning: true,\n imageEmbeddings: true,\n imageGeneration: true,\n videoGeneration: false,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 128000,\n supportedOperations: [\n 'chat',\n 'completion',\n 'embedding',\n 'streaming',\n 'functions',\n 'vision',\n 'image_embedding',\n 'image_generation',\n ],\n },\n describeModel: (modelId) => `OpenAI model: ${modelId}`,\n getContextLength(modelId) {\n if (modelId.includes('gpt-4o')) return 128000;\n if (modelId.includes('gpt-4.1')) return 128000;\n if (modelId.includes('gpt-4-turbo')) return 128000;\n if (modelId.includes('gpt-4')) return 8192;\n if (modelId.includes('gpt-3.5-turbo')) return 16385;\n if (modelId.includes('text-embedding')) return 8192;\n return 4096;\n },\n getModelCapabilities(modelId) {\n const capabilities = ['text'];\n if (modelId.includes('gpt')) {\n capabilities.push('chat', 'functions');\n }\n if (\n modelId.includes('vision') ||\n modelId === 'gpt-4o' ||\n modelId.includes('gpt-4.1')\n ) {\n capabilities.push('vision');\n }\n if (modelId.includes('embedding')) {\n capabilities.push('embeddings');\n }\n return capabilities;\n },\n shouldIncludeModel(modelId) {\n return modelId.includes('gpt') || modelId.includes('text-embedding');\n },\n supportsFunctions(modelId) {\n return modelId.includes('gpt-4') || modelId.includes('gpt-3.5');\n },\n supportsVision(modelId) {\n return (\n modelId.includes('vision') ||\n modelId === 'gpt-4o' ||\n modelId.includes('gpt-4.1')\n );\n },\n};\n\nexport interface OpenAICompatibleOptions extends BaseAIOptions {\n type?: string;\n apiKey?: string;\n baseUrl?: string;\n organization?: string;\n}\n\n/**\n * OpenAI provider implementation that handles all interactions with OpenAI's API.\n * Supports GPT models, embeddings, function calling, streaming, and vision capabilities.\n */\nexport class OpenAIProvider implements AIInterface {\n private client: OpenAI;\n protected options: OpenAICompatibleOptions;\n protected readonly profile: OpenAICompatibleProfile;\n\n /**\n * Creates a new OpenAI provider instance\n * @param options - Configuration options for the OpenAI provider\n */\n constructor(\n options: OpenAICompatibleOptions,\n profile: OpenAICompatibleProfile = OPENAI_PROFILE,\n ) {\n this.profile = profile;\n this.options = normalizeBaseAIOptions({\n defaultModel: this.profile.defaultModel,\n ...options,\n });\n\n this.client = new OpenAI({\n apiKey: this.options.apiKey,\n baseURL: this.options.baseUrl,\n organization: this.options.organization,\n timeout: this.options.timeout,\n maxRetries: this.options.maxRetries,\n defaultHeaders: this.options.headers,\n });\n }\n\n /**\n * Generate a chat completion using OpenAI's chat models\n * @param messages - Array of conversation messages\n * @param options - Optional configuration for the chat completion\n * @returns Promise resolving to the AI response with content and metadata\n * @throws {AIError} When the API request fails or returns invalid data\n *\n * @example\n * ```typescript\n * const response = await provider.chat([\n * { role: 'system', content: 'You are a helpful assistant.' },\n * { role: 'user', content: 'What is the capital of France?' }\n * ], {\n * model: 'gpt-4o',\n * temperature: 0.7,\n * maxTokens: 150\n * });\n * console.log(response.content); // \"Paris is the capital of France.\"\n * ```\n */\n async chat(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): Promise<AIResponse> {\n const startTime = Date.now();\n let controls: PreparedRequestControls | undefined;\n try {\n const model =\n options.model || this.options.defaultModel || this.profile.defaultModel;\n options = normalizeChatOptions(\n this.options,\n options,\n this.profile.providerName,\n model,\n );\n controls = prepareRequestControls(this.options, options);\n const request = {\n model,\n messages: this.mapMessagesToOpenAI(messages),\n ...buildTokenLimitRequestFields(\n model,\n options.maxTokens,\n options.temperature,\n ),\n top_p: options.topP,\n n: options.n,\n stop: options.stop,\n frequency_penalty: options.frequencyPenalty,\n presence_penalty: options.presencePenalty,\n user: options.user,\n tools: options.tools?.map((tool) => ({\n type: 'function' as const,\n function: {\n name: tool.function.name,\n description: tool.function.description,\n parameters: tool.function.parameters,\n },\n })),\n // OpenAI rejects tool_choice without tools (a tool loop's final,\n // tool-less round still says toolChoice: 'none').\n tool_choice: options.tools?.length\n ? this.mapToolChoice(options.toolChoice)\n : undefined,\n response_format: options.responseFormat,\n seed: options.seed,\n stream: false,\n } as OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming & {\n reasoning?: {\n effort?: string;\n max_tokens?: number;\n include_thoughts?: boolean;\n };\n };\n if (\n (this.profile.providerName === 'openai' ||\n this.profile.providerName === 'litellm') &&\n options.reasoning?.effort !== undefined\n ) {\n request.reasoning_effort = options.reasoning.effort;\n }\n if (\n this.profile.providerName === 'bifrost' &&\n (options.reasoning?.effort !== undefined ||\n (options.reasoning?.maxTokens || 0) > 0)\n ) {\n request.reasoning = {\n effort: options.reasoning?.effort,\n max_tokens: options.reasoning?.maxTokens,\n include_thoughts: options.reasoning?.includeThoughts,\n };\n }\n const response = await this.client.chat.completions.create(request, {\n signal: controls.signal,\n timeout: controls.timeout,\n });\n\n const choice = response.choices[0];\n if (!choice) {\n throw new AIError(\n `No choices returned from ${this.profile.providerLabel}`,\n 'NO_CHOICES',\n this.profile.providerName,\n );\n }\n\n const usage = this.mapUsage(response.usage);\n emitUsage(\n this.options,\n this.profile.providerName,\n 'chat',\n response.model || model,\n usage,\n startTime,\n options.usageTags,\n );\n\n return {\n content: choice.message.content || '',\n usage,\n model: response.model,\n finishReason: this.mapFinishReason(choice.finish_reason),\n toolCalls: choice.message.tool_calls\n ?.filter((call) => call.type === 'function')\n .map((call) => ({\n id: call.id,\n type: 'function' as const,\n function: {\n name: call.function.name,\n arguments: call.function.arguments,\n },\n })),\n };\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n this.profile.providerName,\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n this.profile.providerName,\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n /**\n * Generate a text completion for a given prompt\n * @param prompt - The text prompt to complete\n * @param options - Optional configuration for the completion\n * @returns Promise resolving to the AI response\n * @throws {AIError} When the API request fails\n *\n * @example\n * ```typescript\n * const response = await provider.complete('The weather today is', {\n * model: 'gpt-4o',\n * maxTokens: 50,\n * temperature: 0.5\n * });\n * ```\n */\n async complete(\n prompt: string,\n options: CompletionOptions = {},\n ): Promise<AIResponse> {\n return this.chat([{ role: 'user', content: prompt }], {\n model: options.model,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n n: options.n,\n stop: options.stop,\n stream: options.stream,\n onProgress: options.onProgress,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n continueOnLength: options.continueOnLength,\n });\n }\n\n /**\n * Simple message interface for single-turn interactions with optional history\n *\n * @param text - The message text to send\n * @param options - Configuration options including history, model, etc.\n * @returns Promise resolving to the response content string\n *\n * @example\n * ```typescript\n * // Simple usage\n * const response = await provider.message('Hello!');\n *\n * // With options\n * const response = await provider.message('Analyze this', {\n * model: 'gpt-4o',\n * responseFormat: { type: 'json_object' }\n * });\n *\n * // With history\n * const response = await provider.message('What was my question?', {\n * history: [\n * { role: 'user', content: 'What is 2+2?' },\n * { role: 'assistant', content: '4' }\n * ]\n * });\n * ```\n */\n async message(text: string, options: MessageOptions = {}): Promise<string> {\n // Build messages array from history + current message\n const messages: AIMessage[] = [\n ...(options.history || []),\n { role: options.role || 'user', content: text },\n ];\n\n const response = await this.chat(messages, {\n model: options.model,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n stop: options.stop,\n stream: options.stream,\n frequencyPenalty: options.frequencyPenalty,\n presencePenalty: options.presencePenalty,\n responseFormat: options.responseFormat,\n seed: options.seed,\n tools: options.tools,\n toolChoice: options.toolChoice,\n onProgress: options.onProgress,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n continueOnLength: options.continueOnLength,\n });\n\n return response.content;\n }\n\n /**\n * Generate embeddings for the given text(s)\n * @param text - Single text string or array of texts to embed\n * @param options - Optional configuration for embeddings\n * @returns Promise resolving to embeddings response with vector arrays\n * @throws {AIError} When the API request fails\n *\n * @example\n * ```typescript\n * // Single text embedding\n * const response1 = await provider.embed('Hello world');\n * console.log(response1.embeddings[0]); // Array of numbers\n *\n * // Multiple text embeddings\n * const response2 = await provider.embed(['Text 1', 'Text 2']);\n * console.log(response2.embeddings.length); // 2\n * ```\n */\n async embed(\n text: string | string[],\n options: EmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n const startTime = Date.now();\n try {\n const model = options.model || 'text-embedding-3-small';\n const input = Array.isArray(text) ? text : [text];\n const response = await this.client.embeddings.create({\n model,\n input,\n encoding_format: options.encodingFormat,\n dimensions: options.dimensions,\n user: options.user,\n });\n\n const usage = this.mapUsage(response.usage);\n emitUsage(\n this.options,\n this.profile.providerName,\n 'embed',\n response.model || model,\n usage,\n startTime,\n options.usageTags,\n );\n\n return {\n embeddings: response.data.map((item) => item.embedding),\n usage,\n model: response.model,\n };\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Convert an image to a base64 data URL\n * @param image - Image as URL, base64 data URL, or Buffer\n * @returns base64 data URL string\n * @private\n */\n private async imageToBase64(\n image: string | Buffer,\n signal?: AbortSignal,\n ): Promise<string> {\n if (Buffer.isBuffer(image)) {\n return `data:image/png;base64,${image.toString('base64')}`;\n }\n if (image.startsWith('data:')) {\n return image; // Already base64 data URL\n }\n // It's a URL - fetch and convert\n const response = await fetch(image, { signal });\n if (!response.ok) {\n throw new AIError(\n `Failed to fetch image: ${response.status} ${response.statusText}`,\n 'IMAGE_FETCH_ERROR',\n this.profile.providerName,\n );\n }\n const arrayBuffer = await response.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n const contentType = response.headers.get('content-type') || 'image/png';\n return `data:${contentType};base64,${buffer.toString('base64')}`;\n }\n\n /**\n * Generate a text description of an image\n * @param image - Image as URL, base64 data URL, or Buffer\n * @param prompt - Custom prompt for description (optional)\n * @param options - Optional configuration\n * @returns Promise resolving to the description string\n *\n * @example\n * ```typescript\n * const description = await provider.describeImage('https://example.com/image.jpg');\n * ```\n */\n async describeImage(\n image: string | Buffer,\n prompt?: string,\n options: ImageDescriptionOptions = {},\n ): Promise<string> {\n let controls: PreparedRequestControls | undefined;\n try {\n const defaultPrompt =\n 'Describe this image for a search index. Include objects, mood, lighting, and any visible text.';\n\n controls = prepareRequestControls(this.options, options);\n const imageUrl = await this.imageToBase64(image, controls.signal);\n\n const response = await this.chat(\n [\n {\n role: 'user',\n content: [\n { type: 'text', text: prompt || defaultPrompt },\n {\n type: 'image_url',\n image_url: {\n url: imageUrl,\n detail: options.detail || 'auto',\n },\n },\n ],\n },\n ],\n {\n model:\n options.model ||\n this.options.defaultModel ||\n this.profile.defaultModel,\n maxTokens: options.maxTokens ?? 500,\n signal: controls.signal,\n timeout: controls.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n },\n );\n\n return response.content;\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n this.profile.providerName,\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n this.profile.providerName,\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n /**\n * Generate embeddings for an image using describe-then-embed pattern\n * @param image - Image as URL, base64 data URL, or Buffer\n * @param options - Optional configuration for image embeddings\n * @returns Promise resolving to embeddings response\n *\n * @example\n * ```typescript\n * const embedding = await provider.embedImage('https://example.com/image.jpg');\n * ```\n */\n async embedImage(\n image: string | Buffer,\n options: ImageEmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n try {\n // OpenAI doesn't have native image embeddings - use describe-then-embed\n const description = await this.describeImage(\n image,\n 'Describe this image in detail for semantic embedding. Include all visible objects, colors, textures, composition, text, people, actions, and overall scene context.',\n );\n\n return this.embed(description, {\n model: options.model || 'text-embedding-3-small',\n dimensions: options.dimensions,\n user: options.user,\n });\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Generate an image from a text prompt using DALL-E\n * @param prompt - Text description of the image to generate\n * @param options - Optional configuration for image generation\n * @returns Promise resolving to generated image(s)\n *\n * @example\n * ```typescript\n * const result = await provider.generateImage('A sunset over mountains');\n * fs.writeFileSync('image.png', result.images[0].data);\n * ```\n */\n async generateImage(\n prompt: string,\n options: ImageGenerationOptions = {},\n ): Promise<ImageGenerationResponse> {\n let controls: PreparedRequestControls | undefined;\n try {\n const model = options.model || 'dall-e-3';\n options = normalizeImageGenerationOptions(\n this.options,\n options,\n this.profile.providerName,\n model,\n );\n controls = prepareRequestControls(this.options, options);\n\n const requestParams: OpenAI.Images.ImageGenerateParams = {\n model,\n prompt,\n n: model === 'dall-e-3' ? 1 : options.n,\n size:\n (options.size as OpenAI.Images.ImageGenerateParams['size']) ||\n '1024x1024',\n response_format: options.outputFormat === 'url' ? 'url' : 'b64_json',\n };\n\n if (model === 'dall-e-3') {\n if (options.style) {\n requestParams.style = options.style;\n }\n if (options.quality) {\n requestParams.quality =\n options.quality as OpenAI.Images.ImageGenerateParams['quality'];\n }\n }\n\n const response = await this.client.images.generate(requestParams, {\n signal: controls.signal,\n timeout: controls.timeout,\n });\n\n const images = (response.data || []).map((item) => {\n let data: Buffer | string;\n const mimeType = 'image/png';\n\n if (options.outputFormat === 'url') {\n data = item.url || '';\n } else if (options.outputFormat === 'base64') {\n data = item.b64_json || '';\n } else {\n // Default: buffer\n data = Buffer.from(item.b64_json || '', 'base64');\n }\n\n return {\n data,\n mimeType,\n revisedPrompt: item.revised_prompt,\n };\n });\n\n return {\n images,\n model,\n };\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n this.profile.providerName,\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n this.profile.providerName,\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n // ============================================================================\n // Video Generation Methods (Not supported - use gemini, byteplus-modelark,\n // or openai-compat-video provider)\n // ============================================================================\n\n async submitVideoGenerationJob(\n _options: VideoGenerationOptions,\n ): Promise<VideoGenerationJob> {\n throw new AIError(\n `Video generation is not supported by ${this.profile.providerLabel} provider. Use gemini, byteplus-modelark, or openai-compat-video provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async getVideoGenerationJob(\n _handle: VideoGenerationJob,\n ): Promise<VideoGenerationStatusResult> {\n throw new AIError(\n `Video generation is not supported by ${this.profile.providerLabel} provider. Use gemini, byteplus-modelark, or openai-compat-video provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async fetchVideoGenerationResult(\n _handle: VideoGenerationJob,\n ): Promise<VideoGenerationResult> {\n throw new AIError(\n `Video generation is not supported by ${this.profile.providerLabel} provider. Use gemini, byteplus-modelark, or openai-compat-video provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async cancelVideoGenerationJob(_handle: VideoGenerationJob): Promise<void> {\n throw new AIError(\n `Video generation is not supported by ${this.profile.providerLabel} provider. Use gemini, byteplus-modelark, or openai-compat-video provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async validateVideoGenerationAccess(): Promise<boolean> {\n throw new AIError(\n `Video generation is not supported by ${this.profile.providerLabel} provider. Use gemini, byteplus-modelark, or openai-compat-video provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n /**\n * Stream a chat completion response in real-time\n * @param messages - Array of conversation messages\n * @param options - Optional configuration for the chat completion\n * @yields Individual content chunks as they arrive\n * @throws {AIError} When the streaming request fails\n *\n * @example\n * ```typescript\n * for await (const chunk of provider.stream([\n * { role: 'user', content: 'Write a story about AI' }\n * ])) {\n * process.stdout.write(chunk);\n * }\n * ```\n */\n async *stream(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): AsyncIterable<string> {\n const startTime = Date.now();\n let controls: PreparedRequestControls | undefined;\n try {\n const model =\n options.model || this.options.defaultModel || this.profile.defaultModel;\n options = normalizeChatOptions(\n this.options,\n options,\n this.profile.providerName,\n model,\n );\n controls = prepareRequestControls(this.options, options);\n const request = {\n model,\n messages: this.mapMessagesToOpenAI(messages),\n ...buildTokenLimitRequestFields(\n model,\n options.maxTokens,\n options.temperature,\n ),\n top_p: options.topP,\n stop: options.stop,\n frequency_penalty: options.frequencyPenalty,\n presence_penalty: options.presencePenalty,\n user: options.user,\n stream: true,\n } as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming & {\n reasoning?: {\n effort?: string;\n max_tokens?: number;\n include_thoughts?: boolean;\n };\n };\n if (\n (this.profile.providerName === 'openai' ||\n this.profile.providerName === 'litellm') &&\n options.reasoning?.effort !== undefined\n ) {\n request.reasoning_effort = options.reasoning.effort;\n }\n if (\n this.profile.providerName === 'bifrost' &&\n (options.reasoning?.effort !== undefined ||\n (options.reasoning?.maxTokens || 0) > 0)\n ) {\n request.reasoning = {\n effort: options.reasoning?.effort,\n max_tokens: options.reasoning?.maxTokens,\n include_thoughts: options.reasoning?.includeThoughts,\n };\n }\n const stream = await this.client.chat.completions.create(request, {\n signal: controls.signal,\n timeout: controls.timeout,\n });\n\n let streamFinish: string | null = null;\n for await (const chunk of stream) {\n streamFinish = chunk.choices[0]?.finish_reason ?? streamFinish;\n const content = chunk.choices[0]?.delta?.content;\n if (content) {\n if (options.onProgress) {\n options.onProgress(content);\n }\n yield content;\n }\n }\n options.onFinishReason?.(this.mapFinishReason(streamFinish) ?? 'stop');\n\n emitUsage(\n this.options,\n this.profile.providerName,\n 'stream',\n model,\n undefined,\n startTime,\n options.usageTags,\n );\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n this.profile.providerName,\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n this.profile.providerName,\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n /**\n * Count the number of tokens in the given text\n * @param text - The text to count tokens for\n * @returns Promise resolving to the estimated token count\n *\n * @remarks\n * OpenAI doesn't provide a direct token counting API, so this is an approximation\n * based on the general rule of ~4 characters per token. For precise counting,\n * consider using a dedicated tokenizer library.\n *\n * @example\n * ```typescript\n * const count = await provider.countTokens('Hello, world!');\n * console.log(count); // Approximately 4 tokens\n * ```\n */\n async countTokens(text: string): Promise<number> {\n // OpenAI doesn't provide a direct token counting API\n // This is an approximation based on the general rule of ~4 characters per token\n return Math.ceil(text.length / 4);\n }\n\n /**\n * Get a list of available OpenAI models\n * @returns Promise resolving to an array of model information\n * @throws {AIError} When the API request fails\n *\n * @example\n * ```typescript\n * const models = await provider.getModels();\n * const gptModels = models.filter(m => m.id.includes('gpt'));\n * ```\n */\n async getModels(): Promise<AIModel[]> {\n try {\n const response = await this.client.models.list();\n return response.data\n .filter((model) => this.profile.shouldIncludeModel(model.id))\n .map((model) => ({\n id: model.id,\n name: model.id,\n description: this.profile.describeModel(model.id),\n contextLength: this.profile.getContextLength(model.id),\n capabilities: this.profile.getModelCapabilities(model.id),\n supportsFunctions: this.profile.supportsFunctions(model.id),\n supportsVision: this.profile.supportsVision(model.id),\n }));\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Get the capabilities supported by this OpenAI provider\n * @returns Promise resolving to provider capabilities\n *\n * @example\n * ```typescript\n * const caps = await provider.getCapabilities();\n * if (caps.functions) {\n * // Provider supports function calling\n * }\n * ```\n */\n async getCapabilities(): Promise<AICapabilities> {\n return { ...this.profile.capabilities };\n }\n\n // ============================================================================\n // TTS Methods (Not supported - use Qwen3-TTS provider)\n // ============================================================================\n\n async synthesizeSpeech(\n _text: string,\n _options?: TTSOptions,\n ): Promise<TTSResponse> {\n throw new AIError(\n `TTS is not supported by ${this.profile.providerLabel} provider. Use Qwen3-TTS provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n streamSpeech(_text: string, _options?: TTSOptions): AsyncIterable<Buffer> {\n const error = new AIError(\n `TTS streaming is not supported by ${this.profile.providerLabel} provider. Use Qwen3-TTS provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n return {\n [Symbol.asyncIterator]: () => ({\n next: () => Promise.reject(error),\n }),\n };\n }\n\n async cloneVoice(_options: VoiceCloneOptions): Promise<Voice> {\n throw new AIError(\n `Voice cloning is not supported by ${this.profile.providerLabel} provider. Use Qwen3-TTS provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async designVoice(_options: VoiceDesignOptions): Promise<Voice> {\n throw new AIError(\n `Voice design is not supported by ${this.profile.providerLabel} provider. Use Qwen3-TTS provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async getVoices(_options?: VoiceListOptions): Promise<Voice[]> {\n throw new AIError(\n `Voice listing is not supported by ${this.profile.providerLabel} provider. Use Qwen3-TTS provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n /**\n * Maps internal AI messages to OpenAI's message format\n * @param messages - Array of internal AI messages\n * @returns Array of OpenAI-compatible message parameters\n * @private\n */\n private mapMessagesToOpenAI(\n messages: AIMessage[],\n ): OpenAI.Chat.ChatCompletionMessageParam[] {\n return messages.map((message) => {\n // Handle content that can be string or ContentPart[]\n let content: string | OpenAI.Chat.ChatCompletionContentPart[];\n\n if (typeof message.content === 'string') {\n content = message.content;\n } else {\n // Array of content parts - map to OpenAI format\n content = message.content.map((part: ContentPart) => {\n if (part.type === 'text') {\n return { type: 'text' as const, text: part.text };\n }\n // Image content part\n return {\n type: 'image_url' as const,\n image_url: {\n url: part.image_url.url,\n detail: part.image_url.detail,\n },\n };\n });\n }\n\n // Build message based on role and content\n const baseMessage = {\n role: message.role as OpenAI.Chat.ChatCompletionRole,\n content,\n };\n\n // Add optional fields based on role and availability\n if (\n message.name &&\n (message.role === 'system' ||\n message.role === 'user' ||\n message.role === 'function')\n ) {\n (baseMessage as any).name = message.name;\n }\n\n if (message.tool_calls && message.role === 'assistant') {\n // Replay only the wire fields; provider-specific extras such as\n // Gemini thought signatures are not part of the OpenAI schema.\n (baseMessage as any).tool_calls = message.tool_calls.map(\n (toolCall) => ({\n id: toolCall.id,\n type: toolCall.type,\n function: {\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n },\n }),\n );\n }\n\n if (message.role === 'tool' && message.tool_call_id) {\n // OpenAI rejects tool results without the id of the call they answer.\n (baseMessage as any).tool_call_id = message.tool_call_id;\n }\n\n return baseMessage as OpenAI.Chat.ChatCompletionMessageParam;\n });\n }\n\n /**\n * Maps internal tool choice format to OpenAI's tool choice format\n * @param toolChoice - Internal tool choice specification\n * @returns OpenAI-compatible tool choice option or undefined\n * @private\n */\n private mapToolChoice(\n toolChoice?:\n | 'auto'\n | 'none'\n | { type: 'function'; function: { name: string } },\n ): OpenAI.Chat.ChatCompletionToolChoiceOption | undefined {\n if (!toolChoice) return undefined;\n if (typeof toolChoice === 'string') return toolChoice;\n return {\n type: 'function',\n function: { name: toolChoice.function.name },\n };\n }\n\n /**\n * Maps OpenAI usage information to internal token usage format\n * @param usage - OpenAI usage object from API response\n * @returns Internal token usage object or undefined\n * @private\n */\n private mapUsage(\n usage?:\n | OpenAI.CompletionUsage\n | OpenAI.Completions.CompletionUsage\n | OpenAI.Embeddings.CreateEmbeddingResponse.Usage,\n ): TokenUsage | undefined {\n if (!usage) return undefined;\n return {\n promptTokens: usage.prompt_tokens || 0,\n completionTokens: (usage as any).completion_tokens || 0,\n totalTokens: usage.total_tokens || 0,\n };\n }\n\n /**\n * Maps OpenAI finish reason to internal finish reason format\n * @param reason - OpenAI finish reason from API response\n * @returns Internal finish reason\n * @private\n */\n private mapFinishReason(reason: string | null): AIResponse['finishReason'] {\n switch (reason) {\n case 'stop':\n return 'stop';\n case 'length':\n return 'length';\n case 'tool_calls':\n return 'tool_calls';\n case 'content_filter':\n return 'content_filter';\n default:\n return 'stop';\n }\n }\n\n /**\n * Gets the context length for a given OpenAI model\n * @param modelId - The OpenAI model identifier\n * @returns Maximum context length in tokens\n * @private\n */\n /**\n * Maps OpenAI API errors to internal AI error types\n * @param error - The error object from OpenAI API\n * @returns Appropriate internal AI error instance\n * @private\n */\n\n private mapError(error: unknown): AIError {\n if (error instanceof OpenAI.APIError) {\n switch (error.status) {\n case 401:\n return new AuthenticationError(this.profile.providerName);\n case 429: {\n return rateLimitErrorFrom(this.profile.providerName, error);\n }\n case 404:\n return new ModelNotFoundError(\n error.message,\n this.profile.providerName,\n );\n case 413:\n return new ContextLengthError(this.profile.providerName);\n default:\n if (error.message.includes('content_filter')) {\n return new ContentFilterError(this.profile.providerName);\n }\n return new AIError(\n error.message,\n 'API_ERROR',\n this.profile.providerName,\n );\n }\n }\n\n if (error instanceof AIError) {\n return error;\n }\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error occurred';\n return new AIError(\n errorMessage,\n 'UNKNOWN_ERROR',\n this.profile.providerName,\n );\n }\n}\n","import { ApiError, ValidationError } from '@happyvertical/utils';\nimport OpenAI from 'openai';\n\nimport type { AIMessageOptions } from './message';\nimport { buildTokenLimitRequestFields } from './providers/openai';\nimport type { AIProviderType, AIRateLimitOptions } from './types';\nimport { AI_PROVIDER_TYPES } from './types';\n\n/**\n * Common options for AI client configuration\n */\nexport interface AIClientOptions {\n /**\n * Type of AI client (e.g., 'openai')\n */\n type?: AIProviderType | string;\n\n /**\n * Response format for AI completions\n */\n responseFormat?: string;\n\n /**\n * API key for authentication\n */\n apiKey?: string;\n\n /**\n * Base URL for API requests\n */\n baseUrl?: string;\n\n /**\n * Admin API key for gateway providers that support provisioning.\n */\n adminApiKey?: string;\n\n /**\n * Admin base URL for gateway providers when it differs from `baseUrl`.\n */\n adminBaseUrl?: string;\n\n /**\n * Alias for adminBaseUrl.\n */\n adminUrl?: string;\n\n /**\n * Admin username for providers that use HTTP Basic auth.\n */\n adminUser?: string;\n\n /**\n * Admin username for providers that use HTTP Basic auth.\n */\n adminUsername?: string;\n\n /**\n * Admin password for providers that use HTTP Basic auth.\n */\n adminPassword?: string;\n\n /**\n * Custom admin headers for gateway providers.\n */\n adminHeaders?: Record<string, string>;\n\n /**\n * Optional shared pacing / retry configuration for getAI().\n */\n rateLimit?: AIRateLimitOptions;\n}\n\n/**\n * Interface defining required methods for AI clients\n */\nexport interface AIClientInterface {\n /**\n * Configuration options for this client\n */\n options: AIClientOptions;\n\n /**\n * Sends a message to the AI and gets a response\n *\n * @param text - Message text\n * @param options - Message options\n * @returns Promise resolving to the AI response\n */\n message(text: string, options: AIMessageOptions): Promise<unknown>;\n\n /**\n * Gets a text completion from the AI\n *\n * @param text - Input text for completion\n * @param options - Completion options\n * @returns Promise resolving to the completion result\n */\n textCompletion(text: string, options: AIMessageOptions): Promise<unknown>;\n}\n\n/**\n * Type guard to check if options are for OpenAI client\n *\n * @param options - Options to check\n * @returns True if options are valid for OpenAI client\n */\nfunction isOpenAIClientOptions(\n options: AIClientOptions,\n): options is OpenAIClientOptions {\n return options.type === 'openai' && 'apiKey' in options && !!options.apiKey;\n}\n\n/**\n * Type guard to check if value is an AI client instance\n *\n * @param value - Value to check\n * @returns True if value is an AI client instance\n */\nfunction isAIClientInstance(value: any): value is AIClient {\n return value instanceof AIClient;\n}\n\n/**\n * Options for AI text completion requests\n */\nexport interface AITextCompletionOptions {\n /**\n * Model identifier to use\n */\n model?: string;\n\n /**\n * Timeout in milliseconds\n */\n timeout?: number;\n\n /**\n * Role of the message sender\n */\n role?: OpenAI.Chat.ChatCompletionRole;\n\n /**\n * Previous messages in the conversation\n */\n history?: OpenAI.Chat.ChatCompletionMessageParam[];\n\n /**\n * Name of the message sender\n */\n name?: string;\n\n /**\n * Penalty for token frequency\n */\n frequencyPenalty?: number;\n\n /**\n * Token bias adjustments\n */\n logitBias?: Record<string, number>;\n\n /**\n * Whether to return log probabilities\n */\n logprobs?: boolean;\n\n /**\n * Number of top log probabilities to return\n */\n topLogprobs?: number;\n\n /**\n * Maximum tokens to generate\n */\n maxTokens?: number;\n\n /**\n * Number of completions to generate\n */\n n?: number;\n\n /**\n * Penalty for token presence\n */\n presencePenalty?: number;\n\n /**\n * Format for the response\n */\n responseFormat?: { type: 'text' | 'json_object' };\n\n /**\n * Random seed for deterministic results\n */\n seed?: number;\n\n /**\n * Sequences that stop generation\n */\n stop?: string | Array<string>;\n\n /**\n * Whether to stream responses\n */\n stream?: boolean;\n\n /**\n * Sampling temperature\n */\n temperature?: number;\n\n /**\n * Top-p sampling parameter\n */\n topProbability?: number;\n\n /**\n * Available tools for the model\n */\n tools?: Array<any>; // todo: figure out generic solution - Array<OpenAI.Chat.ChatCompletionTool>;\n\n /**\n * Tool selection behavior\n */\n toolChoice?:\n | 'none'\n | 'auto'\n | { type: 'function'; function: { name: string } };\n\n /**\n * User identifier\n */\n user?: string;\n\n /**\n * Callback for handling streaming responses\n */\n onProgress?: (partialMessage: string) => void;\n}\n\n/**\n * Base class for AI clients\n * Provides a common interface for different AI service providers\n */\nexport class AIClient {\n /**\n * Configuration options for this client\n */\n public options: AIClientOptions;\n\n /**\n * Creates a new AIClient\n *\n * @param options - Client configuration options\n */\n constructor(options: AIClientOptions) {\n this.options = options;\n }\n\n /**\n * Sends a message to the AI\n * Base implementation returns a placeholder response\n *\n * @param text - Message text\n * @param options - Message options\n * @returns Promise resolving to a placeholder response\n */\n public async message(\n _text: string,\n _options: AITextCompletionOptions = { role: 'user' },\n ) {\n return 'not a real ai message, this is the base class!';\n }\n\n /**\n * Factory method to create appropriate AI client based on options\n *\n * @param options - Client configuration options\n * @returns Promise resolving to an initialized AI client\n * @throws Error if client type is invalid\n */\n public static async create(\n options: AIClientOptions | AIClient,\n ): Promise<AIClient | OpenAIClient> {\n // If an AI client instance is passed, return it directly\n if (isAIClientInstance(options)) {\n return options;\n }\n\n // Cast to options since we know it's not an instance\n const clientOptions = options as AIClientOptions;\n\n if (isOpenAIClientOptions(clientOptions)) {\n return OpenAIClient.create(clientOptions);\n }\n\n // Delegate to modern factory for non-OpenAI providers\n const providedType = (clientOptions as any).type;\n if (providedType && providedType !== 'openai') {\n const { getAI } = await import('./factory.js');\n return (await getAI(clientOptions as any)) as any;\n }\n\n // Provide specific error messages for common issues\n if (providedType === 'openai') {\n throw new ValidationError(\n 'OpenAI API key is required but missing or empty',\n {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType,\n hint: 'Set OPENAI_API_KEY environment variable or pass apiKey in options',\n },\n );\n }\n\n throw new ValidationError('Invalid client type specified', {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType,\n });\n }\n\n /**\n * Gets a text completion from the AI\n * In base class, delegates to message method\n *\n * @param text - Input text for completion\n * @param options - Completion options\n * @returns Promise resolving to the completion result\n */\n public textCompletion(\n text: string,\n options: AITextCompletionOptions = {\n role: 'user',\n },\n ) {\n return this.message(text, options);\n }\n}\n\n/**\n * Creates an OpenAI client instance\n *\n * @param options - OpenAI configuration options\n * @returns Promise resolving to an OpenAI client\n */\nexport async function getOpenAI(options: {\n apiKey?: string;\n baseUrl?: string;\n}) {\n return new OpenAI({\n apiKey: options.apiKey,\n baseURL: options.baseUrl,\n });\n}\n\n/**\n * Options specific to OpenAI text completion requests\n */\nexport interface OpenAITextCompletionOptions {\n /**\n * Model identifier to use\n */\n model?: string;\n\n /**\n * Timeout in milliseconds\n */\n timeout?: number;\n\n /**\n * Role of the message sender\n */\n role?: OpenAI.Chat.ChatCompletionRole;\n\n /**\n * Previous messages in the conversation\n */\n history?: Array<OpenAI.Chat.ChatCompletionMessageParam>;\n\n /**\n * Name of the message sender\n */\n name?: string;\n\n /**\n * Penalty for token frequency\n */\n frequencyPenalty?: number;\n\n /**\n * Token bias adjustments\n */\n logitBias?: Record<string, number>;\n\n /**\n * Whether to return log probabilities\n */\n logprobs?: boolean;\n\n /**\n * Number of top log probabilities to return\n */\n topLogprobs?: number;\n\n /**\n * Maximum tokens to generate\n */\n maxTokens?: number;\n\n /**\n * Number of completions to generate\n */\n n?: number;\n\n /**\n * Penalty for token presence\n */\n presencePenalty?: number;\n\n /**\n * Format for the response\n */\n responseFormat?: { type: 'text' | 'json_object' };\n\n /**\n * Random seed for deterministic results\n */\n seed?: number;\n\n /**\n * Sequences that stop generation\n */\n stop?: string | Array<string>;\n\n /**\n * Whether to stream responses\n */\n stream?: boolean;\n\n /**\n * Sampling temperature\n */\n temperature?: number;\n\n /**\n * Top-p sampling parameter\n */\n topProbability?: number;\n\n /**\n * Available tools for the model\n */\n tools?: Array<OpenAI.Chat.ChatCompletionTool>;\n\n /**\n * Tool selection behavior\n */\n toolChoice?:\n | 'none'\n | 'auto'\n | { type: 'function'; function: { name: string } };\n\n /**\n * User identifier\n */\n user?: string;\n\n /**\n * Callback for handling streaming responses\n */\n onProgress?: (partialMessage: string) => void;\n}\n\n/**\n * Configuration options specific to OpenAI client\n */\nexport interface OpenAIClientOptions extends AIClientOptions {\n /**\n * OpenAI API key\n */\n apiKey?: string;\n\n /**\n * OpenAI API base URL\n */\n baseUrl?: string;\n}\n\n/**\n * Client implementation for the OpenAI API\n */\nexport class OpenAIClient extends AIClient {\n /**\n * OpenAI client instance\n */\n protected openai!: OpenAI;\n\n /**\n * Configuration options for this client\n */\n public options: OpenAIClientOptions;\n\n /**\n * Creates a new OpenAIClient\n *\n * @param options - OpenAI client configuration options\n */\n constructor(options: OpenAIClientOptions) {\n super(options);\n this.options = options;\n }\n\n /**\n * Sends a message to OpenAI\n *\n * @param text - Message text\n * @param options - Message options\n * @returns Promise resolving to the OpenAI response\n */\n public async message(\n text: string,\n options: AIMessageOptions = { role: 'user' },\n ) {\n const response = await this.textCompletion(text, options);\n return response;\n }\n\n /**\n * Factory method to create and initialize an OpenAIClient\n *\n * @param options - OpenAI client configuration options\n * @returns Promise resolving to an initialized OpenAIClient\n */\n public static async create(\n options: OpenAIClientOptions,\n ): Promise<OpenAIClient> {\n const client = new OpenAIClient(options);\n await client.initialize();\n return client;\n }\n\n /**\n * Initializes the OpenAI client\n */\n protected async initialize() {\n this.openai = new OpenAI({\n apiKey: this.options.apiKey,\n baseURL: this.options.baseUrl,\n });\n }\n\n /**\n * Sends a text completion request to the OpenAI API\n *\n * @param message - The message to send\n * @param options - Configuration options for the completion request\n * @returns Promise resolving to the completion text\n * @throws Error if the OpenAI API response is invalid\n */\n public async textCompletion(\n message: string,\n options: OpenAITextCompletionOptions = {},\n ): Promise<string> {\n const {\n model = 'gpt-4o',\n role = 'user',\n history = [],\n name: _name,\n frequencyPenalty = 0,\n logitBias,\n logprobs = false,\n topLogprobs,\n maxTokens,\n n = 1,\n presencePenalty = 0,\n responseFormat,\n seed,\n stop,\n stream: _stream = false,\n temperature = 1,\n topProbability: topP = 1,\n tools,\n toolChoice,\n user,\n onProgress,\n } = options;\n\n const messages = [\n ...history,\n {\n role: role as OpenAI.Chat.ChatCompletionRole,\n content: message,\n } as OpenAI.Chat.ChatCompletionSystemMessageParam,\n ];\n\n if (onProgress) {\n const stream = await this.openai.chat.completions.create({\n model,\n messages,\n stream: true,\n frequency_penalty: frequencyPenalty,\n logit_bias: logitBias,\n logprobs,\n top_logprobs: topLogprobs,\n ...buildTokenLimitRequestFields(model, maxTokens, temperature),\n n,\n presence_penalty: presencePenalty,\n response_format: responseFormat,\n seed,\n stop,\n top_p: topP,\n tools,\n tool_choice: toolChoice,\n user,\n });\n\n let fullContent = '';\n for await (const chunk of stream) {\n const content = chunk.choices[0]?.delta?.content || '';\n fullContent += content;\n onProgress(content);\n }\n\n return fullContent;\n }\n const response = await this.openai.chat.completions.create({\n model,\n messages,\n frequency_penalty: frequencyPenalty,\n logit_bias: logitBias,\n logprobs,\n top_logprobs: topLogprobs,\n ...buildTokenLimitRequestFields(model, maxTokens, temperature),\n n,\n presence_penalty: presencePenalty,\n response_format: responseFormat,\n seed,\n stop,\n stream: false,\n top_p: topP,\n tools,\n tool_choice: toolChoice,\n user,\n });\n\n const choice = response.choices[0];\n if (!choice || !choice.message || !choice.message.content) {\n throw new ApiError('Invalid response from OpenAI API: Missing content', {\n model,\n responseId: response.id,\n choices: response.choices?.length || 0,\n hasChoice: !!choice,\n hasMessage: !!choice?.message,\n hasContent: !!choice?.message?.content,\n });\n }\n return choice.message.content;\n }\n}\n\n/**\n * Options for getting an AI client with type information\n */\ntype GetAIClientOptions = AIClientOptions & {\n type?: AIProviderType;\n};\n\n/**\n * Factory function to create and initialize an appropriate AI client\n * Delegates to the modern getAI() factory for all provider types\n *\n * @param options - Client configuration options\n * @returns Promise resolving to an initialized AI client\n * @throws Error if client type is invalid\n */\nexport async function getAIClient(\n options: GetAIClientOptions,\n): Promise<AIClient> {\n // Delegate to modern factory for all providers\n const { getAI } = await import('./factory.js');\n return (await getAI(options as any)) as any;\n}\n","/**\n * Universal factory functions for creating AI provider instances\n * Works in both browser and Node.js environments\n */\n\nimport { loadEnvConfig, ValidationError } from '@happyvertical/utils';\n\nimport type { AIClientOptions } from './client';\nimport { createContinuingAI } from './continuation';\nimport { createRateLimitedAI } from './rate-limit';\nimport { createObservedAI, normalizeBaseAIOptions } from './safety';\nimport type {\n AIInterface,\n AIProviderType,\n AnthropicOptions,\n BedrockOptions,\n BifrostOptions,\n ByteplusModelArkOptions,\n ClaudeCliOptions,\n GeminiOptions,\n GetAIOptions,\n HuggingFaceOptions,\n LiteLLMOptions,\n OllamaOptions,\n OpenAICompatVideoOptions,\n OpenAIOptions,\n Qwen3TTSOptions,\n SeevioOptions,\n TypeSafeOptions,\n WebLLMOptions,\n} from './types';\nimport { AI_PROVIDER_TYPES } from './types';\n\n/**\n * Type guards for provider options\n */\n\n/**\n * Checks if the options are for OpenAI provider\n * @param options - The AI provider options to check\n * @returns True if options are for OpenAI provider (including default case)\n */\nfunction isOpenAIOptions(\n options: GetAIOptions | AIClientOptions,\n): options is OpenAIOptions {\n return !options.type || options.type === 'openai';\n}\n\n/**\n * Checks if the options are for LiteLLM provider\n * @param options - The AI provider options to check\n * @returns True if options are for LiteLLM provider\n */\nfunction isLiteLLMOptions(\n options: GetAIOptions | AIClientOptions,\n): options is LiteLLMOptions {\n return options.type === 'litellm';\n}\n\n/**\n * Checks if the options are for Bifrost provider\n * @param options - The AI provider options to check\n * @returns True if options are for Bifrost provider\n */\nfunction isBifrostOptions(\n options: GetAIOptions | AIClientOptions,\n): options is BifrostOptions {\n return options.type === 'bifrost';\n}\n\n/**\n * Checks if the options are for Ollama provider\n * @param options - The AI provider options to check\n * @returns True if options are for Ollama provider\n */\nfunction isOllamaOptions(\n options: GetAIOptions | AIClientOptions,\n): options is OllamaOptions {\n return options.type === 'ollama';\n}\n\n/**\n * Checks if the options are for Google Gemini provider\n * @param options - The AI provider options to check\n * @returns True if options are for Gemini provider\n */\nfunction isGeminiOptions(\n options: GetAIOptions | AIClientOptions,\n): options is GeminiOptions {\n return options.type === 'gemini';\n}\n\n/**\n * Checks if the options are for Anthropic Claude provider\n * @param options - The AI provider options to check\n * @returns True if options are for Anthropic provider\n */\nfunction isAnthropicOptions(\n options: GetAIOptions | AIClientOptions,\n): options is AnthropicOptions {\n return options.type === 'anthropic';\n}\n\n/**\n * Checks if the options are for Hugging Face provider\n * @param options - The AI provider options to check\n * @returns True if options are for Hugging Face provider\n */\nfunction isHuggingFaceOptions(\n options: GetAIOptions | AIClientOptions,\n): options is HuggingFaceOptions {\n return options.type === 'huggingface';\n}\n\n/**\n * Checks if the options are for AWS Bedrock provider\n * @param options - The AI provider options to check\n * @returns True if options are for Bedrock provider\n */\nfunction isBedrockOptions(\n options: GetAIOptions | AIClientOptions,\n): options is BedrockOptions {\n return options.type === 'bedrock';\n}\n\n/**\n * Checks if the options are for Claude CLI provider\n * @param options - The AI provider options to check\n * @returns True if options are for Claude CLI provider\n */\nfunction isClaudeCliOptions(\n options: GetAIOptions | AIClientOptions,\n): options is ClaudeCliOptions {\n return options.type === 'claude-cli';\n}\n\n/**\n * Checks if the options are for Qwen3-TTS provider\n * @param options - The AI provider options to check\n * @returns True if options are for Qwen3-TTS provider\n */\nfunction isQwen3TTSOptions(\n options: GetAIOptions | AIClientOptions,\n): options is Qwen3TTSOptions {\n return options.type === 'qwen3-tts';\n}\n\n/**\n * Checks if the options are for the OpenAI-compatible video-generation provider\n * @param options - The AI provider options to check\n * @returns True if options are for the openai-compat-video provider\n */\nfunction isOpenAICompatVideoOptions(\n options: GetAIOptions | AIClientOptions,\n): options is OpenAICompatVideoOptions {\n return options.type === 'openai-compat-video';\n}\n\n/**\n * Checks if the options are for the BytePlus ModelArk (Seedance) provider\n * @param options - The AI provider options to check\n * @returns True if options are for the byteplus-modelark provider\n */\nfunction isByteplusModelArkOptions(\n options: GetAIOptions | AIClientOptions,\n): options is ByteplusModelArkOptions {\n return options.type === 'byteplus-modelark';\n}\n\n/** Checks if options select Seevio's native Seedance task API. */\nfunction isSeevioOptions(\n options: GetAIOptions | AIClientOptions,\n): options is SeevioOptions {\n return options.type === 'seevio';\n}\n\n/** Checks if options select TypeSafe's System One decision API. */\nfunction isTypeSafeOptions(\n options: GetAIOptions | AIClientOptions,\n): options is TypeSafeOptions {\n return options.type === 'typesafe';\n}\n\n/** Checks if options select the in-browser WebLLM provider. */\nfunction isWebLLMOptions(\n options: GetAIOptions | AIClientOptions,\n): options is WebLLMOptions {\n return options.type === 'webllm';\n}\n\n/**\n * Creates an AI provider instance based on the provided options.\n * Universal version that works in both browser and Node.js environments.\n *\n * Supports environment variable configuration using the pattern:\n * - HAVE_AI_PROVIDER → provider type (string)\n * - HAVE_AI_MODEL → defaultModel (string)\n * - HAVE_AI_TIMEOUT → timeout (number)\n * - HAVE_AI_MAX_RETRIES → maxRetries (number)\n * - HAVE_AI_API_KEY → apiKey (string) - fallback if provider-specific key not set\n * - HAVE_AI_BASE_URL → baseUrl (string)\n *\n * User-provided options always take precedence over environment variables.\n *\n * Accepts both GetAIOptions (provider-specific options with literal types)\n * and AIClientOptions (legacy interface with generic string type) for\n * backward compatibility with existing code.\n *\n * @param options - Configuration options for the AI provider. Can be GetAIOptions or AIClientOptions.\n * @returns Promise resolving to an AI provider instance that implements the AIInterface\n * @throws {ValidationError} When the provider type is unsupported or invalid\n *\n * @example\n * ```typescript\n * // Create OpenAI client with explicit options\n * const openai = await getAI({\n * type: 'openai',\n * apiKey: process.env.OPENAI_API_KEY!,\n * defaultModel: 'gpt-4o'\n * });\n *\n * // Or use environment variables (HAVE_AI_PROVIDER=openai, HAVE_AI_API_KEY=sk-...)\n * const client = await getAI({});\n *\n * // Create Anthropic client\n * const anthropic = await getAI({\n * type: 'anthropic',\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * defaultModel: 'claude-3-5-sonnet-20241022'\n * });\n *\n * // Works with AIClientOptions (legacy interface)\n * const clientOptions: AIClientOptions = { type: 'openai', apiKey: '...' };\n * const legacy = await getAI(clientOptions);\n * ```\n */\nexport async function getAI(\n options: GetAIOptions | AIClientOptions = {},\n): Promise<AIInterface> {\n // Load environment variables with user options taking precedence\n options = loadEnvConfig(options as Record<string, any>, {\n packageName: 'ai',\n schema: {\n provider: 'string',\n type: 'string', // Alias for provider\n model: 'string',\n defaultModel: 'string',\n timeout: 'number',\n maxRetries: 'number',\n apiKey: 'string',\n baseUrl: 'string',\n adminApiKey: 'string',\n adminBaseUrl: 'string',\n adminUrl: 'string',\n adminUser: 'string',\n adminUsername: 'string',\n adminPassword: 'string',\n },\n }) as GetAIOptions;\n\n // Normalize 'provider' field to 'type' for consistency\n if ('provider' in options && !options.type) {\n (options as any).type = (options as any).provider;\n }\n\n // Normalize 'model' field to 'defaultModel' for consistency\n if ('model' in options && !options.defaultModel) {\n (options as any).defaultModel = (options as any).model;\n }\n\n options = normalizeBaseAIOptions(options as GetAIOptions);\n\n let client: AIInterface;\n\n if (isOpenAIOptions(options)) {\n const { OpenAIProvider } = await import('./providers/openai.js');\n client = new OpenAIProvider(options);\n } else if (isLiteLLMOptions(options)) {\n const { LiteLLMProvider } = await import('./providers/litellm.js');\n client = new LiteLLMProvider(options);\n } else if (isBifrostOptions(options)) {\n const { BifrostProvider } = await import('./providers/bifrost.js');\n client = new BifrostProvider(options);\n } else if (isOllamaOptions(options)) {\n const { OllamaProvider } = await import('./providers/ollama.js');\n client = new OllamaProvider(options);\n } else if (isGeminiOptions(options)) {\n const { GeminiProvider } = await import('./providers/gemini.js');\n client = new GeminiProvider(options);\n } else if (isAnthropicOptions(options)) {\n const { AnthropicProvider } = await import('./providers/anthropic.js');\n client = new AnthropicProvider(options);\n } else if (isHuggingFaceOptions(options)) {\n const { HuggingFaceProvider } = await import('./providers/huggingface.js');\n client = new HuggingFaceProvider(options);\n } else if (isBedrockOptions(options)) {\n const { BedrockProvider } = await import('./providers/bedrock.js');\n client = new BedrockProvider(options);\n } else if (isClaudeCliOptions(options)) {\n const { ClaudeCliProvider } = await import('./providers/claude-cli.js');\n client = new ClaudeCliProvider(options);\n } else if (isQwen3TTSOptions(options)) {\n const { Qwen3TTSProvider } = await import('./providers/qwen-tts.js');\n client = new Qwen3TTSProvider(options);\n } else if (isOpenAICompatVideoOptions(options)) {\n const { OpenAICompatVideoProvider } = await import(\n './providers/openai-compat-video.js'\n );\n client = new OpenAICompatVideoProvider(options);\n } else if (isByteplusModelArkOptions(options)) {\n const { ByteplusModelArkProvider } = await import(\n './providers/byteplus-modelark.js'\n );\n client = new ByteplusModelArkProvider(options);\n } else if (isSeevioOptions(options)) {\n const { SeevioProvider } = await import('./providers/seevio.js');\n client = new SeevioProvider(options);\n } else if (isTypeSafeOptions(options)) {\n const { TypeSafeProvider } = await import('./providers/typesafe.js');\n client = new TypeSafeProvider(options);\n } else if (isWebLLMOptions(options)) {\n // Lazy: the provider imports its optional peer (@mlc-ai/web-llm) only on\n // first request, so the root entry never loads it.\n const { WebLLMProvider } = await import('./providers/webllm.js');\n client = new WebLLMProvider(options);\n } else {\n throw new ValidationError('Unsupported AI provider type', {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType: (options as any).type,\n });\n }\n\n // Continuation sits outside the rate limiter so each continuation part is\n // paced and retried on its own (a 429 on part N never re-bills parts 1..N-1).\n return createObservedAI(\n createContinuingAI(createRateLimitedAI(client, options), options, client),\n options,\n );\n}\n\n/**\n * Browser-compatible auto-detection of AI provider based on available credentials.\n * Does not rely on process.env, making it suitable for browser environments.\n *\n * @param options - Configuration options that may contain provider-specific credentials\n * @returns Promise resolving to an AI provider instance based on detected credentials\n * @throws {ValidationError} When no provider can be detected from the provided options\n *\n * @example\n * ```typescript\n * // Auto-detect OpenAI from apiKey\n * const client1 = await getAIAuto({\n * apiKey: 'sk-...', // Detected as OpenAI\n * defaultModel: 'gpt-4o'\n * });\n *\n * // Auto-detect Hugging Face from apiToken\n * const client2 = await getAIAuto({\n * apiToken: 'hf_...', // Detected as Hugging Face\n * model: 'microsoft/DialoGPT-medium'\n * });\n *\n * // Auto-detect AWS Bedrock from region and credentials\n * const client3 = await getAIAuto({\n * region: 'us-east-1',\n * credentials: {\n * accessKeyId: 'AKIA...',\n * secretAccessKey: 'xxx'\n * }\n * });\n * ```\n */\nexport async function getAIAuto(\n options: Record<string, any>,\n): Promise<AIInterface> {\n const baseUrl = String((options as any).baseUrl || '');\n const hasKeepAliveOption =\n 'keepAlive' in options && (options as any).keepAlive !== undefined;\n\n // Auto-detect provider based on available credentials\n if (\n /((?:localhost|127\\.0\\.0\\.1)(?::11434)?(?:\\/(?:api|v1))?|ollama(?:\\.com)?(?:\\/(?:api|v1))?)\\/?$/i.test(\n baseUrl,\n ) ||\n hasKeepAliveOption\n ) {\n return getAI({ ...options, type: 'ollama' } as OllamaOptions);\n }\n\n if (options.apiKey && !options.type) {\n // Default to OpenAI if apiKey is provided without explicit type\n return getAI({ ...options, type: 'openai' } as OpenAIOptions);\n }\n\n if (options.apiToken) {\n // Hugging Face uses apiToken\n return getAI({ ...options, type: 'huggingface' } as HuggingFaceOptions);\n }\n\n if (options.region && options.credentials) {\n // AWS Bedrock uses region and explicit credentials\n return getAI({ ...options, type: 'bedrock' } as BedrockOptions);\n }\n\n if (options.projectId || options.anthropicVersion) {\n // Try to detect based on provider-specific options\n if (options.anthropicVersion) {\n return getAI({ ...options, type: 'anthropic' } as AnthropicOptions);\n }\n if (options.projectId) {\n return getAI({ ...options, type: 'gemini' } as GeminiOptions);\n }\n }\n\n throw new ValidationError('Could not auto-detect AI provider from options', {\n hint: 'Please specify a \"type\" field in options or provide provider-specific credentials',\n supportedTypes: [...AI_PROVIDER_TYPES] as AIProviderType[],\n providedOptions: Object.keys(options),\n });\n}\n","import type { AIThread } from './thread';\n\n/**\n * Options for creating AI messages\n */\nexport interface AIMessageOptions {\n /**\n * Role of the message sender\n */\n role?: 'user' | 'assistant' | 'system';\n\n /**\n * Format for the AI response\n */\n responseFormat?: { type: 'text' | 'json_object' };\n}\n\n/**\n * Represents a message in an AI conversation\n */\nexport class AIMessage {\n /**\n * Original options used to create this message\n */\n protected options;\n\n /**\n * Name of the message sender\n */\n public name: string;\n\n /**\n * Content of the message\n */\n public content: string;\n\n /**\n * Role of the message sender in the conversation\n */\n public role: 'user' | 'assistant' | 'system';\n\n /**\n * Creates a new AI message\n *\n * @param options - Message configuration\n * @param options.role - Role of the message sender\n * @param options.content - Content of the message\n * @param options.name - Name of the message sender\n */\n constructor(options: {\n role: 'user' | 'assistant' | 'system';\n content: string;\n name: string;\n }) {\n this.options = options;\n this.role = options.role;\n this.content = options.content;\n this.name = options.name;\n }\n\n /**\n * Factory method to create a new AI message\n *\n * @param options - Message configuration\n * @param options.thread - Thread this message belongs to\n * @param options.role - Role of the message sender\n * @param options.content - Content of the message\n * @param options.name - Name of the message sender\n * @returns Promise resolving to a new AIMessage instance\n */\n static async create(options: {\n thread: AIThread;\n role: 'user' | 'assistant' | 'system';\n content: string;\n name: string;\n }) {\n return new AIMessage(options);\n }\n}\n","import type OpenAI from 'openai';\nimport { AIClient, type AIClientOptions } from './client';\nimport { AIMessage } from './message';\n\n/**\n * Options for creating an AI conversation thread\n */\nexport interface AIThreadOptions {\n /**\n * Options for the AI client to use in this thread\n */\n ai: AIClientOptions;\n}\n\n/**\n * Represents a conversation thread with an AI model\n * Manages messages, references, and conversation state\n */\nexport class AIThread {\n /**\n * AI client instance for this thread\n */\n protected ai!: AIClient;\n\n /**\n * Options used to configure this thread\n */\n protected options: AIThreadOptions;\n\n /**\n * Messages in this conversation thread\n */\n private messages: AIMessage[] = [];\n\n /**\n * Reference materials to include in the conversation context\n */\n private references: { [name: string]: string } = {};\n\n /**\n * Creates a new AI thread\n *\n * @param options - Thread configuration options\n */\n constructor(options: AIThreadOptions) {\n this.options = options;\n }\n\n /**\n * Factory method to create and initialize a new AI thread\n *\n * @param options - Thread configuration options\n * @returns Promise resolving to an initialized AIThread\n */\n static async create(options: AIThreadOptions) {\n const thread = new AIThread(options);\n await thread.initialize();\n return thread; // No need to add system message here, do it in addSystem\n }\n\n /**\n * Initializes the AI client for this thread\n */\n public async initialize() {\n this.ai = await AIClient.create(this.options.ai);\n }\n\n /**\n * Adds a system message to the conversation\n *\n * @param prompt - System message content\n * @returns Promise resolving to the created AIMessage\n */\n public async addSystem(prompt: string) {\n const message = await AIMessage.create({\n thread: this,\n role: 'system',\n name: 'system',\n content: prompt,\n });\n\n this.messages.push(message);\n return message;\n }\n\n /**\n * Adds a message to the conversation\n *\n * @param options - Message options\n * @param options.role - Role of the message sender\n * @param options.name - Optional name of the message sender\n * @param options.content - Content of the message\n * @returns Promise resolving to the created AIMessage\n */\n public async add(options: {\n role: 'user' | 'assistant' | 'system';\n name?: string;\n content: string;\n }) {\n const message = await AIMessage.create({\n thread: this,\n role: options.role,\n name: options.name || options.role, // Default name to role if not provided\n content: options.content,\n });\n\n this.messages.push(message);\n return message;\n }\n\n /**\n * Gets all messages in this thread\n *\n * @returns Array of AIMessage objects\n */\n public get(): AIMessage[] {\n return this.messages;\n }\n\n /**\n * Adds a reference to be included in the conversation context\n *\n * @param name - Name of the reference\n * @param body - Content of the reference\n */\n public addReference(name: string, body: string): void {\n this.references[name] = body;\n }\n\n /**\n * Assembles the conversation history for sending to the AI\n * Properly orders system message, references, and conversation messages\n *\n * @returns Array of message parameters formatted for the OpenAI API\n */\n public assembleHistory(): OpenAI.Chat.ChatCompletionMessageParam[] {\n const history: OpenAI.Chat.ChatCompletionMessageParam[] = [];\n\n // Add system message first\n const systemMessage = this.messages.find((m) => m.role === 'system');\n if (systemMessage) {\n history.push({\n role: systemMessage.role,\n content: systemMessage.content,\n });\n }\n\n // Add references as user messages (before other user/assistant messages)\n for (const name in this.references) {\n history.push({\n role: 'user',\n content: `Reference - ${name}:\\n${this.references[name]}`,\n });\n }\n\n // Add other messages\n this.messages\n .filter((m) => m.role !== 'system')\n .forEach((message) => {\n history.push({ role: message.role, content: message.content });\n });\n\n return history;\n }\n\n /**\n * Sends a prompt to the AI and gets a response\n *\n * @param prompt - Prompt message to send\n * @param options - Options for the AI response\n * @param options.responseFormat - Format for the AI to respond with\n * @returns Promise resolving to the AI response\n */\n public async do(\n prompt: string,\n options: {\n responseFormat?: 'html' | 'text' | 'json';\n } = {\n responseFormat: 'text',\n },\n ) {\n const { responseFormat } = options;\n const history = this.assembleHistory();\n\n // Get completion from AI with assembled history\n const response = await this.ai.textCompletion(prompt, {\n history,\n responseFormat: {\n type: responseFormat === 'json' ? 'json_object' : 'text',\n },\n });\n return response;\n }\n}\n","/**\n * @happyvertical/ai - A standardized interface for AI model interactions\n *\n * This package provides a unified interface for interacting with various AI models.\n * Supports multiple providers: OpenAI, LiteLLM, Ollama, Gemini, Anthropic,\n * Hugging Face, AWS Bedrock, Claude CLI, and Qwen3-TTS.\n *\n * Key components:\n * - getAI() - Factory function for creating AI provider instances\n * - AIInterface - Standardized interface for all AI providers\n * - Provider-specific implementations for each supported service\n */\n\n// Legacy exports for backward compatibility\nexport * from './shared/client';\nexport * from './shared/factory';\nexport { AIMessage as AIMessageClass } from './shared/message';\nexport {\n DEFAULT_AI_GENERATION_LIMITS,\n DEFAULT_AI_MAX_RETRIES,\n DEFAULT_AI_TIMEOUT_MS,\n} from './shared/safety';\nexport * from './shared/thread';\nexport * from './shared/types';\n\n/** @internal */\nexport const PACKAGE_VERSION_INITIALIZED = true;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2FA,SAAgB,yBAAyB,OAAoC;CAC3E,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,aAAa,MAAM,YAAY;CACrC,MAAM,cAAc,WAAW,MAAM,WAAW,YAAY,GAAG,IAAI,CAAC;CACpE,OAAO,YAAY,KAAK,WAAW,KAAK,eAAe,KAAK,WAAW;AACzE;;;;;;;;;;;;;;;AAgBA,SAAgB,6BACd,OACA,WACA,aAKA;CACA,IAAI,yBAAyB,KAAK,GAChC,OAAO,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,uBAAuB,UAAU;CAE3E,OAAO;EACL,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,UAAU;EAC3D,GAAI,gBAAgB,KAAA,IAA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,KAAK;IAAE,MAAM,QAAQ;IAAM,SAAS,QAAQ;GAAQ,CAAC;EAC/D,CAAC;EAEH,OAAO;CACT;;;;;;;;;CAUA,MAAa,GACX,QACA,UAEI,EACF,gBAAgB,OAClB,GACA;EACA,MAAM,EAAE,mBAAmB;EAC3B,MAAM,UAAU,KAAK,gBAAgB;EASrC,OAAO,MANgB,KAAK,GAAG,eAAe,QAAQ;GACpD;GACA,gBAAgB,EACd,MAAM,mBAAmB,SAAS,gBAAgB,OACpD;EACF,CAAC;CAEH;AACF;;;;ACvKA,IAAa,8BAA8B"}
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import { _ as RateLimitError, b as extractTextContent, d as AI_PROVIDER_TYPES, f as AuthenticationError, g as ModelNotFoundError, h as DEFAULT_RATE_LIMIT_MAX_RETRY_DELAY_MS, i as DEFAULT_AI_TIMEOUT_MS, m as ContextLengthError, n as DEFAULT_AI_GENERATION_LIMITS, p as ContentFilterError, r as DEFAULT_AI_MAX_RETRIES, u as AIError, v as WebGPUUnavailableError, x as isRateLimitRetryableSoon, y as WebLLMPeerMissingError } from "./chunks/usage-BaQKo8bc.js";
2
- import { a as getAI, c as OpenAIClient, l as getAIClient, n as AIThread, o as getAIAuto, r as AIMessage, s as AIClient, t as PACKAGE_VERSION_INITIALIZED, u as getOpenAI } from "./chunks/src-B_NKcxc9.js";
2
+ import { a as getAI, c as OpenAIClient, l as getAIClient, n as AIThread, o as getAIAuto, r as AIMessage, s as AIClient, t as PACKAGE_VERSION_INITIALIZED, u as getOpenAI } from "./chunks/src-nB7u5Xl0.js";
3
3
  export { AIClient, AIError, AIMessage as AIMessageClass, AIThread, AI_PROVIDER_TYPES, AuthenticationError, ContentFilterError, ContextLengthError, DEFAULT_AI_GENERATION_LIMITS, DEFAULT_AI_MAX_RETRIES, DEFAULT_AI_TIMEOUT_MS, DEFAULT_RATE_LIMIT_MAX_RETRY_DELAY_MS, ModelNotFoundError, OpenAIClient, PACKAGE_VERSION_INITIALIZED, RateLimitError, WebGPUUnavailableError, WebLLMPeerMissingError, extractTextContent, getAI, getAIAuto, getAIClient, getOpenAI, isRateLimitRetryableSoon };
package/dist/node.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { _ as RateLimitError, b as extractTextContent, d as AI_PROVIDER_TYPES, f as AuthenticationError, g as ModelNotFoundError, h as DEFAULT_RATE_LIMIT_MAX_RETRY_DELAY_MS, i as DEFAULT_AI_TIMEOUT_MS, m as ContextLengthError, n as DEFAULT_AI_GENERATION_LIMITS, p as ContentFilterError, r as DEFAULT_AI_MAX_RETRIES, u as AIError, v as WebGPUUnavailableError, x as isRateLimitRetryableSoon, y as WebLLMPeerMissingError } from "./chunks/usage-BaQKo8bc.js";
2
- import { a as getAI, c as OpenAIClient, l as getAIClient, n as AIThread, r as AIMessage, s as AIClient, t as PACKAGE_VERSION_INITIALIZED, u as getOpenAI } from "./chunks/src-B_NKcxc9.js";
2
+ import { a as getAI, c as OpenAIClient, l as getAIClient, n as AIThread, r as AIMessage, s as AIClient, t as PACKAGE_VERSION_INITIALIZED, u as getOpenAI } from "./chunks/src-nB7u5Xl0.js";
3
3
  import { ValidationError, loadEnvConfig } from "@happyvertical/utils";
4
4
  //#region src/node/factory.ts
5
5
  /**
@@ -99,7 +99,7 @@ async function getAIAuto(options = {}) {
99
99
  return getAI(config);
100
100
  }
101
101
  try {
102
- return await import("./chunks/src-B_NKcxc9.js").then((n) => n.i).then((m) => m.getAIAuto(config));
102
+ return await import("./chunks/src-nB7u5Xl0.js").then((n) => n.i).then((m) => m.getAIAuto(config));
103
103
  } catch (_error) {}
104
104
  const hasLiteLLMSignal = Boolean(process.env.LITELLM_BASE_URL || process.env.LITELLM_API_KEY);
105
105
  if (Boolean(process.env.BIFROST_BASE_URL) && !config.type) return getAI({
@@ -1 +1 @@
1
- {"version":3,"file":"litellm.d.ts","sourceRoot":"","sources":["../../../src/shared/providers/litellm.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAEV,SAAS,E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CAAC;IAsGxB;;;;;;;;;;;;;;;OAeG;IACG,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAMhD;;;;;;;;;;OAUG;IACG,SAAS,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;IAmBrC;;;;;;;;;;;OAWG;IACG,eAAe,IAAI,OAAO,CAAC,cAAc,CAAC;IAQ1C,gBAAgB,CACpB,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,UAAU,GACpB,OAAO,CAAC,WAAW,CAAC;IAQvB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC;IAanE,UAAU,CAAC,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAAC,KAAK,CAAC;IAQvD,WAAW,CAAC,QAAQ,EAAE,kBAAkB,GAAG,OAAO,CAAC,KAAK,CAAC;IAQzD,SAAS,CAAC,QAAQ,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC;IAQ9D;;;;;OAKG;IACH,OAAO,CAAC,mBAAmB;IAkE3B;;;;;OAKG;IACH,OAAO,CAAC,aAAa;IAcrB;;;;;OAKG;IACH,OAAO,CAAC,QAAQ;IAchB;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAevB;;;;;OAKG;IACH;;;;;OAKG;IAEH,OAAO,CAAC,QAAQ;CAuCjB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/ai",
3
- "version": "0.102.6",
3
+ "version": "0.102.8",
4
4
  "description": "Standardized AI interface supporting chat, embeddings, media, and TypeSafe/Jev typed decisions",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -47,7 +47,7 @@
47
47
  "@anthropic-ai/sdk": "0.90.0",
48
48
  "@aws-sdk/client-bedrock-runtime": "3.1034.0",
49
49
  "@google/genai": "1.50.1",
50
- "@happyvertical/utils": "0.102.6",
50
+ "@happyvertical/utils": "0.102.8",
51
51
  "openai": "6.34.0"
52
52
  },
53
53
  "devDependencies": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"litellm-2ryTH2Ki.js","names":[],"sources":["../../src/shared/providers/litellm.ts"],"sourcesContent":["import { ValidationError } from '@happyvertical/utils';\n\nimport {\n normalizeChatOptions,\n normalizeImageGenerationOptions,\n} from '../safety';\nimport type {\n AICapabilities,\n AIMessage,\n AIModel,\n AIResponse,\n ChatOptions,\n EmbeddingOptions,\n EmbeddingResponse,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n LiteLLMOptions,\n} from '../types';\nimport { LiteLLMAdmin, resolveGatewayAdminBaseUrl } from './gateway-admin';\nimport {\n isAudioModel,\n isSpeechModel,\n isTranscriptionModel,\n} from './gateway-audio-models';\nimport { type OpenAICompatibleProfile, OpenAIProvider } from './openai';\n\nconst LITELLM_CAPABILITIES: AICapabilities = {\n chat: true,\n completion: true,\n embeddings: true,\n streaming: true,\n functions: true,\n vision: true,\n fineTuning: false,\n imageEmbeddings: true,\n imageGeneration: true,\n videoGeneration: false,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 128000,\n supportedOperations: [\n 'chat',\n 'completion',\n 'embedding',\n 'streaming',\n 'functions',\n 'vision',\n 'image_embedding',\n 'image_generation',\n ],\n};\n\nfunction isEmbeddingModel(modelId: string): boolean {\n return /embed/i.test(modelId);\n}\n\nfunction isImageEmbeddingModel(modelId: string): boolean {\n return /titan-embed-image|multimodalembedding|image[-_]?embed|clip/i.test(\n modelId,\n );\n}\n\nfunction isImageGenerationModel(modelId: string): boolean {\n return /gpt-image|dall-e|imagen|stable[-_ ]diffusion|sdxl|flux|titan-image|image-generator/i.test(\n modelId,\n );\n}\n\nfunction isFilteredLiteLLMModel(modelId: string): boolean {\n return /moderation|rerank/i.test(modelId);\n}\n\nfunction inferLiteLLMContextLength(modelId: string): number {\n if (isEmbeddingModel(modelId)) return 8192;\n if (/gemini-1\\.5|gemini-2\\.0|gemini-2\\.5|gemini-3/i.test(modelId)) {\n return 1000000;\n }\n if (/claude/i.test(modelId)) return 200000;\n if (/gpt-4o|gpt-4\\.1|o1|o3|o4|llama|mistral|qwen|deepseek/i.test(modelId)) {\n return 128000;\n }\n return 32768;\n}\n\nfunction inferLiteLLMFunctions(modelId: string): boolean {\n if (isEmbeddingModel(modelId) || isAudioModel(modelId)) return false;\n return /gpt|claude|gemini|command|llama|mistral|qwen|deepseek|o1|o3|o4/i.test(\n modelId,\n );\n}\n\nfunction inferLiteLLMVision(modelId: string): boolean {\n if (isAudioModel(modelId)) return false;\n return /gpt-4o|gpt-4\\.1|vision|claude-3|gemini|pixtral|llava|qwen.*vl|vl-/i.test(\n modelId,\n );\n}\n\nfunction inferLiteLLMCapabilities(modelId: string): string[] {\n if (isTranscriptionModel(modelId)) {\n return ['transcription'];\n }\n\n if (isSpeechModel(modelId)) {\n return ['speech'];\n }\n\n if (isImageGenerationModel(modelId)) {\n return ['image_generation'];\n }\n\n if (isImageEmbeddingModel(modelId)) {\n return ['embeddings', 'image_embedding'];\n }\n\n if (isEmbeddingModel(modelId)) {\n return ['embeddings'];\n }\n\n const capabilities = ['text', 'chat'];\n\n if (inferLiteLLMFunctions(modelId)) {\n capabilities.push('functions');\n }\n\n if (inferLiteLLMVision(modelId)) {\n capabilities.push('vision');\n }\n\n return capabilities;\n}\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n return baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;\n}\n\nfunction ensureLiteLLMOptions(options: LiteLLMOptions): LiteLLMOptions {\n if (!options.baseUrl?.trim()) {\n throw new ValidationError('LiteLLM baseUrl is required', {\n provider: 'litellm',\n hint: 'Pass baseUrl like https://llm.happyvertical.com/v1 or set HAVE_AI_BASE_URL / LITELLM_BASE_URL',\n });\n }\n\n return {\n ...options,\n baseUrl: normalizeBaseUrl(options.baseUrl.trim()),\n };\n}\n\nconst LITELLM_PROFILE: OpenAICompatibleProfile = {\n providerLabel: 'LiteLLM',\n providerName: 'litellm',\n defaultModel: 'gpt-4',\n capabilities: LITELLM_CAPABILITIES,\n describeModel: (modelId) => `LiteLLM model: ${modelId}`,\n getContextLength: inferLiteLLMContextLength,\n getModelCapabilities: inferLiteLLMCapabilities,\n shouldIncludeModel: (modelId) => !isFilteredLiteLLMModel(modelId),\n supportsFunctions: inferLiteLLMFunctions,\n supportsVision: inferLiteLLMVision,\n};\n\ntype LiteLLMResolvedCapability =\n | 'chat'\n | 'vision'\n | 'embeddings'\n | 'image_generation';\n\nfunction supportsCapability(\n model: AIModel,\n capability: LiteLLMResolvedCapability,\n): boolean {\n if (capability === 'vision') {\n return (\n model.capabilities.includes('vision') || model.supportsVision === true\n );\n }\n\n if (capability === 'embeddings') {\n return model.capabilities.includes('embeddings');\n }\n\n if (capability === 'image_generation') {\n return model.capabilities.includes('image_generation');\n }\n\n return model.capabilities.includes('chat');\n}\n\n/**\n * LiteLLM provider implementation.\n *\n * LiteLLM exposes an OpenAI-compatible API surface, so this provider reuses the\n * OpenAI transport while customizing provider identity, model discovery, and\n * capability heuristics for gateway-backed deployments.\n */\nexport class LiteLLMProvider extends OpenAIProvider {\n readonly admin: LiteLLMAdmin;\n private readonly configuredDefaultModel?: string;\n private readonly resolvedModelCache = new Map<\n LiteLLMResolvedCapability,\n Promise<string>\n >();\n\n constructor(options: LiteLLMOptions) {\n const normalized = ensureLiteLLMOptions(options);\n super(normalized, LITELLM_PROFILE);\n this.admin = new LiteLLMAdmin({\n provider: 'litellm',\n baseUrl: resolveGatewayAdminBaseUrl(\n normalized.baseUrl,\n normalized.adminUrl || normalized.adminBaseUrl,\n 'litellm',\n ),\n apiKey: normalized.adminApiKey || normalized.apiKey,\n headers: normalized.adminHeaders,\n timeout: normalized.timeout,\n });\n this.configuredDefaultModel = normalized.defaultModel;\n }\n\n private async resolveModel(\n capability: LiteLLMResolvedCapability,\n explicitModel?: string,\n ): Promise<string> {\n if (explicitModel) {\n return explicitModel;\n }\n\n if (\n this.configuredDefaultModel &&\n (capability === 'chat' || capability === 'vision')\n ) {\n return this.configuredDefaultModel;\n }\n\n const cached = this.resolvedModelCache.get(capability);\n if (cached) {\n return cached;\n }\n\n const pending = this.selectModel(capability).catch((error) => {\n this.resolvedModelCache.delete(capability);\n throw error;\n });\n this.resolvedModelCache.set(capability, pending);\n return pending;\n }\n\n private async selectModel(\n capability: LiteLLMResolvedCapability,\n ): Promise<string> {\n const models = await super.getModels();\n const model = models.find((candidate) =>\n supportsCapability(candidate, capability),\n );\n\n if (!model) {\n throw new ValidationError(\n `No ${capability} model is available from the LiteLLM gateway`,\n {\n provider: 'litellm',\n capability,\n hint: 'Pass defaultModel explicitly or ensure /models returns a compatible model for this key',\n },\n );\n }\n\n return model.id;\n }\n\n async chat(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): Promise<AIResponse> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'litellm',\n options.model || this.options.defaultModel,\n );\n return super.chat(messages, {\n ...safe,\n model: await this.resolveModel('chat', safe.model),\n });\n }\n\n async *stream(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): AsyncIterable<string> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'litellm',\n options.model || this.options.defaultModel,\n );\n yield* super.stream(messages, {\n ...safe,\n model: await this.resolveModel('chat', safe.model),\n });\n }\n\n async describeImage(\n image: string | Buffer,\n prompt?: string,\n options: ImageDescriptionOptions = {},\n ): Promise<string> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'litellm',\n options.model || this.options.defaultModel,\n );\n return super.describeImage(image, prompt, {\n ...safe,\n model: await this.resolveModel('vision', safe.model),\n });\n }\n\n async embed(\n text: string | string[],\n options: EmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n return super.embed(text, {\n ...options,\n model: await this.resolveModel('embeddings', options.model),\n });\n }\n\n async embedImage(\n image: string | Buffer,\n options: ImageEmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n return super.embedImage(image, {\n ...options,\n model: await this.resolveModel('embeddings', options.model),\n });\n }\n\n async generateImage(\n prompt: string,\n options: ImageGenerationOptions = {},\n ): Promise<ImageGenerationResponse> {\n const safe = normalizeImageGenerationOptions(\n this.options,\n options,\n 'litellm',\n options.model,\n );\n return super.generateImage(prompt, {\n ...safe,\n model: await this.resolveModel('image_generation', safe.model),\n });\n }\n}\n"],"mappings":";;;;;AA4BA,IAAM,uBAAuC;CAC3C,MAAM;CACN,YAAY;CACZ,YAAY;CACZ,WAAW;CACX,WAAW;CACX,QAAQ;CACR,YAAY;CACZ,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,KAAK;CACL,cAAc;CACd,aAAa;CACb,kBAAkB;CAClB,qBAAqB;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;AAEA,SAAS,iBAAiB,SAA0B;CAClD,OAAO,SAAS,KAAK,OAAO;AAC9B;AAEA,SAAS,sBAAsB,SAA0B;CACvD,OAAO,8DAA8D,KACnE,OACF;AACF;AAEA,SAAS,uBAAuB,SAA0B;CACxD,OAAO,sFAAsF,KAC3F,OACF;AACF;AAEA,SAAS,uBAAuB,SAA0B;CACxD,OAAO,qBAAqB,KAAK,OAAO;AAC1C;AAEA,SAAS,0BAA0B,SAAyB;CAC1D,IAAI,iBAAiB,OAAO,GAAG,OAAO;CACtC,IAAI,gDAAgD,KAAK,OAAO,GAC9D,OAAO;CAET,IAAI,UAAU,KAAK,OAAO,GAAG,OAAO;CACpC,IAAI,wDAAwD,KAAK,OAAO,GACtE,OAAO;CAET,OAAO;AACT;AAEA,SAAS,sBAAsB,SAA0B;CACvD,IAAI,iBAAiB,OAAO,KAAK,aAAa,OAAO,GAAG,OAAO;CAC/D,OAAO,kEAAkE,KACvE,OACF;AACF;AAEA,SAAS,mBAAmB,SAA0B;CACpD,IAAI,aAAa,OAAO,GAAG,OAAO;CAClC,OAAO,qEAAqE,KAC1E,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ACvB,MAAM,OAAO,qBACX,KAAK,SACL,SACA,WACA,QAAQ,SAAS,KAAK,QAAQ,YAChC;EACA,OAAO,MAAM,OAAO,UAAU;GAC5B,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,QAAQ,KAAK,KAAK;EACnD,CAAC;CACH;CAEA,MAAM,cACJ,OACA,QACA,UAAmC,CAAC,GACnB;EACjB,MAAM,OAAO,qBACX,KAAK,SACL,SACA,WACA,QAAQ,SAAS,KAAK,QAAQ,YAChC;EACA,OAAO,MAAM,cAAc,OAAO,QAAQ;GACxC,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,UAAU,KAAK,KAAK;EACrD,CAAC;CACH;CAEA,MAAM,MACJ,MACA,UAA4B,CAAC,GACD;EAC5B,OAAO,MAAM,MAAM,MAAM;GACvB,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,cAAc,QAAQ,KAAK;EAC5D,CAAC;CACH;CAEA,MAAM,WACJ,OACA,UAAiC,CAAC,GACN;EAC5B,OAAO,MAAM,WAAW,OAAO;GAC7B,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,cAAc,QAAQ,KAAK;EAC5D,CAAC;CACH;CAEA,MAAM,cACJ,QACA,UAAkC,CAAC,GACD;EAClC,MAAM,OAAO,gCACX,KAAK,SACL,SACA,WACA,QAAQ,KACV;EACA,OAAO,MAAM,cAAc,QAAQ;GACjC,GAAG;GACH,OAAO,MAAM,KAAK,aAAa,oBAAoB,KAAK,KAAK;EAC/D,CAAC;CACH;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-B_NKcxc9.js","names":[],"sources":["../../src/shared/providers/openai.ts","../../src/shared/client.ts","../../src/shared/factory.ts","../../src/shared/message.ts","../../src/shared/thread.ts","../../src/index.ts"],"sourcesContent":["/**\n * OpenAI provider implementation\n *\n * Provides a standardized interface for interacting with OpenAI's GPT models,\n * including chat completions, text completions, embeddings, and streaming responses.\n * Supports all major OpenAI features including function calling, vision models,\n * and custom fine-tuned models.\n */\n\nimport OpenAI from 'openai';\nimport { rateLimitErrorFrom } from '../rate-limit';\nimport {\n normalizeBaseAIOptions,\n normalizeChatOptions,\n normalizeImageGenerationOptions,\n type PreparedRequestControls,\n prepareRequestControls,\n} from '../safety';\nimport type {\n AICapabilities,\n AIInterface,\n AIMessage,\n AIModel,\n AIResponse,\n BaseAIOptions,\n ChatOptions,\n CompletionOptions,\n ContentPart,\n EmbeddingOptions,\n EmbeddingResponse,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n MessageOptions,\n TokenUsage,\n TTSOptions,\n TTSResponse,\n VideoGenerationJob,\n VideoGenerationOptions,\n VideoGenerationResult,\n VideoGenerationStatusResult,\n Voice,\n VoiceCloneOptions,\n VoiceDesignOptions,\n VoiceListOptions,\n} from '../types';\nimport {\n AIError,\n AuthenticationError,\n ContentFilterError,\n ContextLengthError,\n ModelNotFoundError,\n} from '../types';\nimport { emitUsage } from './usage';\n\n/**\n * Determines whether a model uses OpenAI's newer reasoning-model request\n * shape: `max_completion_tokens` in place of `max_tokens`, and no\n * `temperature` parameter at all (a non-default `temperature` is rejected\n * with a 400 error).\n *\n * This applies to the `gpt-5` and `gpt-6` families (`gpt-5`, `gpt-5-mini`,\n * `gpt-6-astra`, and future `gpt-5*` / `gpt-6*` variants) and the o-series\n * reasoning models (`o1`,\n * `o3`, `o4`, and their variants such as `o1-mini`, `o3-mini`, `o4-mini`).\n * See OpenAI's reasoning models guide and the Chat Completions API\n * reference for `max_completion_tokens`:\n * https://platform.openai.com/docs/guides/reasoning\n * https://platform.openai.com/docs/api-reference/chat/create\n *\n * The match is a conservative prefix/family check so future `gpt-5*`,\n * `gpt-6*`, and `o1`/`o3`/`o4` variants are covered without needing an\n * allowlist update.\n * Models outside these families (`gpt-4.x`, `gpt-3.5`, etc.) are unaffected\n * and keep sending `max_tokens` and `temperature` as before.\n *\n * Gateway providers (`BifrostProvider`, some `LiteLLMProvider` deployments)\n * route with a vendor-prefixed model id, e.g. `openai/gpt-5-mini` — see\n * `BifrostProvider`'s own `defaultModel: 'openai/gpt-4o-mini'` convention in\n * `bifrost.ts`. Only the final path segment is matched against the family\n * checks so those gateway-routed ids are recognized the same as bare\n * `gpt-5-mini` or `gpt-6-astra` IDs.\n *\n * Internal request-shaping helper: exported at module level only so it can\n * be unit-tested directly. It is not re-exported from the package entry\n * point (`src/index.ts`) and is not part of the package's public API.\n *\n * @param model - The model identifier (e.g. `gpt-6-astra`, `openai/gpt-5-mini`, `gpt-4.1-mini`)\n * @returns `true` when the model requires `max_completion_tokens` and rejects `temperature`\n */\nexport function usesCompletionTokenLimit(model: string | undefined): boolean {\n if (!model) return false;\n const normalized = model.toLowerCase();\n const lastSegment = normalized.slice(normalized.lastIndexOf('/') + 1);\n return /^gpt-[56]/.test(lastSegment) || /^o[134](-|$)/.test(lastSegment);\n}\n\n/**\n * Builds the output-token-limit and temperature fields for a chat/completion\n * request body, shaped for the given model per {@link usesCompletionTokenLimit}.\n *\n * For models that require it: sends `max_completion_tokens` and omits\n * `max_tokens`, and omits `temperature` entirely (never sends a default\n * value in its place). For all other models: sends `max_tokens` and\n * `temperature` unchanged. Fields whose source value is `undefined` are\n * omitted rather than included as `undefined` keys.\n *\n * Internal request-shaping helper: exported at module level only so it can\n * be unit-tested directly. It is not re-exported from the package entry\n * point (`src/index.ts`) and is not part of the package's public API.\n */\nexport function buildTokenLimitRequestFields(\n model: string,\n maxTokens: number | undefined,\n temperature: number | undefined,\n): {\n max_tokens?: number;\n max_completion_tokens?: number;\n temperature?: number;\n} {\n if (usesCompletionTokenLimit(model)) {\n return maxTokens === undefined ? {} : { max_completion_tokens: maxTokens };\n }\n return {\n ...(maxTokens === undefined ? {} : { max_tokens: maxTokens }),\n ...(temperature === undefined ? {} : { temperature }),\n };\n}\n\n/**\n * Shared profile for OpenAI-compatible providers\n */\nexport interface OpenAICompatibleProfile {\n providerLabel: string;\n providerName: string;\n defaultModel: string;\n capabilities: AICapabilities;\n describeModel(modelId: string): string;\n getContextLength(modelId: string): number;\n getModelCapabilities(modelId: string): string[];\n shouldIncludeModel(modelId: string): boolean;\n supportsFunctions(modelId: string): boolean;\n supportsVision(modelId: string): boolean;\n}\n\nconst OPENAI_PROFILE: OpenAICompatibleProfile = {\n providerLabel: 'OpenAI',\n providerName: 'openai',\n defaultModel: 'gpt-4o',\n capabilities: {\n chat: true,\n completion: true,\n embeddings: true,\n streaming: true,\n functions: true,\n vision: true,\n fineTuning: true,\n imageEmbeddings: true,\n imageGeneration: true,\n videoGeneration: false,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 128000,\n supportedOperations: [\n 'chat',\n 'completion',\n 'embedding',\n 'streaming',\n 'functions',\n 'vision',\n 'image_embedding',\n 'image_generation',\n ],\n },\n describeModel: (modelId) => `OpenAI model: ${modelId}`,\n getContextLength(modelId) {\n if (modelId.includes('gpt-4o')) return 128000;\n if (modelId.includes('gpt-4.1')) return 128000;\n if (modelId.includes('gpt-4-turbo')) return 128000;\n if (modelId.includes('gpt-4')) return 8192;\n if (modelId.includes('gpt-3.5-turbo')) return 16385;\n if (modelId.includes('text-embedding')) return 8192;\n return 4096;\n },\n getModelCapabilities(modelId) {\n const capabilities = ['text'];\n if (modelId.includes('gpt')) {\n capabilities.push('chat', 'functions');\n }\n if (\n modelId.includes('vision') ||\n modelId === 'gpt-4o' ||\n modelId.includes('gpt-4.1')\n ) {\n capabilities.push('vision');\n }\n if (modelId.includes('embedding')) {\n capabilities.push('embeddings');\n }\n return capabilities;\n },\n shouldIncludeModel(modelId) {\n return modelId.includes('gpt') || modelId.includes('text-embedding');\n },\n supportsFunctions(modelId) {\n return modelId.includes('gpt-4') || modelId.includes('gpt-3.5');\n },\n supportsVision(modelId) {\n return (\n modelId.includes('vision') ||\n modelId === 'gpt-4o' ||\n modelId.includes('gpt-4.1')\n );\n },\n};\n\nexport interface OpenAICompatibleOptions extends BaseAIOptions {\n type?: string;\n apiKey?: string;\n baseUrl?: string;\n organization?: string;\n}\n\n/**\n * OpenAI provider implementation that handles all interactions with OpenAI's API.\n * Supports GPT models, embeddings, function calling, streaming, and vision capabilities.\n */\nexport class OpenAIProvider implements AIInterface {\n private client: OpenAI;\n protected options: OpenAICompatibleOptions;\n protected readonly profile: OpenAICompatibleProfile;\n\n /**\n * Creates a new OpenAI provider instance\n * @param options - Configuration options for the OpenAI provider\n */\n constructor(\n options: OpenAICompatibleOptions,\n profile: OpenAICompatibleProfile = OPENAI_PROFILE,\n ) {\n this.profile = profile;\n this.options = normalizeBaseAIOptions({\n defaultModel: this.profile.defaultModel,\n ...options,\n });\n\n this.client = new OpenAI({\n apiKey: this.options.apiKey,\n baseURL: this.options.baseUrl,\n organization: this.options.organization,\n timeout: this.options.timeout,\n maxRetries: this.options.maxRetries,\n defaultHeaders: this.options.headers,\n });\n }\n\n /**\n * Generate a chat completion using OpenAI's chat models\n * @param messages - Array of conversation messages\n * @param options - Optional configuration for the chat completion\n * @returns Promise resolving to the AI response with content and metadata\n * @throws {AIError} When the API request fails or returns invalid data\n *\n * @example\n * ```typescript\n * const response = await provider.chat([\n * { role: 'system', content: 'You are a helpful assistant.' },\n * { role: 'user', content: 'What is the capital of France?' }\n * ], {\n * model: 'gpt-4o',\n * temperature: 0.7,\n * maxTokens: 150\n * });\n * console.log(response.content); // \"Paris is the capital of France.\"\n * ```\n */\n async chat(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): Promise<AIResponse> {\n const startTime = Date.now();\n let controls: PreparedRequestControls | undefined;\n try {\n const model =\n options.model || this.options.defaultModel || this.profile.defaultModel;\n options = normalizeChatOptions(\n this.options,\n options,\n this.profile.providerName,\n model,\n );\n controls = prepareRequestControls(this.options, options);\n const request = {\n model,\n messages: this.mapMessagesToOpenAI(messages),\n ...buildTokenLimitRequestFields(\n model,\n options.maxTokens,\n options.temperature,\n ),\n top_p: options.topP,\n n: options.n,\n stop: options.stop,\n frequency_penalty: options.frequencyPenalty,\n presence_penalty: options.presencePenalty,\n user: options.user,\n tools: options.tools?.map((tool) => ({\n type: 'function' as const,\n function: {\n name: tool.function.name,\n description: tool.function.description,\n parameters: tool.function.parameters,\n },\n })),\n // OpenAI rejects tool_choice without tools (a tool loop's final,\n // tool-less round still says toolChoice: 'none').\n tool_choice: options.tools?.length\n ? this.mapToolChoice(options.toolChoice)\n : undefined,\n response_format: options.responseFormat,\n seed: options.seed,\n stream: false,\n } as OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming & {\n reasoning?: {\n effort?: string;\n max_tokens?: number;\n include_thoughts?: boolean;\n };\n };\n if (\n (this.profile.providerName === 'bifrost' ||\n this.profile.providerName === 'litellm') &&\n (options.reasoning?.maxTokens || 0) > 0\n ) {\n request.reasoning = {\n effort: options.reasoning?.effort,\n max_tokens: options.reasoning?.maxTokens,\n include_thoughts: options.reasoning?.includeThoughts,\n };\n }\n const response = await this.client.chat.completions.create(request, {\n signal: controls.signal,\n timeout: controls.timeout,\n });\n\n const choice = response.choices[0];\n if (!choice) {\n throw new AIError(\n `No choices returned from ${this.profile.providerLabel}`,\n 'NO_CHOICES',\n this.profile.providerName,\n );\n }\n\n const usage = this.mapUsage(response.usage);\n emitUsage(\n this.options,\n this.profile.providerName,\n 'chat',\n response.model || model,\n usage,\n startTime,\n options.usageTags,\n );\n\n return {\n content: choice.message.content || '',\n usage,\n model: response.model,\n finishReason: this.mapFinishReason(choice.finish_reason),\n toolCalls: choice.message.tool_calls\n ?.filter((call) => call.type === 'function')\n .map((call) => ({\n id: call.id,\n type: 'function' as const,\n function: {\n name: call.function.name,\n arguments: call.function.arguments,\n },\n })),\n };\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n this.profile.providerName,\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n this.profile.providerName,\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n /**\n * Generate a text completion for a given prompt\n * @param prompt - The text prompt to complete\n * @param options - Optional configuration for the completion\n * @returns Promise resolving to the AI response\n * @throws {AIError} When the API request fails\n *\n * @example\n * ```typescript\n * const response = await provider.complete('The weather today is', {\n * model: 'gpt-4o',\n * maxTokens: 50,\n * temperature: 0.5\n * });\n * ```\n */\n async complete(\n prompt: string,\n options: CompletionOptions = {},\n ): Promise<AIResponse> {\n return this.chat([{ role: 'user', content: prompt }], {\n model: options.model,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n n: options.n,\n stop: options.stop,\n stream: options.stream,\n onProgress: options.onProgress,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n continueOnLength: options.continueOnLength,\n });\n }\n\n /**\n * Simple message interface for single-turn interactions with optional history\n *\n * @param text - The message text to send\n * @param options - Configuration options including history, model, etc.\n * @returns Promise resolving to the response content string\n *\n * @example\n * ```typescript\n * // Simple usage\n * const response = await provider.message('Hello!');\n *\n * // With options\n * const response = await provider.message('Analyze this', {\n * model: 'gpt-4o',\n * responseFormat: { type: 'json_object' }\n * });\n *\n * // With history\n * const response = await provider.message('What was my question?', {\n * history: [\n * { role: 'user', content: 'What is 2+2?' },\n * { role: 'assistant', content: '4' }\n * ]\n * });\n * ```\n */\n async message(text: string, options: MessageOptions = {}): Promise<string> {\n // Build messages array from history + current message\n const messages: AIMessage[] = [\n ...(options.history || []),\n { role: options.role || 'user', content: text },\n ];\n\n const response = await this.chat(messages, {\n model: options.model,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n stop: options.stop,\n stream: options.stream,\n frequencyPenalty: options.frequencyPenalty,\n presencePenalty: options.presencePenalty,\n responseFormat: options.responseFormat,\n seed: options.seed,\n tools: options.tools,\n toolChoice: options.toolChoice,\n onProgress: options.onProgress,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n continueOnLength: options.continueOnLength,\n });\n\n return response.content;\n }\n\n /**\n * Generate embeddings for the given text(s)\n * @param text - Single text string or array of texts to embed\n * @param options - Optional configuration for embeddings\n * @returns Promise resolving to embeddings response with vector arrays\n * @throws {AIError} When the API request fails\n *\n * @example\n * ```typescript\n * // Single text embedding\n * const response1 = await provider.embed('Hello world');\n * console.log(response1.embeddings[0]); // Array of numbers\n *\n * // Multiple text embeddings\n * const response2 = await provider.embed(['Text 1', 'Text 2']);\n * console.log(response2.embeddings.length); // 2\n * ```\n */\n async embed(\n text: string | string[],\n options: EmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n const startTime = Date.now();\n try {\n const model = options.model || 'text-embedding-3-small';\n const input = Array.isArray(text) ? text : [text];\n const response = await this.client.embeddings.create({\n model,\n input,\n encoding_format: options.encodingFormat,\n dimensions: options.dimensions,\n user: options.user,\n });\n\n const usage = this.mapUsage(response.usage);\n emitUsage(\n this.options,\n this.profile.providerName,\n 'embed',\n response.model || model,\n usage,\n startTime,\n options.usageTags,\n );\n\n return {\n embeddings: response.data.map((item) => item.embedding),\n usage,\n model: response.model,\n };\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Convert an image to a base64 data URL\n * @param image - Image as URL, base64 data URL, or Buffer\n * @returns base64 data URL string\n * @private\n */\n private async imageToBase64(\n image: string | Buffer,\n signal?: AbortSignal,\n ): Promise<string> {\n if (Buffer.isBuffer(image)) {\n return `data:image/png;base64,${image.toString('base64')}`;\n }\n if (image.startsWith('data:')) {\n return image; // Already base64 data URL\n }\n // It's a URL - fetch and convert\n const response = await fetch(image, { signal });\n if (!response.ok) {\n throw new AIError(\n `Failed to fetch image: ${response.status} ${response.statusText}`,\n 'IMAGE_FETCH_ERROR',\n this.profile.providerName,\n );\n }\n const arrayBuffer = await response.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n const contentType = response.headers.get('content-type') || 'image/png';\n return `data:${contentType};base64,${buffer.toString('base64')}`;\n }\n\n /**\n * Generate a text description of an image\n * @param image - Image as URL, base64 data URL, or Buffer\n * @param prompt - Custom prompt for description (optional)\n * @param options - Optional configuration\n * @returns Promise resolving to the description string\n *\n * @example\n * ```typescript\n * const description = await provider.describeImage('https://example.com/image.jpg');\n * ```\n */\n async describeImage(\n image: string | Buffer,\n prompt?: string,\n options: ImageDescriptionOptions = {},\n ): Promise<string> {\n let controls: PreparedRequestControls | undefined;\n try {\n const defaultPrompt =\n 'Describe this image for a search index. Include objects, mood, lighting, and any visible text.';\n\n controls = prepareRequestControls(this.options, options);\n const imageUrl = await this.imageToBase64(image, controls.signal);\n\n const response = await this.chat(\n [\n {\n role: 'user',\n content: [\n { type: 'text', text: prompt || defaultPrompt },\n {\n type: 'image_url',\n image_url: {\n url: imageUrl,\n detail: options.detail || 'auto',\n },\n },\n ],\n },\n ],\n {\n model:\n options.model ||\n this.options.defaultModel ||\n this.profile.defaultModel,\n maxTokens: options.maxTokens ?? 500,\n signal: controls.signal,\n timeout: controls.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n },\n );\n\n return response.content;\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n this.profile.providerName,\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n this.profile.providerName,\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n /**\n * Generate embeddings for an image using describe-then-embed pattern\n * @param image - Image as URL, base64 data URL, or Buffer\n * @param options - Optional configuration for image embeddings\n * @returns Promise resolving to embeddings response\n *\n * @example\n * ```typescript\n * const embedding = await provider.embedImage('https://example.com/image.jpg');\n * ```\n */\n async embedImage(\n image: string | Buffer,\n options: ImageEmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n try {\n // OpenAI doesn't have native image embeddings - use describe-then-embed\n const description = await this.describeImage(\n image,\n 'Describe this image in detail for semantic embedding. Include all visible objects, colors, textures, composition, text, people, actions, and overall scene context.',\n );\n\n return this.embed(description, {\n model: options.model || 'text-embedding-3-small',\n dimensions: options.dimensions,\n user: options.user,\n });\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Generate an image from a text prompt using DALL-E\n * @param prompt - Text description of the image to generate\n * @param options - Optional configuration for image generation\n * @returns Promise resolving to generated image(s)\n *\n * @example\n * ```typescript\n * const result = await provider.generateImage('A sunset over mountains');\n * fs.writeFileSync('image.png', result.images[0].data);\n * ```\n */\n async generateImage(\n prompt: string,\n options: ImageGenerationOptions = {},\n ): Promise<ImageGenerationResponse> {\n let controls: PreparedRequestControls | undefined;\n try {\n const model = options.model || 'dall-e-3';\n options = normalizeImageGenerationOptions(\n this.options,\n options,\n this.profile.providerName,\n model,\n );\n controls = prepareRequestControls(this.options, options);\n\n const requestParams: OpenAI.Images.ImageGenerateParams = {\n model,\n prompt,\n n: model === 'dall-e-3' ? 1 : options.n,\n size:\n (options.size as OpenAI.Images.ImageGenerateParams['size']) ||\n '1024x1024',\n response_format: options.outputFormat === 'url' ? 'url' : 'b64_json',\n };\n\n if (model === 'dall-e-3') {\n if (options.style) {\n requestParams.style = options.style;\n }\n if (options.quality) {\n requestParams.quality =\n options.quality as OpenAI.Images.ImageGenerateParams['quality'];\n }\n }\n\n const response = await this.client.images.generate(requestParams, {\n signal: controls.signal,\n timeout: controls.timeout,\n });\n\n const images = (response.data || []).map((item) => {\n let data: Buffer | string;\n const mimeType = 'image/png';\n\n if (options.outputFormat === 'url') {\n data = item.url || '';\n } else if (options.outputFormat === 'base64') {\n data = item.b64_json || '';\n } else {\n // Default: buffer\n data = Buffer.from(item.b64_json || '', 'base64');\n }\n\n return {\n data,\n mimeType,\n revisedPrompt: item.revised_prompt,\n };\n });\n\n return {\n images,\n model,\n };\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n this.profile.providerName,\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n this.profile.providerName,\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n // ============================================================================\n // Video Generation Methods (Not supported - use gemini, byteplus-modelark,\n // or openai-compat-video provider)\n // ============================================================================\n\n async submitVideoGenerationJob(\n _options: VideoGenerationOptions,\n ): Promise<VideoGenerationJob> {\n throw new AIError(\n `Video generation is not supported by ${this.profile.providerLabel} provider. Use gemini, byteplus-modelark, or openai-compat-video provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async getVideoGenerationJob(\n _handle: VideoGenerationJob,\n ): Promise<VideoGenerationStatusResult> {\n throw new AIError(\n `Video generation is not supported by ${this.profile.providerLabel} provider. Use gemini, byteplus-modelark, or openai-compat-video provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async fetchVideoGenerationResult(\n _handle: VideoGenerationJob,\n ): Promise<VideoGenerationResult> {\n throw new AIError(\n `Video generation is not supported by ${this.profile.providerLabel} provider. Use gemini, byteplus-modelark, or openai-compat-video provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async cancelVideoGenerationJob(_handle: VideoGenerationJob): Promise<void> {\n throw new AIError(\n `Video generation is not supported by ${this.profile.providerLabel} provider. Use gemini, byteplus-modelark, or openai-compat-video provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async validateVideoGenerationAccess(): Promise<boolean> {\n throw new AIError(\n `Video generation is not supported by ${this.profile.providerLabel} provider. Use gemini, byteplus-modelark, or openai-compat-video provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n /**\n * Stream a chat completion response in real-time\n * @param messages - Array of conversation messages\n * @param options - Optional configuration for the chat completion\n * @yields Individual content chunks as they arrive\n * @throws {AIError} When the streaming request fails\n *\n * @example\n * ```typescript\n * for await (const chunk of provider.stream([\n * { role: 'user', content: 'Write a story about AI' }\n * ])) {\n * process.stdout.write(chunk);\n * }\n * ```\n */\n async *stream(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): AsyncIterable<string> {\n const startTime = Date.now();\n let controls: PreparedRequestControls | undefined;\n try {\n const model =\n options.model || this.options.defaultModel || this.profile.defaultModel;\n options = normalizeChatOptions(\n this.options,\n options,\n this.profile.providerName,\n model,\n );\n controls = prepareRequestControls(this.options, options);\n const request = {\n model,\n messages: this.mapMessagesToOpenAI(messages),\n ...buildTokenLimitRequestFields(\n model,\n options.maxTokens,\n options.temperature,\n ),\n top_p: options.topP,\n stop: options.stop,\n frequency_penalty: options.frequencyPenalty,\n presence_penalty: options.presencePenalty,\n user: options.user,\n stream: true,\n } as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming & {\n reasoning?: {\n effort?: string;\n max_tokens?: number;\n include_thoughts?: boolean;\n };\n };\n if (\n (this.profile.providerName === 'bifrost' ||\n this.profile.providerName === 'litellm') &&\n (options.reasoning?.maxTokens || 0) > 0\n ) {\n request.reasoning = {\n effort: options.reasoning?.effort,\n max_tokens: options.reasoning?.maxTokens,\n include_thoughts: options.reasoning?.includeThoughts,\n };\n }\n const stream = await this.client.chat.completions.create(request, {\n signal: controls.signal,\n timeout: controls.timeout,\n });\n\n let streamFinish: string | null = null;\n for await (const chunk of stream) {\n streamFinish = chunk.choices[0]?.finish_reason ?? streamFinish;\n const content = chunk.choices[0]?.delta?.content;\n if (content) {\n if (options.onProgress) {\n options.onProgress(content);\n }\n yield content;\n }\n }\n options.onFinishReason?.(this.mapFinishReason(streamFinish) ?? 'stop');\n\n emitUsage(\n this.options,\n this.profile.providerName,\n 'stream',\n model,\n undefined,\n startTime,\n options.usageTags,\n );\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n this.profile.providerName,\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n this.profile.providerName,\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n /**\n * Count the number of tokens in the given text\n * @param text - The text to count tokens for\n * @returns Promise resolving to the estimated token count\n *\n * @remarks\n * OpenAI doesn't provide a direct token counting API, so this is an approximation\n * based on the general rule of ~4 characters per token. For precise counting,\n * consider using a dedicated tokenizer library.\n *\n * @example\n * ```typescript\n * const count = await provider.countTokens('Hello, world!');\n * console.log(count); // Approximately 4 tokens\n * ```\n */\n async countTokens(text: string): Promise<number> {\n // OpenAI doesn't provide a direct token counting API\n // This is an approximation based on the general rule of ~4 characters per token\n return Math.ceil(text.length / 4);\n }\n\n /**\n * Get a list of available OpenAI models\n * @returns Promise resolving to an array of model information\n * @throws {AIError} When the API request fails\n *\n * @example\n * ```typescript\n * const models = await provider.getModels();\n * const gptModels = models.filter(m => m.id.includes('gpt'));\n * ```\n */\n async getModels(): Promise<AIModel[]> {\n try {\n const response = await this.client.models.list();\n return response.data\n .filter((model) => this.profile.shouldIncludeModel(model.id))\n .map((model) => ({\n id: model.id,\n name: model.id,\n description: this.profile.describeModel(model.id),\n contextLength: this.profile.getContextLength(model.id),\n capabilities: this.profile.getModelCapabilities(model.id),\n supportsFunctions: this.profile.supportsFunctions(model.id),\n supportsVision: this.profile.supportsVision(model.id),\n }));\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Get the capabilities supported by this OpenAI provider\n * @returns Promise resolving to provider capabilities\n *\n * @example\n * ```typescript\n * const caps = await provider.getCapabilities();\n * if (caps.functions) {\n * // Provider supports function calling\n * }\n * ```\n */\n async getCapabilities(): Promise<AICapabilities> {\n return { ...this.profile.capabilities };\n }\n\n // ============================================================================\n // TTS Methods (Not supported - use Qwen3-TTS provider)\n // ============================================================================\n\n async synthesizeSpeech(\n _text: string,\n _options?: TTSOptions,\n ): Promise<TTSResponse> {\n throw new AIError(\n `TTS is not supported by ${this.profile.providerLabel} provider. Use Qwen3-TTS provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n streamSpeech(_text: string, _options?: TTSOptions): AsyncIterable<Buffer> {\n const error = new AIError(\n `TTS streaming is not supported by ${this.profile.providerLabel} provider. Use Qwen3-TTS provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n return {\n [Symbol.asyncIterator]: () => ({\n next: () => Promise.reject(error),\n }),\n };\n }\n\n async cloneVoice(_options: VoiceCloneOptions): Promise<Voice> {\n throw new AIError(\n `Voice cloning is not supported by ${this.profile.providerLabel} provider. Use Qwen3-TTS provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async designVoice(_options: VoiceDesignOptions): Promise<Voice> {\n throw new AIError(\n `Voice design is not supported by ${this.profile.providerLabel} provider. Use Qwen3-TTS provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n async getVoices(_options?: VoiceListOptions): Promise<Voice[]> {\n throw new AIError(\n `Voice listing is not supported by ${this.profile.providerLabel} provider. Use Qwen3-TTS provider.`,\n 'NOT_IMPLEMENTED',\n this.profile.providerName,\n );\n }\n\n /**\n * Maps internal AI messages to OpenAI's message format\n * @param messages - Array of internal AI messages\n * @returns Array of OpenAI-compatible message parameters\n * @private\n */\n private mapMessagesToOpenAI(\n messages: AIMessage[],\n ): OpenAI.Chat.ChatCompletionMessageParam[] {\n return messages.map((message) => {\n // Handle content that can be string or ContentPart[]\n let content: string | OpenAI.Chat.ChatCompletionContentPart[];\n\n if (typeof message.content === 'string') {\n content = message.content;\n } else {\n // Array of content parts - map to OpenAI format\n content = message.content.map((part: ContentPart) => {\n if (part.type === 'text') {\n return { type: 'text' as const, text: part.text };\n }\n // Image content part\n return {\n type: 'image_url' as const,\n image_url: {\n url: part.image_url.url,\n detail: part.image_url.detail,\n },\n };\n });\n }\n\n // Build message based on role and content\n const baseMessage = {\n role: message.role as OpenAI.Chat.ChatCompletionRole,\n content,\n };\n\n // Add optional fields based on role and availability\n if (\n message.name &&\n (message.role === 'system' ||\n message.role === 'user' ||\n message.role === 'function')\n ) {\n (baseMessage as any).name = message.name;\n }\n\n if (message.tool_calls && message.role === 'assistant') {\n // Replay only the wire fields; provider-specific extras such as\n // Gemini thought signatures are not part of the OpenAI schema.\n (baseMessage as any).tool_calls = message.tool_calls.map(\n (toolCall) => ({\n id: toolCall.id,\n type: toolCall.type,\n function: {\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n },\n }),\n );\n }\n\n if (message.role === 'tool' && message.tool_call_id) {\n // OpenAI rejects tool results without the id of the call they answer.\n (baseMessage as any).tool_call_id = message.tool_call_id;\n }\n\n return baseMessage as OpenAI.Chat.ChatCompletionMessageParam;\n });\n }\n\n /**\n * Maps internal tool choice format to OpenAI's tool choice format\n * @param toolChoice - Internal tool choice specification\n * @returns OpenAI-compatible tool choice option or undefined\n * @private\n */\n private mapToolChoice(\n toolChoice?:\n | 'auto'\n | 'none'\n | { type: 'function'; function: { name: string } },\n ): OpenAI.Chat.ChatCompletionToolChoiceOption | undefined {\n if (!toolChoice) return undefined;\n if (typeof toolChoice === 'string') return toolChoice;\n return {\n type: 'function',\n function: { name: toolChoice.function.name },\n };\n }\n\n /**\n * Maps OpenAI usage information to internal token usage format\n * @param usage - OpenAI usage object from API response\n * @returns Internal token usage object or undefined\n * @private\n */\n private mapUsage(\n usage?:\n | OpenAI.CompletionUsage\n | OpenAI.Completions.CompletionUsage\n | OpenAI.Embeddings.CreateEmbeddingResponse.Usage,\n ): TokenUsage | undefined {\n if (!usage) return undefined;\n return {\n promptTokens: usage.prompt_tokens || 0,\n completionTokens: (usage as any).completion_tokens || 0,\n totalTokens: usage.total_tokens || 0,\n };\n }\n\n /**\n * Maps OpenAI finish reason to internal finish reason format\n * @param reason - OpenAI finish reason from API response\n * @returns Internal finish reason\n * @private\n */\n private mapFinishReason(reason: string | null): AIResponse['finishReason'] {\n switch (reason) {\n case 'stop':\n return 'stop';\n case 'length':\n return 'length';\n case 'tool_calls':\n return 'tool_calls';\n case 'content_filter':\n return 'content_filter';\n default:\n return 'stop';\n }\n }\n\n /**\n * Gets the context length for a given OpenAI model\n * @param modelId - The OpenAI model identifier\n * @returns Maximum context length in tokens\n * @private\n */\n /**\n * Maps OpenAI API errors to internal AI error types\n * @param error - The error object from OpenAI API\n * @returns Appropriate internal AI error instance\n * @private\n */\n\n private mapError(error: unknown): AIError {\n if (error instanceof OpenAI.APIError) {\n switch (error.status) {\n case 401:\n return new AuthenticationError(this.profile.providerName);\n case 429: {\n return rateLimitErrorFrom(this.profile.providerName, error);\n }\n case 404:\n return new ModelNotFoundError(\n error.message,\n this.profile.providerName,\n );\n case 413:\n return new ContextLengthError(this.profile.providerName);\n default:\n if (error.message.includes('content_filter')) {\n return new ContentFilterError(this.profile.providerName);\n }\n return new AIError(\n error.message,\n 'API_ERROR',\n this.profile.providerName,\n );\n }\n }\n\n if (error instanceof AIError) {\n return error;\n }\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error occurred';\n return new AIError(\n errorMessage,\n 'UNKNOWN_ERROR',\n this.profile.providerName,\n );\n }\n}\n","import { ApiError, ValidationError } from '@happyvertical/utils';\nimport OpenAI from 'openai';\n\nimport type { AIMessageOptions } from './message';\nimport { buildTokenLimitRequestFields } from './providers/openai';\nimport type { AIProviderType, AIRateLimitOptions } from './types';\nimport { AI_PROVIDER_TYPES } from './types';\n\n/**\n * Common options for AI client configuration\n */\nexport interface AIClientOptions {\n /**\n * Type of AI client (e.g., 'openai')\n */\n type?: AIProviderType | string;\n\n /**\n * Response format for AI completions\n */\n responseFormat?: string;\n\n /**\n * API key for authentication\n */\n apiKey?: string;\n\n /**\n * Base URL for API requests\n */\n baseUrl?: string;\n\n /**\n * Admin API key for gateway providers that support provisioning.\n */\n adminApiKey?: string;\n\n /**\n * Admin base URL for gateway providers when it differs from `baseUrl`.\n */\n adminBaseUrl?: string;\n\n /**\n * Alias for adminBaseUrl.\n */\n adminUrl?: string;\n\n /**\n * Admin username for providers that use HTTP Basic auth.\n */\n adminUser?: string;\n\n /**\n * Admin username for providers that use HTTP Basic auth.\n */\n adminUsername?: string;\n\n /**\n * Admin password for providers that use HTTP Basic auth.\n */\n adminPassword?: string;\n\n /**\n * Custom admin headers for gateway providers.\n */\n adminHeaders?: Record<string, string>;\n\n /**\n * Optional shared pacing / retry configuration for getAI().\n */\n rateLimit?: AIRateLimitOptions;\n}\n\n/**\n * Interface defining required methods for AI clients\n */\nexport interface AIClientInterface {\n /**\n * Configuration options for this client\n */\n options: AIClientOptions;\n\n /**\n * Sends a message to the AI and gets a response\n *\n * @param text - Message text\n * @param options - Message options\n * @returns Promise resolving to the AI response\n */\n message(text: string, options: AIMessageOptions): Promise<unknown>;\n\n /**\n * Gets a text completion from the AI\n *\n * @param text - Input text for completion\n * @param options - Completion options\n * @returns Promise resolving to the completion result\n */\n textCompletion(text: string, options: AIMessageOptions): Promise<unknown>;\n}\n\n/**\n * Type guard to check if options are for OpenAI client\n *\n * @param options - Options to check\n * @returns True if options are valid for OpenAI client\n */\nfunction isOpenAIClientOptions(\n options: AIClientOptions,\n): options is OpenAIClientOptions {\n return options.type === 'openai' && 'apiKey' in options && !!options.apiKey;\n}\n\n/**\n * Type guard to check if value is an AI client instance\n *\n * @param value - Value to check\n * @returns True if value is an AI client instance\n */\nfunction isAIClientInstance(value: any): value is AIClient {\n return value instanceof AIClient;\n}\n\n/**\n * Options for AI text completion requests\n */\nexport interface AITextCompletionOptions {\n /**\n * Model identifier to use\n */\n model?: string;\n\n /**\n * Timeout in milliseconds\n */\n timeout?: number;\n\n /**\n * Role of the message sender\n */\n role?: OpenAI.Chat.ChatCompletionRole;\n\n /**\n * Previous messages in the conversation\n */\n history?: OpenAI.Chat.ChatCompletionMessageParam[];\n\n /**\n * Name of the message sender\n */\n name?: string;\n\n /**\n * Penalty for token frequency\n */\n frequencyPenalty?: number;\n\n /**\n * Token bias adjustments\n */\n logitBias?: Record<string, number>;\n\n /**\n * Whether to return log probabilities\n */\n logprobs?: boolean;\n\n /**\n * Number of top log probabilities to return\n */\n topLogprobs?: number;\n\n /**\n * Maximum tokens to generate\n */\n maxTokens?: number;\n\n /**\n * Number of completions to generate\n */\n n?: number;\n\n /**\n * Penalty for token presence\n */\n presencePenalty?: number;\n\n /**\n * Format for the response\n */\n responseFormat?: { type: 'text' | 'json_object' };\n\n /**\n * Random seed for deterministic results\n */\n seed?: number;\n\n /**\n * Sequences that stop generation\n */\n stop?: string | Array<string>;\n\n /**\n * Whether to stream responses\n */\n stream?: boolean;\n\n /**\n * Sampling temperature\n */\n temperature?: number;\n\n /**\n * Top-p sampling parameter\n */\n topProbability?: number;\n\n /**\n * Available tools for the model\n */\n tools?: Array<any>; // todo: figure out generic solution - Array<OpenAI.Chat.ChatCompletionTool>;\n\n /**\n * Tool selection behavior\n */\n toolChoice?:\n | 'none'\n | 'auto'\n | { type: 'function'; function: { name: string } };\n\n /**\n * User identifier\n */\n user?: string;\n\n /**\n * Callback for handling streaming responses\n */\n onProgress?: (partialMessage: string) => void;\n}\n\n/**\n * Base class for AI clients\n * Provides a common interface for different AI service providers\n */\nexport class AIClient {\n /**\n * Configuration options for this client\n */\n public options: AIClientOptions;\n\n /**\n * Creates a new AIClient\n *\n * @param options - Client configuration options\n */\n constructor(options: AIClientOptions) {\n this.options = options;\n }\n\n /**\n * Sends a message to the AI\n * Base implementation returns a placeholder response\n *\n * @param text - Message text\n * @param options - Message options\n * @returns Promise resolving to a placeholder response\n */\n public async message(\n _text: string,\n _options: AITextCompletionOptions = { role: 'user' },\n ) {\n return 'not a real ai message, this is the base class!';\n }\n\n /**\n * Factory method to create appropriate AI client based on options\n *\n * @param options - Client configuration options\n * @returns Promise resolving to an initialized AI client\n * @throws Error if client type is invalid\n */\n public static async create(\n options: AIClientOptions | AIClient,\n ): Promise<AIClient | OpenAIClient> {\n // If an AI client instance is passed, return it directly\n if (isAIClientInstance(options)) {\n return options;\n }\n\n // Cast to options since we know it's not an instance\n const clientOptions = options as AIClientOptions;\n\n if (isOpenAIClientOptions(clientOptions)) {\n return OpenAIClient.create(clientOptions);\n }\n\n // Delegate to modern factory for non-OpenAI providers\n const providedType = (clientOptions as any).type;\n if (providedType && providedType !== 'openai') {\n const { getAI } = await import('./factory.js');\n return (await getAI(clientOptions as any)) as any;\n }\n\n // Provide specific error messages for common issues\n if (providedType === 'openai') {\n throw new ValidationError(\n 'OpenAI API key is required but missing or empty',\n {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType,\n hint: 'Set OPENAI_API_KEY environment variable or pass apiKey in options',\n },\n );\n }\n\n throw new ValidationError('Invalid client type specified', {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType,\n });\n }\n\n /**\n * Gets a text completion from the AI\n * In base class, delegates to message method\n *\n * @param text - Input text for completion\n * @param options - Completion options\n * @returns Promise resolving to the completion result\n */\n public textCompletion(\n text: string,\n options: AITextCompletionOptions = {\n role: 'user',\n },\n ) {\n return this.message(text, options);\n }\n}\n\n/**\n * Creates an OpenAI client instance\n *\n * @param options - OpenAI configuration options\n * @returns Promise resolving to an OpenAI client\n */\nexport async function getOpenAI(options: {\n apiKey?: string;\n baseUrl?: string;\n}) {\n return new OpenAI({\n apiKey: options.apiKey,\n baseURL: options.baseUrl,\n });\n}\n\n/**\n * Options specific to OpenAI text completion requests\n */\nexport interface OpenAITextCompletionOptions {\n /**\n * Model identifier to use\n */\n model?: string;\n\n /**\n * Timeout in milliseconds\n */\n timeout?: number;\n\n /**\n * Role of the message sender\n */\n role?: OpenAI.Chat.ChatCompletionRole;\n\n /**\n * Previous messages in the conversation\n */\n history?: Array<OpenAI.Chat.ChatCompletionMessageParam>;\n\n /**\n * Name of the message sender\n */\n name?: string;\n\n /**\n * Penalty for token frequency\n */\n frequencyPenalty?: number;\n\n /**\n * Token bias adjustments\n */\n logitBias?: Record<string, number>;\n\n /**\n * Whether to return log probabilities\n */\n logprobs?: boolean;\n\n /**\n * Number of top log probabilities to return\n */\n topLogprobs?: number;\n\n /**\n * Maximum tokens to generate\n */\n maxTokens?: number;\n\n /**\n * Number of completions to generate\n */\n n?: number;\n\n /**\n * Penalty for token presence\n */\n presencePenalty?: number;\n\n /**\n * Format for the response\n */\n responseFormat?: { type: 'text' | 'json_object' };\n\n /**\n * Random seed for deterministic results\n */\n seed?: number;\n\n /**\n * Sequences that stop generation\n */\n stop?: string | Array<string>;\n\n /**\n * Whether to stream responses\n */\n stream?: boolean;\n\n /**\n * Sampling temperature\n */\n temperature?: number;\n\n /**\n * Top-p sampling parameter\n */\n topProbability?: number;\n\n /**\n * Available tools for the model\n */\n tools?: Array<OpenAI.Chat.ChatCompletionTool>;\n\n /**\n * Tool selection behavior\n */\n toolChoice?:\n | 'none'\n | 'auto'\n | { type: 'function'; function: { name: string } };\n\n /**\n * User identifier\n */\n user?: string;\n\n /**\n * Callback for handling streaming responses\n */\n onProgress?: (partialMessage: string) => void;\n}\n\n/**\n * Configuration options specific to OpenAI client\n */\nexport interface OpenAIClientOptions extends AIClientOptions {\n /**\n * OpenAI API key\n */\n apiKey?: string;\n\n /**\n * OpenAI API base URL\n */\n baseUrl?: string;\n}\n\n/**\n * Client implementation for the OpenAI API\n */\nexport class OpenAIClient extends AIClient {\n /**\n * OpenAI client instance\n */\n protected openai!: OpenAI;\n\n /**\n * Configuration options for this client\n */\n public options: OpenAIClientOptions;\n\n /**\n * Creates a new OpenAIClient\n *\n * @param options - OpenAI client configuration options\n */\n constructor(options: OpenAIClientOptions) {\n super(options);\n this.options = options;\n }\n\n /**\n * Sends a message to OpenAI\n *\n * @param text - Message text\n * @param options - Message options\n * @returns Promise resolving to the OpenAI response\n */\n public async message(\n text: string,\n options: AIMessageOptions = { role: 'user' },\n ) {\n const response = await this.textCompletion(text, options);\n return response;\n }\n\n /**\n * Factory method to create and initialize an OpenAIClient\n *\n * @param options - OpenAI client configuration options\n * @returns Promise resolving to an initialized OpenAIClient\n */\n public static async create(\n options: OpenAIClientOptions,\n ): Promise<OpenAIClient> {\n const client = new OpenAIClient(options);\n await client.initialize();\n return client;\n }\n\n /**\n * Initializes the OpenAI client\n */\n protected async initialize() {\n this.openai = new OpenAI({\n apiKey: this.options.apiKey,\n baseURL: this.options.baseUrl,\n });\n }\n\n /**\n * Sends a text completion request to the OpenAI API\n *\n * @param message - The message to send\n * @param options - Configuration options for the completion request\n * @returns Promise resolving to the completion text\n * @throws Error if the OpenAI API response is invalid\n */\n public async textCompletion(\n message: string,\n options: OpenAITextCompletionOptions = {},\n ): Promise<string> {\n const {\n model = 'gpt-4o',\n role = 'user',\n history = [],\n name: _name,\n frequencyPenalty = 0,\n logitBias,\n logprobs = false,\n topLogprobs,\n maxTokens,\n n = 1,\n presencePenalty = 0,\n responseFormat,\n seed,\n stop,\n stream: _stream = false,\n temperature = 1,\n topProbability: topP = 1,\n tools,\n toolChoice,\n user,\n onProgress,\n } = options;\n\n const messages = [\n ...history,\n {\n role: role as OpenAI.Chat.ChatCompletionRole,\n content: message,\n } as OpenAI.Chat.ChatCompletionSystemMessageParam,\n ];\n\n if (onProgress) {\n const stream = await this.openai.chat.completions.create({\n model,\n messages,\n stream: true,\n frequency_penalty: frequencyPenalty,\n logit_bias: logitBias,\n logprobs,\n top_logprobs: topLogprobs,\n ...buildTokenLimitRequestFields(model, maxTokens, temperature),\n n,\n presence_penalty: presencePenalty,\n response_format: responseFormat,\n seed,\n stop,\n top_p: topP,\n tools,\n tool_choice: toolChoice,\n user,\n });\n\n let fullContent = '';\n for await (const chunk of stream) {\n const content = chunk.choices[0]?.delta?.content || '';\n fullContent += content;\n onProgress(content);\n }\n\n return fullContent;\n }\n const response = await this.openai.chat.completions.create({\n model,\n messages,\n frequency_penalty: frequencyPenalty,\n logit_bias: logitBias,\n logprobs,\n top_logprobs: topLogprobs,\n ...buildTokenLimitRequestFields(model, maxTokens, temperature),\n n,\n presence_penalty: presencePenalty,\n response_format: responseFormat,\n seed,\n stop,\n stream: false,\n top_p: topP,\n tools,\n tool_choice: toolChoice,\n user,\n });\n\n const choice = response.choices[0];\n if (!choice || !choice.message || !choice.message.content) {\n throw new ApiError('Invalid response from OpenAI API: Missing content', {\n model,\n responseId: response.id,\n choices: response.choices?.length || 0,\n hasChoice: !!choice,\n hasMessage: !!choice?.message,\n hasContent: !!choice?.message?.content,\n });\n }\n return choice.message.content;\n }\n}\n\n/**\n * Options for getting an AI client with type information\n */\ntype GetAIClientOptions = AIClientOptions & {\n type?: AIProviderType;\n};\n\n/**\n * Factory function to create and initialize an appropriate AI client\n * Delegates to the modern getAI() factory for all provider types\n *\n * @param options - Client configuration options\n * @returns Promise resolving to an initialized AI client\n * @throws Error if client type is invalid\n */\nexport async function getAIClient(\n options: GetAIClientOptions,\n): Promise<AIClient> {\n // Delegate to modern factory for all providers\n const { getAI } = await import('./factory.js');\n return (await getAI(options as any)) as any;\n}\n","/**\n * Universal factory functions for creating AI provider instances\n * Works in both browser and Node.js environments\n */\n\nimport { loadEnvConfig, ValidationError } from '@happyvertical/utils';\n\nimport type { AIClientOptions } from './client';\nimport { createContinuingAI } from './continuation';\nimport { createRateLimitedAI } from './rate-limit';\nimport { createObservedAI, normalizeBaseAIOptions } from './safety';\nimport type {\n AIInterface,\n AIProviderType,\n AnthropicOptions,\n BedrockOptions,\n BifrostOptions,\n ByteplusModelArkOptions,\n ClaudeCliOptions,\n GeminiOptions,\n GetAIOptions,\n HuggingFaceOptions,\n LiteLLMOptions,\n OllamaOptions,\n OpenAICompatVideoOptions,\n OpenAIOptions,\n Qwen3TTSOptions,\n SeevioOptions,\n TypeSafeOptions,\n WebLLMOptions,\n} from './types';\nimport { AI_PROVIDER_TYPES } from './types';\n\n/**\n * Type guards for provider options\n */\n\n/**\n * Checks if the options are for OpenAI provider\n * @param options - The AI provider options to check\n * @returns True if options are for OpenAI provider (including default case)\n */\nfunction isOpenAIOptions(\n options: GetAIOptions | AIClientOptions,\n): options is OpenAIOptions {\n return !options.type || options.type === 'openai';\n}\n\n/**\n * Checks if the options are for LiteLLM provider\n * @param options - The AI provider options to check\n * @returns True if options are for LiteLLM provider\n */\nfunction isLiteLLMOptions(\n options: GetAIOptions | AIClientOptions,\n): options is LiteLLMOptions {\n return options.type === 'litellm';\n}\n\n/**\n * Checks if the options are for Bifrost provider\n * @param options - The AI provider options to check\n * @returns True if options are for Bifrost provider\n */\nfunction isBifrostOptions(\n options: GetAIOptions | AIClientOptions,\n): options is BifrostOptions {\n return options.type === 'bifrost';\n}\n\n/**\n * Checks if the options are for Ollama provider\n * @param options - The AI provider options to check\n * @returns True if options are for Ollama provider\n */\nfunction isOllamaOptions(\n options: GetAIOptions | AIClientOptions,\n): options is OllamaOptions {\n return options.type === 'ollama';\n}\n\n/**\n * Checks if the options are for Google Gemini provider\n * @param options - The AI provider options to check\n * @returns True if options are for Gemini provider\n */\nfunction isGeminiOptions(\n options: GetAIOptions | AIClientOptions,\n): options is GeminiOptions {\n return options.type === 'gemini';\n}\n\n/**\n * Checks if the options are for Anthropic Claude provider\n * @param options - The AI provider options to check\n * @returns True if options are for Anthropic provider\n */\nfunction isAnthropicOptions(\n options: GetAIOptions | AIClientOptions,\n): options is AnthropicOptions {\n return options.type === 'anthropic';\n}\n\n/**\n * Checks if the options are for Hugging Face provider\n * @param options - The AI provider options to check\n * @returns True if options are for Hugging Face provider\n */\nfunction isHuggingFaceOptions(\n options: GetAIOptions | AIClientOptions,\n): options is HuggingFaceOptions {\n return options.type === 'huggingface';\n}\n\n/**\n * Checks if the options are for AWS Bedrock provider\n * @param options - The AI provider options to check\n * @returns True if options are for Bedrock provider\n */\nfunction isBedrockOptions(\n options: GetAIOptions | AIClientOptions,\n): options is BedrockOptions {\n return options.type === 'bedrock';\n}\n\n/**\n * Checks if the options are for Claude CLI provider\n * @param options - The AI provider options to check\n * @returns True if options are for Claude CLI provider\n */\nfunction isClaudeCliOptions(\n options: GetAIOptions | AIClientOptions,\n): options is ClaudeCliOptions {\n return options.type === 'claude-cli';\n}\n\n/**\n * Checks if the options are for Qwen3-TTS provider\n * @param options - The AI provider options to check\n * @returns True if options are for Qwen3-TTS provider\n */\nfunction isQwen3TTSOptions(\n options: GetAIOptions | AIClientOptions,\n): options is Qwen3TTSOptions {\n return options.type === 'qwen3-tts';\n}\n\n/**\n * Checks if the options are for the OpenAI-compatible video-generation provider\n * @param options - The AI provider options to check\n * @returns True if options are for the openai-compat-video provider\n */\nfunction isOpenAICompatVideoOptions(\n options: GetAIOptions | AIClientOptions,\n): options is OpenAICompatVideoOptions {\n return options.type === 'openai-compat-video';\n}\n\n/**\n * Checks if the options are for the BytePlus ModelArk (Seedance) provider\n * @param options - The AI provider options to check\n * @returns True if options are for the byteplus-modelark provider\n */\nfunction isByteplusModelArkOptions(\n options: GetAIOptions | AIClientOptions,\n): options is ByteplusModelArkOptions {\n return options.type === 'byteplus-modelark';\n}\n\n/** Checks if options select Seevio's native Seedance task API. */\nfunction isSeevioOptions(\n options: GetAIOptions | AIClientOptions,\n): options is SeevioOptions {\n return options.type === 'seevio';\n}\n\n/** Checks if options select TypeSafe's System One decision API. */\nfunction isTypeSafeOptions(\n options: GetAIOptions | AIClientOptions,\n): options is TypeSafeOptions {\n return options.type === 'typesafe';\n}\n\n/** Checks if options select the in-browser WebLLM provider. */\nfunction isWebLLMOptions(\n options: GetAIOptions | AIClientOptions,\n): options is WebLLMOptions {\n return options.type === 'webllm';\n}\n\n/**\n * Creates an AI provider instance based on the provided options.\n * Universal version that works in both browser and Node.js environments.\n *\n * Supports environment variable configuration using the pattern:\n * - HAVE_AI_PROVIDER → provider type (string)\n * - HAVE_AI_MODEL → defaultModel (string)\n * - HAVE_AI_TIMEOUT → timeout (number)\n * - HAVE_AI_MAX_RETRIES → maxRetries (number)\n * - HAVE_AI_API_KEY → apiKey (string) - fallback if provider-specific key not set\n * - HAVE_AI_BASE_URL → baseUrl (string)\n *\n * User-provided options always take precedence over environment variables.\n *\n * Accepts both GetAIOptions (provider-specific options with literal types)\n * and AIClientOptions (legacy interface with generic string type) for\n * backward compatibility with existing code.\n *\n * @param options - Configuration options for the AI provider. Can be GetAIOptions or AIClientOptions.\n * @returns Promise resolving to an AI provider instance that implements the AIInterface\n * @throws {ValidationError} When the provider type is unsupported or invalid\n *\n * @example\n * ```typescript\n * // Create OpenAI client with explicit options\n * const openai = await getAI({\n * type: 'openai',\n * apiKey: process.env.OPENAI_API_KEY!,\n * defaultModel: 'gpt-4o'\n * });\n *\n * // Or use environment variables (HAVE_AI_PROVIDER=openai, HAVE_AI_API_KEY=sk-...)\n * const client = await getAI({});\n *\n * // Create Anthropic client\n * const anthropic = await getAI({\n * type: 'anthropic',\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * defaultModel: 'claude-3-5-sonnet-20241022'\n * });\n *\n * // Works with AIClientOptions (legacy interface)\n * const clientOptions: AIClientOptions = { type: 'openai', apiKey: '...' };\n * const legacy = await getAI(clientOptions);\n * ```\n */\nexport async function getAI(\n options: GetAIOptions | AIClientOptions = {},\n): Promise<AIInterface> {\n // Load environment variables with user options taking precedence\n options = loadEnvConfig(options as Record<string, any>, {\n packageName: 'ai',\n schema: {\n provider: 'string',\n type: 'string', // Alias for provider\n model: 'string',\n defaultModel: 'string',\n timeout: 'number',\n maxRetries: 'number',\n apiKey: 'string',\n baseUrl: 'string',\n adminApiKey: 'string',\n adminBaseUrl: 'string',\n adminUrl: 'string',\n adminUser: 'string',\n adminUsername: 'string',\n adminPassword: 'string',\n },\n }) as GetAIOptions;\n\n // Normalize 'provider' field to 'type' for consistency\n if ('provider' in options && !options.type) {\n (options as any).type = (options as any).provider;\n }\n\n // Normalize 'model' field to 'defaultModel' for consistency\n if ('model' in options && !options.defaultModel) {\n (options as any).defaultModel = (options as any).model;\n }\n\n options = normalizeBaseAIOptions(options as GetAIOptions);\n\n let client: AIInterface;\n\n if (isOpenAIOptions(options)) {\n const { OpenAIProvider } = await import('./providers/openai.js');\n client = new OpenAIProvider(options);\n } else if (isLiteLLMOptions(options)) {\n const { LiteLLMProvider } = await import('./providers/litellm.js');\n client = new LiteLLMProvider(options);\n } else if (isBifrostOptions(options)) {\n const { BifrostProvider } = await import('./providers/bifrost.js');\n client = new BifrostProvider(options);\n } else if (isOllamaOptions(options)) {\n const { OllamaProvider } = await import('./providers/ollama.js');\n client = new OllamaProvider(options);\n } else if (isGeminiOptions(options)) {\n const { GeminiProvider } = await import('./providers/gemini.js');\n client = new GeminiProvider(options);\n } else if (isAnthropicOptions(options)) {\n const { AnthropicProvider } = await import('./providers/anthropic.js');\n client = new AnthropicProvider(options);\n } else if (isHuggingFaceOptions(options)) {\n const { HuggingFaceProvider } = await import('./providers/huggingface.js');\n client = new HuggingFaceProvider(options);\n } else if (isBedrockOptions(options)) {\n const { BedrockProvider } = await import('./providers/bedrock.js');\n client = new BedrockProvider(options);\n } else if (isClaudeCliOptions(options)) {\n const { ClaudeCliProvider } = await import('./providers/claude-cli.js');\n client = new ClaudeCliProvider(options);\n } else if (isQwen3TTSOptions(options)) {\n const { Qwen3TTSProvider } = await import('./providers/qwen-tts.js');\n client = new Qwen3TTSProvider(options);\n } else if (isOpenAICompatVideoOptions(options)) {\n const { OpenAICompatVideoProvider } = await import(\n './providers/openai-compat-video.js'\n );\n client = new OpenAICompatVideoProvider(options);\n } else if (isByteplusModelArkOptions(options)) {\n const { ByteplusModelArkProvider } = await import(\n './providers/byteplus-modelark.js'\n );\n client = new ByteplusModelArkProvider(options);\n } else if (isSeevioOptions(options)) {\n const { SeevioProvider } = await import('./providers/seevio.js');\n client = new SeevioProvider(options);\n } else if (isTypeSafeOptions(options)) {\n const { TypeSafeProvider } = await import('./providers/typesafe.js');\n client = new TypeSafeProvider(options);\n } else if (isWebLLMOptions(options)) {\n // Lazy: the provider imports its optional peer (@mlc-ai/web-llm) only on\n // first request, so the root entry never loads it.\n const { WebLLMProvider } = await import('./providers/webllm.js');\n client = new WebLLMProvider(options);\n } else {\n throw new ValidationError('Unsupported AI provider type', {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType: (options as any).type,\n });\n }\n\n // Continuation sits outside the rate limiter so each continuation part is\n // paced and retried on its own (a 429 on part N never re-bills parts 1..N-1).\n return createObservedAI(\n createContinuingAI(createRateLimitedAI(client, options), options, client),\n options,\n );\n}\n\n/**\n * Browser-compatible auto-detection of AI provider based on available credentials.\n * Does not rely on process.env, making it suitable for browser environments.\n *\n * @param options - Configuration options that may contain provider-specific credentials\n * @returns Promise resolving to an AI provider instance based on detected credentials\n * @throws {ValidationError} When no provider can be detected from the provided options\n *\n * @example\n * ```typescript\n * // Auto-detect OpenAI from apiKey\n * const client1 = await getAIAuto({\n * apiKey: 'sk-...', // Detected as OpenAI\n * defaultModel: 'gpt-4o'\n * });\n *\n * // Auto-detect Hugging Face from apiToken\n * const client2 = await getAIAuto({\n * apiToken: 'hf_...', // Detected as Hugging Face\n * model: 'microsoft/DialoGPT-medium'\n * });\n *\n * // Auto-detect AWS Bedrock from region and credentials\n * const client3 = await getAIAuto({\n * region: 'us-east-1',\n * credentials: {\n * accessKeyId: 'AKIA...',\n * secretAccessKey: 'xxx'\n * }\n * });\n * ```\n */\nexport async function getAIAuto(\n options: Record<string, any>,\n): Promise<AIInterface> {\n const baseUrl = String((options as any).baseUrl || '');\n const hasKeepAliveOption =\n 'keepAlive' in options && (options as any).keepAlive !== undefined;\n\n // Auto-detect provider based on available credentials\n if (\n /((?:localhost|127\\.0\\.0\\.1)(?::11434)?(?:\\/(?:api|v1))?|ollama(?:\\.com)?(?:\\/(?:api|v1))?)\\/?$/i.test(\n baseUrl,\n ) ||\n hasKeepAliveOption\n ) {\n return getAI({ ...options, type: 'ollama' } as OllamaOptions);\n }\n\n if (options.apiKey && !options.type) {\n // Default to OpenAI if apiKey is provided without explicit type\n return getAI({ ...options, type: 'openai' } as OpenAIOptions);\n }\n\n if (options.apiToken) {\n // Hugging Face uses apiToken\n return getAI({ ...options, type: 'huggingface' } as HuggingFaceOptions);\n }\n\n if (options.region && options.credentials) {\n // AWS Bedrock uses region and explicit credentials\n return getAI({ ...options, type: 'bedrock' } as BedrockOptions);\n }\n\n if (options.projectId || options.anthropicVersion) {\n // Try to detect based on provider-specific options\n if (options.anthropicVersion) {\n return getAI({ ...options, type: 'anthropic' } as AnthropicOptions);\n }\n if (options.projectId) {\n return getAI({ ...options, type: 'gemini' } as GeminiOptions);\n }\n }\n\n throw new ValidationError('Could not auto-detect AI provider from options', {\n hint: 'Please specify a \"type\" field in options or provide provider-specific credentials',\n supportedTypes: [...AI_PROVIDER_TYPES] as AIProviderType[],\n providedOptions: Object.keys(options),\n });\n}\n","import type { AIThread } from './thread';\n\n/**\n * Options for creating AI messages\n */\nexport interface AIMessageOptions {\n /**\n * Role of the message sender\n */\n role?: 'user' | 'assistant' | 'system';\n\n /**\n * Format for the AI response\n */\n responseFormat?: { type: 'text' | 'json_object' };\n}\n\n/**\n * Represents a message in an AI conversation\n */\nexport class AIMessage {\n /**\n * Original options used to create this message\n */\n protected options;\n\n /**\n * Name of the message sender\n */\n public name: string;\n\n /**\n * Content of the message\n */\n public content: string;\n\n /**\n * Role of the message sender in the conversation\n */\n public role: 'user' | 'assistant' | 'system';\n\n /**\n * Creates a new AI message\n *\n * @param options - Message configuration\n * @param options.role - Role of the message sender\n * @param options.content - Content of the message\n * @param options.name - Name of the message sender\n */\n constructor(options: {\n role: 'user' | 'assistant' | 'system';\n content: string;\n name: string;\n }) {\n this.options = options;\n this.role = options.role;\n this.content = options.content;\n this.name = options.name;\n }\n\n /**\n * Factory method to create a new AI message\n *\n * @param options - Message configuration\n * @param options.thread - Thread this message belongs to\n * @param options.role - Role of the message sender\n * @param options.content - Content of the message\n * @param options.name - Name of the message sender\n * @returns Promise resolving to a new AIMessage instance\n */\n static async create(options: {\n thread: AIThread;\n role: 'user' | 'assistant' | 'system';\n content: string;\n name: string;\n }) {\n return new AIMessage(options);\n }\n}\n","import type OpenAI from 'openai';\nimport { AIClient, type AIClientOptions } from './client';\nimport { AIMessage } from './message';\n\n/**\n * Options for creating an AI conversation thread\n */\nexport interface AIThreadOptions {\n /**\n * Options for the AI client to use in this thread\n */\n ai: AIClientOptions;\n}\n\n/**\n * Represents a conversation thread with an AI model\n * Manages messages, references, and conversation state\n */\nexport class AIThread {\n /**\n * AI client instance for this thread\n */\n protected ai!: AIClient;\n\n /**\n * Options used to configure this thread\n */\n protected options: AIThreadOptions;\n\n /**\n * Messages in this conversation thread\n */\n private messages: AIMessage[] = [];\n\n /**\n * Reference materials to include in the conversation context\n */\n private references: { [name: string]: string } = {};\n\n /**\n * Creates a new AI thread\n *\n * @param options - Thread configuration options\n */\n constructor(options: AIThreadOptions) {\n this.options = options;\n }\n\n /**\n * Factory method to create and initialize a new AI thread\n *\n * @param options - Thread configuration options\n * @returns Promise resolving to an initialized AIThread\n */\n static async create(options: AIThreadOptions) {\n const thread = new AIThread(options);\n await thread.initialize();\n return thread; // No need to add system message here, do it in addSystem\n }\n\n /**\n * Initializes the AI client for this thread\n */\n public async initialize() {\n this.ai = await AIClient.create(this.options.ai);\n }\n\n /**\n * Adds a system message to the conversation\n *\n * @param prompt - System message content\n * @returns Promise resolving to the created AIMessage\n */\n public async addSystem(prompt: string) {\n const message = await AIMessage.create({\n thread: this,\n role: 'system',\n name: 'system',\n content: prompt,\n });\n\n this.messages.push(message);\n return message;\n }\n\n /**\n * Adds a message to the conversation\n *\n * @param options - Message options\n * @param options.role - Role of the message sender\n * @param options.name - Optional name of the message sender\n * @param options.content - Content of the message\n * @returns Promise resolving to the created AIMessage\n */\n public async add(options: {\n role: 'user' | 'assistant' | 'system';\n name?: string;\n content: string;\n }) {\n const message = await AIMessage.create({\n thread: this,\n role: options.role,\n name: options.name || options.role, // Default name to role if not provided\n content: options.content,\n });\n\n this.messages.push(message);\n return message;\n }\n\n /**\n * Gets all messages in this thread\n *\n * @returns Array of AIMessage objects\n */\n public get(): AIMessage[] {\n return this.messages;\n }\n\n /**\n * Adds a reference to be included in the conversation context\n *\n * @param name - Name of the reference\n * @param body - Content of the reference\n */\n public addReference(name: string, body: string): void {\n this.references[name] = body;\n }\n\n /**\n * Assembles the conversation history for sending to the AI\n * Properly orders system message, references, and conversation messages\n *\n * @returns Array of message parameters formatted for the OpenAI API\n */\n public assembleHistory(): OpenAI.Chat.ChatCompletionMessageParam[] {\n const history: OpenAI.Chat.ChatCompletionMessageParam[] = [];\n\n // Add system message first\n const systemMessage = this.messages.find((m) => m.role === 'system');\n if (systemMessage) {\n history.push({\n role: systemMessage.role,\n content: systemMessage.content,\n });\n }\n\n // Add references as user messages (before other user/assistant messages)\n for (const name in this.references) {\n history.push({\n role: 'user',\n content: `Reference - ${name}:\\n${this.references[name]}`,\n });\n }\n\n // Add other messages\n this.messages\n .filter((m) => m.role !== 'system')\n .forEach((message) => {\n history.push({ role: message.role, content: message.content });\n });\n\n return history;\n }\n\n /**\n * Sends a prompt to the AI and gets a response\n *\n * @param prompt - Prompt message to send\n * @param options - Options for the AI response\n * @param options.responseFormat - Format for the AI to respond with\n * @returns Promise resolving to the AI response\n */\n public async do(\n prompt: string,\n options: {\n responseFormat?: 'html' | 'text' | 'json';\n } = {\n responseFormat: 'text',\n },\n ) {\n const { responseFormat } = options;\n const history = this.assembleHistory();\n\n // Get completion from AI with assembled history\n const response = await this.ai.textCompletion(prompt, {\n history,\n responseFormat: {\n type: responseFormat === 'json' ? 'json_object' : 'text',\n },\n });\n return response;\n }\n}\n","/**\n * @happyvertical/ai - A standardized interface for AI model interactions\n *\n * This package provides a unified interface for interacting with various AI models.\n * Supports multiple providers: OpenAI, LiteLLM, Ollama, Gemini, Anthropic,\n * Hugging Face, AWS Bedrock, Claude CLI, and Qwen3-TTS.\n *\n * Key components:\n * - getAI() - Factory function for creating AI provider instances\n * - AIInterface - Standardized interface for all AI providers\n * - Provider-specific implementations for each supported service\n */\n\n// Legacy exports for backward compatibility\nexport * from './shared/client';\nexport * from './shared/factory';\nexport { AIMessage as AIMessageClass } from './shared/message';\nexport {\n DEFAULT_AI_GENERATION_LIMITS,\n DEFAULT_AI_MAX_RETRIES,\n DEFAULT_AI_TIMEOUT_MS,\n} from './shared/safety';\nexport * from './shared/thread';\nexport * from './shared/types';\n\n/** @internal */\nexport const PACKAGE_VERSION_INITIALIZED = true;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2FA,SAAgB,yBAAyB,OAAoC;CAC3E,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,aAAa,MAAM,YAAY;CACrC,MAAM,cAAc,WAAW,MAAM,WAAW,YAAY,GAAG,IAAI,CAAC;CACpE,OAAO,YAAY,KAAK,WAAW,KAAK,eAAe,KAAK,WAAW;AACzE;;;;;;;;;;;;;;;AAgBA,SAAgB,6BACd,OACA,WACA,aAKA;CACA,IAAI,yBAAyB,KAAK,GAChC,OAAO,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,uBAAuB,UAAU;CAE3E,OAAO;EACL,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,UAAU;EAC3D,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;CACrD;AACF;AAkBA,IAAM,iBAA0C;CAC9C,eAAe;CACf,cAAc;CACd,cAAc;CACd,cAAc;EACZ,MAAM;EACN,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,WAAW;EACX,QAAQ;EACR,YAAY;EACZ,iBAAiB;EACjB,iBAAiB;EACjB,iBAAiB;EACjB,KAAK;EACL,cAAc;EACd,aAAa;EACb,kBAAkB;EAClB,qBAAqB;GACnB;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF;CACA,gBAAgB,YAAY,iBAAiB;CAC7C,iBAAiB,SAAS;EACxB,IAAI,QAAQ,SAAS,QAAQ,GAAG,OAAO;EACvC,IAAI,QAAQ,SAAS,SAAS,GAAG,OAAO;EACxC,IAAI,QAAQ,SAAS,aAAa,GAAG,OAAO;EAC5C,IAAI,QAAQ,SAAS,OAAO,GAAG,OAAO;EACtC,IAAI,QAAQ,SAAS,eAAe,GAAG,OAAO;EAC9C,IAAI,QAAQ,SAAS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