Containers API
Learn how to provision and manage containerized workloads for your AI agents using Cognitora's Containers API with hardware-level isolation.
The Cognitora Containers API enables you to autonomously provision, execute, and manage containerized workloads in secure Firecracker microVMs. Each container runs with hardware-level isolation, providing enterprise-grade security with sub-second cold starts.
Understanding Containers in Cognitora
Cognitora's compute platform is built around containers as the fundamental execution units. Unlike traditional cloud platforms, every workload runs in a dedicated Firecracker microVM, ensuring complete isolation and security for AI agent operations.
Container Types
Cognitora supports three types of containers, each optimized for different use cases:
- COMPUTE: Long-running compute jobs with custom commands and full resource control
- SESSION: Persistent interactive containers for code interpreter sessions with state management
- ONE_OFF: Temporary containers for single code executions with automatic cleanup
Key Features
- Hardware Isolation: Each container runs in a dedicated Firecracker microVM
- Secure Runtime: Kata Containers provide secure container execution
- Fast Startup: Sub-second cold start times optimized for agent workloads
- Resource Isolation: Dedicated CPU, memory, and storage allocation
- Networking Control: Optional internet access with security-first defaults
- Real-time Monitoring: Live status updates and log streaming
- Container Persistence: SESSION containers maintain state across executions
- Execution Tracking: Comprehensive execution history and management
Basic Container Creation
cURL Example
Here's how to create a basic container using the new containers endpoint:
API_URL="https://api.cognitora.dev"
# Create secure microVM container
curl -X POST $API_URL/api/v1/compute/containers \
-H "Authorization: Bearer <api-key>" \
-H "Content-Type: application/json" \
-d '{
"image": "docker.io/library/python:3.11-alpine",
"command": ["python", "-c", "print(\"Hello from secure microVM!\")"],
"cpuCores": 1,
"memoryMb": 512,
"storageGb": 5,
"maxCostCredits": 100,
"timeoutSeconds": 300
}'
Python SDK Example
from cognitora import Cognitora
client = Cognitora(api_key="your_api_key")
# Create a secure container (isolated by default)
container = client.containers.create_container(
image="docker.io/library/python:3.11-slim",
command=["python", "-c", "print('Hello from secure Cognitora container!')"],
cpu_cores=1.0,
memory_mb=512,
storage_gb=5,
max_cost_credits=100,
networking=False # Default: isolated for security
)
print(f"Container ID: {container.id}")
print(f"Status: {container.status}")
# Create a container with networking enabled when needed
network_container = client.containers.create_container(
image="docker.io/library/python:3.11",
command=["python", "-c", """
import requests
response = requests.get('https://api.github.com/users/octocat')
user_data = response.json()
print(f'GitHub user: {user_data["name"]}')
"""],
cpu_cores=1.0,
memory_mb=512,
storage_gb=5,
max_cost_credits=100,
networking=True # Enable networking for API calls
)
JavaScript/TypeScript SDK Example
import { Cognitora } from '@cognitora/sdk';
const client = new Cognitora({ apiKey: 'your_api_key' });
// Create a secure container (isolated by default)
const container = await client.containers.createContainer({
image: 'docker.io/library/node:18-alpine',
command: ['node', '-e', "console.log('Hello from secure Cognitora container!')"],
cpuCores: 1.0,
memoryMb: 512,
storageGb: 5,
maxCostCredits: 100,
networking: false // Default: isolated for security
});
console.log(`Container ID: ${container.id}`);
console.log(`Status: ${container.status}`);
// Create a container with networking enabled when needed
const networkContainer = await client.containers.createContainer({
image: 'docker.io/library/node:18',
command: ['node', '-e', `
const https = require('https');
https.get('https://api.github.com/users/octocat', (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
const user = JSON.parse(data);
console.log('GitHub user:', user.name);
});
});
`],
cpuCores: 1.0,
memoryMb: 512,
storageGb: 5,
maxCostCredits: 100,
networking: true // Enable networking for API calls
});
Networking Control
Containers support optional networking control for enhanced security:
Default Networking Behavior
Service | Default Networking | Security Rationale |
---|---|---|
Containers | false (disabled) | Security-first: isolated by default |
Secure Container Execution (Default)
# Secure, isolated container execution (default)
execution = client.containers.create_container(
image="docker.io/library/python:3.11",
command=["python", "-c", "print('Secure isolated computation')"],
cpu_cores=1.0,
memory_mb=512,
max_cost_credits=10,
networking=False # Default: isolated for security
)
Network-Enabled Container Execution
# Container with internet access for external API calls
execution = client.containers.create_container(
image="docker.io/library/python:3.11",
command=["python", "-c", """
import subprocess
import requests
# Install package (requires networking)
subprocess.run(['pip', 'install', 'requests'], check=True)
# Fetch external data
response = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
data = response.json()
print(f"Bitcoin price: {data['bpi']['USD']['rate']}")
"""],
cpu_cores=2.0,
memory_mb=1024,
max_cost_credits=20,
networking=True # Enable networking for package installs and API calls
)
Container Execution Management
List All Container Executions
# List all container executions across account
executions = client.containers.list_all_container_executions(
limit=50,
status='running'
)
print(f"Active containers: {len(executions)}")
for execution in executions:
print(f"Container {execution['id']}: {execution['status']}")
print(f" Image: {execution['image']}")
print(f" Runtime: {execution['runtime_seconds']}s")
Get Container Execution Details
# Get detailed information about a specific container execution
execution_details = client.containers.get_container_execution('exec_123456')
print(f"Execution status: {execution_details['status']}")
print(f"Command: {execution_details['command']}")
print(f"Exit code: {execution_details['exit_code']}")
print(f"Networking enabled: {execution_details['networking']}")
Container Execution History
# Get all executions for a specific container
container_executions = client.containers.get_container_executions('container_123456')
print(f"Container has {len(container_executions)} executions")
for execution in container_executions:
print(f"- {execution['status']}: {execution['runtime_seconds']}s")
JavaScript SDK Container Management
// List all container executions
const containerExecutions = await client.containers.listAllContainerExecutions({
limit: 50,
status: 'running'
});
console.log(`Active containers: ${containerExecutions.executions.length}`);
// Get specific container execution details
const executionDetails = await client.containers.getContainerExecution('exec_123456');
console.log(`Container execution: ${executionDetails.status}`);
// Get executions for specific container
const containerHistory = await client.containers.getContainerExecutions('container_123456');
console.log(`Container has ${containerHistory.executions.length} executions`);
Container Resource Management
Resource Specification
You can precisely control the resources allocated to your containers:
# High-performance container with GPU acceleration
execution = client.containers.create_container(
image="tensorflow/tensorflow:latest-gpu",
command=["python", "train_model.py"],
cpu_cores=8.0, # 8 CPU cores
memory_mb=32768, # 32GB memory
storage_gb=100, # 100GB storage
gpu_count=2, # 2 GPUs
max_cost_credits=5000,
timeout_seconds=7200, # 2 hours
networking=True # Enable networking for model downloads
)
Cost Estimation
Always estimate costs before creating expensive containers:
# Estimate cost before container creation
estimate = client.containers.estimate_cost(
cpu_cores=8.0,
memory_mb=32768,
storage_gb=100,
gpu_count=2,
timeout_seconds=7200
)
print(f"Estimated cost: {estimate.estimated_credits} credits")
# Create execution if cost is acceptable
if estimate.estimated_credits <= budget:
execution = client.containers.create_container(...)
Container Lifecycle Management
Monitoring Container Status
# Get container details and status
execution = client.containers.get_container("cnt_abc123def456")
print(f"Status: {execution.status}")
print(f"Actual cost: {execution.actual_cost_credits} credits")
print(f"Started at: {execution.started_at}")
# Container states: QUEUED, STARTING, RUNNING, IDLE, COMPLETED, FAILED, CANCELLED, TERMINATED, TIMEOUT
Retrieving Container Logs
# Get complete container logs
logs = client.containers.get_container_logs("cnt_abc123def456")
print("Container output:", logs.logs)
# cURL example for logs
curl -X GET $API_URL/api/v1/compute/containers/{container-id}/logs \
-H "Authorization: Bearer <api-key>"
Cancelling Containers
# Cancel a running container to stop charges
result = client.containers.cancel_container("cnt_abc123def456")
print(f"Container cancelled: {result.message}")
Container Execution Tracking
For SESSION containers, you can track individual executions within the container:
List Container Executions
# Get all executions for a specific container
executions = client.containers.list_containers(limit=50)
for execution in executions:
print(f"Container {execution.id}: {execution.status}")
print(f"Runtime: {execution.runtime_seconds}s")
Get Execution Details
# Get detailed information about a specific execution
execution = client.containers.get_container("exec_xyz789abc123")
print(f"Command executed: {execution.command}")
print(f"Exit code: {execution.exit_code}")
print(f"Error message: {execution.error_message}")
Advanced Container Configurations
Environment Variables and Secrets
# Container with environment variables
execution = client.containers.create_container(
image="my-registry/ai-agent:latest",
command=["python", "agent.py"],
cpu_cores=2.0,
memory_mb=4096,
environment={
"LOG_LEVEL": "INFO",
"API_ENDPOINT": "https://api.example.com",
"WORKER_ID": "agent-001",
"DEBUG": "false"
},
max_cost_credits=200,
networking=True # Enable networking for external API access
)
Custom Docker Images
# Use your own Docker image with specific configurations
execution = client.containers.create_container(
image="myregistry.com/my-ai-agent:v2.1.0",
command=["./run_agent.sh", "--config", "production"],
cpu_cores=4.0,
memory_mb=8192,
storage_gb=50,
environment={
"ENVIRONMENT": "production",
"SCALE_FACTOR": "10"
},
timeout_seconds=3600,
max_cost_credits=1000,
networking=True # Enable networking for production agent
)
Container Security Best Practices
Image Security
# Use specific image versions for reproducibility
execution = client.containers.create_container(
image="python:3.11.6-slim-bullseye", # Specific version
command=["python", "secure_script.py"],
cpu_cores=1.0,
memory_mb=512,
networking=False # Secure by default
)
# Use private registries for sensitive workloads
execution = client.containers.create_container(
image="your-private-registry.com/secure-agent:v1.2.3",
command=["./secure_agent"],
cpu_cores=2.0,
memory_mb=2048,
networking=False # Secure by default
)
Resource Limits
# Set conservative resource limits to prevent runaway costs
execution = client.containers.create_container(
image="untrusted-image:latest",
command=["python", "user_script.py"],
cpu_cores=1.0, # Limited CPU
memory_mb=512, # Limited memory
storage_gb=1, # Minimal storage
timeout_seconds=300, # 5-minute timeout
max_cost_credits=10, # Low cost limit
networking=False # Secure: no internet access for untrusted code
)
Container Monitoring and Debugging
Real-time Status Monitoring
async def monitor_execution(execution_id, check_interval=5):
"""Monitor execution status until completion"""
while True:
execution = await client.containers.get_container(execution_id)
print(f"Container {execution_id}: {execution.status}")
if execution.status in ['COMPLETED', 'FAILED', 'CANCELLED', 'TIMEOUT']:
print(f"Final status: {execution.status}")
print(f"Total cost: {execution.actual_cost_credits} credits")
print(f"Networking enabled: {execution.networking}")
# Get final logs
logs = await client.containers.get_container_logs(execution_id)
print("Final output:", logs.logs)
break
await asyncio.sleep(check_interval)
# Usage
await monitor_execution("cnt_abc123def456")
Execution Performance Analysis
def analyze_execution_performance(execution):
"""Analyze execution performance metrics"""
runtime_seconds = (execution.completed_at - execution.started_at).total_seconds()
cost_per_second = execution.actual_cost_credits / runtime_seconds
efficiency = {
"runtime_seconds": runtime_seconds,
"cost_per_second": cost_per_second,
"cpu_utilization": execution.actual_cost_credits / execution.max_cost_credits,
"resource_efficiency": "high" if cost_per_second < 0.1 else "low"
}
return efficiency
# Analyze completed execution
execution = client.containers.get_container("cnt_abc123def456")
metrics = analyze_execution_performance(execution)
print(f"Container efficiency: {metrics}")
REST API Reference
Create Container
POST /api/v1/compute/containers
Content-Type: application/json
Authorization: Bearer your_api_key
{
"image": "python:3.11-slim",
"command": ["python", "-c", "print('Hello World')"],
"cpuCores": 1.0,
"memoryMb": 512,
"storageGb": 5,
"gpuCount": 0,
"maxCostCredits": 100,
"timeoutSeconds": 300,
"environment": {
"LOG_LEVEL": "INFO"
}
}
Get Container Status
GET /api/v1/compute/containers/{container_id}
Authorization: Bearer your_api_key
List Containers
GET /api/v1/compute/containers?limit=20&status=RUNNING&containerType=COMPUTE
Authorization: Bearer your_api_key
Get Container Logs
GET /api/v1/compute/containers/{container_id}/logs
Authorization: Bearer your_api_key
Cancel Container
DELETE /api/v1/compute/containers/{container_id}
Authorization: Bearer your_api_key
List Container Executions
GET /api/v1/compute/containers/{container_id}/executions
Authorization: Bearer your_api_key
List All Container Executions
GET /api/v1/compute/containers/executions?limit=50&status=running
Authorization: Bearer your_api_key
Get Container Execution Details
GET /api/v1/compute/containers/executions/{execution_id}
Authorization: Bearer your_api_key
List All Executions (Global)
GET /api/v1/compute/containers/executions?limit=50&language=python
Authorization: Bearer your_api_key