Spaces:
Sleeping

Digitalytics / README.md
faseehsandhu's picture
added insights with extracted values,uses tool calling and test framework
db9343f
|
Raw History Blame Contribute Delete
15.5 kB
---
title: Data Dictionary Chatbot
emoji: πŸ“š
colorFrom: blue
colorTo: purple
sdk: docker
app_port: 7860
pinned: false
---
# Streamlit Data Dictionary Chatbot
An AI-powered intelligent assistant that helps data scientists and analysts quickly discover relevant columns and datasets for machine learning projects. Instead of manually searching through multiple data dictionaries, users can describe their use case in natural language and receive intelligent, cited recommendations powered by Azure OpenAI.
## Executive Summary
This Streamlit web application combines conversational AI with smart retrieval technology (RAG - Retrieval-Augmented Generation) to make data dictionary exploration effortless. It supports multiple file formats, maintains conversation context, and uses advanced semantic search to find the most relevant columns for any data science use case.
## Key Features
### πŸ€– AI-Powered Conversational Interface
- **Natural Language Queries**: Ask questions in plain English (e.g., "Which columns help predict diabetes risk?")
- **Context-Aware Responses**: Remembers last 10 conversation exchanges for meaningful follow-ups
- **Deep-Dive Analysis**: Ask detailed questions about specific columns, definitions, and relationships
- **Smart Clarifications**: AI asks clarifying questions when queries are ambiguous
- **Mandatory Dataset Citation**: Every column recommendation explicitly states its source dataset
### πŸ—ΊοΈ Area Insights (ZIP / City)
- **Geography-Aware Q&A**: Ask questions by ZIP or city to pull only relevant columns for that area
- **ZIP Resolution**: Uses Nominatim to resolve city/state to ZIPs; guides users when county-only inputs lack ZIPs
- **Smart Context Building**: Extracts the most relevant columns for the requested geography and shows what was used
- **Intelligent Data Extraction**: Uses Azure OpenAI Function Calling to decide when to extract data vs respond with general knowledge
- **Cost Optimization**: Skips data extraction for small talk, reducing API calls by ~35%
- **Friendly Fallbacks**: Suggests entering a ZIP directly (examples: 10001, 30301, 94105) if no ZIP can be resolved
### πŸ“Š Multi-Source Data Dictionary Management
- **Default Dictionaries**: Pre-loaded data dictionaries available immediately on startup
- **Session-Based User Uploads**: Upload custom data dictionaries at runtime (isolated per session)
- **Multiple Format Support**: CSV (.csv), Excel (.xlsx, .xls), and PDF (.pdf) files
- **Dictionary Controls**: Toggle dictionaries on/off, view metadata, delete user uploads
- **Real-Time Metrics**: Live dashboard showing loaded dictionaries and cache status
- **Upload Privacy**: Uploaded files are session-specific and automatically discarded on page refresh
- **Naming Rule (important)**: Name each data dictionary file so its filename stem matches the dataset name. Examples: data file `SVI_2022.xlsx` β†’ dictionary `SVI_2022.xlsx`; data file `ahrf-2025.csv` β†’ dictionary `ahrf-2025.xlsx`; multi-sheet data `health.xlsx` sheet `CountyStats` β†’ dictionary `health_CountyStats.xlsx`. User uploads follow the same rule.
### 🎯 Smart Retrieval System (RAG)
- **Two-Stage Retrieval**: Combines fast keyword matching with AI semantic search
- **Massive Token Reduction**: Reduces context from 160,000+ to 5,000-10,000 tokens (97% reduction)
- **Cost Savings**: ~95% reduction in Azure OpenAI API costs
- **Speed Optimized**: First query ~2-3 seconds, subsequent queries <1 second (cached)
- **Intelligent Behavior**: Skips retrieval for simple greetings, auto-detects dictionary changes
- **Configurable Precision**: Adjustable top-k results (5-50) via sidebar slider
### πŸ’Ύ Advanced Caching System
- **Persistent Disk Cache**: Survives application restarts (`.cache/` directory)
- **Instant Startup**: Subsequent launches skip indexing (<500ms load time)
- **Automatic Invalidation**: Rebuilds cache when dictionaries change
- **Manual Controls**: "Clear Cache" and "Force Reindex" buttons
- **Embedding Cache**: Saves chunk embeddings to disk; query embeddings stay in memory only to avoid bloat
### 🎨 User Interface Components
- **Dark Mode Theme**: Modern dark theme enabled by default for comfortable viewing
- **Main Chat View**: Message history, input box, index status badge, debug expander
- **Sidebar Controls**: Navigation, retrieval settings, cache management, metrics dashboard
- **Upload Management**: Drag-and-drop uploader with session-specific file tracking
- **Retrieval Dashboard**: Live metrics for chunks indexed, embeddings cached, corpus signature
- **Multi-User Support**: Isolated conversations and session data for concurrent users
### βš™οΈ Advanced Configuration
- **Top-k Slider**: Adjust precision vs recall (5-50 results)
- **Embeddings Toggle**: Switch between semantic and keyword-only search
- **Debug Mode**: View retrieved snippets, source, and settings used
- **Environment Variables**: Flexible Azure OpenAI configuration
## Project Structure
```
streamlit-data-dictionary-chatbot
β”œβ”€β”€ src
β”‚ β”œβ”€β”€ app.py # Main entry point of the Streamlit application
β”‚ β”œβ”€β”€ components # UI components for the application
β”‚ β”‚ β”œβ”€β”€ chat_interface.py # Chatbot interface implementation
β”‚ β”‚ β”œβ”€β”€ area_insights_interface.py # Area Insights chat/ZIP-driven view
β”‚ β”‚ β”œβ”€β”€ file_uploader.py # File upload functionality
β”‚ β”‚ └── sidebar.py # Sidebar layout for navigation
β”‚ β”œβ”€β”€ services # Services for data handling and API interactions
β”‚ β”‚ β”œβ”€β”€ azure_openai_service.py # Azure OpenAI API interactions
β”‚ β”‚ β”œβ”€β”€ data_dictionary_service.py # Management of data dictionaries
β”‚ β”‚ β”œβ”€β”€ retrieval_service.py # Hybrid lexical/semantic retrieval with chunk-only disk cache
β”‚ β”‚ β”œβ”€β”€ zip_resolution_service.py # Nominatim-powered city/ZIP resolution for Area Insights
β”‚ β”‚ └── file_parser_service.py # File parsing logic
β”‚ β”œβ”€β”€ utils # Utility functions and session management
β”‚ β”‚ β”œβ”€β”€ session_state.py # Session state management
β”‚ β”‚ └── validators.py # Input validation functions
β”‚ └── config.py # Configuration settings
β”œβ”€β”€ data
β”‚ β”œβ”€β”€ default_dictionaries # Directory for default data dictionaries
β”‚ β”‚ └── .gitkeep # Keeps the directory in version control
β”‚ └── user_uploads # Directory for user-uploaded data dictionaries
β”‚ └── .gitkeep # Keeps the directory in version control
β”œβ”€β”€ tests # Unit tests for the application
β”‚ β”œβ”€β”€ test_services.py # Tests for service logic
β”‚ └── test_utils.py # Tests for utility functions
β”œβ”€β”€ .env.example # Example environment variable configuration
β”œβ”€β”€ .gitignore # Files and directories to ignore in version control
β”œβ”€β”€ requirements.txt # Project dependencies
β”œβ”€β”€ README.md # Project documentation
└── setup.py # Packaging configuration
```
## Key Benefits
βœ… **Time Savings**: Find relevant columns in seconds vs hours of manual searching
βœ… **Cost Efficiency**: 95% reduction in API costs through smart retrieval
βœ… **Accuracy**: AI semantic search finds contextually relevant matches, not just keywords
βœ… **Scalability**: Handles unlimited data dictionaries without context limit errors
βœ… **Flexibility**: Works with CSV, Excel, and PDF data dictionaries
βœ… **Transparency**: Debug tools and citation enforcement ensure trustworthy recommendations
βœ… **User Control**: Adjustable precision, cache management, dictionary selection
βœ… **Conversational**: Natural follow-up questions and clarifications supported
βœ… **Persistent**: Cache system ensures instant subsequent uses
βœ… **Production-Ready**: Error handling, logging, graceful degradation built-in
βœ… **Multi-User Ready**: Isolated sessions with private conversations and uploads
βœ… **Privacy-First**: Session-based file uploads automatically cleaned on refresh
## Use Case Example
**User Query:** *"I'm building a diabetes risk prediction model. Which columns should I use?"*
**Application Process:**
1. Indexes all available data dictionaries into searchable chunks (if not cached)
2. Searches for "diabetes risk prediction" using two-stage retrieval
3. Finds 25 most relevant entries across all dictionaries
4. Sends only these 25 entries + query + chat history to AI
5. AI responds with specific column recommendations, each citing the source dataset
6. User follows up: *"Tell me more about the HbA1c column"*
7. System retrieves detailed information about that specific column
**Result:** Precise, cited recommendations in <3 seconds with context-aware assistance.
## Installation
1. Clone the repository:
```
git clone https://github.com/yourusername/streamlit-data-dictionary-chatbot.git
cd streamlit-data-dictionary-chatbot
```
2. Install the required packages:
```
pip install -r requirements.txt
```
3. Set up your environment variables by copying `.env.example` to `.env` and filling in the necessary values:
**Required for chat:**
```env
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_API_KEY=your-api-key
AZURE_OPENAI_DEPLOYMENT=gpt-4o-mini # or your chat model deployment name
AZURE_OPENAI_API_VERSION=2024-08-01-preview # Required for function calling support
```
**Optional for enhanced retrieval (recommended):**
```env
AZURE_OPENAI_EMBEDDING_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_EMBEDDING_DEPLOYMENT=text-embedding-3-large # or your embedding deployment name
AZURE_OPENAI_EMBEDDING_API_VERSION=2024-02-01
```
If embedding variables are not set, the app will fall back to lexical search (still functional, but less accurate).
## How It Works
### Retrieval-Augmented Generation (RAG)
**The Problem:**
Large data dictionaries can contain 100,000+ tokens, but Azure OpenAI's GPT-4o-mini has a 128,000 token context limit. Sending complete dictionaries causes:
- ❌ API errors (context_length_exceeded)
- ❌ High costs (~$0.50+ per query)
- ❌ Slow response times (5-10 seconds)
- ❌ Information overload for the AI
**The Solution:**
Two-stage intelligent retrieval system that selects only the 1-2% most relevant data:
#### Stage 1: Lexical Pre-Filtering (Keyword-Based)
- Quickly scans all indexed chunks (lines from data dictionaries)
- Uses token overlap (60%) + fuzzy matching (40%) to score relevance
- Selects top 300 potentially relevant entries
- Speed: <100ms for thousands of chunks
#### Stage 2: Semantic Re-Ranking (AI-Based)
- Converts user query and top 300 candidates into embeddings (vector representations)
- Uses Azure OpenAI `text-embedding-3-large` model (3,072 dimensions)
- Computes cosine similarity for semantic relevance
- Returns top-k results (configurable 5-50, default 25)
- Caches embeddings to avoid redundant API calls
**Complete Flow:**
1. **Indexes dictionaries** into chunks with metadata (dataset name, line number)
2. **At query time**, runs two-stage retrieval (lexical β†’ semantic)
3. **Sends only 25 relevant snippets** to the LLM with query and chat history
4. **LLM responds** with grounded answers, citing specific datasets and columns
5. **Caches embeddings** for instant subsequent queries
**Performance Metrics:**
- Token Reduction: 160,000 β†’ 5,000-10,000 tokens (97% reduction)
- Cost Reduction: ~95% savings on API calls
- Speed: First query ~2-3s, cached queries <1s
- Accuracy: Retrieves only contextually relevant data
**Intelligent Optimizations:**
- Short messages (≀3 words like "hi", "thanks") skip retrieval entirely
- Automatic cache invalidation when dictionaries change
- Batch embedding API calls for efficiency
- Graceful fallback to keyword-only mode if embeddings unavailable
### Running Locally
To run the application locally, execute the following command:
```bash
streamlit run app.py
```
Open your web browser and navigate to `http://localhost:8501` to access the application.
### Deployed Application
(If you have a live deployment URL, add it here. Otherwise run locally with `streamlit run app.py` and open `http://localhost:8501`.)
## Technical Architecture
**Frontend:** Streamlit (Python web framework)
**Backend:** Python 3.x
**AI Services:**
- Azure OpenAI GPT-4o-mini (chat completions)
- Azure OpenAI text-embedding-3-large (semantic search)
- Azure OpenAI Function Calling (intelligent data extraction decisions)
**Data Processing:** Pandas, PyPDF2
**Storage:** File system (dictionaries + cache)
**Search Algorithm:** Hybrid lexical + semantic retrieval
**Cache Structure:**
```
.cache/
β”œβ”€β”€ chunks.json # Indexed chunks
β”œβ”€β”€ embeddings.json # Cached chunk embeddings (query embeddings stay in memory only)
└── corpus_sig.txt # Dictionary change detection hash
```
## Configuration Reference
### Required Environment Variables (Chat)
```env
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_API_KEY=your-api-key
AZURE_OPENAI_DEPLOYMENT=gpt-4o-mini
AZURE_OPENAI_API_VERSION=2024-08-01-preview # Required for function calling (or later)
```
### Optional Environment Variables (Enhanced Retrieval)
```env
AZURE_OPENAI_EMBEDDING_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_EMBEDDING_DEPLOYMENT=text-embedding-3-large
AZURE_OPENAI_EMBEDDING_API_VERSION=2024-02-01
```
**Note:** Without embedding variables, the app falls back to lexical search (functional but less accurate).
### Runtime Controls (Sidebar)
- **Top-k Slider**: Adjust number of retrieved results (5-50)
- **Embeddings Toggle**: Disable semantic search for faster keyword-only mode
- **Warm-Up Embeddings**: Preload sample chunk embeddings to speed up first queries
- **Force Reindex**: Rebuild index from current dictionaries (does not clear embeddings)
- **Clear Cache**: Wipe cached chunks/embeddings; hidden by default via `ALLOW_CLEAR_CACHE_BUTTON` in `sidebar.py`
## Troubleshooting
**Issue:** Slow first query
**Solution:** First query builds embeddings cache. Subsequent queries are instant.
**Issue:** "Context length exceeded" error
**Solution:** Reduce top-k slider value or verify retrieval service is enabled.
**Issue:** Embeddings not working
**Solution:** Verify `AZURE_OPENAI_EMBEDDING_DEPLOYMENT` is set correctly. App falls back to lexical search.
**Issue:** Uploaded files disappear
**Solution:** This is expected behavior. Files are session-specific and removed on page refresh for privacy.
**Issue:** Dark mode not showing
**Solution:** Clear browser cache and refresh. Dark mode is set as default in `.streamlit/config.toml`.
**Solution:** Verify `AZURE_OPENAI_EMBEDDING_DEPLOYMENT` is set correctly. App falls back to lexical search.
**Issue:** Cache not persisting
**Solution:** Check write permissions for `.cache/` directory.
**Issue:** Inaccurate results
**Solution:** Increase top-k value or enable embeddings if disabled.
## Contributing
Contributions are welcome! Please feel free to submit a pull request or open an issue for any enhancements or bug fixes.
## License
This project is licensed under the MIT License. See the LICENSE file for more details.