# OpenAI Agents SDK

Give an OpenAI Agents SDK agent function tools that run commands and files in a Sandcovery sandbox.

This guide gives an [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/) agent three function tools that work in one Sandcovery sandbox: run a shell command, write a file, and read a file. The sandbox runs 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.
- Set `OPENAI_API_KEY` for the agent's model.

## Install the packages

```bash
pip install openai-agents sandcovery
```

## Define the tools and the run

```py title="agent.py"
from typing import Any

from agents import Agent, Model, RunContextWrapper, Runner, Tool, function_tool
from sandcovery import Sandcovery

def tool_error(_: RunContextWrapper[Any], error: Exception) -> str:
    return f"{type(error).__name__}: {error}"

def sandbox_tools(sandcovery: Sandcovery, sandbox_id: str) -> list[Tool]:
    @function_tool(failure_error_function=tool_error)
    def run_command(command: str) -> str:
        """Run a shell command in the sandbox and return its exit code, stdout, and stderr.

        Args:
            command: The shell command to run.
        """
        return sandcovery.sandboxes.exec(sandbox_id, command).model_dump_json()

    @function_tool(failure_error_function=tool_error)
    def write_file(path: str, content: str) -> str:
        """Write a text file in the sandbox, creating its parent directories.

        Args:
            path: The absolute path of the file.
            content: The text to write.
        """
        return sandcovery.sandboxes.write_file(sandbox_id, path, content).model_dump_json()

    @function_tool(failure_error_function=tool_error)
    def read_file(path: str) -> str:
        """Read a UTF-8 text file in the sandbox.

        Args:
            path: The absolute path of the file.
        """
        return sandcovery.sandboxes.read_file(sandbox_id, path).decode()

    return [run_command, write_file, read_file]

def run_agent(sandcovery: Sandcovery, prompt: str, *, model: str | Model | None = None) -> str:
    sandbox = sandcovery.sandboxes.create(slug="sandcovery/2x4", ttl_seconds=600)
    try:
        agent = Agent(
            name="Sandbox agent",
            instructions="Answer by running code in your Linux sandbox through your tools.",
            model=model,
            tools=sandbox_tools(sandcovery, sandbox.id),
        )
        return str(Runner.run_sync(agent, prompt).final_output)
    finally:
        sandcovery.sandboxes.destroy(sandbox.id)
```

- `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.
- Each tool's docstring becomes the description and argument help the model reads.
- `run_command` returns the exit code, stdout, stderr, and duration as JSON. A command runs for up to 300 seconds, or for the longest command its provider runs when that is shorter, unless `exec` gets `timeout_seconds`.
- A tool that raises, such as a read of a missing file, sends its error to the model instead of ending the run. `failure_error_function` sends the error's type and message, since the SDK's default sends only a generic retry notice.
- `finally` destroys the sandbox after the answer or a failure. If your process exits first, Sandcovery destroys the sandbox when its `ttl_seconds` ends.
- With no `model`, the agent runs the SDK's default OpenAI model.

## Run the agent

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

from agent import run_agent

with Sandcovery() as sandcovery:
    print(run_agent(sandcovery, "Print the first 10 primes with a Python script."))
```

## 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.
