AashitaK commited on
Commit
e96de64
·
verified ·
1 Parent(s): 13c53e5

Rename utils/session_history2.py to utils/session_history3.py

Browse files
utils/{session_history2.py → session_history3.py} RENAMED
@@ -40,7 +40,7 @@ class ResponseManager:
40
 
41
  # Initialize other attributes
42
  self.meta_prompt_file = meta_prompt_file or 'config/meta_prompt.txt'
43
- # self.previous_response_id = None
44
 
45
  # Initialize the OpenAI client
46
  self.client = openai.OpenAI(api_key=self.api_key)
@@ -54,6 +54,12 @@ class ResponseManager:
54
  self.max_output_tokens = max_output_tokens
55
  self.max_num_results = max_num_results
56
 
 
 
 
 
 
 
57
  def _load_meta_prompt(self, meta_prompt_file: str) -> str:
58
  """
59
  Load the meta prompt from the specified file.
@@ -68,7 +74,7 @@ class ResponseManager:
68
  logging.info(f"Meta prompt loaded successfully from '{meta_prompt_file}'.")
69
  return meta_prompt
70
 
71
- def generate_response(self, query: str, history: list, previous_response_id: Optional[str] = None) -> list:
72
  """
73
  Generate a response to a user query using the OpenAI API.
74
  This method interacts with the OpenAI API to create a response based on the user's query.
@@ -80,7 +86,7 @@ class ResponseManager:
80
  list: A list of dictionaries representing the conversation, including the generated response.
