Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

8 Commits

Folders and files

Repository files navigation

db-chatbot-demo — a planning SQL agent (LangGraph)

A SQL agent that plans before it queries. It writes an explicit to-do list of sub-questions, answers each one with a single validated read-only query, records the evidence, and only then writes a detailed answer that cites every step.

It is model-agnostic: the provider and model are chosen by environment variable and go through init_chat_model, so OpenAI, Anthropic, Google, Ollama, Bedrock and the rest work without a code change.

Graph

START → introspect_schema → plan ───────────────────────────────┐
                              ↑                                 │
                    (bounded replan)                             ↓
        ┌──────────────────── assess ←── execute_sql ←──── draft_sql
        │                       │            │ ok             ↑ repair
        │                       │            ↓                │
        └──────────────────→ record_todo ────┴────────────────┘
                                 │ plan exhausted
                                 ↓
                             synthesize → END

Every loop is bounded: MAX_SQL_ATTEMPTS repairs per to-do, one extra attempt that assess may grant, and MAX_REPLANS plan revisions per run. A to-do that cannot be answered is recorded as failed and surfaces in the answer's caveats rather than silently disappearing.

Setup

uv sync                 # or: pip install -r requirements.txt
python main.py --seed   # build data/demo.db

.env needs a key for whichever provider you use (OPENAI_API_KEY by default).

Running

One command serves both the API and the chat UI:

uv run fastapi dev src/app.py   # http://localhost:8000

POST /stream sends the run back as server-sent events: one status frame per log line, then the final answer typed out a token at a time, then a closing answer frame carrying both the markdown and the structured FinalAnswer.

The UI in web/ is plain HTML, CSS and JavaScript — no build step, no second server. FastAPI mounts it at /, so it rebuilds the plan from those frames and you watch each to-do draft its SQL, run it and record a row count while the agent works. Each finding in the answer cites the step it came from; clicking the citation jumps to that row.

LangGraph Studio is the other interface:

uv run langgraph dev

Then run the sql_agent graph with {"question": "..."}. The state inspector shows the plan, the exact SQL for every step, and the accumulated results.

Headless, for a quick check:

python main.py -q "Which category grew the most in Q4 versus Q3 by revenue, \
and does accounting for refunds change that ranking?"

Configuration

All optional, read from the environment (see src/config.py):

Variable Default Meaning
MODEL_PROVIDER openai any provider init_chat_model supports
MODEL_NAME gpt-4.1 model id for that provider
MODEL_TEMPERATURE 0 dropped automatically if the model rejects it
DB_PATH data/demo.db SQLite file to query
MAX_ROWS 200 row cap per query
MAX_SQL_ATTEMPTS 3 repair attempts per to-do
MAX_REPLANS 2 plan revisions per run
MAX_TODOS 8 steps per plan

Switching provider is only environment:

MODEL_PROVIDER=anthropic MODEL_NAME=claude-sonnet-5 python main.py -q "..."

(Install the matching integration package first, e.g. langchain-anthropic.)

Safety

The agent cannot write to the database, by three independent mechanisms in src/db.py:

  1. the connection is opened mode=ro, so writes fail at the driver;
  2. is_read_only rejects anything that is not a single SELECT/WITH/EXPLAIN statement, including multi-statement payloads and PRAGMA;
  3. every query is compiled with EXPLAIN before it runs, and results are capped by row count and by a VM-step limit that kills runaway joins.

The database

src/seed.py builds a deterministic e-commerce database (random.seed(42)), so everyone who runs python main.py --seed gets byte-identical data and the same answers. One store, one year of trading: 2024-01-22 to 2024-12-31, all amounts in a single unnamed currency.

categories ──< products ──< order_items >── orders >── customers
                                              │
                                              └──< payments
Table Rows What a row is Columns worth knowing
categories 6 a product category name: Laptops, Phones, Wearables, Audio, Accessories, Home Office
products 58 a sellable item unit_cost and list_price (so margin is answerable), is_active — 10 products are discontinued
customers 120 a registered buyer segment: consumer (65), business (25), promo (30); country: BR, ES, US, AR, DE, MX; signup_date
orders 330 one checkout status: completed (316) or cancelled (14); channel: web (155), mobile (144), partner (31); order_date
order_items 881 one line of an order unit_price is what was actually charged, after discount (a fraction, 0–0.4, off list_price); 1–4 lines per order
payments 316 the settlement of one order status: captured (276), refunded (32), failed (8); method: card, paypal, transfer; amount; paid_at

Things that trip up a naive single query, and that the agent has to reason about:

  • Cancelled orders still have items. All 330 orders have order_items, but only the 316 completed ones have a payment. Revenue questions need the join or the filter.
  • There is no revenue column. Order value is SUM(unit_price * quantity) over order_items. payments.amount mirrors that total — there is no tax or shipping — but a refunded payment still carries the full amount, so captured revenue and booked revenue are different numbers (413,374 captured vs 462,806 booked).
  • Dates are ISO TEXT. String comparison works; strftime/substr are the tools for grouping by month or quarter.

Three patterns were deliberately seeded, and each one takes several queries to pin down:

  1. The February promo cohort churns. The 30 promo customers all signed up in February and nearly all ordered exactly once, within three weeks, then vanished — 1.03 orders per customer against 3.09 for consumer and 3.92 for business.
  2. Q4 lifts hard. Order volume roughly doubles into the fourth quarter (completed orders — Q3: 80 orders / 125,852; Q4: 145 orders / 196,592), so any year-long average hides the shape of the year.
  3. Refunds are concentrated. A refund applies to the whole order and follows its dominant category: Wearables orders are refunded 22% of the time, Phones 7% and Audio 6%, against a 3% baseline. Category totals barely reorder, but growth rankings do: by gross revenue, Q3→Q4 growth ranks Audio, Accessories, Wearables, Home Office, Phones, Laptops — net of refunds it is Audio, Wearables, Phones, Accessories, Home Office, Laptops.

Questions to ask it

Good demo questions are ones where the second query depends on the first:

  • Which category grew the most in Q4 versus Q3 by revenue, and does accounting for refunds change that ranking?
  • Did the February promo signups turn into repeat customers, or did they order once and stop?
  • Which products are we selling at the thinnest margin once discounts are applied, and are any of them still active?
  • Is the mobile channel actually growing, or is it just taking share from web?
  • Which country has the highest average order value, and is that driven by one segment?
  • How much revenue did we book but never capture, and where is it concentrated?

Small, single-hop questions (how many customers are there?, list the categories) work too, but the plan-then-execute loop only earns its keep on the ones above.

Layout

File Role
src/graph.py graph assembly, build_graph(), Studio entry point
src/nodes.py node implementations and routers
src/states.py AgentState and its reducers
src/schemas.py Pydantic payloads (Plan, SQLDraft, TodoResult, FinalAnswer)
src/prompts.py one prompt per node
src/db.py the only module that touches SQLite
src/tools.py the same DB access exposed as LangChain tools
src/models.py provider-agnostic model + structured-output helpers
src/app.py FastAPI wrapper: the /stream SSE endpoint, and it serves web/
web/ the chat UI — plain HTML, CSS and JS, no build step

Tests

python -m tests.test_agent_loops

Six checks covering the read-only guard, the row cap, the repair loop, the give-up path and the replan budget. All model calls are stubbed, so the suite needs no API key and no network.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages