Connect agents with external services and databases
Connect agents with external APIs and services
Learn how to connect your Fantomu agents with external APIs and services to extend their capabilities.
API integrations allow your agents to:
Most common integration type for web services.
// Configure REST API integration
await agent.integrations.add({
type: 'rest_api',
name: 'Weather Service',
baseUrl: 'https://api.weather.com/v1',
authentication: {
type: 'api_key',
key: 'weather_api_key',
header: 'X-API-Key'
},
endpoints: {
current: '/current',
forecast: '/forecast'
}
});
For more complex data queries and mutations.
// Configure GraphQL integration
await agent.integrations.add({
type: 'graphql',
name: 'Content Management',
endpoint: 'https://api.cms.com/graphql',
authentication: {
type: 'bearer_token',
token: 'cms_bearer_token'
},
queries: {
getPosts: `query GetPosts($limit: Int) {
posts(limit: $limit) {
id
title
content
publishedAt
}
}`
}
});
For real-time data streaming.
// Configure WebSocket integration
await agent.integrations.add({
type: 'websocket',
name: 'Real-time Updates',
url: 'wss://api.realtime.com/stream',
authentication: {
type: 'query_param',
key: 'token',
value: 'realtime_token'
},
events: {
'user_online': 'handleUserOnline',
'message_received': 'handleMessage'
}
});
const integration = {
type: 'rest_api',
authentication: {
type: 'api_key',
key: 'your_api_key',
header: 'Authorization', // or 'X-API-Key'
prefix: 'Bearer' // optional
}
};
const integration = {
type: 'oauth2',
authentication: {
clientId: 'your_client_id',
clientSecret: 'your_client_secret',
authorizationUrl: 'https://api.service.com/oauth/authorize',
tokenUrl: 'https://api.service.com/oauth/token',
scope: ['read', 'write'],
redirectUri: 'https://your-app.com/oauth/callback'
}
};
const integration = {
type: 'rest_api',
authentication: {
type: 'basic',
username: 'your_username',
password: 'your_password'
}
};
const result = await agent.execute({
task: 'Get current weather for New York',
context: {
city: 'New York',
integration: 'weather_service'
}
});
const result = await agent.execute({
task: 'Create a new blog post and publish it',
context: {
title: 'AI Trends 2024',
content: 'Content about AI trends...',
integrations: {
cms: 'content_management',
social: 'social_media'
}
}
});
const integration = {
type: 'rest_api',
errorHandling: {
retries: 3,
retryDelay: 1000,
retryCondition: (error) => error.status >= 500
}
};
const integration = {
type: 'rest_api',
errorHandling: {
onError: 'use_cached_data',
fallback: {
type: 'cache',
ttl: 3600 // 1 hour
}
}
};
const integration = {
type: 'rest_api',
rateLimiting: {
requestsPerMinute: 60,
requestsPerHour: 1000,
burstLimit: 10
}
};
const integration = {
type: 'rest_api',
rateLimiting: {
onLimitExceeded: 'wait_and_retry',
backoffStrategy: 'exponential'
}
};
const integration = {
type: 'rest_api',
transformations: {
input: (data) => ({
query: data.searchTerm,
limit: data.maxResults || 10,
sort: data.sortBy || 'relevance'
})
}
};
const integration = {
type: 'rest_api',
transformations: {
output: (response) => ({
results: response.data.items.map(item => ({
id: item.id,
title: item.title,
url: item.link,
snippet: item.snippet
})),
total: response.data.totalResults
})
}
};
// Test integration configuration
const testResult = await agent.testIntegration({
integrationId: 'weather_service',
testData: {
city: 'London',
country: 'UK'
}
});
console.log('Integration test result:', testResult);
// Test with real API
const liveTest = await agent.testIntegration({
integrationId: 'weather_service',
live: true,
testData: {
city: 'London',
country: 'UK'
}
});
const metrics = await agent.getIntegrationMetrics({
integrationId: 'weather_service',
period: '7d',
metrics: [
'request_count',
'success_rate',
'average_response_time',
'error_rate'
]
});
const logs = await agent.getIntegrationLogs({
integrationId: 'weather_service',
level: 'error',
limit: 100
});
Set up webhooks for real-time notifications
Learn how to set up and use webhooks to receive real-time notifications from Fantomu agents and external services.
Webhooks are HTTP callbacks that allow external services to send real-time notifications to your application when specific events occur. They enable:
Events related to agent execution and performance.
// Configure agent webhooks
await agent.webhooks.create({
url: 'https://your-app.com/webhooks/agent',
events: [
'task_started',
'task_completed',
'task_failed',
'agent_updated'
],
secret: 'your_webhook_secret'
});
Events related to workflow execution.
// Configure workflow webhooks
await workflow.webhooks.create({
url: 'https://your-app.com/webhooks/workflow',
events: [
'workflow_started',
'workflow_completed',
'workflow_failed',
'step_completed'
],
secret: 'your_webhook_secret'
});
Define your own custom events.
// Configure custom webhooks
await agent.webhooks.create({
url: 'https://your-app.com/webhooks/custom',
events: [
'user_registered',
'payment_completed',
'content_published'
],
secret: 'your_webhook_secret'
});
{
"event": "task_completed",
"timestamp": "2024-01-15T10:30:00Z",
"data": {
"agentId": "agent_123",
"taskId": "task_456",
"executionId": "exec_789",
"result": {
"success": true,
"output": "Task completed successfully"
},
"duration": 1500,
"metadata": {
"userId": "user_123",
"sessionId": "session_456"
}
}
}
// Configure custom payload
await agent.webhooks.create({
url: 'https://your-app.com/webhooks/custom',
events: ['task_completed'],
payload: {
customField: 'custom_value',
includeMetadata: true,
transform: (data) => ({
id: data.taskId,
status: data.result.success ? 'success' : 'failed',
timestamp: data.timestamp
})
}
});
// Verify webhook signature
const crypto = require('crypto');
function verifyWebhookSignature(payload, signature, secret) {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
}
// Store webhook secrets securely
const webhookSecret = process.env.WEBHOOK_SECRET;
await agent.webhooks.create({
url: 'https://your-app.com/webhooks/agent',
events: ['task_completed'],
secret: webhookSecret
});
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.raw({ type: 'application/json' }));
app.post('/webhooks/agent', (req, res) => {
const signature = req.headers['x-fantomu-signature'];
const payload = req.body;
// Verify signature
if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
const event = JSON.parse(payload);
// Handle the event
switch (event.event) {
case 'task_completed':
handleTaskCompleted(event.data);
break;
case 'task_failed':
handleTaskFailed(event.data);
break;
default:
console.log('Unknown event:', event.event);
}
res.status(200).send('OK');
});
// pages/api/webhooks/agent.js
import crypto from 'crypto';
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ message: 'Method not allowed' });
}
const signature = req.headers['x-fantomu-signature'];
const payload = JSON.stringify(req.body);
// Verify signature
const expectedSignature = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(payload)
.digest('hex');
if (signature !== expectedSignature) {
return res.status(401).json({ message: 'Invalid signature' });
}
const event = req.body;
// Handle the event
await handleWebhookEvent(event);
res.status(200).json({ message: 'OK' });
}
// Configure retry logic
await agent.webhooks.create({
url: 'https://your-app.com/webhooks/agent',
events: ['task_completed'],
retry: {
maxAttempts: 3,
backoffStrategy: 'exponential',
maxDelay: 30000
}
});
// Retry failed webhook
await agent.webhooks.retry({
webhookId: 'webhook_123',
eventId: 'event_456'
});
// Check webhook delivery status
const status = await agent.webhooks.getStatus({
webhookId: 'webhook_123',
eventId: 'event_456'
});
console.log('Delivery status:', status);
// Get webhook analytics
const analytics = await agent.webhooks.getAnalytics({
webhookId: 'webhook_123',
period: '7d',
metrics: [
'delivery_rate',
'success_rate',
'average_response_time',
'error_rate'
]
});
// Test webhook endpoint
const testResult = await agent.webhooks.test({
webhookId: 'webhook_123',
testEvent: {
event: 'task_completed',
data: {
taskId: 'test_task',
result: { success: true }
}
}
});
// Use ngrok for local testing
const webhook = await agent.webhooks.create({
url: 'https://abc123.ngrok.io/webhooks/agent',
events: ['task_completed'],
secret: 'your_webhook_secret'
});
Connect agents to databases for data persistence
Learn how to connect your Fantomu agents to databases for data persistence, querying, and real-time updates.
// Configure PostgreSQL connection
await agent.databases.add({
name: 'main_database',
type: 'postgresql',
connection: {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_NAME,
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
ssl: true
},
pool: {
min: 2,
max: 10,
idleTimeoutMillis: 30000
}
});
// Configure MongoDB connection
await agent.databases.add({
name: 'document_store',
type: 'mongodb',
connection: {
uri: process.env.MONGODB_URI,
database: 'myapp',
options: {
useNewUrlParser: true,
useUnifiedTopology: true
}
}
});
// Configure Redis connection
await agent.databases.add({
name: 'cache_store',
type: 'redis',
connection: {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PASSWORD,
db: 0
}
});
// Execute SQL query
const result = await agent.execute({
task: 'Get user information',
context: {
database: 'main_database',
query: 'SELECT * FROM users WHERE id = ?',
parameters: [userId]
}
});
// Execute MongoDB query
const result = await agent.execute({
task: 'Find user documents',
context: {
database: 'document_store',
collection: 'users',
query: {
status: 'active',
createdAt: { $gte: new Date('2024-01-01') }
}
}
});
// Execute Redis operations
const result = await agent.execute({
task: 'Cache user session',
context: {
database: 'cache_store',
operation: 'set',
key: `session:${sessionId}`,
value: JSON.stringify(sessionData),
ttl: 3600
}
});
// Insert new record
const result = await agent.execute({
task: 'Create new user',
context: {
database: 'main_database',
operation: 'insert',
table: 'users',
data: {
name: 'John Doe',
email: 'john@example.com',
createdAt: new Date()
}
}
});
// Update existing record
const result = await agent.execute({
task: 'Update user profile',
context: {
database: 'main_database',
operation: 'update',
table: 'users',
where: { id: userId },
data: {
name: 'John Smith',
updatedAt: new Date()
}
}
});
// Delete record
const result = await agent.execute({
task: 'Delete user account',
context: {
database: 'main_database',
operation: 'delete',
table: 'users',
where: { id: userId }
}
});
// Execute transaction
const result = await agent.execute({
task: 'Transfer funds between accounts',
context: {
database: 'main_database',
transaction: true,
operations: [
{
type: 'update',
table: 'accounts',
where: { id: fromAccountId },
data: { balance: 'balance - ?' },
parameters: [amount]
},
{
type: 'update',
table: 'accounts',
where: { id: toAccountId },
data: { balance: 'balance + ?' },
parameters: [amount]
}
]
}
});
// Execute MongoDB transaction
const result = await agent.execute({
task: 'Update multiple documents',
context: {
database: 'document_store',
transaction: true,
operations: [
{
collection: 'users',
operation: 'updateOne',
filter: { _id: userId },
update: { $set: { status: 'inactive' } }
},
{
collection: 'sessions',
operation: 'deleteMany',
filter: { userId: userId }
}
]
}
});
// Configure schema validation
await agent.databases.configureValidation({
database: 'main_database',
table: 'users',
schema: {
name: { type: 'string', required: true, maxLength: 100 },
email: { type: 'string', required: true, format: 'email' },
age: { type: 'number', min: 0, max: 150 }
}
});
// Configure data sanitization
await agent.databases.configureSanitization({
database: 'main_database',
table: 'users',
sanitization: {
name: 'trim,escape',
email: 'trim,lowercase',
bio: 'trim,stripHtml'
}
});
// Configure connection pooling
await agent.databases.configurePooling({
database: 'main_database',
pool: {
min: 5,
max: 20,
acquireTimeoutMillis: 60000,
idleTimeoutMillis: 300000
}
});
// Configure query optimization
await agent.databases.configureOptimization({
database: 'main_database',
optimization: {
enableQueryCache: true,
cacheSize: 1000,
enableIndexHints: true,
maxQueryTime: 5000
}
});
// Configure database caching
await agent.databases.configureCaching({
database: 'main_database',
cache: {
enabled: true,
ttl: 300, // 5 minutes
maxSize: 10000,
strategy: 'lru'
}
});
// Get database metrics
const metrics = await agent.databases.getMetrics({
database: 'main_database',
period: '1h',
metrics: [
'connection_count',
'query_count',
'average_query_time',
'error_rate'
]
});
// Configure query logging
await agent.databases.configureLogging({
database: 'main_database',
logging: {
enabled: true,
level: 'info',
logSlowQueries: true,
slowQueryThreshold: 1000
}
});
// Configure access control
await agent.databases.configureAccess({
database: 'main_database',
access: {
readOnly: false,
allowedTables: ['users', 'posts'],
restrictedColumns: ['password', 'ssn'],
ipWhitelist: ['192.168.1.0/24']
}
});
// Configure encryption
await agent.databases.configureEncryption({
database: 'main_database',
encryption: {
enabled: true,
algorithm: 'AES-256-GCM',
keyRotation: 'monthly'
}
});