# LlamaIndex

Give a LlamaIndex agent function tools that run commands and files in a Sandcovery sandbox.

This guide gives a [LlamaIndex](https://developers.llamaindex.ai/python/framework/) `FunctionAgent` 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 llama-index sandcovery
```

## Define the tools and the run

```py title="agent.py"
from collections.abc import Callable

from llama_index.core.agent.workflow import FunctionAgent
from llama_index.core.llms import LLM
from sandcovery import Sandcovery

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

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

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

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

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

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

    return [run_command, write_file, read_file]

async def run_agent(sandcovery: Sandcovery, prompt: str, *, llm: LLM | None = None) -> str:
    sandbox = sandcovery.sandboxes.create(slug="sandcovery/2x4", ttl_seconds=600)
    try:
        agent = FunctionAgent(
            llm=llm,
            system_prompt="Answer by running code in your Linux sandbox through your tools.",
            tools=sandbox_tools(sandcovery, sandbox.id),
        )
        output = await agent.run(prompt, max_iterations=10, early_stopping_method="generate")
        return str(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.
- LlamaIndex turns each function into a tool: its name becomes the tool name, its docstring the description, and each `Args` line the help for that argument.
- `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 message to the model instead of ending the run.
- `max_iterations=10` stops the agent at its 10th model reply, and `early_stopping_method="generate"` then asks the model for a final answer instead of raising an error.
- `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 `llm`, the agent runs LlamaIndex's default OpenAI model.

## Run the agent

```python title="main.py"
import asyncio

from sandcovery import Sandcovery

from agent import run_agent

with Sandcovery() as sandcovery:
    print(asyncio.run(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.
