Skip to content

agents / Exports / Robota

Class: Robota

Core 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

typescript
import { Robota } from '@robota-sdk/agent-core';
import { OpenAIProvider } from '@robota-sdk/agent-provider-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

typescript
import { Robota, LoggingPlugin, UsagePlugin } from '@robota-sdk/agent-core';
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

typescript
for await (const chunk of robota.runStream('Tell me a story')) {
  process.stdout.write(chunk);
}

Hierarchy

Implements

Table of contents

Constructors

Properties

Methods

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

NameTypeDescription
configIAgentConfigConfiguration options for the agent

Returns

Robota

Throws

When required configuration is missing or invalid

Throws

When configuration values are invalid

Example

typescript
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

AbstractAgent.constructor

Defined in

packages/agents/src/core/robota.ts:194

Properties

name

Readonly name: string

The name of this agent instance

Defined in

packages/agents/src/core/robota.ts:134


version

Readonly version: string = '1.0.0'

The version of the Robota agent implementation

Defined in

packages/agents/src/core/robota.ts:136

Methods

configure

configure(config): Promise<void>

Configure the agent with type-safe configuration

Parameters

NameType
configIAgentConfig

Returns

Promise<void>

Implementation of

IAgent.configure

Inherited from

AbstractAgent.configure

Defined in

packages/agents/src/abstracts/abstract-agent.ts:29


dispose

dispose(): Promise<void>

Cleanup resources

Returns

Promise<void>

Inherited from

AbstractAgent.dispose

Defined in

packages/agents/src/abstracts/abstract-agent.ts:87


updateTools

updateTools(next): Promise<{ version: number }>

Update tools for this agent instance. Rebuilds the Tools registry atomically and emits CONFIG_UPDATED event.

Parameters

NameType
nextAbstractTool<TToolParameters, IToolResult>[]

Returns

Promise<{ version: number }>

Defined in

packages/agents/src/core/robota.ts:276


updateConfiguration

updateConfiguration(patch): Promise<{ version: number }>

Update configuration partially. Currently supports tools.

Parameters

NameType
patchPartial<IAgentConfig>

Returns

Promise<{ version: number }>

Defined in

packages/agents/src/core/robota.ts:335


getConfiguration

getConfiguration(): Promise<{ version: number ; tools: { name: string ; parameters?: string[] }[] ; updatedAt: number ; metadata?: Record<string, unknown> }>

Read-only configuration overview for UI.

Returns

Promise<{ version: number ; tools: { name: string ; parameters?: string[] }[] ; updatedAt: number ; metadata?: Record<string, unknown> }>

Defined in

packages/agents/src/core/robota.ts:346


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

NameTypeDescription
inputstringThe user's message or prompt to send to the AI
optionsIRunOptionsOptional 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

typescript
const response = await robota.run('Hello, how are you?');
console.log(response); // "Hello! I'm doing well, thank you for asking..."

Example

typescript
const response = await robota.run('Analyze this data', {
  sessionId: 'user-123',
  userId: 'john.doe',
  metadata: { source: 'web-app', priority: 'high' },
});

Example

typescript
try {
  const response = await robota.run('Complex request');
} catch (error) {
  if (error instanceof ToolExecutionError) {
    console.error('Tool failed:', error.toolName, error.message);
  }
}

Implementation of

IAgent.run

Overrides

AbstractAgent.run

Defined in

packages/agents/src/core/robota.ts:603


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

NameTypeDescription
inputstringThe user's message or prompt to send to the AI
optionsIRunOptionsOptional 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

typescript
for await (const chunk of robota.runStream('Tell me a story')) {
  process.stdout.write(chunk);
}
console.log('\n'); // New line after story

Example

typescript
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

typescript
try {
  for await (const chunk of robota.runStream('Complex request')) {
    handleChunk(chunk);
  }
} catch (error) {
  console.error('Streaming failed:', error.message);
}

Implementation of

IAgent.runStream

Overrides

AbstractAgent.runStream

Defined in

packages/agents/src/core/robota.ts:716


getHistory

getHistory(): TUniversalMessage[]

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

TUniversalMessage[]

Array of TUniversalMessage objects representing the conversation history

Example

typescript
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

IAgent.getHistory

Overrides

AbstractAgent.getHistory

Defined in

packages/agents/src/core/robota.ts:792


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

typescript
await robota.run('First message');
console.log(robota.getHistory().length); // 2 (user + assistant)

robota.clearHistory();
console.log(robota.getHistory().length); // 0

Implementation of

IAgent.clearHistory

Overrides

AbstractAgent.clearHistory

Defined in

packages/agents/src/core/robota.ts:821


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

NameTypeDescription
pluginAbstractPlugin<IPluginOptions, IPluginStats>The plugin instance to add

Returns

void

Example

typescript
import { UsagePlugin, PerformancePlugin } from '@robota-sdk/agent-core';

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/core/robota.ts:846


removePlugin

removePlugin(pluginName): boolean

Remove a plugin from the agent by name.

Parameters

NameTypeDescription
pluginNamestringThe name of the plugin to remove

Returns

boolean

true if the plugin was found and removed, false otherwise

Example

typescript
const removed = robota.removePlugin('usage-plugin');
if (removed) {
  console.log('Plugin removed successfully');
} else {
  console.log('Plugin not found');
}

Defined in

packages/agents/src/core/robota.ts:867


getPlugin

getPlugin<T>(pluginName): null | T

Get a specific plugin by name with type safety.

Type parameters

NameTypeDescription
Textends AbstractPlugin<IPluginOptions, IPluginStats> = AbstractPlugin<IPluginOptions, IPluginStats>The expected plugin type extending AbstractPlugin

Parameters

NameTypeDescription
pluginNamestringThe name of the plugin to retrieve

Returns

null | T

The plugin instance if found, null otherwise

Example

typescript
import { UsagePlugin } from '@robota-sdk/agent-core';

const usagePlugin = robota.getPlugin\<UsagePlugin\>('usage-plugin');
if (usagePlugin) {
  const stats = usagePlugin.getUsageStats();
  console.log('Token usage:', stats.totalTokens);
}

Defined in

packages/agents/src/core/robota.ts:893


getPlugins

getPlugins(): AbstractPlugin<IPluginOptions, IPluginStats>[]

Get all registered plugins.

Returns

AbstractPlugin<IPluginOptions, IPluginStats>[]

Array of all currently registered plugin instances

Example

typescript
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/core/robota.ts:911


getPluginNames

getPluginNames(): string[]

Get all registered plugin names

Returns

string[]

Defined in

packages/agents/src/core/robota.ts:918


registerModule

registerModule(module, options?): Promise<void>

Register a new module with the agent

Parameters

NameTypeDescription
moduleAbstractModule<BaseModuleOptions, ModuleStats>The module instance to register
options?ObjectRegistration options
options.autoInitialize?boolean-
options.validateDependencies?boolean-

Returns

Promise<void>

Defined in

packages/agents/src/core/robota.ts:934


unregisterModule

unregisterModule(moduleName): Promise<boolean>

Unregister a module from the agent

Parameters

NameTypeDescription
moduleNamestringName of the module to unregister

Returns

Promise<boolean>

True if module was unregistered, false if not found

Defined in

packages/agents/src/core/robota.ts:953


getModule

getModule<T>(moduleName): null | T

Get a module by name with type safety

Type parameters

NameType
Textends AbstractModule<BaseModuleOptions, ModuleStats> = AbstractModule<BaseModuleOptions, ModuleStats>

Parameters

NameTypeDescription
moduleNamestringName of the module to retrieve

Returns

null | T

The module instance or null if not found

Defined in

packages/agents/src/core/robota.ts:972


getModulesByType

getModulesByType<T>(moduleType): T[]

Get modules by type

Type parameters

