Velamuvi AIAcademy
AutoGen

Lesson 4 of 6 · AutoGen

Code Execution Safely

Let AutoGen agents run code without risking your machine: CodeExecutorAgent with Docker, why local execution is risky, approval checks, timeouts and no secrets.

  • 9 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why code written by a model must never run directly on your machine
  • Run code in a container with DockerCommandLineCodeExecutor
  • Check code before it runs with an approval function
  • Apply timeouts, clean working folders and no secrets

Agents that write and run code

One of AutoGen's best-known patterns is a coder agent that writes code and an executor that runs it and reports back. The model can test its own ideas: calculate an answer, check a date, analyse a file, and fix its code when the output shows an error.

The danger is obvious once you say it aloud: you are running code written by a model, which may be wrong, or may have been steered by malicious text in a document or web page it read (see the Agent Security and Guardrails course). That code can delete files, read secrets or send data anywhere your machine can reach.

Run it in a container

import asyncio
from autogen_agentchat.agents import AssistantAgent, CodeExecutorAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor
from autogen_ext.models.anthropic import AnthropicChatCompletionClient

async def main():
    model_client = AnthropicChatCompletionClient(model="MODEL_NAME")
    # Code runs inside a throwaway container, not on your machine
    async with DockerCommandLineCodeExecutor(image="python:3.12-slim", work_dir="coding", timeout=60) as executor:
        coder = AssistantAgent(
            "coder", model_client=model_client,
            system_message="Solve the task with Python, in a Markdown code block marked as python. "
                           "When you have the final answer from the executor's output, say TERMINATE.",
        )
        runner = CodeExecutorAgent("executor", code_executor=executor)
        team = RoundRobinGroupChat([coder, runner],
                                   termination_condition=TextMentionTermination("TERMINATE") | MaxMessageTermination(10))
        result = await team.run(task="How many days are there between 1 March and 30 June 2027?")
        print(result.messages[-1].content)
    await model_client.close()

asyncio.run(main())

DockerCommandLineCodeExecutor runs each code block inside a Docker container started from the image you choose, with only the work_dir folder shared. When the async with block ends, the container is stopped and removed. (It needs Docker running and pip install "autogen-ext[docker]".)

Check code before it runs

CodeExecutorAgent accepts an approval_func, called with the code before anything runs. It can show the code to a person, apply rules, or both. Here a rule-based approval blocks risky libraries, and the coder adapts:

import asyncio, re, tempfile
from autogen_agentchat.agents import ApprovalRequest, ApprovalResponse, AssistantAgent, CodeExecutorAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.messages import TextMessage
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor
from autogen_ext.models.anthropic import AnthropicChatCompletionClient

RISKY = re.compile(r"\b(subprocess|shutil|os\.remove|os\.system|requests|socket|open\()")

def approve(request: ApprovalRequest) -> ApprovalResponse:
    """Called before any code runs. A person could decide here; this one applies rules."""
    found = sorted(set(RISKY.findall(request.code)))
    if found:
        return ApprovalResponse(approved=False, reason=f"Not allowed: {', '.join(found)}. Use only calculations.")
    return ApprovalResponse(approved=True, reason="Calculation only")

async def main():
    model_client = AnthropicChatCompletionClient(model="MODEL_NAME")
    with tempfile.TemporaryDirectory() as work_dir:                 # an empty, temporary folder
        executor = CodeExecutorAgent(
            "executor",
            code_executor=LocalCommandLineCodeExecutor(work_dir=work_dir, timeout=30),
            approval_func=approve,
        )
        coder = AssistantAgent("coder", model_client=model_client,
                               system_message="Put Python code in a Markdown code block marked as python. Say TERMINATE when done.")
        team = RoundRobinGroupChat([coder, executor],
                                   termination_condition=TextMentionTermination("TERMINATE") | MaxMessageTermination(8))
        result = await team.run(task="What is the average of the monthly sales 120, 95, 143 and 88?")
        for m in result.messages:
            if isinstance(m, TextMessage):
                print(f"{m.source}: {m.content.strip()}")
    await model_client.close()

