simple-ai-provider
Version:
A simple and extensible AI provider package for easy integration of multiple AI services
237 lines (236 loc) • 8.24 kB
TypeScript
/**
* OpenAI GPT Provider Implementation
*
* This module provides integration with OpenAI's GPT models through their official SDK.
* OpenAI offers industry-leading language models with excellent performance across
* diverse tasks including reasoning, coding, creative writing, and function calling.
*
* Key Features:
* - Support for all GPT model variants (GPT-4, GPT-4o, GPT-3.5 Turbo)
* - Advanced streaming support with real-time token delivery
* - Native function calling and JSON mode capabilities
* - Vision support for image understanding (model-dependent)
* - Organization and project-level access control
*
* OpenAI-Specific Considerations:
* - Uses "prompt_tokens" and "completion_tokens" terminology
* - Supports system messages natively within conversation flow
* - Has sophisticated rate limiting and pricing tiers
* - Provides extensive model configuration options
* - Supports batch processing and fine-tuning capabilities
*
* @author Jan-Marlon Leibl
* @version 1.0.0
* @see https://platform.openai.com/docs/api-reference
*/
import type { AIProviderConfig, CompletionParams, CompletionResponse, CompletionChunk, ProviderInfo } from '../types/index.js';
import { BaseAIProvider } from './base.js';
/**
* Configuration interface for OpenAI provider with OpenAI-specific options.
*
* @example
* ```typescript
* const config: OpenAIConfig = {
* apiKey: process.env.OPENAI_API_KEY!,
* defaultModel: 'gpt-4o',
* organization: 'org-your-org-id',
* project: 'proj-your-project-id',
* timeout: 60000,
* maxRetries: 3
* };
* ```
*/
export interface OpenAIConfig extends AIProviderConfig {
/**
* Default OpenAI model to use for requests.
*
* Recommended models:
* - 'gpt-4o': Latest multimodal model, best overall performance
* - 'gpt-4o-mini': Faster and cheaper, good for simple tasks
* - 'gpt-4-turbo': Previous generation flagship, excellent reasoning
* - 'gpt-3.5-turbo': Most cost-effective, good for basic tasks
*
* @default 'gpt-4o'
*/
defaultModel?: string;
/**
* OpenAI organization ID for billing and access control.
*
* This is useful for organizations with multiple teams or projects
* that need separate billing and usage tracking.
*
* @see https://platform.openai.com/account/org-settings
*/
organization?: string;
/**
* OpenAI project ID for granular access control.
*
* Projects allow fine-grained permission management within
* an organization, enabling better governance and security.
*
* @see https://platform.openai.com/docs/guides/production-best-practices
*/
project?: string;
}
/**
* OpenAI GPT provider implementation.
*
* This class handles all interactions with OpenAI's chat completion API through
* their official TypeScript SDK. It provides optimized handling of OpenAI's
* features including function calling, vision, and advanced streaming.
*
* Usage Pattern:
* 1. Create instance with configuration including API key
* 2. Call initialize() to set up client and validate credentials
* 3. Use complete() or stream() for text generation
* 4. Handle any AIProviderError exceptions appropriately
*
* @example
* ```typescript
* const openai = new OpenAIProvider({
* apiKey: process.env.OPENAI_API_KEY!,
* defaultModel: 'gpt-4o',
* organization: 'org-your-org-id'
* });
*
* await openai.initialize();
*
* const response = await openai.complete({
* messages: [
* { role: 'system', content: 'You are a helpful assistant.' },
* { role: 'user', content: 'Explain machine learning.' }
* ],
* maxTokens: 1000,
* temperature: 0.7
* });
* ```
*/
export declare class OpenAIProvider extends BaseAIProvider {
/** OpenAI SDK client instance (initialized during doInitialize) */
private client;
/** Default model identifier for requests */
private readonly defaultModel;
/** Organization ID for billing and access control */
private readonly organization?;
/** Project ID for granular permissions */
private readonly project?;
/**
* Creates a new OpenAI provider instance.
*
* @param config - OpenAI-specific configuration options
* @throws {AIProviderError} If configuration validation fails
*/
constructor(config: OpenAIConfig);
/**
* Initializes the OpenAI provider by setting up the client.
*
* This method:
* 1. Creates the OpenAI SDK client with configuration
* 2. Tests the connection with a minimal API call
* 3. Validates API key permissions and model access
* 4. Sets up organization and project context if provided
*
* @protected
* @throws {Error} If client creation or connection validation fails
*/
protected doInitialize(): Promise<void>;
/**
* Generates a text completion using OpenAI's chat completions API.
*
* This method:
* 1. Converts messages to OpenAI's format
* 2. Builds optimized request parameters
* 3. Makes API call with comprehensive error handling
* 4. Formats response to standard interface
*
* @protected
* @param params - Validated completion parameters
* @returns Promise resolving to formatted completion response
* @throws {Error} If API request fails
*/
protected doComplete(params: CompletionParams): Promise<CompletionResponse>;
/**
* Generates a streaming text completion using OpenAI's streaming API.
*
* This method:
* 1. Builds streaming request parameters
* 2. Handles real-time stream chunks from OpenAI
* 3. Tracks token usage throughout the stream
* 4. Yields formatted chunks with proper completion tracking
*
* @protected
* @param params - Validated completion parameters
* @returns AsyncIterable yielding completion chunks
* @throws {Error} If streaming request fails
*/
protected doStream(params: CompletionParams): AsyncIterable<CompletionChunk>;
/**
* Returns comprehensive information about the OpenAI provider.
*
* @returns Provider information including models, capabilities, and limits
*/
getInfo(): ProviderInfo;
/**
* Validates the connection by making a minimal test request.
*
* @private
* @throws {AIProviderError} If connection validation fails
*/
private validateConnection;
/**
* Validates model name format for OpenAI models.
*
* @private
* @param modelName - Model name to validate
* @throws {AIProviderError} If model name format is invalid
*/
private validateModelName;
/**
* Builds optimized request parameters for OpenAI API.
*
* @private
* @param params - Input completion parameters
* @param stream - Whether to enable streaming
* @returns Formatted request parameters
*/
private buildRequestParams;
/**
* Converts generic messages to OpenAI's chat completion format.
*
* OpenAI supports system messages natively within the conversation flow,
* making this conversion straightforward.
*
* @private
* @param messages - Input messages array
* @returns OpenAI-formatted messages
*/
private convertMessages;
/**
* Processes streaming response chunks from OpenAI API.
*
* @private
* @param stream - OpenAI streaming response promise
* @returns AsyncIterable of formatted completion chunks
*/
private processStreamChunks;
/**
* Formats OpenAI's completion response to our standard interface.
*
* @private
* @param response - Raw OpenAI API response
* @returns Formatted completion response
* @throws {AIProviderError} If response format is unexpected
*/
private formatCompletionResponse;
/**
* Handles and transforms OpenAI-specific errors.
*
* This method maps OpenAI's error responses to our standardized
* error format, providing helpful context and actionable suggestions.
*
* @private
* @param error - Original error from OpenAI API
* @returns Normalized AIProviderError
*/
private handleOpenAIError;
}