An agent that writes code also has to run it, and the easiest place to run it is the machine the agent is on. With LangChain’s Deep Agents that is one line of configuration, and from then on every command the model comes up with runs on the machine where the agent runs, which could be your laptop, with that machine’s permissions and files. A sandbox gives the agent a throwaway machine for that work.

Deep Agents works with sandboxes from several providers, but Azure Container Apps sandboxes are not on the list. I wrote the integration myself, a class of about a hundred lines, and a small demo that creates a sandbox, lets an agent work in it and deletes it again. The code is on GitHub: gbaeke/deep-agents-aca-sandbox.

The diagram follows one command from the model to the sandbox:

Diagram titled "The agent stays with you, its shell runs in the sandbox" with five numbered steps. The model asks for the execute tool with a Python command. Deep Agents on your machine owns the tools and calls the backend. The backend, AzureContainerAppsSandbox, sends the command to Azure with the Python SDK. The Azure Container Apps sandbox, a microVM with Ubuntu, runs it and returns the output and exit code. The model reads the result and decides the next step. Model keys and Azure credentials stay on your machine.

What is Deep Agents?

Deep Agents is LangChain’s library for agents that work on a task for a while: they read and write files and hand parts of the work to subagents. You call create_deep_agent with a model and get an agent that already has file tools (ls, read_file, write_file, edit_file, delete, grep, glob) and a task tool to start a subagent. A to-do list for planning is opt-in since version 0.7: you add LangChain’s TodoListMiddleware yourself. I wrote an introduction in Deep Agents from zero.

Where those files live is decided by the backend, a parameter of create_deep_agent. Backends come in two kinds: those that only store files, and those that can also run commands.

Two backends only store files:

  • StateBackend is what you get when you don’t pass a backend. A file the agent writes goes into the agent’s state, next to the messages. No file appears on any disk. The file is kept wherever the state is kept: in memory for the length of one run, or in a database when you give the agent a checkpointer that saves the state there.
  • FilesystemBackend reads and writes a folder on the machine where the agent runs.

With these two the agent has file tools and nothing else. It can write Python or other code, but it has no way to execute that code.

The other kind has a shell. When the backend can run commands, Deep Agents gives the model one more tool, execute, and the agent can run what it wrote:

  • LocalShellBackend is FilesystemBackend plus a shell. Commands run on the machine where the agent runs.
  • A sandbox backend, such as LangSmithSandbox or the one in this post, runs commands and keeps files on a separate machine.

LocalShellBackend is the quickest way to see execute work, and it is fine for a test with a prompt you wrote yourself. For anything else it is a bad idea, because the model decides what runs. That can be rm -rf in the wrong folder, or a command it picked up from a web page it just read.

What is a sandbox?

A sandbox is an isolated machine that exists for the agent’s work: a container or a small virtual machine with its own disk, its own processes and its own network boundary. The agent can install packages, clone repositories and run whatever it wrote. When the work is done you delete the sandbox, and anything that went wrong disappears with it.

A sandbox backend gives a Deep Agent these things:

  • an execute tool that runs shell commands in the sandbox
  • file tools that read and write the sandbox’s disk, so the script the agent writes and the command that runs it see the same files
  • two methods for your own code, upload_files() and download_files(), to put input in before the agent starts and get results out afterwards

The agent itself stays where it is. The loop, the model calls and your API keys stay on your machine or server, and only commands and files travel to the sandbox. The Deep Agents documentation calls this pattern “sandbox as tool”.

In the diagram, the left box is the agent loop and the right box is the backend. Follow the arrows to see a file being written and then executed:

Diagram titled "The loop decides, the backend does the work" with two boxes. The left box is the agent loop, where your agent runs: it asks the model, hands the tool call over and reads the result. The right box is the backend, the sandbox on a separate machine: it writes the file and runs the command. Arrows between the boxes show write_file going to the sandbox with "Updated file" coming back, and execute going to the sandbox with output and exit code coming back. Swap the right box and the loop stays the same.

⚠️ Important: a sandbox limits what a command can damage. The agent can still send data out over the network, and anything you put inside the sandbox (a token, a customer file) is within its reach. Keep secrets outside.

Which sandboxes does Deep Agents support?

The deepagents package contains one remote sandbox, LangSmithSandbox. The sandboxes page in the documentation has examples for eight more, each in its own package: Daytona, E2B, Modal, Runloop, Vercel, AWS AgentCore, Databricks and NVIDIA OpenShell. The integrations index adds about twenty community packages.