NameType
Textends AbstractModule<BaseModuleOptions, ModuleStats> = AbstractModule<BaseModuleOptions, ModuleStats>

Parameters

NameTypeDescription
moduleTypestringType of modules to retrieve

Returns

T[]

Array of modules matching the type

Defined in

packages/agents/src/core/robota.ts:984


getModules

getModules(): AbstractModule<BaseModuleOptions, ModuleStats>[]

Get all registered modules

Returns

AbstractModule<BaseModuleOptions, ModuleStats>[]

Array of all registered modules

Defined in

packages/agents/src/core/robota.ts:995


getModuleNames

getModuleNames(): string[]

Get all registered module names

Returns

string[]

Array of module names

Defined in

packages/agents/src/core/robota.ts:1006


hasModule

hasModule(moduleName): boolean

Check if a module is registered

Parameters

NameTypeDescription
moduleNamestringName of the module to check

Returns

boolean

True if module is registered

Defined in

packages/agents/src/core/robota.ts:1018


executeModule

executeModule(moduleName, context): Promise<{ success: boolean ; data?: ModuleResultData ; error?: Error ; duration?: number }>

Execute a module by name

Parameters

NameTypeDescription
moduleNamestringName of the module to execute
contextObjectExecution 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/core/robota.ts:1031


getModuleStats

getModuleStats(moduleName): null | { totalExecutions: number ; successfulExecutions: number ; failedExecutions: number ; averageExecutionTime: number ; lastExecutionTime?: Date }

Get module execution statistics

Parameters

NameTypeDescription
moduleNamestringName 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/core/robota.ts:1050


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

NameTypeDescription
modelConfigObjectNew model configuration
modelConfig.providerstring-
modelConfig.modelstring-
modelConfig.temperature?number-
modelConfig.maxTokens?number-
modelConfig.topP?number-
modelConfig.systemMessage?string-

Returns

void

Throws

When the provider is not available

Example

typescript
// 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/core/robota.ts:1105


getModel

getModel(): Object

Get the current model configuration.

Returns the current AI provider, model, and related settings.

Returns

Object

Current model configuration

NameType
providerstring
modelstring
temperature?number
maxTokens?number
topP?number
systemMessage?string

Example

typescript
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/core/robota.ts:1177


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

NameTypeDescription
toolAbstractTool<TToolParameters, IToolResult>The tool instance to register

Returns

void

Example

typescript
import { AbstractTool } from '@robota-sdk/agent-core';

class WeatherTool extends AbstractTool {
  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/core/robota.ts:1257


unregisterTool

unregisterTool(toolName): void

Unregister a tool by name.

Removes a previously registered tool, making it unavailable for future AI calls.

Parameters

NameTypeDescription
toolNamestringName of the tool to unregister

Returns

void

Example

typescript
robota.unregisterTool('weather-tool');

const stats = robota.getStats();
console.log('Remaining tools:', stats.tools);

Defined in

packages/agents/src/core/robota.ts:1291


getConfig

getConfig(): IAgentConfig

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

IAgentConfig

Copy of the current IAgentConfig

Example

typescript
const config = robota.getConfig();
console.log('Current model:', config.currentModel);
console.log('Available providers:', Object.keys(config.aiProviders || {}));

Defined in

packages/agents/src/core/robota.ts:1311


getStats

getStats(): Object

Get comprehensive agent statistics including providers, tools, plugins, modules, and performance data.

Returns

Object

Object containing all agent statistics and metadata

NameType
namestring
versionstring
conversationIdstring
providersstring[]
currentProvidernull | string
toolsstring[]
pluginsstring[]
modulesstring[]
historyLengthnumber
historyStatsTAgentStatsMetadata
uptimenumber

Example

typescript
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/core/robota.ts:1332


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

typescript
// Clean shutdown
await robota.destroy();
console.log('Agent destroyed');

Defined in

packages/agents/src/core/robota.ts:1446

Released under the MIT License.