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

# Build a Stateful Code Execution Agent with LangGraph

> Build a LangGraph agent that provisions isolated Gravix Layer runtimes, executes AI-generated Python securely, downloads generated artifacts, and automatically cleans up resources.

# Overview

In this guide you'll build a stateful LangGraph agent powered by Groq and Gravix Layer.

The workflow:

* Creates an isolated runtime
* Generates Python using Groq
* Installs required packages
* Executes the generated code
* Downloads generated files
* Cleans up automatically

By the end you'll have a reusable foundation for building coding agents, data analysis agents, research assistants and autonomous developer tools.

***

## Architecture

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
                 User Prompt
                      │
                      ▼
             LangGraph StateGraph
                      │
        ┌─────────────┴─────────────┐
        ▼                           ▼
 Create Runtime              Generate Code
        │                           │
        └─────────────┬─────────────┘
                      ▼
             Install Packages
                      │
                      ▼
               Execute Python
                      │
          ┌───────────┴────────────┐
          ▼                        ▼
    Download Files            Execution Logs
          │
          ▼
     Cleanup Runtime
```

***

# Prerequisites

* Gravix Layer API Key
* Groq API Key
* Python 3.11+

***

# Install

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install gravixlayer
pip install langgraph
pip install langchain
pip install langchain-groq
pip install python-dotenv
```

***

# Environment

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
GRAVIXLAYER_API_KEY=xxxxxxxxxxxx

GROQ_API_KEY=xxxxxxxxxxxx
```

***

# Project Structure

```
langgraph-agent/

├── main.py
├── graph.py
├── nodes.py
├── state.py
├── requirements.txt
└── .env
```

***

# Define the Agent State

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# state.py
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from typing import TypedDict

class AgentState(TypedDict):

    prompt: str

    runtime: object

    context_id: str

    generated_code: str

    stdout: str

    success: bool
```

***

# Create the Runtime

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# nodes.py
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from gravixlayer import GravixLayer

client = GravixLayer()

def create_runtime(state):

    runtime = client.runtime.create(
        template="base-small"
    )

    ctx = client.runtime.create_context(
        runtime.runtime_id
    )

    state["runtime"] = runtime
    state["context_id"] = ctx.context_id

    return state
```

***

# Initialize Groq

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_groq import ChatGroq

llm = ChatGroq(
    model="llama-3.3-70b-versatile",
    temperature=0
)
```

***

# Generate Python

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
SYSTEM_PROMPT = """
You are an expert Python developer.

Return only executable Python.

Do not return markdown.

Every generated file must be saved inside

/workspace
"""
```

````python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import re

def planner(state):

    response = llm.invoke([
        ("system", SYSTEM_PROMPT),
        ("human", state["prompt"])
    ])

    code = response.content.strip()

    code = re.sub(
        r"^```(?:python)?",
        "",
        code
    )

    code = re.sub(
        r"```$",
        "",
        code
    )

    state["generated_code"] = code.strip()

    return state
````

***

# Install Dependencies

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
def install(state):

    runtime = state["runtime"]

    runtime.run_cmd(
        command="pip",
        args=[
            "install",
            "pandas",
            "matplotlib",
            "seaborn",
            "scikit-learn",
            "-q"
        ]
    )

    return state
```

***

# Execute Code

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
def execute(state):

    result = client.runtime.run_code(
        state["runtime"].runtime_id,
        code=state["generated_code"],
        context_id=state["context_id"]
    )

    state["success"] = result.success

    if result.success:

        state["stdout"] = result.text

        image = state["runtime"].file.download_file(
            "/workspace/iris.png"
        )

        with open("iris.png","wb") as f:
            f.write(image)

    else:

        state["stdout"] = str(result.error)

    return state
```

***

# Cleanup

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
def cleanup(state):

    state["runtime"].kill()

    return state
```

***

# Build the Graph

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langgraph.graph import StateGraph

builder = StateGraph(AgentState)

builder.add_node(
    "runtime",
    create_runtime
)

builder.add_node(
    "planner",
    planner
)

builder.add_node(
    "install",
    install
)

builder.add_node(
    "execute",
    execute
)

builder.add_node(
    "cleanup",
    cleanup
)

builder.set_entry_point("runtime")

builder.add_edge(
    "runtime",
    "planner"
)

builder.add_edge(
    "planner",
    "install"
)

builder.add_edge(
    "install",
    "execute"
)

builder.add_edge(
    "execute",
    "cleanup"
)

graph = builder.compile()
```

***

# Run the Agent

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
initial_state = {

    "prompt": """

Download the Iris dataset.

Display summary statistics.

Generate a histogram.

Save it as iris.png.

"""

}

for event in graph.stream(initial_state):
    print(event)
```

***

# Output

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Runtime Created

Python Generated

Dependencies Installed

Execution Successful

Downloaded:
/workspace/iris.png

Runtime Destroyed
```

***

# What You Built

* Stateful LangGraph workflow
* Isolated Gravix Layer runtime
* Persistent execution context
* Remote package installation
* Secure Python execution
* Automatic artifact download
* Automatic runtime cleanup

***

# Next Steps

* Build a multi-agent workflow
* Execute JavaScript instead of Python
* Clone repositories inside the runtime
* Build autonomous coding agents
* Add retry and validation nodes
