Update app.py
Browse files
app.py
CHANGED
@@ -4,15 +4,13 @@ import os
|
|
4 |
from dotenv import load_dotenv
|
5 |
import http.client
|
6 |
import json
|
7 |
-
import secrets
|
8 |
-
|
9 |
|
10 |
load_dotenv()
|
11 |
|
12 |
app = Flask(__name__)
|
13 |
-
app.secret_key = secrets.token_hex(16) #
|
14 |
|
15 |
-
# Configure the API key
|
16 |
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
17 |
|
18 |
safety_settings = [
|
@@ -22,6 +20,8 @@ safety_settings = [
|
|
22 |
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
23 |
]
|
24 |
|
|
|
|
|
25 |
ss = """
|
26 |
# Prompt System pour Mariam, IA conçu par youssouf
|
27 |
|
@@ -119,11 +119,9 @@ Mariam est une IA chaleureuse, bienveillante et authentique, conçue pour être
|
|
119 |
|
120 |
"""
|
121 |
|
122 |
-
|
123 |
-
|
124 |
model = genai.GenerativeModel(
|
125 |
"gemini-2.0-flash-exp",
|
126 |
-
tools="code_execution",
|
127 |
safety_settings=safety_settings,
|
128 |
system_instruction=ss,
|
129 |
)
|
@@ -200,88 +198,81 @@ def process_uploaded_file(file):
|
|
200 |
|
201 |
@app.route("/")
|
202 |
def index():
|
203 |
-
# Initialize chat and web search in session if not present
|
204 |
if "chat" not in session:
|
205 |
-
session["chat"] = [] # Store chat
|
206 |
session["web_search"] = False
|
207 |
-
session["gemini_chat"] = model.start_chat(history=[])
|
208 |
-
|
209 |
-
|
210 |
return render_template("index.html", chat=session["chat"], web_search=session["web_search"])
|
211 |
|
212 |
|
213 |
-
|
214 |
@app.route("/send_message", methods=["POST"])
|
215 |
def send_message():
|
216 |
prompt = request.form.get("prompt")
|
217 |
-
web_search = request.form.get("web_search") == "true"
|
218 |
file = request.files.get("file")
|
219 |
|
220 |
uploaded_gemini_file = None
|
221 |
if file:
|
222 |
uploaded_gemini_file = process_uploaded_file(file)
|
223 |
|
224 |
-
if "gemini_chat" not in session: # Initialize if it doesn't already exists.
|
225 |
-
session["gemini_chat"] = model.start_chat(history=[])
|
226 |
-
session.modified = True #Important to save session changes!
|
227 |
-
|
228 |
# Add user message to chat history
|
229 |
session["chat"].append({"role": "user", "text": prompt})
|
230 |
-
session.modified = True
|
231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
232 |
try:
|
233 |
-
# Web search
|
234 |
web_results = None
|
235 |
if web_search:
|
236 |
-
|
237 |
-
|
238 |
formatted_results = format_search_results(web_results)
|
239 |
prompt = (
|
240 |
f"Question: {prompt}\n\nRésultats de recherche web:\n"
|
241 |
f"{formatted_results}\n\nPourrais-tu analyser ces informations et "
|
242 |
f"me donner une réponse complète?"
|
243 |
)
|
244 |
-
|
245 |
-
#Handle the "no results" case
|
246 |
prompt = f"Question: {prompt}\n\n(Aucun résultat de recherche trouvé. Répondez en vous basant sur vos connaissances.)"
|
247 |
|
248 |
-
# Send message to Gemini
|
249 |
-
gemini_chat = session["gemini_chat"] # Get the chat object.
|
250 |
if uploaded_gemini_file:
|
251 |
response = gemini_chat.send_message([uploaded_gemini_file, "\n\n", prompt])
|
252 |
else:
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
# Add assistant response to chat history
|
257 |
session["chat"].append({"role": "assistant", "text": response.text})
|
258 |
-
session
|
259 |
-
session.modified = True #Important to save session changes!
|
260 |
-
|
261 |
|
262 |
return jsonify({"role": "assistant", "text": response.text})
|
263 |
|
264 |
except Exception as e:
|
265 |
error_message = f"Error sending message: {e}"
|
266 |
-
print(error_message)
|
267 |
-
return jsonify({"role": "assistant", "text": error_message}), 500
|
268 |
-
|
269 |
|
270 |
|
271 |
@app.route("/toggle_web_search", methods=["POST"])
|
272 |
def toggle_web_search():
|
273 |
session["web_search"] = not session["web_search"]
|
274 |
-
session.modified = True #
|
275 |
return jsonify({"web_search": session["web_search"]})
|
276 |
|
|
|
277 |
@app.route("/clear_chat", methods=["POST"])
|
278 |
def clear_chat():
|
279 |
-
session.pop("chat", None)
|
280 |
-
session.pop("gemini_chat", None)
|
281 |
session["web_search"] = False
|
282 |
-
session.modified = True
|
283 |
return jsonify({"status": "success"})
|
284 |
|
285 |
|
286 |
if __name__ == "__main__":
|
287 |
-
app.run(debug=True)
|
|
|
4 |
from dotenv import load_dotenv
|
5 |
import http.client
|
6 |
import json
|
7 |
+
import secrets
|
|
|
8 |
|
9 |
load_dotenv()
|
10 |
|
11 |
app = Flask(__name__)
|
12 |
+
app.secret_key = secrets.token_hex(16) # CRUCIAL: Secure session key
|
13 |
|
|
|
14 |
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
15 |
|
16 |
safety_settings = [
|
|
|
20 |
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
21 |
]
|
22 |
|
23 |
+
# ... (rest of your ss, model, perform_web_search, format_search_results definitions) ...
|
24 |
+
# Use the full `ss` and `model` definitions from the previous response.
|
25 |
ss = """
|
26 |
# Prompt System pour Mariam, IA conçu par youssouf
|
27 |
|
|
|
119 |
|
120 |
"""
|
121 |
|
|
|
|
|
122 |
model = genai.GenerativeModel(
|
123 |
"gemini-2.0-flash-exp",
|
124 |
+
tools="code_execution",
|
125 |
safety_settings=safety_settings,
|
126 |
system_instruction=ss,
|
127 |
)
|
|
|
198 |
|
199 |
@app.route("/")
|
200 |
def index():
|
|
|
201 |
if "chat" not in session:
|
202 |
+
session["chat"] = [] # Store chat HISTORY as a list of dicts
|
203 |
session["web_search"] = False
|
|
|
|
|
|
|
204 |
return render_template("index.html", chat=session["chat"], web_search=session["web_search"])
|
205 |
|
206 |
|
|
|
207 |
@app.route("/send_message", methods=["POST"])
|
208 |
def send_message():
|
209 |
prompt = request.form.get("prompt")
|
210 |
+
web_search = request.form.get("web_search") == "true"
|
211 |
file = request.files.get("file")
|
212 |
|
213 |
uploaded_gemini_file = None
|
214 |
if file:
|
215 |
uploaded_gemini_file = process_uploaded_file(file)
|
216 |
|
|
|
|
|
|
|
|
|
217 |
# Add user message to chat history
|
218 |
session["chat"].append({"role": "user", "text": prompt})
|
219 |
+
session.modified = True # IMPORTANT: Mark session as modified
|
220 |
|
221 |
+
# 1. Get chat history from session
|
222 |
+
chat_history = session["chat"]
|
223 |
+
|
224 |
+
# 2. Start a NEW chat session with the history
|
225 |
+
gemini_chat = model.start_chat(history=[
|
226 |
+
{"role": msg["role"], "parts": [msg["text"]]} for msg in chat_history if msg["role"] != "assistant" # Recreate history format
|
227 |
+
])
|
228 |
+
|
229 |
try:
|
230 |
+
# Web search (same as before)
|
231 |
web_results = None
|
232 |
if web_search:
|
233 |
+
web_results = perform_web_search(prompt)
|
234 |
+
if web_results:
|
235 |
formatted_results = format_search_results(web_results)
|
236 |
prompt = (
|
237 |
f"Question: {prompt}\n\nRésultats de recherche web:\n"
|
238 |
f"{formatted_results}\n\nPourrais-tu analyser ces informations et "
|
239 |
f"me donner une réponse complète?"
|
240 |
)
|
241 |
+
else:
|
|
|
242 |
prompt = f"Question: {prompt}\n\n(Aucun résultat de recherche trouvé. Répondez en vous basant sur vos connaissances.)"
|
243 |
|
244 |
+
# Send message to Gemini (using the recreated chat)
|
|
|
245 |
if uploaded_gemini_file:
|
246 |
response = gemini_chat.send_message([uploaded_gemini_file, "\n\n", prompt])
|
247 |
else:
|
248 |
+
response = gemini_chat.send_message(prompt)
|
249 |
+
|
|
|
250 |
# Add assistant response to chat history
|
251 |
session["chat"].append({"role": "assistant", "text": response.text})
|
252 |
+
session.modified = True # IMPORTANT
|
|
|
|
|
253 |
|
254 |
return jsonify({"role": "assistant", "text": response.text})
|
255 |
|
256 |
except Exception as e:
|
257 |
error_message = f"Error sending message: {e}"
|
258 |
+
print(error_message)
|
259 |
+
return jsonify({"role": "assistant", "text": error_message}), 500
|
|
|
260 |
|
261 |
|
262 |
@app.route("/toggle_web_search", methods=["POST"])
|
263 |
def toggle_web_search():
|
264 |
session["web_search"] = not session["web_search"]
|
265 |
+
session.modified = True # IMPORTANT
|
266 |
return jsonify({"web_search": session["web_search"]})
|
267 |
|
268 |
+
|
269 |
@app.route("/clear_chat", methods=["POST"])
|
270 |
def clear_chat():
|
271 |
+
session.pop("chat", None) # Safely remove chat history
|
|
|
272 |
session["web_search"] = False
|
273 |
+
session.modified = True # IMPORTANT
|
274 |
return jsonify({"status": "success"})
|
275 |
|
276 |
|
277 |
if __name__ == "__main__":
|
278 |
+
app.run(debug=True) # Turn off debug mode
|