Dipti Dhawade commited on
Commit
661e1b8
·
1 Parent(s): 195674d

Fix study tools

Browse files
Files changed (3) hide show
  1. README.md +3 -3
  2. backend/llm_pipeline.py +26 -10
  3. backend/search.py +20 -0
README.md CHANGED
@@ -176,7 +176,7 @@ find a passage about "rate of reaction".
176
  Collect the text: the open file, plus short parts of other files in the same course folder
177
  │
178
  ▼
179
- Send it to Sarvam AI (sarvam-30b):
180
  • Flashcards and quizzes: about 70% straight from the notes, about 30% on closely
181
  related topics from the same subject (those are labelled "📖 Beyond notes")
182
  • Quizzes: 4 options each, one-line explanation, answer order shuffled
@@ -234,7 +234,7 @@ question wins. The student's own notes are used only when they really match.
234
  | **Search by meaning** | `all-MiniLM-L6-v2` (sentence-transformers) | A small free model, running on our server, that makes the "meaning fingerprints". |
235
  | | LangChain text splitter | Cuts notes into short passages. |
236
  | **Storage** | ChromaDB (Chroma Cloud or self-hosted) | Stores note passages and finds the closest matches to a question. Also stores accounts, folders, decks and usage. |
237
- | **Writing answers** | Sarvam AI chat models | `sarvam-105b` writes answers; `sarvam-30b` writes flashcards, quizzes and summaries. |
238
  | **Passwords** | bcrypt | Passwords are stored scrambled, never as plain text. |
239
  | **Hosting** | GitHub Pages | Hosts the website. |
240
  | | Hugging Face Spaces (Docker) | Hosts the server. |
