On this Daytona SDK tutorial, we offer a hands-on walkthrough for leveraging Daytona’s safe sandbox setting to execute untrusted or AI-generated Python code safely inside Pocket book. Starting with simple sandbox creation and fundamental code execution, the information demonstrates methods to isolate processes, set up dependencies, and run easy scripts with out jeopardizing the host setting. Because the tutorial progresses, it delves into knowledge processing with pandas, file operations together with studying and writing JSON recordsdata, and the execution of advanced AI-generated snippets resembling recursive capabilities and sorting algorithms. Lastly, it showcases parallel activity execution throughout a number of sandboxes and correct cleanup procedures, guaranteeing that each useful resource is managed and disposed of appropriately.
import os
import time
import json
from typing import Record, Dict, Any
strive:
import daytona_sdk
besides ImportError:
print("Putting in Daytona SDK...")
!pip set up daytona-sdk
import daytona_sdk
from daytona_sdk import Daytona, DaytonaConfig, CreateSandboxParams
We set up and import the Daytona SDK (if not already current), then initialize the core Daytona lessons (Daytona, DaytonaConfig, and CreateSandboxParams) for configuring and creating safe Python sandboxes. It additionally brings in normal utilities like os, time, and json to be used inside these sandboxes.
class DaytonaTutorial:
"""Full tutorial for Daytona SDK - Safe AI Code Execution Platform"""
def __init__(self, api_key: str):
"""Initialize Daytona shopper"""
self.config = DaytonaConfig(api_key=api_key)
self.daytona = Daytona(self.config)
self.sandboxes: Record(Any) = ()
def basic_sandbox_demo(self):
"""Demo 1: Fundamental sandbox creation and code execution"""
print("🚀 Demo 1: Fundamental Sandbox Operations")
print("-" * 40)
strive:
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
self.sandboxes.append(sandbox)
print(f"✅ Created sandbox: {sandbox.id}")
code="print("Hey from Daytona Sandbox!")nprint(f"2 + 2 = {2 + 2}")"
response = sandbox.course of.code_run(code)
if response.exit_code == 0:
print(f"📝 Output: {response.outcome}")
else:
print(f"❌ Error: {response.outcome}")
besides Exception as e:
print(f"❌ Error in fundamental demo: {e}")
def data_processing_demo(self):
"""Demo 2: Information processing in remoted setting"""
print("n📊 Demo 2: Safe Information Processing")
print("-" * 40)
strive:
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
self.sandboxes.append(sandbox)
install_cmd = "import subprocess; subprocess.run(('pip', 'set up', 'pandas'))"
response = sandbox.course of.code_run(install_cmd)
data_code = """
import pandas as pd
import json
# Create pattern dataset
knowledge = {
'title': ('Alice', 'Bob', 'Charlie', 'Diana'),
'age': (25, 30, 35, 28),
'wage': (50000, 60000, 70000, 55000)
}
df = pd.DataFrame(knowledge)
outcome = {
'total_records': len(df),
'avg_age': df('age').imply(),
'avg_salary': df('wage').imply(),
'abstract': df.describe().to_dict()
}
print(json.dumps(outcome, indent=2))
"""
response = sandbox.course of.code_run(data_code)
if response.exit_code == 0:
print("✅ Information processing accomplished:")
print(response.outcome)
else:
print(f"❌ Error: {response.outcome}")
besides Exception as e:
print(f"❌ Error in knowledge processing demo: {e}")
def file_operations_demo(self):
"""Demo 3: File operations inside sandbox"""
print("n📁 Demo 3: File Operations")
print("-" * 40)
strive:
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
self.sandboxes.append(sandbox)
file_code = """
import os
import json
# Create a pattern file
knowledge = {'message': 'Hey from Daytona!', 'timestamp': '2025-06-13'}
with open('pattern.json', 'w') as f:
json.dump(knowledge, f, indent=2)
# Learn and show file contents
with open('pattern.json', 'r') as f:
content material = f.learn()
print("File contents:")
print(content material)
# Record recordsdata in present listing
recordsdata = os.listdir('.')
print(f"nFiles in listing: {recordsdata}")
"""
response = sandbox.course of.code_run(file_code)
if response.exit_code == 0:
print("✅ File operations accomplished:")
print(response.outcome)
else:
print(f"❌ Error: {response.outcome}")
besides 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 <= 1: return nn return fib(n-1) + fib(n-2)nprint((fib(i) for i in vary(10)))",
"# Kind algorithmndef bubble_sort(arr):n n = len(arr)n for i in vary(n):n for j in vary(0, n-i-1):n if arr(j) > 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)))",
"# Information analysisnimport mathndata = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)nmean = sum(knowledge) / len(knowledge)nvariance = sum((x - imply) ** 2 for x in knowledge) / len(knowledge)nstd_dev = math.sqrt(variance)nprint(f'Imply: {imply}, Std Dev: {std_dev:.2f}')"
)
strive:
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.course of.code_run(code)
if response.exit_code == 0:
print(f"✅ Output: {response.outcome}")
else:
print(f"❌ Error: {response.outcome}")
time.sleep(1)
besides Exception as e:
print(f"❌ Error in AI code execution demo: {e}")
def parallel_execution_demo(self):
"""Demo 5: A number of sandboxes for parallel processing"""
print("n⚡ Demo 5: Parallel Execution")
print("-" * 40)
duties = (
"print('Job 1: Computing prime numbers')nprimes = (i for i in vary(2, 50) if all(i % j != 0 for j in vary(2, int(i**0.5) + 1)))nprint(f'Primes: {primes(:10)}')",
"print('Job 2: String processing')ntext="Hey Daytona World"nprint(f'Reversed: {textual content(::-1)}')nprint(f'Phrase rely: {len(textual content.cut up())}')",
"print('Job 3: Mathematical calculations')nimport mathnresult = sum(math.sqrt(i) for i in vary(1, 101))nprint(f'Sum of sq. roots 1-100: {outcome:.2f}')"
)
strive:
parallel_sandboxes = ()
for i in vary(len(duties)):
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
parallel_sandboxes.append(sandbox)
self.sandboxes.append(sandbox)
outcomes = ()
for i, (sandbox, activity) in enumerate(zip(parallel_sandboxes, duties)):
print(f"n🏃 Beginning parallel activity {i+1}")
response = sandbox.course of.code_run(activity)
outcomes.append((i+1, response))
for task_num, response in outcomes:
if response.exit_code == 0:
print(f"✅ Job {task_num} accomplished: {response.outcome}")
else:
print(f"❌ Job {task_num} failed: {response.outcome}")
besides Exception as e:
print(f"❌ Error in parallel execution demo: {e}")
def cleanup_sandboxes(self):
"""Clear up all created sandboxes"""
print("n🧹 Cleansing up sandboxes...")
print("-" * 40)
for sandbox in self.sandboxes:
strive:
self.daytona.take away(sandbox)
print(f"✅ Eliminated sandbox: {sandbox.id}")
besides Exception as e:
print(f"❌ Error eradicating sandbox {sandbox.id}: {e}")
self.sandboxes.clear()
print("🎉 Cleanup accomplished!")
def run_full_tutorial(self):
"""Run the entire Daytona tutorial"""
print("🎯 Daytona SDK Full Tutorial")
print("=" * 50)
print("Safe & Remoted 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 accomplished efficiently!")
print("Key Daytona options demonstrated:")
print("• Safe sandbox creation")
print("• Remoted code execution")
print("• File system operations")
print("• Parallel processing")
print("• Useful resource cleanup")
This DaytonaTutorial class encapsulates an entire end-to-end information for utilizing the Daytona SDK: it initializes a safe sandbox shopper together with your API key, demonstrates remoted code execution (from easy prints by way of pandas knowledge processing and file I/O to AI-generated snippets), orchestrates parallel duties throughout a number of sandboxes, and at last ensures clear teardown of all assets. Every methodology is self-contained, showcasing key Daytona options, sandbox creation, dependency set up, protected execution, and useful resource cleanup, in a transparent, step-by-step workflow that’s perfect for operating in Pocket book.
def foremost():
"""Major perform to run the tutorial"""
print("🔑 Daytona Setup Directions:")
print("1. Go to: https://app.daytona.io")
print("2. Create an account")
print("3. Generate API key at: https://app.daytona.io/dashboard/keys")
print("4. Exchange 'YOUR_API_KEY' beneath together with your precise key")
print("-" * 50)
API_KEY = "Use Your API Key Right here"
if API_KEY == "YOUR_API_KEY":
print("⚠️ Please set your Daytona API key earlier than operating the tutorial!")
print(" Replace the API_KEY variable together with your key from https://app.daytona.io/dashboard/keys")
return
strive:
tutorial = DaytonaTutorial(API_KEY)
tutorial.run_full_tutorial()
besides Exception as e:
print(f"❌ Tutorial failed: {e}")
print("💡 Be certain your API secret's legitimate and you've got community entry")
The primary() perform outlines the preliminary setup steps, guiding customers to create a Daytona account and generate their API key, then validates that the important thing has been supplied earlier than instantiating the DaytonaTutorial class and operating the total walkthrough. If the API secret’s lacking or invalid, it prints clear directions and aborts, guaranteeing a clean first-time expertise.
if __name__ == "__main__":
foremost()
Lastly, the above normal Python entry-point verify ensures that foremost() is simply invoked when the script is run immediately, initiating the Daytona tutorial workflow in a transparent and managed method.
In conclusion, by following this tutorial, builders acquire a complete understanding of Daytona’s core capabilities: creating remoted Python sandboxes, performing safe knowledge manipulations, managing file I/O, operating arbitrary or AI-generated code, and orchestrating parallel workloads, all whereas sustaining strict separation from the host system. The cleanup routines underscore the significance of useful resource hygiene in long-running workflows. Armed with these foundational abilities, customers can confidently combine Daytona into bigger machine-learning pipelines, automated testing frameworks, or any state of affairs that requires the protected execution of dynamic code.
Take a look at the Pocket book. All credit score for this analysis goes to the researchers of this challenge. Additionally, be happy to observe us on Twitter and don’t overlook to hitch our 99k+ ML SubReddit and Subscribe to our Publication.

Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is dedicated to harnessing the potential of Synthetic Intelligence for social good. His most up-to-date endeavor is the launch of an Synthetic Intelligence Media Platform, Marktechpost, which stands out for its in-depth protection of machine studying and deep studying information that’s each technically sound and simply comprehensible by a large viewers. The platform boasts of over 2 million month-to-month views, illustrating its reputation amongst audiences.
