Agent class for managing AI agent instances in the Mosaia SDK

This class represents an AI agent that can perform tasks, handle conversations, and execute workflows. Agents are the core AI entities in the platform, providing natural language understanding and task automation capabilities.

Features:

  • Agent configuration management
  • Chat and completion operations
  • Image/avatar management
  • Tool integration
  • Model configuration

Agents can be configured with different models, temperature settings, and system prompts to customize their behavior. They can also be assigned tools to extend their capabilities.

Basic agent usage:

import { Agent } from 'mosaia-node-sdk';

// Create an agent instance
const agent = new Agent({
name: 'Customer Support Agent',
short_description: 'AI agent for customer inquiries',
model: 'gpt-4',
temperature: 0.7,
system_prompt: 'You are a helpful customer support agent.'
});

// Upload an agent avatar
const file = new File(['image data'], 'agent-avatar.png', { type: 'image/png' });
await agent.image.upload(file);

Using chat capabilities:

// Chat with the agent
const response = await agent.chat.completions.create({
messages: [
{ role: 'user', content: 'How can I reset my password?' }
],
temperature: 0.7,
max_tokens: 150
});

console.log('Agent response:', response.choices[0].message.content);

Hierarchy (View Summary)

Constructors

  • Creates a new Agent instance

    Initializes an agent with the provided configuration data and optional URI. The agent represents an AI entity that can perform intelligent tasks.

    Parameters

    • data: Partial<AgentInterface>

      Agent configuration data

    • Optionaluri: string

      Optional URI path for the agent endpoint. Defaults to '/agent'

    Returns Agent

    const agent = new Agent({
    name: 'Support Agent',
    short_description: 'Customer support AI',
    model: 'gpt-4',
    temperature: 0.7
    });

Accessors

  • get chat(): Chat

    Get the chat functionality for this agent

    This getter provides access to the agent's chat capabilities through the Chat class. It allows for chat completions and other chat-related operations specific to this agent.

    Returns Chat

    A new Chat instance configured for this agent

    Basic chat:

    const response = await agent.chat.completions.create({
    messages: [
    { role: 'user', content: 'Hello!' }
    ]
    });

    Advanced chat configuration:

    const response = await agent.chat.completions.create({
    messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'What can you help me with?' }
    ],
    temperature: 0.7,
    max_tokens: 150,
    stream: false
    });

    console.log('Response:', response.choices[0].message.content);
  • get image(): Image

    Get the image functionality for this agent

    This getter provides access to the agent's image operations through the Image class. It allows for image uploads and other image-related operations specific to this agent.

    Returns Image

    A new Image instance configured for this agent

    const updatedAgent = await agent.image.upload<Agent, GetAgentPayload>(file);
    
  • get tasks(): Tasks

    Get the tasks collection for this agent

    This getter provides access to the agent's tasks collection, allowing you to manage tasks associated with this agent.

    Returns Tasks

    Tasks collection for managing agent tasks

    // Get all tasks for this agent
    const tasks = await agent.tasks.get();

    // Create a new task
    const newTask = await agent.tasks.create({
    name: 'Complete analysis',
    description: 'Analyze user feedback'
    });
  • get logs(): Logs

    Get the logs collection for this agent

    This getter provides access to the agent's logs collection, allowing you to manage conversation logs and interaction history for this agent.

    Returns Logs

    Logs collection for managing agent logs

    // Get all logs for this agent
    const logs = await agent.logs.get();

    // Get a specific log
    const log = await agent.logs.get({}, 'log-id');

    // Access messages within a log
    const messages = await log.messages.get();

