Code Execution

Let agents write and run code

Enable agents to write and execute code to solve problems.

Diagram

Code Execution

📋 Problem

🤖 Agent

💻 Code

▶️ Run

📤 Result

Quick Start

  1. Create Code Execution Agent
    rust
    use praisonai::{Agent, tool};
    
    // Define a code execution tool
    #[tool(description = "Execute Python code and return the result")]
    async fn run_python(code: String) -> String {
        // Execute code in sandbox
        execute_python_sandboxed(&code).await
    }
    
    // Create agent with code execution tool
    let agent = Agent::new()
        .name("Coder")
        .instructions("Write and execute code to solve problems. Use the run_python tool.")
        .tool(run_python)
        .build()?;
    
    let response = agent.chat("Calculate the first 10 Fibonacci numbers").await?;
    // Agent writes Python code and executes it via the tool
  2. Safe Code Sandbox
    rust
    use praisonai::tool;
    
    #[tool(description = "Execute JavaScript code safely")]
    async fn run_js(code: String) -> String {
        // Use sandboxed environment with timeout
        sandbox::execute_with_timeout(
            &code,
            std::time::Duration::from_secs(10)
        ).await
    }

Supported Languages

LanguageRuntime
PythonBuilt-in
JavaScriptNode.js
RustCargo

Security

[!CAUTION] Code execution allows running arbitrary code. Use in trusted environments only.

Safety FeatureDescription
SandboxIsolated execution environment
TimeoutMax execution time
Resource limitsMemory and CPU caps

Related