The perfect marriage of intelligent agents and secure code execution
π Full Source Code: github.com/Cognitora/Integration-Example-OpenAI-Agents-SDK
TL;DR
We built a production-ready integration combining OpenAI's Agents SDK with Cognitora's secure sandbox to create truly autonomous AI agents that can write and execute code safely. This isn't just another LLM wrapperβit's a complete framework for building AI systems that actually do things in the real world.
Jump to: Why This Matters β’ The Architecture β’ Live Examples β’ Try It Yourself
The Problem: Bridging Intelligence and Action
Large Language Models are brilliant at reasoning and planning. They can analyze complex problems, break them into steps, and generate sophisticated code. But here's the catch: they can't execute that code themselves.
This is where most AI applications hit a wall. You have two bad options:
- Run AI-generated code locally (dangerous, unsandboxed, security nightmare)
- Don't execute code at all (safe but severely limited)
We needed a third option: secure, isolated, production-ready code execution that AI agents can use autonomously.
The Solution: OpenAI Agents SDK + Cognitora
OpenAI Agents SDK: Intelligence Layer
The OpenAI Agents SDK is OpenAI's official framework for building agentic AI applications. It's the production-ready evolution of Swarm, designed with simplicity and power in mind.
Why we chose it:
- β Minimal abstractions - Agent, Handoffs, Guardrails, Sessions. That's it.
- β Python-first design - Use native Python patterns, not a new DSL
- β Built-in tracing - Visualize, debug, and optimize agent workflows
- β Multi-agent orchestration - Agents that delegate to specialized agents
- β Provider agnostic - Works with OpenAI, and 100+ LLMs via LiteLLM
from agents import Agent, Runner
agent = Agent(
name="DataAnalyst",
instructions="You analyze data and provide insights",
tools=[your_custom_tools]
)
result = await Runner.run(agent, "Analyze Q4 sales trends")
Cognitora: Execution Layer
Cognitora is an enterprise-grade code execution platform built specifically for AI agents. It provides isolated sandboxes with:
- β‘ Sub-second cold starts - No waiting for containers
- π Military-grade isolation - Every execution is completely sandboxed
- π Configurable networking - Enable/disable internet access per execution
- π¦ Multi-language support - Python, JavaScript, Bash, and more
- πΎ File operations - Upload data, generate files, download results
- π Production-ready - Built for scale, not just prototypes
from cognitora import Cognitora
client = Cognitora(api_key=os.environ["COGNITORA_API_KEY"])
result = client.run(
code="import numpy as np\nprint(np.mean([1,2,3,4,5]))",
language="python",
enable_networking=True # Optional: for API calls
)
The Architecture
Here's how these pieces work together:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β User: "Analyze AAPL stock and predict next week" β
ββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β OpenAI Agents SDK (Intelligence) β
β β’ Understands intent β
β β’ Plans approach β
β β’ Generates Python code β
β β’ Decides when to use tools β
ββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β execute_code Tool (Integration Layer) β
β β’ Validates code β
β β’ Wraps Cognitora API β
β β’ Handles errors gracefully β
ββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Cognitora (Execution Layer) β
β β’ Spins up isolated sandbox β
β β’ Executes code securely β
β β’ Captures output/errors β
β β’ Returns results β
ββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Output: "AAPL trading at $252.29 β
β Predicted: +4.99% growth β
β Recommendation: BUY π’" β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The Integration: execute_code Tool
The magic happens in our custom tool that bridges both platforms:
async def execute_code(
code: str,
language: Literal["python", "javascript", "bash"],
enable_networking: bool = False
) -> str:
"""
Execute code in a secure Cognitora sandbox.
The AI agent can call this tool to run any code it generates.
"""
client = Cognitora(api_key=os.environ["COGNITORA_API_KEY"])
result = client.run(
code=code,
language=language,
enable_networking=enable_networking
)
if result.exit_code == 0:
return f"β
Success:\n{result.output}"
else:
return f"β Error:\n{result.stderr}"
This simple interface gives AI agents the superpower of code execution without any security compromises.
What We Built
We created 6 production-ready examples that showcase what's possible when intelligence meets secure execution:
1οΈβ£ Agentic Task Automation (1-example-basic-tasks.py)
8 autonomous tasks demonstrating goal-oriented problem solving:
- πΌ Sales analysis with ML predictions
- π’ Prime number generation
- π° Financial calculations
- π Statistical analysis
- π Password generation
The agentic approach:
β Traditional: "Use pandas to load CSV, calculate mean, plot graph"
β
Agentic: "Analyze my sales data and predict January revenue"
The agent figures out how to solve it. You just provide the what.

