Skip to content

Building Your First Agent

Learn how to build, deploy, and manage your first AI agent using Connix. This tutorial will guide you through creating a simple but powerful agent that can process data and interact with external APIs.

By the end of this guide, you’ll have:

  • ✅ A working AI agent deployed on Connix
  • ✅ Understanding of agent lifecycle management
  • ✅ Knowledge of agent communication patterns
  • ✅ Experience with Connix’s orchestration features

Let’s build a Data Analysis Agent that can:

  1. Accept datasets in various formats
  2. Perform statistical analysis
  3. Generate insights and summaries
  4. Return structured results
graph LR
A[Input Data] --> B[Data Validation]
B --> C[Statistical Analysis]
C --> D[Insight Generation]
D --> E[Results Output]

First, create a project to house your agent:

import { ConnixClient } from '@connix/sdk';
const client = new ConnixClient();
async function createProject() {
const project = await client.createProject({
name: 'data-analysis-workspace',
description: 'Workspace for data analysis agents'
});
console.log(`📊 Project created: ${project.name} (ID: ${project.id})`);
return project;
}
const project = await createProject();

Create a configuration for your data analysis agent:

const agentConfig = {
name: 'data-analyzer-v1',
projectId: project.id,
capabilities: [
'data-processing',
'statistical-analysis',
'report-generation'
],
resources: {
memory: '2GB',
cpu: '1 core',
storage: '10GB'
},
environment: {
'PYTHON_VERSION': '3.11',
'PANDAS_VERSION': '2.0.0',
'NUMPY_VERSION': '1.24.0'
}
};

Deploy the agent to Connix:

async function launchAgent(config) {
try {
console.log('🚀 Launching agent...');
const agent = await client.launchAgent({
name: config.name,
projectId: config.projectId
});
console.log(`✅ Agent launched successfully!`);
console.log(` Agent: ${config.name}`);
console.log(` Status: ${agent.message}`);
console.log(` Project: ${config.projectId}`);
return agent;
} catch (error) {
console.error('❌ Failed to launch agent:', error.message);
throw error;
}
}
const agent = await launchAgent(agentConfig);

Now let’s implement the core functionality. In a real scenario, this would be deployed as part of your agent container:

class DataAnalysisAgent {
constructor(agentId, projectId) {
this.agentId = agentId;
this.projectId = projectId;
this.client = new ConnixClient();
}
async processDataset(data) {
console.log('📊 Processing dataset...');
// Validate input data
if (!this.validateData(data)) {
throw new Error('Invalid data format');
}
// Perform statistical analysis
const stats = this.calculateStatistics(data);
// Generate insights
const insights = this.generateInsights(stats);
// Return structured results
return {
summary: stats,
insights: insights,
processedAt: new Date().toISOString(),
agentId: this.agentId
};
}
validateData(data) {
return Array.isArray(data) && data.length > 0;
}
calculateStatistics(data) {
const numbers = data.filter(item => typeof item === 'number');
if (numbers.length === 0) {
throw new Error('No numeric data found');
}
const sum = numbers.reduce((a, b) => a + b, 0);
const mean = sum / numbers.length;
const sorted = numbers.sort((a, b) => a - b);
const median = sorted[Math.floor(sorted.length / 2)];
return {
count: numbers.length,
sum: sum,
mean: mean,
median: median,
min: Math.min(...numbers),
max: Math.max(...numbers)
};
}
generateInsights(stats) {
const insights = [];
if (stats.mean > stats.median) {
insights.push('Data is right-skewed (mean > median)');
} else if (stats.mean < stats.median) {
insights.push('Data is left-skewed (mean < median)');
} else {
insights.push('Data appears to be normally distributed');
}
const range = stats.max - stats.min;
insights.push(`Data range: ${range} (${stats.min} to ${stats.max})`);
return insights;
}
}
// Example usage
const analysisAgent = new DataAnalysisAgent(agent.id, project.id);
// Test with sample data
const sampleData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20];
const results = await analysisAgent.processDataset(sampleData);
console.log('📈 Analysis Results:');
console.log(JSON.stringify(results, null, 2));

Implement monitoring to track your agent’s performance:

class AgentMonitor {
constructor(client, projectId) {
this.client = client;
this.projectId = projectId;
this.metrics = {
requestsProcessed: 0,
totalProcessingTime: 0,
errors: 0,
lastActivity: null
};
}
async logActivity(activity, duration = null, error = null) {
this.metrics.lastActivity = new Date();
if (error) {
this.metrics.errors++;
console.error(`❌ Agent error in ${activity}:`, error.message);
} else {
this.metrics.requestsProcessed++;
if (duration) {
this.metrics.totalProcessingTime += duration;
}
console.log(`✅ Agent completed ${activity} ${duration ? `in ${duration}ms` : ''}`);
}
// Log metrics every 10 requests
if (this.metrics.requestsProcessed % 10 === 0) {
this.printMetrics();
}
}
printMetrics() {
const avgProcessingTime = this.metrics.totalProcessingTime / this.metrics.requestsProcessed;
console.log('\n📊 Agent Performance Metrics:');
console.log(` Requests Processed: ${this.metrics.requestsProcessed}`);
console.log(` Average Processing Time: ${avgProcessingTime.toFixed(2)}ms`);
console.log(` Errors: ${this.metrics.errors}`);
console.log(` Success Rate: ${((this.metrics.requestsProcessed - this.metrics.errors) / this.metrics.requestsProcessed * 100).toFixed(2)}%`);
console.log(` Last Activity: ${this.metrics.lastActivity}\n`);
}
}
// Enhanced agent with monitoring
class MonitoredDataAnalysisAgent extends DataAnalysisAgent {
constructor(agentId, projectId) {
super(agentId, projectId);
this.monitor = new AgentMonitor(this.client, projectId);
}
async processDataset(data) {
const startTime = Date.now();
try {
const result = await super.processDataset(data);
const duration = Date.now() - startTime;
await this.monitor.logActivity('data processing', duration);
return result;
} catch (error) {
await this.monitor.logActivity('data processing', null, error);
throw error;
}
}
}

Run comprehensive tests to ensure your agent works correctly:

async function testAgent() {
console.log('🧪 Testing Data Analysis Agent...\n');
const agent = new MonitoredDataAnalysisAgent('test-agent', project.id);
// Test cases
const testCases = [
{
name: 'Normal Distribution',
data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
},
{
name: 'Right Skewed',
data: [1, 1, 2, 2, 3, 8, 9, 10, 15, 20]
},
{
name: 'Mixed Data Types',
data: [1, 'text', 2, null, 3, 4, 'more text', 5]
},
{
name: 'Large Dataset',
data: Array.from({length: 1000}, () => Math.random() * 100)
}
];
for (const testCase of testCases) {
try {
console.log(`Testing: ${testCase.name}`);
const result = await agent.processDataset(testCase.data);
console.log(`${testCase.name}: Passed`);
console.log(` Insights: ${result.insights.join(', ')}\n`);
} catch (error) {
console.log(`${testCase.name}: Failed - ${error.message}\n`);
}
}
console.log('🎉 Agent testing completed!');
}
await testAgent();

Check that your agent is running correctly in the Connix platform:

async function checkAgentStatus() {
try {
// List all projects to verify our agent's project exists
const projects = await client.listProjects();
const ourProject = projects.projects.find(p => p.id === project.id);
if (ourProject) {
console.log('✅ Project found:', ourProject.name);
// In a real implementation, you would have endpoints to check agent status
// For now, we'll simulate this
console.log('✅ Agent status: Running');
console.log('✅ Agent health: Good');
console.log('✅ Last heartbeat:', new Date().toISOString());
} else {
console.log('❌ Project not found');
}
} catch (error) {
console.error('❌ Failed to check agent status:', error.message);
}
}
await checkAgentStatus();

Congratulations! You’ve successfully built and deployed your first AI agent. Here’s what you can do next:

  • Add more capabilities: Extend the analysis with visualization, machine learning, or external API integrations
  • Implement real-time processing: Handle streaming data or real-time requests
  • Add persistence: Store results in databases or file systems
  • Create agent networks: Build multiple agents that work together
  • Environment configuration: Set up proper environment variables and secrets
  • Monitoring & alerting: Implement comprehensive logging and monitoring
  • Error handling: Add robust error handling and recovery mechanisms
  • Security: Implement proper authentication and authorization

Happy building! 🚀