Spaces:
Runtime error
Runtime error
Update chatbot.py
Browse files- chatbot.py +77 -123
chatbot.py
CHANGED
|
@@ -1,28 +1,25 @@
|
|
| 1 |
-
import warnings
|
| 2 |
-
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
| 3 |
import os
|
|
|
|
|
|
|
| 4 |
from groq import Groq
|
| 5 |
from langchain.memory import ConversationTokenBufferMemory
|
| 6 |
-
from langchain.memory import ConversationBufferMemory
|
| 7 |
from langchain_community.chat_models import ChatOpenAI
|
| 8 |
-
from langdetect import detect
|
| 9 |
-
from deep_translator import GoogleTranslator
|
| 10 |
from langchain_community.document_loaders.csv_loader import CSVLoader
|
| 11 |
from langchain_community.vectorstores import FAISS
|
| 12 |
-
import
|
| 13 |
-
|
| 14 |
|
| 15 |
class Comsatsbot:
|
| 16 |
def __init__(self, hf, llm, api_keys, chats_collection, paths, index_path='faiss_kb'):
|
| 17 |
self.llm = llm
|
| 18 |
self.api_keys = api_keys
|
| 19 |
self.client = None
|
| 20 |
-
self.models = [
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
self.chats_collection = chats_collection
|
| 27 |
self.index_path = index_path
|
| 28 |
self.hf = hf
|
|
@@ -42,19 +39,16 @@ class Comsatsbot:
|
|
| 42 |
def initialize_faiss_index(self):
|
| 43 |
if os.path.exists(self.index_path):
|
| 44 |
self.faiss_index = FAISS.load_local(self.index_path, self.hf, allow_dangerous_deserialization=True)
|
| 45 |
-
self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
|
| 46 |
else:
|
| 47 |
documents = self.load_data(self.paths)
|
| 48 |
self.faiss_index = FAISS.from_documents(documents, self.hf)
|
| 49 |
self.faiss_index.save_local(self.index_path)
|
| 50 |
-
|
| 51 |
|
| 52 |
def retrieve_answer(self, query):
|
| 53 |
if self.faiss_retriever:
|
| 54 |
return self.faiss_retriever.invoke(query)
|
| 55 |
-
|
| 56 |
-
print("FAISS retriever is not initialized. Please create or load an index.")
|
| 57 |
-
return None
|
| 58 |
|
| 59 |
def create_chat_record(self, chat_id):
|
| 60 |
self.chats_collection.insert_one({
|
|
@@ -75,20 +69,14 @@ class Comsatsbot:
|
|
| 75 |
return chat_record.get('history', [])
|
| 76 |
|
| 77 |
def new_chat(self, chat_id):
|
| 78 |
-
# Check if chat ID already exists
|
| 79 |
if self.chats_collection.find_one({"_id": chat_id}):
|
| 80 |
-
raise KeyError(f"Chat ID {chat_id}
|
| 81 |
-
|
| 82 |
-
# Create a new chat record if it doesn't exist
|
| 83 |
self.create_chat_record(chat_id)
|
| 84 |
return "success"
|
| 85 |
|
| 86 |
def delete_chat(self, chat_id):
|
| 87 |
-
# Check if the chat ID exists
|
| 88 |
if not self.chats_collection.find_one({"_id": chat_id}):
|
| 89 |
raise KeyError(f"Chat ID {chat_id} does not exist.")
|
| 90 |
-
|
| 91 |
-
# Delete the chat if it exists
|
| 92 |
self.chats_collection.delete_one({"_id": chat_id})
|
| 93 |
return "success"
|
| 94 |
|
|
@@ -133,141 +121,107 @@ class Comsatsbot:
|
|
| 133 |
'''
|
| 134 |
while True:
|
| 135 |
for api_key in self.api_keys:
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
chat_completion = self.client.chat.completions.create(
|
| 141 |
messages=[
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
"content": prompt,
|
| 145 |
-
},
|
| 146 |
-
{
|
| 147 |
-
"role": "user",
|
| 148 |
-
"content": f"Answer the following question : {question}",
|
| 149 |
-
},
|
| 150 |
],
|
| 151 |
model=model,
|
| 152 |
max_tokens=1024,
|
| 153 |
)
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
continue
|
| 161 |
-
|
| 162 |
-
return "Sorry, unable to provide an answer at this time."
|
| 163 |
|
| 164 |
def detect_language(self, question):
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
for
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
for model in self.models:
|
| 171 |
-
try:
|
| 172 |
-
chat_completion = self.client.chat.completions.create(
|
| 173 |
messages=[
|
| 174 |
{
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
{
|
| 186 |
-
"role": "user",
|
| 187 |
-
"content": f"detect the language for the following Question: {question}",
|
| 188 |
-
},
|
| 189 |
],
|
| 190 |
model=model,
|
| 191 |
-
max_tokens=
|
| 192 |
response_format={"type": "json_object"},
|
| 193 |
)
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
continue
|
| 202 |
-
def translate_urdu(self, text):
|
| 203 |
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
chat_completion = self.client.chat.completions.create(
|
| 211 |
messages=[
|
| 212 |
{
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
{
|
| 224 |
-
"role": "user",
|
| 225 |
-
"content": f"detect the language for the following Question: {text}",
|
| 226 |
-
},
|
| 227 |
],
|
| 228 |
model=model,
|
| 229 |
max_tokens=512,
|
| 230 |
response_format={"type": "json_object"},
|
| 231 |
)
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
continue
|
| 240 |
-
|
| 241 |
|
| 242 |
def response(self, question, chat_id):
|
| 243 |
chat_history = self.load_chat(chat_id)
|
| 244 |
|
| 245 |
-
# Load the previous conversation into memory
|
| 246 |
for entry in chat_history:
|
| 247 |
self.memory.save_context({"input": entry["question"]}, {"output": entry["answer"]})
|
| 248 |
|
| 249 |
language = self.detect_language(question)
|
|
|
|
| 250 |
if language == 'urdu':
|
| 251 |
question_translation = GoogleTranslator(source='ur', target='en').translate(question)
|
| 252 |
context = self.faiss_retriever.invoke(question_translation)
|
| 253 |
else:
|
| 254 |
context = self.faiss_retriever.invoke(question)
|
| 255 |
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
answer = self.generate_response(question, self.memory.load_memory_variables({})['history'], all_content)
|
| 261 |
|
| 262 |
-
|
| 263 |
-
|
| 264 |
if language == 'urdu':
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
self.update_chat(chat_id, question, answer)
|
| 270 |
-
return answer
|
| 271 |
|
| 272 |
|
| 273 |
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import time
|
| 3 |
+
import json
|
| 4 |
from groq import Groq
|
| 5 |
from langchain.memory import ConversationTokenBufferMemory
|
|
|
|
| 6 |
from langchain_community.chat_models import ChatOpenAI
|
|
|
|
|
|
|
| 7 |
from langchain_community.document_loaders.csv_loader import CSVLoader
|
| 8 |
from langchain_community.vectorstores import FAISS
|
| 9 |
+
from deep_translator import GoogleTranslator
|
| 10 |
+
|
| 11 |
|
| 12 |
class Comsatsbot:
|
| 13 |
def __init__(self, hf, llm, api_keys, chats_collection, paths, index_path='faiss_kb'):
|
| 14 |
self.llm = llm
|
| 15 |
self.api_keys = api_keys
|
| 16 |
self.client = None
|
| 17 |
+
self.models = [
|
| 18 |
+
"llama3-groq-70b-8192-tool-use-preview",
|
| 19 |
+
"llama-3.1-70b-versatile",
|
| 20 |
+
"llama3-70b-8192"
|
| 21 |
+
]
|
| 22 |
+
self.memory = ConversationTokenBufferMemory(llm=self.llm, max_token_limit=3000)
|
| 23 |
self.chats_collection = chats_collection
|
| 24 |
self.index_path = index_path
|
| 25 |
self.hf = hf
|
|
|
|
| 39 |
def initialize_faiss_index(self):
|
| 40 |
if os.path.exists(self.index_path):
|
| 41 |
self.faiss_index = FAISS.load_local(self.index_path, self.hf, allow_dangerous_deserialization=True)
|
|
|
|
| 42 |
else:
|
| 43 |
documents = self.load_data(self.paths)
|
| 44 |
self.faiss_index = FAISS.from_documents(documents, self.hf)
|
| 45 |
self.faiss_index.save_local(self.index_path)
|
| 46 |
+
self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
|
| 47 |
|
| 48 |
def retrieve_answer(self, query):
|
| 49 |
if self.faiss_retriever:
|
| 50 |
return self.faiss_retriever.invoke(query)
|
| 51 |
+
return None
|
|
|
|
|
|
|
| 52 |
|
| 53 |
def create_chat_record(self, chat_id):
|
| 54 |
self.chats_collection.insert_one({
|
|
|
|
| 69 |
return chat_record.get('history', [])
|
| 70 |
|
| 71 |
def new_chat(self, chat_id):
|
|
|
|
| 72 |
if self.chats_collection.find_one({"_id": chat_id}):
|
| 73 |
+
raise KeyError(f"Chat ID {chat_id} exists already.")
|
|
|
|
|
|
|
| 74 |
self.create_chat_record(chat_id)
|
| 75 |
return "success"
|
| 76 |
|
| 77 |
def delete_chat(self, chat_id):
|
|
|
|
| 78 |
if not self.chats_collection.find_one({"_id": chat_id}):
|
| 79 |
raise KeyError(f"Chat ID {chat_id} does not exist.")
|
|
|
|
|
|
|
| 80 |
self.chats_collection.delete_one({"_id": chat_id})
|
| 81 |
return "success"
|
| 82 |
|
|
|
|
| 121 |
'''
|
| 122 |
while True:
|
| 123 |
for api_key in self.api_keys:
|
| 124 |
+
self.client = Groq(api_key=api_key)
|
| 125 |
+
for model in self.models:
|
| 126 |
+
try:
|
| 127 |
+
chat_completion = self.client.chat.completions.create(
|
|
|
|
| 128 |
messages=[
|
| 129 |
+
{"role": "system", "content": prompt},
|
| 130 |
+
{"role": "user", "content": f"Answer the following question: {question}"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
],
|
| 132 |
model=model,
|
| 133 |
max_tokens=1024,
|
| 134 |
)
|
| 135 |
+
return chat_completion.choices[0].message.content
|
| 136 |
+
except Exception:
|
| 137 |
+
time.sleep(2)
|
| 138 |
+
continue
|
| 139 |
+
return "Sorry, unable to provide an answer at this time."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
def detect_language(self, question):
|
| 142 |
+
for api_key in self.api_keys:
|
| 143 |
+
self.client = Groq(api_key=api_key)
|
| 144 |
+
for model in self.models:
|
| 145 |
+
try:
|
| 146 |
+
chat_completion = self.client.chat.completions.create(
|
|
|
|
|
|
|
|
|
|
| 147 |
messages=[
|
| 148 |
{
|
| 149 |
+
"role": "system",
|
| 150 |
+
"content": """
|
| 151 |
+
You are an expert agent and your task is to detect the language.
|
| 152 |
+
Return a JSON: {'detected_language': 'urdu' or 'english'}
|
| 153 |
+
"""
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"role": "user",
|
| 157 |
+
"content": f"Detect the language for: {question}"
|
| 158 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
],
|
| 160 |
model=model,
|
| 161 |
+
max_tokens=256,
|
| 162 |
response_format={"type": "json_object"},
|
| 163 |
)
|
| 164 |
+
response = json.loads(chat_completion.choices[0].message.content)
|
| 165 |
+
return response['detected_language'].lower()
|
| 166 |
+
except Exception:
|
| 167 |
+
time.sleep(2)
|
| 168 |
+
continue
|
| 169 |
+
return "english"
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
def translate_urdu(self, text):
|
| 172 |
+
for api_key in self.api_keys:
|
| 173 |
+
self.client = Groq(api_key=api_key)
|
| 174 |
+
for model in self.models:
|
| 175 |
+
try:
|
| 176 |
+
chat_completion = self.client.chat.completions.create(
|
|
|
|
| 177 |
messages=[
|
| 178 |
{
|
| 179 |
+
"role": "system",
|
| 180 |
+
"content": """
|
| 181 |
+
Translate the following text into proper Urdu. Return a JSON:
|
| 182 |
+
{'text': 'translated urdu text'}
|
| 183 |
+
"""
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"role": "user",
|
| 187 |
+
"content": f"Translate this: {text}"
|
| 188 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
],
|
| 190 |
model=model,
|
| 191 |
max_tokens=512,
|
| 192 |
response_format={"type": "json_object"},
|
| 193 |
)
|
| 194 |
+
response = json.loads(chat_completion.choices[0].message.content)
|
| 195 |
+
return response['text']
|
| 196 |
+
except Exception:
|
| 197 |
+
time.sleep(2)
|
| 198 |
+
continue
|
| 199 |
+
return text
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
def response(self, question, chat_id):
|
| 202 |
chat_history = self.load_chat(chat_id)
|
| 203 |
|
|
|
|
| 204 |
for entry in chat_history:
|
| 205 |
self.memory.save_context({"input": entry["question"]}, {"output": entry["answer"]})
|
| 206 |
|
| 207 |
language = self.detect_language(question)
|
| 208 |
+
|
| 209 |
if language == 'urdu':
|
| 210 |
question_translation = GoogleTranslator(source='ur', target='en').translate(question)
|
| 211 |
context = self.faiss_retriever.invoke(question_translation)
|
| 212 |
else:
|
| 213 |
context = self.faiss_retriever.invoke(question)
|
| 214 |
|
| 215 |
+
combined_context = '\n'.join([doc.page_content for doc in context])
|
| 216 |
+
answer = self.generate_response(question, self.memory.load_memory_variables({})['history'], combined_context)
|
| 217 |
+
|
| 218 |
+
self.update_chat(chat_id, question, answer)
|
|
|
|
| 219 |
|
|
|
|
|
|
|
| 220 |
if language == 'urdu':
|
| 221 |
+
return self.translate_urdu(answer)
|
| 222 |
+
return answer
|
| 223 |
+
|
| 224 |
+
|
|
|
|
|
|
|
| 225 |
|
| 226 |
|
| 227 |
|