UNPKG

simple-ai-provider

Version:

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

188 lines (187 loc) 5.99 kB
/** * Core types and interfaces for the Simple AI Provider package * Defines the contract that all AI providers must implement */ /** * Configuration options for AI providers */ export interface AIProviderConfig { /** API key for the AI service */ apiKey: string; /** Optional base URL for custom endpoints */ baseUrl?: string; /** Request timeout in milliseconds (default: 30000) */ timeout?: number; /** Maximum number of retry attempts (default: 3) */ maxRetries?: number; /** Additional provider-specific options */ [key: string]: any; } /** * Message role types supported by AI providers */ export type MessageRole = "system" | "user" | "assistant"; /** * Individual message in a conversation */ export interface AIMessage { /** Role of the message sender */ role: MessageRole; /** Content of the message */ content: string; /** Optional metadata for the message */ metadata?: Record<string, any>; } /** * Response type definition for structured AI outputs */ export interface ResponseType<T = any> { /** The TypeScript type definition as a string */ typeDefinition?: string; /** Human-readable description of the expected response format */ description: string; /** Example of the expected response structure */ example?: T; /** Whether to enforce strict JSON formatting */ strictJson?: boolean; } /** * Parameters for AI completion requests */ export interface CompletionParams<T = any> { /** Array of messages forming the conversation */ messages: AIMessage[]; /** Model to use for completion */ model?: string; /** Maximum tokens to generate (default: 1000) */ maxTokens?: number; /** Temperature for randomness (0.0 to 1.0, default: 0.7) */ temperature?: number; /** Top-p for nucleus sampling (default: 1.0) */ topP?: number; /** Stop sequences to end generation */ stopSequences?: string[]; /** Whether to stream the response */ stream?: boolean; /** Expected response type for structured outputs */ responseType?: ResponseType<T>; /** Additional provider-specific parameters */ [key: string]: any; } /** * Usage statistics for a completion */ export interface TokenUsage { /** Number of tokens in the prompt */ promptTokens: number; /** Number of tokens in the completion */ completionTokens: number; /** Total number of tokens used */ totalTokens: number; } /** * Response from an AI completion request */ export interface CompletionResponse<T = string> { /** Generated content, either as a string or a typed object */ content: T; /** Raw response from the provider, if content is a typed object */ rawContent?: string; /** Model used for generation */ model: string; /** Token usage statistics */ usage: TokenUsage; /** Unique identifier for the request */ id: string; /** Provider-specific metadata */ metadata?: Record<string, any>; } /** * Streaming chunk from an AI completion */ export interface CompletionChunk { /** Content delta for this chunk */ content: string; /** Whether this is the final chunk */ isComplete: boolean; /** Unique identifier for the request */ id: string; /** Token usage (only available on final chunk) */ usage?: TokenUsage; } /** * Error types that can occur during AI operations */ export declare enum AIErrorType { AUTHENTICATION = "authentication", RATE_LIMIT = "rate_limit", INVALID_REQUEST = "invalid_request", MODEL_NOT_FOUND = "model_not_found", NETWORK = "network", TIMEOUT = "timeout", UNKNOWN = "unknown" } /** * Custom error class for AI provider errors */ export declare class AIProviderError extends Error { type: AIErrorType; statusCode?: number | undefined; originalError?: Error | undefined; constructor(message: string, type: AIErrorType, statusCode?: number | undefined, originalError?: Error | undefined); } /** * Provider information and capabilities */ export interface ProviderInfo { /** Name of the provider */ name: string; /** Version of the provider implementation */ version: string; /** List of available models */ models: string[]; /** Maximum context length supported */ maxContextLength: number; /** Whether streaming is supported */ supportsStreaming: boolean; /** Additional capabilities */ capabilities?: Record<string, any>; } /** * Creates a response type definition for structured AI outputs * * @param description - Human-readable description of the expected format * @param example - Optional example of the expected response structure * @param strictJson - Whether to enforce strict JSON formatting (default: true) * @returns ResponseType object for use in completion requests * * @example * ```typescript * const userType = createResponseType( * 'A user profile with personal information and preferences', * { * name: 'John Doe', * age: 30, * email: 'john@example.com', * preferences: { theme: 'dark', notifications: true } * } * ); * ``` */ export declare function createResponseType<T = any>(description: string, example?: T, strictJson?: boolean): ResponseType<T>; /** * Generates a system prompt instruction for structured output based on response type * * @param responseType - The response type definition * @returns Formatted system prompt instruction */ export declare function generateResponseTypePrompt(responseType: ResponseType): string; /** * Parses and validates that a response matches the expected type structure * * @param response - The response content to validate * @param responseType - The expected response type * @returns The parsed and validated data object * @throws {AIProviderError} If parsing or validation fails */ export declare function parseAndValidateResponseType<T = any>(response: string, responseType: ResponseType<T>): T;