UNPKG

@robota-sdk/core

Version:

Core functionality for building AI agents with TypeScript - conversation management, function calling, and multi-provider support for OpenAI, Anthropic, and Google AI

1,332 lines (1,315 loc) 40.5 kB
import { FunctionCall, ToolProvider, FunctionSchema } from '@robota-sdk/tools'; /** * Provider options interface */ interface ProviderOptions { model: string; temperature?: number; maxTokens?: number; stopSequences?: string[]; streamMode?: boolean; } /** * Run options interface */ interface RunOptions { systemPrompt?: string; functionCallMode?: string; forcedFunction?: string; forcedArguments?: Record<string, unknown>; temperature?: number; maxTokens?: number; } /** * Universal message role type - Provider-independent neutral role * * @public */ type UniversalMessageRole = 'user' | 'assistant' | 'system' | 'tool'; /** * Base message interface with common properties * * @public */ interface BaseMessage { /** Message creation timestamp */ timestamp: Date; /** Additional metadata */ metadata?: Record<string, any>; } /** * User message interface - for messages from users/humans * * @public */ interface UserMessage extends BaseMessage { /** Message role - always 'user' */ role: 'user'; /** User message content */ content: string; /** Optional user identifier */ name?: string; } /** * Assistant message interface - for AI responses * * @public */ interface AssistantMessage extends BaseMessage { /** Message role - always 'assistant' */ role: 'assistant'; /** Assistant response content (can be null when making tool calls) */ content: string | null; /** Tool calls made by the assistant (OpenAI tool calling format) */ toolCalls?: Array<{ id: string; type: 'function'; function: { name: string; arguments: string; }; }>; } /** * System message interface - for system instructions and prompts * * @public */ interface SystemMessage extends BaseMessage { /** Message role - always 'system' */ role: 'system'; /** System instruction content */ content: string; /** Optional system message identifier */ name?: string; } /** * Tool message interface - for tool execution results * * @public */ interface ToolMessage extends BaseMessage { /** Message role - always 'tool' */ role: 'tool'; /** Tool execution result summary */ content: string; /** Tool call ID for OpenAI tool calling format */ toolCallId?: string; /** Name of the tool that was executed */ name?: string; } /** * Universal message type covering all possible message variations * * This union type ensures type safety by requiring specific properties * based on the message role, preventing invalid combinations. * * @see {@link ../../apps/examples/04-sessions | Session and Conversation Examples} * * @public */ type UniversalMessage = UserMessage | AssistantMessage | SystemMessage | ToolMessage; /** * Type guard functions for message type checking */ /** * Check if a message is a user message * * @param message - Message to check * @returns True if the message is a user message */ declare function isUserMessage(message: UniversalMessage): message is UserMessage; /** * Check if a message is an assistant message * * @param message - Message to check * @returns True if the message is an assistant message */ declare function isAssistantMessage(message: UniversalMessage): message is AssistantMessage; /** * Check if a message is a system message * * @param message - Message to check * @returns True if the message is a system message */ declare function isSystemMessage(message: UniversalMessage): message is SystemMessage; /** * Check if a message is a tool message * * @param message - Message to check * @returns True if the message is a tool message */ declare function isToolMessage(message: UniversalMessage): message is ToolMessage; /** * Interface for managing conversation history * * This interface provides methods for adding, retrieving, and managing * messages in a conversation thread. Implementations may provide * different storage mechanisms, message limits, or special handling * for specific message types. * * @public */ interface ConversationHistory { /** * Add a message to conversation history * * @param message - Universal message to add */ addMessage(message: UniversalMessage): void; /** * Add user message (convenience method) * * @param content - User message content * @param metadata - Optional metadata */ addUserMessage(content: string, metadata?: Record<string, any>): void; /** * Add assistant message (convenience method) * * @param content - Assistant response content * @param toolCalls - Optional tool calls made by assistant * @param metadata - Optional metadata */ addAssistantMessage(content: string, toolCalls?: Array<{ id: string; type: 'function'; function: { name: string; arguments: string; }; }>, metadata?: Record<string, any>): void; /** * Add system message (convenience method) * * @param content - System instruction content * @param metadata - Optional metadata */ addSystemMessage(content: string, metadata?: Record<string, any>): void; /** * Add tool execution result message with tool call ID (for tool calling format) * * @param content - Tool result content * @param toolCallId - Tool call ID from the assistant's tool call * @param toolName - Name of the tool that was executed * @param metadata - Optional metadata */ addToolMessageWithId(content: string, toolCallId: string, toolName: string, metadata?: Record<string, any>): void; /** * Get all messages in chronological order * * @returns Array of all messages */ getMessages(): UniversalMessage[]; /** * Get messages filtered by specific role * * @param role - Message role to filter by * @returns Array of messages with the specified role */ getMessagesByRole(role: UniversalMessageRole): UniversalMessage[]; /** * Get the most recent n messages * * @param count - Number of recent messages to return * @returns Array of recent messages */ getRecentMessages(count: number): UniversalMessage[]; /** * Clear all conversation history */ clear(): void; /** * Get total message count * * @returns Number of messages in history */ getMessageCount(): number; } /** * Abstract base class for conversation history implementations * * Provides common functionality and message factory methods * that can be shared across different conversation history implementations. * * @internal */ declare abstract class BaseConversationHistory implements ConversationHistory { /** Maximum number of messages to store (0 = unlimited) */ protected readonly maxMessages: number; constructor(options?: { maxMessages?: number; }); abstract addMessage(message: UniversalMessage): void; abstract getMessages(): UniversalMessage[]; abstract clear(): void; abstract getMessageCount(): number; addUserMessage(content: string, metadata?: Record<string, any>): void; addAssistantMessage(content: string, toolCalls?: Array<{ id: string; type: 'function'; function: { name: string; arguments: string; }; }>, metadata?: Record<string, any>): void; addSystemMessage(content: string, metadata?: Record<string, any>): void; addToolMessageWithId(content: string, toolCallId: string, toolName: string, metadata?: Record<string, any>): void; getMessagesByRole(role: UniversalMessageRole): UniversalMessage[]; getRecentMessages(count: number): UniversalMessage[]; /** * Apply message limit by removing oldest messages while preserving system messages * @internal */ protected applyMessageLimit(messages: UniversalMessage[]): UniversalMessage[]; } /** * Default conversation history implementation * * Provides a simple in-memory storage for conversation messages with optional * message count limiting. Supports all message types with type safety. * * @see {@link ../../apps/examples/04-sessions | Session and Conversation Examples} * * @public */ declare class SimpleConversationHistory extends BaseConversationHistory { /** @internal Array storing all messages */ private messages; /** * Create a new SimpleConversationHistory instance * * @param options - Configuration options * @param options.maxMessages - Maximum number of messages to keep (0 = unlimited) */ constructor(options?: { maxMessages?: number; }); /** * Add a message to conversation history * * Appends the message to the history and applies message count limits if configured. * System messages are always preserved when applying limits. * * @param message - Universal message to add */ addMessage(message: UniversalMessage): void; /** * Get all messages in chronological order * * @returns Defensive copy of all messages */ getMessages(): UniversalMessage[]; /** * Get total message count * * @returns Number of messages currently stored */ getMessageCount(): number; /** * Clear all conversation history * * Removes all messages from the history. */ clear(): void; /** * Apply message count limits while preserving system messages * * When maxMessages is set and exceeded, this method removes older messages * while always preserving system messages which are important for context. * * @internal */ private _applyMessageLimit; } /** * Conversation history implementation that maintains system messages * * Extends SimpleConversationHistory with automatic system prompt management. * The system prompt is automatically maintained and can be updated dynamically. * * @see {@link ../../apps/examples/04-sessions | Session and Conversation Examples} * * @public */ declare class PersistentSystemConversationHistory extends BaseConversationHistory { /** @internal Underlying conversation history */ private readonly history; /** @internal Current system prompt */ private systemPrompt; /** * Create a new PersistentSystemConversationHistory instance * * @param systemPrompt - Initial system prompt to set * @param options - Configuration options passed to underlying SimpleConversationHistory */ constructor(systemPrompt: string, options?: { maxMessages?: number; }); /** * Add a message to conversation history (delegates to underlying history) * * @param message - Universal message to add */ addMessage(message: UniversalMessage): void; /** * Get all messages (delegates to underlying history) * * @returns Array of all messages including system messages */ getMessages(): UniversalMessage[]; /** * Get total message count (delegates to underlying history) * * @returns Total number of messages including system messages */ getMessageCount(): number; /** * Clear conversation history but preserve system prompt * * Clears all messages and re-adds the current system prompt. */ clear(): void; /** * Update the system prompt and refresh system messages * * Removes old system messages, updates the system prompt, and adds * the new system prompt as a system message. * * @param systemPrompt - New system prompt to set */ updateSystemPrompt(systemPrompt: string): void; /** * Get the current system prompt * * @returns Current system prompt string */ getSystemPrompt(): string; } /** * Message role type */ type MessageRole = 'user' | 'assistant' | 'system' | 'function'; /** * Basic message interface */ interface Message { role: MessageRole; content: string; name?: string; functionCall?: FunctionCall; functionResult?: any; toolCalls?: Array<{ id: string; type: 'function'; function: { name: string; arguments: string; }; }>; toolCallId?: string; } /** * Response from AI model * * Contains the generated content, usage statistics, and metadata from AI provider. * Also includes tool calling information when applicable. * * @public */ interface ModelResponse { /** Generated text content (may be null for tool-only responses) */ content?: string; /** Token usage statistics from the AI provider */ usage?: { /** Number of tokens in the input prompt */ promptTokens: number; /** Number of tokens in the generated completion */ completionTokens: number; /** Total tokens used (prompt + completion) */ totalTokens: number; }; /** Provider-specific metadata */ metadata?: { /** Model name used for generation */ model?: string; /** Reason why generation finished */ finishReason?: string; /** Provider-specific system fingerprint */ systemFingerprint?: string; /** Additional provider-specific data */ [key: string]: any; }; /** Tool calls made by the assistant (OpenAI tool calling format) */ toolCalls?: Array<{ /** Unique identifier for this tool call */ id: string; /** Type of tool call (currently only 'function' is supported) */ type: 'function'; /** Function call details */ function: { /** Name of the function to call */ name: string; /** Function arguments as JSON string */ arguments: string; }; }>; } /** * Streaming response chunk interface */ interface StreamingResponseChunk { content?: string; functionCall?: Partial<FunctionCall>; isComplete?: boolean; } /** * Conversation context interface */ interface Context { messages: UniversalMessage[]; systemPrompt?: string; systemMessages?: Message[]; metadata?: Record<string, any>; } /** * AI provider interface (unified wrapper) */ interface AIProvider { /** Provider name */ name: string; /** Chat request */ chat(model: string, context: Context, options?: any): Promise<ModelResponse>; /** Streaming chat request (optional) */ chatStream?(model: string, context: Context, options?: any): AsyncGenerator<StreamingResponseChunk, void, unknown>; /** Resource cleanup (optional) */ close?(): Promise<void>; } /** * Logger interface */ interface Logger { info(message: string, ...args: any[]): void; debug(message: string, ...args: any[]): void; warn(message: string, ...args: any[]): void; error(message: string, ...args: any[]): void; } /** * Core execution interface for Robota * Contains only essential execution methods * * @public */ interface RobotaCore { /** * Execute AI conversation with prompt * * @param prompt - User input text * @param options - Optional run configuration * @returns Promise resolving to AI response text */ run(prompt: string, options?: RunOptions): Promise<string>; /** * Execute AI conversation with streaming response * * @param prompt - User input text * @param options - Optional run configuration * @returns Promise resolving to async iterable of response chunks */ runStream(prompt: string, options?: RunOptions): Promise<AsyncIterable<StreamingResponseChunk>>; /** * Release all resources and close connections * * @returns Promise that resolves when cleanup is complete */ close(): Promise<void>; } /** * Configuration interface for Robota * Contains configuration and management methods * * @public */ interface RobotaConfigurable { /** * Call a specific tool directly * * @param toolName - Name of the tool to call * @param parameters - Parameters to pass to the tool * @returns Promise resolving to the tool's result */ callTool(toolName: string, parameters: Record<string, any>): Promise<any>; /** * Get list of all available tools * * @returns Array of tool metadata objects */ getAvailableTools(): any[]; /** * Clear all conversation history */ clearConversationHistory(): void; } /** * Complete Robota interface combining core and configurable functionality * * @public */ interface RobotaComplete extends RobotaCore, RobotaConfigurable { } /** * AI provider management class * Responsible for registering, configuring, and querying AI providers. */ declare class AIProviderManager { private aiProviders; private currentProvider?; private currentModel?; /** * Add an AI provider * * @param name - Provider name * @param aiProvider - AI provider instance */ addProvider(name: string, aiProvider: AIProvider): void; /** * Set current AI provider and model * * @param providerName - Provider name * @param model - Model name */ setCurrentAI(providerName: string, model: string): void; /** * Get currently configured AI provider and model */ getCurrentAI(): { provider?: string; model?: string; }; /** * Get current AI provider instance */ getCurrentProvider(): AIProvider | null; /** * Get current model name */ getCurrentModel(): string | null; /** * Check if AI provider is configured */ isConfigured(): boolean; /** * Release resources of all AI providers */ close(): Promise<void>; } /** * Tool provider management class * Handles registration, invocation, and retrieval of Tool Providers. */ declare class ToolProviderManager { private toolProviders; private allowedFunctions?; private logger; constructor(logger: Logger, allowedFunctions?: string[]); /** * Add a Tool Provider * * @param toolProvider - Tool provider instance */ addProvider(toolProvider: ToolProvider): void; /** * Add multiple Tool Providers * * @param toolProviders - Array of tool providers */ addProviders(toolProviders: ToolProvider[]): void; /** * Set allowed function list * * @param allowedFunctions - Array of allowed function names */ setAllowedFunctions(allowedFunctions?: string[]): void; /** * Call a tool * * @param toolName - Name of the tool to call * @param parameters - Parameters to pass to the tool * @returns Tool call result */ callTool(toolName: string, parameters: Record<string, any>): Promise<any>; /** * Get list of available tools * * @returns List of tool schemas */ getAvailableTools(): FunctionSchema[]; /** * Get the number of registered Tool Providers */ getProviderCount(): number; /** * Check if Tool Providers are registered */ hasProviders(): boolean; /** * Check if a specific tool is available * * @param toolName - Name of the tool to check */ hasTool(toolName: string): boolean; /** * Clean up resources for all tool providers */ close(): Promise<void>; } /** * System message management class * Manages system prompts and system messages. */ declare class SystemMessageManager { private systemPrompt?; private systemMessages?; /** * Set a single system prompt * * @param prompt - System prompt content */ setSystemPrompt(prompt: string): void; /** * Set multiple system messages * * @param messages - Array of system messages */ setSystemMessages(messages: Message[]): void; /** * Add a new system message to existing system messages * * @param content - Content of the system message to add */ addSystemMessage(content: string): void; /** * Get the current system prompt */ getSystemPrompt(): string | undefined; /** * Get the current system messages */ getSystemMessages(): Message[] | undefined; /** * Check if system messages are configured */ hasSystemMessages(): boolean; /** * Clear system messages */ clear(): void; } /** * Function call mode */ type FunctionCallMode = 'auto' | 'force' | 'disabled'; /** * Function call configuration interface */ interface FunctionCallConfig { defaultMode?: FunctionCallMode; maxCalls?: number; timeout?: number; allowedFunctions?: string[]; } /** * Function call management class * Manages function call settings and modes. */ declare class FunctionCallManager { private config; constructor(initialConfig?: FunctionCallConfig); /** * Set function call mode * * @param mode - Function call mode ('auto', 'force', 'disabled') */ setFunctionCallMode(mode: FunctionCallMode): void; /** * Configure function call settings * * @param config - Function call configuration options */ configure(config: { mode?: FunctionCallMode; maxCalls?: number; timeout?: number; allowedFunctions?: string[]; }): void; /** * Get current function call mode */ getDefaultMode(): FunctionCallMode; /** * Get maximum call count */ getMaxCalls(): number; /** * Get timeout setting */ getTimeout(): number; /** * Get allowed functions list */ getAllowedFunctions(): string[] | undefined; /** * Get complete configuration */ getConfig(): FunctionCallConfig; /** * Check if a specific function is allowed * * @param functionName - Function name to check */ isFunctionAllowed(functionName: string): boolean; } /** * Analytics Manager class * Manages analytics data collection (requests and token usage history) */ declare class AnalyticsManager { private requestCount; private totalTokensUsed; private tokenUsageHistory; /** * Record a new request and token usage * @param tokensUsed - Number of tokens used in this request * @param provider - AI provider name * @param model - Model name */ recordRequest(tokensUsed: number, provider: string, model: string): void; /** * Get total number of requests made */ getRequestCount(): number; /** * Get total number of tokens used */ getTotalTokensUsed(): number; /** * Get detailed analytics data */ getAnalytics(): { requestCount: number; totalTokensUsed: number; averageTokensPerRequest: number; tokenUsageHistory: { timestamp: Date; tokens: number; provider: string; model: string; }[]; }; /** * Reset all analytics data */ reset(): void; /** * Get token usage for a specific time period * @param startDate - Start date for the period * @param endDate - End date for the period (optional, defaults to now) */ getTokenUsageByPeriod(startDate: Date, endDate?: Date): { totalTokens: number; requestCount: number; usageHistory: { timestamp: Date; tokens: number; provider: string; model: string; }[]; }; } /** * Request Limit Manager class * Manages request count and token limits with default values */ declare class RequestLimitManager { private maxTokens; private maxRequests; private currentTokensUsed; private currentRequestCount; constructor(maxTokens?: number, maxRequests?: number); /** * Set maximum token limit (0 = unlimited) */ setMaxTokens(limit: number): void; /** * Set maximum request limit (0 = unlimited) */ setMaxRequests(limit: number): void; /** * Get current maximum token limit */ getMaxTokens(): number; /** * Get current maximum request limit */ getMaxRequests(): number; /** * Check if adding estimated tokens would exceed the limit * @param estimatedTokens - Estimated number of tokens to add * @throws Error if token limit would be exceeded */ checkEstimatedTokenLimit(estimatedTokens: number): void; /** * Check if adding new tokens would exceed the limit * @param tokensToAdd - Number of tokens to add * @throws Error if token limit would be exceeded */ checkTokenLimit(tokensToAdd: number): void; /** * Check if adding a new request would exceed the request limit * @throws Error if request limit would be exceeded */ checkRequestLimit(): void; /** * Record a successful request with token usage * @param tokensUsed - Number of tokens used in this request */ recordRequest(tokensUsed: number): void; /** * Get current token usage */ getCurrentTokensUsed(): number; /** * Get current request count */ getCurrentRequestCount(): number; /** * Get remaining tokens (undefined if unlimited) */ getRemainingTokens(): number | undefined; /** * Get remaining requests (undefined if unlimited) */ getRemainingRequests(): number | undefined; /** * Check if tokens are unlimited */ isTokensUnlimited(): boolean; /** * Check if requests are unlimited */ isRequestsUnlimited(): boolean; /** * Reset usage counters (but keep limits) */ reset(): void; /** * Get comprehensive limit information */ getLimitInfo(): { maxTokens: number; maxRequests: number; currentTokensUsed: number; currentRequestCount: number; remainingTokens?: number; remainingRequests?: number; isTokensUnlimited: boolean; isRequestsUnlimited: boolean; }; } /** * Configuration options for initializing Robota instance * * @public * @interface RobotaOptions */ interface RobotaOptions { /** * Tool providers that supply tools like MCP, OpenAPI, ZodFunction, etc. * * @see {@link ../../../apps/examples/02-functions | Function Examples} */ toolProviders?: ToolProvider[]; /** * AI providers - Register multiple AI providers by name * * @see {@link ../../../apps/examples/03-integrations | Provider Integration Examples} */ aiProviders?: Record<string, AIProvider>; /** * Current AI provider name to use from registered providers * Must match a key in aiProviders */ currentProvider?: string; /** * Current model name to use with the selected provider */ currentModel?: string; /** * Model temperature for response generation (0.0 to 2.0) * Lower values make responses more focused and deterministic * * @defaultValue undefined (uses provider default) */ temperature?: number; /** * Maximum number of tokens for generated responses * * @defaultValue undefined (uses provider default) */ maxTokens?: number; /** * System prompt to set context for AI responses * Will be converted to a system message */ systemPrompt?: string; /** * Array of system messages for more complex system configuration * Use this instead of systemPrompt for multiple system messages */ systemMessages?: Message[]; /** * Custom conversation history implementation * * @defaultValue SimpleConversationHistory instance */ conversationHistory?: ConversationHistory; /** * Configuration for function/tool calling behavior */ functionCallConfig?: FunctionCallConfig; /** * Callback function executed when a tool is called * Useful for monitoring, logging, or custom handling * * @param toolName - Name of the called tool * @param params - Parameters passed to the tool * @param result - Result returned by the tool */ onToolCall?: (toolName: string, params: any, result: any) => void; /** * Custom logger implementation * * @defaultValue console */ logger?: Logger; /** * Enable debug mode for detailed logging * * @defaultValue false */ debug?: boolean; /** * Maximum token limit across all requests (0 = unlimited) * Used for budget control and preventing excessive usage * * @defaultValue 4096 */ maxTokenLimit?: number; /** * Maximum request limit (0 = unlimited) * Used for rate limiting and controlling API usage * * @defaultValue 25 */ maxRequestLimit?: number; /** * Legacy option: Single tool provider (use toolProviders array instead) * @deprecated Use toolProviders array instead */ provider?: ToolProvider; } /** * Main Robota class for AI agent interaction with Facade pattern * * Provides a high-level interface for AI conversations with support for: * - Multiple AI providers (OpenAI, Anthropic, Google, etc.) * - Tool/function calling * - Conversation history management * - Request limiting and analytics * - Streaming responses * * Uses Facade pattern to expose functional managers while keeping core interface simple. * Access detailed functionality through the exposed managers: * - ai: AI provider management * - system: System message management * - functions: Function/tool call management * - analytics: Usage analytics and metrics * - tools: Tool provider management * - conversation: Conversation history management * * @see {@link ../../../apps/examples/01-basic | Basic Usage Examples} * @see {@link ../../../apps/examples/05-advanced | Advanced Configuration Examples} * * @public */ declare class Robota implements RobotaComplete { /** @internal Configuration manager handling all settings */ private readonly configManager; /** @internal Service handling execution logic */ private readonly executionService; /** @internal Conversation service for high-level operations */ private readonly conversationService; /** @internal Token analysis utilities */ private readonly tokenAnalyzer; /** @internal Conversation history storage */ private readonly conversationHistory; /** @internal Optional tool call callback */ private readonly onToolCall?; /** @internal Logger instance */ private readonly logger; /** @internal Debug mode flag */ private readonly debug; /** * AI provider management - register providers, set current provider/model, configure parameters * * @see {@link AIProviderManager} */ readonly ai: AIProviderManager; /** * System message management - set prompts, manage system instructions * * @see {@link SystemMessageManager} */ readonly system: SystemMessageManager; /** * Function/tool call management - configure modes, timeouts, allowed functions * * @see {@link FunctionCallManager} */ readonly functions: FunctionCallManager; /** * Analytics and metrics - track usage, performance, costs * * @see {@link AnalyticsManager} */ readonly analytics: AnalyticsManager; /** * Tool provider management - register and manage tool providers * * @see {@link ToolProviderManager} */ readonly tools: ToolProviderManager; /** * Request and token limits - control usage and costs * * @see {@link RequestLimitManager} */ readonly limits: RequestLimitManager; /** * Conversation history - direct access to conversation management * * @see {@link ConversationHistory} */ readonly conversation: ConversationHistory; constructor(options?: RobotaOptions); /** * Apply configuration from options * @internal */ private applyConfiguration; /** * Execute a prompt and get a text response * * Main method for running AI conversations. Handles the full pipeline: * - Context preparation with conversation history * - AI provider execution with tool support * - Response processing and history updates * - Analytics and limit tracking * * @param prompt - The user prompt to process * @param options - Optional configuration for this specific request * @returns Promise resolving to the AI's text response * * @throws {Error} When no AI provider is configured * @throws {Error} When rate limits are exceeded * @throws {Error} When AI provider fails * * @see {@link ../../../apps/examples/01-basic/01-simple-conversation.ts | Basic Usage} */ run(prompt: string, options?: RunOptions): Promise<string>; /** * Execute a prompt and get a streaming response * * Similar to run() but returns an async iterator for streaming responses. * Useful for real-time display of AI responses. * * @param prompt - The user prompt to process * @param options - Optional configuration for this specific request * @returns Promise resolving to an async iterator of response chunks * * @throws {Error} When no AI provider is configured * @throws {Error} When rate limits are exceeded * @throws {Error} When AI provider fails * * @see {@link ../../../apps/examples/01-basic/01-simple-conversation.ts | Streaming Example} */ runStream(prompt: string, options?: RunOptions): Promise<AsyncIterable<StreamingResponseChunk>>; /** * Call a specific tool directly by name * * Bypasses AI provider and calls a tool directly with provided parameters. * Useful for testing tools or direct tool execution. * * @param toolName - Name of the tool to call * @param parameters - Parameters to pass to the tool * @returns Promise resolving to the tool's result * * @throws {Error} When tool is not found * @throws {Error} When tool execution fails */ callTool(toolName: string, parameters: Record<string, any>): Promise<any>; /** * Get list of available tools * * @returns Array of available tool definitions */ getAvailableTools(): any[]; /** * Clear all conversation history */ clearConversationHistory(): void; /** * Clean up resources and close connections * * Should be called when done using the Robota instance to properly * clean up any resources, close connections, etc. */ close(): Promise<void>; } /** * Base abstract class for AI providers * * Provides common functionality and standardized interfaces for all AI providers. * Handles tool calling support, message filtering, and response parsing. */ declare abstract class BaseAIProvider implements AIProvider { /** * Provider identifier name */ abstract readonly name: string; /** * Provider configuration options */ abstract readonly options: any; /** * Send a chat request and receive a complete response */ abstract chat(model: string, context: Context, options?: any): Promise<ModelResponse>; /** * Send a streaming chat request and receive response chunks */ abstract chatStream(model: string, context: Context, options?: any): AsyncGenerator<StreamingResponseChunk, void, unknown>; /** * Close the provider and clean up resources */ abstract close(): Promise<void>; /** * Configure tools for the API request * * Each provider can override this to implement provider-specific tool configuration. * By default, returns undefined (no tools). * * @param tools - Array of function schemas * @returns Provider-specific tool configuration or undefined */ protected configureTools(tools?: FunctionSchema[]): any; /** * Validate context object * * Common validation logic for all providers. * * @param context - Context object to validate * @throws {Error} When context is invalid */ protected validateContext(context: Context): void; /** * Handle API errors with consistent error formatting * * @param error - Original error from API call * @param operation - Operation that failed (e.g., 'chat', 'chatStream') * @throws {Error} Formatted error with provider context */ protected handleApiError(error: any, operation: string): never; } /** * Conversation service class * Handles conversation processing with AI. */ declare class ConversationService { private temperature?; private maxTokens?; private logger; private debug; constructor(temperature?: number, maxTokens?: number, logger?: Logger, debug?: boolean); /** * Prepare context * * @param conversationHistory - ConversationHistory instance * @param systemPrompt - Optional system prompt * @param systemMessages - System messages * @param options - Run options */ prepareContext(conversationHistory: ConversationHistory, systemPrompt?: string, systemMessages?: Message[], options?: RunOptions): Context; /** * Generate response * * @param aiProvider - AI provider * @param model - Model name * @param context - Conversation context * @param options - Run options * @param availableTools - Available tools * @param onToolCall - Tool call function * @param conversationHistory - Conversation history to store messages sequentially */ generateResponse(aiProvider: AIProvider, model: string, context: Context, options?: RunOptions, availableTools?: any[], onToolCall?: (toolName: string, params: any) => Promise<any>, conversationHistory?: ConversationHistory): Promise<ModelResponse>; /** * Handle function call (simplified - only tool_calls format) */ private handleFunctionCall; /** * Handle new tool_calls format (OpenAI tool calling) */ private handleToolCalls; /** * Generate streaming response */ generateStream(aiProvider: AIProvider, model: string, context: Context, options?: RunOptions, availableTools?: any[]): Promise<AsyncIterable<StreamingResponseChunk>>; } /** * Function to remove undefined values from object * * @param obj Object to clean * @returns Object with undefined values removed */ declare function removeUndefined<T extends Record<string, unknown>>(obj: T): T; /** * Logger utility (console.log replacement) */ declare const logger: { info: (...args: unknown[]) => void; warn: (...args: unknown[]) => void; error: (...args: unknown[]) => void; }; /** * Helper function to convert UniversalMessage to basic Message format * Can be used in AI Provider adapters. */ declare function convertUniversalToBaseMessage(universalMessage: UniversalMessage): Message; /** * Helper function to convert UniversalMessage array to basic Message array */ declare function convertUniversalToBaseMessages(universalMessages: UniversalMessage[]): Message[]; /** * Message conversion interface that AI Provider adapters should implement */ interface MessageAdapter<T = any> { /** * Convert UniversalMessage to specific AI Provider format */ convertFromUniversal(universalMessage: UniversalMessage): T; /** * Convert UniversalMessage array to specific AI Provider format array */ convertFromUniversalMessages(universalMessages: UniversalMessage[]): T[]; } export { type AIProvider, AIProviderManager, AnalyticsManager, type AssistantMessage, BaseAIProvider, type BaseMessage, type Context, type ConversationHistory, ConversationService, type FunctionCallConfig, FunctionCallManager, type FunctionCallMode, type Logger, type Message, type MessageAdapter, type MessageRole, type ModelResponse, PersistentSystemConversationHistory, type ProviderOptions, Robota, type RobotaComplete, type RobotaConfigurable, type RobotaCore, type RobotaOptions, type RunOptions, SimpleConversationHistory, type StreamingResponseChunk, type SystemMessage, SystemMessageManager, type ToolMessage, ToolProviderManager, type UniversalMessage, type UniversalMessageRole, type UserMessage, convertUniversalToBaseMessage, convertUniversalToBaseMessages, isAssistantMessage, isSystemMessage, isToolMessage, isUserMessage, logger, removeUndefined };