Spaces:
Sleeping
Sleeping
Download src/components/area_insights_interface.py from faseehsandhu/Digitalytics: direct link, hf CLI and curl.
- Browser
- Download file 42.3 kB
-
https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/components/area_insights_interface.py
- Command line
-
hf download hf://spaces/faseehsandhu/Digitalytics/src/components/area_insights_interface.py
-
curl -L -o area_insights_interface.py https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/components/area_insights_interface.py
42.3 kB
| """ | |
| Area Insights Interface Component | |
| This component provides a chat-based interface for geographical area insights, | |
| combining ZIP code resolution, offline dataset querying, and LLM responses. | |
| """ | |
| import logging | |
| import re | |
| import streamlit as st | |
| from typing import Dict, List, Optional, Set, Tuple | |
| from services.azure_openai_service import AzureOpenAIService | |
| from services.zip_resolution_service import ZipResolutionService | |
| from services.offline_dataset_service import OfflineDatasetService | |
| from services.retrieval_service import RetrievalService | |
| from services.area_ranking_service import AreaRankingService | |
| logger = logging.getLogger(__name__) | |
| # Tunables | |
| COLUMN_SEARCH_TOP_K = 20 # how many chunks to retrieve when matching user query to columns | |
| MAX_RELEVANT_COLS_PER_DATASET = 10 # cap relevant columns included per dataset in LLM context | |
| DESCRIPTION_MAX_CHARS = 200 # truncation cap for column descriptions | |
| SHORT_MESSAGE_WORD_THRESHOLD = 3 # messages at/under this word count skip the decision LLM call | |
| CONTEXT_PREVIEW_CHARS = 2000 # debug-panel context preview size | |
| # Specialized system prompt for area insights | |
| AREA_INSIGHTS_SYSTEM_PROMPT = """You are a geographical data analyst assistant providing insights about specific US areas. | |
| Your analysis is for: {area_name} (ZIP Code: {zip_code}) | |
| CRITICAL INSTRUCTIONS: | |
| 1. ALWAYS prioritize provided dataset facts over general knowledge | |
| 2. When presenting facts from datasets, cite the source explicitly using format: **(Source: DatasetName)** | |
| 3. When data is unavailable or incomplete, clearly state "Based on general knowledge" and acknowledge the data limitation | |
| 4. Be conversational but factual - avoid speculation when data is missing | |
| 5. When column descriptions are provided, use them to explain what the data represents | |
| 6. Format numerical data clearly with appropriate units when known | |
| 7. If asked about topics with no data, politely explain what data is available instead | |
| RESPONSE GUIDELINES - GENERATE NARRATIVE INSIGHTS: | |
| - Do NOT just list raw numbers and definitions | |
| - Group related metrics by theme (health, economy, education, demographics, etc.) | |
| - Show connections between metrics (e.g., how poverty affects health outcomes) | |
| - Highlight the most critical issues or patterns in the data | |
| - Provide interpretation of what the numbers mean for residents | |
| - Suggest what's driving observed patterns | |
| - Use narrative paragraphs, not bullet lists for main insights | |
| - End with key takeaways about what matters most | |
| Remember: You are analyzing {area_name} (ZIP: {zip_code}). Ground your responses in provided data with narrative context and implications.""" | |
| class AreaInsightsInterface: | |
| """Chat interface for area-based insights using offline datasets.""" | |
| def __init__(self, data_dictionary_service, retrieval_service: RetrievalService, | |
| zip_service: ZipResolutionService, dataset_service: OfflineDatasetService): | |
| """ | |
| Initialize the Area Insights interface. | |
| Args: | |
| data_dictionary_service: Service for data dictionary management | |
| retrieval_service: Service for semantic search over data dictionaries | |
| zip_service: Service for resolving area names to ZIP codes | |
| dataset_service: Service for querying offline datasets | |
| """ | |
| # Initialize services | |
| try: | |
| self.openai_service = AzureOpenAIService() | |
| except ValueError as e: | |
| st.error(f"Configuration Error: {str(e)}") | |
| st.info("Please check your .env file and ensure all Azure OpenAI credentials are set correctly.") | |
| self.openai_service = None | |
| self.data_dictionary_service = data_dictionary_service | |
| self.retrieval_service = retrieval_service | |
| self.zip_service = zip_service | |
| self.dataset_service = dataset_service | |
| # Ranking service (use-case → top areas). Built here so its lifetime matches the component. | |
| self.ranking_service = ( | |
| AreaRankingService( | |
| openai_service=self.openai_service, | |
| retrieval_service=self.retrieval_service, | |
| data_dictionary_service=self.data_dictionary_service, | |
| dataset_service=self.dataset_service, | |
| ) | |
| if self.openai_service else None | |
| ) | |
| # Initialize session state for area insights | |
| if 'area_chat_history' not in st.session_state: | |
| st.session_state.area_chat_history = [] | |
| if 'area_current_zip' not in st.session_state: | |
| st.session_state.area_current_zip = None | |
| if 'area_current_name' not in st.session_state: | |
| st.session_state.area_current_name = None | |
| if 'area_chat_started' not in st.session_state: | |
| st.session_state.area_chat_started = False | |
| if 'area_no_data_warning' not in st.session_state: | |
| st.session_state.area_no_data_warning = False | |
| if 'area_column_descriptions' not in st.session_state: | |
| st.session_state.area_column_descriptions = {} | |
| # Recommendation-mode state | |
| if 'area_show_recommendations' not in st.session_state: | |
| st.session_state.area_show_recommendations = False | |
| if 'area_recommendations' not in st.session_state: | |
| st.session_state.area_recommendations = None | |
| def display(self): | |
| """Display the area insights interface.""" | |
| st.subheader("🗺️ Area Insights Chatbot") | |
| # Check if OpenAI service is configured | |
| if not self.openai_service: | |
| st.error("Azure OpenAI is not configured. Please set up your credentials.") | |
| return | |
| # State machine: chat > recommendations > entry | |
| if st.session_state.area_chat_started: | |
| self._display_chat() | |
| elif st.session_state.area_show_recommendations: | |
| self._display_recommendations() | |
| else: | |
| self._display_area_entry() | |
| def _display_area_entry(self): | |
| """Entry screen with two modes: use-case-based recommendations or direct ZIP lookup.""" | |
| tab1, tab2 = st.tabs([ | |
| "🎯 Recommend areas for my use case", | |
| "📍 Look up a specific ZIP", | |
| ]) | |
| with tab1: | |
| self._display_use_case_entry() | |
| with tab2: | |
| self._display_zip_entry() | |
| def _display_use_case_entry(self): | |
| """Describe-your-use-case form → ranked list of recommended areas.""" | |
| st.markdown( | |
| "Describe what you're looking for — the system scans your loaded datasets and " | |
| "ranks the areas that best match." | |
| ) | |
| with st.expander("💡 Example use cases"): | |
| st.markdown( | |
| "- *I'm running a Phase 2 diabetes medication trial and need counties with " | |
| "high adult diabetes prevalence.*\n" | |
| "- *Looking for counties with high poverty and limited healthcare access for " | |
| "a community health outreach study.*\n" | |
| "- *Need areas with high cardiovascular disease risk and large populations " | |
| "for a cardiac device trial.*" | |
| ) | |
| use_case = st.text_area( | |
| "Your use case:", | |
| placeholder="e.g. I'm recruiting for a Phase 2 diabetes trial and need areas with high diabetes prevalence and at least 20,000 residents.", | |
| height=120, | |
| key="use_case_input", | |
| ) | |
| top_n = st.slider("How many areas to recommend?", 5, 20, 10, key="recommend_top_n") | |
| submitted = st.button( | |
| "🎯 Find Matching Areas", | |
| type="primary", | |
| disabled=not (use_case or "").strip(), | |
| key="find_areas_btn", | |
| ) | |
| if submitted and (use_case or "").strip(): | |
| with st.spinner("Analysing data dictionaries and ranking areas..."): | |
| try: | |
| rec = self.ranking_service.rank_areas_for_use_case(use_case.strip(), top_n=top_n) | |
| st.session_state.area_recommendations = rec | |
| st.session_state.area_show_recommendations = True | |
| logger.info( | |
| f"Ranking complete: {len(rec.get('top_areas', []))} areas on dataset " | |
| f"{rec.get('primary_dataset')}" | |
| ) | |
| st.rerun() | |
| except Exception as e: | |
| logger.error(f"Area ranking failed: {e}") | |
| st.error(f"Ranking failed: {e}") | |
| def _display_zip_entry(self): | |
| """Direct 5-digit ZIP entry (existing flow).""" | |
| st.markdown( | |
| "Enter a 5-digit US ZIP code to jump straight into insights for that area.\n\n" | |
| "**Examples:** `01001` · `10001` · `94102`" | |
| ) | |
| zip_input = st.text_input( | |
| "Enter 5-digit ZIP code:", | |
| placeholder="e.g., 01001", | |
| max_chars=5, | |
| key="direct_zip_input", | |
| help="Enter a valid 5-digit US ZIP code", | |
| ) | |
| zip_value = (zip_input or "").strip() | |
| is_valid_zip = zip_value.isdigit() and len(zip_value) == 5 | |
| if zip_value and not is_valid_zip: | |
| st.caption("⚠️ ZIP must be exactly 5 digits.") | |
| start_zip_button = st.button( | |
| "🚀 Start Chat", | |
| type="primary", | |
| disabled=not is_valid_zip, | |
| key="start_by_zip", | |
| ) | |
| if start_zip_button and is_valid_zip: | |
| with st.spinner("Loading data for ZIP code..."): | |
| result = self.zip_service.manual_zip_entry(zip_value) | |
| if not result['error']: | |
| self._start_chat_with_zip(result) | |
| st.rerun() | |
| else: | |
| st.error(result['error']) | |
| def _display_recommendations(self): | |
| """Render the ranked list of recommended areas.""" | |
| rec = st.session_state.area_recommendations or {} | |
| use_case = rec.get('use_case', '') | |
| criteria = rec.get('criteria', []) | |
| top_areas = rec.get('top_areas', []) | |
| primary_dataset = rec.get('primary_dataset') | |
| warning = rec.get('warning') | |
| narrative = rec.get('narrative', '') | |
| # Header row with "new search" escape hatch | |
| col_hdr, col_btn = st.columns([5, 1]) | |
| with col_hdr: | |
| st.markdown(f"**Use case:** {use_case}") | |
| with col_btn: | |
| if st.button("🔙 New search", key="rec_back_btn"): | |
| st.session_state.area_show_recommendations = False | |
| st.session_state.area_recommendations = None | |
| st.rerun() | |
| if warning: | |
| st.warning(warning) | |
| if not top_areas: | |
| if not warning: | |
| st.info("No areas could be ranked. Try rewording your use case.") | |
| return | |
| # Show criteria used | |
| if criteria: | |
| with st.expander(f"📐 Ranking criteria (dataset: **{primary_dataset}**)", expanded=True): | |
| for c in criteria: | |
| arrow = "↑" if c['direction'] == 'high' else "↓" | |
| st.markdown( | |
| f"- **{c['column']}** {arrow} (weight {c['weight']:.1f}) — {c.get('reason', '')}" | |
| ) | |
| # Narrative summary | |
| if narrative: | |
| st.markdown("### 📊 Analysis") | |
| st.markdown(narrative) | |
| # Ranked list | |
| st.markdown(f"### 🏆 Top {len(top_areas)} Matching Areas") | |
| for rank, area in enumerate(top_areas, start=1): | |
| area_id = area.get('area_id') or "(unknown)" | |
| display_name = area.get('display_name') | |
| score = area.get('composite_score', 0.0) | |
| with st.container(): | |
| col_info, col_action = st.columns([5, 1]) | |
| with col_info: | |
| if display_name: | |
| st.markdown( | |
| f"**#{rank} · {display_name}** " | |
| f"<span style='color:#888;font-size:0.85em'>(FIPS {area_id})</span> — " | |
| f"composite score **{score:.3f}**", | |
| unsafe_allow_html=True, | |
| ) | |
| else: | |
| st.markdown(f"**#{rank} · Area `{area_id}`** — composite score **{score:.3f}**") | |
| metric_bits = [] | |
| for col, m in area.get('metrics', {}).items(): | |
| val = m.get('value') | |
| arrow = "↑" if m.get('direction') == 'high' else "↓" | |
| metric_bits.append(f"{col} {arrow} {val:,.2f}") | |
| if metric_bits: | |
| st.caption(" · ".join(metric_bits)) | |
| with col_action: | |
| drill_key = f"drill_{rank}_{area_id}" | |
| if st.button( | |
| "🔍 Explore", | |
| key=drill_key, | |
| help="Open a focused chat about this area — ask follow-up questions like 'what's the physician density?' or 'how does poverty compare to state average?'", | |
| ): | |
| self._start_chat_with_zip({ | |
| 'zip_code': area_id, | |
| 'display_name': display_name or f"Area {area_id}", | |
| }) | |
| st.session_state.area_show_recommendations = False | |
| st.rerun() | |
| st.divider() | |
| def _start_chat_with_zip(self, resolution_result: Dict): | |
| """ | |
| Start the chat session with a resolved ZIP code. | |
| Args: | |
| resolution_result: Dictionary with zip_code, display_name, etc. | |
| """ | |
| zip_code = resolution_result['zip_code'] | |
| display_name = resolution_result.get('display_name', f"ZIP {zip_code}") | |
| # Store in session state | |
| st.session_state.area_current_zip = zip_code | |
| st.session_state.area_current_name = display_name | |
| st.session_state.area_chat_started = True | |
| # Check if data exists for this ZIP | |
| has_data = self.dataset_service.has_data_for_zip(zip_code) | |
| st.session_state.area_no_data_warning = not has_data | |
| if not has_data: | |
| # Get nearby ZIP suggestions | |
| available_zips = self.dataset_service.get_available_zips() | |
| nearby = self.zip_service.get_nearby_zips(zip_code, available_zips) | |
| if nearby: | |
| st.session_state.area_nearby_zips = nearby | |
| # Clear previous chat and column descriptions | |
| st.session_state.area_chat_history = [] | |
| st.session_state.area_column_descriptions = {} | |
| logger.info(f"Started area chat for {display_name} (ZIP: {zip_code}), has_data: {has_data}") | |
| # Don't call st.rerun() - let Streamlit handle it naturally | |
| def _display_chat(self): | |
| """Display the chat interface with locked area context.""" | |
| # Show locked area context | |
| zip_code = st.session_state.area_current_zip | |
| area_name = st.session_state.area_current_name | |
| logger.info(f"_display_chat called for {area_name} (ZIP: {zip_code})") | |
| if not zip_code or not area_name: | |
| st.error("Session data lost. Please start a new area chat.") | |
| if st.button("Start Over"): | |
| self._reset_area_chat() | |
| st.rerun() | |
| return | |
| logger.info("Displaying area info banner") | |
| st.info(f"📍 **Current Area:** {area_name} (ZIP: {zip_code})") | |
| logger.info("Checking no data warning") | |
| # Show warning if no data available | |
| if st.session_state.area_no_data_warning: | |
| nearby_zips = st.session_state.get('area_nearby_zips', []) | |
| nearby_text = f" Nearby ZIPs with data: {', '.join(nearby_zips)}" if nearby_zips else "" | |
| st.warning(f"⚠️ No local data available for ZIP {zip_code}.{nearby_text}\n\nResponses will be based on general knowledge only.") | |
| logger.info("Building sidebar controls") | |
| # Sidebar controls | |
| with st.sidebar: | |
| st.divider() | |
| st.subheader("Area Chat Controls") | |
| # Quick ZIP switch — lets users compare areas without losing context | |
| with st.form("area_switch_form", clear_on_submit=True): | |
| new_zip = st.text_input( | |
| "Switch to ZIP:", | |
| placeholder="e.g., 94102", | |
| max_chars=5, | |
| key="switch_zip_input", | |
| help="Enter a new 5-digit ZIP to switch area (clears chat history)" | |
| ) | |
| switch_submitted = st.form_submit_button("🔀 Switch Area") | |
| if switch_submitted: | |
| candidate = (new_zip or "").strip() | |
| if candidate.isdigit() and len(candidate) == 5: | |
| result = self.zip_service.manual_zip_entry(candidate) | |
| if not result['error']: | |
| self._start_chat_with_zip(result) | |
| st.rerun() | |
| else: | |
| st.error(result['error']) | |
| else: | |
| st.error("ZIP must be exactly 5 digits.") | |
| if st.button("🔄 Start New Area Chat", help="Reset and choose a different area"): | |
| self._reset_area_chat() | |
| st.rerun() | |
| if st.button("🗑️ Clear Chat History", help="Clear messages but keep current area"): | |
| st.session_state.area_chat_history = [] | |
| st.session_state.area_column_descriptions = {} | |
| st.rerun() | |
| # Show dataset info | |
| st.divider() | |
| st.caption("**Available Datasets**") | |
| dataset_info = self.dataset_service.get_dataset_info() | |
| if dataset_info: | |
| for ds in dataset_info: | |
| st.caption(f"📊 {ds['name']}: {ds['rows']} rows, {ds['unique_zips']} ZIPs") | |
| else: | |
| st.caption("No offline datasets loaded") | |
| logger.info("Displaying chat history") | |
| # Display chat history or welcome message | |
| if not st.session_state.area_chat_history: | |
| # Show welcome message when chat is empty | |
| with st.chat_message("assistant"): | |
| st.write(f"👋 Welcome to Area Insights Chat for **{area_name}** (ZIP: {zip_code})!\n\n" | |
| "Ask me any questions about this area and I'll provide insights based on available data.") | |
| for user_msg, bot_msg in st.session_state.area_chat_history: | |
| with st.chat_message("user"): | |
| st.write(user_msg) | |
| with st.chat_message("assistant"): | |
| st.write(bot_msg) | |
| logger.info("Rendering chat input") | |
| # User input | |
| user_input = st.chat_input("Ask about this area...") | |
| logger.info(f"Chat input rendered, user_input value: {user_input}") | |
| if user_input: | |
| logger.info(f"Area chat input: {user_input}") | |
| # Display user message | |
| with st.chat_message("user"): | |
| st.write(user_input) | |
| # Generate response | |
| with st.chat_message("assistant"): | |
| with st.spinner("Analyzing area data..."): | |
| try: | |
| bot_response = self._generate_area_response(user_input) | |
| st.write(bot_response) | |
| # Store in history | |
| st.session_state.area_chat_history.append((user_input, bot_response)) | |
| except Exception as e: | |
| error_msg = f"❌ Error: {str(e)}" | |
| st.error(error_msg) | |
| st.session_state.area_chat_history.append((user_input, error_msg)) | |
| logger.error(f"Error generating area response: {e}") | |
| def _generate_area_response(self, user_message: str) -> str: | |
| """ | |
| Generate a response using area data and LLM with function calling. | |
| Uses Azure OpenAI function calling to decide whether to extract data. | |
| Args: | |
| user_message: User's question about the area | |
| Returns: | |
| Generated response string | |
| """ | |
| import json | |
| zip_code = st.session_state.area_current_zip | |
| area_name = st.session_state.area_current_name | |
| logger.info(f"Generating area response for: {user_message}") | |
| # Construct system prompt | |
| system_prompt = AREA_INSIGHTS_SYSTEM_PROMPT.format( | |
| area_name=area_name, | |
| zip_code=zip_code | |
| ) | |
| # Short-message fast path: skip the decision LLM call for trivial inputs | |
| # (greetings, acknowledgements) — they never need data extraction. | |
| if len(user_message.split()) <= SHORT_MESSAGE_WORD_THRESHOLD: | |
| logger.info(f"Short-message bypass: '{user_message}' -> skipping decision call") | |
| final_prompt = f"""Area: {area_name} (ZIP: {zip_code}) | |
| User Question: {user_message} | |
| Provide a brief, friendly response. You can use general knowledge about this area.""" | |
| final_response = self.openai_service.generate_response( | |
| final_prompt, | |
| st.session_state.area_chat_history, | |
| system_prompt=system_prompt, | |
| tools=None | |
| ) | |
| return self.openai_service.get_message_content(final_response) | |
| # Step 1: Define the data extraction tool for Azure OpenAI function calling | |
| # This tells the model what "functions" it can call | |
| tools = [ | |
| { | |
| "type": "function", | |
| "function": { | |
| "name": "extract_area_data", | |
| "description": "Extract and analyze relevant data values from local datasets for the geographic area. Call this when answering questions that require local data insights. Skip for greetings, small talk, or general knowledge questions.", | |
| "parameters": { | |
| "type": "object", | |
| "properties": { | |
| "should_extract": { | |
| "type": "boolean", | |
| "description": "True if the user question requires local data extraction and analysis. False for greetings, small talk, or general knowledge questions." | |
| }, | |
| "reason": { | |
| "type": "string", | |
| "description": "Brief reason for the extraction decision" | |
| } | |
| }, | |
| "required": ["should_extract", "reason"] | |
| } | |
| } | |
| } | |
| ] | |
| # Step 2: Call Azure OpenAI with function calling enabled | |
| # The model will decide whether to call extract_area_data or just respond | |
| logger.info("Calling Azure OpenAI with function calling to decide on data extraction...") | |
| decision_prompt = f"""User Question: {user_message} | |
| This is a question about {area_name} (ZIP Code: {zip_code}). | |
| Decide whether this question requires extracting and analyzing local data from our geographic databases. | |
| Consider: Does this question need specific data about this area to answer well, or can it be answered with general knowledge?""" | |
| try: | |
| # Make API call with tools parameter | |
| response = self.openai_service.generate_response( | |
| decision_prompt, | |
| st.session_state.area_chat_history, | |
| system_prompt=system_prompt, | |
| tools=tools # Pass tools for function calling | |
| ) | |
| logger.info(f"Azure OpenAI response received. Checking for tool calls...") | |
| # Step 3: Check if model decided to call the extraction tool | |
| needs_data = False | |
| extraction_reason = "Not determined" | |
| if self.openai_service.has_tool_calls(response): | |
| tool_calls = self.openai_service.get_tool_calls(response) | |
| logger.info(f"Model made {len(tool_calls)} tool call(s)") | |
| for tool_call in tool_calls: | |
| if tool_call["function"]["name"] == "extract_area_data": | |
| # Parse the tool arguments | |
| try: | |
| args = json.loads(tool_call["function"]["arguments"]) | |
| needs_data = args.get("should_extract", False) | |
| extraction_reason = args.get("reason", "Not provided") | |
| logger.info(f"Tool call decision: needs_data={needs_data}, reason={extraction_reason}") | |
| except json.JSONDecodeError as e: | |
| logger.warning(f"Could not parse tool arguments: {e}") | |
| needs_data = True # Default to extract on error | |
| else: | |
| # Model didn't call a tool, check if it provided a direct answer | |
| content = self.openai_service.get_message_content(response) | |
| logger.info(f"No tool call made. Model response: {content[:100]}...") | |
| # If model directly answered without calling tool, treat as "no data needed" | |
| needs_data = False | |
| except Exception as e: | |
| logger.warning(f"Error in function calling, defaulting to extract data: {e}") | |
| needs_data = True | |
| extraction_reason = f"Error occurred: {str(e)}" | |
| # Step 4: Query datasets only if extraction is needed | |
| dataset_results = {} | |
| relevant_columns = {} | |
| context = "" | |
| if needs_data: | |
| logger.info(f"Extracting data for this query (reason: {extraction_reason})...") | |
| dataset_results = self.dataset_service.query_by_zip(zip_code) | |
| logger.info(f"Found data in {len(dataset_results)} datasets for ZIP {zip_code}") | |
| if dataset_results: | |
| # Find columns relevant to user's question | |
| logger.info("Finding columns relevant to user question...") | |
| relevant_columns = self._get_relevant_columns(user_message, dataset_results) | |
| logger.info(f"Found relevant columns: {relevant_columns}") | |
| # Build context with relevant values | |
| context = self._build_smart_context(dataset_results, relevant_columns, user_message) | |
| logger.info(f"Built context with {len(relevant_columns)} datasets") | |
| else: | |
| logger.info(f"Skipping data extraction (reason: {extraction_reason})") | |
| # Step 5: Build response prompt with or without data | |
| if context: | |
| # We have data - include it with narrative insight instructions | |
| logger.info("Found relevant context, using data-backed response") | |
| final_prompt = f"""{context} | |
| User Question: {user_message} | |
| Generate narrative insights: group related metrics by theme, show connections between data points, | |
| highlight critical patterns, and provide interpretation of what numbers mean for residents.""" | |
| else: | |
| # No data extraction or no relevant data | |
| if needs_data and dataset_results: | |
| # Data exists but no relevant columns - mention available data | |
| logger.info("Data exists but no relevant columns - using general knowledge with data mention") | |
| available_summary = "Available datasets and their main characteristics:\n" | |
| for dataset_name, data in dataset_results.items(): | |
| available_summary += f"- {dataset_name}: {data['row_count']} record(s) with {len(data['columns'])} columns\n" | |
| final_prompt = f"""For ZIP Code {zip_code} ({area_name}), the following datasets are available: | |
| {available_summary} | |
| User Question: {user_message} | |
| While specific data for this question may not be in our databases, provide helpful insights by: | |
| 1. Using general knowledge about this area (if well-known) | |
| 2. Suggesting what data would help answer this question better""" | |
| else: | |
| # No data extraction needed - general knowledge response | |
| logger.info("Using general knowledge response") | |
| final_prompt = f"""Area: {area_name} (ZIP: {zip_code}) | |
| User Question: {user_message} | |
| Provide a helpful response. You can use general knowledge about this area.""" | |
| logger.info(f"Sending final response prompt to OpenAI (context length: {len(context)} chars)") | |
| # Step 6: Generate final response without tools (just conversation) | |
| final_response = self.openai_service.generate_response( | |
| final_prompt, | |
| st.session_state.area_chat_history, | |
| system_prompt=system_prompt, | |
| tools=None # No tools for final response | |
| ) | |
| bot_response = self.openai_service.get_message_content(final_response) | |
| logger.info(f"Received area response (length: {len(bot_response)} chars)") | |
| # Show debug info | |
| self._show_debug_info(dataset_results, context, relevant_columns) | |
| return bot_response | |
| def _get_relevant_columns(self, user_message: str, dataset_results: Dict) -> Dict[str, List[str]]: | |
| """ | |
| Map the user's query to relevant columns in the loaded datasets. | |
| Each retrieved chunk comes from exactly one dictionary (via its `dataset` | |
| field). We map that dictionary back to a loaded dataset, then match the | |
| chunk text against that dataset's columns using word-bounded regexes. | |
| This avoids the cross-dataset false-positives caused by naive substring | |
| matching against every dataset's columns, and preserves retrieval rank | |
| order so the most relevant columns appear first. | |
| """ | |
| all_dicts = self.data_dictionary_service.get_all_dictionaries() | |
| active_dicts = [d['name'] for d in all_dicts if d.get('active', True)] | |
| loaded_datasets = set(dataset_results.keys()) | |
| # Map each active dictionary -> its corresponding loaded dataset (if any) | |
| dict_to_dataset: Dict[str, str] = {} | |
| for dict_name in active_dicts: | |
| dict_lower = dict_name.lower() | |
| for dataset_name in loaded_datasets: | |
| ds_lower = dataset_name.lower() | |
| if (ds_lower in dict_lower or dict_lower in ds_lower or | |
| dict_lower.startswith(ds_lower.split('_')[0])): | |
| dict_to_dataset[dict_name] = dataset_name | |
| break | |
| filtered_dicts = list(dict_to_dataset.keys()) | |
| if not filtered_dicts: | |
| logger.warning("No dictionaries match the loaded datasets") | |
| return {} | |
| logger.info( | |
| f"Searching {len(filtered_dicts)} dictionaries for columns matching: '{user_message}'" | |
| ) | |
| search_results = self.retrieval_service.search( | |
| user_message, | |
| filtered_dicts, | |
| top_k=COLUMN_SEARCH_TOP_K, | |
| disable_embeddings=False, | |
| ) | |
| if not search_results: | |
| logger.info("No relevant columns found in data dictionaries") | |
| return {} | |
| # Precompile word-bounded patterns per dataset column (supports underscore<->space variants). | |
| # Short names (<=2 chars) are skipped to avoid noise from abbreviations. | |
| dataset_col_patterns: Dict[str, List[Tuple[str, "re.Pattern[str]"]]] = {} | |
| for ds_name, ds_data in dataset_results.items(): | |
| patterns: List[Tuple[str, "re.Pattern[str]"]] = [] | |
| for col in ds_data['columns']: | |
| if len(col) <= 2: | |
| continue | |
| variants = {re.escape(col), re.escape(col.replace('_', ' '))} | |
| patterns.append((col, re.compile(r'(?i)\b(?:' + '|'.join(variants) + r')\b'))) | |
| dataset_col_patterns[ds_name] = patterns | |
| # Walk chunks in retrieval-rank order; each chunk contributes to at most | |
| # one dataset (the one its source dictionary maps to). | |
| relevant_columns: Dict[str, List[str]] = {} | |
| seen: Set[Tuple[str, str]] = set() | |
| for result in search_results: | |
| chunk_dict = result.get('dataset') | |
| chunk_text = result.get('text', '') | |
| if not chunk_dict or not chunk_text: | |
| continue | |
| dataset_name = dict_to_dataset.get(chunk_dict) | |
| if not dataset_name: | |
| continue | |
| for col, pat in dataset_col_patterns.get(dataset_name, []): | |
| key = (dataset_name, col) | |
| if key in seen: | |
| continue | |
| if pat.search(chunk_text): | |
| seen.add(key) | |
| relevant_columns.setdefault(dataset_name, []).append(col) | |
| # Cap per dataset while preserving retrieval rank | |
| for ds_name in relevant_columns: | |
| relevant_columns[ds_name] = relevant_columns[ds_name][:MAX_RELEVANT_COLS_PER_DATASET] | |
| total = sum(len(cols) for cols in relevant_columns.values()) | |
| logger.info( | |
| f"Selected {total} relevant columns across {len(relevant_columns)} datasets " | |
| f"from {len(search_results)} chunks" | |
| ) | |
| return relevant_columns | |
| def _build_smart_context(self, dataset_results: Dict, relevant_columns: Dict[str, List[str]], user_message: str) -> str: | |
| """ | |
| Build context using only columns relevant to the user's question. | |
| Args: | |
| dataset_results: Results from dataset query | |
| relevant_columns: Dict mapping dataset_name -> [relevant_column_names] | |
| user_message: User's question (for reference) | |
| Returns: | |
| Formatted context string with relevant data | |
| """ | |
| if not relevant_columns: | |
| logger.info("No relevant columns to build context") | |
| return "" | |
| context_parts = [] | |
| context_parts.append("**Relevant Data Available for this Area:**\n") | |
| # Get descriptions for relevant columns only (much smaller set) | |
| all_relevant_cols = set() | |
| for cols in relevant_columns.values(): | |
| all_relevant_cols.update(cols) | |
| logger.info(f"Getting descriptions for {len(all_relevant_cols)} relevant columns") | |
| column_descriptions = self._get_column_descriptions(list(all_relevant_cols)) | |
| # Build context with relevant data only | |
| extraction_log = [] # Track all extracted values for logging | |
| extracted_values = {} # Store extracted relevant column values | |
| for dataset_name, data in dataset_results.items(): | |
| if dataset_name not in relevant_columns or not relevant_columns[dataset_name]: | |
| continue # Skip if no relevant columns in this dataset | |
| df = data['rows'] | |
| context_parts.append(f"\n**Dataset: {dataset_name}** ({data['row_count']} record(s))") | |
| extraction_log.append(f"\n=== Extracting from {dataset_name} ===") | |
| extraction_log.append(f"Relevant columns: {relevant_columns[dataset_name]}") | |
| # Store extracted values for logging | |
| if dataset_name not in extracted_values: | |
| extracted_values[dataset_name] = {} | |
| # Extract only relevant columns for context | |
| for col in relevant_columns[dataset_name]: | |
| if col not in df.columns: | |
| extraction_log.append(f" ⚠️ Column '{col}' NOT FOUND in dataframe") | |
| continue | |
| # Get first non-null value | |
| values = df[col].dropna().unique() | |
| if len(values) > 0: | |
| value = values[0] | |
| value_str = str(value).strip() | |
| # Store for logging | |
| extracted_values[dataset_name][col] = value | |
| else: | |
| extraction_log.append(f" ⚠️ Column '{col}' has no non-null values") | |
| continue | |
| # Get description if available | |
| desc = column_descriptions.get(col, "") | |
| if desc: | |
| context_parts.append(f" - **{col}**: {value_str}\n ℹ️ {desc}") | |
| else: | |
| context_parts.append(f" - **{col}**: {value_str}") | |
| # Log extracted relevant column values | |
| extraction_log.append(f"\nExtracted values being sent to LLM:") | |
| for dataset_name, col_values in extracted_values.items(): | |
| extraction_log.append(f" {dataset_name}:") | |
| for col, val in col_values.items(): | |
| extraction_log.append(f" {col} = {repr(val)}") | |
| result = "\n".join(context_parts) | |
| # Log all extracted values for debugging | |
| extraction_summary = "\n".join(extraction_log) | |
| logger.info(f"DATA EXTRACTION:\n{extraction_summary}") | |
| logger.info(f"Built smart context (length: {len(result)} chars)") | |
| return result | |
| def _get_column_descriptions(self, columns: List[str]) -> Dict[str, str]: | |
| """ | |
| Get descriptions for columns using a single batched semantic search. | |
| One retrieval call is made per invocation (not per column), then results | |
| are matched back to the requested columns by substring lookup. Results | |
| are memoised in `st.session_state.area_column_descriptions`. | |
| """ | |
| cached = st.session_state.area_column_descriptions | |
| uncached = [col for col in columns if col not in cached] | |
| # Fast path: everything cached | |
| if not uncached: | |
| return {col: cached.get(col, "") for col in columns} | |
| active_dicts = [ | |
| d['name'] | |
| for d in self.data_dictionary_service.get_all_dictionaries() | |
| if d.get('active', True) | |
| ] | |
| if not active_dicts: | |
| logger.warning("No active data dictionaries for column description lookup") | |
| return {col: "" for col in columns} | |
| # One batched search covering every uncached column name | |
| query = "column definitions: " + ", ".join(uncached) | |
| try: | |
| results = self.retrieval_service.search( | |
| query, | |
| active_dicts, | |
| top_k=min(max(len(uncached) * 3, 10), 60), | |
| disable_embeddings=False, | |
| ) | |
| except Exception as e: | |
| logger.error(f"Batched column description search failed: {e}") | |
| results = [] | |
| logger.info( | |
| f"Batched description search: {len(uncached)} columns, " | |
| f"{len(results)} chunks returned" | |
| ) | |
| # Match each column to the highest-ranked chunk that mentions it | |
| for col in uncached: | |
| col_lower = col.lower() | |
| col_spaces = col.replace('_', ' ').lower() | |
| matched_text = "" | |
| for r in results: | |
| text = r.get('text', '') | |
| text_lower = text.lower() | |
| if col_lower in text_lower or col_spaces in text_lower: | |
| matched_text = text.strip() | |
| break | |
| if matched_text and len(matched_text) > DESCRIPTION_MAX_CHARS: | |
| matched_text = matched_text[: DESCRIPTION_MAX_CHARS - 3] + "..." | |
| cached[col] = matched_text | |
| st.session_state.area_column_descriptions = cached | |
| return {col: cached.get(col, "") for col in columns} | |
| def _show_debug_info(self, dataset_results: Dict, context: str, relevant_columns: Dict[str, List[str]] = None): | |
| """ | |
| Show debug information in an expander. | |
| Args: | |
| dataset_results: Query results from datasets | |
| context: Built context string | |
| relevant_columns: Relevant columns found for user query | |
| """ | |
| with st.expander("🔍 Show debug information"): | |
| st.caption("**Dataset Query Results:**") | |
| if dataset_results: | |
| for ds_name, data in dataset_results.items(): | |
| st.caption(f"📊 {ds_name}: {data['row_count']} rows, {len(data['columns'])} columns") | |
| else: | |
| st.caption("No data found for this ZIP code") | |
| if relevant_columns: | |
| st.caption("**Relevant Columns Selected:**") | |
| for ds_name, cols in relevant_columns.items(): | |
| st.caption(f" {ds_name}: {', '.join(cols)}") | |
| st.caption("**Context sent to LLM:**") | |
| st.code( | |
| context[:CONTEXT_PREVIEW_CHARS] | |
| + ("...[truncated]" if len(context) > CONTEXT_PREVIEW_CHARS else ""), | |
| language="markdown", | |
| ) | |
| st.caption("**Cached Column Descriptions:**") | |
| st.json(st.session_state.area_column_descriptions) | |
| def _reset_area_chat(self): | |
| """Reset all area chat session state.""" | |
| st.session_state.area_chat_history = [] | |
| st.session_state.area_current_zip = None | |
| st.session_state.area_current_name = None | |
| st.session_state.area_chat_started = False | |
| st.session_state.area_no_data_warning = False | |
| st.session_state.area_column_descriptions = {} | |
| st.session_state.area_show_recommendations = False | |
| st.session_state.area_recommendations = None | |
| if 'area_nearby_zips' in st.session_state: | |
| del st.session_state.area_nearby_zips | |
| logger.info("Area chat reset") | |