Cognitora SDK Guide
A complete guide to the Cognitora SDKs for Python and JavaScript/TypeScript with networking control and execution management.
Cognitora provides powerful SDKs for Python and JavaScript/TypeScript to interact with the Cognitora API. This guide covers installation, configuration, and usage for both SDKs with the containers architecture, networking control, and comprehensive execution management.
Python SDK
The Python SDK for Cognitora provides a user-friendly interface to the Cognitora API, with support for both synchronous and asynchronous operations.
Installation
pip install cognitora
Authentication
You can authenticate by passing your API key directly to the client or by using environment variables.
from cognitora import Cognitora
import os
# Method 1: Direct API key
client = Cognitora(
api_key="your_api_key_here",
base_url="https://api.cognitora.dev"
)
# Method 2: Environment variable
# set os.environ['COGNITORA_API_KEY'] = "your_api_key_here"
client = Cognitora(base_url="https://api.cognitora.dev")
Code Interpreter
The Code Interpreter API allows you to execute code in a sandboxed environment.
Basic Execution
result = client.code_interpreter.execute(
code="print('Hello from Cognitora!')",
language="python",
networking=True # Enable internet access (default for code interpreter)
)
print(f"Status: {result.data.status}")
for output in result.data.outputs:
print(f"{output.type}: {output.data}")
Sessions
For stateful executions, you can use sessions.
# Create a session (defaults to 1 day if no timeout specified)
session = client.code_interpreter.create_session(
language="python",
timeout_seconds=1800 # 30 minutes (optional)
)
# Execute code in the session (networking enabled by default)
client.code_interpreter.execute(
code="x = 10",
session_id=session.session_id,
networking=True # Enable networking for package installs
)
result = client.code_interpreter.execute(
code="print(x)",
session_id=session.session_id
)
# The output will be "10"
print(result.data.outputs[0].data)
Working with Files
# Execute code with file uploads
files = [
{
"name": "data.csv",
"content": "name,age\nJohn,30\nJane,25"
}
]
result = client.code_interpreter.execute(
code="""
import pandas as pd
df = pd.read_csv('data.csv')
print(df.head())
""",
language="python",
files=files
)
Containers API
The Containers API allows you to run containerized workloads with custom Docker images and networking control.
Creating a Container
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 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
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/zen')
print(f'GitHub Zen: {response.text}')
"""],
cpu_cores=1.0,
memory_mb=512,
storage_gb=5,
max_cost_credits=100,
networking=True # Enable networking for external API calls
)
Managing Containers
# List all containers
containers = client.containers.list_containers(limit=10)
print(f"Found {len(containers)} containers")
# Get container details
container_details = client.containers.get_container(container.id)
print(f"Container status: {container_details.status}")
print(f"Networking enabled: {container_details.networking}")
# Get container logs
logs = client.containers.get_container_logs(container.id)
print(f"Container logs: {logs}")
# Cancel a running container
client.containers.cancel_container(container.id)
# List all container executions across account
all_executions = client.containers.list_all_container_executions(limit=20)
print(f"Total container executions: {len(all_executions)}")
# Get specific container execution details
execution_details = client.containers.get_container_execution('exec_123456')
print(f"Execution status: {execution_details['status']}")
Advanced Container Operations
# Wait for container completion
completed_container = client.containers.wait_for_completion(
container.id,
timeout_seconds=300
)
# Run and wait for completion in one call
result = client.containers.run_and_wait(
image="docker.io/library/python:3.11",
command=["python", "-c", "import time; time.sleep(5); print('Done!')"],
cpu_cores=1.0,
memory_mb=512,
max_cost_credits=100,
networking=False # Secure by default
)
print(f"Container: {result['execution'].status}")
print(f"Logs: {result['logs']}")
print(f"Networking enabled: {result['execution'].networking}")
Cost Estimation
# Estimate costs before running
cost_estimate = client.containers.estimate_cost(
cpu_cores=2.0,
memory_mb=1024,
storage_gb=10,
timeout_seconds=600
)
print(f"Estimated cost: {cost_estimate['estimated_credits']} credits")
print(f"Hourly rate: {cost_estimate['hourly_rate']} credits/hour")
Async Support
The Python SDK also provides async support:
import asyncio
from cognitora import Cognitora
async def main():
client = Cognitora(api_key="your_api_key")
async with client.async_client() as async_client:
# Async container creation
container = await async_client.containers.create_container(
image="docker.io/library/python:3.11",
command=["python", "-c", "print('Async container!')"],
cpu_cores=1.0,
memory_mb=512,
max_cost_credits=50
)
print(f"Async container created: {container.id}")
asyncio.run(main())
JavaScript/TypeScript SDK
The JavaScript/TypeScript SDK provides a modern, Promise-based interface with full TypeScript support.
Installation
npm install @cognitora/sdk
# or
yarn add @cognitora/sdk
Authentication
import { Cognitora } from '@cognitora/sdk';
// Method 1: Direct API key
const client = new Cognitora({
apiKey: 'your_api_key_here',
baseURL: 'https://api.cognitora.dev'
});
// Method 2: Environment variable (COGNITORA_API_KEY)
const client = new Cognitora({
baseURL: 'https://api.cognitora.dev'
});
Code Interpreter
Basic Execution
const result = await client.codeInterpreter.execute({
code: "console.log('Hello from Cognitora!')",
language: 'javascript',
networking: true // Enable internet access (default for code interpreter)
});
console.log(`Status: ${result.data.status}`);
result.data.outputs.forEach(output => {
console.log(`${output.type}: ${output.data}`);
});
Session Management
// Create a session
const session = await client.codeInterpreter.createSession({
language: 'javascript',
timeoutMinutes: 30
});
// Execute code in session (networking enabled by default)
await client.codeInterpreter.execute({
code: 'let x = 42;',
sessionId: session.data.sessionId,
networking: true // Enable networking for package installs
});
const result = await client.codeInterpreter.execute({
code: 'console.log(`The value is ${x}`);',
sessionId: session.data.sessionId
});
Containers API
Creating Containers
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 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
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/zen', (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => console.log('GitHub Zen:', data));
});
`],
cpuCores: 1.0,
memoryMb: 512,
storageGb: 5,
maxCostCredits: 100,
networking: true // Enable networking for external API calls
});
Container Management
// List containers
const containers = await client.containers.listContainers({
limit: 10,
status: 'RUNNING'
});
console.log(`Found ${containers.executions.length} containers`);
// Get container details
const containerDetails = await client.containers.getContainer(container.id);
console.log(`Container status: ${containerDetails.status}`);
console.log(`Networking enabled: ${containerDetails.networking}`);
// Get container logs
const logs = await client.containers.getContainerLogs(container.id);
console.log(`Container logs: ${logs.logs}`);
// Cancel container
await client.containers.cancelContainer(container.id);
// List all container executions across account
const allExecutions = await client.containers.listAllContainerExecutions({ limit: 20 });
console.log(`Total container executions: ${allExecutions.executions.length}`);
// Get specific container execution details
const executionDetails = await client.containers.getContainerExecution('exec_123456');
console.log(`Execution status: ${executionDetails.status}`);
Advanced Operations
// Wait for completion with timeout
try {
const completedContainer = await client.containers.waitForCompletion(
container.id,
300000, // 5 minutes timeout
5000 // 5 second polling interval
);
console.log(`Container completed with status: ${completedContainer.status}`);
} catch (error) {
console.error('Container did not complete in time:', error.message);
}
// Run and wait in one operation
const result = await client.containers.runAndWait({
image: 'docker.io/library/python:3.11-alpine',
command: ['python', '-c', 'import time; time.sleep(2); print("Done!")'],
cpuCores: 1.0,
memoryMb: 512,
maxCostCredits: 50,
networking: false // Secure by default
});
console.log(`Container status: ${result.execution.status}`);
console.log(`Logs: ${result.logs}`);
console.log(`Networking enabled: ${result.execution.networking}`);
Cost Management
// Estimate costs
const costEstimate = await client.containers.estimateCost({
cpu_cores: 2.0,
memory_mb: 1024,
timeout_seconds: 600
});
console.log(`Estimated cost: ${costEstimate.estimated_credits} credits`);
console.log(`Hourly rate: ${costEstimate.hourly_rate} credits/hour`);
Error Handling
Both SDKs provide comprehensive error handling:
Python
from cognitora import CognitoraError, AuthenticationError, RateLimitError
try:
result = client.containers.create_container(
image="invalid-image",
command=["echo", "test"],
cpu_cores=1.0,
memory_mb=512,
max_cost_credits=10,
networking=False # Secure by default
)
except AuthenticationError:
print("Invalid API key")
except RateLimitError:
print("Rate limit exceeded, please wait")
except CognitoraError as e:
print(f"API error: {e}")
JavaScript/TypeScript
import { CognitoraError, AuthenticationError, RateLimitError } from '@cognitora/sdk';
try {
const result = await client.containers.createContainer({
image: 'invalid-image',
command: ['echo', 'test'],
cpuCores: 1.0,
memoryMb: 512,
maxCostCredits: 10,
networking: false // Secure by default
});
} catch (error) {
if (error instanceof AuthenticationError) {
console.log('Invalid API key');
} else if (error instanceof RateLimitError) {
console.log('Rate limit exceeded, please wait');
} else if (error instanceof CognitoraError) {
console.log(`API error: ${error.message}`);
}
}
Best Practices
Resource Management
- Set appropriate timeouts to avoid long-running containers
- Use cost limits to prevent unexpected charges
- Clean up containers when no longer needed
- Monitor resource usage for optimization
Session Management
- Reuse sessions for related operations
- Set reasonable timeouts to balance functionality and cost
- Clean up sessions when workflows are complete
Error Handling
- Implement retry logic for transient failures
- Use specific error types for different handling strategies
- Log errors appropriately for debugging
Performance
- Use async operations when possible
- Batch related operations to reduce API calls
- Implement caching for frequently accessed data
- Monitor API rate limits and implement backoff strategies
API Refactor Updates
Key Changes
- Container-focused architecture: compute.* methods renamed to containers.*
- Networking parameter: Added optional networking parameter with security-focused defaults
- New execution endpoints: Enhanced execution management and history tracking
- Endpoint path updates: Code interpreter paths changed from /code-interpreter/ to /interpreter/
- Production-ready: Default base URL updated to https://api.cognitora.dev
Migration Guide
Python SDK Updates
# Old (deprecated)
# execution = client.compute.create_execution(...)
# containers = client.compute.list_executions()
# details = client.compute.get_execution(id)
# New (current)
container = client.containers.create_container(
...,
networking=False # New: security-focused default
)
containers = client.containers.list_containers()
details = client.containers.get_container(id)
# New execution management features
all_executions = client.containers.list_all_container_executions()
execution_details = client.containers.get_container_execution(exec_id)
interpreter_executions = client.code_interpreter.list_all_executions()
JavaScript SDK Updates
// Old (deprecated)
// const execution = await client.compute.createExecution({...});
// const containers = await client.compute.listExecutions();
// const details = await client.compute.getExecution(id);
// New (current)
const container = await client.containers.createContainer({
...,
networking: false // New: security-focused default
});
const containers = await client.containers.listContainers();
const details = await client.containers.getContainer(id);
// New execution management features
const allExecutions = await client.containers.listAllContainerExecutions();
const executionDetails = await client.containers.getContainerExecution(execId);
const interpreterExecutions = await client.codeInterpreter.listAllExecutions();
Networking Defaults
Service | Old Default | New Default | Rationale |
---|---|---|---|
Code Interpreter | N/A | true (enabled) | Needs package installs, data fetching |
Containers | N/A | false (disabled) | Security-first: isolated by default |
Breaking Changes
- Method names: All compute.* methods renamed to containers.*
- Default networking: Containers default to networking: false for security
- Base URL: Default changed from http://localhost:8080 to https://api.cognitora.dev
- Execution management: New methods added for comprehensive execution tracking
Conclusion
Both SDKs provide comprehensive access to Cognitora's platform capabilities with clean, modern interfaces and security-focused defaults. The recent API refactor brings enhanced networking control, execution management, and production-ready configurations.
Key Features:
- Security-first: Containers isolated by default, networking optional
- Comprehensive: Full API coverage with new execution management endpoints
- Production-ready: Default connection to https://api.cognitora.dev
- Developer-friendly: Maintained backward compatibility where possible
Choose the Python SDK for data science workflows and server-side applications, or the JavaScript/TypeScript SDK for web applications and Node.js services.
For more examples and advanced usage patterns, check out the examples repository and the integration examples.