AashitaK commited on
Commit
127b728
·
verified ·
1 Parent(s): e0ac28f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -100
app.py CHANGED
@@ -1,105 +1,109 @@
1
  import os
2
  import json
 
3
  import gradio as gr
4
- from utils.response_manager import ResponseManager # Import the ResponseManager class
5
- """
6
- This script sets up a Gradio interface to host an AI chatbot using RAG (Retrieval-Augmented Generation)
7
- to provide responses to user queries. Response API from OpenAI is used for both retrieval and generation of responses.
8
- """
9
-
10
- # Vector store ID for the retrieval of knowledge base documents
11
- # Load the vector store ID from the environment variable
12
- vector_store_id = os.getenv('VECTOR_STORE_ID')
13
-
14
- # Check if the VECTOR_STORE_ID environment variable is set
15
- if not vector_store_id:
16
- raise ValueError("VECTOR_STORE_ID environment variable is not set.")
17
-
18
- # Initialize the ResponseManager with the vector store ID
19
- response_manager = ResponseManager(vector_store_id)
20
-
21
- # Define the chatbot function to handle user queries and generate responses
22
- def chat_interaction(query: str, history):
23
- """
24
- Function to handle the chatbot interaction and maintain conversation history.
25
- :param query: The user query to respond to.
26
- :param history: The conversation history (list of [input, output] pairs).
27
- :return: Updated conversation history.
28
- """
29
- try:
30
- if query.strip():
31
- response = response_manager.create_response(query, model, temperature, max_output_tokens, max_num_results)
32
- if not response:
33
- response = "Sorry, I couldn't generate a response at this time. Please try again later."
34
- # Append the conversation
35
- history.append((query, response))
36
- else:
37
- history.append((query, "Please enter a valid query."))
38
- return history
39
- except Exception as e:
40
- history.append((query, str(e)))
41
- return history
42
-
43
- # Set parameters for the response generation
44
- model = "gpt-4o-mini" # Set the model to be used for response generation
45
- temperature=0 # Set the temperature for response generation
46
- max_output_tokens=800 # Set the maximum number of output tokens
47
- max_num_results=7 # Set the maximum number of knowledge base documents to return for retrieval
48
-
49
- # Load the configuration for Gradio GUI interface from the JSON file
50
- with open('config/gradio_config.json', 'r') as config_file:
51
- config = json.load(config_file)
52
- # Check if the configuration file is loaded successfully
53
- if not config:
54
- raise ValueError("Failed to load the configuration file.")
55
- # Extract the configuration parameters
56
- chatbot_title = config["chatbot_title"]
57
- chatbot_description = config["chatbot_description"]
58
- chatbot_input_label = config["chatbot_input_label"]
59
- chatbot_input_placeholder = config["chatbot_input_placeholder"]
60
- chatbot_output_label = config["chatbot_output_label"]
61
- chatbot_output_placeholder = config["chatbot_output_placeholder"]
62
- chatbot_submit_button = config["chatbot_submit_button"]
63
- chatbot_reset_button = config["chatbot_reset_button"]
64
-
65
- # Check if the configuration parameters are set correctly
66
- if not all([chatbot_title, chatbot_description,
67
- chatbot_input_label, chatbot_input_placeholder,
68
- chatbot_output_label, chatbot_output_placeholder,
69
- chatbot_submit_button, chatbot_reset_button]):
70
- raise ValueError("One or more configuration parameters are missing or empty.")
71
-
72
- # Define the reset function
73
- def reset_output():
74
- return []
75
-
76
- # Create a Gradio Blocks interface
77
- with gr.Blocks() as demo:
78
- gr.Markdown(f"## {chatbot_title}\n{chatbot_description}")
79
-
80
- # Chatbot history component
81
- chatbot_output = gr.Chatbot(label="Chat History")
82
-
83
- # User input
84
- user_input = gr.Textbox(
85
- lines=2,
86
- label=chatbot_input_label,
87
- placeholder=chatbot_input_placeholder
88
- )
89
-
90
- # Buttons
91
- with gr.Row():
92
- # Reset button on the left (Gray)
93
- with gr.Column(scale=1):
94
- reset = gr.Button(chatbot_reset_button, variant="secondary")
95
- # Submit button on the right (Blue)
96
- with gr.Column(scale=1):
97
- submit = gr.Button(chatbot_submit_button, variant="primary")
98
-
99
- # Submit and Reset button actions
100
- submit.click(fn=chat_interaction, inputs=[user_input, chatbot_output], outputs=chatbot_output)
101
- user_input.submit(fn=chat_interaction, inputs=[user_input, chatbot_output], outputs=chatbot_output)
102
- reset.click(fn=reset_output, inputs=None, outputs=chatbot_output)
103
 
