Krish2005tech2 commited on
Commit
de1c0ef
·
verified ·
1 Parent(s): 2638548

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +138 -70
  2. embeddings.json +0 -0
  3. requirements.txt +4 -0
app.py CHANGED
@@ -1,70 +1,138 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
-
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
-
68
-
69
- if __name__ == "__main__":
70
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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