Mold.cx Documentation

Installation & Setup

Get started with Mold in your project quickly and easily.

NPM Installation

npm install mold-ai

Basic Setup

import { Mold } from 'mold-ai';

const mold = new Mold({

apiKey: 'your-api-key',

environment: 'production'

});

Basic Configuration

Configure Mold for your specific needs with our flexible configuration options.

Configuration Options

const config = {

apiKey: 'your-api-key',

environment: 'production',

timeout: 30000,

retries: 3,

models: ['gpt-4', 'stable-diffusion'],

logging: true

}

const mold = new Mold(config);

Authentication

Secure your Mold API requests with proper authentication.

API Key Authentication

// Using API key in headers

const headers = {

'Authorization': 'Bearer your-api-key',

'Content-Type': 'application/json'

};

// Or using the SDK

const mold = new Mold({

apiKey: process.env.MOLD_API_KEY

});

First API Call

Make your first API call with Mold.

Simple Text Analysis

// Basic sentiment analysis

const result = await mold.analyze({

text: "This is a sample text",

type: "sentiment"

});

console.log(result.sentiment);

Architecture Overview

Understanding Mold's architecture and core components.

System Components

const mold = new Mold({

components: {

nlp: true, // Natural Language Processing

vision: true, // Computer Vision

audio: true, // Audio Processing

inference: true // Model Inference

}

});

Data Flow

Mold uses a streamlined data flow architecture:

  • Input Processing

  • Model Selection

  • Inference Engine

  • Output Formatting

Data Models

Core data structures and models used in Mold.

Basic Data Types

interface MoldInput {

text?: string;

image?: Buffer;

audio?: Buffer;

metadata?: Record;

}

interface MoldOutput {

result: any;

confidence: number;

timing: {

start: number;

end: number;

duration: number;

};

}

Model Configuration

const modelConfig = {

type: 'classification',

architecture: 'transformer',

parameters: {

layers: 12,

heads: 8,

hiddenSize: 768

}

};

Error Handling

Comprehensive guide to handling errors in Mold.

Error Types

try {

const result = await mold.process(input);

} catch (error) {

if (error instanceof MoldValidationError) {

// Handle validation errors

} else if (error instanceof MoldAPIError) {

// Handle API errors

} else if (error instanceof MoldTimeoutError) {

// Handle timeout errors

}

}

Custom Error Handlers

mold.onError((error, context) => {

logger.error({

message: error.message,

code: error.code,

context: context

});

// Implement fallback behavior

return fallbackHandler(error);

});

Best Practices

Recommended patterns and practices for Mold applications.

Performance Optimization

// Use batch processing for multiple inputs

const results = await mold.batchProcess({

inputs: [input1, input2, input3],

options: {

concurrency: 3,

timeout: 30000

}

});

// Implement caching for frequent requests

const cache = new MoldCache({

ttl: 3600,

maxSize: 1000

});

Resource Management

// Properly initialize and cleanup resources

const mold = new Mold();

process.on('SIGTERM', async () => {

await mold.shutdown();

process.exit(0);

});

// Use connection pooling

mold.setConnectionPool({

min: 5,

max: 20,

idleTimeoutMillis: 30000

});

Endpoints

Complete list of available API endpoints and their usage.

REST API Endpoints

// Text Analysis

POST /api/v1/analyze/text

POST /api/v1/analyze/sentiment

// Image Processing

POST /api/v1/vision/detect

POST /api/v1/vision/classify

// Model Management

GET /api/v1/models

POST /api/v1/models/train

PUT /api/v1/models/{id}/deploy

Request/Response Format

Standard formats for API requests and responses.

Request Format

// Standard Request Format

{

"input": {

"text": "Sample text",

"options": {

"language": "en",

"model": "default"

}

},

"config": {

"timeout": 30000,

"version": "v1"

}

}

Response Format

// Standard Response Format

{

"status": "success",

"data": {

"result": {},

"metadata": {}

},

"timing": {

"processed_at": "2024-01-01T12:00:00Z",

"duration_ms": 127

}

}

Rate Limits

Understanding and handling API rate limits.

Rate Limit Rules

// Rate Limit Headers

X-RateLimit-Limit: 1000

X-RateLimit-Remaining: 999

X-RateLimit-Reset: 1640995200

// Handling Rate Limits

try {

const response = await mold.api.call();

} catch (error) {

if (error.code === 429) {

const resetTime = error.headers['X-RateLimit-Reset'];

await wait(resetTime);

// Retry request

}

}

API Versioning

API version management and compatibility.

Version Selection

const mold = new Mold({

apiVersion: 'v1',

compatibility: {

minVersion: 'v1',

maxVersion: 'v2'

}

});

Framework Plugins

