Quick Start
Welcome to the VigilAI SDK documentation! This guide will help you integrate AI-powered error monitoring and automated code fixes into your application.
You will learn
- How to install and initialize the SDK
- How to add monitoring to your application
- How to configure anomaly detection
- How to enable AI-powered diagnosis
- How to automate code fixes with GitHub integration
Installation
Install the VigilAI SDK using your package manager:
npm install @vigilai/sdk
Creating your first monitored application
VigilAI SDK integrates seamlessly with popular frameworks. Here's how to get started with Express.js:
import express from 'express';
import { VigilAI } from '@vigilai/sdk';
const app = express();
// Initialize VigilAI
const vigilai = new VigilAI({
apiKey: process.env.VIGILAI_API_KEY,
});
await vigilai.initialize();
// Add middleware
app.use(vigilai.expressMiddleware());
// Your routes
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000);
Configuration
Customize VigilAI's behavior with configuration options:
const vigilai = new VigilAI({
apiKey: 'your-api-key',
// Monitoring configuration
monitoring: {
interval: 60000, // Metric collection interval (ms)
samplingRate: 1.0, // Sample 100% of requests
bufferSize: 1000, // Max events in buffer
},
// Performance thresholds
thresholds: {
responseTime: 1000, // Max response time (ms)
errorRate: 5, // Max error rate (%)
memoryUsage: 500, // Max memory usage (MB)
cpuUsage: 80, // Max CPU usage (%)
},
// Anomaly detection
anomalyDetection: {
sensitivity: 2, // Z-score threshold
deduplicationWindow: 300000, // 5 minutes
},
// Security
security: {
enablePIIRedaction: true,
dataRetentionPeriod: 7 * 24 * 60 * 60 * 1000, // 7 days
},
});
Monitoring
VigilAI automatically monitors your application's performance and health. It captures:
HTTP Metrics
Response times, status codes, throughput
Error Tracking
Exceptions with full stack traces
System Metrics
CPU usage, memory consumption
Custom Metrics
Track your own business metrics
Manual Instrumentation
Track custom metrics and errors manually:
// Track custom metrics
vigilai.trackMetric('user.login.count', 1);
vigilai.trackMetric('cache.hit_rate', 0.95);
// Track errors with context
try {
// Some operation
} catch (error) {
vigilai.trackError(error as Error, {
operation: 'database_query',
userId: '12345'
});
}
Anomaly Detection
VigilAI uses statistical analysis to detect anomalies in your application's behavior:
- Baseline Calculation: Learns normal behavior from historical data
- Z-score Detection: Identifies outliers using statistical methods
- Threshold Violations: Alerts when metrics exceed configured limits
- Incident Deduplication: Groups similar incidents to reduce noise
AI-Powered Diagnosis
When an incident is detected, VigilAI uses AI (powered by AWS Bedrock) to diagnose the root cause:
// AI diagnosis happens automatically
// View results in the VigilAI dashboard
// Or trigger manually via API
const response = await fetch('/api/incidents/{id}/analyze', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`
}
});
const diagnosis = await response.json();
console.log(diagnosis.aiDiagnosis);
console.log(diagnosis.suggestedFix);
Automated Code Fixes
VigilAI can automatically generate code fixes and create pull requests:
Error Detection
SDK captures error with full stack trace
AI Analysis
AWS Bedrock analyzes error and generates fix
PR Creation
Automatic pull request created on GitHub
Review & Merge
Developer reviews and merges the fix
GitHub Integration
Configure GitHub integration in your application settings:
// Set environment variables
GITHUB_TOKEN=your_github_token
GITHUB_OWNER=your-username
GITHUB_REPO=your-repo
// Or configure via dashboard
// Settings > Applications > GitHub Repository
Express.js Integration
Complete example of integrating VigilAI with Express.js:
import express from 'express';
import { VigilAI } from '@vigilai/sdk';
const app = express();
// Initialize VigilAI
const vigilai = new VigilAI({
apiKey: process.env.VIGILAI_API_KEY,
monitoring: {
interval: 60000,
samplingRate: 1.0,
bufferSize: 1000,
},
thresholds: {
responseTime: 1000,
errorRate: 5,
memoryUsage: 500,
cpuUsage: 80,
},
});
await vigilai.initialize();
// Add middleware
app.use(express.json());
app.use(vigilai.expressMiddleware());
// Your routes
app.get('/', (req, res) => {
res.json({ message: 'Hello World!' });
});
app.post('/api/users', (req, res) => {
const { name } = req.body;
// Track custom metric
vigilai.trackMetric('user.created', 1);
res.status(201).json({ id: 3, name });
});
// Health check
app.get('/health', (req, res) => {
const health = vigilai.healthCheck();
res.json(health);
});
// Graceful shutdown
process.on('SIGTERM', async () => {
await vigilai.shutdown();
process.exit(0);
});
app.listen(3000);
Next.js Integration
Integrate VigilAI with Next.js using middleware:
App Router (Next.js 13+)
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { VigilAI } from '@vigilai/sdk';
const vigilai = new VigilAI({
apiKey: process.env.VIGILAI_API_KEY,
});
await vigilai.initialize();
export async function middleware(request: NextRequest) {
return vigilai.nextMiddleware(request, async (req) => {
// Skip monitoring for static assets
const url = new URL(req.url);
if (url.pathname.startsWith('/_next/')) {
return NextResponse.next();
}
const response = NextResponse.next();
response.headers.set('X-Monitored-By', 'VigilAI');
return response;
});
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
API Routes
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { vigilai } from '@/lib/vigilai';
export async function GET(request: NextRequest) {
return vigilai.nextMiddleware(request, async () => {
const users = await fetchUsers();
return NextResponse.json(users);
});
}
export async function POST(request: NextRequest) {
return vigilai.nextMiddleware(request, async () => {
const body = await request.json();
const user = await createUser(body);
// Track custom metric
vigilai.trackMetric('user.created', 1);
return NextResponse.json(user, { status: 201 });
});
}
Django Integration
Integrate VigilAI with Django using middleware:
Step 1: Initialize SDK
# settings.py or __init__.py
from vigilai import VigilAI, VigilAIConfig
vigilai = VigilAI(VigilAIConfig(
api_key=os.environ.get('VIGILAI_API_KEY'),
monitoring_interval=60000,
thresholds={
'response_time': 1000,
'error_rate': 5,
'memory_usage': 500,
'cpu_usage': 80,
}
))
Step 2: Add Middleware
# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# Add VigilAI middleware
vigilai.django_middleware(),
]
Step 3: Use in Views
# views.py
from django.http import JsonResponse
from django.views import View
class UserListView(View):
def get(self, request):
users = User.objects.all()
return JsonResponse({
'users': list(users.values())
})
def post(self, request):
data = json.loads(request.body)
user = User.objects.create(**data)
# Track custom metric
vigilai.track_metric('user.created', 1)
return JsonResponse({'user': user.to_dict()}, status=201)
FastAPI Integration
Integrate VigilAI with FastAPI using middleware:
from fastapi import FastAPI, HTTPException
from vigilai import VigilAI, VigilAIConfig
# Initialize VigilAI
config = VigilAIConfig(
api_key="your-api-key",
monitoring={"interval": 60000, "sampling_rate": 1.0},
thresholds={
"response_time": 1000,
"error_rate": 5,
"memory_usage": 500,
"cpu_usage": 80,
}
)
vigilai = VigilAI(config)
# Create FastAPI app
app = FastAPI(title="My API")
# Add VigilAI middleware
app.middleware("http")(vigilai.fastapi_middleware())
@app.on_event("startup")
async def startup_event():
await vigilai.initialize()
print("VigilAI initialized")
@app.on_event("shutdown")
async def shutdown_event():
await vigilai.shutdown()
print("VigilAI shutdown complete")
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.post("/users")
async def create_user(user: UserCreate):
user = await create_user_in_db(user)
# Track custom metric
vigilai.track_metric('user.created', 1)
return user
@app.get("/health")
async def health():
health = vigilai.health_check()
return health
Manual Tracking
Track custom metrics and errors manually:
// Track custom metrics
vigilai.trackMetric('user.login.count', 1);
vigilai.trackMetric('cache.hit_rate', 0.95);
vigilai.trackMetric('queue.size', 42);
vigilai.trackMetric('payment.amount', 99.99);
// Track errors with context
try {
await performDatabaseQuery();
} catch (error) {
vigilai.trackError(error as Error, {
operation: 'database_query',
userId: '12345',
query: 'SELECT * FROM users',
});
throw error;
}
Python
# Track custom metrics
vigilai.track_metric('user.login.count', 1)
vigilai.track_metric('cache.hit_rate', 0.95)
vigilai.track_metric('queue.size', 42)
# Track errors with context
try:
perform_database_query()
except Exception as error:
vigilai.track_error(error, {
'operation': 'database_query',
'user_id': '12345',
'query': 'SELECT * FROM users',
})
raise
Health Check
Check the SDK's health status:
const health = vigilai.healthCheck();
console.log(`Status: ${health.status}`);
console.log(`Buffer size: ${health.metrics.bufferSize}`);
console.log(`Success rate: ${health.metrics.transmissionSuccessRate}%`);
console.log(`Last transmission: ${health.metrics.lastTransmission}`);
Graceful Shutdown
Ensure all buffered data is sent before shutdown:
Node.js / TypeScript
process.on('SIGTERM', async () => {
console.log('SIGTERM received, shutting down gracefully');
await vigilai.shutdown();
process.exit(0);
});
process.on('SIGINT', async () => {
console.log('SIGINT received, shutting down gracefully');
await vigilai.shutdown();
process.exit(0);
});
Python
import signal
import asyncio
async def shutdown(sig, loop):
await vigilai.shutdown()
loop.stop()
loop = asyncio.get_event_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(
sig,
lambda: asyncio.create_task(shutdown(sig, loop))
)