@@ -395,7 +395,7 @@ Step-by-step instructions, backups and checks are in [DEPLOYMENT.md](DEPLOYMENT.
395
 
396
  | Area | Settings |
397
  |---|---|
398
- | Sarvam AI | `SARVAM_API_BASE`, `SARVAM_MODEL_RAG` (`sarvam-105b`), `SARVAM_MODEL_STUDY` (`sarvam-30b`), `SARVAM_DOC_INTEL_LANGUAGE` (`en-IN`), `SARVAM_DOC_INTEL_TIMEOUT` (180 s) |
399
  | Security and sizes | `CORS_ORIGINS` (localhost + `https://cherie-dips.github.io`), `SESSION_TTL_DAYS` (14), `MAX_UPLOAD_MB` (20), `MAX_CHAT_UPLOAD_CHARS` (300000), `CHAT_CACHE_TTL_SECONDS` (7200), `USER_DOCUMENT_MAX_BYTES` (2000000), `RATE_LIMIT_MULTIPLIER` (1) |
400
  | Password-reset email | `FRONTEND_URL`, `SMTP_HOST`, `SMTP_PORT` (587), `SMTP_USERNAME`, `SMTP_PASSWORD`, `SMTP_FROM`, `SMTP_STARTTLS` (true). Turned on only when `SMTP_HOST` and `SMTP_FROM` are set. |
401
  | OneNote | `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`, `MICROSOFT_REDIRECT_URI` |
 
176
  Collect the text: the open file, plus short parts of other files in the same course folder
177
  │
178
  ▼
179
+ Send it to Sarvam AI (sarvam-105b, with low reasoning effort):
180
  • Flashcards and quizzes: about 70% straight from the notes, about 30% on closely
181
  related topics from the same subject (those are labelled "📖 Beyond notes")
182
  • Quizzes: 4 options each, one-line explanation, answer order shuffled
 
234
  | **Search by meaning** | `all-MiniLM-L6-v2` (sentence-transformers) | A small free model, running on our server, that makes the "meaning fingerprints". |
235
  | | LangChain text splitter | Cuts notes into short passages. |
236
  | **Storage** | ChromaDB (Chroma Cloud or self-hosted) | Stores note passages and finds the closest matches to a question. Also stores accounts, folders, decks and usage. |
237
+ | **Writing answers** | Sarvam AI chat models | `sarvam-105b` writes answers, flashcards, quizzes and summaries (study tools use low reasoning effort). |
238
  | **Passwords** | bcrypt | Passwords are stored scrambled, never as plain text. |
239
  | **Hosting** | GitHub Pages | Hosts the website. |
240
  | | Hugging Face Spaces (Docker) | Hosts the server. |
 
395
 
396
  | Area | Settings |
397
  |---|---|
398
+ | Sarvam AI | `SARVAM_API_BASE`, `SARVAM_MODEL_RAG` (`sarvam-105b`), `SARVAM_MODEL_STUDY` (`sarvam-105b`), `SARVAM_DOC_INTEL_LANGUAGE` (`en-IN`), `SARVAM_DOC_INTEL_TIMEOUT` (180 s) |
399
  | Security and sizes | `CORS_ORIGINS` (localhost + `https://cherie-dips.github.io`), `SESSION_TTL_DAYS` (14), `MAX_UPLOAD_MB` (20), `MAX_CHAT_UPLOAD_CHARS` (300000), `CHAT_CACHE_TTL_SECONDS` (7200), `USER_DOCUMENT_MAX_BYTES` (2000000), `RATE_LIMIT_MULTIPLIER` (1) |
400
  | Password-reset email | `FRONTEND_URL`, `SMTP_HOST`, `SMTP_PORT` (587), `SMTP_USERNAME`, `SMTP_PASSWORD`, `SMTP_FROM`, `SMTP_STARTTLS` (true). Turned on only when `SMTP_HOST` and `SMTP_FROM` are set. |
401
  | OneNote | `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`, `MICROSOFT_REDIRECT_URI` |
backend/llm_pipeline.py CHANGED
@@ -15,7 +15,10 @@ logger = logging.getLogger(__name__)
15
 
16
  # Chat models (see https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/chat-completion/overview)
17
  _DEFAULT_MODEL_RAG = "sarvam-105b"
18
- _DEFAULT_MODEL_STUDY = "sarvam-30b"
 
 
 
19
 
20
  _GROUNDING_STOPWORDS = {
21
  "about", "after", "again", "also", "among", "another", "because", "before", "being", "between",
@@ -64,11 +67,11 @@ def _chat_base_url() -> str:
64
 
65
 
66
  def _model_rag() -> str:
67
- return os.getenv("SARVAM_MODEL_RAG", _DEFAULT_MODEL_RAG).strip()
68
 
69
 
70
  def _model_study() -> str:
71
- return os.getenv("SARVAM_MODEL_STUDY", _DEFAULT_MODEL_STUDY).strip()
72
 
73
 
74
  def _sarvam_chat_complete(
@@ -77,11 +80,17 @@ def _sarvam_chat_complete(
77
  model: str,
78
  max_tokens: int,
79
  temperature: float,
 
80
  ) -> tuple[str | None, str | None]:
81
  key = _sarvam_api_key()
82
  if not key:
83
  return None, "SARVAM_API_KEY not configured"
84
  url = f"{_chat_base_url()}/v1/chat/completions"
 
 
 
 
 
85
  try:
86
  r = httpx.post(
87
  url,
@@ -89,18 +98,23 @@ def _sarvam_chat_complete(
89
  "Authorization": f"Bearer {key}",
90
  "Content-Type": "application/json",
91
  },
92
- json={
93
- "model": model,
94
- "messages": messages,
95
- "max_tokens": max_tokens,
96
- "temperature": temperature,
97
- },
98
  timeout=300.0,
99
  )
100
  data = r.json()
101
  if r.status_code >= 400:
102
  err = data.get("error") if isinstance(data.get("error"), dict) else {}
103
  msg = err.get("message") if isinstance(err, dict) else None
 
 
 
 
 
 
 
 
 
 
104
  return None, msg or r.text or f"HTTP {r.status_code}"
105
  choices = data.get("choices") or []
106
  if not choices:
@@ -531,6 +545,7 @@ def cheap_study_json(context: str, task: str, n: int, language: str = "English")
531
  model=_model_study(),
532
  max_tokens=8192,
533
  temperature=0.4,
 
534
  )
535
  if err:
536
  last_err = err
@@ -587,8 +602,9 @@ def topic_summary(context: str, language: str = "English") -> tuple[str | None,
587
  raw, err = _sarvam_chat_complete(
588
  [{"role": "user", "content": msg}],
589
  model=_model_study(),
590
- max_tokens=1024,
591
  temperature=0.2,
 
592
  )
593
  if err:
594
  last_err = err
 
15
 
16
  # Chat models (see https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/chat-completion/overview)
17
  _DEFAULT_MODEL_RAG = "sarvam-105b"
18
+ _DEFAULT_MODEL_STUDY = "sarvam-105b" # Sarvam retired sarvam-30b in 2026
19
+ # Flashcards, quizzes and summaries don't need the model's long reasoning: without it they take
20
+ # about a second instead of up to a minute, and cost a fraction of the tokens.
21
+ _STUDY_REASONING_EFFORT = "off"
22
 
23
  _GROUNDING_STOPWORDS = {
24
  "about", "after", "again", "also", "among", "another", "because", "before", "being", "between",
 
67
 
68
 
69
  def _model_rag() -> str:
70
+ return (os.getenv("SARVAM_MODEL_RAG") or "").strip() or _DEFAULT_MODEL_RAG
71
 
72
 
73
  def _model_study() -> str:
74
+ return (os.getenv("SARVAM_MODEL_STUDY") or "").strip() or _DEFAULT_MODEL_STUDY
75
 
76
 
77
  def _sarvam_chat_complete(
 
80
  model: str,
81
  max_tokens: int,
82
  temperature: float,
83
+ reasoning_effort: str | None = None,
84
  ) -> tuple[str | None, str | None]:
85
  key = _sarvam_api_key()
86
  if not key:
87
  return None, "SARVAM_API_KEY not configured"
88
  url = f"{_chat_base_url()}/v1/chat/completions"
89
+ payload = {"model": model, "messages": messages, "max_tokens": max_tokens, "temperature": temperature}
90
+ if reasoning_effort == "off":
91
+ payload["reasoning_effort"] = None # Sarvam: an explicit null turns reasoning off
92
+ elif reasoning_effort:
93
+ payload["reasoning_effort"] = reasoning_effort # low | medium (default) | high | max
94
  try:
95
  r = httpx.post(
96
  url,
 
98
  "Authorization": f"Bearer {key}",
99
  "Content-Type": "application/json",
100
  },
101
+ json=payload,
 
 
 
 
 
102
  timeout=300.0,
103
  )
104
  data = r.json()
105
  if r.status_code >= 400:
106
  err = data.get("error") if isinstance(data.get("error"), dict) else {}
107
  msg = err.get("message") if isinstance(err, dict) else None
108
+ if "deprecated" in (msg or "").lower() and model != _DEFAULT_MODEL_RAG:
109
+ # A model setting that Sarvam has since retired: keep working on the default model.
110
+ logger.warning("Sarvam model %s is retired (%s); using %s", model, msg, _DEFAULT_MODEL_RAG)
111
+ return _sarvam_chat_complete(
112
+ messages,
113
+ model=_DEFAULT_MODEL_RAG,
114
+ max_tokens=max_tokens,
115
+ temperature=temperature,
116
+ reasoning_effort=reasoning_effort,
117
+ )
118
  return None, msg or r.text or f"HTTP {r.status_code}"
119
  choices = data.get("choices") or []
120
  if not choices:
 
545
  model=_model_study(),
546
  max_tokens=8192,
547
  temperature=0.4,
548
+ reasoning_effort=_STUDY_REASONING_EFFORT,
549
  )
550
  if err:
551
  last_err = err
 
602
  raw, err = _sarvam_chat_complete(
603
  [{"role": "user", "content": msg}],
604
  model=_model_study(),
605
+ max_tokens=4096, # room for the model's reasoning as well as the ~150-word summary
606
  temperature=0.2,
607
+ reasoning_effort=_STUDY_REASONING_EFFORT,
608
  )
609
  if err:
610
  last_err = err
backend/search.py CHANGED
@@ -26,6 +26,8 @@ from backend.settings import (
26
 
27
  MAX_SELECTED = 8
28
  OPEN_LIBRARY_FILE_LEAD = 0.10 # ranking lead for the course PDF the student has open
 
 
29
 
30
 
31
  @dataclass
@@ -197,6 +199,7 @@ def find_context(
197
  for name, docs, min_score in stages:
198
  if docs and docs[0]["_score"] >= min_score:
199
  result.stage, result.selected = name, _closest(docs)
 
200
  return result
201
  # A question about a course PDF never falls back to loosely related notes of the student's own
202
  # (e.g. sample physics notes for a maths course): only the course library itself.
@@ -205,5 +208,22 @@ def find_context(
205
  if available:
206
  result.stage, docs = max(available, key=lambda s: s[1][0]["_score"])
207
  result.selected = _closest(docs)
 
208
  return result
209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  MAX_SELECTED = 8
28
  OPEN_LIBRARY_FILE_LEAD = 0.10 # ranking lead for the course PDF the student has open
29
+ OPEN_PDF_KEEP = 3 # passages of the open PDF always sent when it is nearly as relevant...
30
+ OPEN_PDF_KEEP_GAP = 0.25 # ...as the best passage of its course (within this much)
31
 
32
 
33
  @dataclass
 
199
  for name, docs, min_score in stages:
200
  if docs and docs[0]["_score"] >= min_score:
201
  result.stage, result.selected = name, _closest(docs)
202
+ _keep_open_pdf(result, lib_file_docs, lib_subject_docs)
203
  return result
204
  # A question about a course PDF never falls back to loosely related notes of the student's own
205
  # (e.g. sample physics notes for a maths course): only the course library itself.
 
208
  if available:
209
  result.stage, docs = max(available, key=lambda s: s[1][0]["_score"])
210
  result.selected = _closest(docs)
211
+ _keep_open_pdf(result, lib_file_docs, lib_subject_docs)
212
  return result
213
 
214
+
215
+ def _keep_open_pdf(result: SearchResult, file_docs: list[dict], subject_docs: list[dict]) -> None:
216
+ """
217
+ The student asked while reading a course PDF: make sure its best passages reach the answer when
218
+ it is nearly as relevant as the rest of the course, even if many other passages score a little
219
+ higher (e.g. exam answers that all mention "time complexity"). They go first in the context.
220
+ """
221
+ if not file_docs or not result.stage.startswith("library"):
222
+ return
223
+ best_other = subject_docs[0]["_score"] if subject_docs else -1.0
224
+ if file_docs[0]["_score"] < max(MIN_SCORE_LIBRARY_FILE, best_other - OPEN_PDF_KEEP_GAP):
225
+ return
226
+ keep = [d for d in file_docs[:OPEN_PDF_KEEP] if d["_score"] >= MIN_SCORE_LIBRARY_FILE]
227
+ kept_ids = {d["id"] for d in keep}
228
+ result.selected = (keep + [d for d in result.selected if d["id"] not in kept_ids])[:MAX_SELECTED]
229
+