Official plugins for popular frameworks and libraries.

React Integration

import { useMold } from '@mold/react';

function App() {

const { analyze, loading } = useMold();

const handleAnalysis = async () => {

const result = await analyze(data);

console.log(result);

};

}

Vue Integration

import { createMold } from '@mold/vue';

export default {

setup() {

const mold = createMold();

const processData = async () => {

const result = await mold.process(data);

return result;

};

}

}

Angular Integration

import { MoldModule } from '@mold/angular';

@NgModule({

imports: [

MoldModule.forRoot({

apiKey: 'your-api-key',

config: { /* ... */ }

})

]

})

Cloud Providers

Seamless integration with major cloud platforms and services.

AWS Integration

const mold = new Mold({

cloud: {

provider: 'aws',

region: 'us-east-1',

credentials: {

accessKeyId: process.env.AWS_ACCESS_KEY,

secretAccessKey: process.env.AWS_SECRET_KEY

},

services: {

s3: true,

lambda: true,

sagemaker: true

}

}

});

Google Cloud Integration

const mold = new Mold({

cloud: {

provider: 'gcp',

projectId: 'your-project-id',

keyFilename: 'path/to/service-account.json',

services: {

storage: true,

functions: true,

aiPlatform: true

}

}

});

Azure Integration

const mold = new Mold({

cloud: {

provider: 'azure',

tenantId: 'your-tenant-id',

clientId: 'your-client-id',

clientSecret: process.env.AZURE_CLIENT_SECRET,

services: {

blob: true,

functions: true,

cognitiveServices: true

}

}

});

Cloud Agnostic Features

  • Automatic failover between providers

  • Cross-cloud data synchronization

  • Unified monitoring and logging

  • Cost optimization strategies

Third-party Services

Connecting Mold with external services.

Service Integration

mold.connect({

service: 'slack',

webhook: process.env.SLACK_WEBHOOK,

events: ['alert', 'error']

});

Custom Integrations

Building custom integrations with Mold.

Custom Adapter

class CustomAdapter extends MoldAdapter {

async connect() {

// Implementation

}

async process(data) {

// Custom processing logic

}

}

Performance Optimization

Optimize your Mold implementation for maximum performance.

Batch Processing

const results = await mold.batchProcess({

texts: ['text1', 'text2', 'text3'],

options: {

concurrency: 3,

timeout: 30000

}

});

Security Guidelines

Best practices for securing your Mold implementation and protecting sensitive data.

API Key Management

// Store API keys securely in environment variables

require('dotenv').config();

const mold = new Mold({

apiKey: process.env.MOLD_API_KEY,

environment: 'production'

});

Data Encryption

// Enable end-to-end encryption

const mold = new Mold({

apiKey: process.env.MOLD_API_KEY,

encryption: {

enabled: true,

algorithm: 'aes-256-gcm',

key: process.env.ENCRYPTION_KEY

}

});

Rate Limiting

// Implement rate limiting

const mold = new Mold({

rateLimit: {

maxRequests: 100,

windowMs: 60000, // 1 minute

retryAfter: 5000 // 5 seconds

}

});

Custom Models

Create and deploy your own AI models with Mold.

Model Training

// Train a custom model

const model = await mold.models.train({

name: 'custom-classifier',

type: 'classification',

data: trainingData,

parameters: {

epochs: 100,

batchSize: 32,

learningRate: 0.001

}

});

Model Deployment

// Deploy your model

await mold.models.deploy({

modelId: model.id,

version: '1.0.0',

scaling: {

minInstances: 1,

maxInstances: 5,

targetConcurrency: 80

}

});

Model Monitoring

// Monitor model performance

const metrics = await mold.models.getMetrics({

modelId: model.id,

timeframe: '24h',

metrics: ['accuracy', 'latency', 'requests']

});

Advanced Configuration

Advanced configuration options for fine-tuning your Mold implementation.

Custom Middleware

// Add custom middleware

mold.use(async (req, next) => {

// Pre-processing

console.log('Processing request:', req.id);

const result = await next(req);

// Post-processing

console.log('Request completed:', result.status);

return result;

});

Distributed Setup

// Configure distributed processing

const mold = new Mold({

cluster: {

enabled: true,

nodes: ['node1', 'node2', 'node3'],

strategy: 'round-robin',

healthCheck: {

interval: 30000,

timeout: 5000

}

}

});

Custom Error Handling

// Advanced error handling

mold.onError((error, context) => {

if (error instanceof RateLimitError) {

return handleRateLimit(error);

}

if (error instanceof ValidationError) {

return handleValidation(error, context);

}

// Log to monitoring service

monitoring.logError({

error,

context,

severity: 'high'

});

return fallbackResponse(error);

});

Last updated