Spaces:
Runtime error
Runtime error
Oviya commited on
Commit ·
92aab26
1
Parent(s): 78c78fd
fix
Browse filesFiles changed (2)
- ragg/app.py+17-50
- ragg/rag_llm.py+72-15
189 unmodified lines19019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326458 unmodified lines3233243253263273283293303313322 unmodified lines335336337338339340341189 unmodified linesreturn jsonify(result)@rag_bp.route("/explain-grammar", methods=["POST", "OPTIONS"])def rag_explain_grammar():if request.method == "OPTIONS":return ("", 204)data = request.json or {}username = extract_username_from_request(request)db_level = user_to_db_level(username)body = ExplainBody(**data)if not body.db_level:body.db_level = db_level# 1) LLM/RAGresult_raw = llm_explain(body)# 2) Normalize + extract answer textresult_dict = Noneanswer_text = ""try:if isinstance(result_raw, dict):result_dict = dict(result_raw)elif hasattr(result_raw, "model_dump"):result_dict = result_raw.model_dump()elif hasattr(result_raw, "dict"):result_dict = result_raw.dict()elif isinstance(result_raw, str):result_dict = {"answer": result_raw}else:result_dict = {"answer": str(result_raw)}answer_text = (result_dict.get("answer") or result_dict.get("response") or result_dict.get("text") or "").strip()except Exception as e:current_app.logger.exception("Failed to normalize llm_explain result: %s", e)return jsonify({"error": "Internal error normalizing LLM response"}), 500# 3) Optional D-ID videovideo_url = Nonedid_ready = bool(DID_API_KEY and DID_SOURCE_IMAGE_URL)if answer_text and did_ready:try:talk_id, err = _did_create_talk(answer_text)if err:current_app.logger.error("D-ID talk creation error: %s", err[0])else:video_url, err = _did_poll_talk(talk_id, timeout_sec=75, interval_sec=2.0)if err:current_app.logger.error("D-ID polling error: %s", err[0])except Exception as e:current_app.logger.exception("Unexpected error calling D-ID: %s", e)result_dict["video_url"] = video_urlreturn jsonify(result_dict), 200@rag_bp.route("/suggest-followups", methods=["POST", "OPTIONS"])def rag_suggest_followups():if request.method == "OPTIONS":return ("", 204)data = request.get_json(force=True) or {}username = extract_username_from_request(request)db_level = user_to_db_level(username)body = FollowupBody(last_question=(data.get("last_question") or "").strip(),last_answer=(data.get("last_answer") or "").strip(),n=int(data.get("n", 5)),model=data.get("model", "gpt-4o-mini"),db_level=db_level,)result = llm_followups(body)return jsonify(result)58 unmodified lines# from .rag_llm import CHROMA_DIR, CHROMA_ROOT, get_vectorstore, get_vectorstore_for# except ImportError:# from rag_llm import CHROMA_DIR, CHROMA_ROOT, get_vectorstore, get_vectorstore_for# import os# from flask import jsonify# def _count(vs):# try:# return vs._collection.count()2 unmodified lines# return vs._client.get_collection(vs._collection.name).count()# except Exception:# return None# info = {# "env_seen": {"CHROMA_DIR": CHROMA_DIR, "CHROMA_ROOT": CHROMA_ROOT},# "low_dir": {189 unmodified lines19019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023158 unmodified lines2902912922932942952962972982992 unmodified lines302303304305306307308189 unmodified linesreturn jsonify(result)# @rag_bp.route("/explain-grammar", methods=["POST", "OPTIONS"])@rag_bp.route("/explain-grammar", methods=["POST", "OPTIONS"])def rag_explain_grammar():if request.method == "OPTIONS":return ("", 204)data = request.get_json(force=True) or {}username = extract_username_from_request(request)db_level = user_to_db_level(username)body = ExplainBody(question=(data.get("question") or "").strip(),model=data.get("model", "gpt-4o-mini"),db_level=db_level,source_ids=data.get("source_ids") or [] # ← added)result = llm_explain(body)return jsonify(result)# @rag_bp.route("/suggest-followups", methods=["POST", "OPTIONS"])@rag_bp.route("/suggest-followups", methods=["POST", "OPTIONS"])def rag_suggest_followups():if request.method == "OPTIONS":return ("", 204)data = request.get_json(force=True) or {}username = extract_username_from_request(request)db_level = user_to_db_level(username)body = FollowupBody(last_question=(data.get("last_question") or "").strip(),last_answer=(data.get("last_answer") or "").strip(),n=int(data.get("n", 5)),model=data.get("model", "gpt-4o-mini"),db_level=db_level,source_ids=data.get("source_ids") or [] # ← same addition here)result = llm_followups(body)return jsonify(result)58 unmodified lines# from .rag_llm import CHROMA_DIR, CHROMA_ROOT, get_vectorstore, get_vectorstore_for# except ImportError:# from rag_llm import CHROMA_DIR, CHROMA_ROOT, get_vectorstore, get_vectorstore_for## import os# from flask import jsonify## def _count(vs):# try:# return vs._collection.count()2 unmodified lines# return vs._client.get_collection(vs._collection.name).count()# except Exception:# return None## info = {# "env_seen": {"CHROMA_DIR": CHROMA_DIR, "CHROMA_ROOT": CHROMA_ROOT},# "low_dir": {
147 unmodified lines148149150151152153338 unmodified lines49249349449549649749849950050150250350450550650750850951053 unmodified lines56456556656756856957057157257357499 unmodified lines674675676677147 unmodified linesmodel: str = "gpt-4o-mini"max_words: int = 120db_level: Optional[str] = Noneclass FollowupBody(BaseModel):338 unmodified linesif not query_text:return {"answer": "", "source_ids": [], "note": "No question provided."}# Retrieve relevant chunksdocs_with_scores = vs.similarity_search_with_score(query_text, k=20)docs = [doc for doc, dist in docs_with_scores if dist <= MAX_DISTANCE]# Fallback if nothing passes the thresholdif not docs:docs = [doc for doc, _ in docs_with_scores[:6]]print(f"ℹ️ Fallback engaged (QA): using top {len(docs)} docs without distance filter.")print(f"🔎 QA retrieved {len(docs_with_scores)} raw, {len(docs)} kept (≤ {MAX_DISTANCE})")for i, (doc, dist) in enumerate(docs_with_scores[:5]):snippet = (doc.page_content or "")[:100].replace("\n", " ")print(f" QA DOC {i+1} distance={dist:.3f} | {snippet}...")# Build compact contextsource_ids: List[str] = []53 unmodified lines}# ---------------------- Follow-up Suggestions ---------------------- #def llm_followups(body: FollowupBody) -> Dict[str, Any]:"""Suggest follow-up grammar questions based on the user's last question and the answer just given.Ground suggestions in the same textbook context (Chroma) used for the answer."""vs = get_vectorstore_for(body.db_level)99 unmodified linesif preferred:filtered = preferredreturn {"suggestions": filtered[: max(1, body.n)], "source_ids": source_ids}147 unmodified lines148149150151152153154338 unmodified lines49349449549649749849950050150250350450550650750850951051153 unmodified lines56556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061199 unmodified lines711712713714715716717718719720721722723724725726727728729730731732733734147 unmodified linesmodel: str = "gpt-4o-mini"max_words: int = 120db_level: Optional[str] = Nonesource_ids: Optional[List[str]] = None # ← NEWclass FollowupBody(BaseModel):338 unmodified linesif not query_text:return {"answer": "", "source_ids": [], "note": "No question provided."}# --- NEW: retrieval prefers provided source_ids first ---if body.source_ids:docs = _fetch_docs_for_followups(vs, body.source_ids, body.question, "")if not docs:# fallback to similarity search if nothing found in same pagesdocs_with_scores = vs.similarity_search_with_score(query_text, k=20)docs = [doc for doc, dist in docs_with_scores if dist <= MAX_DISTANCE] or [doc for doc, _ in docs_with_scores[:6]]else:docs_with_scores = vs.similarity_search_with_score(query_text, k=20)docs = [doc for doc, dist in docs_with_scores if dist <= MAX_DISTANCE]if not docs:docs = [doc for doc, _ in docs_with_scores[:6]]print(f"ℹ️ Fallback engaged (QA): using top {len(docs)} docs without distance filter.")# Build compact contextsource_ids: List[str] = []53 unmodified lines}# ---------------------- Follow-up Suggestions ---------------------- #def _verify_answerable(question: str, *, db_level: Optional[str], model: str, max_words: int = 60) -> Tuple[bool, List[str]]:"""Check quickly if a follow-up question is answerable from the PDFs for the given db_levelby calling llm_explain with a short answer budget.Returns (ok, source_ids)."""try:res = llm_explain(ExplainBody(question=question,model=model,max_words=max_words,db_level=db_level,source_ids=None # verification uses full retrieval))except Exception:return (False, [])ans_text = (res.get("answer") or "").strip() if isinstance(res, dict) else (str(res).strip())src_ids: List[str] = []if isinstance(res, dict):val = res.get("source_ids")if isinstance(val, list):src_ids = valif not ans_text:return (False, src_ids)low = ans_text.lower()if ("no information available" in low) or ("not found" in low) or ("insufficient" in low):return (False, src_ids)return (True, src_ids)def llm_followups(body: FollowupBody) -> Dict[str, Any]:"""Suggest follow-up grammar questions based on the user's last question and the answer just given.Ground suggestions in the same textbook context (Chroma) used for the answer,and KEEP ONLY those that are actually answerable from the PDFs (verified via llm_explain)."""vs = get_vectorstore_for(body.db_level)99 unmodified linesif preferred:filtered = preferred# ---- Verification: keep only answerable follow-ups ----verified: List[str] = []for s in filtered:ok, _ = _verify_answerable(s,db_level=body.db_level,model=(body.model or "gpt-4o-mini"),max_words=60,)if ok:verified.append(s)if len(verified) >= max(1, body.n):breaknote = f"kept {len(verified)} of {len(filtered)} after verification" if filtered else "no candidates"return {"suggestions": verified[: max(1, body.n)],"source_ids": source_ids,"note": note}
ragg/app.py+17-50
ragg/rag_llm.py+72-15