# LangChain Deep Agents

Run every shell and file tool of a Deep Agents agent in a Sandcovery sandbox through a sandbox backend.

[Deep Agents](https://docs.langchain.com/oss/python/deepagents/overview) gives an agent the file tools `ls`, `read_file`, `write_file`, `edit_file`, `glob`, and `grep`, plus `execute` when its backend is a sandbox. This guide writes that backend on Sandcovery, so each of those tools works in one sandbox on a provider account you connected.

## Before you start

- Create an API key and add at least one provider credential, as the [quickstart](/docs/quickstart) shows, and set `SANDCOVERY_API_KEY`.
- Use Python 3.11 or later, which the `sandcovery` package supports.
- Hold a key for the model you call. This guide calls Claude with `ANTHROPIC_API_KEY`, through the Anthropic package that Deep Agents installs.

## Install the packages

```bash
pip install deepagents sandcovery
```

## Write the backend and the run

```py title="agent.py"
from deepagents import create_deep_agent
from deepagents.backends.protocol import ExecuteResponse, FileDownloadResponse, FileUploadResponse
from deepagents.backends.sandbox import BaseSandbox
from langchain_core.language_models import BaseChatModel
from sandcovery import Sandcovery, SandcoveryError

def _file_error(error: SandcoveryError) -> str:
    return "file_not_found" if error.code == "not_found" else str(error)

class SandcoverySandbox(BaseSandbox):
    def __init__(self, sandcovery: Sandcovery, sandbox_id: str) -> None:
        self._sandcovery = sandcovery
        self._sandbox_id = sandbox_id

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

    def execute(self, command: str, *, timeout: int | None = None) -> ExecuteResponse:
        try:
            result = self._sandcovery.sandboxes.exec(self._sandbox_id, command, timeout_seconds=timeout or None)
        except SandcoveryError as error:
            if error.code == "unsupported":
                raise ValueError(str(error)) from error
            raise
        output = result.stdout + (f"\n<stderr>{result.stderr}</stderr>" if result.stderr else "")
        return ExecuteResponse(output=output, exit_code=result.exit_code)

    def upload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]:
        return [FileUploadResponse(path=path, error=self._upload(path, content)) for path, content in files]

    def download_files(self, paths: list[str]) -> list[FileDownloadResponse]:
        return [self._download(path) for path in paths]

    def _upload(self, path: str, content: bytes) -> str | None:
        if not path.startswith("/"):
            return "invalid_path"
        try:
            self._sandcovery.sandboxes.write_file(self._sandbox_id, path, content)
        except SandcoveryError as error:
            return _file_error(error)
        return None

    def _download(self, path: str) -> FileDownloadResponse:
        if not path.startswith("/"):
            return FileDownloadResponse(path=path, error="invalid_path")
        try:
            content = self._sandcovery.sandboxes.read_file(self._sandbox_id, path)
        except SandcoveryError as error:
            return FileDownloadResponse(path=path, error=_file_error(error))
        return FileDownloadResponse(path=path, content=content)

def run_agent(sandcovery: Sandcovery, prompt: str, *, model: str | BaseChatModel) -> str:
    sandbox = sandcovery.sandboxes.create(slug="sandcovery/2x4", ttl_seconds=600)
    try:
        agent = create_deep_agent(model=model, backend=SandcoverySandbox(sandcovery, sandbox.id))
        result = agent.invoke({"messages": [{"role": "user", "content": prompt}]})
        return result["messages"][-1].text
    finally:
        sandcovery.sandboxes.destroy(sandbox.id)
```

- `SandcoverySandbox` subclasses Deep Agents' `BaseSandbox`, which builds the file tools from `execute`, `upload_files`, and `download_files`. Those tools run `python3` in the sandbox, so its image needs Python 3.
- `execute` returns stdout, then any stderr inside `<stderr>` tags, with the exit code.
- With no timeout, or a timeout of 0, a command runs for up to Sandcovery's default of 300 seconds, or for the longest command the provider runs when that is shorter. A timeout past the longest command the provider runs raises `ValueError`, which Deep Agents sends to the model as an invalid parameter.
- A missing file comes back as `file_not_found` and a relative path as `invalid_path`, the codes Deep Agents expects.
- `run_agent` creates one sandbox for the run. `sandcovery/2x4` starts it on the [candidate](/docs/routing#how-a-create-is-routed) with the lowest hourly price among the providers that bill by use at 2 vCPU and 4 GiB, and falls back to the next candidate when a create fails.
- `finally` destroys the sandbox after the answer or a failure. If your process exits first, Sandcovery destroys the sandbox when its `ttl_seconds` ends.

## Run the agent

```python title="main.py"
from sandcovery import Sandcovery

from agent import run_agent

with Sandcovery() as sandcovery:
    answer = run_agent(
        sandcovery,
        "Print the first 10 primes with a Python script.",
        model="anthropic:claude-sonnet-5-5",
    )
    print(answer)
```

## Next steps

- [Routing](/docs/routing): rank providers by start latency or uptime instead, such as with `sandcovery/2x4:fastest`.
- [API keys](/docs/keys): cap the spend, providers, and concurrency of the key the agent uses.
