import os import time import streamlit as st from dotenv import load_dotenv, find_dotenv from langchain_openai import ChatOpenAI from langchain_community.tools.tavily_search import TavilySearchResults from langgraph.prebuilt import create_react_agent from langchain_core.messages import HumanMessage # Set page configuration - MUST BE THE FIRST STREAMLIT COMMAND st.set_page_config( page_title="AI Search Assistant", page_icon="🔍", layout="wide", initial_sidebar_state="expanded" ) # Load environment variables (for local development) _ = load_dotenv(find_dotenv()) # Initialize session state for API keys if not already present if "openai_api_key" not in st.session_state: st.session_state.openai_api_key = os.getenv('OPENAI_API_KEY', '') if "tavily_api_key" not in st.session_state: st.session_state.tavily_api_key = os.getenv('TAVILY_API_KEY', '') if "api_keys_valid" not in st.session_state: st.session_state.api_keys_valid = False if "messages" not in st.session_state: st.session_state.messages = [] if "thinking" not in st.session_state: st.session_state.thinking = False # Custom CSS for a more professional look st.markdown(""" """, unsafe_allow_html=True) # App title and description st.markdown('

🔍 AI Search Assistant

', unsafe_allow_html=True) # Create tabs for different sections tabs = st.tabs(["🤖 Chat", "â„šī¸ About", "đŸ› ī¸ Settings"]) with tabs[0]: # Chat Tab if st.session_state.api_keys_valid: # Chat interface st.markdown('

Ask me anything

', unsafe_allow_html=True) # Query input with dynamic placeholder placeholders = [ "e.g., What are the latest developments in AI?", "e.g., Tell me about recent movies in 2025", "e.g., What are the best tourist spots in Japan?", "e.g., How does quantum computing work?", "e.g., What are the trending technologies in 2025?" ] import random query = st.text_input("", placeholder=random.choice(placeholders), key="query_input") # Buttons col1, col2 = st.columns([1, 5]) with col1: search_button = st.button("🔍 Search", use_container_width=True) with col2: clear_button = st.button("đŸ—‘ī¸ Clear Chat", use_container_width=False, key="clear_button") st.markdown('
', unsafe_allow_html=True) # Chat container st.markdown('

Conversation

', unsafe_allow_html=True) chat_container = st.container(height=500) # Process the query when submitted if query and search_button: # Add user message to chat history st.session_state.messages.append({"role": "user", "content": query}) st.session_state.thinking = True # Force a rerun to show the user message immediately st.experimental_rerun() # Display chat messages with chat_container: if not st.session_state.messages: st.info("👋 Hello! Ask me anything and I'll search the web for answers.") for message in st.session_state.messages: if message["role"] == "user": st.markdown(f"""
user
{message["content"]}
""", unsafe_allow_html=True) else: st.markdown(f"""
assistant
{message["content"]}
""", unsafe_allow_html=True) # Show thinking animation if st.session_state.thinking: st.markdown(f"""
assistant

Thinking...

""", unsafe_allow_html=True) try: # Set API keys from session state os.environ["OPENAI_API_KEY"] = st.session_state.openai_api_key os.environ["TAVILY_API_KEY"] = st.session_state.tavily_api_key # Get the last user message last_user_message = next((msg["content"] for msg in reversed(st.session_state.messages) if msg["role"] == "user"), None) if last_user_message: # Get model and max results from session state model_name = st.session_state.get("model_name", "gpt-3.5-turbo-0125") max_results = st.session_state.get("max_results", 3) # Initialize the model and tools chat_model = ChatOpenAI(model=model_name) search = TavilySearchResults(max_results=max_results) tools = [search] # Create the agent agent_executor = create_react_agent(chat_model, tools) # Execute the agent response = agent_executor.invoke({"messages": [HumanMessage(content=last_user_message)]}) # Extract the final AI response ai_message = response['messages'][-1].content # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": ai_message}) except Exception as e: # Add error message to chat history error_message = f"Sorry, I encountered an error: {str(e)}" st.session_state.messages.append({"role": "assistant", "content": error_message}) # Turn off thinking animation st.session_state.thinking = False # Force a rerun to update the chat with the response st.experimental_rerun() # Clear conversation when button is clicked if clear_button: st.session_state.messages = [] st.experimental_rerun() else: # Welcome message if API keys are not yet provided st.info("👈 Please enter your API keys in the Settings tab to get started") # Example of what the app can do st.markdown('

What can this AI assistant do?

', unsafe_allow_html=True) # Feature cards col1, col2 = st.columns(2) with col1: st.markdown("""

🌐 Real-time Web Search

Get up-to-date information from across the internet on any topic.

The assistant uses Tavily's powerful search API to find relevant and current information.

""", unsafe_allow_html=True) st.markdown("""

🧠 Powered by Advanced AI

