> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gravixlayer.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Data Analysis with AI

> Run LLM-generated Python in an isolated Agent Runtime—analyze data and save charts without executing code on your machine.

Use [Gravix Layer](https://gravixlayer.ai) **Agent Runtimes** to run AI-generated Python safely in an isolated microVM. This guide walks through the official **[Data Analyst Agent](https://github.com/gravixlayer/gravixlayer-python/tree/main/examples/agents/python/data-analyst-agent)** example: an OpenAI-compatible LLM writes analysis code, the runtime executes it, and you get text insights plus PNG charts on disk.

## Overview

A typical workflow looks like this:

1. You (or your app) ask the model to analyze a dataset with natural-language prompts.
2. The model returns Python inside a fenced code block.
3. **Gravix Layer** runs that code inside a **dedicated Agent Runtime** (not your laptop).
4. Stdout/stderr go back into the chat so the model can fix or extend the code across several rounds.
5. Charts are written under `/workspace/charts` in the runtime and can be **downloaded** to your project folder.

Nothing in the user’s prompt runs locally except the small driver script that calls the API.

## What you’ll build

* Loads the **Seaborn Diamonds** dataset (≈54k rows) from a public URL inside the runtime.
* Installs **pandas**, **matplotlib**, **seaborn**, etc. **inside the runtime** via `pip`.
* Runs **five analysis steps** (overview, plots, cross-tabs, written summary).
* Saves PNG charts and optionally prints an execution timing summary.

Full source: **[gravixlayer-python/examples/agents/python/data-analyst-agent](https://github.com/gravixlayer/gravixlayer-python/tree/main/examples/agents/python/data-analyst-agent)**.

## How it works

```text theme={null}
User prompts  →  LLM emits Python in a fenced code block
                         │
                         ▼
              Agent Runtime runs code (isolated VM)
                         │
                         ▼
           stdout/stderr returned to the LLM for the next turn
                         │
                         ▼
              Charts saved under /workspace/charts → download locally
```

The script uses the high-level `Runtime` helper from `gravixlayer.types.runtime`: it creates a runtime, runs `runtime.run_code(...)` in a loop, then downloads PNGs with the SDK file APIs.

## Prerequisites

* **Python 3.9+**
* **[Gravix Layer API key](https://gravixlayer.ai)** (Agent Runtime access)
* An **OpenAI-compatible** API key (OpenAI, or any provider with a compatible base URL—Groq, Together, OpenRouter, etc.)

## 1. Get the example

Clone the repo and enter the example folder:

```bash theme={null}
git clone https://github.com/gravixlayer/gravixlayer-python.git
cd gravixlayer-python/examples/agents/python/data-analyst-agent
```

Or copy only this directory from the monorepo if you already have it checked out.

## 2. Install dependencies

Create a virtual environment and install requirements:

```bash theme={null}
python -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -r requirements.txt
```

`requirements.txt` pins:

```text theme={null}
openai>=1.30.0
gravixlayer>=0.1.0
python-dotenv>=1.0.0
```

## 3. Configure API keys

Get a **Gravix Layer** key from [gravixlayer.ai](https://gravixlayer.ai) and export both keys in your shell:

```bash theme={null}
export OPENAI_API_KEY="sk-..."
export GRAVIXLAYER_API_KEY="..."
```

Optional: copy `.env.example` to `.env` if you use `python-dotenv` in your own wrapper; the stock script reads the environment directly.

### Optional: other LLM providers

Point the OpenAI client at a compatible base URL and model, for example:

```bash theme={null}
export OPENAI_API_BASE_URL="https://api.groq.com/openai/v1"
export OPENAI_MODEL="llama-3.3-70b-versatile"
```

## 4. Run the agent

From `examples/agents/python/data-analyst-agent`:

```bash theme={null}
python data_analyst_agent.py
```

The script will:

1. Create an Agent Runtime (template defaults to `python-3.14-base-medium` unless you set `GRAVIXLAYER_TEMPLATE`).
2. Download the CSV and install analysis packages **in the runtime**.
3. Loop over analysis steps: LLM → code → `run_code` → feed output back until the step completes (up to five LLM rounds per step).
4. Download generated charts into a local `./charts` folder.

## 5. Dataset and outputs

| Item            | Detail                                                                                                |
| --------------- | ----------------------------------------------------------------------------------------------------- |
| **Dataset**     | [Seaborn diamonds](https://github.com/mwaskom/seaborn-data) — price, carat, cut, color, clarity, etc. |
| **Remote path** | `/workspace/diamonds.csv`                                                                             |
| **Charts**      | e.g. `price_by_cut.png`, `carat_vs_price.png`, `price_by_color_clarity.png` under `/workspace/charts` |

## 6. Configuration reference

| Variable               | Required | Default                     | Description               |
| ---------------------- | -------- | --------------------------- | ------------------------- |
| `OPENAI_API_KEY`       | Yes      | —                           | Provider API key          |
| `GRAVIXLAYER_API_KEY`  | Yes      | —                           | Gravix Layer key          |
| `OPENAI_API_BASE_URL`  | No       | `https://api.openai.com/v1` | Compatible API base       |
| `OPENAI_MODEL`         | No       | `gpt-4o`                    | Model name                |
| `GRAVIXLAYER_TEMPLATE` | No       | `python-3.14-base-medium`   | Runtime template          |
| `GRAVIXLAYER_TIMEOUT`  | No       | `600`                       | Runtime timeout (seconds) |

## 7. Core pattern (simplified)

The example wraps execution like this (conceptually):

```python theme={null}
from gravixlayer.types.runtime import Runtime

# Runtime is already created via Runtime.create(...) in the script
def execute_code_in_runtime(runtime: Runtime, code: str) -> tuple[str, float]:
    result = runtime.run_code(code)
    # Combine stdout / stderr for the LLM
    ...
```

The LLM is prompted so each code block **re-imports libraries and reloads the CSV** (execution cells are isolated unless you use a persistent [code context](/documentation/agentruntime/code-execution/create-context)).

## Next steps

* Read the **[README in the repo](https://github.com/gravixlayer/gravixlayer-python/blob/main/examples/agents/python/data-analyst-agent/README.md)** for the step-by-step analysis table and project layout.
* Explore **[Agent Runtime](/documentation/agentruntime/overview)** and **[run Python](/documentation/agentruntime/code-execution/run-python)** in the docs.
* Swap prompts or datasets by editing `ANALYSIS_STEPS` and `DATASET_URL` in `data_analyst_agent.py`.
