memex-in commited on
Commit
da04fb3
Β·
verified Β·
1 Parent(s): a44cef6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -0
app.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import google.generativeai as genai
3
+ from datetime import datetime
4
+ import requests
5
+ import os
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables
9
+ load_dotenv()
10
+
11
+ # Configure Gemini
12
+ genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
13
+
14
+ # Set up the model
15
+ generation_config = {
16
+ "temperature": 0.9,
17
+ "top_p": 1,
18
+ "top_k": 1,
19
+ "max_output_tokens": 2048,
20
+ }
21
+
22
+ safety_settings = [
23
+ {
24
+ "category": "HARM_CATEGORY_HARASSMENT",
25
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
26
+ },
27
+ {
28
+ "category": "HARM_CATEGORY_HATE_SPEECH",
29
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
30
+ },
31
+ {
32
+ "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
33
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
34
+ },
35
+ {
36
+ "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
37
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
38
+ },
39
+ ]
40
+
41
+ model = genai.GenerativeModel(
42
+ model_name="gemini-1.5-flash",
43
+ generation_config=generation_config,
44
+ safety_settings=safety_settings
45
+ )
46
+
47
+ # Function to perform web search (using SerpAPI)
48
+ def search_web(query):
49
+ try:
50
+ api_key = os.getenv("SERPAPI_KEY")
51
+ if not api_key:
52
+ return None
53
+
54
+ params = {
55
+ 'q': query,
56
+ 'api_key': api_key,
57
+ 'engine': 'google'
58
+ }
59
+
60
+ response = requests.get('https://serpapi.com/search', params=params)
61
+ results = response.json()
62
+
63
+ if 'organic_results' in results:
64
+ return results['organic_results'][:3] # Return top 3 results
65
+ return None
66
+ except Exception as e:
67
+ st.error(f"Search error: {e}")
68
+ return None
69
+
70
+ # Initialize chat history
71
+ if "messages" not in st.session_state:
72
+ st.session_state.messages = [
73
+ {
74
+ "role": "assistant",
75
+ "content": "Hello! I'm Gemini AI with web search capabilities. How can I help you today?",
76
+ "timestamp": datetime.now().strftime("%H:%M")
77
+ }
78
+ ]
79
+
80
+ # App title and sidebar
81
+ st.set_page_config(page_title="Gemini AI Chatbot", page_icon="πŸ€–")
82
+ st.title("πŸ’Ž Gemini AI Chatbot")
83
+ st.caption("Powered by Gemini 1.5 Flash with web search capabilities")
84
+
85
+ # Sidebar controls
86
+ with st.sidebar:
87
+ st.header("Settings")
88
+ web_search = st.toggle("Enable Web Search", value=True)
89
+ st.divider()
90
+ if st.button("New Chat"):
91
+ st.session_state.messages = [
92
+ {
93
+ "role": "assistant",
94
+ "content": "Hello! I'm Gemini AI with web search capabilities. How can I help you today?",
95
+ "timestamp": datetime.now().strftime("%H:%M")
96
+ }
97
+ ]
98
+ st.divider()
99
+ st.markdown("### About")
100
+ st.markdown("This chatbot uses Google's Gemini 1.5 Flash model and can perform web searches when enabled.")
101
+
102
+ # Display chat messages
103
+ for message in st.session_state.messages:
104
+ avatar = "πŸ€–" if message["role"] == "assistant" else "πŸ‘€"
105
+ with st.chat_message(message["role"], avatar=avatar):
106
+ st.markdown(message["content"])
107
+ if "search_results" in message:
108
+ st.divider()
109
+ st.markdown("**Web Search Results**")
110
+ for result in message["search_results"]:
111
+ with st.expander(result.get("title", "No title")):
112
+ st.markdown(f"**Snippet:** {result.get('snippet', 'No snippet available')}")
113
+ st.markdown(f"**Link:** [{result.get('link', 'No link')}]({result.get('link', '#')})")
114
+ st.caption(f"{message['timestamp']} β€’ {message['role'].capitalize()}")
115
+
116
+ # Accept user input
117
+ if prompt := st.chat_input("Ask me anything..."):
118
+ # Add user message to chat history
119
+ st.session_state.messages.append({
120
+ "role": "user",
121
+ "content": prompt,
122
+ "timestamp": datetime.now().strftime("%H:%M")
123
+ })
124
+
125
+ # Display user message
126
+ with st.chat_message("user", avatar="πŸ‘€"):
127
+ st.markdown(prompt)
128
+ st.caption(f"{datetime.now().strftime('%H:%M')} β€’ User")
129
+
130
+ # Display assistant response
131
+ with st.chat_message("assistant", avatar="πŸ€–"):
132
+ message_placeholder = st.empty()
133
+ full_response = ""
134
+
135
+ # If web search is enabled, perform search first
136
+ search_results = None
137
+ if web_search:
138
+ with st.spinner("Searching the web..."):
139
+ search_results = search_web(prompt)
140
+
141
+ # Generate response from Gemini
142
+ with st.spinner("Thinking..."):
143
+ try:
144
+ # Prepare the prompt
145
+ chat_prompt = prompt
146
+ if search_results:
147
+ chat_prompt += "\n\nHere are some web search results to help with your response:\n"
148
+ for i, result in enumerate(search_results, 1):
149
+ chat_prompt += f"\n{i}. {result.get('title', 'No title')}\n{result.get('snippet', 'No snippet')}\n"
150
+
151
+ # Get response from Gemini
152
+ response = model.generate_content(chat_prompt)
153
+
154
+ # Stream the response
155
+ for chunk in response.text.split(" "):
156
+ full_response += chunk + " "
157
+ message_placeholder.markdown(full_response + "β–Œ")
158
+ message_placeholder.markdown(full_response)
159
+
160
+ except Exception as e:
161
+ full_response = f"Sorry, I encountered an error: {str(e)}"
162
+ message_placeholder.markdown(full_response)
163
+
164
+ # Display search results if available
165
+ if search_results:
166
+ st.divider()
167
+ st.markdown("**Web Search Results**")
168
+ for result in search_results:
169
+ with st.expander(result.get("title", "No title")):
170
+ st.markdown(f"**Snippet:** {result.get('snippet', 'No snippet available')}")
171
+ st.markdown(f"**Link:** [{result.get('link', 'No link')}]({result.get('link', '#')})")
172
+
173
+ st.caption(f"{datetime.now().strftime('%H:%M')} β€’ Assistant")
174
+
175
+ # Add assistant response to chat history
176
+ st.session_state.messages.append({
177
+ "role": "assistant",
178
+ "content": full_response,
179
+ "timestamp": datetime.now().strftime("%H:%M"),
180
+ "search_results": search_results if search_results else None
181
+ })