They all work the same way. You create a sandbox with the provider’s SDK, wrap it in the provider’s backend class and pass that to the agent. This is the Daytona version:

sandbox = Daytona().create()
backend = DaytonaSandbox(sandbox=sandbox)

agent = create_deep_agent(model=model, backend=backend)

Nothing from Microsoft is on either page.

What are Azure Container Apps sandboxes?

Azure Container Apps sandboxes are a fairly new part of Container Apps. A sandbox is a microVM that starts from a disk image and gets its own CPU, memory, disk and network boundary. You run commands in it, read and write its files and delete it when you are done. Some properties that matter for agents:

  • A sandbox starts fast. In my runs, creating one took 2 to 3 seconds, with the SDK checking every 3 seconds whether it is running.
  • After 300 seconds without activity a sandbox suspends, and you stop paying for CPU and memory. You can resume it later, with its files.
  • Disk images come from Microsoft (I use ubuntu) or from your own container images.
  • An egress policy decides which hosts a sandbox can reach. Without one, outbound traffic is open.
  • Snapshots save memory and disk, so you can start new sandboxes from a prepared state.

Sandboxes live in a sandbox group, an Azure resource in a resource group and a region. The group costs nothing. You pay per vCPU second and GiB second while a sandbox runs.

There is a Python SDK, azure-containerapps-sandbox. Running a command with it takes a few lines:

client = SandboxGroupClient(
    endpoint_for_region("swedencentral"),
    DefaultAzureCredential(),
    subscription_id=subscription_id,
    resource_group="rg-deep-agents-sandbox",
    sandbox_group="deep-agents",
)

sandbox = client.begin_create_sandbox(disk="ubuntu").result()
result = sandbox.exec("python3 --version")
print(result.stdout, result.exit_code)

⚠️ Important: the SDK is a beta (I used 1.0.0b1) and its API can still change. Your account also needs the role Container Apps SandboxGroup Data Owner on the sandbox group, or every call to a sandbox fails.

Why do we need our own backend?

Deep Agents does not know the Azure SDK. It expects a backend with a fixed set of methods: execute, ls, read, write, edit, grep, glob and the two file transfer methods. The Azure SDK has exec, read_file and write_file, with other names and other return types. Something has to translate, and that translation is the backend class.

Two packages on PyPI do this already. langchain-acasandbox is a backend for Azure Container Apps sandboxes that supports async calls only and pins exact versions of Deep Agents and the Azure SDK. maf-sandbox-deepagents reaches the same sandboxes through a router from an extension project for Microsoft Agent Framework. Both are fine choices. I wrote my own because the class is small and writing it shows how Deep Agents talks to a sandbox.

It is small because of BaseSandbox, a base class in Deep Agents. It implements the file tools as commands that run inside the sandbox. ls is a short Python script sent through execute(). grep runs grep in the sandbox, and delete runs rm -rf. write_file creates the folder with a command and sends the content with upload_files(). A subclass only has to supply four members:

Diagram titled "The file tools are inherited, four members are yours". On the left, seven file tools inherited from BaseSandbox: ls, read_file, grep, glob, edit_file, delete and write_file, each implemented as a command or Python script sent through execute, with write_file also using upload_files. On the right, the four members you write for Azure: execute, upload_files, download_files and id. The sandbox image needs a shell and python3.

The backend

The class takes a sandbox from the Azure SDK and keeps it. The id property returns the sandbox’s ID:

class AzureContainerAppsSandbox(BaseSandbox):
    def __init__(self, sandbox: SandboxClient, *, timeout: int = 120,
                 working_directory: str | None = None) -> None:
        self._sandbox = sandbox
        self._timeout = timeout
        self._working_directory = working_directory

    @property
    def id(self) -> str:
        return self._sandbox.sandbox_id

execute() does most of the work. Deep Agents passes a command and sometimes a timeout, and wants back one string of output and an exit code:

def execute(self, command: str, *, timeout: int | None = None) -> ExecuteResponse:
    seconds = self._timeout if timeout is None else timeout
    wrapped = f"bash -c {shlex.quote(command)}"
    if seconds > 0:
        wrapped = f"timeout --signal=KILL {seconds} {wrapped}"
    try:
        result = self._sandbox.exec(wrapped, working_directory=self._working_directory)
    except AzureError as error:
        return ExecuteResponse(output=f"Error: the sandbox did not run the command: {error}", exit_code=1)

    output = result.stdout or ""
    if result.stderr:
        output = f"{output.rstrip(chr(10))}\n{result.stderr}" if output else result.stderr
    # ...
    return ExecuteResponse(output=output, exit_code=result.exit_code)

