AashitaK commited on
Commit
535dab8
·
verified ·
1 Parent(s): 88154fc

Update utils/chatbot_interface.py

Browse files
Files changed (1) hide show
  1. utils/chatbot_interface.py +89 -33
utils/chatbot_interface.py CHANGED
@@ -1,36 +1,92 @@
1
- def conversation(self, query: str, history: list) -> list:
2
- """
3
- Function to handle the chatbot interaction and maintain conversation history.
4
- :param query: The user query to respond to.
5
- :param history: The conversation history (list of [input, output] pairs).
6
- :return: Updated conversation history.
7
- """
8
- logging.info("Received query: %s", query)
9
-
10
- # Validate the query
11
- if not query.strip():
12
- logging.warning("Empty or invalid query received.")
13
- history.append((query, "Please enter a valid query."))
14
- return history
15
-
16
- try:
17
- # Generate a response using the create_response method
18
- logging.info("Generating response for the query...")
19
- response = self.create_response(
20
- query=query,
21
- model=self.DEFAULT_MODEL,
22
- temperature=self.DEFAULT_TEMPERATURE,
23
- max_output_tokens=self.DEFAULT_MAX_OUTPUT_TOKENS,
24
- max_num_results=self.DEFAULT_MAX_NUM_RESULTS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  )
26
 
27
- # Append the query and response to the conversation history
28
- history.append((query, response))
29
- logging.info("Response generated successfully.")
30
- return history
 
 
 
 
 
31
 
32
- except Exception as e:
33
- # Log the error and append it to the conversation history
34
- logging.error("An error occurred while generating a response: %s", str(e))
35
- history.append((query, f"An error occurred: {str(e)}"))
36
- return history
 
1
+ import os
2
+ import json
3
+ import logging
4
+ import gradio as gr
5
+ from utils.response_manager import ResponseManager
6
+
7
+ class ChatbotInterface:
8
+ def __init__(self, config_path: str = 'config/gradio_config.json'):
9
+ """
10
+ Initialize the ChatbotInterface with configuration.
11
+ :param config_path: Path to the configuration JSON file.
12
+ """
13
+ self.config = self.load_config(config_path)
14
+ self.title = self.config["chatbot_title"]
15
+ self.description = self.config["chatbot_description"]
16
+ self.input_label = self.config["chatbot_input_label"]
17
+ self.input_placeholder = self.config["chatbot_input_placeholder"]
18
+ self.output_label = self.config["chatbot_output_label"]
19
+ self.reset_button = self.config["chatbot_reset_button"]
20
+ self.submit_button = self.config["chatbot_submit_button"]
21
+ self.response_manager = ResponseManager()
22
+ self.conversation = self.response_manager.conversation # Shortcut to the conversation method
23
+ logging.info("ChatbotInterface initialized with configuration.")
24
+
25
+ @staticmethod
26
+ def load_config(config_path: str) -> dict:
27
+ """
28
+ Load the configuration for Gradio GUI interface from the JSON file.
29
+ :param config_path: Path to the configuration JSON file.
30
+ :return: Configuration dictionary.
31
+ """
32
+ logging.info(f"Loading configuration from {config_path}...")
33
+ if not os.path.exists(config_path):
34
+ logging.error(f"Configuration file not found: {config_path}")
35
+ raise FileNotFoundError(f"Configuration file not found: {config_path}")
36
+
37
+ with open(config_path, 'r') as config_file:
38
+ config = json.load(config_file)
39
+
40
+ required_keys = [
41
+ "chatbot_title", "chatbot_description", "chatbot_input_label",
42
+ "chatbot_input_placeholder", "chatbot_output_label",
43
+ "chatbot_reset_button", "chatbot_submit_button"
44
+ ]
45
+ for key in required_keys:
46
+ if key not in config:
47
+ logging.error(f"Missing required configuration key: {key}")
48
+ raise ValueError(f"Missing required configuration key: {key}")
49
+
50
+ logging.info("Configuration loaded successfully.")
51
+ return config
52
+
53
+ def reset_output(self) -> list:
54
+ """
55
+ Reset the chatbot output.
56
+ :return: An empty list to reset the output.
57
+ """
58
+ return []
59
+
60
+ def create_interface(self) -> gr.Blocks:
61
+ """
62
+ Create the Gradio Blocks interface.
63
+ :return: A Gradio Blocks interface object.
64
+ """
65
+ logging.info("Creating Gradio interface...")
66
+
67
+ # Define the Gradio Blocks interface
68
+ with gr.Blocks() as demo:
69
+ gr.Markdown(f"## {self.title}\n{self.description}")
70
+
71
+ # Chatbot history component
72
+ chatbot_output = gr.Chatbot(label=self.output_label)
73
+
74
+ # User input
75
+ user_input = gr.Textbox(
76
+ lines=2,
77
+ label=self.input_label,
78
+ placeholder=self.input_placeholder
79
  )
80
 
81
+ # Buttons
82
+ with gr.Row():
83
+ reset = gr.Button(self.reset_button, variant="secondary")
84
+ submit = gr.Button(self.submit_button, variant="primary")
85
+
86
+ # Button actions
87
+ submit.click(fn=self.conversation, inputs=[user_input, chatbot_output], outputs=chatbot_output)
88
+ user_input.submit(fn=self.conversation, inputs=[user_input, chatbot_output], outputs=chatbot_output)
89
+ reset.click(fn=self.reset_output, inputs=None, outputs=chatbot_output)
90
 
91
+ logging.info("Gradio interface created successfully.")
92
+ return demo