Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

39 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🧠 Dash: Self Learning Data Agents

A self-learning data agent system built with LangGraph, Azure OpenAI, Snowflake, and Qdrant.

Python Streamlit Snowflake Azure LangGraph Qdrant

Dash Application Interface

Inspired by Ashpreet Bedi's Dash, rebuilt from scratch with an enhanced multi-node architecture on top of the TPC-DS 100TB benchmark dataset.

Dash answers natural language questions about retail data by generating, validating, executing, and interpreting SQL β€” and learns from every interaction.

✨ Key Features

  • Natural Language to SQL: Converts complex business questions into optimized Snowflake SQL.
  • Self-Learning: Captures and reuses successful query patterns and error corrections.
  • Cost Protection: 4 layers of credit protection to prevent expensive Snowflake queries.
  • Multi-Agent Architecture: 9 specialized nodes orchestrated by LangGraph.

πŸ—οΈ Architecture

User ──► Intent Classifier (gpt-4o-mini)
              β”‚
              β”œβ”€β”€ data_question / infra_request ──► Context Retrieval
              β”‚                                        β”‚
              β”‚                          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚                          β–Ό             β–Ό             β”‚
              β”‚                       Analyst      Engineer          β”‚
              β”‚                          β”‚             β”‚             β”‚
              β”‚                     SQL Validator      β”‚             β”‚
              β”‚                      β”‚       β”‚         β”‚             β”‚
              β”‚                 Executor  ◄─retry      β”‚             β”‚
              β”‚                      β”‚       β”‚         β”‚             β”‚
              β”‚                 Interpreter   β”‚        β”‚             β”‚
              β”‚                      β”‚        β”‚        β”‚             β”‚
              β”‚              Learning Evaluatorβ”‚       β”‚             β”‚
              β”‚                      β”‚        β”‚        β”‚             β”‚
              β”œβ”€β”€ general / feedback ──► Leader β”‚      β”‚             β”‚
              β”‚                          β”‚     β”‚       β”‚             β”‚
              β–Ό                          β–Ό     β–Ό       β–Ό             β”‚
             END β—„β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜             β”‚
                                                                     β”‚
                                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                   β–Ό
                         validation_failed / execution_failed ──► END

9 specialized nodes + 3 helper nodes (retry, validation_failed, execution_failed) connected via conditional edges with a max 3-retry loop.


πŸ› οΈ Tech Stack

Component Technology Description
🎼 Orchestration LangGraph StateGraph for routing and flow control
🧠 LLM Azure OpenAI gpt-4o (analyst, engineer, interpreter) + gpt-4o-mini (intent, leader)
πŸ”€ Embeddings Azure OpenAI text-embedding-3-small
πŸ—„οΈ Vector Store Qdrant Persistent storage for knowledge & learnings (supports both local memory and Cloud)
❄️ Database Snowflake SNOWFLAKE_SAMPLE_DATA.TPCDS_SF100TCL (100TB)
🎨 Frontend Streamlit Interactive chat UI

πŸ“Š Dataset: TPC-DS SF100TCL

A 100TB retail benchmark featuring:

  • πŸ“ˆ 7 Fact Tables: STORE_SALES (~300B rows), CATALOG_SALES, WEB_SALES, STORE_RETURNS, CATALOG_RETURNS, WEB_RETURNS, INVENTORY.
  • πŸ—‚οΈ 17 Dimension Tables: CUSTOMER (~100M rows), ITEM (~500K rows), DATE_DIM, STORE, CUSTOMER_ADDRESS, etc.
  • πŸ•’ Scope: 1998–2002 across 3 sales channels (Store, Catalog, Web).

πŸ“‚ Project Structure

Click to expand
Dash-LangGraph/
β”œβ”€β”€ app.py                        # Streamlit UI
β”œβ”€β”€ config.py                     # Central configuration (env vars)
β”œβ”€β”€ requirements.txt              # Python dependencies
β”‚
β”œβ”€β”€ db/
β”‚   β”œβ”€β”€ __init__.py               # Snowflake connection factory (read + write engines)
β”‚   └── schema_cache.py           # INFORMATION_SCHEMA β†’ local JSON cache
β”‚
β”œβ”€β”€ graph/
β”‚   β”œβ”€β”€ state.py                  # DashState TypedDict (shared graph state)
β”‚   β”œβ”€β”€ edges.py                  # 4 conditional routing functions
β”‚   β”œβ”€β”€ builder.py                # Graph assembly (nodes + edges + compile)
β”‚   β”œβ”€β”€ graph_view.py             # Export compiled graph as PNG
β”‚   └── nodes/
β”‚       β”œβ”€β”€ intent_classifier.py  # Classifies intent (gpt-4o-mini)
β”‚       β”œβ”€β”€ context_retrieval.py  # Fetches knowledge + learnings + schema
β”‚       β”œβ”€β”€ analyst.py            # Generates read-only SQL (gpt-4o)
β”‚       β”œβ”€β”€ sql_validator.py      # Validates SQL (regex, no LLM)
β”‚       β”œβ”€β”€ executor.py           # Runs SQL on Snowflake
β”‚       β”œβ”€β”€ interpreter.py        # Converts results to insights (gpt-4o)
β”‚       β”œβ”€β”€ learning_evaluator.py # Saves learnings from interactions
β”‚       β”œβ”€β”€ leader.py             # Handles general/greeting messages
β”‚       └── engineer.py           # Creates views in DASH schema (gpt-4o)
β”‚
β”œβ”€β”€ vectorstore/
β”‚   └── __init__.py               # Qdrant wrapper (knowledge + learnings)
β”‚
β”œβ”€β”€ knowledge/
β”‚   β”œβ”€β”€ tables/                   # 24 table metadata JSONs (all TPC-DS tables)
β”‚   β”œβ”€β”€ queries/                  # 8 validated SQL patterns
β”‚   └── business/
β”‚       └── rules.json            # Metrics, gotchas, join patterns
β”‚
β”œβ”€β”€ scripts/
β”‚   β”œβ”€β”€ snowflake_setup.sql       # Snowflake setup (warehouse, roles, grants)
β”‚   β”œβ”€β”€ cache_schema.py           # One-time schema fetch β†’ JSON
β”‚   └── load_knowledge.py         # Embed knowledge into Qdrant
β”‚
β”œβ”€β”€ .env.example                  # Environment variable template
└── .gitignore

