• Home
  • Pricing
  • Integrations
  • Blog
  • Documentation
Sign InSign Up

The next-generation cloud platform designed exclusively for AI agents

© Copyright 2026 Cognitora. All Rights Reserved.

Product
  • Documentation
  • Blog
  • Integrations
  • Roadmap
  • FAQ
Company
  • Drop me an email
Jan 21, 2025

Quick Start: Execute Python Code Securely with Cognitora in 5 Minutes

Learn how to use Cognitora's Python SDK to execute code securely in isolated sandboxes. From installation to your first execution in under 5 minutes.

Getting started with Cognitora is incredibly simple. In this guide, you'll go from zero to executing Python code in secure sandboxes in less than 5 minutes.

What You'll Build

By the end of this tutorial, you'll have a working Python script that:

  • Connects to Cognitora's secure execution environment
  • Runs Python code with internet access
  • Retrieves and processes execution results

No complex setup. No Docker. No infrastructure headaches.


Prerequisites

Before you start, make sure you have:

  • Python 3.7+ installed on your machine
  • A Cognitora API key (get one free here)

That's it. No additional tools required.


Step 1: Install the SDK (30 seconds)

Open your terminal and install the Cognitora Python SDK:

bash
Copy
pip install cognitora python-dotenv

What we installed:

  • cognitora - The official Python SDK
  • python-dotenv - For secure API key management

Step 2: Set Up Your API Key (1 minute)

Create a .env file in your project directory:

bash
Copy
# .env
COGNITORA_API_KEY=cgk_your_api_key_here

Security tip: Never commit your .env file to version control. Add it to .gitignore:

bash
Copy
echo ".env" >> .gitignore

Step 3: Write Your First Script (2 minutes)

Create a file called hello_cognitora.py:

python
Copy
import os
from dotenv import load_dotenv
from cognitora import Cognitora

# Load API key from .env file
load_dotenv()

# Initialize the Cognitora client
client = Cognitora()

# Execute Python code in a secure sandbox
result = client.code_interpreter.execute(
    code="""
import requests
import json

# Fetch a random joke from an API
response = requests.get('https://official-joke-api.appspot.com/random_joke')
joke = response.json()

print(f"Here's a joke for you:")
print(f"{joke['setup']}")
print(f"...{joke['punchline']}")
    """,
    language="python",
    networking=True  # Enable internet access
)

# Process the results
print(f"Execution Status: {result.data.status}")
print("\nOutput:")
for output in result.data.outputs:
    if output.type == "stdout":
        print(output.data)

Step 4: Run It! (10 seconds)

Execute your script:

bash
Copy
python hello_cognitora.py

Expected output:

text
Copy
Execution Status: success

Output:
Here's a joke for you:
Why don't scientists trust atoms?
...Because they make up everything!

🎉 Congratulations! You just executed Python code in a secure, isolated sandbox with internet access.


What Just Happened?

Let's break down what Cognitora did behind the scenes:

  1. Created an isolated sandbox - Your code ran in a completely isolated environment
  2. Enabled networking - The sandbox had controlled internet access to fetch the joke
  3. Executed the code - Your Python script ran with full access to standard libraries
  4. Captured output - All stdout was captured and returned to you
  5. Cleaned up - The sandbox was destroyed after execution

All in under 2 seconds.


Real-World Examples

Now that you've got the basics, here are practical use cases:

Example 1: Data Processing

python
Copy
from cognitora import Cognitora

client = Cognitora()

result = client.code_interpreter.execute(
    code="""
import pandas as pd
import numpy as np

# Generate sample data
data = {
    'sales': [100, 150, 200, 175, 225],
    'expenses': [60, 80, 110, 95, 120]
}

df = pd.DataFrame(data)
df['profit'] = df['sales'] - df['expenses']
df['margin'] = (df['profit'] / df['sales'] * 100).round(2)

print("Sales Analysis:")
print(df.to_string())
print(f"\\nTotal Profit: ${df['profit'].sum()}")
print(f"Average Margin: {df['margin'].mean():.2f}%")
    """,
    language="python",
    networking=False  # No internet needed for this
)

print(result.data.outputs[0].data)

Output:

text
Copy
Sales Analysis:
   sales  expenses  profit  margin
