Sadiaa commited on
Commit
738595c
·
verified ·
1 Parent(s): 80a3f7f

Update chatbot.py

Browse files
Files changed (1) hide show
  1. chatbot.py +115 -131
chatbot.py CHANGED
@@ -81,153 +81,137 @@ class Comsatsbot:
81
  return "success"
82
 
83
  def generate_response(self, question, history, context):
84
-
85
  prompt = f'''
86
- Kindly use the proper emojis where we need to use in responses.
87
- You are an comsats assistant to help the user related to comsats university, conversation, studies related query. Your answer should be very concise and to the point short answer. Dont need to repeat irrelevant text.
88
- Answer the following Question: {question}
89
- Kindly use the proper emojis where we need to use in responses.
90
- Kindly generate a concise and to the point answer. Kindly answer the question from the provided context and if you dont find the answer from chat histoy and context then inform the user i dont know and dont make the answer from yourself.
91
- Dont need to mention that (according to provided context/Based on the provided chat history) in response and just generate the response just like human without mention this according to context and chat history.
92
- You are a conversational and helpfull agent to help the comsats university attock campus students, and your task is to provide concise and direct answers to the questions.
93
- Your task is to use the emoji when there is happy, sad, surprise, angry expression required in response. Kindly analyze the question and if expression is required in response then use the emoji otherwise dont use the emoji and remember that you dont need to use the emoji in simple studies and comstas related question.
94
- For example user ask same question again and again, user is not understanding anything, user asking wrong things etc then your task is to use the emoji in such response and be choosy in using emoji in response in happy sad angry response according to user question.
95
- If there is any need to provide the url and then kindly generate the url according to following structure. Kindly provide the link clickable. Your provided should be generated according to following structure
96
- [Click here to visit "website name"](website url "https://comsats.edu.pk" write the same url as it is provided in context below and dont use the www in url and use the same link url as it provided in context(admssion detail: (http://admissions.comsats.edu.pk/Home/EligibilityCriteria?pt=BS)))
97
- Dont need to explain and repeat the prompt in response.
98
- 1. Kindly generate a full concise answer and if you dont find answer from context and chathistoyr then dont need to make the answer just answer it in i dont know.
99
- 2. Dont need to explain irrelevant explanation and use the proper emojis in answer if required in responses.
100
- 3. Always respond in a human-like tone and keep your answers concise, to the point and friendly.
101
- 4. If the question is conversational (like greetings, need any converstaion, help related studies, knowledge base question etc), respond in a warm, conversational tone.
102
- 5. Always consider the provided context and chat history to formulate your response.
103
- 6. If you don’t know the answer to the provided question or you did not find the answer from the context and chat history, kindly respond with "I don't know the answer to this.emooji" without adding irrelevant text explanations.
104
- 7. Kindly generate a perfect and to the point and short answer. Dont use any irrelevant text explanation and i want full concise and to the point answer.
105
- Kindly use the proper emojis where we need to use in responses.
106
- Question: {question}
107
- Kindly answer the question from the provided context and if you dont find the answer from chat histoy and context then inform the user i dont know and dont make the answer from yourself.
108
- Use the following context to answer and dont mention that you are answer from this tcontext in response:
109
- Comsats Attock Campus Provide BSomputerScience, BSSoftwareEngineer BSArtificialIntelligence BSEnglish BSmath BSElectricalEngineering BSComputerEngineering BSBBA
110
- Has three departments CS(CS, AI, SE), Math(math, BBA, english) and EE(EE, CE).
111
- It has cricket ground and football ground and two canteens. First near math and ee department and second near cs department. There is also mosque near cs department. CS department has threater liker rooms lt and total 9 theaters called lt and math has classroom cr and ee has labs.
112
- They accept the nts test for admission and provide the cgpa for 4 on 85 percent and 3.66 between 79 to 84 and many more.
113
-
114
-
115
- {context}
116
- Context is ending
117
- Now here is chat history that you have to consider and identify
118
- **Consider the following chat history for additional context to answer the question:**
119
- {history}
120
- Answer the following Question: {question}
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
-
228
-
229
-
230
 
 
231
 
 
 
232
 
233
 
 
81
  return "success"
82
 
83
  def generate_response(self, question, history, context):
 
84
  prompt = f'''
