Numbers and the reasons behind them: an AI data analyst on LangGraph
A LangGraph workflow that answers a business question from two sources at once: SQL for the numbers and documents for the context, with a bounded retry loop and a cited report. Animated walkthrough and business cases.
| At a glance | |
|---|---|
| Repo | tanldt/python_langgraph_AI_Data_Analyst_RAG |
| Orchestration | LangGraph StateGraph, MemorySaver checkpointer |
| Model | Optional. OpenAI through langchain-openai, default gpt-4o-mini |
| Numbers | SQLite, opened read-only |
| Context | .md, .txt and text-based .pdf files |
| Interface | Streamlit |
| Data | Fictional ticket sales and business notes |
Ask a manager why revenue dropped last month and you get two kinds of answer. One is a number: September came in at 48,000, down from 80,000. The other is a reason: fewer featured concerts, a smaller promo budget. The number lives in a database. The reason lives in someone’s notes, a campaign brief or an email thread.
Most “chat with your data” demos only cover the first half. Text-to-SQL gives you the number, and the reason is left to whoever reads the chart. This post walks through a small project that does both in one run: query the database, pull the relevant passages from the documents, and write a report that keeps the two apart and cites where each claim came from. It is a learning project with made-up data, but the shape of the workflow is one I would use on real systems.
The problem: half an answer
Text-to-SQL alone answers what. Document search alone (classic RAG) answers what someone wrote. A useful analyst answer needs both, plus some discipline:
- The numbers have to come from the database, not from the model’s memory.
- The explanation has to come from documents, and say which ones.
- A pattern in the numbers and a sentence in a note line up in time. That does not make one the cause of the other, and the report should say so.
- If a step fails, for example the query returns nothing, the system should notice and not write a confident paragraph about empty data.
That last point is why I reached for LangGraph instead of a single prompt or a plain chain.
What I built
A six-step workflow. Each step is an ordinary Python function, and LangGraph wires them together:
| Node | Job |
|---|---|
plan | Writes a short task plan. Uses the model if a key is set, otherwise a default plan. |
query | Produces one SELECT, checks it, runs it against SQLite in read-only mode. |
retrieve | Finds the document passages that share the most terms with the question. |
analyze | Combines rows and passages into findings, citing passages as [file#chunk]. |
validate | Checks that there are rows and an analysis. Sends the run back to query if not. |
report | Builds a Markdown report: status, question, SQL, analysis, sources, a causation warning. |
The whole thing runs without an API key. In that mode the SQL comes from two safe built-in queries and the analysis is a plain evidence dump, so you can see the graph work before spending a cent on tokens. Add OPENAI_API_KEY and the model writes the plan, the SQL and the analysis.
How the graph runs
Press play. The left side is the graph; the right side is the shared state that every node reads from and writes to.
AgentState
- question
- —
- plan
- —
- sql
- —
- rows
- —
- sources
- —
- analysis
- —
- valid
- —
- retries
- —
- report
- —
trace
Three LangGraph ideas do all the work here.
One shared state. AgentState is a TypedDict with keys like question, sql, rows, sources, analysis, valid, retries and trace. A node receives the whole state and returns only the keys it changed. LangGraph merges them in. Nodes never call each other, so each one is easy to test on its own.
Fixed edges for the happy path. START → plan → query → retrieve → analyze → validate is a straight line. No routing logic, no model deciding what to do next.
One conditional edge for judgment. After validate, a small function decides where to go:
def route(state):
return 'report' if state['valid'] or state['retries'] >= 2 else 'query'
graph.add_conditional_edges('validate', route, {'query': 'query', 'report': 'report'})
graph.add_edge('report', END)
app = graph.compile(checkpointer=MemorySaver())
The second button in the animation shows that loop. The model writes a query for December 2026, which is not in the table, so it gets zero rows. validate fails and sends the run back to query, and since the edges after query are fixed, retrieve and analyze run again too. After the second failure the route gives up and goes to report, which is marked Incomplete analysis: review data/query instead of pretending. The loop has a hard ceiling, and running out of retries ends with an honest report, not an error.
The checkpointer saves the state after every step, keyed by a thread_id that Streamlit creates per browser session. The trace key is a plain list each node appends to, and the UI prints it, so you can always see which path a run took.
Retrieving the “why”
The retrieve node is the RAG half. It is deliberately simple: no embeddings, no vector database, just text matching you can follow by eye.
Question terms (4+ letters, or 4 digits)
- compare
- august
- september
- 2026
- revenue
- look
- explanations
- documents
notes.md · 3,000 characters (illustrative)
0window 1,000 · step 850 · overlap 1503,000
Score = shared terms
- notes.md#04
- notes.md#10
- notes.md#22
- notes.md#31
→ sources: #0, #2, #3 (top 4 with score > 0) · #1 dropped
- Load every
.md,.txtand.pdffile indata/docs/(PDFs throughpypdf), up to 40,000 characters per file. - Chunk with a 1,000-character window that moves 850 characters at a time, so neighbouring chunks overlap by 150. A sentence cut at a chunk edge still appears whole in one of them.
- Tokenise the question and each chunk into lowercase words of four letters or more, plus four-digit numbers like
2026. - Score each chunk by how many terms it shares with the question.
- Keep up to four chunks with a score above zero, best first, each labelled
file#chunkso the analysis can cite it.
Keyword matching does mean the words have to match: a question about “income” will not find a note that only says “revenue”. For a demo with one notes file, that trade is worth it, because you can predict exactly which passage will come back and why. Swapping in embeddings later changes this one node and nothing else in the graph.
One question, end to end
Here is the default question in no-key mode: “Compare August and September 2026 revenue and look for explanations in documents.”
The sample database has eight rows, ticket sales by month and category:
Show data
| Concert | Sports | |
|---|---|---|
| Jul 2026 | 42,000 USD | 26,000 USD |
| Aug 2026 | 50,000 USD | 30,000 USD |
| Sep 2026 | 26,000 USD | 22,000 USD |
| Oct 2026 | 31,000 USD | 25,000 USD |
- plan writes the default plan: query monthly sales totals and retrieve relevant business notes.
- query sees no “product” or “category” in the question, so it picks the monthly totals query.
safe_sqlchecks it, SQLite runs it read-only, and four rows come back: August 80,000, September 48,000. - retrieve matches
august,september,2026andexplanationsagainstbusiness_notes.md. The file is short enough to be a single chunk; it scores 4 and comes back asbusiness_notes.md#0. - analyze has no model in this mode, so it lists the rows and the passage, with a note that this is an evidence summary and not a causal explanation. With a model, the system prompt tells it to use only the supplied rows and excerpts, separate observations from hypotheses, quote numbers exactly and cite
[file#chunk]. - validate finds rows and an analysis, so
validis true. - report assembles the Markdown and ends with: Correlation or coincident timing does not establish causation.
The note itself says September had “fewer featured concert events than August and a smaller promotional budget”, and calls those “potential explanations, not proven causal drivers.” The report keeps that wording. It hands the reader a number, a candidate reason and a pointer to the source, and leaves the conclusion to a person.
Guardrails on the SQL side
The model writes SQL, so the query node does not trust it:
safe_sqlonly accepts a singleSELECTon thesalestable. Write keywords,PRAGMA,ATTACH, comments and multiple statements are rejected. If the model’s query fails the check, the node falls back to a built-in safe query and records why inerror.- The database is opened with
mode=roandPRAGMA query_only=ON, so even a query that slipped past the check could not change data. - A SQLite progress handler stops long-running queries, and results are capped at 100 rows before they reach the model.
None of this replaces a restricted database account in a real deployment, but it means the demo fails closed.
Where this pattern fits
The demo is about ticket sales, but the shape is general: a structured system of record plus the unstructured documents that explain it. Most small and mid-sized companies have exactly that, usually a SQL Server database behind a .NET application and a shared drive full of notes. These are the cases where I would apply the same graph, pointed at a read-only replica so the production system is never touched.
| Business case | Numbers (SQL) | Context (documents) | Question it answers |
|---|---|---|---|
| Ticketing and live events | Sales by event, category, channel | Promo calendar, event briefs, on-sale notes | “Why did September concert revenue drop 48%?” |
| Retail and e-commerce | Orders, returns, stock levels | Campaign briefs, supplier emails, stock-out notes | “Which categories slipped this week, and was anything going on?” |
| Finance month-end | GL actuals against budget | Budget memos, contracts, prior commentary | “Draft variance commentary for every line over 10%, with sources.” |
| Customer support operations | Ticket volume, SLA breaches by day | Incident post-mortems, release notes | “Why did tickets spike on the 14th?” |
A few things carry over from the demo to each of these:
- The split between numbers and reasons is the product. A finance controller does not want a model’s opinion on why marketing spend went up. They want the figure from the ledger next to the paragraph from the memo, with a link, so they can decide.
- Validation before the report is what makes it safe to automate. A month-end job that runs overnight should come back as “incomplete, here is why” rather than a fluent paragraph built on zero rows. The bounded loop gives you that for free.
- Each node is a swap point. SQLite becomes SQL Server, the folder of notes becomes SharePoint, keyword retrieval becomes a vector index. The graph, the state and the routing stay the same.
- No-key mode is a real feature. It lets you test the plumbing, the permissions and the data access with an IT team before any company data is sent to a model provider.
Takeaways
- Use LangGraph for the parts that need judgment and state, not to look sophisticated. Here that is one conditional edge and one shared state. Everything else is a straight line.
- Keep the number and the reason in separate state keys, from separate sources, all the way to the report. That is what stops the model from blending them into a plausible story.
- Put a ceiling on every loop, and make running out of retries produce an honest result.
- Start with retrieval you can explain. Keyword matching is crude, but when a passage comes back you know exactly why, which matters more than recall while you are still proving the workflow.
The code is on GitHub at tanldt/python_langgraph_AI_Data_Analyst_RAG. It runs with streamlit run app/ui.py after a one-line setup script, no key required. If you want to see how a single agent with tools compares to a graph like this, I wrote about that in One agent, four tools.