TLTan LeAI, cloud & automation for legacy systems · CalgaryLet’s talk
← All posts

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.

6graph nodes
2max SQL retries
0API keys needed for the demo
At a glance
Repotanldt/python_langgraph_AI_Data_Analyst_RAG
OrchestrationLangGraph StateGraph, MemorySaver checkpointer
ModelOptional. OpenAI through langchain-openai, default gpt-4o-mini
NumbersSQLite, opened read-only
Context.md, .txt and text-based .pdf files
InterfaceStreamlit
DataFictional 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:

NodeJob
planWrites a short task plan. Uses the model if a key is set, otherwise a default plan.
queryProduces one SELECT, checks it, runs it against SQLite in read-only mode.
retrieveFinds the document passages that share the most terms with the question.
analyzeCombines rows and passages into findings, citing passages as [file#chunk].
validateChecks that there are rows and an analysis. Sends the run back to query if not.
reportBuilds 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.

no API key · demo SQL
LangGraph analyst graphSTART leads to plan, query, retrieve, analyze, validate. The query node reads a read-only SQLite database and the retrieve node reads files in data/docs. From validate, a conditional edge goes to report when the result is valid or after two retries, and otherwise loops back to query. Report leads to END.retry · no rows · max 2valid, or retries ≥ 2STARTENDplanPlanner · task planLLMquerySELECT on read-only SQLiteLLMretrievekeyword match over docsanalyzerows + passages → findingsLLMvalidateany rows? any analysis?reportMarkdown with sourcesSQLitesales · read-onlydata/docs.md · .txt · .pdfLLMonly with a key

AgentState

question
—
plan
—
sql
—
rows
—
sources
—
analysis
—
valid
—
retries
—
report
—

trace

    Press a button to run the graph. Values match the repo's no-key demo; the second run is an illustrative model-written query for a month that is not in the table.

    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)

    #0
    #1
    #2
    #3

    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

    1. Load every .md, .txt and .pdf file in data/docs/ (PDFs through pypdf), up to 40,000 characters per file.
    2. 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.
    3. Tokenise the question and each chunk into lowercase words of four letters or more, plus four-digit numbers like 2026.
    4. Score each chunk by how many terms it shares with the question.
    5. Keep up to four chunks with a score above zero, best first, each labelled file#chunk so 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:

    Sample ticket revenue by month (fictional data) (USD)
    012,50025,00037,50050,000Concert · Jul 2026: 42,000 USDSports · Jul 2026: 26,000 USDConcert · Aug 2026: 50,000 USDSports · Aug 2026: 30,000 USDConcert · Sep 2026: 26,000 USDSports · Sep 2026: 22,000 USDConcert · Oct 2026: 31,000 USDSports · Oct 2026: 25,000 USDJul 2026Aug 2026Sep 2026Oct 2026
    ConcertSports
    Show data
    ConcertSports
    Jul 202642,000 USD26,000 USD
    Aug 202650,000 USD30,000 USD
    Sep 202626,000 USD22,000 USD
    Oct 202631,000 USD25,000 USD
    1. plan writes the default plan: query monthly sales totals and retrieve relevant business notes.
    2. query sees no “product” or “category” in the question, so it picks the monthly totals query. safe_sql checks it, SQLite runs it read-only, and four rows come back: August 80,000, September 48,000.
    3. retrieve matches august, september, 2026 and explanations against business_notes.md. The file is short enough to be a single chunk; it scores 4 and comes back as business_notes.md#0.
    4. 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].
    5. validate finds rows and an analysis, so valid is true.
    6. 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_sql only accepts a single SELECT on the sales table. 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 in error.
    • The database is opened with mode=ro and PRAGMA 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 caseNumbers (SQL)Context (documents)Question it answers
    Ticketing and live eventsSales by event, category, channelPromo calendar, event briefs, on-sale notes“Why did September concert revenue drop 48%?”
    Retail and e-commerceOrders, returns, stock levelsCampaign briefs, supplier emails, stock-out notes“Which categories slipped this week, and was anything going on?”
    Finance month-endGL actuals against budgetBudget memos, contracts, prior commentary“Draft variance commentary for every line over 10%, with sources.”
    Customer support operationsTicket volume, SLA breaches by dayIncident 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.