Build a secure AI code execution workflow using the Daytona SDK

In this Daytona SDK tutorial, we provide hands-on walkthroughs to leverage Daytona’s secure sandbox environment to safely execute untrusted or AI-generated Python code in your notebook. Starting with direct sandbox creation and basic code execution, the guide demonstrates how to isolate the process, install dependencies and run simple scripts without damaging the host environment. As the tutorial progresses, it digs into giant pandas’ data processing, including file operations that read and write JSON files, and execution of complex AI-generated summary such as recursive functions and classification algorithms. Finally, it shows parallel task execution across multiple sandboxes and the correct cleaning process to ensure that each resource is managed and processed correctly.
import os
import time
import json
from typing import List, Dict, Any
try:
import daytona_sdk
except ImportError:
print("Installing Daytona SDK...")
!pip install daytona-sdk
import daytona_sdk
from daytona_sdk import Daytona, DaytonaConfig, CreateSandboxParams
We install and import the Daytona SDK (if not already exists), and then initialize the Core Daytona classes (Daytona, DaytonAconFig, and CreateSandBoxParams) to configure and create secure Python Sandboxes. It also brings standard utilities such as OS, Tim, and JSON to use in these sandboxes.
class DaytonaTutorial:
"""Complete tutorial for Daytona SDK - Secure AI Code Execution Platform"""
def __init__(self, api_key: str):
"""Initialize Daytona client"""
self.config = DaytonaConfig(api_key=api_key)
self.daytona = Daytona(self.config)
self.sandboxes: List[Any] = []
def basic_sandbox_demo(self):
"""Demo 1: Basic sandbox creation and code execution"""
print("π Demo 1: Basic Sandbox Operations")
print("-" * 40)
try:
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
self.sandboxes.append(sandbox)
print(f"β
Created sandbox: {sandbox.id}")
code="print("Hello from Daytona Sandbox!")nprint(f"2 + 2 = {2 + 2}")"
response = sandbox.process.code_run(code)
if response.exit_code == 0:
print(f"π Output: {response.result}")
else:
print(f"β Error: {response.result}")
except Exception as e:
print(f"β Error in basic demo: {e}")
def data_processing_demo(self):
"""Demo 2: Data processing in isolated environment"""
print("nπ Demo 2: Secure Data Processing")
print("-" * 40)
try:
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
self.sandboxes.append(sandbox)
install_cmd = "import subprocess; subprocess.run(['pip', 'install', 'pandas'])"
response = sandbox.process.code_run(install_cmd)
data_code = """
import pandas as pd
import json
# Create sample dataset
data = {
'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'age': [25, 30, 35, 28],
'salary': [50000, 60000, 70000, 55000]
}
df = pd.DataFrame(data)
result = {
'total_records': len(df),
'avg_age': df['age'].mean(),
'avg_salary': df['salary'].mean(),
'summary': df.describe().to_dict()
}
print(json.dumps(result, indent=2))
"""
response = sandbox.process.code_run(data_code)
if response.exit_code == 0:
print("β
Data processing completed:")
print(response.result)
else:
print(f"β Error: {response.result}")
except Exception as e:
print(f"β Error in data processing demo: {e}")
def file_operations_demo(self):
"""Demo 3: File operations within sandbox"""
print("nπ Demo 3: File Operations")
print("-" * 40)
try:
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
self.sandboxes.append(sandbox)
file_code = """
import os
import json
# Create a sample file
data = {'message': 'Hello from Daytona!', 'timestamp': '2025-06-13'}
with open('sample.json', 'w') as f:
json.dump(data, f, indent=2)
# Read and display file contents
with open('sample.json', 'r') as f:
content = f.read()
print("File contents:")
print(content)
# List files in current directory
files = os.listdir('.')
print(f"\nFiles in directory: {files}")
"""
response = sandbox.process.code_run(file_code)
if response.exit_code == 0:
print("β
File operations completed:")
print(response.result)
else:
print(f"β Error: {response.result}")
except Exception as e:
print(f"β Error in file operations demo: {e}")
def ai_code_execution_demo(self):
"""Demo 4: Simulated AI-generated code execution"""
print("nπ€ Demo 4: AI-Generated Code Execution")
print("-" * 40)
ai_codes = [
"# Calculate fibonacci sequencendef fib(n):n if n arr[j+1]:n arr[j], arr[j+1] = arr[j+1], arr[j]n return arrnprint(bubble_sort([64, 34, 25, 12, 22, 11, 90]))",
"# Data analysisnimport mathndata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]nmean = sum(data) / len(data)nvariance = sum((x - mean) ** 2 for x in data) / len(data)nstd_dev = math.sqrt(variance)nprint(f'Mean: {mean}, Std Dev: {std_dev:.2f}')"
]
try:
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
self.sandboxes.append(sandbox)
for i, code in enumerate(ai_codes, 1):
print(f"nπ Executing AI Code Snippet {i}:")
response = sandbox.process.code_run(code)
if response.exit_code == 0:
print(f"β
Output: {response.result}")
else:
print(f"β Error: {response.result}")
time.sleep(1)
except Exception as e:
print(f"β Error in AI code execution demo: {e}")
def parallel_execution_demo(self):
"""Demo 5: Multiple sandboxes for parallel processing"""
print("nβ‘ Demo 5: Parallel Execution")
print("-" * 40)
tasks = [
"print('Task 1: Computing prime numbers')nprimes = [i for i in range(2, 50) if all(i % j != 0 for j in range(2, int(i**0.5) + 1))]nprint(f'Primes: {primes[:10]}')",
"print('Task 2: String processing')ntext="Hello Daytona World"nprint(f'Reversed: {text[::-1]}')nprint(f'Word count: {len(text.split())}')",
"print('Task 3: Mathematical calculations')nimport mathnresult = sum(math.sqrt(i) for i in range(1, 101))nprint(f'Sum of square roots 1-100: {result:.2f}')"
]
try:
parallel_sandboxes = []
for i in range(len(tasks)):
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
parallel_sandboxes.append(sandbox)
self.sandboxes.append(sandbox)
results = []
for i, (sandbox, task) in enumerate(zip(parallel_sandboxes, tasks)):
print(f"nπ Starting parallel task {i+1}")
response = sandbox.process.code_run(task)
results.append((i+1, response))
for task_num, response in results:
if response.exit_code == 0:
print(f"β
Task {task_num} completed: {response.result}")
else:
print(f"β Task {task_num} failed: {response.result}")
except Exception as e:
print(f"β Error in parallel execution demo: {e}")
def cleanup_sandboxes(self):
"""Clean up all created sandboxes"""
print("nπ§Ή Cleaning up sandboxes...")
print("-" * 40)
for sandbox in self.sandboxes:
try:
self.daytona.remove(sandbox)
print(f"β
Removed sandbox: {sandbox.id}")
except Exception as e:
print(f"β Error removing sandbox {sandbox.id}: {e}")
self.sandboxes.clear()
print("π Cleanup completed!")
def run_full_tutorial(self):
"""Run the complete Daytona tutorial"""
print("π― Daytona SDK Complete Tutorial")
print("=" * 50)
print("Secure & Isolated AI Code Execution Platform")
print("=" * 50)
self.basic_sandbox_demo()
self.data_processing_demo()
self.file_operations_demo()
self.ai_code_execution_demo()
self.parallel_execution_demo()
self.cleanup_sandboxes()
print("nπ Tutorial completed successfully!")
print("Key Daytona features demonstrated:")
print("β’ Secure sandbox creation")
print("β’ Isolated code execution")
print("β’ File system operations")
print("β’ Parallel processing")
print("β’ Resource cleanup")
This Daytonatutorial class encapsulates a complete end-to-end guide using the Daytona SDK: it initializes a secure sandbox client with your API keys, demonstrates orphaned code execution (simple prints from Pandas data processing and file I/O to AI-generated snippets, and uses spanned snippets to span parts and identify spanned parts. Each approach is independent, demonstrating key Daytona features, sandbox creation, dependency installation, secure execution, and resource cleaning in a clear, step-by-step workflow, ideal for running in a notebook.
def main():
"""Main function to run the tutorial"""
print("π Daytona Setup Instructions:")
print("1. Visit:
print("2. Create an account")
print("3. Generate API key at:
print("4. Replace 'YOUR_API_KEY' below with your actual key")
print("-" * 50)
API_KEY = "Use Your API Key Here"
if API_KEY == "YOUR_API_KEY":
print("β οΈ Please set your Daytona API key before running the tutorial!")
print(" Update the API_KEY variable with your key from
return
try:
tutorial = DaytonaTutorial(API_KEY)
tutorial.run_full_tutorial()
except Exception as e:
print(f"β Tutorial failed: {e}")
print("π‘ Make sure your API key is valid and you have network access")
The Main() function outlines the initial setup steps, guides the user to create a Daytona account and generates their API key, and then verifies that the key is provided and runs the full walkthrough before instantiating the Daytonatutorial class. If the API key is lost or invalid, it will print clear instructions and interrupts to ensure a smooth first experience.
if __name__ == "__main__":
main()
Finally, the above standard Python entry point check ensures that main() is called only when the script is run directly and starts the Daytona tutorial workflow in a clear and controlled way.
In short, by following this tutorial, developers gain a comprehensive understanding of Daytonaβs core capabilities: creating orphaned Python sandboxes, performing secure data operations, managing file I/O, running arbitrary or AI-generated code, and coordinating parallel workloads while being strictly separated from the host system. Cleanup routines emphasize the importance of resource hygiene in long-running workflows. With these basic skills, users can confidently integrate Daytona into a larger machine learning pipeline, an automated testing framework, or any situation that requires the secure execution of dynamic code.
Check notebook. All credits for this study are to the researchers on the project. Also, please feel free to follow us twitter And don’t forget to join us 99K+ ml reddit And subscribe Our newsletter.
Asif Razzaq is CEO of Marktechpost Media Inc. As a visionary entrepreneur and engineer, ASIF is committed to harnessing the potential of artificial intelligence to achieve social benefits. His recent effort is to launch Marktechpost, an artificial intelligence media platform that has an in-depth coverage of machine learning and deep learning news that can sound both technically, both through technical voices and be understood by a wide audience. The platform has over 2 million views per month, demonstrating its popularity among its audience.
