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 simple sandbox creation and fundamental code execution, the information demonstrates how one can isolate processes, set up dependencies, and run easy scripts with out jeopardizing the host surroundings. 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 corresponding to recursive capabilities and sorting algorithms. Lastly, it showcases parallel process 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 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 customary 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 consumer"""
self.config = DaytonaConfig(api_key=api_key)
self.daytona = Daytona(self.config)
self.sandboxes: Checklist[Any] = []
def basic_sandbox_demo(self):
"""Demo 1: Primary sandbox creation and code execution"""
print("🚀 Demo 1: Primary Sandbox Operations")
print("-" * 40)
strive:
sandbox = self.daytona.create(CreateSandboxParams(language="python"))
self.sandboxes.append(sandbox)
print(f"✅ Created sandbox: {sandbox.id}")
code="print("Good day 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.consequence}")
else:
print(f"❌ Error: {response.consequence}")
besides Exception as e:
print(f"❌ Error in fundamental demo: {e}")
def data_processing_demo(self):
"""Demo 2: Information processing in remoted surroundings"""
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', 'install', '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)
consequence = {
'total_records': len(df),
'avg_age': df['age'].imply(),
'avg_salary': df['salary'].imply(),
'abstract': df.describe().to_dict()
}
print(json.dumps(consequence, indent=2))
"""
response = sandbox.course of.code_run(data_code)
if response.exit_code == 0:
print("✅ Information processing accomplished:")
print(response.consequence)
else:
print(f"❌ Error: {response.consequence}")
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': 'Good day 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)
# Checklist 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.consequence)
else:
print(f"❌ Error: {response.consequence}")
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 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.consequence}")
else:
print(f"❌ Error: {response.consequence}")
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="Good day Daytona World"nprint(f'Reversed: {textual content[::-1]}')nprint(f'Phrase rely: {len(textual content.break 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: {consequence:.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.consequence}")
else:
print(f"❌ Job {task_num} failed: {response.consequence}")
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 consumer along with your API key, demonstrates remoted code execution (from easy prints by 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 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 preferrred for operating in Pocket book.
def principal():
"""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. Change 'YOUR_API_KEY' under along 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 along 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 that 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 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__":
principal()
Lastly, the above customary Python entry-point verify ensures that principal() 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 achieve 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 expertise, 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.
Try the Pocket book. All credit score for this analysis goes to the researchers of this undertaking. Additionally, be at liberty to observe us on Twitter and don’t overlook to affix 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.