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

# LangGraph + Declaw

> Build a LangGraph ReAct agent that executes Python code in a Declaw sandbox. Define a @tool with langchain_core, wire it into create_react_agent, and run it with or without an OpenAI key.

## What You'll Learn

* Defining a `@tool` with `langchain_core.tools` that executes Python in a Declaw sandbox
* Creating a LangGraph ReAct agent with `create_react_agent`
* Demo mode that exercises the sandbox tool directly without needing an OpenAI key

## Prerequisites

* Declaw instance running and `DECLAW_API_KEY` / `DECLAW_DOMAIN` set
* `OPENAI_API_KEY` (optional — the example runs in demo mode without it)

```bash theme={null}
pip install declaw python-dotenv langgraph langchain-openai
```

<Note>This example is available in Python. TypeScript support coming soon.</Note>

## Code Walkthrough

### 1. Define the Declaw sandbox tool

Wrap `Sandbox.create()` in a LangChain `@tool`. The agent receives the function's docstring as the tool description, so make it clear:

```python theme={null}
from langchain_core.tools import tool
from declaw import Sandbox

@tool
def execute_python(code: str) -> str:
    """Execute Python code in a secure Declaw sandbox."""
    sbx = Sandbox.create(template="python", timeout=300)
    try:
        sbx.files.write("/tmp/code.py", code)
        result = sbx.commands.run("python3 /tmp/code.py", timeout=30)
        return (
            f"stdout: {result.stdout}\n"
            f"stderr: {result.stderr}\n"
            f"exit_code: {result.exit_code}"
        )
    finally:
        sbx.kill()
```

Each call to `execute_python` spins up a fresh sandbox, runs the code, and destroys the sandbox. Sandboxes are fully isolated — code from one call cannot affect another.

### 2. Create a LangGraph ReAct agent

```python theme={null}
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
agent = create_react_agent(llm, [execute_python])
```

### 3. Run the agent

```python theme={null}
prompt = "Write Python code to compute the first 10 Fibonacci numbers and print them."
result = agent.invoke({"messages": [("user", prompt)]})

for msg in result["messages"]:
    role = getattr(msg, "type", "unknown")
    content = getattr(msg, "content", "")
    if content:
        print(f"\n[{role}] {content}")
```

The agent will reason about the task, call `execute_python` with the generated code, receive the sandbox output, and formulate a final answer.

### 4. Demo mode (no API key needed)

Run the sandbox tool directly without the LangGraph agent:

```python theme={null}
from declaw import Sandbox

code = """\
a, b = 0, 1
fibs = []
for _ in range(10):
    fibs.append(a)
    a, b = b, a + b
print("Fibonacci:", fibs)
"""

sbx = Sandbox.create(template="python", timeout=300)
try:
    sbx.files.write("/tmp/code.py", code)
    result = sbx.commands.run("python3 /tmp/code.py", timeout=30)
    print(result.stdout)
finally:
    sbx.kill()
```

## Expected Output

In demo mode:

```
=======================================================
LangGraph + Declaw Sandbox Example
=======================================================
No OPENAI_API_KEY found -- running demo mode.

--- Tool Definition ---
from langchain_core.tools import tool
from declaw import Sandbox

@tool
def execute_python(code: str) -> str:
    """Execute Python code in a secure Declaw sandbox."""
    ...

--- Running Code Directly in Declaw Sandbox ---
Code:
a, b = 0, 1
fibs = []
...

stdout: Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
stderr:
exit_code: 0

Sandbox cleaned up.

=======================================================
Done!
=======================================================
```
