File size: 6,308 Bytes
da04fb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import streamlit as st
import google.generativeai as genai
from datetime import datetime
import requests
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure Gemini
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))

# Set up the model
generation_config = {
    "temperature": 0.9,
    "top_p": 1,
    "top_k": 1,
    "max_output_tokens": 2048,
}

safety_settings = [
    {
        "category": "HARM_CATEGORY_HARASSMENT",
        "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
]

model = genai.GenerativeModel(
    model_name="gemini-1.5-flash",
    generation_config=generation_config,
    safety_settings=safety_settings
)

# Function to perform web search (using SerpAPI)
def search_web(query):
    try:
        api_key = os.getenv("SERPAPI_KEY")
        if not api_key:
            return None
            
        params = {
            'q': query,
            'api_key': api_key,
            'engine': 'google'
        }
        
        response = requests.get('https://serpapi.com/search', params=params)
        results = response.json()
        
        if 'organic_results' in results:
            return results['organic_results'][:3]  # Return top 3 results
        return None
    except Exception as e:
        st.error(f"Search error: {e}")
        return None

# Initialize chat history
if "messages" not in st.session_state:
    st.session_state.messages = [
        {
            "role": "assistant", 
            "content": "Hello! I'm Gemini AI with web search capabilities. How can I help you today?",
            "timestamp": datetime.now().strftime("%H:%M")
        }
    ]

# App title and sidebar
st.set_page_config(page_title="Gemini AI Chatbot", page_icon="πŸ€–")
st.title("πŸ’Ž Gemini AI Chatbot")
st.caption("Powered by Gemini 1.5 Flash with web search capabilities")

# Sidebar controls
with st.sidebar:
    st.header("Settings")
    web_search = st.toggle("Enable Web Search", value=True)
    st.divider()
    if st.button("New Chat"):
        st.session_state.messages = [
            {
                "role": "assistant", 
                "content": "Hello! I'm Gemini AI with web search capabilities. How can I help you today?",
                "timestamp": datetime.now().strftime("%H:%M")
            }
        ]
    st.divider()
    st.markdown("### About")
    st.markdown("This chatbot uses Google's Gemini 1.5 Flash model and can perform web searches when enabled.")

# Display chat messages
for message in st.session_state.messages:
    avatar = "πŸ€–" if message["role"] == "assistant" else "πŸ‘€"
    with st.chat_message(message["role"], avatar=avatar):
        st.markdown(message["content"])
        if "search_results" in message:
            st.divider()
            st.markdown("**Web Search Results**")
            for result in message["search_results"]:
                with st.expander(result.get("title", "No title")):
                    st.markdown(f"**Snippet:** {result.get('snippet', 'No snippet available')}")
                    st.markdown(f"**Link:** [{result.get('link', 'No link')}]({result.get('link', '#')})")
        st.caption(f"{message['timestamp']} β€’ {message['role'].capitalize()}")

# Accept user input
if prompt := st.chat_input("Ask me anything..."):
    # Add user message to chat history
    st.session_state.messages.append({
        "role": "user", 
        "content": prompt,
        "timestamp": datetime.now().strftime("%H:%M")
    })
    
    # Display user message
    with st.chat_message("user", avatar="πŸ‘€"):
        st.markdown(prompt)
        st.caption(f"{datetime.now().strftime('%H:%M')} β€’ User")
    
    # Display assistant response
    with st.chat_message("assistant", avatar="πŸ€–"):
        message_placeholder = st.empty()
        full_response = ""
        
        # If web search is enabled, perform search first
        search_results = None
        if web_search:
            with st.spinner("Searching the web..."):
                search_results = search_web(prompt)
        
        # Generate response from Gemini
        with st.spinner("Thinking..."):
            try:
                # Prepare the prompt
                chat_prompt = prompt
                if search_results:
                    chat_prompt += "\n\nHere are some web search results to help with your response:\n"
                    for i, result in enumerate(search_results, 1):
                        chat_prompt += f"\n{i}. {result.get('title', 'No title')}\n{result.get('snippet', 'No snippet')}\n"
                
                # Get response from Gemini
                response = model.generate_content(chat_prompt)
                
                # Stream the response
                for chunk in response.text.split(" "):
                    full_response += chunk + " "
                    message_placeholder.markdown(full_response + "β–Œ")
                message_placeholder.markdown(full_response)
                
            except Exception as e:
                full_response = f"Sorry, I encountered an error: {str(e)}"
                message_placeholder.markdown(full_response)
        
        # Display search results if available
        if search_results:
            st.divider()
            st.markdown("**Web Search Results**")
            for result in search_results:
                with st.expander(result.get("title", "No title")):
                    st.markdown(f"**Snippet:** {result.get('snippet', 'No snippet available')}")
                    st.markdown(f"**Link:** [{result.get('link', 'No link')}]({result.get('link', '#')})")
        
        st.caption(f"{datetime.now().strftime('%H:%M')} β€’ Assistant")
    
    # Add assistant response to chat history
    st.session_state.messages.append({
        "role": "assistant", 
        "content": full_response,
        "timestamp": datetime.now().strftime("%H:%M"),
        "search_results": search_results if search_results else None
    })