Spaces:
Sleeping
Sleeping
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 |
-
|
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
|
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
|
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
|
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=
|
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
|
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
|
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 |
-
#
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
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 |
-
#
|
227 |
conversation_state = gr.State([])
|
228 |
-
|
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 |
-
#
|
247 |
-
def
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
|
|
|
|
|
|
|
|
|
|
253 |
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
268 |
|
269 |
-
|
270 |
reset.click(
|
271 |
fn=reset_output,
|
272 |
inputs=None,
|
273 |
-
outputs=[chatbot_output,
|
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,
|
280 |
-
outputs=[chatbot_output, conversation_state,
|
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.")
|