AroojImtiaz commited on
Commit
5cd09ba
·
verified ·
1 Parent(s): 75ed8a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -18
app.py CHANGED
@@ -1,14 +1,18 @@
1
- # app.py
2
  import os
3
  import asyncio
 
4
  from dotenv import load_dotenv
5
  import chainlit as cl
6
 
 
 
 
7
  # Attempt to import google.generativeai (optional dependency)
8
  try:
9
  import google.generativeai as genai
10
- except Exception:
11
  genai = None
 
12
 
13
  # Load .env (won't override Space secrets)
14
  load_dotenv()
@@ -19,19 +23,16 @@ MODEL_NAME = os.getenv("MODEL_NAME", "gemini-2.0-flash")
19
 
20
  # Try to configure Gemini if possible
21
  model = None
22
- if genai is None:
23
- print("[Info] google-generativeai not installed or failed to import. Gemini will be unavailable.")
24
- else:
25
  if GOOGLE_API_KEY:
26
  try:
27
  genai.configure(api_key=GOOGLE_API_KEY)
28
  model = genai.GenerativeModel(MODEL_NAME)
29
- print(f"[Info] Gemini model initialized: {MODEL_NAME}")
30
  except Exception as e:
31
- print(f"[Warning] Failed to init Gemini model '{MODEL_NAME}': {e}")
32
- model = None
33
- else:
34
- print("[Info] GOOGLE_API_KEY not found in environment. Set it in Space Secrets to enable Gemini.")
35
 
36
  SYSTEM_PROMPT = "You are a helpful assistant."
37
 
@@ -46,7 +47,6 @@ async def on_chat_start():
46
  """Welcome message and session init."""
47
  cl.user_session.set("message_history", [{"role": "system", "content": SYSTEM_PROMPT}])
48
  if model is None:
49
- # Informative welcome when Gemini not available
50
  await cl.Message(
51
  content=(
52
  "Hello — the app is running. Gemini is not available because GOOGLE_API_KEY is not set or the model failed to init.\n\n"
@@ -64,17 +64,16 @@ async def handle_message(message: cl.Message):
64
  await cl.Message(content="Please type a question or prompt.").send()
65
  return
66
 
67
- # Store message in session history (for bookkeeping)
68
  history = cl.user_session.get("message_history", [])
69
  history.append({"role": "user", "content": user_text})
70
  cl.user_session.set("message_history", history)
71
 
72
- # Send a progress message that we'll update
73
  progress = cl.Message(content="(Thinking...)")
74
  await progress.send()
75
 
76
  if model is None:
77
- # Fallback behavior: echo plus short helpful tips
78
  reply = (
79
  "Gemini not initialized (GOOGLE_API_KEY missing or model failed to init).\n\n"
80
  "Echoing your input:\n\n" + user_text + "\n\n"
@@ -84,16 +83,17 @@ async def handle_message(message: cl.Message):
84
  try:
85
  resp = await _call_gemini_generate(user_text)
86
  reply = getattr(resp, "text", None) or str(resp)
 
 
87
  except Exception as e:
88
  reply = f"[Error calling Gemini API] {e}"
89
 
90
  # Update the progress message with final reply
91
  try:
92
- progress.content = reply
93
- await progress.update()
94
- except Exception:
95
  await cl.Message(content=reply).send()
96
 
97
  # Save assistant reply to history
98
  history.append({"role": "assistant", "content": reply})
99
- cl.user_session.set("message_history", history)
 
 
1
  import os
2
  import asyncio
3
+ import logging
4
  from dotenv import load_dotenv
5
  import chainlit as cl
6
 
7
+ # Set up logging
8
+ logging.basicConfig(level=logging.INFO)
9
+
10
  # Attempt to import google.generativeai (optional dependency)
11
  try:
12
  import google.generativeai as genai
13
+ except ImportError:
14
  genai = None
15
+ logging.warning("google.generativeai not installed or failed to import. Gemini will be unavailable.")
16
 
17
  # Load .env (won't override Space secrets)
18
  load_dotenv()
 
23
 
24
  # Try to configure Gemini if possible
25
  model = None
26
+ if genai is not None:
 
 
27
  if GOOGLE_API_KEY:
28
  try:
29
  genai.configure(api_key=GOOGLE_API_KEY)
30
  model = genai.GenerativeModel(MODEL_NAME)
31
+ logging.info(f"Gemini model initialized: {MODEL_NAME}")
32
  except Exception as e:
33
+ logging.warning(f"Failed to init Gemini model '{MODEL_NAME}': {e}")
34
+ else:
35
+ logging.info("GOOGLE_API_KEY not found in environment. Set it in Space Secrets to enable Gemini.")
 
36
 
37
  SYSTEM_PROMPT = "You are a helpful assistant."
38
 
 
47
  """Welcome message and session init."""
48
  cl.user_session.set("message_history", [{"role": "system", "content": SYSTEM_PROMPT}])
49
  if model is None:
 
50
  await cl.Message(
51
  content=(
52
  "Hello — the app is running. Gemini is not available because GOOGLE_API_KEY is not set or the model failed to init.\n\n"
 
64
  await cl.Message(content="Please type a question or prompt.").send()
65
  return
66
 
67
+ # Store message in session history
68
  history = cl.user_session.get("message_history", [])
69
  history.append({"role": "user", "content": user_text})
70
  cl.user_session.set("message_history", history)
71
 
72
+ # Send a progress message
73
  progress = cl.Message(content="(Thinking...)")
74
  await progress.send()
75
 
76
  if model is None:
 
77
  reply = (
78
  "Gemini not initialized (GOOGLE_API_KEY missing or model failed to init).\n\n"
79
  "Echoing your input:\n\n" + user_text + "\n\n"
 
83
  try:
84
  resp = await _call_gemini_generate(user_text)
85
  reply = getattr(resp, "text", None) or str(resp)
86
+ except RuntimeError as e:
87
+ reply = f"[Runtime Error] {e}"
88
  except Exception as e:
89
  reply = f"[Error calling Gemini API] {e}"
90
 
91
  # Update the progress message with final reply
92
  try:
93
+ await progress.update(content=reply)
94
+ except Exception as e:
 
95
  await cl.Message(content=reply).send()
96
 
97
  # Save assistant reply to history
98
  history.append({"role": "assistant", "content": reply})
99
+ cl.user_session.set("message_history", history)