# Tutorial: build a read-only SQL data agent with LangChain 1.5 and test it without an LLM

A step-by-step tutorial: three SQL tools, a read-only database connection, call limits as middleware, a scripted model that replays a real agent trajectory, and four tests that run in under a second. Then swap in a real model and turn on tracing.

"How much did we sell in Turkey last month?" is the question every data team hears, and it is a natural first agent. The agent has to look at the schema, write SQL, read errors, fix its query and turn rows into a sentence. It is also a good place to learn agent safety, because a careless SQL tool can delete a table.

This tutorial builds that agent step by step with LangChain 1.5.2 and LangGraph 1.2.24 on Python 3.13. Every piece of code below was run as written. You do not need an API key: the agent is driven first by a scripted model that replays a realistic trajectory, including one failed query. That lets you write fast, repeatable tests for the parts you control: the tools, the safety limits and the order of steps. At the end you swap in a real model and turn on [LangSmith](/tools/langsmith) tracing.

## What happened

### LangChain 1.5.0 moves to Python 3.11 and adds decision middleware (11 November 2026)

The LangChain changelog says `langchain` 1.5 and `langchain-core` 1.8 drop Python 3.10 support. The release adds a Decisions API in `langchain_core.decisions` and two beta middlewares, `ModelRouterMiddleware` and `AutoModeMiddleware`, which now need an explicit `classifier=`. The call-limit middlewares used in this tutorial are unchanged built-ins.

### LangChain 1.5.2 and LangGraph 1.2.24 reach PyPI (18 and 20 November 2026)

PyPI lists `langchain` 1.5.2 on 18 November and `langgraph` 1.2.24 on 20 November. This tutorial pins `langchain` 1.5.2, which installed `langchain-core` 1.8.4 and `langgraph` 1.2.24.

## Build the database and the tools

The finished agent has five parts:

| Part | File | What it does |
|---|---|---|
| Sample database | `make_db.py` | Creates `shop.db` with customers and orders |
| Tools | `tools.py` | `list_tables`, `describe_table`, `run_sql`, all read-only |
| Agent | `agent.py` | `create_agent` with a system prompt and two limit middlewares |
| Scripted model | `scripted_model.py` | Replays fixed model messages so runs are deterministic |
| Tests | `test_agent.py` | Four pytest tests: safety, trajectory, answer, runaway loop |

The design idea is simple. A good kitchen gives a new cook sharp knives but keeps the knife block bolted to the counter. Here the model gets real SQL power, but the database connection itself refuses writes, and middleware caps how many times the model can try.

### Step 1: install and create a sample database

Create a virtual environment and install the two packages. LangChain 1.5 requires Python 3.11 or later.

```bash
python -m venv .venv && source .venv/bin/activate
pip install "langchain==1.5.2" pytest
```

Now create a small shop database:

```python
# make_db.py
import sqlite3

def make_db(path="shop.db"):
    con = sqlite3.connect(path)
    con.executescript("""
    DROP TABLE IF EXISTS orders;
    DROP TABLE IF EXISTS customers;
    CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, country TEXT);
    CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, month TEXT, amount REAL);
    INSERT INTO customers VALUES (1,'Ada','TR'),(2,'Bo','US'),(3,'Cem','TR'),(4,'Dee','DE');
    INSERT INTO orders VALUES
      (1,1,'2026-10',120.0),(2,1,'2026-11',80.0),(3,2,'2026-11',200.0),
      (4,3,'2026-11',45.5),(5,3,'2026-11',54.5),(6,4,'2026-10',300.0);
    """)
    con.commit(); con.close()
    return path

if __name__ == "__main__":
    print(make_db())
```

Work out the expected answer by hand first, so you can check the agent later. November orders are 80.0 (Ada, TR), 200.0 (Bo, US), 45.5 and 54.5 (Cem, TR). So TR is 80.0 + 45.5 + 54.5 = 180.0, US is 200.0, and DE has no November orders.

### Step 2: write three read-only tools

An agent sees a tool as a name, a description and an argument schema. The `@tool` decorator builds all three from the function signature and docstring, so the docstring is part of the prompt. (See [function calling](/tools/function-calling) for how models choose tools.)

