Skip to content
Shehryar Ahmed
All projects

Case study 02 · Independent build

AI-Powered Data Analytics PlatformNatural-Language Analysis of Excel Data

Upload a spreadsheet, ask questions in plain language, and get answers, charts and reports, where every number comes from SQL that actually ran.

Role
Sole engineer: ingestion, query engine, LLM tool loop, charts, reports and UI
Status
Core product implemented · PowerPoint export planned
Core stack
  • Python
  • FastAPI
  • DuckDB
  • sqlglot
  • OpenAI
  • React

The source code is in a private repository, so this page documents the design instead of linking to it.

01

Overview

A data analyst for business spreadsheets. Users upload an Excel or CSV file, such as sales or rental transactions, ask questions in a chat, get answers with charts, and turn the analysis into a PDF or Word report.

It is a separate product from Ilmora with its own pipeline, tables and storage. Spreadsheets are never chunked or embedded: the model plans the analysis and writes SQL, and DuckDB computes every figure on the full table. The two products share only sign-in, the OpenAI client and the app shell.

02

Business problem

  • Business teams have answers sitting in spreadsheets of tens of thousands of rows, but getting them means pivot tables, SQL or waiting for an analyst.
  • Language models are unreliable with numbers. Asked to read rows, they produce plausible but wrong totals, and retrieval over chunked rows cannot aggregate a whole table.
  • Model-written SQL is untrusted code. Running it against user data requires real isolation, not a prompt asking the model to behave.

03

Solution

  • A background ingestion job turns every worksheet into a typed Parquet table and builds a data-quality profile, with a report that explains each cleaning decision.
  • A tool-calling loop: the model receives the schema and column statistics (sample rows only if the user opts in), then calls tools to look up values, run SQL, detect outliers, build charts, or ask a clarifying question.
  • Every SQL statement is parsed and validated with sqlglot, regenerated from the validated syntax tree, and executed in an in-memory DuckDB with file and network access disabled and time, memory and row limits.
  • Answers are written only from the returned results and include a "How this was calculated" trace. Charts are drawn from stored query results, never from numbers the model wrote. Reports render to PDF and DOCX.

04

My contribution

  • Built the module end to end: ingestion pipeline, SQL guard and sandbox, tool loop and prompts, chart specifications, report templates and renderers, and the React interface.
  • Wrote the implementation plan first, including explicit isolation rules (import direction, table prefixes, separate storage and rate limits) so the existing knowledge assistant stayed untouched.

05

Technical architecture

From spreadsheet to answer

8 stages

  1. 01

    Excel upload

    .xlsx or CSV; defaults of 25 MB and 200,000 rows

  2. 02

    Data ingestion

    Background job; every sheet read as a table, headers detected

  3. 03

    Validation & profiling

    Signature, zip-bomb and macro checks; types, nulls, quality notes

  4. 04

    Structured processing

    Cleaned, typed Parquet per sheet; schema and profile in PostgreSQL

  5. 05

    Natural-language query

    Model sees schema and statistics, plans with tool calls

  6. 06

    Query execution

    SQL validated by sqlglot, run in a locked-down DuckDB

  7. 07

    Results

    Capped results; answer grounded in them, with a calculation trace

  8. 08

    Charts & reports

    Charts from stored results; PDF and DOCX reports

The spreadsheet itself never goes to the model. Only the schema, statistics and the small, capped results of queries the assistant runs are sent.

Ingestion

  • Upload validation: type, signature, size, zip bombs, macros, encryption
  • Streaming Excel and CSV readers, header and merged-cell handling
  • Cleaning and typing; sentinels such as N/A kept as text
  • Data-dictionary sheets detected and used for allowed values
  • Personal columns detected for masking

Query engine

  • sqlglot guard: one SELECT/WITH statement, own tables only
  • Allow-listed functions and complexity limits
  • SQL regenerated from the parsed tree and row-limited
  • In-memory DuckDB, no file or network access, locked configuration
  • Per-query timeout, memory limit and concurrency cap

Analysis chat

  • Tool loop over the OpenAI API, at most 8 tool rounds
  • Tools: find values, run SQL, detect outliers, chart, clarify
  • Privacy policy decides what is sent and is recorded per answer
  • Every query traced with purpose, SQL, filters, rows and timing

Charts and reports

  • One chart spec drawn by recharts in the browser and matplotlib in reports
  • Built-in templates: executive summary, market performance, data quality
  • Templates drafted from a reference PDF, reviewed by the user
  • PDF (PyMuPDF) and DOCX (python-docx) rendering

06

Technology stack

Backend
  • Python
  • FastAPI
  • SQLAlchemy
  • PostgreSQL (metadata)
Data
  • DuckDB
  • Parquet (pyarrow)
  • openpyxl
  • sqlglot
AI
  • OpenAI API
  • Tool calling
Output
  • matplotlib
  • PyMuPDF
  • python-docx
Frontend
  • React
  • TypeScript
  • recharts

07

Key engineering challenges

Running model-written SQL safely

The model's SQL is treated as untrusted input. It is parsed, restricted to a single read-only statement over the dataset's own tables with allow-listed functions, rewritten from the syntax tree rather than passed through, and executed in a DuckDB instance that has no file or network access and a locked configuration.