2οΈβ£ Interactive AI Chat (2-example-interactive.py)
Natural language interface with real-time code execution:
- π¬ Ask questions in plain English
- π¨ Beautiful terminal UI
- β‘ Instant code generation and execution
- π Session statistics
You: "Calculate compound interest on $5000 at 6% for 10 years"
AI: *writes Python code* β *executes* β "$8,954.24"
3οΈβ£ Stock Market Analyst π (3-example-stock-analyst.py)
This is where it gets serious. A fully autonomous financial analyst that:
- π Fetches real stock data (Yahoo Finance API)
- π€ Applies machine learning (linear regression)
- π Generates 10-day price predictions
- π‘ Provides investment recommendations
- π Creates professional markdown reports
Output: stock_analysis_20251018_120315.md with complete analysis, predictions, and actionable insights.

4οΈβ£ Live Crypto Tracker π (4-example-live-crypto-tracker.py)
AI agents with internet accessβsafely:
- π Networking enabled in sandbox
- π° Fetches live crypto prices (CoinGecko API)
- π Analyzes portfolio value
- π‘ Provides investment advice
Security note: Networking is optional and configurable. Only enable it when needed.

5οΈβ£ Multi-Agent Research System π€ (5-example-multi-agent-research.py)
The future of AI: Multiple specialized agents collaborating:
Master Orchestrator
β
ββββββββ΄βββββββ
β β
Data Analyst Statistician
(Python code) (Advanced stats)
β β
Report Writer
Each agent has specialized knowledge and tools. The orchestrator decides which specialist to delegate to. All agents can execute code via Cognitora.
Use cases:
- E-commerce analysis with growth projections
- A/B test statistical significance
- Customer segmentation and LTV calculation

6οΈβ£ Data Visualization Pipeline π (6-example-data-visualization.py)
Complete file upload β analysis β chart generation β download workflow:
- π Upload CSV data to sandbox
- π€ AI analyzes and identifies insights
- π Generates 4 professional charts (matplotlib)
- β¬οΈ Downloads all files to local filesystem
Output: 4 beautiful visualizations saved to output_charts/