```python
# tools.py
import re, sqlite3
from langchain.tools import tool

DB_PATH = "shop.db"
MAX_ROWS = 50

def _connect():
    # mode=ro: SQLite itself refuses writes, whatever the SQL says
    return sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)

@tool
def list_tables() -> str:
    """List the tables in the shop database."""
    with _connect() as con:
        rows = con.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").fetchall()
    return ", ".join(r[0] for r in rows)

@tool
def describe_table(table: str) -> str:
    """Show the columns and types of one table."""
    if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", table):
        return "ERROR: invalid table name"
    with _connect() as con:
        cols = con.execute(f"PRAGMA table_info({table})").fetchall()
    if not cols:
        return f"ERROR: no table named {table}"
    return "; ".join(f"{c[1]} {c[2]}" for c in cols)

@tool
def run_sql(query: str) -> str:
    """Run one read-only SELECT query and return up to 50 rows as text."""
    q = query.strip().rstrip(";")
    if not q.lower().startswith(("select", "with")) or ";" in q:
        return "ERROR: only a single SELECT statement is allowed"
    try:
        with _connect() as con:
            cur = con.execute(q)
            header = [d[0] for d in cur.description]
            rows = cur.fetchmany(MAX_ROWS + 1)
    except sqlite3.Error as e:
        return f"ERROR: {e}"   # the model sees the error and can fix its query
    more = len(rows) > MAX_ROWS
    lines = [" | ".join(header)] + [" | ".join(str(v) for v in r) for r in rows[:MAX_ROWS]]
    return "\n".join(lines) + ("\n(truncated)" if more else "")
```

Three design choices matter here.

**Two locks, not one.** The prefix check rejects anything that does not start with `SELECT` or `WITH` and anything with a second statement. But a prefix check alone is weak. The query `WITH x AS (SELECT 1) DELETE FROM orders` starts with `WITH` and passes it. The second lock catches it: opening SQLite with the URI `file:shop.db?mode=ro` makes the database read-only at the engine level. Running that sneaky query returns:

```text
ERROR: attempt to write a readonly database
```

One caveat from the SQLite documentation: the `mode=ro` setting is not carried over to databases added later with `ATTACH`. Our prefix check already rejects an `ATTACH` statement, but keep it in mind if you loosen the check. For a production warehouse, the stronger version of the second lock is a database user that only has `SELECT` grants.

**Errors are returned, not raised.** When the model writes bad SQL, `run_sql` returns the SQLite error as text. The model reads it on the next step and fixes the query. Raising an exception would end the run instead of teaching the model.

**Output is capped.** `fetchmany(MAX_ROWS + 1)` reads at most 51 rows, returns 50 and marks the result as truncated. A `SELECT *` on a large table would otherwise fill the context window and the bill. The [agent loop token cost simulation](/ai-simulations/agent-loop-token-cost) shows how fast tool output grows the prompt on every later step.

## Build the agent and drive it with a scripted model

### Step 3: build the agent with limits

`create_agent` builds a [LangGraph](/tools/langgraph) graph that runs the standard loop: call the model, run any tool calls it asked for, feed the results back, repeat until the model answers without tool calls. This is the [ReAct loop](/tools/react-loop); you can step through it in the [ReAct tool calling simulation](/ai-simulations/react-tool-calling).

```python
# agent.py
from langchain.agents import create_agent
from langchain.agents.middleware import ModelCallLimitMiddleware, ToolCallLimitMiddleware
from tools import list_tables, describe_table, run_sql

SYSTEM = """You answer questions about the shop database.
Always look at the schema before writing SQL. Use only SELECT.
If a query fails, read the error, fix the query and try again.
Answer in one or two sentences and quote the numbers you got."""

def build_agent(model):
    return create_agent(
        model,
        tools=[list_tables, describe_table, run_sql],
        system_prompt=SYSTEM,
        middleware=[
            ModelCallLimitMiddleware(run_limit=8),          # at most 8 model calls per question
            ToolCallLimitMiddleware(tool_name="run_sql", run_limit=4),
        ],
    )
```

The two middlewares are the brakes. According to the LangChain docs:

- `ModelCallLimitMiddleware` counts model calls. `run_limit` applies to one invocation, `thread_limit` to a whole conversation (and needs a checkpointer). Its default `exit_behavior` is `"end"`, a graceful stop.
- `ToolCallLimitMiddleware` counts tool calls, for all tools or one named tool. Its default `exit_behavior` is `"continue"`: calls over the limit are blocked with an error message, and the model keeps running so it can decide to stop.

Why both? The tool limit stops the model from hammering the database. The model limit stops everything else, including a model that keeps calling a blocked tool. The site's guide to [LangChain 1.5 middleware](/articles/langchain-1-5-agent-middleware-guide) covers the other built-in middlewares.

