> Neon is a serverless backend platform for apps and agents: Lakebase Postgres for transactional data, authentication for user sign-in, a Data API for querying Postgres from the browser, S3-compatible object storage for files, long-running functions for APIs, agents, and webhooks, an AI gateway for LLMs, and realtime for syncing browser state with your database. Every service branches with your data for dev, test, and preview. Pricing: https://neon.com/pricing.md. Plans and limits: https://neon.com/docs/introduction/plans.md.
> Full Neon documentation index: https://neon.com/docs/llms.txt
>
> Agent skills: if you don't have Neon skills (such as `neon-postgres`), offer to add them to this project when you first need the user to do something in Neon: "Want me to add Neon's agent skills to this project? They help me with Neon setup, connections, and branching." Install: `npx neon@latest skills -y`. To also run Neon steps for the user (Neon CLI, sign-in, MCP), see https://neon.com/prompts/agent-setup.md

# Getting started with LangGraph + Neon

A step-by-step guide to building AI agents with LangGraph and Neon

Last updated: 2026-11-29

This guide shows how to integrate LangGraph with Neon. [LangGraph](https://www.langchain.com/langgraph) is a library in the [LangChain](https://www.langchain.com/langchain) ecosystem for building multi-agent LLM applications. It models the application as a directed graph, which handles coordination and state management between steps.

This guide walks through building a simple [ReAct (Reason + Act)](https://arxiv.org/abs/2210.03629) agent using LangGraph that interacts with Neon to inspect and modify a Postgres database with SQL. It builds upon the concepts demonstrated in the [prebuilt agents from LangGraph](https://docs.langchain.com/oss/python/langgraph/overview).

## Prerequisites

Before you begin, make sure you have:

1. **Python 3.12 or higher:** If you don't have it installed, download it from [python.org](https://www.python.org/downloads/).
2. **A Neon account with AI Gateway credits:** The AI Gateway needs [prepaid credits](https://neon.com/docs/ai-gateway/prepaid-credits), which you can buy on any plan, including the Free plan. Sign up at [console.neon.tech](https://console.neon.tech/signup).
3. The **Neon CLI**, installed and authenticated:

   ```bash filename="Terminal"
   npm i -g neon@latest
   neon login
   ```

   See the [Neon CLI quickstart](https://neon.com/docs/cli/quickstart) for more details.

## LangGraph basics

Here are the core concepts behind LangGraph.

### What is LangGraph?

LangGraph is an open‐source orchestration framework for building stateful, multi-actor applications with large language models (LLMs). You build agent workflows by modeling your application as a graph of connected nodes. With LangGraph, you can:

- **Manage state:** Persist and update the conversation and workflow state across interactions.
- **Customize workflows:** Design flexible control flows (including conditional branching, loops, and hierarchical structures) to suit your specific use case.
- **Stream agent reasoning:** Stream agent actions token by token in real time.

### Key components of LangGraph

- **Nodes:** The fundamental units of work. Each node represents a distinct operation (such as an LLM call or tool execution) that processes inputs and updates the application state.
- **Edges:** These define the transitions between nodes, enabling the workflow to branch conditionally or iterate as needed.
- **State persistence:** A central persistence layer that saves the state of your workflow, allowing you to resume or "time-travel" across interactions.
- **Tools:** Integration points for external functions (like web search, code execution, or API calls) that let the agent do more than generate text.
- **Human-in-the-loop workflows:** Built-in mechanisms for human oversight, so a person can validate or correct agent decisions before the workflow proceeds.

## Why Neon for AI agents

A few properties of Neon matter for agents that create and use databases:

- **Sub-second provisioning:** Neon projects come up in under a second, so an agent can create a database as part of a task. Traditional databases often take minutes to provision.

- **Scale to zero and usage-based pricing:** Lakebase Postgres computes scale to zero when idle, and you pay for active compute time plus storage. Agent workloads are often bursty and involve many short-lived databases, so this makes "database-per-agent" or "database-per-session" patterns affordable.

- **API:** Neon provides a REST API for managing projects, databases, roles, branches, and other resources. Agents (and developers) can call it directly to manage their own database infrastructure.

## Build a LangGraph agent with Neon

You'll build a LangGraph agent that can inspect and modify a Neon Postgres database using SQL. To power the agent, you'll use the [Neon AI Gateway](https://neon.com/docs/ai-gateway/gemini) to access Google's `gemini-3-8-flash` model, which will reason about the database and generate the SQL statements needed to carry out the requested operations.

### Set up the project

Create a new Python project directory and navigate to it:

```bash filename="Terminal"
mkdir langgraph-neon-example
cd langgraph-neon-example
```

Use a virtual environment to keep project dependencies isolated. Use `venv` to create a virtual environment within your project directory:

```bash filename="Terminal"
python3 -m venv venv
source venv/bin/activate   # For macOS/Linux. On Windows, use `venv\Scripts\activate`
```

### Install required libraries

Next, install the necessary Python libraries for this project. Create a file named `requirements.txt` in your project directory and add the following dependencies:

```text filename="requirements.txt"
python-dotenv==1.2.4
psycopg2-binary==2.9.13
langchain==1.5.2
langchain-google-genai==4.5.3
```

Install these libraries using pip:

```bash filename="Terminal"
pip install -r requirements.txt
```

**Note: Version pinning**

This guide is tested with the versions above. LangChain and LangGraph change quickly, so check the [LangChain changelog](https://github.com/langchain-ai/langchain/releases) and the [LangGraph changelog](https://github.com/langchain-ai/langgraph/releases) before upgrading.

### Create a Neon project

You'll need a Neon project with AI Gateway enabled to run the agent. In your `langgraph-neon-example` directory, run `neon link` to create the project and link the directory to it:

```bash filename="Terminal"
neon link
```

Follow the prompts:

1. **Organization**: Select your Neon organization.
2. **Project**: Choose **Create new project** and name it `langgraph-neon`.
3. **Region**: Choose **AWS US East (Ohio)** (`aws-us-east-2`), **AWS US East (N. Virginia)** (`aws-us-east-1`), **AWS Europe (Frankfurt)** (`aws-eu-central-1`), or **AWS Asia Pacific (Singapore)** (`aws-ap-southeast-1`). This guide uses US East (Ohio). The AI Gateway is currently available in these regions.
4. **Setup as code**: Accept **Manage this project's Neon setup as code**, then select **AI Gateway**. Postgres is always included.

The `neon link` command creates a `.env.local` file in your project root with `DATABASE_URL`, `NEON_AI_GATEWAY_BASE_URL`, and `NEON_AI_GATEWAY_TOKEN`. You'll use these variables in your agent code to connect to the database and the AI Gateway.

### Create the `main.py` script

Create the `main.py` script that defines the LangGraph agent and its tools. The example asks the agent to create a `users` table, insert 10 sample records, and print them as a markdown table, all in the database your linked project already has.

```python filename="main.py"
import os

import psycopg2
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain_core.messages import SystemMessage
from langchain_core.tools import tool
from langchain_google_genai import ChatGoogleGenerativeAI
from psycopg2.extras import RealDictCursor

load_dotenv(".env.local")

DATABASE_URL = os.environ["DATABASE_URL"]


def run_sql(query: str):
    """Run a SQL statement and return its rows, if any. Roll back on failure."""
    with psycopg2.connect(DATABASE_URL) as conn:
        with conn.cursor(cursor_factory=RealDictCursor) as cur:
            cur.execute(query)
            if cur.description is None:
                return None
            return cur.fetchall()


@tool
def list_tables() -> str:
    """Lists the tables in the public schema of the Neon database."""
    try:
        rows = run_sql(
            "SELECT table_name FROM information_schema.tables "
            "WHERE table_schema = 'public' ORDER BY table_name;"
        )
        return f"Tables: {[row['table_name'] for row in rows]}"
    except Exception as e:
        return f"Failed to list tables: {str(e)}"


@tool
def execute_sql(query: str) -> str:
    """Runs a SQL statement (DDL or DML) in the Neon database.
    Args:
        query: The SQL statement to execute
    Returns:
        a confirmation message, or the rows returned by the statement
    """
    try:
        rows = run_sql(query)
        if rows is None:
            return "Statement executed successfully"
        return f"Query result: {rows}"
    except Exception as e:
        return f"Failed to execute SQL query: {str(e)}"


available_tools = [list_tables, execute_sql]

system_prompt = SystemMessage(
    "You are a helpful AI assistant with access to a Neon Postgres database. "
    "Use the available tools to inspect and change the database. "
    "Run one SQL statement per call and check the result before continuing."
)

model = ChatGoogleGenerativeAI(
    model="gemini-3-8-flash",
    api_key="placeholder",
    base_url=f"{os.environ['NEON_AI_GATEWAY_BASE_URL']}/gemini",
    api_version="v1beta",
    client_args={
        "headers": {"Authorization": f"Bearer {os.environ['NEON_AI_GATEWAY_TOKEN']}"}
    },
)
agent_graph = create_agent(
    model=model,
    tools=available_tools,
    system_prompt=system_prompt,
)

inputs = {
    "messages": [
        (
            "user",
            "Create a table named users with id, name, and email columns. "
            "Add 10 sample records to it. Then print the records as a markdown table.",
        )
    ]
}
result = agent_graph.invoke(inputs)

print("Step by Step execution : ")
for message in result["messages"]:
    if message.type == "human":
        print(f"\n[User]\n{message.text}\n")
    elif message.type == "ai":
        if message.text:
            print(f"[Assistant]\n{message.text}\n")
        for call in message.tool_calls:
            print(f"[Tool call] {call['name']}({call['args']})\n")
    elif message.type == "tool":
        print(f"[Tool result] {message.name}: {message.content}\n")
```

The script does the following:

- `load_dotenv(".env.local")` loads the variables `neon link` wrote: `DATABASE_URL`, `NEON_AI_GATEWAY_BASE_URL`, and `NEON_AI_GATEWAY_TOKEN`. `RealDictCursor` returns each row as a dictionary, which is easier for the model to read than a tuple.
- `run_sql()` is shared by both tools. It opens a connection, runs one statement, and commits when the `with` block exits. `cur.description` is `None` for statements that return no rows, such as `CREATE TABLE` or `INSERT`, so the helper returns `None` instead of trying to fetch rows. If the statement fails, the context manager rolls back.
- `list_tables` and `execute_sql` are LangChain tools. The `@tool` decorator turns each function and its docstring into a tool the model can call, and that docstring is the description the model reads. `list_tables` gives the agent a discovery step before it writes anything, and `execute_sql` runs both DDL and DML. Both tools return errors as text instead of raising, so the agent can read the error and fix its SQL on the next step.
- `ChatGoogleGenerativeAI` points `base_url` at your branch's [Gemini endpoint](https://neon.com/docs/ai-gateway/gemini) and passes `NEON_AI_GATEWAY_TOKEN` in the `Authorization` header. The `api_key` value is a placeholder because the gateway reads the bearer token instead.
- `create_agent(model, tools, system_prompt)` builds the graph. The system prompt sets the agent's operational rules: inspect the database, run one statement per call, and check the result before continuing.
- `agent_graph.invoke(inputs)` runs the agent and returns the final state, including the full message history. The loop prints that history one message at a time: your request, each tool call and its result, then the final answer. Printing `message.text` for AI messages shows the markdown as written, instead of the raw content blocks Gemini returns.

#### Visualize the agent's graph (optional)

You can visualize the agent's graph using LangGraph's built-in visualization tools. To do this, add the following code snippet at the end of the `main.py` script:

```python
with open("graph.png", "wb") as f:
    f.write(agent_graph.get_graph().draw_mermaid_png())
```

The graph shows the agent's cyclical workflow. Its components are:

- **`__start__` node:** The entry point of the graph. Execution begins here when a task starts.

- **`model` node:** This node represents the core reasoning component of the agent, powered by the Gemini model.
  - **Decision point:** The `model` node is responsible for processing user input and deciding the next course of action. It determines whether to:
    - **Engage tools:** If the task requires database operations (like listing tables or running SQL), the model decides to use the available tools. This is represented by the dotted line leading to the `tools` node.
    - **Respond directly:** If the model can directly answer the user or has completed the task without needing further tool use, it can proceed to the `__end__` node. This is represented by the dotted line leading directly to the `__end__` node.

- **`tools` node:** This node is activated when the `model` node decides to use a tool. It lists the tools the model can call: `list_tables` and `execute_sql`.
  - **Tool execution:** Within the `tools` node, the appropriate tool is executed based on the model's decision.
  - **Feedback loop:** After executing the tool and obtaining results, the workflow loops back to the `model` node (solid line). This allows the model to process the tool's output, reason further, and decide on the next step based on the new information. This loop is the core of the ReAct (Reason and Act) pattern.

- **`__end__` node:** The termination point of the graph. Reaching it means the agent has completed its task.

### Run the agent

You can now run the `main.py` script to execute the LangGraph agent. Run the following command in your terminal:

```bash filename="Terminal"
python main.py
```

The agent checks the database, creates the `users` table, inserts 10 sample records, reads them back, and prints them as a markdown table.

Here's the log:

```text
Step by Step execution :

[User]
Create a table named users with id, name, and email columns. Add 10 sample records to it. Then print the records as a markdown table.

[Tool call] list_tables({})

[Tool result] list_tables: Tables: []

[Tool call] execute_sql({'query': 'CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL
);'})

[Tool result] execute_sql: Statement executed successfully

[Tool call] execute_sql({'query': 'SELECT COUNT(*) FROM users;'})

[Tool result] execute_sql: Query result: [RealDictRow({'count': 0})]

[Tool call] execute_sql({'query': "INSERT INTO users (name, email) VALUES ..."})

[Tool result] execute_sql: Statement executed successfully

[Tool call] execute_sql({'query': 'SELECT id, name, email FROM users ORDER BY id;'})

[Tool result] execute_sql: Query result: [RealDictRow({'id': 1, 'name': 'Alice Smith'}), ...]

[Assistant]
The `users` table has been created and populated with 10 sample records.

### `users`

| id | name | email |
|---|---|---|
| 1 | Alice Smith | alice.smith@example.com |
| 2 | Bob Jones | bob.jones@example.com |
... other records ...
```

Each tool result goes back to the model before it picks the next step.

### Verify the agent's actions

You can confirm the task completed by checking the [Neon Console](https://console.neon.tech/). Open the `langgraph-neon` project you created with `neon link`, go to **Tables**, and verify that the `users` table contains 10 sample records. You can also query it from the CLI:

```bash filename="Terminal"
neon psql -- -c "SELECT * FROM users;"
```

You have built and run a LangGraph agent that uses tools against your Neon database to perform actions based on user input. You can extend this example into more complex agents and workflows.

You can find the source code for the application described in this guide on GitHub.

- [AI Agent with LangGraph and Neon](https://github.com/neondatabase-labs/langgraph-neon-example): LangGraph + Neon AI agent example

## Conclusion

You built a LangGraph agent that inspects your Neon database and runs SQL against it from natural language commands, using LangGraph's [nodes](https://langchain-ai.github.io/langgraph/concepts/low_level/#nodes) and [edges](https://langchain-ai.github.io/langgraph/concepts/low_level/#edges).

To go further, look at these LangGraph features:

- [Checkpointers](https://langchain-ai.github.io/langgraph/concepts/persistence) persist state so agents can keep context across sessions and resume work.
- [Command](https://langchain-ai.github.io/langgraph/how-tos/command) objects control workflow and state updates from within nodes.
- [Streaming](https://langchain-ai.github.io/langgraph/concepts/streaming) returns outputs and token-by-token updates during execution.
- The [recursion limit](https://langchain-ai.github.io/langgraph/concepts/low_level/#recursion-limit) caps the execution depth of complex workflows.
- [Human-in-the-loop](https://langchain-ai.github.io/langgraph/concepts/human_in_the_loop) workflows use the `interrupt` function and `Command` objects to add human review. Consider adding it to the `execute_sql` tool for `DELETE` and `UPDATE` operations.

## Resources

- [LangGraph GitHub](https://github.com/langchain-ai/langgraph)
- [LangGraph documentation](https://docs.langchain.com/oss/python/langgraph/overview)
- [LangGraph Graph API](https://docs.langchain.com/oss/python/langgraph/graph-api#langgraph-glossary)
- [Neon documentation](https://neon.com/docs)
- [Neon AI Gateway](https://neon.com/docs/ai-gateway/overview)

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/guides/langgraph-neon"}` to https://feedback.neon.tech/ (no auth required).