Utilizes OpenAI's powerful language models to understand questions and generate helpful responses.

Choose between different models based on your needs.

""", unsafe_allow_html=True) with col2: st.markdown("""

đŸ’Ŧ Natural Conversation

Have a flowing conversation with follow-up questions and contextual responses.

The chat history is maintained throughout your session.

""", unsafe_allow_html=True) st.markdown("""

📊 Customizable Results

Adjust the number of search results to balance between comprehensive information and response speed.

Configure the AI model to suit your specific needs.

""", unsafe_allow_html=True) with tabs[1]: # About Tab st.markdown('

About AI Search Assistant

', unsafe_allow_html=True) st.markdown(""" This application combines the power of large language models with real-time web search capabilities to provide you with up-to-date information on any topic. ### How It Works 1. **User Input**: You ask a question or request information on any topic 2. **Web Search**: The app searches the internet using Tavily's search API 3. **AI Processing**: OpenAI's language model processes the search results 4. **Response Generation**: The AI generates a comprehensive, informative response ### Technologies Used - **Frontend**: Streamlit - **AI**: OpenAI GPT models - **Search**: Tavily Search API - **Framework**: LangChain and LangGraph ### Privacy & Security - Your API keys are stored only in your browser's session - Keys are never saved to our servers - Each user must provide their own API keys """) # Example use cases st.markdown('

Example Use Cases

', unsafe_allow_html=True) use_cases = [ { "title": "Research Assistant", "description": "Get summaries and insights on academic topics, current events, or historical information.", "example": "What are the latest developments in quantum computing?" }, { "title": "Current Events", "description": "Stay updated on news, sports, entertainment, and global happenings.", "example": "What major events happened this week in technology?" }, { "title": "Learning Tool", "description": "Explain complex concepts in an easy-to-understand manner.", "example": "Explain machine learning algorithms to a beginner." }, { "title": "Travel Planning", "description": "Get information about destinations, attractions, and travel tips.", "example": "What are the must-visit places in Tokyo?" } ] cols = st.columns(2) for i, use_case in enumerate(use_cases): with cols[i % 2]: st.markdown(f"""

{use_case['title']}

{use_case['description']}

Example: "{use_case['example']}"

""", unsafe_allow_html=True) with tabs[2]: # Settings Tab st.markdown('

API Configuration

', unsafe_allow_html=True) # API key input section with better UX with st.form("api_form", clear_on_submit=False): st.markdown(""" To use this application, you need to provide your own API keys for OpenAI and Tavily. These keys are stored only in your browser session and are never saved on our servers. """) # Get API keys from session state or user input openai_api_key = st.text_input( "OpenAI API Key", value=st.session_state.openai_api_key, type="password", help="Get your API key from https://platform.openai.com/api-keys" ) tavily_api_key = st.text_input( "Tavily API Key", value=st.session_state.tavily_api_key, type="password", help="Get your API key from https://tavily.com/#api" ) col1, col2 = st.columns([1, 3]) with col1: submitted = st.form_submit_button("Save API Keys", use_container_width=True) if submitted: if not openai_api_key or not tavily_api_key: st.error("Please provide both API keys") else: # Save API keys to session state st.session_state.openai_api_key = openai_api_key st.session_state.tavily_api_key = tavily_api_key st.session_state.api_keys_valid = True st.success("✅ API keys saved successfully!") # Only show these settings if API keys are provided if st.session_state.api_keys_valid: st.markdown('

Search Settings

', unsafe_allow_html=True) col1, col2 = st.columns(2) with col1: # Model selection model_options = { "gpt-3.5-turbo-0125": "GPT-3.5 Turbo (Faster, Lower Cost)", "gpt-4-turbo-preview": "GPT-4 Turbo (More Capable, Higher Cost)" } selected_model = st.selectbox( "Select AI Model", options=list(model_options.keys()), format_func=lambda x: model_options[x], index=0, help="GPT-4 provides better results but costs more" ) # Save to session state st.session_state.model_name = selected_model with col2: # Number of search results max_results = st.slider( "Maximum Search Results", min_value=1, max_value=10, value=st.session_state.get("max_results", 3), help="More results provide more context but may slow down the response" ) # Save to session state st.session_state.max_results = max_results # Information section st.markdown('

How to Get API Keys

', unsafe_allow_html=True) col1, col2 = st.columns(2) with col1: st.markdown("""

OpenAI API Key

  1. Go to OpenAI and create an account
  2. Navigate to the API section
  3. Click on "Create new secret key"
  4. Copy the key and paste it in the form above
""", unsafe_allow_html=True) with col2: st.markdown("""

Tavily API Key

  1. Go to Tavily and create an account
  2. Navigate to the API dashboard
  3. Generate a new API key
  4. Copy the key and paste it in the form above
""", unsafe_allow_html=True) # Footer st.markdown(""" """, unsafe_allow_html=True)