AI Model Wiki

    Skip to main content
    40 min
    Lesson 3 of 5

    Code Execution & Tool Use

    From the course AutoGen: Multi-Agent Conversations

    Executing Code Safely

    Code Execution Configuration

    user_proxy = UserProxyAgent(
        name="executor",
        code_execution_config={
            "work_dir": "workspace",
            "use_docker": True,  # Recommended for safety
            "timeout": 60,
        },
    )
    

    Docker Isolation

    Run code in Docker containers for safety:

    • Prevents filesystem access outside the container
    • Limits resource usage (CPU, memory)
    • Supports custom images with pre-installed packages
    • Automatically cleans up after execution

    Custom Functions as Tools

    from autogen import register_function
    
    def search_web(query: str) -> str:
        """Search the web and return relevant results."""
        return perform_search(query)
    
    register_function(
        search_web,
        caller=assistant,
        executor=user_proxy,
        description="Search the web for information",
    )
    

    Practical Examples

    • Data analysis: Agent writes pandas code, executor runs it, agent interprets results
    • Web scraping: Agent generates scraping code, executor fetches and parses pages
    • File generation: Agent creates documents, charts, or reports saved to workspace
    • API integration: Agent calls external services through registered functions

    Common Pitfall: Returning Raw Exceptions to the Agent

    When a tool function raises an exception, AutoGen by default sends the Python traceback back to the agent. This wastes tokens and can confuse the agent. Wrap tool functions to return clean, actionable error messages:

    def safe_query_database(sql: str) -> str:
        """Execute a SQL query and return results as CSV."""
        try:
            results = execute_query(sql)
            return results.to_csv(index=False)
        except Exception as e:
            return f"Database error: {type(e).__name__}: {str(e)}. Check the SQL syntax and try again."
    

    Best Practice: Sandbox Tool Execution with Timeouts

    Long-running tool calls can block the entire agent conversation. Wrap external calls with a timeout:

    import signal
    
    def with_timeout(func, seconds=30):
        def handler(signum, frame):
            raise TimeoutError(f"Tool execution timed out after {seconds}s")
        signal.signal(signal.SIGALRM, handler)
        signal.alarm(seconds)
        try:
            return func()
        finally:
            signal.alarm(0)
    

    Named Product Reference: Azure Code Interpreter

    For teams using Azure OpenAI, the Azure Code Interpreter API executes Python in a managed sandbox — no Docker setup required. AutoGen integrates with it through the AzureCodeInterpreterTool. This is the recommended production choice for enterprise deployments where running Docker on the application server is not possible or not permitted by security policy.

    Key Takeaways

    • •Use Docker isolation for safe code execution in production
    • •Register custom functions as tools agents can call
    • •Code execution enables data analysis, scraping, and file generation
    • •Set timeouts and resource limits for all execution environments
    0 of 5 lessons marked complete

    Progress is kept in this browser only.