0    100        60      40   40.00
1    150        80      70   46.67
2    200       110      90   45.00
3    175        95      80   45.71
4    225       120     105   46.67

Total Profit: $385
Average Margin: 44.81%

Example 2: Web Scraping (with respect to robots.txt)

python
Copy
result = client.code_interpreter.execute(
    code="""
import requests
from bs4 import BeautifulSoup

# Fetch Python.org homepage
response = requests.get('https://www.python.org/')
soup = BeautifulSoup(response.text, 'html.parser')

# Extract latest news
news_items = soup.select('.blog-widget .list-recent-posts li')[:3]

print("Latest Python News:")
for i, item in enumerate(news_items, 1):
    title = item.find('a').text.strip()
    print(f"{i}. {title}")
    """,
    language="python",
    networking=True
)

print(result.data.outputs[0].data)

Example 3: Machine Learning Prediction

python
Copy
result = client.code_interpreter.execute(
    code="""
import numpy as np
from sklearn.linear_model import LinearRegression

# Sample data: hours studied vs exam score
X = np.array([[1], [2], [3], [4], [5], [6], [7], [8]])
y = np.array([50, 55, 65, 70, 75, 82, 88, 95])

# Train model
model = LinearRegression()
model.fit(X, y)

# Predict score for 10 hours of study
prediction = model.predict([[10]])

print(f"If you study for 10 hours, predicted score: {prediction[0]:.1f}%")
print(f"Model accuracy (R²): {model.score(X, y):.3f}")
    """,
    language="python",
    networking=False
)

print(result.data.outputs[0].data)

Advanced Configuration

Method 1: Direct API Key

python
Copy
from cognitora import Cognitora

client = Cognitora(api_key="cgk_1234567890abcdef")

Method 2: Environment Variable (Recommended)

python
Copy
import os
from cognitora import Cognitora

# Client automatically uses COGNITORA_API_KEY from environment
client = Cognitora()

Method 3: Custom Configuration

python
Copy
from cognitora import Cognitora

client = Cognitora(
    api_key="your_api_key",
    base_url="https://api.cognitora.dev",
    timeout=30  # Request timeout in seconds
)

Understanding the Response

Every execution returns a structured response:

python
Copy
result = client.code_interpreter.execute(
    code="print('Hello'); print(1/0)",
    language="python"
)

# Check execution status
print(result.data.status)  # 'success' or 'error'

# Process outputs
for output in result.data.outputs:
    print(f"Type: {output.type}")    # 'stdout' or 'stderr'
    print(f"Data: {output.data}")
    print(f"Timestamp: {output.timestamp}")

Output types:

  • stdout - Standard output (successful prints)
  • stderr - Standard error (error messages)

Security Features

Cognitora provides enterprise-grade security out of the box:

🔒 Isolated Execution

Every code execution runs in a completely isolated sandbox. No access to your infrastructure.

🌐 Controlled Networking

python
Copy
# Networking disabled by default for code interpreter
result = client.code_interpreter.execute(
    code="import requests; requests.get('https://api.example.com')",
    language="python",
    networking=False  # This will fail safely
)

Enable networking only when needed:

python
Copy
result = client.code_interpreter.execute(
    code="import requests; print(requests.get('https://api.example.com').status_code)",
    language="python",
    networking=True  # Now it works
)

🧹 Automatic Cleanup

Sandboxes are destroyed after execution. No persistent state. No data leaks.

⏱️ Resource Limits

Built-in timeouts and resource constraints prevent runaway processes.


Error Handling

Always handle execution errors gracefully:

python
Copy
from cognitora import Cognitora

client = Cognitora()

try:
    result = client.code_interpreter.execute(
        code="""
# This will cause a division by zero error
print(10 / 0)
        """,
        language="python"
    )
    
    if result.data.status == "error":
        print("Execution failed:")
        for output in result.data.outputs:
            if output.type == "stderr":
                print(output.data)
    else:
        print("Success!")
        for output in result.data.outputs:
            if output.type == "stdout":
                print(output.data)
                
except Exception as e:
    print(f"API Error: {e}")

Common Use Cases

1. Dynamic Report Generation

