Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files- .env.example +6 -2
- app/__pycache__/main.cpython-312.pyc +0 -0
- app/main.py +169 -73
.env.example
CHANGED
|
@@ -1,12 +1,16 @@
|
|
| 1 |
KB_BACKEND=qdrant
|
| 2 |
-
RAG_RETRIEVAL_MODE=
|
|
|
|
|
|
|
|
|
|
| 3 |
QDRANT_URL=
|
| 4 |
QDRANT_API_KEY=
|
| 5 |
QDRANT_COLLECTION=doc_kb
|
| 6 |
|
| 7 |
HUGGINGFACE_API_TOKEN=
|
| 8 |
GROQ_API_KEY=
|
| 9 |
-
RAG_MODEL_ID=
|
|
|
|
| 10 |
RAG_TEMPERATURE=0.2
|
| 11 |
RAG_MAX_TOKENS=512
|
| 12 |
|
|
|
|
| 1 |
KB_BACKEND=qdrant
|
| 2 |
+
RAG_RETRIEVAL_MODE=semantic
|
| 3 |
+
RAG_LLM_RERANK=true
|
| 4 |
+
RAG_RERANK_CANDIDATES=8
|
| 5 |
+
RAG_RERANK_MAX_TOKENS=280
|
| 6 |
QDRANT_URL=
|
| 7 |
QDRANT_API_KEY=
|
| 8 |
QDRANT_COLLECTION=doc_kb
|
| 9 |
|
| 10 |
HUGGINGFACE_API_TOKEN=
|
| 11 |
GROQ_API_KEY=
|
| 12 |
+
RAG_MODEL_ID=llama-3.1-8b-instant
|
| 13 |
+
RAG_MODEL_CANDIDATES=llama-3.1-8b-instant,llama-3.3-70b-versatile,openai/gpt-oss-20b
|
| 14 |
RAG_TEMPERATURE=0.2
|
| 15 |
RAG_MAX_TOKENS=512
|
| 16 |
|
app/__pycache__/main.cpython-312.pyc
CHANGED
|
Binary files a/app/__pycache__/main.cpython-312.pyc and b/app/__pycache__/main.cpython-312.pyc differ
|
|
|
app/main.py
CHANGED
|
@@ -44,7 +44,7 @@ VISUAL_TYPES = {
|
|
| 44 |
_VECTORSTORE: Optional[Any] = None
|
| 45 |
_EMBEDDINGS: Optional[Any] = None
|
| 46 |
|
| 47 |
-
STOPWORDS = {
|
| 48 |
"the",
|
| 49 |
"and",
|
| 50 |
"for",
|
|
@@ -101,11 +101,22 @@ STOPWORDS = {
|
|
| 101 |
"you",
|
| 102 |
"they",
|
| 103 |
"their",
|
| 104 |
-
"them",
|
| 105 |
-
}
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
role: str
|
| 110 |
content: str
|
| 111 |
|
|
@@ -195,13 +206,33 @@ def get_rerank_candidate_k(top_k: int) -> int:
|
|
| 195 |
return max(int(top_k), cfg)
|
| 196 |
|
| 197 |
|
| 198 |
-
def hf_routed_model(model_id: str) -> str:
|
| 199 |
-
return model_id if ":" in model_id else f"{model_id}:groq"
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
def
|
| 203 |
-
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
messages: list[dict[str, Any]],
|
| 206 |
temperature: float,
|
| 207 |
max_tokens: int,
|
|
@@ -217,48 +248,65 @@ def openai_chat(
|
|
| 217 |
return content or "", resp
|
| 218 |
|
| 219 |
|
| 220 |
-
def llm_chat_with_fallback(
|
| 221 |
-
model_id: str,
|
| 222 |
messages: list[dict[str, Any]],
|
| 223 |
temperature: float,
|
| 224 |
max_tokens: int,
|
| 225 |
hf_token: Optional[str],
|
| 226 |
groq_key: Optional[str],
|
| 227 |
-
) -> dict[str, Any]:
|
| 228 |
-
result: dict[str, Any] = {
|
| 229 |
-
"content": "",
|
| 230 |
-
"primary_used": False,
|
| 231 |
-
"raw": None,
|
| 232 |
-
"
|
| 233 |
-
"
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
result["
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
|
| 263 |
|
| 264 |
def load_faiss(embeddings: Any, path: Path = FAISS_DIR) -> Optional[FAISS]:
|
|
@@ -669,7 +717,7 @@ def llm_rerank_chunks(
|
|
| 669 |
return re_ranked_candidates + remaining_candidates + chunks[candidate_limit:], None
|
| 670 |
|
| 671 |
|
| 672 |
-
def build_qa_prompt_with_history(
|
| 673 |
history: list[dict[str, str]],
|
| 674 |
context_blocks: list[str],
|
| 675 |
question: str,
|
|
@@ -696,11 +744,34 @@ def build_qa_prompt_with_history(
|
|
| 696 |
]
|
| 697 |
messages.extend(msgs)
|
| 698 |
context_blob = "\n\n".join(context_blocks)
|
| 699 |
-
messages.append({"role": "user", "content": f"Snippets:\n{context_blob}\n\nQuestion: {question}\nAnswer:"})
|
| 700 |
-
return messages
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 704 |
if not chunks:
|
| 705 |
return "No relevant content found in the knowledge base."
|
| 706 |
lines = []
|
|
@@ -750,20 +821,41 @@ def health() -> dict[str, str]:
|
|
| 750 |
@app.post("/query", response_model=QueryResponse)
|
| 751 |
def query(payload: QueryRequest) -> QueryResponse:
|
| 752 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 753 |
retrieved = retrieve_from_uploaded_document(payload)
|
| 754 |
if not retrieved:
|
| 755 |
retrieved = retrieve_from_vectorstore(payload)
|
| 756 |
|
| 757 |
if not retrieved:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 758 |
return QueryResponse(answer="No relevant content found in the knowledge base.", retrievedChunks=[], citations=[])
|
| 759 |
|
| 760 |
-
model_id = get_secret("RAG_MODEL_ID", "openai/gpt-oss-20b") or "openai/gpt-oss-20b"
|
| 761 |
-
temperature = float(get_secret("RAG_TEMPERATURE", "0.2") or "0.2")
|
| 762 |
-
max_tokens = int(get_secret("RAG_MAX_TOKENS", "512") or "512")
|
| 763 |
-
hf_token = get_secret("HUGGINGFACE_API_TOKEN")
|
| 764 |
-
groq_key = get_secret("GROQ_API_KEY")
|
| 765 |
-
history = [m.model_dump() for m in payload.history]
|
| 766 |
-
|
| 767 |
retrieved, clarifying_question = llm_rerank_chunks(
|
| 768 |
question=payload.message,
|
| 769 |
history=history,
|
|
@@ -786,16 +878,20 @@ def query(payload: QueryRequest) -> QueryResponse:
|
|
| 786 |
max_tokens=max_tokens,
|
| 787 |
hf_token=hf_token,
|
| 788 |
groq_key=groq_key,
|
| 789 |
-
)
|
| 790 |
-
answer = normalize_text(result.get("content", ""))
|
| 791 |
-
if not answer:
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
"
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 799 |
|
| 800 |
if "not found in the knowledge base" in answer.lower() and context_blocks:
|
| 801 |
retry_messages = [
|
|
|
|
| 44 |
_VECTORSTORE: Optional[Any] = None
|
| 45 |
_EMBEDDINGS: Optional[Any] = None
|
| 46 |
|
| 47 |
+
STOPWORDS = {
|
| 48 |
"the",
|
| 49 |
"and",
|
| 50 |
"for",
|
|
|
|
| 101 |
"you",
|
| 102 |
"they",
|
| 103 |
"their",
|
| 104 |
+
"them",
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
DOC_GROUNDED_RE = re.compile(
|
| 108 |
+
r"\b(document|doc|pdf|page|citation|snippet|source|context|table|figure|selected)\b",
|
| 109 |
+
flags=re.IGNORECASE,
|
| 110 |
+
)
|
| 111 |
+
DEFAULT_MODEL_ID = "llama-3.1-8b-instant"
|
| 112 |
+
DEFAULT_MODEL_CANDIDATES = [
|
| 113 |
+
"llama-3.1-8b-instant",
|
| 114 |
+
"llama-3.3-70b-versatile",
|
| 115 |
+
"openai/gpt-oss-20b",
|
| 116 |
+
]
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class HistoryMessage(BaseModel):
|
| 120 |
role: str
|
| 121 |
content: str
|
| 122 |
|
|
|
|
| 206 |
return max(int(top_k), cfg)
|
| 207 |
|
| 208 |
|
| 209 |
+
def hf_routed_model(model_id: str) -> str:
|
| 210 |
+
return model_id if ":" in model_id else f"{model_id}:groq"
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def get_model_candidates(model_id: str) -> list[str]:
|
| 214 |
+
preferred = normalize_text(model_id) or DEFAULT_MODEL_ID
|
| 215 |
+
raw = (get_secret("RAG_MODEL_CANDIDATES", "") or "").strip()
|
| 216 |
+
if raw:
|
| 217 |
+
candidates = [normalize_text(part) for part in raw.split(",")]
|
| 218 |
+
candidates = [c for c in candidates if c]
|
| 219 |
+
else:
|
| 220 |
+
candidates = [preferred] + [m for m in DEFAULT_MODEL_CANDIDATES if m != preferred]
|
| 221 |
+
|
| 222 |
+
deduped: list[str] = []
|
| 223 |
+
seen: set[str] = set()
|
| 224 |
+
for candidate in candidates:
|
| 225 |
+
key = candidate.lower()
|
| 226 |
+
if key in seen:
|
| 227 |
+
continue
|
| 228 |
+
seen.add(key)
|
| 229 |
+
deduped.append(candidate)
|
| 230 |
+
return deduped or [DEFAULT_MODEL_ID]
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def openai_chat(
|
| 234 |
+
client: OpenAI,
|
| 235 |
+
model: str,
|
| 236 |
messages: list[dict[str, Any]],
|
| 237 |
temperature: float,
|
| 238 |
max_tokens: int,
|
|
|
|
| 248 |
return content or "", resp
|
| 249 |
|
| 250 |
|
| 251 |
+
def llm_chat_with_fallback(
|
| 252 |
+
model_id: str,
|
| 253 |
messages: list[dict[str, Any]],
|
| 254 |
temperature: float,
|
| 255 |
max_tokens: int,
|
| 256 |
hf_token: Optional[str],
|
| 257 |
groq_key: Optional[str],
|
| 258 |
+
) -> dict[str, Any]:
|
| 259 |
+
result: dict[str, Any] = {
|
| 260 |
+
"content": "",
|
| 261 |
+
"primary_used": False,
|
| 262 |
+
"raw": None,
|
| 263 |
+
"used_model": None,
|
| 264 |
+
"error_primary": None,
|
| 265 |
+
"error_fallback": None,
|
| 266 |
+
}
|
| 267 |
+
candidate_models = get_model_candidates(model_id)
|
| 268 |
+
|
| 269 |
+
if hf_token:
|
| 270 |
+
hf_client = OpenAI(base_url="https://router.huggingface.co/v1", api_key=hf_token)
|
| 271 |
+
primary_errors: list[str] = []
|
| 272 |
+
for candidate in candidate_models:
|
| 273 |
+
try:
|
| 274 |
+
routed = hf_routed_model(candidate)
|
| 275 |
+
content, raw = openai_chat(hf_client, routed, messages, temperature, max_tokens)
|
| 276 |
+
if normalize_text(content):
|
| 277 |
+
result.update(
|
| 278 |
+
{
|
| 279 |
+
"content": content,
|
| 280 |
+
"primary_used": True,
|
| 281 |
+
"raw": raw,
|
| 282 |
+
"used_model": candidate,
|
| 283 |
+
}
|
| 284 |
+
)
|
| 285 |
+
return result
|
| 286 |
+
primary_errors.append(f"{candidate}: empty content")
|
| 287 |
+
except Exception as exc: # pragma: no cover
|
| 288 |
+
primary_errors.append(f"{candidate}: {type(exc).__name__}: {exc}")
|
| 289 |
+
result["error_primary"] = " | ".join(primary_errors[:4]) or "Primary returned empty content."
|
| 290 |
+
else:
|
| 291 |
+
result["error_primary"] = "Missing HUGGINGFACE_API_TOKEN"
|
| 292 |
+
|
| 293 |
+
if not groq_key:
|
| 294 |
+
result["error_fallback"] = "Missing GROQ_API_KEY (fallback not available)"
|
| 295 |
+
return result
|
| 296 |
+
|
| 297 |
+
groq_client = OpenAI(base_url="https://api.groq.com/openai/v1", api_key=groq_key)
|
| 298 |
+
fallback_errors: list[str] = []
|
| 299 |
+
for candidate in candidate_models:
|
| 300 |
+
try:
|
| 301 |
+
content, raw = openai_chat(groq_client, candidate, messages, temperature, max_tokens)
|
| 302 |
+
if normalize_text(content):
|
| 303 |
+
result.update({"content": content, "raw": raw, "used_model": candidate})
|
| 304 |
+
return result
|
| 305 |
+
fallback_errors.append(f"{candidate}: empty content")
|
| 306 |
+
except Exception as exc: # pragma: no cover
|
| 307 |
+
fallback_errors.append(f"{candidate}: {type(exc).__name__}: {exc}")
|
| 308 |
+
result["error_fallback"] = " | ".join(fallback_errors[:4]) or "Fallback returned empty content."
|
| 309 |
+
return result
|
| 310 |
|
| 311 |
|
| 312 |
def load_faiss(embeddings: Any, path: Path = FAISS_DIR) -> Optional[FAISS]:
|
|
|
|
| 717 |
return re_ranked_candidates + remaining_candidates + chunks[candidate_limit:], None
|
| 718 |
|
| 719 |
|
| 720 |
+
def build_qa_prompt_with_history(
|
| 721 |
history: list[dict[str, str]],
|
| 722 |
context_blocks: list[str],
|
| 723 |
question: str,
|
|
|
|
| 744 |
]
|
| 745 |
messages.extend(msgs)
|
| 746 |
context_blob = "\n\n".join(context_blocks)
|
| 747 |
+
messages.append({"role": "user", "content": f"Snippets:\n{context_blob}\n\nQuestion: {question}\nAnswer:"})
|
| 748 |
+
return messages
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
def build_general_chat_prompt(history: list[dict[str, str]], question: str, max_history_turns: int = 8) -> list[dict[str, str]]:
|
| 752 |
+
msgs = [m for m in history if m.get("role") in ("user", "assistant")]
|
| 753 |
+
if len(msgs) > max_history_turns * 2:
|
| 754 |
+
msgs = msgs[-max_history_turns * 2 :]
|
| 755 |
+
messages: list[dict[str, str]] = [
|
| 756 |
+
{
|
| 757 |
+
"role": "system",
|
| 758 |
+
"content": (
|
| 759 |
+
"You are ChatQnA, a concise and helpful assistant. "
|
| 760 |
+
"Answer naturally. If user asks document-specific questions without available context, "
|
| 761 |
+
"ask them to upload/select the relevant document section."
|
| 762 |
+
),
|
| 763 |
+
}
|
| 764 |
+
]
|
| 765 |
+
messages.extend(msgs)
|
| 766 |
+
messages.append({"role": "user", "content": question})
|
| 767 |
+
return messages
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def is_doc_grounded_query(question: str) -> bool:
|
| 771 |
+
return bool(DOC_GROUNDED_RE.search(question or ""))
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
def build_local_fallback_answer(chunks: list[dict[str, Any]]) -> str:
|
| 775 |
if not chunks:
|
| 776 |
return "No relevant content found in the knowledge base."
|
| 777 |
lines = []
|
|
|
|
| 821 |
@app.post("/query", response_model=QueryResponse)
|
| 822 |
def query(payload: QueryRequest) -> QueryResponse:
|
| 823 |
try:
|
| 824 |
+
model_id = get_secret("RAG_MODEL_ID", DEFAULT_MODEL_ID) or DEFAULT_MODEL_ID
|
| 825 |
+
temperature = float(get_secret("RAG_TEMPERATURE", "0.2") or "0.2")
|
| 826 |
+
max_tokens = int(get_secret("RAG_MAX_TOKENS", "512") or "512")
|
| 827 |
+
hf_token = get_secret("HUGGINGFACE_API_TOKEN")
|
| 828 |
+
groq_key = get_secret("GROQ_API_KEY")
|
| 829 |
+
history = [m.model_dump() for m in payload.history]
|
| 830 |
+
|
| 831 |
retrieved = retrieve_from_uploaded_document(payload)
|
| 832 |
if not retrieved:
|
| 833 |
retrieved = retrieve_from_vectorstore(payload)
|
| 834 |
|
| 835 |
if not retrieved:
|
| 836 |
+
if not is_doc_grounded_query(payload.message):
|
| 837 |
+
general_messages = build_general_chat_prompt(history, payload.message, max_history_turns=8)
|
| 838 |
+
general = llm_chat_with_fallback(
|
| 839 |
+
model_id=model_id,
|
| 840 |
+
messages=general_messages,
|
| 841 |
+
temperature=temperature,
|
| 842 |
+
max_tokens=max_tokens,
|
| 843 |
+
hf_token=hf_token,
|
| 844 |
+
groq_key=groq_key,
|
| 845 |
+
)
|
| 846 |
+
general_answer = normalize_text(general.get("content", ""))
|
| 847 |
+
if general_answer:
|
| 848 |
+
return QueryResponse(answer=general_answer, retrievedChunks=[], citations=[])
|
| 849 |
+
return QueryResponse(
|
| 850 |
+
answer=(
|
| 851 |
+
"I can answer this, but the answer model is currently unavailable. "
|
| 852 |
+
"Please retry shortly."
|
| 853 |
+
),
|
| 854 |
+
retrievedChunks=[],
|
| 855 |
+
citations=[],
|
| 856 |
+
)
|
| 857 |
return QueryResponse(answer="No relevant content found in the knowledge base.", retrievedChunks=[], citations=[])
|
| 858 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 859 |
retrieved, clarifying_question = llm_rerank_chunks(
|
| 860 |
question=payload.message,
|
| 861 |
history=history,
|
|
|
|
| 878 |
max_tokens=max_tokens,
|
| 879 |
hf_token=hf_token,
|
| 880 |
groq_key=groq_key,
|
| 881 |
+
)
|
| 882 |
+
answer = normalize_text(result.get("content", ""))
|
| 883 |
+
if not answer:
|
| 884 |
+
answer = build_local_fallback_answer(retrieved)
|
| 885 |
+
if result.get("error_primary") or result.get("error_fallback"):
|
| 886 |
+
print(
|
| 887 |
+
"llm_unavailable:",
|
| 888 |
+
{
|
| 889 |
+
"model_candidates": get_model_candidates(model_id),
|
| 890 |
+
"error_primary": result.get("error_primary"),
|
| 891 |
+
"error_fallback": result.get("error_fallback"),
|
| 892 |
+
},
|
| 893 |
+
)
|
| 894 |
+
answer += "\n\n(LLM unavailable right now; showing highest-signal retrieved context.)"
|
| 895 |
|
| 896 |
if "not found in the knowledge base" in answer.lower() and context_blocks:
|
| 897 |
retry_messages = [
|