UNPKG

simple-ai-provider

Version:

A simple and extensible AI provider package for easy integration of multiple AI services

280 lines (279 loc) 9.82 kB
/** * Abstract Base Provider for AI Services * * This module provides the foundation for all AI provider implementations, * ensuring consistency, proper error handling, and maintainable code structure. * * Design Principles: * - Template Method Pattern: Define algorithm structure, let subclasses implement specifics * - Fail-Fast: Validate inputs early and provide clear error messages * - Separation of Concerns: Configuration, validation, execution are clearly separated * - Type Safety: Comprehensive TypeScript support for better DX * * @author Jan-Marlon Leibl * @version 1.0.0 */ import type { AIProviderConfig, CompletionParams, CompletionResponse, CompletionChunk, ProviderInfo } from '../types/index.js'; import { AIProviderError } from '../types/index.js'; /** * Abstract base class that all AI providers must extend. * * This class implements the Template Method pattern, providing a consistent * interface and workflow while allowing providers to implement their specific * logic in protected abstract methods. * * Lifecycle: * 1. Construction: validateConfig() called automatically * 2. Initialization: initialize() must be called before use * 3. Usage: complete() and stream() methods available * 4. Error Handling: All errors are normalized to AIProviderError * * @example * ```typescript * class MyProvider extends BaseAIProvider { * protected async doInitialize(): Promise<void> { * // Initialize your client/connection here * } * * protected async doComplete(params: CompletionParams): Promise<CompletionResponse> { * // Implement completion logic here * } * * // ... other required methods * } * ``` */ export declare abstract class BaseAIProvider { /** Validated configuration object for this provider instance */ protected readonly config: AIProviderConfig; /** Internal flag tracking initialization state */ private initialized; /** * Constructs a new provider instance with validated configuration. * * @param config - Provider configuration object * @throws {AIProviderError} If configuration is invalid * * @example * ```typescript * const provider = new MyProvider({ * apiKey: 'your-api-key', * timeout: 30000, * maxRetries: 3 * }); * ``` */ constructor(config: AIProviderConfig); /** * Initializes the provider for use. * * This method must be called before any completion requests. It handles * provider-specific setup such as client initialization and connection testing. * * @returns Promise that resolves when initialization is complete * @throws {AIProviderError} If initialization fails * * @example * ```typescript * await provider.initialize(); * // Provider is now ready for use * ``` */ initialize(): Promise<void>; /** * Checks if the provider has been initialized. * * @returns true if the provider is ready for use, false otherwise */ isInitialized(): boolean; /** * Generates a text completion based on the provided parameters. * * This method handles validation, error normalization, and delegates to * the provider-specific implementation via the Template Method pattern. * * @param params - Completion parameters including messages, model options, etc. * @returns Promise resolving to the completion response * @throws {AIProviderError} If the request fails or parameters are invalid * * @example * ```typescript * const response = await provider.complete({ * messages: [{ role: 'user', content: 'Hello!' }], * maxTokens: 100, * temperature: 0.7 * }); * console.log(response.content); * ``` */ complete(params: CompletionParams): Promise<CompletionResponse>; /** * Generates a streaming text completion. * * This method returns an async iterable that yields chunks of the response * as they become available, enabling real-time UI updates. * * @param params - Completion parameters * @returns AsyncIterable yielding completion chunks * @throws {AIProviderError} If the request fails or parameters are invalid * * @example * ```typescript * for await (const chunk of provider.stream(params)) { * if (!chunk.isComplete) { * process.stdout.write(chunk.content); * } else { * console.log('\nDone! Usage:', chunk.usage); * } * } * ``` */ stream(params: CompletionParams): AsyncIterable<CompletionChunk>; /** * Returns information about this provider and its capabilities. * * This method provides metadata about the provider including supported * models, context length, streaming support, and special capabilities. * * @returns Provider information object */ abstract getInfo(): ProviderInfo; /** * Provider-specific initialization logic. * * Subclasses should implement this method to handle their specific * initialization requirements such as: * - Creating API clients * - Testing connections * - Validating credentials * - Setting up authentication * * @protected * @returns Promise that resolves when initialization is complete * @throws {Error} If initialization fails (will be normalized to AIProviderError) */ protected abstract doInitialize(): Promise<void>; /** * Provider-specific completion implementation. * * Subclasses should implement this method to handle text completion * using their specific API. The base class handles validation and * error normalization. * * @protected * @param params - Validated completion parameters * @returns Promise resolving to completion response * @throws {Error} If completion fails (will be normalized to AIProviderError) */ protected abstract doComplete(params: CompletionParams): Promise<CompletionResponse>; /** * Provider-specific streaming implementation. * * Subclasses should implement this method to handle streaming completions * using their specific API. The base class handles validation and * error normalization. * * @protected * @param params - Validated completion parameters * @returns AsyncIterable yielding completion chunks * @throws {Error} If streaming fails (will be normalized to AIProviderError) */ protected abstract doStream(params: CompletionParams): AsyncIterable<CompletionChunk>; /** * Validates and normalizes provider configuration. * * This method ensures all required fields are present and sets sensible * defaults for optional fields. It follows the fail-fast principle. * * @protected * @param config - Raw configuration object * @returns Validated and normalized configuration * @throws {AIProviderError} If configuration is invalid */ protected validateAndNormalizeConfig(config: AIProviderConfig): AIProviderConfig; /** * Validates timeout configuration value. * * @private * @param timeout - Timeout value to validate * @returns Validated timeout value with default if needed */ private validateTimeout; /** * Validates max retries configuration value. * * @private * @param maxRetries - Max retries value to validate * @returns Validated max retries value with default if needed */ private validateMaxRetries; /** * Ensures the provider has been initialized before use. * * @protected * @throws {AIProviderError} If the provider is not initialized */ protected ensureInitialized(): void; /** * Validates completion parameters comprehensively. * * This method performs thorough validation of all completion parameters * to ensure they meet the requirements and constraints. * * @protected * @param params - Parameters to validate * @throws {AIProviderError} If any parameter is invalid */ protected validateCompletionParams(params: CompletionParams): void; /** * Validates the messages array parameter. * * @private * @param messages - Messages array to validate * @throws {AIProviderError} If messages are invalid */ private validateMessages; /** * Validates temperature parameter. * * @private * @param temperature - Temperature value to validate * @throws {AIProviderError} If temperature is invalid */ private validateTemperature; /** * Validates top-p parameter. * * @private * @param topP - Top-p value to validate * @throws {AIProviderError} If top-p is invalid */ private validateTopP; /** * Validates max tokens parameter. * * @private * @param maxTokens - Max tokens value to validate * @throws {AIProviderError} If max tokens is invalid */ private validateMaxTokens; /** * Validates stop sequences parameter. * * @private * @param stopSequences - Stop sequences to validate * @throws {AIProviderError} If stop sequences are invalid */ private validateStopSequences; /** * Normalizes any error into a standardized AIProviderError. * * This method provides consistent error handling across all providers, * mapping various error types and status codes to appropriate categories. * * @protected * @param error - The original error to normalize * @returns Normalized AIProviderError with appropriate type and context */ protected normalizeError(error: Error): AIProviderError; }