@happyvertical/ai 0.93.0 → 0.94.1
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/AGENT.md +2 -2
- package/README.md +37 -0
- package/dist/chunks/{anthropic-ByuqC5mC.js → anthropic-CD9Ud7a5.js} +4 -4
- package/dist/chunks/{anthropic-ByuqC5mC.js.map → anthropic-CD9Ud7a5.js.map} +1 -1
- package/dist/chunks/{bedrock-BeVCmkrS.js → bedrock-Bv1qCquH.js} +3 -3
- package/dist/chunks/{bedrock-BeVCmkrS.js.map → bedrock-Bv1qCquH.js.map} +1 -1
- package/dist/chunks/{bifrost-s3K7V8oU.js → bifrost-D1io0ttr.js} +4 -4
- package/dist/chunks/{bifrost-s3K7V8oU.js.map → bifrost-D1io0ttr.js.map} +1 -1
- package/dist/chunks/{byteplus-modelark-DaF0U4n1.js → byteplus-modelark-BIEXaTWw.js} +4 -4
- package/dist/chunks/{byteplus-modelark-DaF0U4n1.js.map → byteplus-modelark-BIEXaTWw.js.map} +1 -1
- package/dist/chunks/{claude-cli-BH_C62dV.js → claude-cli-Chfnckyj.js} +3 -3
- package/dist/chunks/{claude-cli-BH_C62dV.js.map → claude-cli-Chfnckyj.js.map} +1 -1
- package/dist/chunks/{gateway-admin-B4RSBDmo.js → gateway-admin-04mvbDHC.js} +2 -2
- package/dist/chunks/{gateway-admin-B4RSBDmo.js.map → gateway-admin-04mvbDHC.js.map} +1 -1
- package/dist/chunks/{gemini-GQdugon1.js → gemini-BGwrHeGc.js} +4 -4
- package/dist/chunks/{gemini-GQdugon1.js.map → gemini-BGwrHeGc.js.map} +1 -1
- package/dist/chunks/{huggingface-DxPspM6Q.js → huggingface-mthYVbLR.js} +3 -3
- package/dist/chunks/{huggingface-DxPspM6Q.js.map → huggingface-mthYVbLR.js.map} +1 -1
- package/dist/chunks/{litellm-D8iaHaji.js → litellm-xv_7hqm_.js} +4 -4
- package/dist/chunks/{litellm-D8iaHaji.js.map → litellm-xv_7hqm_.js.map} +1 -1
- package/dist/chunks/{ollama-BrB6bjnz.js → ollama-Bedt8Agy.js} +3 -3
- package/dist/chunks/{ollama-BrB6bjnz.js.map → ollama-Bedt8Agy.js.map} +1 -1
- package/dist/chunks/{openai-compat-video-DNE1Yvp6.js → openai-compat-video-B-xVe9bW.js} +4 -4
- package/dist/chunks/{openai-compat-video-DNE1Yvp6.js.map → openai-compat-video-B-xVe9bW.js.map} +1 -1
- package/dist/chunks/{qwen-tts-CAh1upii.js → qwen-tts-D-UmiMMy.js} +2 -2
- package/dist/chunks/{qwen-tts-CAh1upii.js.map → qwen-tts-D-UmiMMy.js.map} +1 -1
- package/dist/chunks/{rate-limit-C2oPwLGI.js → rate-limit-BVW_1Tey.js} +3 -2
- package/dist/chunks/rate-limit-BVW_1Tey.js.map +1 -0
- package/dist/chunks/{safety-ClfpyKEN.js → safety-BKswBoqy.js} +9 -8
- package/dist/chunks/safety-BKswBoqy.js.map +1 -0
- package/dist/chunks/{seevio-Bbu_hTUF.js → seevio-BJRiguLc.js} +4 -4
- package/dist/chunks/{seevio-Bbu_hTUF.js.map → seevio-BJRiguLc.js.map} +1 -1
- package/dist/chunks/{src-B3ZLEBD2.js → src-DOm4LN_h.js} +23 -16
- package/dist/chunks/{src-B3ZLEBD2.js.map → src-DOm4LN_h.js.map} +1 -1
- package/dist/chunks/{types-sSecpd_N.js → types-BpnNcTU1.js} +3 -2
- package/dist/chunks/types-BpnNcTU1.js.map +1 -0
- package/dist/chunks/typesafe-qpVPDkOR.js +306 -0
- package/dist/chunks/typesafe-qpVPDkOR.js.map +1 -0
- package/dist/index.js +3 -3
- package/dist/node/factory.d.ts.map +1 -1
- package/dist/node.js +18 -4
- package/dist/node.js.map +1 -1
- package/dist/shared/factory.d.ts.map +1 -1
- package/dist/shared/providers/typesafe.d.ts +30 -0
- package/dist/shared/providers/typesafe.d.ts.map +1 -0
- package/dist/shared/rate-limit.d.ts.map +1 -1
- package/dist/shared/safety.d.ts.map +1 -1
- package/dist/shared/types.d.ts +87 -3
- package/dist/shared/types.d.ts.map +1 -1
- package/metadata.json +2 -2
- package/package.json +3 -3
- package/dist/chunks/rate-limit-C2oPwLGI.js.map +0 -1
- package/dist/chunks/safety-ClfpyKEN.js.map +0 -1
- package/dist/chunks/types-sSecpd_N.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"src-B3ZLEBD2.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 { extractRetryAfterSeconds } 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 RateLimitError,\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` family (`gpt-5`, `gpt-5-mini`, `gpt-5-nano`,\n * and future `gpt-5*` variants) and the `o`-series 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*` and\n * `o1`/`o3`/`o4` variants are covered without needing an 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 a bare\n * `gpt-5-mini`.\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-5-mini`, `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 lastSegment.startsWith('gpt-5') || /^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 tool_choice: this.mapToolChoice(options.toolChoice),\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 });\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 });\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 for await (const chunk of stream) {\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\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 (baseMessage as any).tool_calls = message.tool_calls;\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 new RateLimitError(\n this.profile.providerName,\n extractRetryAfterSeconds(error),\n );\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 { 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} 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/**\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 {\n throw new ValidationError('Unsupported AI provider type', {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType: (options as any).type,\n });\n }\n\n return createObservedAI(createRateLimitedAI(client, options), options);\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,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,WAAW,OAAO,KAAK,eAAe,KAAK,WAAW;AAC3E;;;;;;;;;;;;;;;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,Y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,cAAc;GACpB,SAAS,cAAc;EACzB,CAAC;EAIH,KAAK,MAAM,QAAQ,KAAK,YACtB,QAAQ,KAAK;GACX,MAAM;GACN,SAAS,eAAe,KAAK,KAAK,KAAK,WAAW;EACpD,CAAC;EAIH,KAAK,SACF,QAAQ,MAAM,EAAE,SAAS,QAAQ,CAAC,CAClC,SAAS,YAAY;GACpB,QAAQ,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"}
|
|
1
|
+
{"version":3,"file":"src-DOm4LN_h.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 { extractRetryAfterSeconds } 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 RateLimitError,\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` family (`gpt-5`, `gpt-5-mini`, `gpt-5-nano`,\n * and future `gpt-5*` variants) and the `o`-series 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*` and\n * `o1`/`o3`/`o4` variants are covered without needing an 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 a bare\n * `gpt-5-mini`.\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-5-mini`, `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 lastSegment.startsWith('gpt-5') || /^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 tool_choice: this.mapToolChoice(options.toolChoice),\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 });\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 });\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 for await (const chunk of stream) {\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\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 (baseMessage as any).tool_calls = message.tool_calls;\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 new RateLimitError(\n this.profile.providerName,\n extractRetryAfterSeconds(error),\n );\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 { 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} 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/**\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 {\n throw new ValidationError('Unsupported AI provider type', {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType: (options as any).type,\n });\n }\n\n return createObservedAI(createRateLimitedAI(client, options), options);\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,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,WAAW,OAAO,KAAK,eAAe,KAAK,WAAW;AAC3E;;;;;;;;;;;;;;;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,OA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eAAe,QAAQ;GACpD;GACA,gBAAgB,EACd,MAAM,mBAAmB,SAAS,gBAAgB,OACpD;EACF,CAAC;CAEH;AACF;;;;ACvKA,IAAa,8BAA8B"}
|
|
@@ -15,7 +15,8 @@ var AI_PROVIDER_TYPES = [
|
|
|
15
15
|
"qwen3-tts",
|
|
16
16
|
"openai-compat-video",
|
|
17
17
|
"byteplus-modelark",
|
|
18
|
-
"seevio"
|
|
18
|
+
"seevio",
|
|
19
|
+
"typesafe"
|
|
19
20
|
];
|
|
20
21
|
/**
|
|
21
22
|
* Extract text content from a message content field.
|
|
@@ -117,4 +118,4 @@ var ContentFilterError = class extends AIError {
|
|
|
117
118
|
//#endregion
|
|
118
119
|
export { ContextLengthError as a, extractTextContent as c, ContentFilterError as i, AI_PROVIDER_TYPES as n, ModelNotFoundError as o, AuthenticationError as r, RateLimitError as s, AIError as t };
|
|
119
120
|
|
|
120
|
-
//# sourceMappingURL=types-
|
|
121
|
+
//# sourceMappingURL=types-BpnNcTU1.js.map
|