qdb-knowledge-bot / app /rag /generator.py
ahmedala95's picture
Add conversation memory, persistent history, feedback, and analytics
060ab9b verified
Raw History Blame Contribute Delete
6.44 kB
from dataclasses import dataclass
from app.core.llm import generate
from app.rag.retriever import RetrievedChunk, retrieve
SYSTEM_PROMPT = """You are the internal knowledge assistant for QDB (بنك تنمية المهارات / Qualification Development Bank), Egypt's first accreditation institution for technical and vocational education and training (TVET). You serve QDB employees by answering their questions about the organization's procedures and operations.
QDB's seven core service areas:
1. Qualifications & Assessment Development — تطوير المؤهلات والتقييمات
2. Curriculum Content Development — تطوير المحتوى التدريبي
3. Accreditation of training providers — اعتماد مزودي التدريب
4. Trainer Development (TOT) — تدريب المدربين
5. Assessment Management — إدارة التقييم
6. Beneficiary Support — دعم المستفيدين
7. Consultation Services — الاستشارات
Employees may ask about any of these areas, internal procedures, qualification frameworks, accreditation criteria, or assessment workflows. Answer strictly from the provided CONTEXT (excerpts from official QDB documents).
Rules:
1. Answer only from the CONTEXT below. If the answer is not in the CONTEXT, reply: "لا تتوفر لدي معلومات كافية في المراجع المتاحة للإجابة على هذا السؤال." (or the English equivalent if the question is in English).
2. Always cite the source file and section for each fact you state, like: [filename.docx — Section Name].
3. Match the language of the question (Arabic question → Arabic answer; English question → English answer).
4. Be concise and accurate. Do not invent details, do not extrapolate beyond the CONTEXT.
5. If the user asks about a process or procedure (إجراء), present it as clear numbered steps.
6. If multiple sources contradict, mention both and indicate the conflict.
7. Use proper QDB terminology: "مؤهل" for qualification, "تقييم" for assessment, "اعتماد" for accreditation, "تدريب المدربين" or "TOT" for trainer-of-trainers.
"""
@dataclass
class Answer:
text: str
chunks: list[RetrievedChunk]
citations: list[dict]
def _format_context(chunks: list[RetrievedChunk]) -> str:
parts = []
for i, c in enumerate(chunks, 1):
header = f"[Source {i}] File: {c.source_file}"
if c.section:
header += f" | Section: {c.section}"
parts.append(f"{header}\n{c.text}")
return "\n\n---\n\n".join(parts)
def _format_history(history: list[dict]) -> str:
"""Render previous turns for the LLM, with a tag separating roles."""
if not history:
return ""
lines = []
for turn in history:
role = "USER" if turn.get("role") == "user" else "ASSISTANT"
lines.append(f"{role}: {turn.get('content', '').strip()}")
return "\n\n".join(lines)
def _condense_query(question: str, history: list[dict]) -> str:
"""Use the LLM to rewrite a follow-up question into a standalone query.
Why: the retriever embeds the *current* user message — if it's "ما هي
الخطوة التالية؟" it has no context. We rewrite it into a self-contained
question using the recent history, then retrieve on the rewritten form.
"""
if not history:
return question
convo = _format_history(history[-4:]) # last 2 user/assistant pairs
rewrite_prompt = (
"Given the conversation below, rewrite the FOLLOW-UP question as a standalone "
"question that can be understood without the prior context. Preserve the original "
"language. Output ONLY the rewritten question, nothing else.\n\n"
f"CONVERSATION:\n{convo}\n\nFOLLOW-UP: {question}\n\nSTANDALONE QUESTION:"
)
try:
rewritten = generate(rewrite_prompt).strip().strip('"').strip("'")
# Sanity: if rewrite is suspiciously empty or much longer than the original, keep original
if not rewritten or len(rewritten) > 4 * len(question) + 200:
return question
return rewritten
except Exception:
return question
def answer_question(
question: str,
top_k: int | None = None,
where: dict | None = None,
history: list[dict] | None = None,
) -> Answer:
"""Retrieve relevant chunks and generate a grounded answer with citations.
`history` is an optional list of {role, content} dicts (prior turns in the
same conversation). When provided, we (1) rewrite the question into a
standalone query for retrieval, and (2) include the recent turns in the
prompt so the LLM keeps continuity.
"""
history = history or []
# Step 1: rewrite follow-ups so retrieval has full context
retrieval_query = _condense_query(question, history) if history else question
chunks = retrieve(retrieval_query, top_k=top_k, where=where)
if not chunks:
return Answer(
text="لا توجد ملفات مفهرسة بعد، أو لا يوجد محتوى مرتبط بسؤالك.",
chunks=[],
citations=[],
)
context = _format_context(chunks)
history_block = ""
if history:
history_block = f"\n\nCONVERSATION SO FAR:\n{_format_history(history[-6:])}\n"
prompt = (
f"CONTEXT:\n{context}"
f"{history_block}\n"
f"\nUSER QUESTION: {question}\n\nANSWER:"
)
text = generate(prompt, system=SYSTEM_PROMPT)
citations = [
{"source_file": c.source_file, "section": c.section, "score": round(c.score, 3)}
for c in chunks
]
return Answer(text=text, chunks=chunks, citations=citations)
def generate_title(first_user_message: str) -> str:
"""Use the LLM to produce a short 3-6 word title for a new conversation."""
prompt = (
"Generate a short, descriptive title (3-6 words MAX) for a chat that starts "
"with the user message below. Output ONLY the title, no quotes, no punctuation. "
"Match the language of the message.\n\n"
f"USER MESSAGE: {first_user_message}\n\nTITLE:"
)
try:
title = generate(prompt).strip().strip('"').strip("'").strip(".")
# Truncate to safe length and remove newlines
title = title.split("\n")[0][:60].strip()
return title or first_user_message[:40]
except Exception:
return first_user_message[:40]