Sadiaa commited on
Commit
8102a2e
·
verified ·
1 Parent(s): fa21896

Update chatbot.py

Browse files
Files changed (1) hide show
  1. chatbot.py +102 -94
chatbot.py CHANGED
@@ -1,5 +1,4 @@
1
  import os
2
-
3
  import time
4
  import json
5
  from groq import Groq
@@ -82,73 +81,59 @@ class Comsatsbot:
82
  return "success"
83
 
84
  def generate_response(self, question, history, context):
85
- comsats_context = """
86
- 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.
87
- It has three departments: CS (CS, AI, SE), Math (Math, BBA, English), and EE (EE, CE).
88
- 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.
89
- 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.
90
- """
91
-
92
- prompt = f'''
93
- Kindly use the proper emojis where we need to use in responses.
94
- 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.
95
- Answer the following Question: {question}
96
- Kindly use the proper emojis where we need to use in responses.
97
- 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.
98
- 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.
99
- 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.
100
- 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.
101
- For example, if the user asks the same question again and again and 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.
102
- 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:
103
- [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.)
104
- Don't explain or repeat the prompt in the response.
105
- 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."
106
- 2. Don’t explain irrelevant explanations and use the proper emojis in the answer if required.
107
- 3. Always respond in a human-like tone and keep your answers concise, to the point, and friendly.
108
- 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.
109
- 5. Always consider the provided context and chat history to formulate your response.
110
- 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 don’t know the answer to this 😔" without adding irrelevant text explanations.
111
- 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.
112
- Kindly use the proper emojis where we need to use in responses.
113
- Question: {question}
114
- 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.
115
- Use the following context to answer and don’t mention that you are answering from this context:
116
- {comsats_context}
117
- Context is ending.
118
- Now here is the chat history that you have to consider and identify
119
- **Consider the following chat history for additional context to answer the question:**
120
- {history}
121
- Answer the following Question: {question}
122
- '''
123
-
124
- # Log context to check if it's passed correctly
125
- print("Context being passed to the model:", comsats_context)
126
- print("Question being asked:", question)
127
-
128
- # Groq API call here
129
- max_retries = 3 # Limit the number of retries
130
- for attempt in range(max_retries):
131
- for api_key in self.api_keys:
132
- self.client = Groq(api_key=api_key)
133
- for model in self.models:
134
- try:
135
- chat_completion = self.client.chat.completions.create(
136
- messages=[{"role": "system", "content": prompt},
137
- {"role": "user", "content": f"Answer the following question: {question}"}],
138
- model=model,
139
- max_tokens=1024,
140
- )
141
- response_content = chat_completion.choices[0].message.content
142
- print("Response from Groq model:", response_content)
143
- return response_content
144
- except Exception as e:
145
- print(f"Error encountered on attempt {attempt + 1}: {e}")
146
- time.sleep(2)
147
- if attempt == max_retries - 1:
148
- return "Sorry, unable to provide an answer at this time."
149
- continue
150
- return "Sorry, unable to provide an answer at this time."
151
-
152
 
153
  def detect_language(self, question):
154
  for api_key in self.api_keys:
@@ -156,25 +141,26 @@ class Comsatsbot:
156
  for model in self.models:
157
  try:
158
  chat_completion = self.client.chat.completions.create(
159
- messages=[{
160
- "role": "system",
161
- "content": """
162
- You are an expert agent, and your task is to detect the language.
163
- Return a JSON: {'detected_language': 'urdu' or 'english'}
164
- """
165
- },
166
  {
167
- "role": "user",
168
- "content": f"Detect the language for: {question}"
169
- }],
 
 
 
 
 
 
 
 
170
  model=model,
171
  max_tokens=256,
172
  response_format={"type": "json_object"},
173
  )
174
  response = json.loads(chat_completion.choices[0].message.content)
175
  return response['detected_language'].lower()
176
- except Exception as e:
177
- print(f"Error encountered: {e}")
178
  time.sleep(2)
179
  continue
180
  return "english"
@@ -185,23 +171,45 @@ class Comsatsbot:
185
  for model in self.models:
186
  try:
187
  chat_completion = self.client.chat.completions.create(
188
- messages=[{
189
- "role": "system",
190
- "content": """
191
- Translate the following text into proper Urdu. Return a response without any extra explanation.
192
- """
193
- },
 
 
194
  {
195
- "role": "user",
196
- "content": f"Translate this into Urdu: {text}"
197
- }],
 
198
  model=model,
199
  max_tokens=512,
 
200
  )
201
- response = chat_completion.choices[0].message.content
202
- return response
203
- except Exception as e:
204
- print(f"Error encountered: {e}")
205
  time.sleep(2)
206
  continue
207
- return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
 
2
  import time
3
  import json
4
  from groq import Groq
 
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. Dont 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:
 
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"
 
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