Package Exports
- @meshailabs/sdk
- @meshailabs/sdk/dist/index.js
- @meshailabs/sdk/dist/index.mjs
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@meshailabs/sdk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
MeshAI SDK for JavaScript/TypeScript
Universal AI Agent Orchestration Platform
MeshAI SDK enables seamless communication and orchestration between AI agents built on different frameworks. Connect agents from OpenAI, Anthropic, Google, LangChain, CrewAI, and more in a unified platform.
Features
- Cross-Framework Communication - Agents from different platforms work together seamlessly
- Intelligent Routing - Advanced strategies for optimal agent selection
- Agent Instructions - Define comprehensive behavioral guidelines and guardrails
- Context Preservation - Maintain conversation context across agents
- Real-time Monitoring - WebSocket support for live task updates
- TypeScript Support - Full type safety and IntelliSense
- Production Ready - Built-in error handling, retries, and circuit breakers
Installation
npm install @meshailabs/sdk
# or
yarn add @meshailabs/sdk
# or
pnpm add @meshailabs/sdk
Quick Start
Basic Setup
Set your MeshAI API key:
export MESHAI_API_KEY="your-api-key"
Simple Task Execution
import { MeshClient } from '@meshailabs/sdk';
// Create client
const client = await MeshClient.createAndInitialize();
// Execute a task
const result = await client.quickExecute(
'Analyze the sentiment of this text: I love using MeshAI!',
['sentiment-analysis']
);
console.log('Result:', result.result);
Advanced Usage
import { MeshClient, RoutingStrategy, TaskStatus } from '@meshailabs/sdk';
const client = new MeshClient({
apiKey: process.env.MESHAI_API_KEY,
defaultRoutingStrategy: RoutingStrategy.PERFORMANCE_BASED,
timeout: 30000,
maxRetries: 3
});
// Initialize the client
await client.initialize();
// Create a task with specific routing
const task = client.createTask(
{ prompt: 'Generate a business plan for a tech startup' },
{
taskType: 'generation',
requiredCapabilities: ['business-planning', 'strategic-thinking'],
routingStrategy: RoutingStrategy.CAPABILITY_MATCH,
preserveContext: true,
conversationId: 'session-123'
}
);
// Execute with real-time updates
const result = await client.execute(task, {
async: true,
onProgress: (status, details) => {
console.log(`Task status: ${status}`, details);
},
callback: (finalResult) => {
console.log('Task completed:', finalResult);
}
});
Agent Discovery
// Discover agents by capabilities
const agents = await client.discoverAgents({
requiredCapabilities: ['code-generation', 'debugging'],
preferredFramework: 'langchain',
limit: 5
});
agents.forEach(agent => {
console.log(`Agent: ${agent.name} (${agent.framework})`);
console.log(`Capabilities: ${agent.capabilities?.join(', ')}`);
});
Agent Instructions
Define comprehensive behavioral guidelines for agents:
// Register agent with instructions
const agent = await client.registerAgent({
id: 'assistant-001',
name: 'Customer Assistant',
framework: 'openai',
capabilities: ['customer-support', 'problem-solving'],
endpoint: 'https://api.openai.com/v1/chat/completions',
// Define agent behavior
instructions: {
guidelines: [
'Be professional and empathetic',
'Provide clear, actionable solutions',
'Follow company policies strictly'
],
taskBoundaries: [
'DO provide product support',
'DO NOT share customer data',
'DO NOT make unauthorized promises'
],
outputFormat: 'Structured response with: Problem, Solution, Next Steps',
guardrails: [
'Verify customer identity before account changes',
'Escalate complex technical issues'
]
}
});
// Override instructions for specific tasks
const result = await client.execute({
taskType: 'urgent_support',
input: 'Customer complaint about service',
instructions: {
taskGuidelines: ['Prioritize immediate resolution'],
constraints: ['Response within 2 minutes']
}
});
Context Management
// Maintain conversation context
const conversationId = 'conv-' + Date.now();
// First task
const task1 = await client.execute(
client.createTask('What is quantum computing?', {
preserveContext: true,
conversationId
})
);
// Follow-up task with context
const task2 = await client.execute(
client.createTask('How does it differ from classical computing?', {
preserveContext: true,
conversationId
})
);
// Get full conversation history
const history = await client.getTaskHistory(conversationId);
Routing Strategies
Strategy | Description | Use Case |
---|---|---|
ROUND_ROBIN |
Distribute tasks evenly | Load balancing |
CAPABILITY_MATCH |
Match agent capabilities | Specialized tasks |
LEAST_LOADED |
Route to least busy agent | Performance optimization |
PERFORMANCE_BASED |
Choose best performing | Quality-critical tasks |
STICKY_SESSION |
Keep same agent | Context preservation |
COST_OPTIMIZED |
Most cost-effective | Budget management |
GEOGRAPHIC |
Geographic proximity | Latency optimization |
Configuration
const client = new MeshClient({
// Authentication
apiKey: 'your-api-key',
// Service URLs (optional - defaults to MeshAI cloud)
registryUrl: 'https://api.meshai.dev/registry',
runtimeUrl: 'https://api.meshai.dev/runtime',
// Performance
timeout: 30000, // 30 seconds
maxRetries: 3,
maxConcurrentTasks: 100,
// Circuit breaker
circuitBreakerEnabled: true,
circuitBreakerThreshold: 5,
// Monitoring
metricsEnabled: true,
logLevel: 'info'
});
Error Handling
import {
MeshError,
AuthenticationError,
TaskExecutionError,
TimeoutError
} from '@meshailabs/sdk';
try {
const result = await client.execute(task);
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof TaskExecutionError) {
console.error('Task failed:', error.taskId, error.message);
} else if (error instanceof TimeoutError) {
console.error('Task timed out');
} else {
console.error('Unknown error:', error);
}
}
TypeScript Support
The SDK is written in TypeScript and provides full type definitions:
import {
MeshClient,
TaskData,
TaskResult,
AgentInfo,
AgentRegistration,
RoutingStrategy,
TaskStatus,
AgentStatus
} from '@meshailabs/sdk';
// All types are fully typed
const task: TaskData = {
taskType: 'analysis',
input: { data: 'sample' },
requiredCapabilities: ['analysis'],
routingStrategy: RoutingStrategy.CAPABILITY_MATCH,
// New: Task-specific instructions
instructions: {
taskGuidelines: ['Focus on key insights'],
outputRequirements: 'JSON format with findings array'
}
};
// Agent with instructions
const agent: AgentRegistration = {
id: 'agent-001',
name: 'Analysis Agent',
framework: 'langchain',
capabilities: ['analysis'],
endpoint: 'https://api.example.com',
instructions: {
guidelines: ['Provide data-driven insights'],
guardrails: ['No PII in outputs']
}
};
const result: TaskResult = await client.execute(task);
API Reference
MeshClient
Main client for interacting with MeshAI:
initialize()
- Initialize the clientexecute(task, options?)
- Execute a taskexecuteWithAgent(agentId, task, options?)
- Execute with specific agentdiscoverAgents(query)
- Find agents by capabilitiesgetAgent(agentId)
- Get agent detailslistAgents(limit?, offset?)
- List all agentsquickExecute(input, capabilities?)
- Simplified task execution
RegistryClient
Agent management operations:
registerAgent(registration)
- Register new agentupdateAgent(agentId, updates)
- Update agent infoderegisterAgent(agentId)
- Remove agentcheckAgentHealth(agentId)
- Health checkgetAgentMetrics(agentId)
- Performance metrics
RuntimeClient
Task execution operations:
execute(task, options?)
- Execute taskexecuteBatch(tasks)
- Execute multiple tasksgetTaskStatus(taskId)
- Check task statuscancelTask(taskId)
- Cancel running taskretryTask(taskId)
- Retry failed task
MemoryClient
Persistent memory and learning capabilities:
healthCheck()
- Check Memory Service healthstoreEpisodic(memory)
- Store complete task interactiongetEpisodic(memoryId)
- Retrieve specific memorylistEpisodic(filters)
- List memories with filterssearchSemantic(query)
- Vector similarity searchgetStats(filters?)
- Memory statisticsgenerateSummary(agentId, hours)
- Generate summary memorygetSummary(agentId, hours)
- Retrieve summarylistProcedures(agentId, limit)
- List learned patternsgetProcedure(procedureId)
- Get procedure detailsreflect(agentId, type, hours, areas?)
- Perform self-evaluationgetReflection(agentId, type)
- Retrieve reflection
Memory Client Example
import { MeshConfig, MemoryClient } from '@meshailabs/sdk';
const config = new MeshConfig({ apiKey: process.env.MESHAI_API_KEY });
const memory = new MemoryClient(config);
// Store episodic memory
await memory.storeEpisodic({
agentId: 'agent-001',
sessionId: 'session-123',
interactionType: 'customer_query',
inputData: { query: 'How do I reset my password?' },
outputData: { response: 'Go to Settings > Security' },
success: true,
durationMs: 1250,
tokensUsed: 150,
tags: ['password', 'security']
});
// Semantic search for similar past interactions
const results = await memory.searchSemantic({
agentId: 'agent-001',
queryText: 'I forgot my login credentials',
topK: 5,
minSimilarity: 0.7
});
// Get memory statistics
const stats = await memory.getStats({ agentId: 'agent-001' });
console.log(`Total memories: ${stats.totalMemories}`);
console.log(`Success rate: ${(stats.successRate * 100).toFixed(1)}%`);
// Agent self-reflection
const reflection = await memory.reflect(
'agent-001',
'performance_analysis',
168, // last week
['accuracy', 'response_time']
);
console.log('Insights:', reflection.insights);
For complete examples, see examples/memory-client.ts
.
Examples
Basic Example
import { MeshClient } from '@meshailabs/sdk';
async function main() {
const client = await MeshClient.createAndInitialize();
const result = await client.quickExecute(
'Translate "Hello World" to Spanish'
);
console.log(result.result);
client.disconnect();
}
main().catch(console.error);
WebSocket Monitoring
const result = await client.execute(task, {
async: true,
onProgress: (status, details) => {
console.log(`Status: ${status}`);
if (details) {
console.log('Details:', details);
}
},
callback: (result) => {
if (result.status === TaskStatus.COMPLETED) {
console.log('Success:', result.result);
} else if (result.status === TaskStatus.FAILED) {
console.error('Failed:', result.error);
}
}
});
Support
- Documentation: docs.meshai.dev
- GitHub: github.com/meshailabs-org/meshai-sdk-js
- Issues: GitHub Issues
- Email: support@meshai.dev
License
MIT License - see LICENSE file for details
Contributing
Contributions are welcome! Please read our Contributing Guide for details.