Spaces:
Running
Running
Upload 3 files
Browse files- app.py +138 -70
- embeddings.json +0 -0
- requirements.txt +4 -0
app.py
CHANGED
|
@@ -1,70 +1,138 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
)
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
""
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
)
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import datetime
|
| 4 |
+
import threading
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
from langchain_nvidia_ai_endpoints import ChatNVIDIA, NVIDIAEmbeddings
|
| 11 |
+
|
| 12 |
+
# ================= ENV =================
|
| 13 |
+
load_dotenv()
|
| 14 |
+
NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY")
|
| 15 |
+
if not NVIDIA_API_KEY:
|
| 16 |
+
raise RuntimeError("NVIDIA_API_KEY not found")
|
| 17 |
+
|
| 18 |
+
os.environ["NVIDIA_API_KEY"] = NVIDIA_API_KEY
|
| 19 |
+
|
| 20 |
+
# ================= CONFIG =================
|
| 21 |
+
DAILY_LIMIT = 50
|
| 22 |
+
RATE_FILE = Path("rate_limit.json")
|
| 23 |
+
EMBEDDINGS_FILE = Path("embeddings.json")
|
| 24 |
+
MAX_HISTORY_TURNS = 3 # keep last 3 Q/A pairs
|
| 25 |
+
|
| 26 |
+
lock = threading.Lock()
|
| 27 |
+
|
| 28 |
+
# ================= MODELS =================
|
| 29 |
+
embedder = NVIDIAEmbeddings(
|
| 30 |
+
model="nvidia/nv-embed-v1",
|
| 31 |
+
truncate="END"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
llm = ChatNVIDIA(
|
| 35 |
+
model="mistralai/mixtral-8x22b-instruct-v0.1",
|
| 36 |
+
temperature=0.2
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# ================= LOAD DOCS =================
|
| 40 |
+
with open(EMBEDDINGS_FILE) as f:
|
| 41 |
+
DOCS = json.load(f)
|
| 42 |
+
|
| 43 |
+
# ================= UTILS =================
|
| 44 |
+
def cosine(a, b):
|
| 45 |
+
a, b = np.array(a), np.array(b)
|
| 46 |
+
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
|
| 47 |
+
|
| 48 |
+
def retrieve(question, k=4):
|
| 49 |
+
qvec = embedder.embed_query(question)
|
| 50 |
+
scored = [(cosine(qvec, d["embedding"]), d["text"]) for d in DOCS]
|
| 51 |
+
scored.sort(reverse=True)
|
| 52 |
+
return [t for _, t in scored[:k]]
|
| 53 |
+
|
| 54 |
+
def check_rate_limit():
|
| 55 |
+
today = datetime.date.today().isoformat()
|
| 56 |
+
with lock:
|
| 57 |
+
data = json.loads(RATE_FILE.read_text()) if RATE_FILE.exists() else {}
|
| 58 |
+
if data.get(today, 0) >= DAILY_LIMIT:
|
| 59 |
+
return False
|
| 60 |
+
data[today] = data.get(today, 0) + 1
|
| 61 |
+
RATE_FILE.write_text(json.dumps(data))
|
| 62 |
+
return True
|
| 63 |
+
|
| 64 |
+
def build_prompt(context, history, question):
|
| 65 |
+
history_text = "\n".join(
|
| 66 |
+
f"User: {q}\nAssistant: {a}"
|
| 67 |
+
for q, a in history[-MAX_HISTORY_TURNS:]
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
return f"""
|
| 71 |
+
You are a document-grounded assistant.
|
| 72 |
+
Answer ONLY using the context.
|
| 73 |
+
If the answer is not present, say "I don't know".
|
| 74 |
+
|
| 75 |
+
Conversation so far:
|
| 76 |
+
{history_text}
|
| 77 |
+
|
| 78 |
+
Context:
|
| 79 |
+
{"\n\n---\n\n".join(context)}
|
| 80 |
+
|
| 81 |
+
User question:
|
| 82 |
+
{question}
|
| 83 |
+
""".strip()
|
| 84 |
+
|
| 85 |
+
# ================= CHAT FN (STREAMING) =================
|
| 86 |
+
def chat_stream(question, history):
|
| 87 |
+
if not question.strip():
|
| 88 |
+
yield history
|
| 89 |
+
return
|
| 90 |
+
|
| 91 |
+
if not check_rate_limit():
|
| 92 |
+
history.append((question, "Daily limit reached (50 queries)."))
|
| 93 |
+
yield history
|
| 94 |
+
return
|
| 95 |
+
|
| 96 |
+
context = retrieve(question)
|
| 97 |
+
prompt = build_prompt(context, history, question)
|
| 98 |
+
|
| 99 |
+
partial = ""
|
| 100 |
+
for chunk in llm.stream(prompt):
|
| 101 |
+
partial += chunk.content
|
| 102 |
+
yield history + [(question, partial)]
|
| 103 |
+
|
| 104 |
+
# ================= UI =================
|
| 105 |
+
with gr.Blocks(title="Academic Regulations RAG") as demo:
|
| 106 |
+
gr.Markdown("## 📘 Academic Regulations Queries")
|
| 107 |
+
gr.Markdown(
|
| 108 |
+
"Ask questions about the academic regulations document. "
|
| 109 |
+
"Answers are generated **only** from the official document."
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
chatbot = gr.Chatbot(height=420)
|
| 113 |
+
|
| 114 |
+
question = gr.Textbox(
|
| 115 |
+
placeholder="e.g. What is the E grade?",
|
| 116 |
+
label="Your question",
|
| 117 |
+
scale=4
|
| 118 |
+
)
|
| 119 |
+
ask = gr.Button("Ask", scale=1, min_width=100)
|
| 120 |
+
|
| 121 |
+
clear = gr.Button("Clear Chat")
|
| 122 |
+
|
| 123 |
+
ask.click(chat_stream, [question, chatbot], chatbot)
|
| 124 |
+
|
| 125 |
+
question.submit(
|
| 126 |
+
chat_stream,
|
| 127 |
+
inputs=[question, chatbot],
|
| 128 |
+
outputs=chatbot
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
clear.click(lambda: [], None, chatbot)
|
| 132 |
+
|
| 133 |
+
# ================= RUN =================
|
| 134 |
+
if __name__ == "__main__":
|
| 135 |
+
demo.launch(
|
| 136 |
+
server_name="0.0.0.0",
|
| 137 |
+
server_port=int(os.getenv("PORT", 7860))
|
| 138 |
+
)
|
embeddings.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
numpy
|
| 3 |
+
python-dotenv
|
| 4 |
+
langchain-nvidia-ai-endpoints
|