python
Copy
# User uploads CSV, you process it and generate insights
result = client.code_interpreter.execute(
    code=f"""
import pandas as pd
import io

# Load data from string (in practice, upload a file)
data = '''
date,revenue,costs
2024-01,10000,6000
2024-02,12000,7000
2024-03,15000,8500
'''

df = pd.read_csv(io.StringIO(data))
df['profit'] = df['revenue'] - df['costs']

print("Monthly Analysis:")
print(df.to_markdown(index=False))
print(f"\\nTotal Profit: ${df['profit'].sum():,}")
    """,
    language="python"
)

2. API Data Aggregation

python
Copy
# Fetch and combine data from multiple APIs
result = client.code_interpreter.execute(
    code="""
import requests

# Get weather and news (example)
weather = requests.get('https://api.weather.gov/...').json()
news = requests.get('https://newsapi.org/v2/...').json()

print(f"Current temp: {weather['temperature']}")
print(f"Top headline: {news['articles'][0]['title']}")
    """,
    language="python",
    networking=True
)

3. Educational Platforms

python
Copy
# Run student code submissions safely
student_code = """
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))
"""

result = client.code_interpreter.execute(
    code=student_code,
    language="python"
)

# Grade the submission based on output
if result.data.status == "success":
    print("✅ Code executed successfully")
else:
    print("❌ Code has errors")

Best Practices

1. Use Environment Variables

python
Copy
# ✅ Good - secure
load_dotenv()
client = Cognitora()

# ❌ Bad - exposed in code
client = Cognitora(api_key="cgk_hardcoded_key")

2. Enable Networking Selectively

python
Copy
# Only enable when you need external API access
networking = code_needs_internet_access

result = client.code_interpreter.execute(
    code=user_code,
    language="python",
    networking=networking
)

3. Always Check Status

python
Copy
result = client.code_interpreter.execute(code=code, language="python")

if result.data.status != "success":
    # Handle error
    error_output = [o.data for o in result.data.outputs if o.type == "stderr"]
    log_error(error_output)

4. Set Appropriate Timeouts

python
Copy
# For long-running computations
client = Cognitora(timeout=60)  # 60 second timeout

Next Steps

Now that you've mastered the basics, explore more advanced features:

  1. Sessions - Maintain state across multiple executions
  2. File Uploads - Process CSVs, images, and documents
  3. Container API - For custom runtime environments
  4. Async Execution - For background processing

Check out our comprehensive SDK guide for advanced patterns.


Troubleshooting

Issue: "API key not found"

Solution: Ensure your .env file has the correct key:

bash
Copy
COGNITORA_API_KEY=cgk_your_actual_key_here

And you're loading it:

python
Copy
from dotenv import load_dotenv
load_dotenv()  # Don't forget this line!

Issue: "Networking error"

Solution: Check that networking is enabled:

python
Copy
result = client.code_interpreter.execute(
    code=code_that_needs_internet,
    language="python",
    networking=True  # ← Make sure this is True
)

Issue: "Timeout"

Solution: Increase timeout for long-running code:

python
Copy
client = Cognitora(timeout=60)  # Increase from default 30s

Complete Example Repository

Want to see all these examples in action? Check out our example repository:

📦 Cognitora Python SDK Examples

Clone it and start experimenting:

bash
Copy
git clone https://github.com/Cognitora/Example-with-Cognitora-Python-SDK.git
cd Example-with-Cognitora-Python-SDK
pip install -r requirements.txt
python example.py

Pricing

Cognitora offers a generous free tier to get started:

  • ✅ $50 in free credits (5,000 execution credits)
  • ✅ Full API access
  • ✅ Up to 1-hour execution sessions
  • ✅ 5 concurrent executions
  • ✅ Community support

No credit card required. Sign up now →


Join the Community

  • 📚 Documentation: cognitora.dev/docs
  • 💬 GitHub: github.com/Cognitora
  • 🐦 Twitter: Updates and tips
  • 📧 Support: hello@cognitora.dev

What's Next?

You've learned how to execute Python code securely with Cognitora. Here's what to explore next:

  1. Build AI Agents - Combine with OpenAI Agents SDK
  2. Container API - Custom runtime environments
  3. Code Interpreter API - Advanced features

Start building something amazing! 🚀


Built with ❤️ by the Cognitora team

Making code execution safe, simple, and scalable.