Create a secure AI code execution workflow using the Daytona SDK

by Brenden Burgess

When you buy through links on our site, we may earn a commission at no extra cost to you. However, this does not influence our evaluations.

Right now Daytona SDK tutorial, we provide a practical procedure to take advantage of the secure sand environment of Daytona to execute the unreliable or generated Python code generated by AI Notebook. Starting with the creation of simple sand bins and the execution of basic code, the guide shows how to isolate the processes, install dependencies and execute simple scripts without compromising the host environment. As the tutorial progresses, it immerses itself in data processing with pandas, file operations, including reading and writing JSON files, and the execution of complex extracts generated by AI such as recursive functions and sorting algorithms. Finally, it presents the execution of parallel tasks on several sandboxes and the appropriate cleaning procedures, ensuring that each resource is managed and eliminated 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 SDK Daytona (if it is not already present), then initialize the classes of Daytona Core (Daytona, Daytonaconfig and Createandboxparams) to configure and create secure python sandbox. It also provides standard public services such as the operating system, time and JSON for 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 sequence\ndef fib(n):\n    if n  arr(j+1):\n                arr(j), arr(j+1) = arr(j+1), arr(j)\n    return arr\nprint(bubble_sort((64, 34, 25, 12, 22, 11, 90)))",
            "# Data analysis\nimport math\ndata = (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 math\nresult = 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 daytonatuutorial class sums up a complete end-to-end guide for the use of Daytona SDK: it initializes a secure sandbox client with your API key, demonstrates the insulated code execution (simple prints via the processing of Pandas data and the I / O file to AI-Ai-Ai-Ai demolition extracts), orchestra parallel tasks on several boxes of sand and Cleaning all resources. Each method is autonomous, presenting key features of Daytona, the creation of sandboxes, the installation of dependence, safe execution and cleaning of resources, in a clear workflow and step by step which is ideal for operating in Notebook.

def main():
    """Main function to run the tutorial"""


    print("🔑 Daytona Setup Instructions:")
    print("1. Visit: https://app.daytona.io")
    print("2. Create an account")
    print("3. Generate API key at: https://app.daytona.io/dashboard/keys")
    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 https://app.daytona.io/dashboard/keys")
        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 hand () function describes the initial configuration steps, guiding users to create a Daytona account and generate their API key, then valid that the key was provided before instantiation of the Daytonaturial class and to do the full procedure. If the API key is missing or not valid, it prints clear instructions and abandonment, ensuring a smooth first experience.

if __name__ == "__main__":
    main()

Finally, the verification of the standard Python input above guarantees that hand () is only invoked when the script is executed directly, by initiating the workflow of the Daytona tutorial in a clear and controlled manner.

In conclusion, by following this tutorial, the developers acquire a complete understanding of the basic capacities of Daytona: create isolated python bins, carry out secure data manipulations, manage the files of files, execute an arbitrary work code or generated by AI and orchestrate the parallel workloads, while maintaining a strict separation of the host system. Cleaning routines highlight the importance of resource hygiene in long -standing workflows. Armed with these fundamental skills, users can fully integrate Daytona into larger automatic learning pipelines, automated test frameworks or any scenario that requires safe execution of the dynamic code.


Discover the Notebook. All the merit of this research goes to researchers in this project. Also, don't hesitate to follow us Twitter And don't forget to join our 99K + ML Subreddit and subscribe to Our newsletter.


Asif Razzaq is the CEO of Marktechpost Media Inc .. as a visionary entrepreneur and engineer, AIF undertakes to exploit the potential of artificial intelligence for social good. His most recent company is the launch of an artificial intelligence media platform, Marktechpost, which stands out from its in-depth coverage of automatic learning and in-depth learning news which are both technically solid and easily understandable by a large audience. The platform has more than 2 million monthly views, illustrating its popularity with the public.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.