asyncio.run(main())
Output
user: What is the average of the monthly sales 120, 95, 143 and 88?
coder: ```python
import requests
sales = requests.get('https://example.com/sales.json').json()
print(sum(sales) / len(sales))
```
executor: Code execution was not approved. Reason: Not allowed: requests. Use only calculations.
coder: ```python
sales = [120, 95, 143, 88]
print(sum(sales) / len(sales))
```
executor: 111.5
coder: The average monthly sales figure is 111.5. TERMINATE

The first attempt tried to fetch data from the internet, which the approval function refused, with a reason. The coder read the refusal and rewrote the code using only the numbers it was given, which ran and printed 111.5. The refusal reason went back into the conversation, which is what let the coder correct itself.

What the approval step looks at

Here is the core of what happens before code runs, in plain Python: find the code blocks in a message, then check each against a policy:

Try it yourselfPython
import re

# What a code-executing agent does before running anything, in plain Python:
# 1) find the code blocks in the model's message, 2) check them against a policy.
FENCE = "`" * 3                                          # three backticks start and end a code block

message = (f"Here's my solution:\n{FENCE}python\nimport os\nos.system('rm -rf /tmp/data')\n{FENCE}\n"
           f"And a check:\n{FENCE}python\nprint(sum([120, 95, 143, 88]) / 4)\n{FENCE}")

def extract_code_blocks(text):
    pattern = FENCE + r"(\w*)\n(.*?)" + FENCE
    return [(lang or "text", code) for lang, code in re.findall(pattern, text, re.S)]

BLOCKED = ["os.system", "subprocess", "shutil.rmtree", "socket", "requests"]
def policy(code):
    return [b for b in BLOCKED if b in code]

for lang, code in extract_code_blocks(message):
    problems = policy(code)
    first_line = code.strip().splitlines()[-1]
    print(f"[{lang}] {first_line:<40} -> {'BLOCKED: ' + ', '.join(problems) if problems else 'allowed'}")

A safety checklist

  • Isolate: run code in a container (or a microVM for strangers' tasks), never on your own machine or server.
  • Limit time: set timeout so runaway loops are stopped.
  • Start clean: give each task an empty working folder, and delete it afterwards.
  • No secrets: don't pass API keys or credentials into the executor's environment or folder.
  • Approve what matters: for anything beyond calculation (files, network, installs), add an approval step, with a person for high-risk actions.
  • Cap the loop: a MaxMessageTermination stops a coder and executor that keep failing.

Common mistakes

Practice exercise

Find the code blocks in an agent's reply, the first thing a code executor agent does before deciding what to run.

Your solutionPython
import re
FENCE = "`" * 3
reply = f"Try this:\n{FENCE}python\nx = 6 * 7\nprint(x)\n{FENCE}\nThen run:\n{FENCE}sh\nls -la\n{FENCE}"

# Find every code block with re.findall(FENCE + r"(\w*)\n(.*?)" + FENCE, reply, re.S).
# Print one line per block: the language, a colon, and the number of lines of code, e.g.  js: 3
Knowledge check

Why should a CodeExecutorAgent use DockerCommandLineCodeExecutor rather than LocalCommandLineCodeExecutor for model-written code?

Summary

  • A coder and a CodeExecutorAgent let models test their own code, but the code is untrusted.
  • Use DockerCommandLineCodeExecutor; keep LocalCommandLineCodeExecutor for code you'd run yourself.
  • An approval_func checks code before it runs and returns a reason the coder can act on.
  • Pattern checks are a filter, not protection; the sandbox is the protection.
  • Set timeouts, use clean folders, keep secrets out and cap the conversation.

Next: the project, a coding assistant team.

Finished reading? Tick it off to track your progress.