Kerikim commited on
Commit
7979c8a
·
1 Parent(s): 0617fab

elkay: api.py

Browse files
phase/Student_view/chatbot.py CHANGED
@@ -60,8 +60,6 @@ def _normalize_messages():
60
  st.session_state.messages = normed
61
 
62
  def _history_for_backend():
63
- """Convert our local history into [{role, content}] for the backend,
64
- excluding the static welcome message."""
65
  hist = []
66
  for m in st.session_state.get("messages", []):
67
  text = (m.get("text") or "").strip()
@@ -69,7 +67,7 @@ def _history_for_backend():
69
  continue
70
  role = "assistant" if (m.get("sender") == "assistant") else "user"
71
  hist.append({"role": role, "content": text})
72
- return hist
73
 
74
  # -------------------------------
75
  # Reply via backend (/chat)
 
60
  st.session_state.messages = normed
61
 
62
  def _history_for_backend():
 
 
63
  hist = []
64
  for m in st.session_state.get("messages", []):
65
  text = (m.get("text") or "").strip()
 
67
  continue
68
  role = "assistant" if (m.get("sender") == "assistant") else "user"
69
  hist.append({"role": role, "content": text})
70
+ return hist[-4:] # <= keep it tiny
71
 
72
  # -------------------------------
73
  # Reply via backend (/chat)
phase/Student_view/quiz.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import streamlit as st
3
  from utils.quizdata import quizzes_data
@@ -350,13 +351,26 @@ def show_results(quiz_id):
350
  st.session_state.answers = {}
351
  if "messages" not in st.session_state:
352
  st.session_state.messages = []
353
- wrong_q_text = "\n".join(
354
- [f"Q: {q}\nYour answer: {ua}\nCorrect answer: {ca}\nExplanation: {ex}"
355
- for q, ua, ca, ex in wrong_answers])
356
- tutor_prompt = f"I just completed a financial quiz and got some questions wrong. Here are the details:\n{wrong_q_text}\nCan you help me understand these concepts better?"
 
 
 
 
 
 
 
 
 
 
 
 
 
357
  st.session_state.messages.append({
358
  "id": str(datetime.datetime.now().timestamp()),
359
- "text": tutor_prompt,
360
  "sender": "user",
361
  "timestamp": datetime.datetime.now()
362
  })
 
1
+ #quiz.py
2
  import os
3
  import streamlit as st
4
  from utils.quizdata import quizzes_data
 
351
  st.session_state.answers = {}
352
  if "messages" not in st.session_state:
353
  st.session_state.messages = []
354
+
355
+ # keep only first 3 wrong items, and cap text length
356
+ short = wrong_answers[:3]
357
+ rows = []
358
+ for q, ua, ca, ex in short:
359
+ q = (q or "")[:160]
360
+ ua = (", ".join(ua) if isinstance(ua, list) else str(ua or ""))[:120]
361
+ ca = (", ".join(ca) if isinstance(ca, list) else str(ca or ""))[:120]
362
+ ex = (ex or "")[:200]
363
+ rows.append(f"Q: {q}\nYour answer: {ua}\nCorrect answer: {ca}\nExplanation: {ex}")
364
+
365
+ handoff = (
366
+ "I just completed a financial quiz and missed a few. "
367
+ "Explain each briefly and give one easy tip to remember:\n\n" +
368
+ "\n\n".join(rows)
369
+ )
370
+
371
  st.session_state.messages.append({
372
  "id": str(datetime.datetime.now().timestamp()),
373
+ "text": handoff,
374
  "sender": "user",
375
  "timestamp": datetime.datetime.now()
376
  })
utils/api.py CHANGED
@@ -12,7 +12,7 @@ if not BACKEND:
12
  raise RuntimeError("BACKEND_URL is not set in Space secrets.")
13
 
14
  TOKEN = (os.getenv("BACKEND_TOKEN") or os.getenv("HF_TOKEN") or "").strip()
15
- DEFAULT_TIMEOUT = int(os.getenv("BACKEND_TIMEOUT", "60"))
16
 
17
  _session = requests.Session()
18
  retry = Retry(
@@ -65,18 +65,24 @@ def _req(method: str, path: str, **kw):
65
  # try next prefix on 404
66
  if status == 404:
67
  continue
 
 
 
 
 
 
 
 
 
 
 
68
  body = ""
69
  try:
70
  body = e.response.text[:500]
71
  except Exception:
72
  pass
73
- if status in (401, 403):
74
- raise RuntimeError(
75
- f"{method} {url} failed [{status}] – auth rejected. "
76
- f"Check BACKEND_TOKEN/HF_TOKEN and backend visibility."
77
- ) from e
78
  raise RuntimeError(f"{method} {url} failed [{status}]: {body}") from e
79
- except requests.RequestException as e:
80
  # try next prefix
81
  continue
82
  raise RuntimeError(f"No matching endpoint for {method} {path} with prefixes {list(_prefixes())}")
@@ -337,12 +343,12 @@ def chat_ai(query: str, lesson_id: int, level_slug: str, history=None) -> str:
337
  "history": history or [],
338
  }
339
  try:
340
- # Force the full path without relying on _prefixes
341
- url = f"{BACKEND}/chat" # make sure BACKEND has no trailing slash
342
- r = _session.post(url, json=payload, timeout=DEFAULT_TIMEOUT)
 
343
  r.raise_for_status()
344
- d = r.json()
345
- return d.get("answer", "")
346
  except Exception as e:
347
  return f"(chat failed: {e})"
348
 
 
12
  raise RuntimeError("BACKEND_URL is not set in Space secrets.")
13
 
14
  TOKEN = (os.getenv("BACKEND_TOKEN") or os.getenv("HF_TOKEN") or "").strip()
15
+ DEFAULT_TIMEOUT = int(os.getenv("BACKEND_TIMEOUT", "120"))
16
 
17
  _session = requests.Session()
18
  retry = Retry(
 
65
  # try next prefix on 404
66
  if status == 404:
67
  continue
68
+
69
+ # ---------- friendlier auth errors ----------
70
+ if status in (401, 403):
71
+ # Normal bad credentials on the login endpoint
72
+ if path.endswith("/auth/login"):
73
+ raise RuntimeError("Incorrect email or password.") from e
74
+ # Generic auth issue elsewhere (expired session, etc.)
75
+ raise RuntimeError("Authentication failed. Please sign in again.") from e
76
+ # -------------------------------------------
77
+
78
+ # keep a tiny body for other errors
79
  body = ""
80
  try:
81
  body = e.response.text[:500]
82
  except Exception:
83
  pass
 
 
 
 
 
84
  raise RuntimeError(f"{method} {url} failed [{status}]: {body}") from e
85
+ except requests.RequestException:
86
  # try next prefix
87
  continue
88
  raise RuntimeError(f"No matching endpoint for {method} {path} with prefixes {list(_prefixes())}")
 
343
  "history": history or [],
344
  }
345
  try:
346
+ url = f"{BACKEND}/chat"
347
+ with requests.Session() as s:
348
+ s.headers.update(_session.headers)
349
+ r = s.post(url, json=payload, timeout=DEFAULT_TIMEOUT) # no retry adapter
350
  r.raise_for_status()
351
+ return r.json().get("answer", "")
 
352
  except Exception as e:
353
  return f"(chat failed: {e})"
354