Spaces:
Sleeping
Sleeping
|
Download README.md from faseehsandhu/Digitalytics: direct link, hf CLI and curl.
- Browser
- Download file 15.5 kB
-
https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/README.md
- Command line
-
hf download hf://spaces/faseehsandhu/Digitalytics/README.md
-
curl -L -o README.md https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/README.md
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. |