Real-world spreadsheets

Multiple sheets, headers that don't start on row one, merged cells, N/A sentinels and README or data-dictionary tabs. Ingestion handles each case and produces a report that tells the user exactly what it decided and why.

Misleading trends

In transaction data, an incomplete latest month looks like a market drop, and a change in mix looks like a change in price. The analysis prompt requires checking month completeness, separating price from price per area, quantifying period-over-period change and stating every filter and excluded row.

Privacy

The file never leaves the server. The model sees column names, types and statistics; sample rows are sent only if the user turns that on, with personal columns replaced by placeholders. Logs never contain cell values.

08

Technical decisions and trade-offs

Why text-to-SQL instead of RAG over spreadsheet rows?

Analytical questions are aggregations: totals, trends and comparisons over every row. Retrieval returns a handful of chunks, so any total computed from them is wrong. Having the model write SQL and a database compute the result keeps the arithmetic exact and auditable.

Trade-off: The model has to understand the schema. Ambiguous columns need a clarifying question, and the guard occasionally rejects a legitimate query, which the model then rewrites.

Why DuckDB and Parquet instead of loading data into PostgreSQL?

DuckDB runs in-process, is fast on 100k to 1M rows, reads Parquet directly, and can be locked down. PostgreSQL keeps only metadata, profiles and the small capped results needed to trace and redraw answers. pandas was deliberately not added: ingestion streams rows into pyarrow and analysis is SQL.

Trade-off: Two data stores to manage, and per-process limits on concurrent queries.

How is the model kept from inventing numbers?

The model never supplies figures directly. Answers are written from returned query results, chart data comes from stored results, and report editing allows changes to the narrative but rejects changes to numbers.

Every answer records the dataset version and file hash, the privacy policy used, and each query with its purpose, SQL, filters, row count and timing, including rejected attempts. Replacing a file creates a new version, and old answers stay linked to the data they used.

Why a single tool-calling loop instead of an agent framework?

One loop over the existing OpenAI client, with at most eight tool rounds followed by a final answer-only completion. The model cannot execute Python. A small, explicit loop is easier to test, secure and debug than a framework.

Trade-off: Fewer ready-made features, such as parallel planning or persistent agent memory, which this product does not need yet.

Validating untrusted SQL

python
def validate_sql(sql: str, *, tables: dict[str, dict[str, str]],
                 default_table: str, max_rows: int) -> GuardedQuery:
    statements = sqlglot.parse(sql, read="duckdb")
    living = [tree for tree in statements if tree is not None]
    if len(living) > 1:
        raise GuardError("Only one statement is allowed.", "parse")
    tree = living[0]
    if not _is_read_query(tree):
        raise GuardError("Only SELECT (and WITH / UNION of SELECTs) is allowed.", "ddl")
    _reject_forbidden_nodes(tree)
    _reject_into(tree)
    _check_tables(tree, set(tables) | {"data"}, _cte_names(tree))
    _check_functions(tree)
    _check_complexity(tree)
    tree = qualify(tree, schema=schema, dialect="duckdb",
                   qualify_columns=True, validate_qualify_columns=True)
    ...
Abridged excerpt of the query guard. The statement that finally runs is regenerated from the validated syntax tree, not the model's original text.

09

Implemented functionality

ImplementedPlanned
  • Excel (.xlsx) and CSV upload; defaults of 25 MB, 200,000 rows and 20 sheets

    Covers datasets of around 100,000 rows

    Implemented
  • Upload validation: signature, size, zip bombs, macros and encryption

    Implemented
  • Multi-sheet ingestion with header detection, cleaning, typing and an ingest report

    Implemented
  • Data profiling and quality notes, including latest-month completeness

    Implemented
  • Natural-language questions answered through validated, sandboxed SQL

    Implemented
  • Analysis guidance for sales and rental data: trends, comparisons, mix effects

    Implemented
  • Clarifying questions when the data or the question is ambiguous

    Implemented
  • Charts: line, area, bar, stacked, combo, histogram, scatter, pie, waterfall; PNG and CSV export

    Implemented
  • "How this was calculated" trace on every answer

    Implemented
  • Downloadable PDF and DOCX reports from templates or from an analysis chat

    Implemented
  • Report templates drafted from a reference PDF

    Implemented
  • Per-user isolation, quotas, retention cleanup and admin status

    Implemented
  • Opt-in live accuracy evaluation script

    Implemented
  • PowerPoint (PPTX) report export

    Planned
  • Sharing analysis conversations

    Planned
  • Larger automated accuracy evaluation set

    Planned

10

Outcomes and future improvements

Outcomes

  • A complete product loop: upload, analysis chat, charts and editable reports, with the safety and traceability business data requires.
  • Built as an isolated module. The knowledge assistant's code, tables and behaviour are unchanged, and the whole feature can be switched off with one setting.

Next steps

  • PowerPoint report export alongside PDF and DOCX.
  • A larger automated accuracy evaluation set.
  • Sharing analysis conversations, following the patterns already used in the knowledge assistant.