### Step 4: drive the agent with a scripted model

To test the agent without an API, replace the model with one that replays a fixed list of messages. `langchain-core` ships `GenericFakeChatModel`, which returns messages from an iterator. `create_agent` calls `bind_tools` on the model to attach the tool schemas; a scripted model does not need them, so we override it to return itself.

```python
# scripted_model.py
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage

class ScriptedChatModel(GenericFakeChatModel):
    """Replays a fixed list of AIMessages. bind_tools is a no-op so create_agent accepts it."""
    def bind_tools(self, tools, **kwargs):
        return self

def call(name, args, id):
    return {"name": name, "args": args, "id": id, "type": "tool_call"}

SCRIPT = [
    AIMessage(content="", tool_calls=[call("list_tables", {}, "c1")]),
    AIMessage(content="", tool_calls=[call("describe_table", {"table": "orders"}, "c2"),
                                      call("describe_table", {"table": "customers"}, "c3")]),
    AIMessage(content="", tool_calls=[call("run_sql", {"query":
        "SELECT c.country, SUM(o.amont) AS revenue FROM orders o JOIN customers c "
        "ON c.id = o.customer_id WHERE o.month = '2026-11' GROUP BY c.country"}, "c4")]),
    AIMessage(content="", tool_calls=[call("run_sql", {"query":
        "SELECT c.country, SUM(o.amount) AS revenue FROM orders o JOIN customers c "
        "ON c.id = o.customer_id WHERE o.month = '2026-11' GROUP BY c.country ORDER BY revenue DESC"}, "c5")]),
    AIMessage(content="In November 2026, US customers spent 200.0 and TR customers spent 180.0. DE had no November orders."),
]

def scripted_model():
    return ScriptedChatModel(messages=iter(SCRIPT))
```

The script deliberately contains a typo, `o.amont`, on the first query. Real models make this kind of mistake, and the recovery path is exactly what you want to exercise. Think of the script as a flight simulator: the pilot's moves are fixed, so you can check that the aircraft, not the pilot, behaves correctly.

Now run it and print the trace:

```python
# run.py
from make_db import make_db
from scripted_model import scripted_model
from agent import build_agent

make_db()
agent = build_agent(scripted_model())
result = agent.invoke({"messages": [{"role": "user", "content": "Revenue by country in November 2026?"}]})
for m in result["messages"]:
    if m.type == "ai" and m.tool_calls:
        for tc in m.tool_calls:
            print(f"AI   -> {tc['name']}({tc['args']})")
    elif m.type == "tool":
        print(f"TOOL <- {m.name}: {m.content!r}")
    else:
        print(f"{m.type.upper():4} {m.content}")
```

Output (long queries shortened with "..."):

```text
HUMAN Revenue by country in November 2026?
AI   -> list_tables({})
TOOL <- list_tables: 'customers, orders'
AI   -> describe_table({'table': 'orders'})
AI   -> describe_table({'table': 'customers'})
TOOL <- describe_table: 'id INTEGER; customer_id INTEGER; month TEXT; amount REAL'
TOOL <- describe_table: 'id INTEGER; name TEXT; country TEXT'
AI   -> run_sql({'query': "SELECT c.country, SUM(o.amont) AS revenue ... GROUP BY c.country"})
TOOL <- run_sql: 'ERROR: no such column: o.amont'
AI   -> run_sql({'query': "SELECT c.country, SUM(o.amount) AS revenue ... ORDER BY revenue DESC"})
TOOL <- run_sql: 'country | revenue\nUS | 200.0\nTR | 180.0'
AI   In November 2026, US customers spent 200.0 and TR customers spent 180.0. DE had no November orders.
```

Read the trace as a story. Step 1 discovers tables. Step 2 runs two schema lookups in one model turn. Step 3 fails with a real SQLite error. Step 4 fixes the column name. Step 5 answers. The numbers match the hand calculation from Step 1: US 200.0, TR 180.0. That is five model calls, well within the limits. The [agent run simulation](/ai-simulations/agent-run) animates the same kind of trace.

## Test the agent without an LLM

### Step 5: write the tests

Four tests cover what you control. They use a fresh database per test via `tmp_path`, so they never touch your real file.

