import gradio as gr from langchain_chroma import Chroma from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpoint, ChatHuggingFace from langchain_core.prompts import ChatPromptTemplate import os # ── Load once at startup ────────────────────────────────────────────────────── embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2") vector_store = Chroma(persist_directory="chroma_policy_db", embedding_function=embeddings) llm = HuggingFaceEndpoint( repo_id="HuggingFaceH4/zephyr-7b-beta", task="text-generation", huggingfacehub_api_token=os.getenv(""), max_new_tokens=150, temperature=0.1, repetition_penalty=1.1 ) model = ChatHuggingFace(llm=llm) prompt_template = ChatPromptTemplate.from_template("""<|system|> You are Docent, a university policy expert for SSUET. Answer based ONLY on the policy documents. Be concise — 2-4 sentences max. If not found, say: "Not available in current policy documents." <|user|> POLICY CONTEXT: {context} STUDENT QUERY: {query} <|assistant|> """) def answer(query, history): retriever = vector_store.as_retriever(search_kwargs={"k": 4}) chunks = retriever.invoke(query) context = "" sources = [] for chunk in chunks: context += chunk.page_content + "\n\n" fname = chunk.metadata.get("file_name", "") if fname and fname not in sources: sources.append(fname) prompt = prompt_template.format_messages(context=context, query=query) response = model.invoke(prompt) source_text = "\n\n📎 **Sources:** " + ", ".join(sources) if sources else "" return response.content + source_text demo = gr.ChatInterface( fn=answer, title="Docent AI — SSUET Policy Engine", description="Ask questions about SSUET university policies. Answers are based solely on official policy documents.", examples=[ "How to apply for research funding?", "What is the attendance policy?", "What are thesis submission requirements?", ] ) demo.launch()