# Create a simple chat 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 st.set_page_config( page_title="SeniorMatch - Elder Engage", page_icon="👵👴", layout="wide" ) st.title("✨ SeniorMatch: Activities & Resources for Seniors") st.markdown("*Connecting seniors to social activities, volunteer opportunities, and community engagement*") def get_result(user_prompt, age_group, zip_code, mobility, serper_api_key): # Double-check that API keys are set if "OPENAI_API_KEY" not in os.environ or not os.environ["OPENAI_API_KEY"]: raise ValueError("OpenAI API key is not set properly") if "SERPER_API_KEY" not in os.environ or not os.environ["SERPER_API_KEY"]: # Set the required API key for SerperDevTool if not already set os.environ["SERPER_API_KEY"] = serper_api_key researcher = Agent( name="Senior Activities Researcher", role="Elderly Support Specialist", goal=f"Find appropriate activities for a senior (Age: {age_group}, Mobility: {mobility}) in zipcode {zip_code}.", backstory="You are a compassionate elderly care specialist who understands the unique needs and interests of seniors. You find accessible, engaging activities that promote well-being and social connection.", tools=[WebsiteSearchTool(), SerperDevTool()], verbose=False ) writer = Agent( name="Senior Engagement Specialist", role="Elderly Care Advisor", goal="Provide clear, accessible activity recommendations that consider the physical capabilities, interests, and social needs of seniors.", backstory=f"You are a compassionate advisor for seniors who understands the challenges they face. You focus on activities that promote physical health, mental stimulation, and social connection while considering mobility limitations ({mobility}) and age-appropriate options for someone {age_group} years old.", verbose=False ) # Define tasks research_task = Task( description=f"Find senior-friendly activities, community resources, and online events related to: {user_prompt} in zipcode {zip_code}. Consider mobility level: {mobility} and age: {age_group}.", expected_output=f"Provide a mix of in-person and virtual activities suitable for seniors. Include senior centers, community classes, accessible events, and easy-to-follow online videos. For each suggestion, provide clear accessibility information, transportation options if available, and direct links. Ensure all activities are appropriate for someone with {mobility} mobility level.", agent=researcher ) write_task = Task( description=f"Select the most appropriate activities for a senior (Age: {age_group}, Mobility: {mobility}) interested in {user_prompt}. Include a mix of social, physical, and mental stimulation options.", expected_output="Provide 3-5 senior-friendly recommendations with detailed information on: \n1. Why this activity is beneficial for seniors \n2. Clear accessibility information \n3. Transportation options if needed \n4. Step-by-step instructions for participating \n5. Direct links to register or participate \n\nFormat the information in large, readable text with clear headings and simple instructions.", agent=writer, context=[research_task] ) crew = Crew( agents=[researcher, writer], tasks=[research_task, write_task], process=Process.sequential, verbose=True ) result = crew.kickoff() return result 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 = '' user_api_key = st.sidebar.text_input("Enter your OpenAI API key", type="password", value=st.session_state.user_api_key, help="Required for both CrewAI 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, 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, 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 """) # 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)}") # We can't easily test SerperDevTool without making a real query # Just set the environment variable to check format 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)}") st.header("Senior Information") st.markdown("Tell us about yourself so we can find the most appropriate activities and resources.") age_group = st.text_input("Enter your age") zip_code = st.text_input("Enter your zip code") 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: result = get_result(user_prompt, age_group, zip_code, mobility, serper_api_key) 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"""