Spaces:
Running
Running
Update rag.py
Browse files
rag.py
CHANGED
@@ -2,14 +2,10 @@ import json
|
|
2 |
from sentence_transformers import SentenceTransformer, util
|
3 |
from groq import Groq
|
4 |
from datetime import datetime
|
5 |
-
import requests
|
6 |
-
from datasets import load_dataset, Dataset
|
7 |
-
from io import BytesIO
|
8 |
-
from PIL import Image, ImageDraw, ImageFont
|
9 |
-
import numpy as np
|
10 |
-
from dotenv import load_dotenv
|
11 |
import os
|
12 |
import pandas as pd
|
|
|
|
|
13 |
|
14 |
# Load environment variables
|
15 |
load_dotenv()
|
@@ -17,16 +13,22 @@ load_dotenv()
|
|
17 |
# Initialize Groq client
|
18 |
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
19 |
|
20 |
-
# Load
|
21 |
similarity_model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
|
22 |
|
23 |
# Config
|
24 |
HF_DATASET_REPO = "midrees2806/unmatched_queries"
|
25 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
26 |
|
27 |
-
# Load dataset
|
28 |
-
|
29 |
-
dataset
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
# Precompute embeddings
|
32 |
dataset_questions = [item.get("Question", "").lower().strip() for item in dataset]
|
@@ -50,6 +52,7 @@ def manage_unmatched_queries(query: str):
|
|
50 |
except Exception as e:
|
51 |
print(f"Failed to save query: {e}")
|
52 |
|
|
|
53 |
def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
54 |
try:
|
55 |
chat_completion = groq_client.chat.completions.create(
|
@@ -66,24 +69,23 @@ def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
|
66 |
print(f"Error querying Groq API: {e}")
|
67 |
return ""
|
68 |
|
|
|
69 |
def get_best_answer(user_input):
|
70 |
-
|
71 |
if not user_input.strip():
|
72 |
return "Please enter a valid question."
|
|
|
73 |
user_input_lower = user_input.lower().strip()
|
74 |
|
75 |
-
if len(user_input_lower.split()) < 3:
|
76 |
return "Please ask your question properly with at least 3 words."
|
77 |
|
78 |
-
|
79 |
-
if any(keyword in user_input_lower for keyword in ["fee structure", "fees structure"]):
|
80 |
return (
|
81 |
"π° For complete and up-to-date fee details for this program, we recommend visiting the official University of Education fee structure page.\n"
|
82 |
-
"You
|
83 |
"π https://ue.edu.pk/allfeestructure.php"
|
84 |
)
|
85 |
|
86 |
-
# π Continue with normal similarity-based logic
|
87 |
user_embedding = similarity_model.encode(user_input_lower, convert_to_tensor=True)
|
88 |
similarities = util.pytorch_cos_sim(user_embedding, dataset_embeddings)[0]
|
89 |
best_match_idx = similarities.argmax().item()
|
@@ -91,33 +93,45 @@ def get_best_answer(user_input):
|
|
91 |
|
92 |
if best_score < 0.65:
|
93 |
manage_unmatched_queries(user_input)
|
94 |
-
|
95 |
if best_score >= 0.65:
|
96 |
original_answer = dataset_answers[best_match_idx]
|
97 |
-
prompt = f"""
|
98 |
-
|
99 |
-
|
100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
else:
|
102 |
-
prompt = f"""As an official assistant for University of Education Lahore, provide a helpful response:
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
|
|
|
|
|
|
|
|
107 |
|
108 |
llm_response = query_groq_llm(prompt)
|
109 |
|
110 |
if llm_response:
|
111 |
-
for marker in ["Improved Answer:", "Official Answer:"]:
|
112 |
if marker in llm_response:
|
113 |
-
|
114 |
-
|
115 |
-
else:
|
116 |
-
response = llm_response
|
117 |
else:
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
|
|
2 |
from sentence_transformers import SentenceTransformer, util
|
3 |
from groq import Groq
|
4 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import os
|
6 |
import pandas as pd
|
7 |
+
from datasets import load_dataset, Dataset
|
8 |
+
from dotenv import load_dotenv
|
9 |
|
10 |
# Load environment variables
|
11 |
load_dotenv()
|
|
|
13 |
# Initialize Groq client
|
14 |
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
15 |
|
16 |
+
# Load similarity model
|
17 |
similarity_model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
|
18 |
|
19 |
# Config
|
20 |
HF_DATASET_REPO = "midrees2806/unmatched_queries"
|
21 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
22 |
|
23 |
+
# Load local dataset
|
24 |
+
try:
|
25 |
+
with open('dataset.json', 'r') as f:
|
26 |
+
dataset = json.load(f)
|
27 |
+
if not all(isinstance(item, dict) and 'Question' in item and 'Answer' in item for item in dataset):
|
28 |
+
raise ValueError("Invalid dataset structure")
|
29 |
+
except Exception as e:
|
30 |
+
print(f"Error loading dataset: {e}")
|
31 |
+
dataset = []
|
32 |
|
33 |
# Precompute embeddings
|
34 |
dataset_questions = [item.get("Question", "").lower().strip() for item in dataset]
|
|
|
52 |
except Exception as e:
|
53 |
print(f"Failed to save query: {e}")
|
54 |
|
55 |
+
# Query Groq LLM
|
56 |
def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
57 |
try:
|
58 |
chat_completion = groq_client.chat.completions.create(
|
|
|
69 |
print(f"Error querying Groq API: {e}")
|
70 |
return ""
|
71 |
|
72 |
+
# Main logic function to be called from Gradio
|
73 |
def get_best_answer(user_input):
|
|
|
74 |
if not user_input.strip():
|
75 |
return "Please enter a valid question."
|
76 |
+
|
77 |
user_input_lower = user_input.lower().strip()
|
78 |
|
79 |
+
if len(user_input_lower.split()) < 3 and not any(greet in user_input_lower for greet in GREETINGS):
|
80 |
return "Please ask your question properly with at least 3 words."
|
81 |
|
82 |
+
if any(keyword in user_input_lower for keyword in ["fee structure", "fees structure", "semester fees", "semester fee"]):
|
|
|
83 |
return (
|
84 |
"π° For complete and up-to-date fee details for this program, we recommend visiting the official University of Education fee structure page.\n"
|
85 |
+
"You'll find comprehensive information regarding tuition, admission charges, and other applicable fees there.\n"
|
86 |
"π https://ue.edu.pk/allfeestructure.php"
|
87 |
)
|
88 |
|
|
|
89 |
user_embedding = similarity_model.encode(user_input_lower, convert_to_tensor=True)
|
90 |
similarities = util.pytorch_cos_sim(user_embedding, dataset_embeddings)[0]
|
91 |
best_match_idx = similarities.argmax().item()
|
|
|
93 |
|
94 |
if best_score < 0.65:
|
95 |
manage_unmatched_queries(user_input)
|
96 |
+
|
97 |
if best_score >= 0.65:
|
98 |
original_answer = dataset_answers[best_match_idx]
|
99 |
+
prompt = f"""Name is UOE AI Assistant! You are an official assistant for the University of Education Lahore.
|
100 |
+
|
101 |
+
Rephrase the following official answer clearly and professionally.
|
102 |
+
Use structured formatting (like headings, bullet points, or numbered lists) where appropriate.
|
103 |
+
DO NOT add any new or extra information. ONLY rephrase and improve the clarity and formatting of the original answer.
|
104 |
+
|
105 |
+
### Question:
|
106 |
+
{user_input}
|
107 |
+
|
108 |
+
### Original Answer:
|
109 |
+
{original_answer}
|
110 |
+
|
111 |
+
### Rephrased Answer:
|
112 |
+
"""
|
113 |
else:
|
114 |
+
prompt = f"""Name is UOE AI Assistant! As an official assistant for University of Education Lahore, provide a helpful response:
|
115 |
+
Include relevant details about university policies.
|
116 |
+
If unsure, direct to official channels.
|
117 |
+
|
118 |
+
### Question:
|
119 |
+
{user_input}
|
120 |
+
|
121 |
+
### Official Answer:
|
122 |
+
"""
|
123 |
|
124 |
llm_response = query_groq_llm(prompt)
|
125 |
|
126 |
if llm_response:
|
127 |
+
for marker in ["Improved Answer:", "Official Answer:", "Rephrased Answer:"]:
|
128 |
if marker in llm_response:
|
129 |
+
return llm_response.split(marker)[-1].strip()
|
130 |
+
return llm_response
|
|
|
|
|
131 |
else:
|
132 |
+
return dataset_answers[best_match_idx] if best_score >= 0.65 else (
|
133 |
+
"For official information:\n"
|
134 |
+
"π +92-42-99262231-33\n"
|
135 |
+
"βοΈ info@ue.edu.pk\n"
|
136 |
+
"π https://ue.edu.pk"
|
137 |
+
)
|