On this Daytona SDK tutorial, we offer a hands-on walkthrough for leveraging Daytona’s safe sandbox surroundings to execute untrusted or AI-generated Python code safely inside Pocket book. Starting with easy sandbox creation and primary code execution, the information demonstrates easy methods to isolate processes, set up dependencies, and run easy scripts with out jeopardizing the host surroundings. Because the tutorial progresses, it delves into information processing with pandas, file operations together with studying and writing JSON information, and the execution of complicated AI-generated snippets comparable to recursive features and sorting algorithms. Lastly, it showcases parallel process execution throughout a number of sandboxes and correct cleanup procedures, making certain that each useful resource is managed and disposed of appropriately.
import os
import time
import json
from typing import Checklist, 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 courses (Daytona, DaytonaConfig, and CreateSandboxParams) for configuring and creating safe Python sandboxes. It additionally brings in commonplace 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: Checklist[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("Hi there 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 primary demo: {e}")
def data_processing_demo(self):
"""Demo 2: Knowledge processing in remoted surroundings"""
print("n📊 Demo 2: Safe Knowledge Processing")
print("-" * 40)
strive:
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
self.sandboxes.append(sandbox)
install_cmd = "import subprocess; subprocess.run(['pip', 'install', 'pandas'])"
response = sandbox.course of.code_run(install_cmd)
data_code = """
import pandas as pd
import json
# Create pattern dataset
information = {
'title': ['Alice', 'Bob', 'Charlie', 'Diana'],
'age': [25, 30, 35, 28],
'wage': [50000, 60000, 70000, 55000]
}
df = pd.DataFrame(information)
outcome = {
'total_records': len(df),
'avg_age': df['age'].imply(),
'avg_salary': df['salary'].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("✅ Knowledge processing accomplished:")
print(response.outcome)
else:
print(f"❌ Error: {response.outcome}")
besides Exception as e:
print(f"❌ Error in information 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
information = {'message': 'Hi there from Daytona!', 'timestamp': '2025-06-13'}
with open('pattern.json', 'w') as f:
json.dump(information, 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)
# Checklist information in present listing
information = os.listdir('.')
print(f"nFiles in listing: {information}")
"""
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 range(10)])",
"# Type 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]))",
"# Knowledge analysisnimport mathndata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]nmean = sum(information) / len(information)nvariance = sum((x - imply) ** 2 for x in information) / len(information)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('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('Job 2: String processing')ntext="Hi there 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, process) in enumerate(zip(parallel_sandboxes, duties)):
print(f"n🏃 Beginning parallel process {i+1}")
response = sandbox.course of.code_run(process)
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 via pandas information processing and file I/O to AI-generated snippets), orchestrates parallel duties throughout a number of sandboxes, and eventually ensures clear teardown of all assets. Every technique 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 superb for working in Pocket book.
def major():
"""Important 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. Substitute 'YOUR_API_KEY' under 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 working 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("💡 Ensure your API secret's legitimate and you've got community entry")
The principle() 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 working the complete walkthrough. If the API secret’s lacking or invalid, it prints clear directions and aborts, making certain a easy first-time expertise.
if __name__ == "__main__":
major()
Lastly, the above commonplace Python entry-point examine ensures that major() is barely invoked when the script is run straight, 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 information manipulations, managing file I/O, working 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 situation 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 at liberty to comply with us on Twitter and don’t overlook to hitch our 99k+ ML SubReddit and Subscribe to our E-newsletter.
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 recognition amongst audiences.