Class: Robota
Main AI agent implementation for the Robota SDK.
Robota is a comprehensive AI agent that integrates multiple AI providers, tools, and plugins into a unified conversational interface. Each instance is completely independent with its own managers and services - NO GLOBAL SINGLETONS are used.
Key Features:
- Multiple AI provider support (OpenAI, Anthropic, Google)
- Function/tool calling with Zod schema validation
- Plugin system for extensible functionality
- Streaming response support
- Conversation history management
- Instance-specific resource management
Implements
AgentInterface
Example
import { Robota } from '@robota-sdk/agents';
import { OpenAIProvider } from '@robota-sdk/openai';
const robota = new Robota({
name: 'MyAgent',
aiProviders: [new OpenAIProvider({ apiKey: 'sk-...' })],
defaultModel: {
provider: 'openai',
model: 'gpt-4'
}
});
const response = await robota.run('Hello, how are you?');
console.log(response);
Example
import { Robota, LoggingPlugin, UsagePlugin } from '@robota-sdk/agents';
import { weatherTool, calculatorTool } from './my-tools';
const robota = new Robota({
name: 'AdvancedAgent',
aiProviders: [openaiProvider],
defaultModel: {
provider: 'openai',
model: 'gpt-4'
},
tools: [weatherTool, calculatorTool],
plugins: [
new LoggingPlugin({ level: 'info' }),
new UsagePlugin({ trackTokens: true })
]
});
const response = await robota.run('What\'s the weather in Tokyo?');
Example
for await (const chunk of robota.runStream('Tell me a story')) {
process.stdout.write(chunk);
}
Hierarchy
BaseAgent
<AgentConfig
,RunOptions
,Message
>↳
Robota
Implements
Table of contents
Constructors
Properties
Methods
- configure
- dispose
- run
- runStream
- getHistory
- clearHistory
- addPlugin
- removePlugin
- getPlugin
- getPlugins
- getPluginNames
- registerModule
- unregisterModule
- getModule
- getModulesByType
- getModules
- getModuleNames
- hasModule
- executeModule
- getModuleStats
- setModel
- getModel
- registerTool
- unregisterTool
- getConfig
- getStats
- destroy
Constructors
constructor
• new Robota(config
): Robota
Creates a new Robota agent instance with the new aiProviders array design.
The constructor performs synchronous initialization and validation. Async initialization (AI provider setup, tool registration) is deferred until the first run() call for optimal performance.
Parameters
Name | Type | Description |
---|---|---|
config | AgentConfig | Configuration options for the agent |
Returns
Throws
When required configuration is missing or invalid
Throws
When configuration values are invalid
Example
const robota = new Robota({
name: 'CustomerSupport',
aiProviders: [
new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY }),
new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY })
],
defaultModel: {
provider: 'openai',
model: 'gpt-4',
temperature: 0.7
},
tools: [emailTool, ticketTool],
plugins: [new LoggingPlugin(), new ErrorHandlingPlugin()]
});
Overrides
Defined in
packages/agents/src/agents/robota.ts:176
Properties
name
• Readonly
name: string
The name of this agent instance
Defined in
packages/agents/src/agents/robota.ts:122
version
• Readonly
version: string
= '1.0.0'
The version of the Robota agent implementation
Defined in
packages/agents/src/agents/robota.ts:124
Methods
configure
▸ configure(config
): Promise
<void
>
Configure the agent with type-safe configuration
Parameters
Name | Type |
---|---|
config | AgentConfig |
Returns
Promise
<void
>
Implementation of
Inherited from
Defined in
packages/agents/src/abstracts/base-agent.ts:28
dispose
▸ dispose(): Promise
<void
>
Cleanup resources
Returns
Promise
<void
>
Inherited from
Defined in
packages/agents/src/abstracts/base-agent.ts:86
run
▸ run(input
, options?
): Promise
<string
>
Execute a conversation turn with the AI agent.
This is the primary method for interacting with the agent. It processes user input, manages conversation history, executes any required tools, and returns the AI response. The method automatically initializes the agent on first use.
Parameters
Name | Type | Description |
---|---|---|
input | string | The user's message or prompt to send to the AI |
options | RunOptions | Optional configuration for this specific execution |
Returns
Promise
<string
>
Promise that resolves to the AI's response as a string
Throws
When the agent configuration is invalid
Throws
When the AI provider encounters an error
Throws
When a tool execution fails
Example
const response = await robota.run('Hello, how are you?');
console.log(response); // "Hello! I'm doing well, thank you for asking..."
Example
const response = await robota.run('Analyze this data', {
sessionId: 'user-123',
userId: 'john.doe',
metadata: { source: 'web-app', priority: 'high' }
});
Example
try {
const response = await robota.run('Complex request');
} catch (error) {
if (error instanceof ToolExecutionError) {
console.error('Tool failed:', error.toolName, error.message);
}
}
Implementation of
Overrides
Defined in
packages/agents/src/agents/robota.ts:442
runStream
▸ runStream(input
, options?
): AsyncGenerator
<string
, void
, undefined
>
Execute a conversation turn with streaming response.
Similar to run() but returns an async generator that yields response chunks as they arrive from the AI provider. This enables real-time streaming of the AI's response for better user experience.
Parameters
Name | Type | Description |
---|---|---|
input | string | The user's message or prompt to send to the AI |
options | RunOptions | Optional configuration for this specific execution |
Returns
AsyncGenerator
<string
, void
, undefined
>
AsyncGenerator that yields string chunks of the AI response
Throws
When the agent configuration is invalid
Throws
When the AI provider encounters an error
Throws
When a tool execution fails
Example
for await (const chunk of robota.runStream('Tell me a story')) {
process.stdout.write(chunk);
}
console.log('\n'); // New line after story
Example
let fullResponse = '';
for await (const chunk of robota.runStream('Explain quantum computing')) {
fullResponse += chunk;
updateUI(chunk); // Update UI in real-time
}
console.log('Complete response:', fullResponse);
Example
try {
for await (const chunk of robota.runStream('Complex request')) {
handleChunk(chunk);
}
} catch (error) {
console.error('Streaming failed:', error.message);
}
Implementation of
Overrides
Defined in
packages/agents/src/agents/robota.ts:541
getHistory
▸ getHistory(): Message
[]
Get the conversation history for this agent instance.
Returns an array of messages representing the complete conversation history for this agent's conversation session. The history includes user messages, assistant responses, and tool call results.
Returns
Message
[]
Array of Message objects representing the conversation history
Example
await robota.run('What is 2 + 2?');
await robota.run('What about 3 + 3?');
const history = robota.getHistory();
console.log(history.length); // 4 (2 user messages, 2 assistant responses)
console.log(history[0].role); // 'user'
console.log(history[0].content); // 'What is 2 + 2?'
Implementation of
Overrides
Defined in
packages/agents/src/agents/robota.ts:607
clearHistory
▸ clearHistory(): void
Clear the conversation history for this agent instance.
Removes all messages from the conversation history, starting fresh. This does not affect the agent's configuration or other state.
Returns
void
Example
await robota.run('First message');
console.log(robota.getHistory().length); // 2 (user + assistant)
robota.clearHistory();
console.log(robota.getHistory().length); // 0
Implementation of
Overrides
Defined in
packages/agents/src/agents/robota.ts:636
addPlugin
▸ addPlugin(plugin
): void
Add a plugin to the agent at runtime.
Plugins provide extensible functionality through lifecycle hooks. This method allows dynamic addition of plugins after agent creation.
Parameters
Name | Type | Description |
---|---|---|
plugin | BasePlugin <BasePluginOptions , PluginStats > | The plugin instance to add |
Returns
void
Example
import { UsagePlugin, PerformancePlugin } from '@robota-sdk/agents';
const robota = new Robota(config);
// Add plugins dynamically
robota.addPlugin(new UsagePlugin({ trackTokens: true }));
robota.addPlugin(new PerformancePlugin({ trackMemory: true }));
Defined in
packages/agents/src/agents/robota.ts:661
removePlugin
▸ removePlugin(pluginName
): boolean
Remove a plugin from the agent by name.
Parameters
Name | Type | Description |
---|---|---|
pluginName | string | The name of the plugin to remove |
Returns
boolean
true if the plugin was found and removed, false otherwise
Example
const removed = robota.removePlugin('usage-plugin');
if (removed) {
console.log('Plugin removed successfully');
} else {
console.log('Plugin not found');
}
Defined in
packages/agents/src/agents/robota.ts:682
getPlugin
▸ getPlugin<T
>(pluginName
): null
| T
Get a specific plugin by name with type safety.
Type parameters
Name | Type | Description |
---|---|---|
T | extends BasePlugin <BasePluginOptions , PluginStats > = BasePlugin <BasePluginOptions , PluginStats > | The expected plugin type extending BasePlugin |
Parameters
Name | Type | Description |
---|---|---|
pluginName | string | The name of the plugin to retrieve |
Returns
null
| T
The plugin instance if found, null otherwise
Example
import { UsagePlugin } from '@robota-sdk/agents';
const usagePlugin = robota.getPlugin\<UsagePlugin\>('usage-plugin');
if (usagePlugin) {
const stats = usagePlugin.getUsageStats();
console.log('Token usage:', stats.totalTokens);
}
Defined in
packages/agents/src/agents/robota.ts:708
getPlugins
▸ getPlugins(): BasePlugin
<BasePluginOptions
, PluginStats
>[]
Get all registered plugins.
Returns
BasePlugin
<BasePluginOptions
, PluginStats
>[]
Array of all currently registered plugin instances
Example
const plugins = robota.getPlugins();
console.log(`Agent has ${plugins.length} plugins registered`);
plugins.forEach(plugin => {
console.log(`- ${plugin.name} (${plugin.version})`);
});
Defined in
packages/agents/src/agents/robota.ts:726
getPluginNames
▸ getPluginNames(): string
[]
Get all registered plugin names
Returns
string
[]
Defined in
packages/agents/src/agents/robota.ts:733
registerModule
▸ registerModule(module
, options?
): Promise
<void
>
Register a new module with the agent
Parameters
Name | Type | Description |
---|---|---|
module | BaseModule <BaseModuleOptions , ModuleStats > | The module instance to register |
options? | Object | Registration options |
options.autoInitialize? | boolean | - |
options.validateDependencies? | boolean | - |
Returns
Promise
<void
>
Defined in
packages/agents/src/agents/robota.ts:749
unregisterModule
▸ unregisterModule(moduleName
): Promise
<boolean
>
Unregister a module from the agent
Parameters
Name | Type | Description |
---|---|---|
moduleName | string | Name of the module to unregister |
Returns
Promise
<boolean
>
True if module was unregistered, false if not found
Defined in
packages/agents/src/agents/robota.ts:768
getModule
▸ getModule<T
>(moduleName
): null
| T
Get a module by name with type safety
Type parameters
Name | Type |
---|---|
T | extends BaseModule <BaseModuleOptions , ModuleStats > = BaseModule <BaseModuleOptions , ModuleStats > |
Parameters
Name | Type | Description |
---|---|---|
moduleName | string | Name of the module to retrieve |
Returns
null
| T
The module instance or null if not found
Defined in
packages/agents/src/agents/robota.ts:787
getModulesByType
▸ getModulesByType<T
>(moduleType
): T
[]
Get modules by type
Type parameters
Name | Type |
---|---|
T | extends BaseModule <BaseModuleOptions , ModuleStats > = BaseModule <BaseModuleOptions , ModuleStats > |
Parameters
Name | Type | Description |
---|---|---|
moduleType | string | Type of modules to retrieve |
Returns
T
[]
Array of modules matching the type
Defined in
packages/agents/src/agents/robota.ts:799
getModules
▸ getModules(): BaseModule
<BaseModuleOptions
, ModuleStats
>[]
Get all registered modules
Returns
BaseModule
<BaseModuleOptions
, ModuleStats
>[]
Array of all registered modules
Defined in
packages/agents/src/agents/robota.ts:810
getModuleNames
▸ getModuleNames(): string
[]
Get all registered module names
Returns
string
[]
Array of module names
Defined in
packages/agents/src/agents/robota.ts:821
hasModule
▸ hasModule(moduleName
): boolean
Check if a module is registered
Parameters
Name | Type | Description |
---|---|---|
moduleName | string | Name of the module to check |
Returns
boolean
True if module is registered
Defined in
packages/agents/src/agents/robota.ts:833
executeModule
▸ executeModule(moduleName
, context
): Promise
<{ success
: boolean
; data?
: ModuleResultData
; error?
: Error
; duration?
: number
}>
Execute a module by name
Parameters
Name | Type | Description |
---|---|---|
moduleName | string | Name of the module to execute |
context | Object | Execution context |
context.executionId? | string | - |
context.sessionId? | string | - |
context.userId? | string | - |
context.metadata? | Record <string , string | number | boolean | Date > | - |
Returns
Promise
<{ success
: boolean
; data?
: ModuleResultData
; error?
: Error
; duration?
: number
}>
Module execution result
Defined in
packages/agents/src/agents/robota.ts:846
getModuleStats
▸ getModuleStats(moduleName
): null
| { totalExecutions
: number
; successfulExecutions
: number
; failedExecutions
: number
; averageExecutionTime
: number
; lastExecutionTime?
: Date
}
Get module execution statistics
Parameters
Name | Type | Description |
---|---|---|
moduleName | string | Name of the module |
Returns
null
| { totalExecutions
: number
; successfulExecutions
: number
; failedExecutions
: number
; averageExecutionTime
: number
; lastExecutionTime?
: Date
}
Module statistics or null if not found
Defined in
packages/agents/src/agents/robota.ts:865
setModel
▸ setModel(modelConfig
): void
Set the current model configuration (complete replacement).
Updates the current AI provider, model, and related settings. This completely replaces the current model configuration with the new values.
Parameters
Name | Type | Description |
---|---|---|
modelConfig | Object | New model configuration |
modelConfig.provider | string | - |
modelConfig.model | string | - |
modelConfig.temperature? | number | - |
modelConfig.maxTokens? | number | - |
modelConfig.topP? | number | - |
modelConfig.systemMessage? | string | - |
Returns
void
Throws
When the provider is not available
Example
// Switch to a different provider and model
robota.setModel({
provider: 'anthropic',
model: 'claude-3-opus',
temperature: 0.9,
maxTokens: 4000
});
// Simple model change
robota.setModel({
provider: 'openai',
model: 'gpt-4-turbo'
});
Defined in
packages/agents/src/agents/robota.ts:920
getModel
▸ getModel(): Object
Get the current model configuration.
Returns the current AI provider, model, and related settings.
Returns
Object
Current model configuration
Name | Type |
---|---|
provider | string |
model | string |
temperature? | number |
maxTokens? | number |
topP? | number |
systemMessage? | string |
Example
const current = robota.getModel();
console.log(`Current: ${current.provider}/${current.model}`);
console.log(`Temperature: ${current.temperature}`);
console.log(`Max tokens: ${current.maxTokens}`);
Defined in
packages/agents/src/agents/robota.ts:992
registerTool
▸ registerTool(tool
): void
Register a new tool for function calling.
Adds a tool that the AI can call during conversations. The tool's schema defines its name, description, and parameters for the AI to understand.
Parameters
Name | Type | Description |
---|---|---|
tool | BaseTool <BaseToolParameters , ToolResult > | The tool instance to register |
Returns
void
Example
import { BaseTool } from '@robota-sdk/agents';
class WeatherTool extends BaseTool {
name = 'get_weather';
description = 'Get current weather for a location';
get schema() {
return {
name: this.name,
description: this.description,
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name' }
},
required: ['location']
}
};
}
async execute(params: { location: string }) {
// Implementation here
return { temperature: 22, condition: 'sunny' };
}
}
robota.registerTool(new WeatherTool());
Defined in
packages/agents/src/agents/robota.ts:1072
unregisterTool
▸ unregisterTool(toolName
): void
Unregister a tool by name.
Removes a previously registered tool, making it unavailable for future AI calls.
Parameters
Name | Type | Description |
---|---|---|
toolName | string | Name of the tool to unregister |
Returns
void
Example
robota.unregisterTool('weather-tool');
const stats = robota.getStats();
console.log('Remaining tools:', stats.tools);
Defined in
packages/agents/src/agents/robota.ts:1112
getConfig
▸ getConfig(): AgentConfig
Get the current agent configuration.
Returns a copy of the current configuration object. Modifications to the returned object do not affect the agent - use updateConfig() to make changes.
Returns
Copy of the current AgentConfig
Example
const config = robota.getConfig();
console.log('Current model:', config.currentModel);
console.log('Available providers:', Object.keys(config.aiProviders || {}));
Defined in
packages/agents/src/agents/robota.ts:1132
getStats
▸ getStats(): Object
Get comprehensive agent statistics including providers, tools, plugins, modules, and performance data.
Returns
Object
Object containing all agent statistics and metadata
Name | Type |
---|---|
name | string |
version | string |
conversationId | string |
providers | string [] |
currentProvider | null | string |
tools | string [] |
plugins | string [] |
modules | string [] |
historyLength | number |
historyStats | AgentStatsMetadata |
uptime | number |
Example
const stats = robota.getStats();
console.log(`Agent: ${stats.name} v${stats.version}`);
console.log(`Uptime: ${stats.uptime}ms`);
console.log(`Providers: ${stats.providers.join(', ')}`);
console.log(`Tools: ${stats.tools.join(', ')}`);
console.log(`Plugins: ${stats.plugins.join(', ')}`);
console.log(`Modules: ${stats.modules.join(', ')}`);
console.log(`Messages: ${stats.historyLength}`);
Defined in
packages/agents/src/agents/robota.ts:1153
destroy
▸ destroy(): Promise
<void
>
Clean up and dispose of the agent instance.
This method properly cleans up all resources, managers, and services to prevent memory leaks and ensure graceful shutdown.
Returns
Promise
<void
>
Example
// Clean shutdown
await robota.destroy();
console.log('Agent destroyed');