```python
# test_agent.py
import itertools
import pytest
from langchain_core.messages import AIMessage
from make_db import make_db
from tools import run_sql
from scripted_model import ScriptedChatModel, scripted_model, call
from agent import build_agent

@pytest.fixture(autouse=True)
def db(tmp_path, monkeypatch):
    import tools
    path = make_db(str(tmp_path / "shop.db"))
    monkeypatch.setattr(tools, "DB_PATH", path)

def ask(model, question="Revenue by country in November 2026?"):
    agent = build_agent(model)
    return agent.invoke({"messages": [{"role": "user", "content": question}]})["messages"]

def test_tools_reject_writes():
    assert run_sql.invoke({"query": "DELETE FROM orders"}).startswith("ERROR: only")
    # passes the prefix check, but the read-only connection still refuses it
    sneaky = "WITH x AS (SELECT 1) DELETE FROM orders"
    assert "readonly" in run_sql.invoke({"query": sneaky})
    assert run_sql.invoke({"query": "SELECT COUNT(*) AS n FROM orders"}) == "n\n6"

def test_trajectory_checks_schema_before_sql():
    msgs = ask(scripted_model())
    names = [tc["name"] for m in msgs if m.type == "ai" for tc in m.tool_calls]
    assert names.index("describe_table") < names.index("run_sql")
    assert names.count("run_sql") == 2            # one failure, one fix

def test_answer_matches_database():
    final = ask(scripted_model())[-1].content
    truth = run_sql.invoke({"query": "SELECT ROUND(SUM(amount),1) FROM orders o JOIN customers c "
                                     "ON c.id=o.customer_id WHERE month='2026-11' AND country='TR'"})
    assert truth.splitlines()[1] in final           # 180.0

def test_runaway_loop_is_stopped():
    loop = (AIMessage(content="", tool_calls=[call("run_sql", {"query": "SELECT 1"}, f"x{i}")])
            for i in itertools.count())
    msgs = ask(ScriptedChatModel(messages=loop))
    tool_msgs = [m for m in msgs if m.type == "tool"]
    executed = [m for m in tool_msgs if m.content == "1\n1"]
    blocked = [m for m in tool_msgs if m.content.startswith("Tool call limit exceeded")]
    assert len(executed) == 4                      # run_sql run_limit
    assert len(blocked) == 4                       # later calls are refused, not run
    assert msgs[-1].content.startswith("Model call limits exceeded")   # 8 calls, then stop
```

Run them:

```text
$ python -m pytest -q
....                                                                     [100%]
4 passed in 0.33s
```

The last test is the most instructive. It feeds the agent an endless stream of identical tool calls, the classic stuck agent. Here is what happened inside, counted from the message list:

| Model call | Tool result |
|---|---|
| 1 to 4 | `SELECT 1` runs and returns `1\n1` (header "1", then the value 1) |
| 5 to 8 | `Tool call limit exceeded. Do not call 'run_sql' again.` |
| After 8 | Run ends with `Model call limits exceeded: run limit (8/8)` |

So the database was hit exactly four times, and the whole run stopped after eight model calls instead of looping forever. Note that the final stop message is an extra AI message added by the middleware, so the message list holds nine AI messages for eight real model calls. I first wrote the test as "at most 8 AI messages" and it failed with `assert 9 <= 8`; reading the trace showed why. That is a good habit: when a test fails, print the messages before changing the code.

What these tests do not cover is whether a real model writes good SQL. That is an evaluation question, not a unit test, and the article on [agent evaluation with trajectories and judges](/articles/agent-evaluation-trajectories-judges-benchmarks) shows how to measure it.

## What it means in practice

The split between scripted tests and real-model runs is the main practical lesson. Unit tests check what you own: tool safety, limits and step order. Real-model runs check what you rent: the model's judgment. Keep them in separate suites.

### Step 6: swap in a real model and trace it

Because `build_agent` takes the model as an argument, moving to a real model is one line. `create_agent` accepts a `"provider:model"` string. For Anthropic, install the integration and set your key:

```bash
pip install langchain-anthropic
export ANTHROPIC_API_KEY=...
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=...
```

```python
from make_db import make_db
from agent import build_agent

make_db()
agent = build_agent("anthropic:claude-sonnet-5-5")
out = agent.invoke({"messages": [{"role": "user", "content": "Which country spent most in October 2026?"}]})
print(out["messages"][-1].content)
```

With `LANGSMITH_TRACING=true` and an API key set, each run appears in LangSmith as a tree: the agent graph at the top, model calls and tool calls underneath, with inputs, outputs, tokens and latency. If the real model skips `describe_table` and guesses column names, tighten the system prompt or make `run_sql` return the schema along with any "no such column" error.