πŸš€ Setup & Installation

1. Clone & Environment

git clone <repo-url>
cd Dash-LangGraph
python -m venv venv

# Windows
.\venv\Scripts\activate
# macOS/Linux
source venv/bin/activate

2. Install Dependencies

pip install -r requirements.txt

3. Environment Variables

cp .env.example .env

Update .env with your credentials. (See Environment Variables Reference below).

4. Snowflake Setup

Run scripts/snowflake_setup.sql in a Snowflake worksheet as ACCOUNTADMIN. This creates:

  • COMPUTE_WH β€” XSMALL warehouse (auto-suspend 60s)
  • DASH_DB.DASH β€” Schema for Engineer-created views
  • Required Roles: DASH_ANALYST (read-only) & DASH_ENGINEER (read/write to DASH schema)
  • Resource monitor capping at 10 credits/month

5. Initialization (One-Time)

Cache the schema to avoid expensive queries, and load knowledge into ChromaDB:

python scripts/cache_schema.py
python scripts/load_knowledge.py --recreate

6. Launch App

streamlit run app.py

(Optional) Visualize the graph structure:

python graph/graph_view.py

πŸ›‘οΈ Cost Protection & Optimizations

Running on a 100TB dataset requires aggressive cost controls:

Layer Mechanism How it Works
1. Knowledge-first Skip SQL generation Pre-validated queries matched via semantic search.
2. SQL Validator Prevent expensive scans Auto-injects LIMIT, warns on missing date filters, blocks DML.
3. Schema Cache Avoid info queries Fetched once, stored as local JSON, kept in memory.
4. Vector Store Zero Snowflake cost Qdrant stores pre-calculated vectors. Fallbacks to in-memory for testing, saving I/O.

Performance Gains: Connection pooling, LLM singletons, and memory caching reduce per-request overhead, bringing response times down to ~18-20s after an initial warmup.


πŸ”„ Self-Learning Loop

The Learning Evaluator node captures two types of data:

  1. πŸ› Error Corrections: When a SQL error is fixed after a retry, the error β†’ fix pattern is saved.
  2. 🎯 Successful Patterns: When a query runs successfully, it's saved as a reusable pattern.

These are stored in Qdrant and retrieved by the Context node for future queries.


πŸ’¬ Example Questions

Try these out in the Streamlit app:

"What is the total revenue by sales channel for 2001?"
"Show me the top 10 product categories by sales amount"
"What's the return rate comparison across store, catalog, and web?"
"Rank all stores by revenue for year 2000"
"How does customer spending vary by education level?"
"Create a view that shows monthly revenue trends by channel"


πŸ”‘ Environment Variables Reference

Variable Description Default
AZURE_OPENAI_API_KEY Azure OpenAI API key Required
AZURE_OPENAI_ENDPOINT Azure OpenAI endpoint URL Required
AZURE_OPENAI_CHAT_DEPLOYMENT GPT-4o deployment name gpt-4o
AZURE_OPENAI_MINI_DEPLOYMENT GPT-4o-mini deployment name gpt-4o-mini
AZURE_OPENAI_EMBEDDING_DEPLOYMENT Embedding model deployment text-embedding-3-small
AZURE_OPENAI_API_VERSION Azure API version 2024-12-01-preview
SNOWFLAKE_ACCOUNT Snowflake account identifier Required
SNOWFLAKE_USER Snowflake username Required
SNOWFLAKE_PASSWORD Snowflake password Required
SNOWFLAKE_DATABASE Database name SNOWFLAKE_SAMPLE_DATA
SNOWFLAKE_SCHEMA Schema name TPCDS_SF100TCL
SNOWFLAKE_WAREHOUSE Warehouse name COMPUTE_WH
SNOWFLAKE_ROLE Default role SYSADMIN
QDRANT_URL Qdrant Cluster URL Optional (defaults to memory)
QDRANT_API_KEY Qdrant API Key Optional

About

Built a self-learning multi-agent AI system using LangGraph to convert natural language questions into accurate SQL queries and business insights.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages