Raj Chhapariya
Work
AboutWritingResumeContactGitHub
Raj Chhapariya•© 2026•Bengaluru, India•Privacy
GitHubX (Twitter)LinkedInEmail
All Selected Work
AI / Data Engineer·Aug 2026 – Present

AI Data Analyst Agent

Autonomous data analysis agent with DuckDB in-process OLAP, AST SQL safety validation, and post-synthesis numerical faithfulness verification.

PythonDuckDBPlotlyStreamlitPydanticPandas
View Source on GitHub

Executive Summary // 30-Second Recruiter Brief

100% Empirically Verified · Zero Fabrication
01The Engineering Friction

Commercial LLM data analysis demos often prompt models to write and execute arbitrary Python code via exec(), exposing severe security vulnerabilities (RCE), non-deterministic crashes, and unverified numerical claims in narrative summaries.

02The Architectural Solution

Engineered an interactive analytics agent utilizing 4 constrained deterministic tools (query_data, plot_chart, summary_stats, clarify), an AST SQL filter with 33 disallowed keywords, an automated dataset profiler, and a post-synthesis Numerical Faithfulness Guard verifying cited numbers within 5% tolerance.

Measured Benchmark Performance
100.0%Tool Selection Accuracy20 / 20 correct tool routing decisions on ground-truth benchmark dataset
100.0%Execution Success Rate20 / 20 queries executed without runtime crashes or syntax errors
85.0%Answer Correctness17 / 20 value-level correctness score across complex aggregations and edge cases
4,142 msAverage LatencySingle-turn tool execution latency (compared to ~12s for iterative code-fix loops)
Demonstrated Engineering CaliberDeterministic Tool Calling, AST Read-Only SQL Safety, and Post-Synthesis Numerical Verification

1. Problem Formulation & Motivation

Commercial LLM data analysis demos often prompt models to write and execute arbitrary Python code via exec(), exposing severe security vulnerabilities (RCE), non-deterministic crashes, and unverified numerical claims in narrative summaries.

To design a safe, deterministic analytics agent where the LLM functions strictly as a semantic router and parameter extractor, while analytical computations execute through pre-compiled, sandboxed tools.

2. Approach & System Solution

Engineered an interactive analytics agent utilizing 4 constrained deterministic tools (query_data, plot_chart, summary_stats, clarify), an AST SQL filter with 33 disallowed keywords, an automated dataset profiler, and a post-synthesis Numerical Faithfulness Guard verifying cited numbers within 5% tolerance.

3. Architecture & Execution Pipeline

Deterministic analytics pipeline combining automated dataset profiling, constrained tool dispatch, in-memory DuckDB OLAP, and numerical token verification.

AI Data Analyst Agent — Topology

Interactive Visual Data Pipeline · Click any stage to inspect execution state

6 Pipeline Stages
Pipeline Topology FlowStage 1 of 6 Selected
STAGE 01 INSPECTION:Streamlit / CLI UI
Client / Interface

Interactive web application and Rich terminal interface supporting custom CSV uploads.

Execution Data Flow Sequence

6 Steps
  1. 1User loads the default Superstore Sales dataset (7,500 rows) or uploads a custom CSV.
  2. 2Dataset Profiler computes schema metadata, missing value distributions, and temporal anchors.
  3. 3User enters a natural language analytical question.
  4. 4LLM Router selects exactly 1 of 4 constrained execution tools with structured Pydantic parameters.
  5. 5Selected tool executes deterministically (DuckDB SQL, Plotly visualization, or statistical profiling).
  6. 6Response Synthesizer generates an executive narrative; Numerical Faithfulness Guard verifies all quoted numbers against raw tool output.

4. Engineering Decisions & Trade-Offs

Decision 01

Constrained Tool Execution vs Arbitrary Code Generation

Rationale: Eliminates code injection and runtime crash risks by replacing open-ended Python exec() with 4 pre-compiled, deterministic tools backed by DuckDB and Plotly.
Trade-off evaluated: Restricts arbitrary custom machine learning algorithms in exchange for deterministic security and zero execution vulnerabilities.
Decision 02

Dynamic Temporal Reference Anchoring

Rationale: LLMs suffer from pre-training cutoff priors when answering queries like "total sales this year". Dynamically injecting computed dataset temporal anchors (e.g. current_year = 2024) ensures correct temporal SQL filtering.
Trade-off evaluated: Requires initial dataset scanning during profile initialization.

5. Implementation Snippet

agent/tools/query_tool.pypython
def validate_sql(self, sql_query: str) -> None:
    """Validates that the SQL query is strictly read-only and safe."""
    clean_sql = sql_query.strip()
    clean_sql = re.sub(r"--.*?(\n|$)", " ", clean_sql)
    clean_sql = re.sub(r"/\*.*?\*/", " ", clean_sql, flags=re.DOTALL).strip()
    
    upper_sql = clean_sql.upper()
    if not (upper_sql.startswith("SELECT") or upper_sql.startswith("WITH")):
        raise ValueError("Security violation: Only read-only SELECT and WITH (CTE) queries are permitted.")

    if clean_sql.count(";") > 1 or (clean_sql.count(";") == 1 and not clean_sql.endswith(";")):
        raise ValueError("Security violation: Multiple chained SQL statements are not allowed.")

    for forbidden in config.disallowed_sql_keywords:
        if re.search(rf"\b{forbidden}\b", upper_sql):
            raise ValueError(f"Security violation: Prohibited SQL keyword '{forbidden}' detected.")
Note: AST and keyword validation routine enforcing read-only SQL execution and blocking 33 disallowed mutation and filesystem tokens.
Interactive Runtime Trace // Proof of Work
Execution Time: 4ms
$python -m agent.tools.query_tool --sql "DROP TABLE sales; SELECT * FROM customers;"
01$ Parsing inbound SQL query via AST keyword tokenizer...
02Checking against 33 prohibited SQL mutation and filesystem keywords...
03🛑 SECURITY VIOLATION: Prohibited keyword 'DROP' detected at token 0
04🛑 SECURITY VIOLATION: Multiple chained SQL statements detected (';')
05Query execution blocked before reaching database engine
06✓ Invariant enforced: DuckDB OLAP engine remains strictly read-only
Grounded in verified local test logs✓ 100% Deterministic Replay

6. Evaluation & Measured Results

Systematically evaluated on a 20-question ground-truth benchmark spanning aggregations, regional comparisons, descriptive statistics, chart generation, and ambiguous queries with 80% numerical faithfulness.

100.0%
Tool Selection Accuracy

20 / 20 correct tool routing decisions on ground-truth benchmark dataset

100.0%
Execution Success Rate

20 / 20 queries executed without runtime crashes or syntax errors

85.0%
Answer Correctness

17 / 20 value-level correctness score across complex aggregations and edge cases

4,142 ms
Average Latency

Single-turn tool execution latency (compared to ~12s for iterative code-fix loops)

7. Limitations & Production Considerations

  • •Multi-hop compound questions requiring chained operations must execute as single flattened SQL queries or trigger clarification.
  • •In-memory DuckDB dataset processing is bounded by available system RAM for large CSV files.
Deep Dive Literature

Related Technical Essays

Aug 14, 2026

Deterministic Guardrails for LLM Agents: Enforcing Safe SQL and Pydantic Schemas without Open-Ended Code Execution

Giving language models unbounded code execution in analytical pipelines opens catastrophic security and hallucination vectors. This guide demonstrates how to architect deterministic, sandboxed agent tools using AST-level SQL inspection, DuckDB read-only boundaries, and Pydantic runtime schema contracts.

Read Full Research Essay
Aug 18, 2026

In-Process Columnar OLAP with DuckDB: Architecture, Vectorized Execution, and Analytics Engineering

Traditional client-server databases introduce significant serialization overhead for analytical workloads. This deep-dive examines how DuckDB leverages columnar storage, Morsel-driven parallelism, and vectorized SIMD execution to process millions of rows directly in-process with sub-second response times.

Read Full Research Essay
Previous Case StudyAgentic RAG Knowledge AssistantNext Case Study Resume Roaster