81
  """
82
  # Prepare the input for the API call
83
- input_data = [{"role": "developer", "content": self.meta_prompt}] if previous_response_id is None else []#if self.previous_response_id is None else []
84
  input_data.append({"role": "user", "content": query})
85
 
86
  # Validate the query
@@ -88,13 +94,13 @@ class ResponseManager:
88
  logging.warning("Empty or invalid query received.")
89
  warning_message = "Please enter a valid query."
90
  input_data.append({"role": "assistant", "content": warning_message})
91
- return history + input_data, previous_response_id
92
 
93
  try:
94
  logging.info("Sending request to OpenAI API...")
95
  response = self.client.responses.create(
96
  model=self.model,
97
- previous_response_id=sprevious_response_id,#self.previous_response_id,
98
  input=input_data,
99
  tools=[{
100
  "type": "file_search",
@@ -108,13 +114,13 @@ class ResponseManager:
108
  self.previous_response_id = response.id
109
  logging.info("Response received successfully.")
110
  input_data.append({"role": "assistant", "content": response.output_text})
111
- return history + input_data, previous_response_id
112
 
113
  except Exception as e:
114
  logging.error(f"An error occurred while generating a response: {e}")
115
  error_message = "Sorry, I couldn't generate a response at this time. Please try again later."
116
  input_data.append({"role": "assistant", "content": error_message})
117
- return history + input_data, previous_response_id
118
 
119
  import os
120
  import json
@@ -150,29 +156,15 @@ class ChatbotInterface:
150
  self.input_placeholder = self.config["chatbot_input_placeholder"]
151
  self.output_label = self.config["chatbot_output_label"]
152
 
153
- # Initialize ResponseManager with custom parameters
154
- try:
155
- self.response_manager = ResponseManager(
156
- model=model,
157
- temperature=temperature,
158
- max_output_tokens=max_output_tokens,
159
- max_num_results=max_num_results,
160
- vector_store_id=vector_store_id,
161
- api_key=api_key,
162
- meta_prompt_file=meta_prompt_file
163
- )
164
-
165
- logging.info(
166
- "ChatbotInterface initialized with the following parameters:\n"
167
- f" - Model: {model}\n"
168
- f" - Temperature: {temperature}\n"
169
- f" - Max Output Tokens: {max_output_tokens}\n"
170
- f" - Max Number of Results: {max_num_results}\n"
171
- )
172
-
173
- except Exception as e:
174
- logging.error(f"Failed to initialize ResponseManager: {e}")
175
- raise
176
 
177
  @staticmethod
178
  def load_config(config_path: str) -> dict:
@@ -223,9 +215,9 @@ class ChatbotInterface:
223
  # # Session-specific state to store conversation history.
224
  # conversation_state = gr.State([])
225
 
226
- # Create session states for history and previous_response_id
227
  conversation_state = gr.State([])
228
- previous_response_id_state = gr.State(None)
229
 
230
  # Use a gr.Row container as the input box with an integrated submit button.
231
  with gr.Row(elem_id="input-container", equal_height=True):
@@ -243,41 +235,62 @@ class ChatbotInterface:
243
  size="lg"
244
  )
245
 
246
- # Define a local function to reset input
247
- def reset_output() -> list:
248
- """
249
- Reset the chatbot output.
250
- :return: An empty list to reset the output.
251
- """
252
- return [], [], None, "" # [chatbot_output, conversation_state, previous_response_id_state, cleared input]
 
 
 
 
 
253
 
254
- # Define a local function to process input
255
- def process_input(user_message, chat_history, previous_response_id_state):
256
- """
257
- Call generate_response with the user's message and chat history.
258
- Return a tuple with the updated chat history and an empty string to clear the input.
259
- """
260
- updated_history, new_previous_id = self.response_manager.generate_response(
261
- user_message,
262
- chat_history,
263
- previous_response_id
264
- )
265
- return updated_history, updated_history, new_previous_id, "" # [chatbot_output, conversation_state, previous_response_id_state, user_input]
266
- # updated_history = self.response_manager.generate_response(user_message, chat_history)
267
- # return updated_history, updated_history, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
- # Bind the reset button click to the reset function
270
  reset.click(
271
  fn=reset_output,
272
  inputs=None,
273
- outputs=[chatbot_output, conversation_state, previous_response_id_state, user_input]
274
  )
275
-
276
- # Bind the Enter key (textbox submit) to the same processing function
277
  user_input.submit(
278
  fn=process_input,
279
- inputs=[user_input, conversation_state, previous_response_id_state],#[user_input, chatbot_output],
280
- outputs=[chatbot_output, conversation_state, previous_response_id_state, user_input]
281
  )
282
 
283
  logging.info("Gradio interface created successfully.")
 
40
 
41
  # Initialize other attributes
42
  self.meta_prompt_file = meta_prompt_file or 'config/meta_prompt.txt'
43
+ self.previous_response_id = None
44
 
45
  # Initialize the OpenAI client
46
  self.client = openai.OpenAI(api_key=self.api_key)
 
54
  self.max_output_tokens = max_output_tokens
55
  self.max_num_results = max_num_results
56
 
57
+ def reset_conversation(self):
58
+ """
59
+ Reset the conversation state internally maintained by OpenAI Response API.
60
+ """
61
+ self.previous_response_id = None
62
+
63
  def _load_meta_prompt(self, meta_prompt_file: str) -> str:
64
  """
65
  Load the meta prompt from the specified file.
 
74
  logging.info(f"Meta prompt loaded successfully from '{meta_prompt_file}'.")
75
  return meta_prompt
76
 
77
+ def generate_response(self, query: str, history: list) -> list:
78
  """
79
  Generate a response to a user query using the OpenAI API.
80
  This method interacts with the OpenAI API to create a response based on the user's query.
 
86
  list: A list of dictionaries representing the conversation, including the generated response.
87
  """
88
  # Prepare the input for the API call
89
+ input_data = [{"role": "developer", "content": self.meta_prompt}] if self.previous_response_id is None else []
90
  input_data.append({"role": "user", "content": query})
91
 
92
  # Validate the query
 
94
  logging.warning("Empty or invalid query received.")
95
  warning_message = "Please enter a valid query."
96
  input_data.append({"role": "assistant", "content": warning_message})
97
+ return history + input_data
98
 
99
  try:
100
  logging.info("Sending request to OpenAI API...")
101
  response = self.client.responses.create(
102
  model=self.model,
103
+ previous_response_id=self.previous_response_id,
104
  input=input_data,
105
  tools=[{
106
  "type": "file_search",
 
114
  self.previous_response_id = response.id
115
  logging.info("Response received successfully.")
116
  input_data.append({"role": "assistant", "content": response.output_text})
117
+ return history + input_data
118
 
119
  except Exception as e:
120
  logging.error(f"An error occurred while generating a response: {e}")
121
  error_message = "Sorry, I couldn't generate a response at this time. Please try again later."
122
  input_data.append({"role": "assistant", "content": error_message})
123
+ return history + input_data
124
 
125
  import os
126
  import json
 
156
  self.input_placeholder = self.config["chatbot_input_placeholder"]
157
  self.output_label = self.config["chatbot_output_label"]
158
 
159
+ # Parameters for ResponseManager class
160
+ self.model = model
161
+ self.temperature = temperature
162
+ self.max_output_tokens = max_output_tokens
163
+ self.max_num_results = max_num_results
164
+ self.vector_store_id = vector_store_id
165
+ self.api_key = api_key
166
+ self.meta_prompt_file = meta_prompt_file
167
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
  @staticmethod
170
  def load_config(config_path: str) -> dict:
 
215
  # # Session-specific state to store conversation history.
216
  # conversation_state = gr.State([])
217
 
218
+ # Session-specific states
219
  conversation_state = gr.State([])
220
+ response_manager_state = gr.State(None)
221
 
222
  # Use a gr.Row container as the input box with an integrated submit button.
223
  with gr.Row(elem_id="input-container", equal_height=True):
 
235
  size="lg"
236
  )
237
 
238
+ # 🟢 Initialization function for session-specific response manager
239
+ def init_response_manager():
240
+ try:
241
+ rm = ResponseManager(
242
+ model=self.model,
243
+ temperature=self.temperature,
244
+ max_output_tokens=self.max_output_tokens,
245
+ max_num_results=self.max_num_results,
246
+ vector_store_id=self.vector_store_id,
247
+ api_key=self.api_key,
248
+ meta_prompt_file=self.meta_prompt_file
249
+ )
250
 
251
+ logging.info(
252
+ "ChatbotInterface initialized with the following parameters:\n"
253
+ f" - Model: {self.model}\n"
254
+ f" - Temperature: {self.temperature}\n"
255
+ f" - Max Output Tokens: {self.max_output_tokens}\n"
256
+ f" - Max Number of Results: {self.max_num_results}\n"
257
+ )
258
+
259
+ rm.reset_conversation()
260
+ return rm
261
+ except Exception as e:
262
+ logging.error(f"Failed to initialize ResponseManager: {e}")
263
+ raise
264
+
265
+ # 🟢 Reset function updated to reset ResponseManager
266
+ def reset_output():
267
+ response_manager = init_response_manager()
268
+ return [], response_manager, ""
269
+
270
+ # 🟢 Process input now uses session-specific ResponseManager
271
+ def process_input(user_message, chat_history, response_manager):
272
+ updated_history = response_manager.generate_response(user_message, chat_history)
273
+ return updated_history, updated_history, response_manager, ""
274
+
275
+ # Initialize ResponseManager on load
276
+ demo.load(
277
+ fn=init_response_manager,
278
+ inputs=None,
279
+ outputs=response_manager_state
280
+ )
281
+
282
 
283
+
284
  reset.click(
285
  fn=reset_output,
286
  inputs=None,
287
+ outputs=[chatbot_output, response_manager_state, user_input]
288
  )
289
+
 
290
  user_input.submit(
291
  fn=process_input,
292
+ inputs=[user_input, conversation_state, response_manager_state],
293
+ outputs=[chatbot_output, conversation_state, response_manager_state, user_input]
294
  )
295
 
296
  logging.info("Gradio interface created successfully.")