Three things in it are specific to Azure:

  • The SDK’s exec() has no timeout parameter. The backend puts the Linux timeout command in front, so the sandbox kills a command that runs too long.
  • The command goes through bash -c, so the model can use pipes, && and heredocs the way it would in a terminal.
  • Azure returns stdout and stderr separately. Deep Agents wants one text for the model, so the backend joins them.

An Azure error becomes a normal result with exit code 1. The model then reads what went wrong and can react, and the agent run does not crash.

The file methods take a list and return a result per file. A failed file gets an error code in its own result, and the other files still go through:

def upload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]:
    responses = []
    for path, content in files:
        if not path.startswith("/"):
            responses.append(FileUploadResponse(path=path, error="invalid_path"))
            continue
        try:
            self._sandbox.write_file(path, content, create_dirs=True)
            responses.append(FileUploadResponse(path=path))
        except AzureError as error:
            responses.append(FileUploadResponse(path=path, error=_file_error(error)))
    return responses

download_files() is the same loop with read_file(). The helper _file_error maps Azure’s errors to the codes Deep Agents knows, such as file_not_found and is_directory. The full class is in backend.py.

A sandbox per conversation

The backend wraps a sandbox that already exists. Creating and finding sandboxes is a separate, small module. Every sandbox gets two labels: one for the app and one for the conversation, the thread:

def create_sandbox(client, *, thread_id: str, disk: str = "ubuntu", auto_suspend_seconds: int = 300):
    return client.begin_create_sandbox(
        disk=disk,
        auto_suspend_seconds=auto_suspend_seconds,
        labels={"app": "deep-agents-sandbox", "thread": thread_id},
    ).result()

With the thread label, a later run finds the sandbox of the same conversation and wakes it up when it was suspended:

def find_sandbox(client, *, thread_id: str):
    for sandbox in client.list_sandboxes(labels={"app": "deep-agents-sandbox", "thread": thread_id}):
        found = client.get_sandbox_client(sandbox.id)
        found.ensure_running()
        return found
    return None

Giving the sandbox to the agent is then the same three lines as with any other provider:

sandbox = create_sandbox(group_client(), thread_id=thread_id)

agent = create_deep_agent(
    model=model,
    system_prompt=SYSTEM_PROMPT,
    backend=AzureContainerAppsSandbox(sandbox, working_directory="/"),
)

Running it

You need uv, the Azure CLI with az login, and a model. I use Azure OpenAI models behind a local gateway; any OpenAI-compatible endpoint with the Responses API works. One script creates the resource group, the sandbox group and the role assignment:

git clone https://github.com/gbaeke/deep-agents-aca-sandbox && cd deep-agents-aca-sandbox
cp .env.example .env
./scripts/azure-up.sh
uv run main.py

main.py prints what happens: the sandbox it created, each tool call with its result, the answer and the delete. This is the default task, a script that prints prime numbers. Look at the first and last line for the sandbox’s life, and at the arrows for the tool calls:

Terminal output of uv run main.py. A sandbox is created in 2.2 seconds. The task asks for a Python script that prints the first 20 prime numbers. The agent calls execute to check the machine, write_file to create /work/primes.py, execute to run it, which prints the primes, and execute to read the OS version. The answer reports Ubuntu 26.04.1 LTS with Python 3.14.4. The last line says the sandbox was deleted.

The agent wrote the file with write_file and ran it with execute. Both went to the same machine in Azure, an Ubuntu VM that was gone again when the run ended.

A task with more to it: clone a repository and count its Python code. With --keep the sandbox stays, and --thread gives the conversation a name:

uv run main.py --keep --thread demo "Clone https://github.com/langchain-ai/deepagents (shallow) \
  into /work/deepagents. How many Python files does it have, and how many lines of Python in total?"

This is the start of the output, trimmed:

Created sandbox 75108402-1e86-4cae-8062-34bb60bd844d (thread demo) in 2.3s
→ execute(command='git clone --depth 1 https://github.com/langchain-ai/deepagents /work/deepagents', timeout='120000')
Error: timeout 120000s exceeds maximum allowed (3600s).
→ execute(command='git clone --depth 1 https://github.com/langchain-ai/deepagents /work/deepagents', timeout='300')
Cloning into '/work/deepagents'...
[Command succeeded with exit code 0]
→ execute(command='python -c \'from pathlib import Path; ...', timeout='300')
bash: line 1: python: command not found
[Command failed with exit code 127]
→ execute(command='python3 -c \'from pathlib import Path; ...', timeout='300')
...
Python files: 1274
Python lines: 739134
[Command succeeded with exit code 0]