From October 2026 data, the right answer is DE with 300.0 (against TR's 120.0). Add that question and answer to a small evaluation set, and run it against every prompt or model change.

## What to do now

1. **Pin your versions.** Install `langchain==1.5.2` on Python 3.11 or later, and record the resolved `langchain-core` and `langgraph` versions.
2. **Lock the database twice.** Keep the cheap SQL text check, and add an engine-level guarantee: a read-only connection or a database user with only `SELECT` rights.
3. **Return errors as tool results.** Let the model read SQLite or warehouse errors and fix its own query.
4. **Cap tool output.** Limit rows and characters so one wide query cannot flood the context.
5. **Set both limits.** Use `ToolCallLimitMiddleware` for expensive tools and `ModelCallLimitMiddleware` for the whole run; add `thread_limit` once you use a checkpointer.
6. **Test with a scripted model.** Replay realistic trajectories, including failures, and assert on step order, final numbers and runaway handling.
7. **Evaluate real models separately.** Keep a small set of questions with hand-checked answers, such as October's DE at 300.0, and rerun it on every prompt or model change.
8. **Gate anything that leaves the building.** If you add export or email tools, require [human-in-the-loop](/tools/human-in-the-loop) approval. The [text-to-SQL](/tools/text-to-sql) page covers schema linking and query validation in more depth.

## Risks and open questions

**A SELECT can still hurt.** Read-only does not mean cheap. A cross join on large tables can run for minutes, so set a statement timeout on the database side.

**Sensitive columns leak through schema tools.** `describe_table` shows every column. Hide personal data columns, or the model will happily select them.

**Scripted tests can drift from reality.** A script encodes how you think the model behaves. Refresh scripts from real traces now and then, so tests keep exercising the paths real models take.

**Prompt injection through data.** Text stored in the database is returned to the model as tool output. A row containing instructions could steer the next step, which is one more reason to keep the tools read-only and the limits tight.

**Watch next:** whether LangChain makes per-call human approval the default in its next major release, as its changelog says it plans, and how the new Decisions API middlewares settle after their beta.

## Frequently asked questions

### Why use a scripted model instead of a real one in tests?

A scripted model gives the same messages every time, so a failing test points to your code, not to model randomness. It also runs in a fraction of a second with no API cost. Use real models in a separate evaluation suite.

### Is checking that the query starts with SELECT enough?

No. A query starting with `WITH` can still contain `DELETE`, as the tutorial shows. Combine a cheap text check with an engine-level guarantee, such as a read-only connection or a database user with only `SELECT` rights.

### What is the difference between run_limit and thread_limit?

`run_limit` counts calls in one invocation, meaning one user message and the agent's response. `thread_limit` counts across all runs in a conversation and needs a checkpointer to remember earlier runs.

### Why return SQL errors to the model instead of raising them?

The error message is useful information. Returned as a tool result, it lets the model correct a typo or a wrong column on the next step. A raised exception would stop the run and lose that chance.

### Does this work with LangGraph directly?

Yes. `create_agent` returns a compiled LangGraph graph, so you can add a checkpointer, stream steps or embed it as a node in a larger graph. The tools and tests stay the same.

## Summary

A useful SQL data agent needs only three tools, a clear system prompt and two brakes. LangChain 1.5.2's `create_agent` runs the loop, `ModelCallLimitMiddleware` and `ToolCallLimitMiddleware` cap the work, and a read-only SQLite connection backs up the cheap SQL text check. A scripted model built on `GenericFakeChatModel` replays a realistic trajectory, including a failed query, so four pytest tests can check write safety, step order, the final numbers and runaway-loop handling in under a second. Swapping in a real model is one line, and LangSmith tracing shows where the real model's path differs from the script.

## Sources

- [LangChain: Built-in middleware](https://docs.langchain.com/oss/python/langchain/middleware/built-in)
- [LangChain: Python changelog, langchain 1.5.0](https://docs.langchain.com/oss/python/releases/changelog)
- [LangChain: Trace with LangChain in LangSmith](https://docs.langchain.com/langsmith/trace-with-langchain)
- [PyPI: langchain](https://pypi.org/project/langchain/)
- [PyPI: langgraph](https://pypi.org/project/langgraph/)
- [SQLite: Uniform Resource Identifiers](https://www.sqlite.org/uri.html)
