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-4o model configuration
const gpt4Model = new Model({
name: 'gpt-4o',
model: 'gpt-4o',
description: 'Flagship multimodal model from OpenAI.',
type: 'chat',
api_type: 'openai',
base_url: 'https://api.openai.com/v1',
api_key: process.env.OPENAI_API_KEY!,
prices: {
input_per_1k: 0.005,
output_per_1k: 0.015
},
max_context_tokens: 128000,
max_output_tokens: 16384
});

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: Display name (required, unique among public models) - model: Upstream model identifier (e.g. 'gpt-4o', 'claude-3-5-sonnet-20241022') - description: One-line description (required) - api_type: Provider protocol (e.g. 'openai', 'anthropic') - base_url: Provider API base URL (required, encrypted) - api_key: Provider API key (required, encrypted) - prices: Pricing map (values must be numbers) - type: Model category (chat | image | rerank | moderation | language | embedding | contextualized_embedding) - max_context_tokens / max_output_tokens: Token limits

    • Optionaluri: string

      Optional custom URI path for the model endpoint

    Returns Model

    Basic configuration:

    const model = new Model({
    name: 'support-gpt',
    model: 'gpt-4o',
    description: 'Support model fine-tuned on Zendesk tickets.',
    api_type: 'openai',
    base_url: 'https://api.openai.com/v1',
    api_key: process.env.OPENAI_API_KEY!,
    prices: { input_per_1k: 0.005, output_per_1k: 0.015 }
    });

    Advanced configuration:

    const model = new Model({
    name: 'enterprise-claude',
    model: 'claude-3-5-sonnet-20241022',
    description: 'Enterprise documentation assistant.',
    api_type: 'anthropic',
    base_url: 'https://api.anthropic.com/v1',
    api_key: process.env.ANTHROPIC_API_KEY!,
    prices: { input_per_1k: 0.003, output_per_1k: 0.015 },
    type: 'chat',
    max_context_tokens: 200000,
    max_output_tokens: 8192,
    encoding: 'cl100k_base'
    }, '/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

    Parameters

    • Optionalparams: object

      Optional query parameters for deletion (e.g., { delete: true, deleteS3: true })

    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);
    }
    }

    Delete with query parameters:

    // Hard delete
    await item.delete({ delete: true });

    // Delete with S3 cleanup
    await item.delete({ deleteS3: true, delete: true });
  • Subscribe to live updates for this entity via the SSE relay.

    Opens a Server-Sent Events connection to the Mosaia relay server (mosaia-sse-relay-server) scoped to this specific document. The relay watches the underlying MongoDB change stream and forwards every update to handlers.onUpdate.

    Requires the entity to have an id (must be saved first).

    Type Parameters

    • TStart = any

    Parameters

    Returns SSESubscription

    A subscription handle. Call close() to disconnect.

    const drive = await client.drives.get({}, driveId);
    const sub = drive.subscribe({
    onUpdate: (doc) => console.log('drive changed', doc),
    onError: (err) => console.error(err),
    });

    // later
    sub.close();
  • 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