Framework API
The SkinFlow Framework API provides the main interface for creating and managing multi-agent systems.
createMultiAgentFramework
Creates a new instance of the SkinFlow framework with the specified configuration.
import { createMultiAgentFramework } from 'skingflow'
const framework = await createMultiAgentFramework(config)Parameters
config(Object): Configuration object for the frameworkllm(Object): LLM provider configurationmemory(Object): Memory system configurationtools(Object): Tool system configurationagents(Object): Agent system configurationsecurity(Object): Security configurationlogging(Object): Logging configuration
Returns
Returns a Promise that resolves to a Framework instance.
Example
const framework = await createMultiAgentFramework({
llm: {
provider: 'openai',
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4'
},
memory: {
storage: {
type: 'memory'
}
}
})Framework Class
The main framework class that provides all functionality.
Methods
processRequest(request, context)
Processes a user request using the multi-agent system.
const result = await framework.processRequest(
"Create a todo list application",
{ userId: 'user123' }
)Parameters:
request(string): The user request to processcontext(Object): Context object containing user and session informationuserId(string): Unique identifier for the usersessionId(string): Unique identifier for the sessionmetadata(Object): Additional context metadata
Returns:
- Promise<Object>: Result object containing:
success(boolean): Whether the request was successfulcontent(string): The main response contentdata(Object): Additional data returned by agentsmetadata(Object): Processing metadataerror(string): Error message if failed
Example:
const result = await framework.processRequest(
"Analyze the sales data and create a report",
{
userId: 'user123',
sessionId: 'session456',
metadata: {
department: 'sales',
priority: 'high'
}
}
)
if (result.success) {
console.log('Response:', result.content)
console.log('Additional data:', result.data)
} else {
console.error('Error:', result.error)
}processRequestStream(request, context)
Processes a user request with streaming output for real-time responses.
const stream = await framework.processRequestStream(
"Write a detailed analysis of current AI trends",
{ userId: 'user123' }
)
for await (const chunk of stream) {
console.log(chunk.content)
}Parameters:
request(string): The user request to processcontext(Object): Context object (same asprocessRequest)
Returns:
- AsyncIterable<Object>: Async iterable that yields chunks containing:
content(string): Content chunktype(string): Chunk type ('content', 'metadata', 'error')done(boolean): Whether this is the final chunk
Example:
const stream = await framework.processRequestStream(
"Create a comprehensive business plan",
{ userId: 'user123' }
)
let fullContent = ''
for await (const chunk of stream) {
if (chunk.type === 'content') {
fullContent += chunk.content
process.stdout.write(chunk.content)
} else if (chunk.type === 'metadata') {
console.log('\nMetadata:', chunk.data)
}
}
console.log('\nComplete response received')executeWorkflow(workflow, context)
Executes a predefined workflow with multiple steps and agents.
const workflow = {
name: 'data-analysis-workflow',
description: 'Analyze data and create visualizations',
steps: [
{
name: 'data-collection',
agent: 'research',
input: 'Collect sales data for Q4 2023',
timeout: 300000
},
{
name: 'data-analysis',
agent: 'analysis',
input: 'Analyze the collected sales data',
dependencies: ['data-collection']
},
{
name: 'visualization',
agent: 'programming',
input: 'Create charts and graphs from the analysis',
dependencies: ['data-analysis']
},
{
name: 'report',
agent: 'content-creation',
input: 'Write a comprehensive report with findings',
dependencies: ['visualization']
}
]
}
const result = await framework.executeWorkflow(workflow, { userId: 'user123' })Parameters:
workflow(Object): Workflow definitionname(string): Unique workflow namedescription(string): Workflow descriptionsteps(Array<Object>): Array of workflow stepsname(string): Step nameagent(string): Agent type to useinput(string): Input for the steptimeout(number): Step timeout in millisecondsdependencies(Array<string>): Dependencies on other steps
context(Object): Context object
Returns:
- Promise<Object>: Workflow execution result
success(boolean): Whether workflow completed successfullyresults(Object): Results from each stepmetadata(Object): Execution metadataerror(string): Error message if failed
getAgentStatus()
Gets the current status of all agents in the system.
const status = await framework.getAgentStatus()
console.log('Agent Status:', status)Returns:
- Promise<Object>: Agent status information
planning(Object): Planning agent statussub-agents(Object): Sub-agent statustotal(number): Total number of active agentscapacity(Object): Agent capacity information
Example:
{
"planning": {
"status": "idle",
"currentTask": null,
"lastActivity": "2024-01-15T10:30:00Z"
},
"sub-agents": {
"research": {
"status": "busy",
"currentTask": "market-analysis",
"activeTime": 120000
},
"programming": {
"status": "idle",
"currentTask": null,
"lastActivity": "2024-01-15T10:25:00Z"
}
},
"total": 5,
"capacity": {
"used": 2,
"available": 3,
"utilization": 0.4
}
}getHealthStatus()
Gets the overall health status of the framework.
const health = await framework.getHealthStatus()
console.log('System Health:', health)Returns:
- Promise<Object>: Health status information
status(string): Overall health status ('healthy', 'degraded', 'unhealthy')components(Object): Status of individual componentsmetrics(Object): System metrics
Example:
{
"status": "healthy",
"components": {
"llm": {
"status": "connected",
"provider": "openai",
"responseTime": 234
},
"memory": {
"status": "connected",
"storage": "memory",
"usage": 0.3
},
"tools": {
"status": "operational",
"available": 15,
"enabled": 12
}
},
"metrics": {
"uptime": 86400000,
"requestsProcessed": 1234,
"successRate": 0.98,
"averageResponseTime": 2345
}
}registerAgent(agentConfig)
Registers a custom agent with the framework.
const customAgent = {
name: 'custom-data-processor',
type: 'specialist',
capabilities: ['data-processing', 'etl'],
model: 'gpt-4',
tools: ['data-analysis', 'csv-export'],
maxConcurrentTasks: 3,
timeout: 300000,
handler: async (task, context) => {
// Custom agent implementation
return {
success: true,
result: 'Data processed successfully',
data: processedData
}
}
}
await framework.registerAgent(customAgent)Parameters:
agentConfig(Object): Agent configurationname(string): Unique agent nametype(string): Agent typecapabilities(Array<string>): Agent capabilitiesmodel(string): LLM model to usetools(Array<string>): Tools the agent can usehandler(Function): Agent handler function
Returns:
- Promise<void>
updateConfig(newConfig)
Updates the framework configuration at runtime.
await framework.updateConfig({
logging: {
level: 'debug'
},
agents: {
maxConcurrentAgents: 10
}
})Parameters:
newConfig(Object): New configuration values to merge with existing config
Returns:
- Promise<void>
shutdown()
Gracefully shuts down the framework and releases resources.
await framework.shutdown()
console.log('Framework shutdown complete')Returns:
- Promise<void>
Events
The framework emits various events that you can listen to:
framework.on('requestStarted', (requestId, request, context) => {
console.log(`Request started: ${requestId}`)
})
framework.on('requestCompleted', (requestId, result, duration) => {
console.log(`Request completed: ${requestId} in ${duration}ms`)
})
framework.on('requestFailed', (requestId, error, duration) => {
console.log(`Request failed: ${requestId} - ${error.message}`)
})
framework.on('agentStatusChanged', (agentName, oldStatus, newStatus) => {
console.log(`Agent ${agentName} status changed: ${oldStatus} -> ${newStatus}`)
})
framework.on('workflowStepCompleted', (workflowName, stepName, result) => {
console.log(`Workflow ${workflowName} step ${stepName} completed`)
})Event Types
requestStarted: Fired when a request starts processingrequestCompleted: Fired when a request completes successfullyrequestFailed: Fired when a request failsagentStatusChanged: Fired when an agent's status changesworkflowStepCompleted: Fired when a workflow step completesworkflowCompleted: Fired when a workflow completesconfigUpdated: Fired when configuration is updatedhealthStatusChanged: Fired when system health status changes
Error Handling
The framework provides comprehensive error handling:
try {
const result = await framework.processRequest(
"Complex request that might fail",
{ userId: 'user123' }
)
} catch (error) {
switch (error.code) {
case 'LLM_API_ERROR':
console.error('LLM API Error:', error.message)
break
case 'MEMORY_ERROR':
console.error('Memory Error:', error.message)
break
case 'TOOL_ERROR':
console.error('Tool Error:', error.message)
break
case 'TIMEOUT_ERROR':
console.error('Timeout Error:', error.message)
break
case 'AUTHENTICATION_ERROR':
console.error('Authentication Error:', error.message)
break
default:
console.error('Unknown Error:', error.message)
}
}Error Codes
LLM_API_ERROR: LLM provider API errorMEMORY_ERROR: Memory system errorTOOL_ERROR: Tool execution errorTIMEOUT_ERROR: Operation timeoutAUTHENTICATION_ERROR: Authentication failureAUTHORIZATION_ERROR: Authorization failureVALIDATION_ERROR: Input validation errorCONFIGURATION_ERROR: Configuration errorINTERNAL_ERROR: Internal system error
Performance Optimization
Request Batching
// Process multiple requests efficiently
const requests = [
{ request: "Task 1", context: { userId: 'user123' } },
{ request: "Task 2", context: { userId: 'user123' } },
{ request: "Task 3", context: { userId: 'user123' } }
]
const results = await Promise.all(
requests.map(r => framework.processRequest(r.request, r.context))
)Connection Pooling
The framework automatically manages connection pooling for optimal performance:
// Configure connection pooling
const framework = await createMultiAgentFramework({
performance: {
resources: {
connections: {
llm: {
maxConnections: 10,
minConnections: 2
},
database: {
maxConnections: 20,
minConnections: 5
}
}
}
}
})Configuration Examples
Production Configuration
const framework = await createMultiAgentFramework({
llm: {
provider: 'openai',
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4',
maxTokens: 4000,
temperature: 0.3,
retry: {
maxRetries: 5,
retryDelay: 1000
}
},
memory: {
storage: {
type: 'postgres',
config: {
host: process.env.DB_HOST,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
}
}
},
agents: {
maxConcurrentAgents: 10,
maxConcurrentTasks: 20
},
logging: {
level: 'info',
outputs: [
{
type: 'elasticsearch',
host: process.env.ELASTICSEARCH_HOST
}
]
}
})Development Configuration
const framework = await createMultiAgentFramework({
llm: {
provider: 'openai',
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-3.5-turbo',
temperature: 0.7
},
memory: {
storage: {
type: 'memory'
}
},
logging: {
level: 'debug'
}
})Next Steps
- Agent API - Agent-specific API documentation
- Tool API - Tool system API documentation
- Memory API - Memory system API documentation
- Examples - Practical implementations