Model class for managing AI model configurations

This class represents an AI model configuration in the Mosaia platform. It provides a structured way to define, customize, and interact with various AI models through a unified interface.

Features:

  • Model configuration management
  • Chat completion capabilities
  • Parameter customization
  • Provider integration
  • Performance monitoring

Models are the core AI engines that power:

  • Text generation and completion
  • Natural language understanding
  • Decision making and analysis
  • Content transformation
  • Knowledge extraction

The class supports various model providers and configurations:

  • OpenAI (GPT-3.5, GPT-4)
  • Anthropic (Claude)
  • Custom models

Basic model setup:

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

// Create a GPT-4 model configuration
const gpt4Model = new Model({
name: 'Enhanced GPT-4',
provider: 'openai',
model_id: 'gpt-4',
temperature: 0.7,
max_tokens: 2000,
metadata: {
purpose: 'general-purpose',
version: '1.0'
}
});

await gpt4Model.save();

Using chat capabilities:

// Interact with the model
const response = await gpt4Model.chat.completions.create({
messages: [
{
role: 'system',
content: 'You are a helpful assistant.'
},
{
role: 'user',
content: 'Explain quantum computing in simple terms.'
}
],
temperature: 0.5,
max_tokens: 500
});

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

Hierarchy (View Summary)

Constructors

  • Creates a new AI model configuration

    Initializes a model configuration with the specified parameters and settings. The model configuration defines how the AI model behaves and interacts with the platform.

    Parameters

    • data: Partial<ModelInterface>

      Configuration data including: - name: Model configuration name - provider: AI provider (e.g., 'openai', 'anthropic') - model_id: Provider's model identifier - temperature: Response randomness (0-1) - max_tokens: Maximum response length - metadata: Custom metadata object

    • Optionaluri: string

      Optional custom URI path for the model endpoint

    Returns Model

    Basic configuration:

    const model = new Model({
    name: 'Support GPT',
    provider: 'openai',
    model_id: 'gpt-4',
    temperature: 0.7
    });

    Advanced configuration:

    const model = new Model({
    name: 'Enterprise Claude',
    provider: 'anthropic',
    model_id: 'claude-2',
    temperature: 0.5,
    max_tokens: 4000,
    metadata: {
    team: 'enterprise',
    use_case: 'documentation',
    version: '2.0'
    }
    }, '/enterprise/model');

Accessors

  • get chat(): Chat

    Get the chat functionality for this model

    This getter provides access to the model's chat capabilities through the Chat class. It enables direct interaction with the model for text generation and completion tasks.

    Returns Chat

    A new Chat instance configured for this model

    Basic chat:

    const response = await model.chat.completions.create({
    messages: [
    { role: 'user', content: 'What is machine learning?' }
    ]
    });

    Advanced chat with system prompt:

    const response = await model.chat.completions.create({
    messages: [
    {
    role: 'system',
    content: 'You are an expert in artificial intelligence.'
    },
    {
    role: 'user',
    content: 'Explain neural networks to a beginner.'
    }
    ],
    temperature: 0.3,
    max_tokens: 1000,
    stream: false
    });

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

Methods

  • 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 ModelInterface

    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<ModelInterface>

    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<ModelInterface>

      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<ModelInterface>

    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);
    }
    }
  • Rerank documents using this model

    Uses this model to rerank documents based on their relevance to a query string.

    Parameters

    • request: RerankRequest

      Rerank request parameters

      Rerank request interface

      • query: string
      • documents: string[]
      • Optionalmodel?: string
      • Optionalreorder_results?: boolean

    Returns Promise<RerankResponse>

    Promise resolving to the rerank response

    const response = await model.rerank({
    query: 'What is artificial intelligence?',
    documents: [
    'Document about AI...',
    'Document about machine learning...',
    'Document about unrelated topic...'
    ],
    reorder_results: true
    });

    console.log('Top result:', response.results[0].document.text);

    When API request fails

  • Generate embeddings using this model

    Generates vector embeddings for text input using this model.

    Parameters

    • request: EmbeddingRequest

      Embedding request parameters

      Embedding request interface

      • Optionalmodel?: string
      • input: string | string[]

    Returns Promise<EmbeddingResponse>

    Promise resolving to the embedding response

    // Generate embedding for single text
    const response = await model.embeddings({
    input: 'Text to embed'
    });

    // Generate embeddings for multiple texts
    const response = await model.embeddings({
    input: ['Text 1', 'Text 2', 'Text 3']
    });

    console.log('First embedding:', response.data[0].embedding);

    When API request fails

  • Like or unlike this model

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

    Returns Promise<Model>

    Promise that resolves to the updated model instance

    await model.like();
    console.log('Model liked:', model.liked);

    When API request fails