Why This Integration is Powerful
1. True Autonomy
Traditional AI: "Here's some code to solve your problem"
Our integration: "Here's the solution. I ran the code and verified it works."
The agent doesn't just generate codeβit executes it, checks results, and iterates until it works.
2. Production-Ready Security
Running AI-generated code is scary. Cognitora makes it safe:
- β Complete isolation from your infrastructure
- β No access to your filesystem (unless explicitly provided)
- β Configurable networking (disabled by default)
- β Resource limits prevent runaway processes
- β Every execution is a fresh, clean environment
3. Multi-Agent Workflows
OpenAI Agents SDK's handoff system + Cognitora's execution = powerful orchestration:
# Data Analyst agent can delegate to Statistician
statistician = Agent(
name="Statistician",
instructions="You perform advanced statistical analysis",
tools=[execute_code]
)
analyst = Agent(
name="DataAnalyst",
instructions="You analyze data and delegate complex stats",
tools=[execute_code],
handoff_to=[statistician]
)
Each specialist agent can execute code independently. The orchestrator coordinates them.
4. Real-World Data Integration
Enable networking in Cognitora, and suddenly your agents can:
- π Fetch live data from APIs
- π° Get real-time market prices
- πΊοΈ Access geographic data
- π¬ Pull research papers
- π Query public datasets
All while remaining sandboxed and secure.
5. Iterative Refinement
The agent loop handles failures gracefully:
- Generate code
- Execute in Cognitora
- Check output
- If error β analyze error β generate fix β retry
- If success β continue with result
This isn't scripted error handlingβthe LLM reasons about errors and fixes them autonomously.
Real-World Use Cases
This integration pattern unlocks entirely new categories of AI applications:
π€ Autonomous Data Analysis
Upload a CSV, ask questions, get insights with charts. The agent handles data cleaning, statistical tests, and visualizationβcompletely autonomously.
πΌ Financial Advisors
Real-time market analysis, predictive modeling, portfolio optimization. All with live data and transparent calculations.
π¬ Research Assistants
Multi-agent systems that can search, analyze, compute statistics, and write comprehensive reportsβall backed by real code execution.
π Business Intelligence
Natural language queries that generate SQL, fetch data, perform analysis, and create executive-ready reports.
π Educational Platforms
Interactive coding tutors that can run student code, analyze errors, and provide guided debuggingβsafely sandboxed.
π€ Customer Support
Agents that can actually do things: run diagnostics, generate reports, process refunds, update databasesβnot just chat.
The Code: Clean and Simple
Here's the complete integration (simplified):
import os
from agents import Agent, Runner
from cognitora import Cognitora
# Initialize Cognitora client
cognitora_client = Cognitora(api_key=os.environ["COGNITORA_API_KEY"])
async def execute_code(
code: str,
language: str = "python",
enable_networking: bool = False
) -> str:
"""Execute code securely in Cognitora sandbox."""
result = cognitora_client.run(
code=code,
language=language,
enable_networking=enable_networking
)
return result.output if result.exit_code == 0 else result.stderr
# Create an agent with code execution superpower
agent = Agent(
name="CodeExecutor",
model="gpt-4o",
instructions="You can write and execute code to solve problems.",
tools=[execute_code]
)
# Give it a complex task
result = await Runner.run(
agent,
"Fetch live Bitcoin price and predict next week's trend using linear regression"
)
print(result.final_output)
That's it. ~30 lines of code for a fully autonomous AI agent that can write and execute code safely.
Performance & Scale
Speed
- Cognitora cold start: <500ms
- Code execution: Depends on code (typically <2s)
- Full agent loop: 5-15s for complex tasks
Cost
- OpenAI API: $0.002-0.015 per request (GPT-4o)
- Cognitora: Pay-per-execution, starting at $0.001 per run
- Total: ~$0.01-0.05 per autonomous task
Scale
- Concurrent executions: Unlimited (Cognitora handles load)
- Agent instances: Stateless, scale horizontally
- Session management: Built into Agents SDK
Get Started
Prerequisites
- Python >=3.10.0, <3.13.0
- OpenAI API key (get one here)
- Cognitora API key (sign up here)
Quick Setup (2 minutes)
# Clone the repo
git clone https://github.com/Cognitora/Integration-Example-OpenAI-Agents-SDK.git
cd Integration-Example-OpenAI-Agents-SDK
# Install dependencies
pip install -r requirements.txt
# Set your API keys
export OPENAI_API_KEY="sk-your-key-here"
export COGNITORA_API_KEY="cgk-your-key-here"
# Run examples
python 1-example-basic-tasks.py
python 3-example-stock-analyst.py
python 5-example-multi-agent-research.py
Try Each Example
| Example | Description | Complexity |
|---|---|---|
| Example 1 | Basic agentic tasks | β Beginner |
| Example 2 | Interactive chat | β Beginner |
| Example 3 | Stock analyst (ML) | βββ Advanced |
| Example 4 | Live crypto data | ββ Intermediate |
| Example 5 | Multi-agent system | βββ Advanced |
| Example 6 | Data visualization | ββ Intermediate |
Why Choose Cognitora?
Built for AI Agents, Not Just Code Execution
Cognitora was designed from the ground up for agentic AI workflows:
β
AI-Native API
Simple, intuitive interface that LLMs can use autonomously
β
Error Messages That LLMs Understand
Clear, actionable error messages that agents can reason about and fix
β
Predictable Behavior
Consistent environments mean agents learn and improve over time
β
Production-Ready from Day One
No "scale this later" surprisesβit just works at any volume
β
File Operations
Upload data, generate reports, download resultsβfull filesystem support
β
Multi-Language Support
Python, JavaScript, Bashβlet agents choose the right tool
Enterprise-Grade Security
- π Isolated Sandboxes - Complete isolation per execution
- π‘οΈ No Persistent State - Fresh environment every time
- π¦ Network Controls - Granular control over internet access
- π Audit Logs - Full visibility into what code ran and when
- πΌ SOC2 Compliant - Enterprise security standards
Developer Experience
from cognitora import Cognitora
client = Cognitora(api_key="cgk-...")
# That's it. You're ready to execute code.
result = client.run(code="print('Hello, World!')", language="python")
No Docker. No K8s. No infrastructure headaches. Just code execution that works.
Join the Agentic Revolution
We're at an inflection point in AI development. The combination of:
- π§ Intelligent reasoning (LLMs like GPT-4o)
- π€ Agentic frameworks (OpenAI Agents SDK)
- β‘ Secure execution (Cognitora)
...unlocks a new category of applications that can truly understand and act autonomously.
Start Building Today
π Try Cognitora Free: cognitora.dev/home/api-keys
π Explore the Integration: github.com/Cognitora/Integration-Example-OpenAI-Agents-SDK
π OpenAI Agents SDK Docs: openai.github.io/openai-agents-python
π¬ Questions? Ideas? Open an issue on GitHub or reach out to our team
What Will You Build?
The examples in this repo are just the beginning. We've seen developers build:
- π Autonomous business analysts that generate weekly reports
- π€ Trading bots that analyze markets and execute strategies
- π¬ Research assistants that process datasets and write papers
- π Educational platforms with AI tutors that debug student code
- πΌ Internal tools that turn natural language into database queries
The only limit is your imagination.
Start with our examples, modify them, extend them, and build something amazing.
Technical Resources
- GitHub Repository: Integration-Example-OpenAI-Agents-SDK
- OpenAI Agents SDK: Documentation
- Cognitora Platform: Website
- Cognitora Dashboard: API Keys
About This Integration
This integration was built to demonstrate production-ready patterns for combining intelligent AI agents with secure code execution. All code is open source and production-ready. Use it as:
- π Learning resource for agentic AI development
- ποΈ Starting point for your own applications
- π Reference implementation for best practices
Built with β€οΈ by the Cognitora team
Making AI agents safe, powerful, and production-readyβone execution at a time.
Call to Action
Ready to add autonomous code execution to your AI agents?
π― Get Started in 60 Seconds:
- Sign up at cognitora.dev
- Get your API key (starts with cgk_)
- Run the examples: python 1-example-basic-tasks.py
π‘ Have Questions? We're here to help. Open an issue or contact us through our website.
π Share What You Build! We'd love to see what you create with this integration. Tag us or open a PR with your examples.
Last updated: October 2025