The model made two mistakes here and fixed both. It asked for a timeout in milliseconds, and Deep Agents refused before anything reached Azure. Then it called python, which the ubuntu image does not have, read the exit code 127 and switched to python3. This trial and error is why you want a sandbox: the model tries things, and you would rather have it try them on a machine you can delete. 😊

While that sandbox is kept, a second script lists what is in the sandbox group:

Terminal output of uv run scripts/sandboxes.py: a table titled "Sandboxes in deep-agents" with one row, a sandbox ID, the state Running, the thread demo and the creation time.

A second run with the same thread name finds that sandbox by its label. The repository from the first run is still on its disk, so the agent can go straight to the question:

Terminal output of uv run main.py --thread demo. The first line says the sandbox was reused in 2.2 seconds. The task asks which three Python files in /work/deepagents have the most lines. The agent runs one execute call with a Python script and lists three files with their line counts. The last line says the sandbox was deleted.

Without --keep the sandbox is deleted at the end of the run, and the cloned repository goes with it.

Does it behave like the other providers?

LangChain publishes a standard test suite for sandbox backends, SandboxIntegrationTests in the langchain-tests package. You give it a fixture that creates a sandbox, and it runs 87 tests against it: commands, exit codes, large output, file uploads, edits, searches, and the async variants.

class TestAzureContainerAppsSandbox(SandboxIntegrationTests):
    @pytest.fixture(scope="class")
    def sandbox(self):
        sandbox = create_sandbox(group_client(), thread_id="standard-tests")
        try:
            backend = AzureContainerAppsSandbox(sandbox)
            backend.execute("ln -sf /usr/bin/python3 /usr/local/bin/python")
            yield backend
        finally:
            sandbox.delete()

Against a real sandbox, 80 of the 87 tests pass in under a minute. The 7 that fail test glob and write, two methods the class inherits from BaseSandbox without changes. With deepagents 0.7.43 and langchain-tests 1.2.0 the two disagree: the base class returns absolute paths from glob and overwrites an existing file on write, and the suite expects relative paths and an error. I left the backend alone, because changing it would make the agent’s file tools behave differently from their own descriptions.

The suite found a real mistake of mine too. My first version cut command output at 200 KB. BaseSandbox reads files through execute(), so a large file came back as broken JSON. The cap is gone, and Deep Agents takes care of large output before it reaches the model.

What this post leaves out

This post has one goal: getting an Azure Container Apps sandbox to work as a backend for LangChain’s Deep Agents. The demo creates a sandbox from the ubuntu disk, runs commands in it, reads and writes its files and deletes it. Azure Container Apps sandboxes can do a lot more.

Two of those features are in the repository, although this post does not cover them. In the runs above the sandbox has open internet access. With --lockdown, the demo creates it with an egress policy that denies outbound traffic except a list of allowed hosts. The egress proxy can also add a header, such as an API token, to requests for one host, so the agent calls an API without ever holding the key. The demo does that with a GitHub token. The README explains how to try both.

None of the following is in the demo:

  • Snapshots save memory and disk, so new sandboxes can start from a prepared state, for example with a repository and its packages in place.
  • A sandbox’s disk can come from your own container image, and you can commit a running sandbox to a new image.
  • A lifecycle policy can delete a sandbox some time after it stops. The demo only has the default suspend after 300 seconds, so a kept sandbox stays in the group until you delete it.
  • An exposed port gives a service in the sandbox an HTTPS URL, open or behind Microsoft Entra ID. That is how you would preview a web app the agent built.
  • Volumes keep data that outlives a sandbox, and can mount Azure Blob storage.
  • Sandboxes come in sizes from 0.25 vCPU with 0.5 GiB of memory to 16 vCPU with 32 GiB. The demo takes the default of 1 vCPU and 2 GiB.
  • A sandbox group can connect to a virtual network, so sandboxes reach private resources.

I might come back to some of these in later posts. 😊

Wrapping up

If you standardize on Deep Agents and your workloads run on Azure, it is a bit of a disappointment that Azure Container Apps sandboxes are missing from the list of supported sandboxes. The gap is easy to close yourself: a subclass of BaseSandbox with four members, about a hundred lines. A backend like this touches little of Deep Agents and of the Azure SDK, so it is stable enough to use in your own deployments.

Do check out the community packages too, langchain-acasandbox and maf-sandbox-deepagents, and make up your mind after you have evaluated them. The code for this post is at gbaeke/deep-agents-aca-sandbox.

If you spot any errors or have questions, feel free to reach out!