import streamlit as st from openai import OpenAI from crewai import Agent, Task, Crew, Process from crewai_tools import SerperDevTool, WebsiteSearchTool import os import time import re import requests from bs4 import BeautifulSoup from langchain_community.document_loaders import WebBaseLoader from urllib.parse import urlparse from langchain_community.document_loaders import TextLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings from langchain_core.documents import Document as LangchainDocument from langchain.chains import RetrievalQA from langchain_openai import ChatOpenAI st.set_page_config( page_title="SeniorMatch - Elder Engage", page_icon="👵👴", layout="wide" ) # Create a debug expander at the top of your app (optional location) debug_expander = st.expander("Debug Information", expanded=False) st.title("✨ SeniorMatch: Activities & Resources for Seniors") st.markdown("*Connecting seniors to social activities, volunteer opportunities, and community engagement*") # Initialize session state for knowledge base if 'knowledge_base' not in st.session_state: st.session_state.knowledge_base = None if 'knowledge_files' not in st.session_state: st.session_state.knowledge_files = [] def is_valid_url(url): """Check if the URL is valid.""" try: result = urlparse(url) return all([result.scheme, result.netloc]) except: return False def fetch_content_from_url(url): """Fetch content from URL and return as text.""" try: response = requests.get(url, timeout=10) response.raise_for_status() # Raise exception for 4XX/5XX responses # Parse HTML content soup = BeautifulSoup(response.text, 'html.parser') # Remove script and style elements for script in soup(["script", "style"]): script.decompose() # Extract text text = soup.get_text(separator='\n') # Clean up text (remove extra whitespace) lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) text = '\n'.join(chunk for chunk in chunks if chunk) return text except Exception as e: return f"Error fetching content: {str(e)}" def create_url_rag_documents(urls): """Create RAG documents from a list of URLs using LangChain WebBaseLoader.""" langchain_docs = [] for url in urls: if not is_valid_url(url): st.warning(f"Invalid URL format: {url}") continue try: # Use LangChain's WebBaseLoader to load the content loader = WebBaseLoader(url) documents = loader.load() # Each document already contains the source URL in metadata langchain_docs.extend(documents) except Exception as e: st.error(f"Error processing URL {url}: {str(e)}") return langchain_docs def add_url_to_knowledge_base(urls, existing_vectorstore=None): """Add URLs to the knowledge base.""" # Create documents from URLs url_docs = create_url_rag_documents(urls) if not url_docs: return existing_vectorstore, "No valid documents created from URLs." # Split text into chunks text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200 ) all_splits = text_splitter.split_documents(url_docs) # Create embeddings embeddings = OpenAIEmbeddings() # If we have an existing vectorstore, add to it if existing_vectorstore: existing_vectorstore.add_documents(all_splits) return existing_vectorstore, f"Added {len(url_docs)} URLs to existing knowledge base." else: # Create new vectorstore vectorstore = Chroma.from_documents( documents=all_splits, embedding=embeddings, persist_directory="./chroma_db" ) return vectorstore, f"Created new knowledge base with {len(url_docs)} URLs." def validate_and_preprocess_urls(urls): """Validate URLs and provide detailed feedback.""" valid_urls = [] feedback = [] for url in urls: # Check if URL has scheme if not url.startswith(('http://', 'https://')): modified_url = f"https://{url}" feedback.append(f"Added https:// to {url}") url = modified_url # Validate URL if is_valid_url(url): valid_urls.append(url) else: feedback.append(f"Skipped invalid URL: {url}") return valid_urls, feedback def preview_url_content(url, max_length=300): """Fetch and display a preview of the URL content.""" try: text = fetch_content_from_url(url) if text.startswith("Error fetching content"): return text # Return a truncated preview preview = text[:max_length] + "..." if len(text) > max_length else text return preview except Exception as e: return f"Error previewing content: {str(e)}" def check_url_accessibility(urls): """Check if URLs are accessible and return status.""" results = [] for url in urls: try: response = requests.head(url, timeout=5) if response.status_code < 400: results.append((url, True, response.status_code)) else: results.append((url, False, response.status_code)) except Exception as e: results.append((url, False, str(e))) return results def extract_urls(text): """Extract URLs from text content.""" url_pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+' urls = re.findall(url_pattern, text) return urls def create_rag_knowledge_base(documents): """Create a RAG knowledge base using LangChain with URL extraction.""" # Initialize a list to store LangChain documents langchain_docs = [] # Process and add documents to the collection for doc in documents: try: # Create LangChain Document from the uploaded file content content = doc.getvalue().decode('utf-8') # Extract URLs from the content urls = extract_urls(content) url_string = "\n".join(urls) if urls else "" # Add extracted URLs to metadata metadata = { "source": doc.name, "urls": url_string } langchain_docs.append( LangchainDocument( page_content=content, metadata=metadata ) ) except Exception as e: st.error(f"Error processing document {doc.name}: {str(e)}") # Split text into chunks text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200 ) all_splits = text_splitter.split_documents(langchain_docs) # Preserve URLs in metadata when splitting for split_doc in all_splits: if "urls" not in split_doc.metadata and "source" in split_doc.metadata: # Find the original document to get URLs for doc in langchain_docs: if doc.metadata["source"] == split_doc.metadata["source"]: split_doc.metadata["urls"] = doc.metadata.get("urls", "") break # Create embeddings and vector store embeddings = OpenAIEmbeddings() # Create and persist vector store vectorstore = Chroma.from_documents( documents=all_splits, embedding=embeddings, persist_directory="./chroma_db" ) return vectorstore def query_knowledge_base(vectorstore, query, openai_api_key): """Query the knowledge base with RAG using LangChain.""" # Set up OpenAI for embeddings and completion os.environ["OPENAI_API_KEY"] = openai_api_key # Create a retriever from the vector store retriever = vectorstore.as_retriever(search_kwargs={"k": 3}) # Create a ChatOpenAI model llm = ChatOpenAI(model_name="gpt-3.5-turbo") # Create a chain to retrieve and then answer the question qa_chain = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True ) # Build the prompt augmented_query = f""" Based on the following information about senior activities and resources, please provide relevant suggestions for a senior interested in: {query} Focus on specific activities, locations, or resources mentioned in the context. If available, include direct URLs to resources. """ # Generate response result = qa_chain.invoke({"query": augmented_query}) # Check if we have any results if not result or not result.get("result"): return "No relevant information found in the knowledge base. Proceeding with general search." # Extract URLs from source documents source_urls = [] if "source_documents" in result: for doc in result["source_documents"]: if "urls" in doc.metadata and doc.metadata["urls"]: urls = doc.metadata["urls"].split("\n") source_urls.extend(urls) # Add URLs to the result if available final_result = result["result"] if source_urls: final_result += "\n\nRelevant Resources:\n" for i, url in enumerate(set(source_urls), 1): # Using set to remove duplicates final_result += f"{i}. {url}\n" return final_result def get_result(user_prompt, age_group, zip_code, mobility, serper_api_key, openai_api_key, collection=None): """Get activity recommendations for seniors with optimized performance.""" from urllib.parse import quote # Set environment variables for API keys - do this once outside the function # if possible to avoid setting them on every call os.environ["OPENAI_API_KEY"] = openai_api_key os.environ["SERPER_API_KEY"] = serper_api_key # Validate API keys first with a simple check rather than waiting for API calls to fail if not openai_api_key or not serper_api_key: missing = [] if not openai_api_key: missing.append("OpenAI") if not serper_api_key: missing.append("Serper") raise ValueError(f"{', '.join(missing)} API key(s) not set properly") # Prepare context string placeholder context_str = "" # Query knowledge base asynchronously if available if collection: try: # Use a placeholder message while query runs kb_placeholder = st.empty() kb_placeholder.info("Checking knowledge base...") # Query knowledge base rag_results = query_knowledge_base(collection, user_prompt, openai_api_key) if rag_results and rag_results.strip(): kb_placeholder.success("Found relevant information in knowledge base") context_str = f"Knowledge base information: {rag_results}" else: kb_placeholder.info("No matching information in knowledge base") except Exception as e: st.warning(f"Knowledge base query failed: {str(e)}") # Create both agents immediately - no need to wait sequentially # Define the core details once to ensure consistency and reduce duplication base_context = f"Age: {age_group}, Mobility: {mobility}, Zipcode: {zip_code}, Interest: {user_prompt}" # Create agents with more focused prompts researcher = Agent( name="Senior Activities Researcher", role="Elderly Support Specialist", goal=f"Find appropriate activities for seniors in zipcode {zip_code}", backstory=f"You find accessible activities for seniors with {mobility} mobility. Context: {base_context}", tools=[WebsiteSearchTool(), SerperDevTool()], verbose=True # Keep verbose=False to reduce overhead ) writer = Agent( name="Senior Engagement Specialist", role="Elderly Care Advisor", goal="Provide clear, accessible senior activity recommendations", backstory=f"You create personalized recommendations for seniors. Context: {base_context}", verbose=True ) # Streamline task descriptions - more concise prompts often work better research_task = Task( description=f"Find senior activities related to: {user_prompt} in zipcode {zip_code}. Mobility: {mobility}, Age: {age_group}. {context_str}", expected_output="Provide 5-7 accessible activities with links, transportation options, and accessibility details.", agent=researcher ) write_task = Task( description=f"Select the best activities for a senior with {mobility} mobility interested in {user_prompt}. {context_str}", expected_output="Provide 3-5 recommendations with: benefits, accessibility info, transportation, instructions, event date time and direct links.", agent=writer, context=[research_task] ) # Streamline crew with minimal configuration crew = Crew( agents=[researcher, writer], tasks=[research_task, write_task], process=Process.sequential, verbose=False # Set to False to reduce logging overhead ) result = crew.kickoff() return result def dummy_extract_activity_details(result_text): """Extract structured activity details from the result text.""" # Format activity details activity_details = [] for i in range(1): # Limit to 5 activities # Clean up the activity title title = "Want to meet up " location = "Saratoga wildwood park" # Extract date/time if available time = "Sunday 12:00 pm" activity_details.append({ "title": title, "location": location, "time": time, "full_text": result_text }) return activity_details def extract_activity_details(result_text): """Extract structured activity details from the result text.""" import re # Look for activity sections (numbered or with headings) activity_pattern = r'(?:(?:\d+\.\s+)|(?:#+\s+))([^\n]+)' activities = re.findall(activity_pattern, result_text) # If no activities found with pattern, try splitting by double newlines if not activities: paragraphs = result_text.split('\n\n') activities = [p.strip() for p in paragraphs if len(p.strip()) > 10][:5] # Limit to 5 activities # Format activity details activity_details = [] for activity in activities[:5]: # Limit to 5 activities # Clean up the activity title title = activity.strip() if len(title) > 50: title = title[:47] + "..." # Extract location if available location_match = re.search(r'location:\s*([^\n]+)', result_text, re.IGNORECASE) location = location_match.group(1) if location_match else "" # Extract date/time if available time_match = re.search(r'(?:date|time|when):\s*([^\n]+)', result_text, re.IGNORECASE) time = time_match.group(1) if time_match else "" activity_details.append({ "title": title, "location": location, "time": time, "full_text": result_text }) return activity_details def create_whatsapp_share_button(activity, index): """Create a WhatsApp share button for an activity.""" from urllib.parse import quote # Create a formatted message message = f"Join me for this senior activity: {activity['title']}" if activity['location']: message += f"\nLocation: {activity['location']}" if activity['time']: message += f"\nWhen: {activity['time']}" message += "\n\nLet me know if you're interested!" # Create the WhatsApp deep link whatsapp_link = f"https://wa.me/?text={quote(message)}" # Create a button to open the WhatsApp share dialog col1, col2 = st.columns([3, 1]) with col1: st.write(f"**{index}. {activity['title']}**") with col2: st.markdown(f"[]({whatsapp_link})") # Add option to create a group if st.button(f"Create WhatsApp group for Activity {index}", key=f"group_{index}"): group_name = f"Senior Activity - {activity['title'][:20]}" group_desc = f"Group for coordinating {activity['title']}" # WhatsApp doesn't have a direct API for creating groups, so we'll use the next best option message = f"I want to create a group named '{group_name}' for this activity. Who wants to join?" group_link = f"https://wa.me/?text={quote(message)}" st.markdown(f"Opening WhatsApp to create group. [Click here if it doesn't open automatically]({group_link})") st.markdown(f""" """, unsafe_allow_html=True) def open_ai_chat(user_prompt, api_key): # Set the API key explicitly for OpenAI os.environ["OPENAI_API_KEY"] = api_key # Create client with the API key client = OpenAI(api_key=api_key) try: response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": user_prompt} ] ) return response.choices[0].message.content except Exception as e: st.error(f"OpenAI API Error: {str(e)}") return "Could not generate additional tips. Please check your API key." # App UI st.sidebar.header("API Keys") # Use session state to preserve API keys if 'user_api_key' not in st.session_state: st.session_state.user_api_key = '' if 'serper_api_key' not in st.session_state: st.session_state.serper_api_key = '' if 'youtube_api_key' not in st.session_state: st.session_state.youtube_api_key = '' # Modified to use environment variables if available user_api_key = st.sidebar.text_input("Enter your OpenAI API key", type="password", value=st.session_state.user_api_key or os.environ.get("OPENAI_API_KEY", ""), help="Required for agents and additional tips") serper_api_key = st.sidebar.text_input("Enter your Serper API key", type="password", value=st.session_state.serper_api_key or os.environ.get("SERPER_API_KEY", ""), help="Required for web search functionality") youtube_api_key = st.sidebar.text_input("Enter your YouTube API key", type="password", value=st.session_state.youtube_api_key or os.environ.get("YOUTUBE_API_KEY", ""), help="Optional: Enhances video search results") # Store API keys in session state st.session_state.user_api_key = user_api_key st.session_state.serper_api_key = serper_api_key st.session_state.youtube_api_key = youtube_api_key # Verify API keys format if user_api_key: if not user_api_key.startswith('sk-'): st.sidebar.warning("OpenAI API key should start with 'sk-'") # Add API key instructions with st.sidebar.expander("How to get API keys"): st.markdown(""" **OpenAI API Key:** 1. Go to [OpenAI Platform](https://platform.openai.com/) 2. Sign up or log in 3. Navigate to API keys section 4. Create a new secret key **Serper API Key:** 1. Go to [Serper.dev](https://serper.dev/) 2. Sign up or log in 3. Find your API key in the dashboard """) # Knowledge base section in sidebar st.sidebar.markdown("---") st.sidebar.header("Knowledge Base") st.sidebar.markdown("Upload documents about senior activities and resources") # File uploader for knowledge base uploaded_files = st.sidebar.file_uploader("Upload documents (txt, pdf, csv)", type=["txt", "pdf", "csv"], accept_multiple_files=True) # URL knowledge base section st.sidebar.markdown("---") st.sidebar.header("URL Knowledge Base") st.sidebar.markdown("Add URLs with information about senior activities and resources") # Initialize session state for URLs if 'url_list' not in st.session_state: st.session_state.url_list = [] # Text input for adding URLs new_url = st.sidebar.text_input("Enter URL to add to knowledge base", help="Add websites containing relevant senior activities information") # Button to add URL to the list if st.sidebar.button("Add URL") and new_url: if is_valid_url(new_url): if new_url not in st.session_state.url_list: st.session_state.url_list.append(new_url) st.sidebar.success(f"Added URL: {new_url}") else: st.sidebar.warning(f"URL already in list: {new_url}") else: st.sidebar.error("Invalid URL format. Please include http:// or https://") # Display current URLs and ability to remove them if st.session_state.url_list: st.sidebar.markdown("### Current URLs:") for i, url in enumerate(st.session_state.url_list): col1, col2 = st.sidebar.columns([4, 1]) col1.text(f"{i+1}. {url[:30]}..." if len(url) > 30 else f"{i+1}. {url}") if col2.button("❌", key=f"remove_{i}"): st.session_state.url_list.pop(i) st.experimental_rerun() # Button to create knowledge base from URLs if st.sidebar.button("Create URL Knowledge Base"): with st.sidebar: with st.spinner("Creating knowledge base from URLs..."): try: # If existing knowledge base, update it; otherwise create new vectorstore, message = add_url_to_knowledge_base( st.session_state.url_list, st.session_state.knowledge_base ) st.session_state.knowledge_base = vectorstore st.success(f"✅ {message}") # Update knowledge files list to include URLs if 'knowledge_files' not in st.session_state: st.session_state.knowledge_files = [] # Add URLs to knowledge files list (if not already there) for url in st.session_state.url_list: url_label = f"URL: {url[:30]}..." if len(url) > 30 else f"URL: {url}" if url_label not in st.session_state.knowledge_files: st.session_state.knowledge_files.append(url_label) except Exception as e: st.error(f"Error creating knowledge base from URLs: {str(e)}") # Button to create knowledge base if uploaded_files and st.sidebar.button("Create Knowledge Base"): with st.sidebar: with st.spinner("Creating knowledge base..."): try: st.session_state.knowledge_base = create_rag_knowledge_base(uploaded_files) st.session_state.knowledge_files = [file.name for file in uploaded_files] st.success(f"✅ Knowledge base created with {len(uploaded_files)} documents") except Exception as e: st.error(f"Error creating knowledge base: {str(e)}") # Display knowledge base status if st.session_state.knowledge_base: st.sidebar.info(f"Knowledge base active with {len(st.session_state.knowledge_files)} documents") for file in st.session_state.knowledge_files: st.sidebar.text(f"- {file}") # Test connection button if st.sidebar.button("Test API Connections"): with st.sidebar: if not user_api_key or not serper_api_key: st.error("Please enter both required API keys") else: with st.spinner("Testing connections..."): try: # Test OpenAI connection os.environ["OPENAI_API_KEY"] = user_api_key client = OpenAI(api_key=user_api_key) client.models.list() st.success("✅ OpenAI connection successful") except Exception as e: st.error(f"❌ OpenAI connection failed: {str(e)}") try: os.environ["SERPER_API_KEY"] = serper_api_key st.success("✅ Serper API key set correctly") except Exception as e: st.error(f"❌ Serper API key error: {str(e)}") # Create tabs for different sections tab1, tab2, tab3 = st.tabs(["Find Activities", "About the App", "URL Preview"]) # Then add the URL preview tab content with tab3: st.header("URL Content Preview") st.markdown("Preview the content from URLs before adding them to your knowledge base.") preview_url = st.text_input("Enter a URL to preview") if st.button("Preview Content") and preview_url: with st.spinner("Fetching content..."): if is_valid_url(preview_url): # Check accessibility accessibility = check_url_accessibility([preview_url]) if accessibility[0][1]: # If accessible # Get content preview preview = preview_url_content(preview_url, max_length=500) st.success(f"URL is accessible (Status code: {accessibility[0][2]})") # Display preview in expandable section with st.expander("Content Preview", expanded=True): st.markdown(preview) # Add to knowledge base button if st.button("Add to URL Knowledge Base"): if preview_url not in st.session_state.url_list: st.session_state.url_list.append(preview_url) st.success(f"Added URL: {preview_url}") else: st.info(f"URL already in list: {preview_url}") else: st.error(f"URL is not accessible. Error: {accessibility[0][2]}") else: st.error("Invalid URL format. Please include http:// or https://") with tab1: st.header("Senior Information") st.markdown("Please provide information to help find appropriate activities and resources.") col1, col2 = st.columns(2) with col1: age_group = st.text_input("Enter your age") zip_code = st.text_input("Enter your zip code") with col2: mobility = st.selectbox("Mobility level:", ["Fully mobile", "Some limitations", "Limited mobility", "Requires assistance"]) user_prompt = st.text_area("What activities or interests would you like to explore?", height=100) st.caption("Examples: gardening, book clubs, gentle exercise, music, crafts, technology learning") st.markdown("---") # Initialize session state for tracking errors if not already initialized if 'api_error' not in st.session_state: st.session_state.api_error = False if st.button("Find Activities", type="primary"): if not user_prompt: st.warning("Please enter your interests.") elif not user_api_key: st.warning("Please enter your OpenAI API key.") elif not serper_api_key: st.warning("Please enter your Serper API key.") else: with st.spinner("Finding activities for you..."): try: st.subheader("Results:") # Set API keys in environment variables os.environ["OPENAI_API_KEY"] = user_api_key os.environ["SERPER_API_KEY"] = serper_api_key if youtube_api_key: os.environ["YOUTUBE_API_KEY"] = youtube_api_key # Add a small delay to ensure environment variables are set time.sleep(0.5) try: # Include knowledge base if available result = get_result(user_prompt, age_group, zip_code, mobility, serper_api_key, user_api_key, collection=st.session_state.knowledge_base) st.session_state.api_error = False except Exception as e: st.error(f"CrewAI Error: {str(e)}") st.session_state.api_error = True st.stop() # Format the result with better styling st.markdown("## Recommended Activities") st.markdown(f"""