Methods

  • Like or unlike this agent

    Toggles the like status of this agent. If the agent is already liked, it will be unliked, and vice versa.

    Returns Promise<Agent>

    Promise that resolves to the updated agent instance

    await agent.like();
    console.log('Agent liked:', agent.liked);

    When API request fails

  • Fork this agent

    Creates a copy of this agent that can be independently modified. Useful for creating variations of existing agents.

    Parameters

    • Optionaloptions: { generate_system_message?: boolean }

      Optional fork options

      • Optionalgenerate_system_message?: boolean

        Whether to generate a new system message

    Returns Promise<Agent>

    Promise resolving to the forked agent instance

    // Basic fork
    const forkedAgent = await agent.fork();

    // Fork with system message generation
    const forkedAgent = await agent.fork({
    generate_system_message: true
    });

    When API request fails

  • Check if the entity is active

    This method checks the active status of the entity. Most entities in the system can be active or inactive, which affects their availability and usability in the platform.

    Returns boolean

    True if the entity is active, false otherwise

    const user = new User(userData);
    if (user.isActive()) {
    // Perform operations with active user
    } else {
    console.log('User is inactive');
    }
  • Convert model instance to interface data

    This method serializes the model instance to a plain object that matches the interface type. This is useful for:

    • Sending data to the API
    • Storing data in a database
    • Passing data between components
    • Debugging model state

    Returns AgentInterface

    The model data as a plain object matching the interface type

    const user = new User({
    email: 'user@example.com',
    firstName: 'John'
    });

    const data = user.toJSON();
    console.log(data); // { email: '...', firstName: '...' }

    // Use with JSON.stringify
    const json = JSON.stringify(user);
  • Convert model instance to API payload

    This method creates a payload suitable for API requests by:

    • Converting the model to a plain object
    • Removing read-only fields (like 'id')
    • Ensuring proper data format for the API

    Returns Partial<AgentInterface>

    A clean object suitable for API requests

    const user = new User({
    id: '123', // Will be removed from payload
    email: 'new@example.com',
    firstName: 'John'
    });

    const payload = user.toAPIPayload();
    // payload = { email: '...', firstName: '...' }
    // Note: 'id' is removed as it's read-only

    await apiClient.POST('/users', payload);
  • Update model data with new values

    This method updates the model's data and instance properties with new values. It performs a shallow merge of the updates with existing data, allowing for partial updates of the model's properties.

    Parameters

    • updates: Partial<AgentInterface>

      Object containing properties to update

    Returns void

    const user = new User({
    email: 'old@example.com',
    firstName: 'John'
    });

    // Update multiple properties
    user.update({
    email: 'new@example.com',
    lastName: 'Doe'
    });

    // Save changes to API
    await user.save();

    This method only updates the local model instance. To persist changes to the API, call save after updating.

  • Save the model instance to the API

    This method persists the current state of the model to the API using a PUT request. It requires the model to have an ID (existing instance). For new instances, use the collection's create method instead.

    The method:

    1. Validates the model has an ID
    2. Sends current data to the API
    3. Updates local instance with API response

    Returns Promise<AgentInterface>

    Promise resolving to the updated model data

    When model has no ID

    When API request fails

    const user = new User({
    id: '123',
    email: 'user@example.com'
    });

    // Update and save
    user.update({ firstName: 'John' });
    await user.save();

    Error handling:

    try {
    await user.save();
    } catch (error) {
    if (error.message.includes('ID is required')) {
    // Handle missing ID error
    } else {
    // Handle API errors
    }
    }
  • Delete the model instance from the API

    This method permanently deletes the model instance from the API and clears the local data. This operation cannot be undone.

    The method:

    1. Validates the model has an ID
    2. Sends DELETE request to the API
    3. Clears local instance data on success

    Returns Promise<void>

    Promise that resolves when deletion is successful

    When model has no ID

    When API request fails

    Basic deletion:

    const user = await users.get({}, 'user-id');
    if (user) {
    await user.delete();
    // User is now deleted and instance is cleared
    }

    Error handling:

    try {
    await user.delete();
    console.log('User deleted successfully');
    } catch (error) {
    if (error.message.includes('ID is required')) {
    console.error('Cannot delete - no ID');
    } else {
    console.error('Deletion failed:', error.message);
    }
    }