Python SDK Reference
Complete API reference for the AIM Python SDK. The SDK provides a high-level, Pythonic interface for agent registration, capability management, MCP integration, and secure operations.
v1.0.0StablePython 3.8+
⚠️ SDK Download (NO pip install)
Important: There is NO pip package for the AIM SDK. You must download it from your AIM dashboard with pre-configured credentials.
# There is NO pip package for AIM SDK!
# Download SDK from AIM Dashboard (Settings → SDK Download)
# The SDK comes with your pre-configured credentials
# After download, install dependencies:
pip install keyring PyNaCl requests cryptography
# For async support
pip install aiohttp
# For CLI tools
pip install click richTo get the SDK:
- 1. Login to AIM Dashboard
- 2. Go to Settings → SDK Download
- 3. Click "Download Python SDK"
- 4. Extract and use in your project
Quick Start
from aim_sdk import secure
# Zero-configuration mode (uses embedded credentials)
agent = secure("my-agent")
# The SDK automatically:
# - Registers the agent with AIM
# - Manages authentication tokens
# - Handles token refresh
# - Reports capabilities
# - Tracks operations
# Use the agent
result = agent.execute("process_data", {"input": "data"})Core Classes & Functions
Module Imports
# Core Classes and Functions
from aim_sdk import (
secure, # Enterprise-grade security function
AIMAgent, # Main agent class
AIMConfig, # Configuration class
AIMClient, # Low-level API client
Capability, # Capability decorator
MCPServer, # MCP server registration
TrustScore, # Trust score utilities
AIMException, # Base exception class
)
# Type hints
from aim_sdk.types import (
AgentMetadata,
CapabilityDefinition,
MCPServerConfig,
TrustMetrics,
TokenPair,
ExecutionContext,
)AIMAgent Class Methods
# AIMAgent Class Methods
class AIMAgent:
"""Main agent class for interacting with AIM"""
# Registration & Lifecycle
def register(self) -> Dict[str, Any]:
"""Register agent with AIM server"""
def unregister(self) -> bool:
"""Unregister agent from AIM"""
def refresh_registration(self) -> Dict[str, Any]:
"""Refresh agent registration"""
# Capability Management
def add_capability(
self,
name: str,
handler: Callable,
description: str = None,
parameters: Dict = None
) -> None:
"""Add a capability to the agent"""
def remove_capability(self, name: str) -> bool:
"""Remove a capability"""
def list_capabilities(self) -> List[CapabilityDefinition]:
"""List all registered capabilities"""
# MCP Server Management
def register_mcp_server(
self,
name: str,
url: str,
public_key: str = None
) -> MCPServerConfig:
"""Register an MCP server"""
def list_mcp_servers(self) -> List[MCPServerConfig]:
"""List registered MCP servers"""
# Execution & Operations
def execute(
self,
capability: str,
parameters: Dict = None,
timeout: float = 30.0
) -> Any:
"""Execute a capability"""
async def execute_async(
self,
capability: str,
parameters: Dict = None
) -> Any:
"""Execute capability asynchronously"""
# Trust & Security
def get_trust_score(self) -> TrustScore:
"""Get current trust score"""
def report_verification_event(
self,
event_type: str,
success: bool,
metadata: Dict = None
) -> bool:
"""Report verification event"""
# Status & Health
def get_status(self) -> Dict[str, Any]:
"""Get agent status"""
def health_check(self) -> bool:
"""Perform health check"""
def get_metrics(self) -> Dict[str, Any]:
"""Get agent metrics"""Decorators & Clean Code
Decorator-Based API
# Decorators for Clean Code
from aim_sdk import secure, capability, mcp_tool
# Register agent with decorator
@secure("data-processor", auto_refresh=True)
class DataProcessor:
def __init__(self):
self.processed_count = 0
@capability(
name="process_batch",
description="Process a batch of data",
parameters={
"batch_size": "int",
"format": "str"
}
)
def process_batch(self, batch_size: int, format: str = "json"):
"""Process data batch"""
self.processed_count += batch_size
return {"processed": batch_size, "format": format}
@capability("analyze_data")
async def analyze_data(self, data: List[Dict]):
"""Async capability for data analysis"""
results = await self._analyze(data)
return results
@mcp_tool(
name="export_results",
server="data-exporter"
)
def export_results(self, destination: str):
"""MCP tool for exporting results"""
return self._export_to(destination)
# Usage
processor = DataProcessor() # Auto-registered with AIM
result = processor.process_batch(100, "parquet")Configuration
Configuration Options
# Configuration Options
from aim_sdk import AIMConfig, secure
# 1. Environment Variables (Recommended)
# Set these in your environment:
# AIM_API_URL=https://api.aim.example.com
# AIM_API_KEY=your-api-key
# AIM_AGENT_NAME=my-agent
# AIM_PRIVATE_KEY_PATH=/path/to/key.pem
# 2. Configuration Object
config = AIMConfig(
api_url="https://api.aim.example.com",
api_key="your-api-key", # Optional if using key auth
agent_name="my-agent",
private_key_path="/path/to/ed25519_key.pem",
# Optional settings
auto_refresh=True, # Auto-refresh tokens
refresh_buffer=300, # Refresh 5 min before expiry
retry_attempts=3, # API retry attempts
timeout=30.0, # Request timeout
# Logging
log_level="INFO",
log_file="/var/log/aim/agent.log",
# Security
verify_ssl=True,
ca_bundle="/path/to/ca-bundle.pem",
)
agent = secure("my-agent", config=config)
# 3. Configuration File (aim.yaml)
"""
api:
url: https://api.aim.example.com
key: ${AIM_API_KEY} # Support env vars
agent:
name: my-agent
private_key: /path/to/key.pem
security:
verify_ssl: true
ca_bundle: /etc/ssl/certs/ca-certificates.crt
logging:
level: INFO
file: /var/log/aim/agent.log
"""
# Load from file
agent = secure("my-agent", config_file="aim.yaml")Async/Await Support
# Async/Await Support
import asyncio
from aim_sdk import secure
# Async agent registration
async def main():
agent = await secure("async-agent", async_mode=True)
# Async capability execution
result = await agent.execute_async(
"process_data",
{"input": "data"}
)
# Async batch operations
tasks = []
for i in range(10):
task = agent.execute_async(
"process_item",
{"item_id": i}
)
tasks.append(task)
results = await asyncio.gather(*tasks)
# Async context manager
async with secure("context-agent") as agent:
await agent.execute_async("operation")
# Auto cleanup on exit
# Run async code
asyncio.run(main())
# Async decorator support
class AsyncProcessor:
@capability(async_mode=True)
async def process(self, data):
result = await self.async_operation(data)
return resultError Handling
Exception Hierarchy
# Error Handling
from aim_sdk import (
secure,
AIMException,
RegistrationError,
AuthenticationError,
CapabilityError,
TokenExpiredError,
NetworkError,
ValidationError,
)
try:
agent = secure("my-agent")
result = agent.execute("operation")
except RegistrationError as e:
# Failed to register agent
print(f"Registration failed: {e.message}")
print(f"Status code: {e.status_code}")
except AuthenticationError as e:
# Auth token issues
if isinstance(e, TokenExpiredError):
# Token expired, SDK should auto-refresh
agent.refresh_tokens()
else:
print(f"Auth error: {e}")
except CapabilityError as e:
# Capability execution failed
print(f"Capability '{e.capability}' failed: {e}")
except NetworkError as e:
# Network connectivity issues
print(f"Network error: {e}")
# SDK automatically retries with exponential backoff
except ValidationError as e:
# Invalid parameters or configuration
print(f"Validation error: {e.field}: {e.message}")
except AIMException as e:
# Base exception for all AIM errors
print(f"AIM error: {e}")
# Custom error handling
@agent.on_error
def handle_error(error: AIMException):
"""Custom error handler"""
logger.error(f"Agent error: {error}")
# Send alert, metrics, etc.MCP Server Integration
# MCP Server Integration
from aim_sdk import secure, MCPServer
agent = secure("mcp-agent")
# Register MCP server
mcp_server = agent.register_mcp_server(
name="data-processor",
url="http://localhost:8080",
public_key="""-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
-----END PUBLIC KEY-----""",
capabilities=[
"process_text",
"analyze_data",
"export_results"
]
)
# List MCP servers
servers = agent.list_mcp_servers()
for server in servers:
print(f"{server.name}: {server.url}")
print(f" Capabilities: {server.capabilities}")
print(f" Verified: {server.is_verified}")
# Call MCP tool
result = agent.call_mcp_tool(
server="data-processor",
tool="process_text",
parameters={"text": "Hello, World!"}
)
# MCP discovery
discovered = agent.discover_mcp_servers()
for server in discovered:
if server.trust_score > 0.8:
agent.register_mcp_server(
name=server.name,
url=server.url,
auto_verify=True
)CLI Tools
Command-Line Interface
# CLI Tools (with aim-sdk[cli])
# Command-line interface
$ aim agent register my-agent
Agent 'my-agent' registered successfully
$ aim agent status my-agent
Agent: my-agent
Status: active
Trust Score: 0.92
Capabilities: 5
MCP Servers: 2
$ aim capability list --agent my-agent
- process_data: Process data batches
- analyze_text: Analyze text content
- export_results: Export to various formats
- generate_report: Generate analysis reports
- validate_input: Validate input data
$ aim trust score my-agent
Trust Score: 0.92
Factors:
- Uptime: 0.98 (30 days)
- Success Rate: 0.95
- Security Events: 0.90
- Capability Coverage: 0.88
$ aim mcp register \
--agent my-agent \
--name "custom-mcp" \
--url "http://localhost:9000" \
--verify
$ aim test capability \
--agent my-agent \
--name process_data \
--params '{"size": 100}'Testing & Development
# Testing & Development
import pytest
from unittest.mock import Mock, patch
from aim_sdk import secure, AIMAgent
from aim_sdk.testing import MockAIMServer, TestAgent
# Unit testing with mocks
def test_agent_registration():
with MockAIMServer() as mock_server:
agent = secure("test-agent", api_url=mock_server.url)
assert agent.is_registered
assert mock_server.received_registration("test-agent")
# Test capability
agent.add_capability("test_cap", lambda x: x * 2)
result = agent.execute("test_cap", {"x": 5})
assert result == 10
# Integration testing
@pytest.fixture
def test_agent():
"""Fixture for test agent"""
return TestAgent("integration-agent")
def test_end_to_end(test_agent):
# TestAgent provides isolated environment
test_agent.register()
test_agent.add_capability("process", process_func)
result = test_agent.execute("process", {"data": "test"})
assert result["status"] == "success"
# Verify metrics
metrics = test_agent.get_metrics()
assert metrics["executions"] == 1
assert metrics["success_rate"] == 1.0
# Load testing
from aim_sdk.testing import LoadTester
async def test_load():
tester = LoadTester(
agent_name="load-test-agent",
concurrent_requests=100,
duration_seconds=60
)
results = await tester.run()
assert results.avg_latency < 0.1 # 100ms
assert results.success_rate > 0.99
assert results.requests_per_second > 1000Advanced Features
# Advanced Features
from aim_sdk import secure, middleware, events
agent = secure("advanced-agent")
# 1. Middleware
@agent.use_middleware
def logging_middleware(request, next):
"""Log all operations"""
start = time.time()
result = next(request)
duration = time.time() - start
logger.info(f"{request.capability}: {duration:.2f}s")
return result
@agent.use_middleware
def rate_limit_middleware(request, next):
"""Rate limiting"""
if rate_limiter.is_exceeded(request.agent_id):
raise RateLimitError("Rate limit exceeded")
return next(request)
# 2. Event Handlers
@agent.on("registered")
def on_registered(event):
print(f"Agent registered: {event.agent_id}")
notify_admin(event)
@agent.on("capability_executed")
def on_capability_executed(event):
metrics.record(
capability=event.capability,
duration=event.duration,
success=event.success
)
@agent.on("trust_score_changed")
def on_trust_changed(event):
if event.new_score < 0.5:
alert_security_team(event)
# 3. Custom Token Storage
class RedisTokenStorage:
def get_tokens(self, agent_id: str) -> TokenPair:
return redis.get(f"tokens:{agent_id}")
def set_tokens(self, agent_id: str, tokens: TokenPair):
redis.setex(
f"tokens:{agent_id}",
tokens.expires_in,
tokens
)
agent = secure(
"custom-storage",
token_storage=RedisTokenStorage()
)
# 4. Circuit Breaker
from aim_sdk.resilience import CircuitBreaker
breaker = CircuitBreaker(
failure_threshold=5,
recovery_timeout=60,
expected_exception=NetworkError
)
@breaker
def protected_operation():
return agent.execute("critical_operation")
# 5. Metrics & Monitoring
from aim_sdk.monitoring import PrometheusExporter
exporter = PrometheusExporter(port=8000)
agent.attach_exporter(exporter)
# Metrics available at http://localhost:8000/metricsSDK Features
Security
- • Ed25519 signatures
- • Automatic token refresh
- • Secure credential storage
- • SSL/TLS verification
- • Rate limiting
Reliability
- • Automatic retries
- • Circuit breaker
- • Connection pooling
- • Graceful degradation
- • Health checks
Performance
- • Async/await support
- • Connection reuse
- • Response caching
- • Batch operations
- • Zero-copy streaming
Version Compatibility
| SDK Version | Python Version | AIM API Version |
|---|---|---|
| 1.0.x | 3.8+ | v1 |
| 0.9.x | 3.7+ | v1-beta |
| 0.8.x | 3.7+ | v1-alpha |