Understand how Fantomu agents work
Understanding the fundamentals of AI agents
AI agents are autonomous systems that can perceive their environment, make decisions, and take actions to achieve specific goals. In the context of Fantomu, AI agents are intelligent assistants that can understand natural language instructions and perform complex tasks.
AI agents operate independently without constant human intervention:
Agents respond to changes in their environment:
Agents can take initiative:
Agents can interact with other systems:
┌─────────────────────────────────────────────────────────┐
│ Fantomu Agent │
├─────────────────────────────────────────────────────────┤
│ Natural Language Interface │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Input Parser │ │ Response Gen │ │
│ └─────────────────┘ └─────────────────┘ │
├─────────────────────────────────────────────────────────┤
│ Core Processing Engine │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Task Planner │ │ Context Mgmt │ │
│ └─────────────────┘ └─────────────────┘ │
├─────────────────────────────────────────────────────────┤
│ Integration Layer │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ API Clients │ │ Data Sources │ │
│ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────┘
Ready to build your first AI agent? Check out our [Quick Start Guide](/docs/getting-started) to get up and running in minutes.
How agents are created, deployed, and managed
Understanding the complete lifecycle of AI agents in Fantomu, from creation to retirement.
The initial stage where an agent is defined and configured.
const agent = await client.agents.create({
name: 'Customer Support Bot',
description: 'Handles customer inquiries and support tickets',
capabilities: ['natural_language', 'ticket_management'],
settings: {
model: 'gpt-4',
temperature: 0.7,
maxTokens: 1000
}
});
Key Activities:
Building and testing the agent's functionality.
// Add custom instructions
await agent.update({
instructions: `You are a helpful customer support agent.
Guidelines:
- Always be polite and professional
- Provide accurate information
- Escalate complex issues to human agents
- Follow company policies`
});
// Test with sample tasks
const testResult = await agent.execute({
task: 'Help a customer with a billing question',
context: { customerTier: 'premium' }
});
Key Activities:
Teaching the agent through examples and feedback.
// Add training examples
await agent.training.addExamples([
{
input: 'I need help with my account',
output: 'I'd be happy to help with your account. What specific issue are you experiencing?',
context: { category: 'account_help' }
},
{
input: 'How do I cancel my subscription?',
output: 'To cancel your subscription, please go to Settings > Billing > Cancel Subscription. Is there anything I can do to help you stay?',
context: { category: 'billing' }
}
]);
// Fine-tune based on feedback
await agent.training.fineTune({
epochs: 3,
learningRate: 0.001
});
Key Activities:
Making the agent available for production use.
// Deploy to production
await agent.deploy({
environment: 'production',
version: '1.0.0',
monitoring: {
enabled: true,
logLevel: 'info'
}
});
// Set up webhooks
await agent.webhooks.create({
url: 'https://your-app.com/webhooks/agent',
events: ['task_completed', 'task_failed']
});
Key Activities:
Tracking performance and usage in production.
// Monitor agent performance
const analytics = await agent.getAnalytics({
period: '7d',
metrics: ['response_time', 'success_rate', 'user_satisfaction']
});
// Set up alerts
await agent.alerts.create({
condition: 'error_rate > 0.05',
action: 'notify_team',
channels: ['email', 'slack']
});
Key Activities:
Improving performance based on data and feedback.
// Optimize based on analytics
if (analytics.responseTime > 5000) {
await agent.update({
settings: {
...agent.settings,
temperature: 0.5, // More focused responses
maxTokens: 800 // Shorter responses
}
});
}
// A/B test different configurations
await agent.experiments.create({
name: 'response_length_test',
variants: [
{ maxTokens: 500, weight: 0.5 },
{ maxTokens: 1000, weight: 0.5 }
]
});
Key Activities:
Ongoing updates and improvements.
// Regular maintenance tasks
await agent.maintenance.update({
schedule: 'weekly',
tasks: [
'update_training_data',
'optimize_settings',
'review_feedback'
]
});
// Version management
await agent.versions.create({
name: 'v1.1.0',
changes: ['Improved response accuracy', 'Added new capabilities'],
rollbackStrategy: 'gradual'
});
Key Activities:
End-of-life management for agents.
// Archive old agent
await agent.archive({
reason: 'replaced_by_v2',
dataRetention: '1y',
migrationPath: 'agent_v2'
});
// Migrate data to new agent
await agent.migrate({
targetAgent: 'agent_v2',
dataTypes: ['conversations', 'preferences', 'training_data']
});
Key Activities:
How agents execute tasks and handle errors
Understanding how Fantomu agents execute tasks, handle errors, and ensure reliable performance.
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Task Input │───▶│ Preprocessing │───▶│ Execution │
│ │ │ │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ Validation │ │ Postprocessing│
│ │ │ │
└─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ Result │
│ Output │
└─────────────────┘
const result = await agent.execute({
task: 'Write a professional email',
context: {
recipient: 'client@example.com',
subject: 'Project Update',
tone: 'professional'
}
});
console.log(result.result);
const result = await agent.execute({
task: 'Analyze sales data and create a report',
context: {
dataSource: 'sales_database',
period: 'Q1_2024',
format: 'executive_summary'
},
options: {
maxSteps: 10,
timeout: 30000,
retries: 3
}
});
Create written content based on prompts.
const content = await agent.execute({
task: 'Generate blog post about AI trends',
context: {
topic: 'AI in healthcare',
length: '1000 words',
audience: 'healthcare professionals'
}
});
Process and analyze datasets.
const analysis = await agent.execute({
task: 'Analyze customer feedback data',
context: {
data: customerFeedback,
metrics: ['sentiment', 'topics', 'trends'],
outputFormat: 'insights_report'
}
});
Make decisions based on criteria and data.
const decision = await agent.execute({
task: 'Determine if customer qualifies for premium support',
context: {
customerTier: 'basic',
issueComplexity: 'high',
supportHistory: customerSupportHistory
}
});
Interact with external systems.
const integration = await agent.execute({
task: 'Create a new project in Jira',
context: {
projectName: 'Q2 Marketing Campaign',
description: 'Marketing campaign for Q2 product launch',
assignee: 'marketing-team'
}
});
try {
const result = await agent.execute({
task: 'Process user request',
context: userContext
});
if (result.success) {
console.log('Task completed:', result.result);
} else {
console.error('Task failed:', result.error);
}
} catch (error) {
console.error('Execution error:', error.message);
}
async function executeWithRetry(agent, task, context, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const result = await agent.execute({ task, context });
return result;
} catch (error) {
console.log(`Attempt ${attempt} failed:`, error.message);
if (attempt === maxRetries) {
throw new Error(`Task failed after ${maxRetries} attempts`);
}
// Exponential backoff
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, attempt) * 1000)
);
}
}
}
{
"error": "validation_failed",
"message": "Invalid task format",
"details": {
"field": "context",
"issue": "missing_required_field"
}
}
{
"error": "execution_failed",
"message": "Task execution timeout",
"details": {
"timeout": 30000,
"elapsed": 30001
}
}
{
"error": "integration_failed",
"message": "External service unavailable",
"details": {
"service": "jira_api",
"status": 503
}
}
// Execute multiple tasks in parallel
const tasks = [
{ task: 'Analyze sales data', context: salesContext },
{ task: 'Generate report', context: reportContext },
{ task: 'Send notifications', context: notificationContext }
];
const results = await Promise.all(
tasks.map(task => agent.execute(task))
);
// Enable caching for repeated tasks
const result = await agent.execute({
task: 'Generate weekly report',
context: weeklyContext,
options: {
cache: true,
cacheTTL: 3600 // 1 hour
}
});
// Limit resource usage
const result = await agent.execute({
task: 'Process large dataset',
context: largeDataset,
options: {
maxMemory: '512MB',
maxCPU: '50%',
timeout: 60000
}
});
// Monitor task execution
agent.on('task_started', (data) => {
console.log('Task started:', data.taskId);
});
agent.on('task_completed', (data) => {
console.log('Task completed:', {
taskId: data.taskId,
duration: data.duration,
success: data.success
});
});
agent.on('task_failed', (error) => {
console.error('Task failed:', error);
});
// Get detailed analytics
const analytics = await agent.getAnalytics({
period: '7d',
metrics: [
'execution_time',
'success_rate',
'error_rate',
'resource_usage'
]
});
console.log('Performance metrics:', analytics);
How agents maintain context across tasks
Understanding how Fantomu agents maintain context and memory across tasks and conversations.
Context is the information that an agent uses to understand and respond appropriately to tasks. It includes:
Temporary information that persists during a single conversation.
// Short-term context for a conversation
const context = {
conversationId: 'conv_123',
userId: 'user_456',
sessionData: {
currentTask: 'email_drafting',
preferences: {
tone: 'professional',
length: 'medium'
}
}
};
Persistent information that spans multiple conversations.
// Long-term user preferences
const userMemory = {
userId: 'user_456',
preferences: {
communicationStyle: 'formal',
timezone: 'PST',
language: 'en-US'
},
history: {
commonTasks: ['email_drafting', 'data_analysis'],
preferredIntegrations: ['gmail', 'slack']
}
};
Temporary storage for active task processing.
// Working memory during task execution
const workingMemory = {
taskId: 'task_789',
currentStep: 3,
intermediateResults: {
step1: 'data_analyzed',
step2: 'insights_generated',
step3: 'report_drafting'
},
variables: {
dataSource: 'sales_db',
reportFormat: 'executive_summary'
}
};
// Set initial context
await agent.setContext({
userId: 'user_123',
sessionId: 'session_456',
preferences: {
tone: 'professional',
detailLevel: 'high'
}
});
// Update context during conversation
await agent.updateContext({
currentTask: 'email_drafting',
recipient: 'client@example.com',
subject: 'Project Update'
});
// Get current context
const context = await agent.getContext();
// Get specific context data
const userPrefs = await agent.getContext('preferences');
const taskState = await agent.getContext('currentTask');
// Save context for later use
await agent.saveContext({
key: 'user_preferences',
data: {
communicationStyle: 'formal',
timezone: 'PST'
},
ttl: 86400 // 24 hours
});
// Retrieve saved context
const savedContext = await agent.getSavedContext('user_preferences');
Limit the amount of context to maintain performance.
// Configure context window
await agent.configureMemory({
maxContextLength: 4000,
contextWindow: 'sliding', // or 'fixed'
retentionPolicy: 'lru' // least recently used
});
Compress old context to save space.
// Enable context summarization
await agent.enableSummarization({
threshold: 3000, // Summarize when context exceeds this
method: 'extractive', // or 'abstractive'
preserveKey: true // Keep important information
});
Choose what to remember based on importance.
// Configure selective memory
await agent.configureSelectiveMemory({
importanceThreshold: 0.7,
categories: ['user_preferences', 'task_outcomes'],
autoForget: ['temporary_data', 'debug_info']
});
// Execute task with context
const result = await agent.execute({
task: 'Draft a follow-up email',
context: {
previousEmails: [
'Initial inquiry about pricing',
'Scheduled demo call'
],
recipient: 'prospect@company.com',
meetingOutcome: 'positive_interest'
}
});
// Agent automatically uses context
const response = await agent.execute({
task: 'Respond to customer inquiry',
context: {
customerHistory: {
previousIssues: ['billing_dispute', 'feature_request'],
satisfaction: 'high',
tier: 'premium'
},
currentIssue: 'technical_support'
}
});
// Use efficient data structures
const context = {
// Use references instead of duplicating data
userId: 'user_123',
taskRefs: ['task_456', 'task_789'],
// Compress large data
compressedData: await compress(largeDataset),
// Use timestamps for temporal data
lastUpdated: Date.now()
};
// Regular cleanup of old context
await agent.cleanupMemory({
olderThan: 7 * 24 * 60 * 60 * 1000, // 7 days
keepImportant: true,
compressOld: true
});
// Monitor memory usage
const memoryStats = await agent.getMemoryStats();
console.log('Memory usage:', {
totalSize: memoryStats.totalSize,
contextCount: memoryStats.contextCount,
averageContextSize: memoryStats.averageContextSize
});
// Inherit context from parent task
const childTask = await agent.execute({
task: 'Generate detailed report',
context: {
inheritFrom: 'parent_task_123',
additionalContext: {
detailLevel: 'high',
includeCharts: true
}
}
});
// Share context between agents
await agent.shareContext({
targetAgent: 'analytics_agent',
contextKeys: ['user_preferences', 'data_sources'],
permissions: 'read_only'
});
// Validate context before use
const isValid = await agent.validateContext({
required: ['userId', 'taskType'],
optional: ['preferences', 'history'],
constraints: {
userId: 'string',
taskType: ['email', 'analysis', 'automation']
}
});