85
+ Kindly use the proper emojis where we need to use in responses.
86
+ You are a comsats assistant to help the user with comsats university-related queries. Your answer should be very concise and to the point with a short answer. Don't repeat irrelevant text.
87
+ Answer the following Question: {question}
88
+ Kindly use the proper emojis where we need to use in responses.
89
+ Kindly generate a concise and to-the-point answer. Kindly answer the question from the provided context, and if you don't find the answer from chat history and context, then inform the user "I don't know" and don't make the answer up yourself.
90
+ Don't mention "according to provided context/Based on the provided chat history" in the response, just generate the response like a human without mentioning context and chat history.
91
+ You are a conversational and helpful agent to help the comsats university attock campus students, and your task is to provide concise and direct answers to the questions.
92
+ Your task is to use the emoji when there is a happy, sad, surprise, or angry expression required in the response. Kindly analyze the question and if an expression is required in response, then use the emoji. Otherwise, don't use the emoji, and remember that you don't need to use the emoji in simple studies and comsats-related questions.
93
+ For example, if the user asks the same question again and again, doesn't understand anything, asks wrong questions, etc., then use the emoji in such responses. Be choosy when using emojis in responses according to the user's question.
94
+ If there is any need to provide a URL, generate the URL according to the following structure. Kindly provide the link clickable. Your provided link should be generated according to this structure:
95
+ [Click here to visit "website name"](website url "https://comsats.edu.pk") (Write the same URL as it is provided in the context below and don't use "www" in the URL.)
96
+ Don't explain or repeat the prompt in the response.
97
+ 1. Kindly generate a full concise answer and if you don't find the answer from context and chat history, then don’t make the answer, just say "I don’t know."
98
+ 2. Don’t explain irrelevant explanations and use the proper emojis in the answer if required.
99
+ 3. Always respond in a human-like tone and keep your answers concise, to the point, and friendly.
100
+ 4. If the question is conversational (like greetings, need any conversation, help related to studies, knowledge-based question, etc.), respond in a warm, conversational tone.
101
+ 5. Always consider the provided context and chat history to formulate your response.
102
+ 6. If you don’t know the answer to the provided question or you didn’t find the answer from the context and chat history, kindly respond with "I dont know the answer to this 😔" without adding irrelevant text explanations.
103
+ 7. Kindly generate a perfect and to-the-point short answer. Don’t use any irrelevant text explanation and I want a full concise and to-the-point answer.
104
+ Kindly use the proper emojis where we need to use in responses.
105
+ Question: {question}
106
+ Kindly answer the question from the provided context, and if you don’t find the answer from chat history and context, then inform the user "I don’t know" and don’t make the answer yourself.
107
+ Use the following context to answer and don’t mention that you are answering from this context:
108
+ Comsats Attock Campus Provides BS Computer Science, BS Software Engineering, BS Artificial Intelligence, BS English, BS Math, BS Electrical Engineering, BS Computer Engineering, BS BBA.
109
+ It has three departments: CS (CS, AI, SE), Math (Math, BBA, English), and EE (EE, CE).
110
+ It has a cricket ground, football ground, and two canteens. The first canteen is near the Math and EE departments, and the second canteen is near the CS department. There is also a mosque near the CS department. The CS department has theater-like rooms (LT), and there are a total of 9 theaters called LT. The Math department has classrooms (CR), and the EE department has labs.
111
+ They accept the NTS test for admission and provide the CGPA for 4 on 85 percent, and 3.66 between 79 to 84, and many more.
112
+ {context}
113
+ Context is ending.
114
+ Now here is the chat history that you have to consider and identify
115
+ **Consider the following chat history for additional context to answer the question:**
116
+ {history}
117
+ Answer the following Question: {question}
118
+ '''
 
 
119
  while True:
120
  for api_key in self.api_keys:
121
+ self.client = Groq(api_key=api_key)
122
+ for model in self.models:
123
+ try:
124
+ chat_completion = self.client.chat.completions.create(
125
+ messages=[
126
+ {"role": "system", "content": prompt},
127
+ {"role": "user", "content": f"Answer the following question: {question}"}
128
+ ],
129
+ model=model,
130
+ max_tokens=1024,
131
+ )
132
+ return chat_completion.choices[0].message.content
133
+ except Exception:
134
+ time.sleep(2)
135
+ continue
136
+ return "Sorry, unable to provide an answer at this time."
137
+
138
+ def detect_language(self, question):
139
+ for api_key in self.api_keys:
140
  self.client = Groq(api_key=api_key)
141
  for model in self.models:
142
  try:
143
  chat_completion = self.client.chat.completions.create(
144
  messages=[
145
+ {
146
+ "role": "system",
147
+ "content": """
148
+ You are an expert agent, and your task is to detect the language.
149
+ Return a JSON: {'detected_language': 'urdu' or 'english'}
150
+ """
151
+ },
152
+ {
153
+ "role": "user",
154
+ "content": f"Detect the language for: {question}"
155
+ }
156
  ],
157
  model=model,
158
+ max_tokens=256,
159
+ response_format={"type": "json_object"},
160
  )
161
+ response = json.loads(chat_completion.choices[0].message.content)
162
+ return response['detected_language'].lower()
163
  except Exception:
164
  time.sleep(2)
165
  continue
166
+ return "english"
167
+
168
+ def translate_urdu(self, text):
169
+ for api_key in self.api_keys:
170
+ self.client = Groq(api_key=api_key)
171
+ for model in self.models:
172
+ try:
173
+ chat_completion = self.client.chat.completions.create(
174
+ messages=[
175
+ {
176
+ "role": "system",
177
+ "content": """
178
+ Translate the following text into proper Urdu. Return a JSON:
179
+ {'text': 'translated urdu text'}
180
+ """
181
+ },
182
+ {
183
+ "role": "user",
184
+ "content": f"Translate this: {text}"
185
+ }
186
+ ],
187
+ model=model,
188
+ max_tokens=512,
189
+ response_format={"type": "json_object"},
190
+ )
191
+ response = json.loads(chat_completion.choices[0].message.content)
192
+ return response['text']
193
+ except Exception:
194
+ time.sleep(2)
195
+ continue
196
+ return text
197
+
198
+ def response(self, question, chat_id):
199
+ chat_history = self.load_chat(chat_id)
200
+
201
+ for entry in chat_history:
202
+ self.memory.save_context({"input": entry["question"]}, {"output": entry["answer"]})
203
 
204
+ language = self.detect_language(question)
205
+
206
+ if language == 'urdu':
207
+ question_translation = GoogleTranslator(source='ur', target='en').translate(question)
208
+ context = self.faiss_retriever.invoke(question_translation)
209
+ else:
210
+ context = self.faiss_retriever.invoke(question)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
+ answer = self.generate_response(question, chat_history, context)
213
 
214
+ self.update_chat(chat_id, question, answer)
215
+ return answer
216
 
217