104
  if __name__ == "__main__":
105
- demo.launch()
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import json
3
+ import logging
4
  import gradio as gr
5
+ from utils.chatbot_logic import conversation # Import the chatbot logic
6
+
7
+ # Configure logging to both file and console
8
+ log_file_path = "logs/chatbot_interface.log"
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format="%(asctime)s - %(levelname)s - %(message)s",
12
+ handlers=[
13
+ logging.FileHandler(log_file_path, mode='a', encoding='utf-8'), # Save logs to a file
14
+ logging.StreamHandler() # Print logs to the console
15
+ ]
16
+ )
17
+
18
+ class ChatbotInterface:
19
+ def __init__(self, config_path: str = 'config/gradio_config.json'):
20
+ """
21
+ Initialize the ChatbotInterface with configuration.
22
+ :param config_path: Path to the configuration JSON file.
23
+ """
24
+ self.config = self.load_config(config_path)
25
+ self.title = self.config["chatbot_title"]
26
+ self.description = self.config["chatbot_description"]
27
+ self.input_label = self.config["chatbot_input_label"]
28
+ self.input_placeholder = self.config["chatbot_input_placeholder"]
29
+ self.output_label = self.config["chatbot_output_label"]
30
+ self.reset_button = self.config["chatbot_reset_button"]
31
+ self.submit_button = self.config["chatbot_submit_button"]
32
+
33
+ @staticmethod
34
+ def load_config(config_path: str) -> dict:
35
+ """
36
+ Load the configuration for Gradio GUI interface from the JSON file.
37
+ :param config_path: Path to the configuration JSON file.
38
+ :return: Configuration dictionary.
39
+ """
40
+ if not os.path.exists(config_path):
41
+ logging.error(f"Configuration file not found: {config_path}")
42
+ raise FileNotFoundError(f"Configuration file not found: {config_path}")
43
+
44
+ with open(config_path, 'r') as config_file:
45
+ config = json.load(config_file)
46
+
47
+ required_keys = [
48
+ "chatbot_title", "chatbot_description", "chatbot_input_label",
49
+ "chatbot_input_placeholder", "chatbot_output_label",
50
+ "chatbot_reset_button", "chatbot_submit_button"
51
+ ]
52
+ for key in required_keys:
53
+ if key not in config:
54
+ logging.error(f"Missing required configuration key: {key}")
55
+ raise ValueError(f"Missing required configuration key: {key}")
56
+
57
+ logging.info("Configuration loaded successfully.")
58
+ return config
59
+
60
+ def reset_output() -> list:
61
+ """
62
+ Reset the chatbot output.
63
+ :return: An empty list to reset the output.
64
+ """
65
+ return []
66
+
67
+ def create_interface(self) -> gr.Blocks:
68
+ """
69
+ Create the Gradio Blocks interface.
70
+ :return: A Gradio Blocks interface object.
71
+ """
72
+ with gr.Blocks() as demo:
73
+ gr.Markdown(f"## {self.title}\n{self.description}")
74
+
75
+ # Chatbot history component
76
+ chatbot_output = gr.Chatbot(label=self.output_label)
77
+
78
+ # User input
79
+ user_input = gr.Textbox(
80
+ lines=2,
81
+ label=self.input_label,
82
+ placeholder=self.input_placeholder
83
+ )
84
+
85
+ # Buttons
86
+ with gr.Row():
87
+ reset = gr.Button(self.reset_button, variant="secondary")
88
+ submit = gr.Button(self.submit_button, variant="primary")
89
+
90
+ # Button actions
91
+ submit.click(fn=conversation, inputs=[user_input, chatbot_output], outputs=chatbot_output)
92
+ user_input.submit(fn=conversation, inputs=[user_input, chatbot_output], outputs=chatbot_output)
93
+ reset.click(fn=self.reset_output, inputs=None, outputs=chatbot_output)
94
+
95
+ logging.info("Gradio interface created successfully.")
96
+ return demo
97
+
 
 
 
 
 
 
98
 
99
  if __name__ == "__main__":
100
+ try:
101
+ # Instantiate the ChatbotInterface class and create the interface
102
+ chatbot_interface = ChatbotInterface()
103
+ demo = chatbot_interface.create_interface()
104
+
105
+ # Launch the Gradio interface
106
+ logging.info("Launching the Gradio interface...")
107
+ demo.launch()
108
+ except Exception as e:
109
+ logging.error(f"An error occurred: {e}")