AashitaK commited on
Commit
870177b
·
verified ·
1 Parent(s): 8805a1a

Create chatbot_interface2.py

Browse files
Files changed (1) hide show
  1. utils/chatbot_interface2.py +168 -0
utils/chatbot_interface2.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import logging
4
+ from typing import Optional
5
+ import gradio as gr
6
+ from utils.response_manager import ResponseManager
7
+
8
+ class ChatbotInterface:
9
+ def __init__(self,
10
+ config_path: str = 'config/gradio_config.json',
11
+ model: str = "gpt-4o-mini",
12
+ temperature: float = 0,
13
+ max_output_tokens: int = 800,
14
+ max_num_results: int = 15,
15
+ vector_store_id: Optional[str] = None,
16
+ api_key: Optional[str] = None,
17
+ meta_prompt_file: Optional[str] = None):
18
+ """
19
+ Initialize the ChatbotInterface with configuration and custom parameters for ResponseManager.
20
+ :param config_path: Path to the configuration JSON file.
21
+ :param model: The OpenAI model to use (default: 'gpt-4o-mini').
22
+ :param temperature: The temperature for response generation (default: 0).
23
+ :param max_output_tokens: The maximum number of output tokens (default: 800).
24
+ :param max_num_results: The maximum number of search results to return (default: 15).
25
+ :param vector_store_id: The ID of the vector store to use for file search.
26
+ :param api_key: The OpenAI API key for authentication.
27
+ :param meta_prompt_file: Path to the meta prompt file .
28
+ """
29
+ self.config = self.load_config(config_path)
30
+ self.title = self.config["chatbot_title"]
31
+ self.description = self.config["chatbot_description"]
32
+ self.input_label = self.config["chatbot_input_label"]
33
+ self.input_placeholder = self.config["chatbot_input_placeholder"]
34
+ self.output_label = self.config["chatbot_output_label"]
35
+ self.reset_button = self.config["chatbot_reset_button"]
36
+ self.submit_button = self.config["chatbot_submit_button"]
37
+
38
+ # Initialize ResponseManager with custom parameters
39
+ try:
40
+ self.response_manager = ResponseManager(
41
+ model=model,
42
+ temperature=temperature,
43
+ max_output_tokens=max_output_tokens,
44
+ max_num_results=max_num_results,
45
+ vector_store_id=vector_store_id,
46
+ api_key=api_key,
47
+ meta_prompt_file=meta_prompt_file
48
+ )
49
+ self.generate_response = self.response_manager.generate_response
50
+ logging.info(
51
+ "ChatbotInterface initialized with the following parameters:\n"
52
+ f" - Model: {model}\n"
53
+ f" - Temperature: {temperature}\n"
54
+ f" - Max Output Tokens: {max_output_tokens}\n"
55
+ f" - Max Number of Results: {max_num_results}\n"
56
+ f" - Vector Store ID: {vector_store_id}\n"
57
+ f" - API Key: {'Provided' if api_key else 'Not Provided'}\n"
58
+ f" - Meta Prompt File: {meta_prompt_file or 'Default'}"
59
+ )
60
+ except Exception as e:
61
+ logging.error(f"Failed to initialize ResponseManager: {e}")
62
+ raise
63
+
64
+
65
+ @staticmethod
66
+ def load_config(config_path: str) -> dict:
67
+ """
68
+ Load the configuration for Gradio GUI interface from the JSON file.
69
+ :param config_path: Path to the configuration JSON file.
70
+ :return: Configuration dictionary.
71
+ """
72
+ logging.info(f"Loading configuration from {config_path}...")
73
+ if not os.path.exists(config_path):
74
+ logging.error(f"Configuration file not found: {config_path}")
75
+ raise FileNotFoundError(f"Configuration file not found: {config_path}")
76
+
77
+ with open(config_path, 'r') as config_file:
78
+ config = json.load(config_file)
79
+
80
+ required_keys = [
81
+ "chatbot_title", "chatbot_description", "chatbot_input_label",
82
+ "chatbot_input_placeholder", "chatbot_output_label",
83
+ "chatbot_reset_button", "chatbot_submit_button"
84
+ ]
85
+ for key in required_keys:
86
+ if key not in config:
87
+ logging.error(f"Missing required configuration key: {key}")
88
+ raise ValueError(f"Missing required configuration key: {key}")
89
+
90
+ logging.info("Configuration loaded successfully.")
91
+ return config
92
+
93
+ def reset_output(self) -> list:
94
+ """
95
+ Reset the chatbot output.
96
+ :return: An empty list to reset the output.
97
+ """
98
+ return []
99
+
100
+ def create_interface(self) -> gr.Blocks:
101
+ """
102
+ Create the Gradio Blocks interface.
103
+ :return: A Gradio Blocks interface object.
104
+ """
105
+ logging.info("Creating Gradio interface...")
106
+
107
+ # Define the Gradio Blocks interface
108
+ with gr.Blocks() as demo:
109
+ # Title and description
110
+ gr.Markdown(f"## {self.title}\n{self.description}")
111
+
112
+ # Chatbot history component
113
+ chatbot_output = gr.Chatbot(label=self.output_label, type="messages")
114
+
115
+ # User input
116
+ user_input = gr.Textbox(
117
+ lines=2,
118
+ label=self.input_label,
119
+ placeholder=self.input_placeholder
120
+ )
121
+
122
+ # Buttons
123
+ with gr.Row():
124
+ reset = gr.Button(self.reset_button, variant="secondary")
125
+ submit = gr.Button(self.submit_button, variant="primary")
126
+
127
+ # Define a local function to process input:
128
+ def process_input(user_message, chat_history):
129
+ """
130
+ Call generate_response with the user's message and chat history.
131
+ Return a tuple with the updated chat history and an empty string to clear the input.
132
+ """
133
+ updated_history = self.generate_response(user_message, chat_history)
134
+ return updated_history, ""
135
+
136
+ # # Button actions
137
+ # submit.click(
138
+ # fn=self.generate_response,
139
+ # inputs=[user_input, chatbot_output],
140
+ # outputs=chatbot_output)
141
+ # user_input.submit(
142
+ # fn=self.generate_response,
143
+ # inputs=[user_input, chatbot_output],
144
+ # outputs=chatbot_output)
145
+ # reset.click(
146
+ # fn=self.reset_output,
147
+ # inputs=None,
148
+ # outputs=chatbot_output)
149
+
150
+ # Button actions
151
+ submit.click(
152
+ fn=self.generate_response,
153
+ inputs=[user_input, chatbot_output],
154
+ outputs=[chatbot_output, user_input]
155
+ )
156
+ user_input.submit(
157
+ fn=self.generate_response,
158
+ inputs=[user_input, chatbot_output],
159
+ outputs=[chatbot_output, user_input]
160
+ )
161
+ reset.click(
162
+ fn=self.reset_output,
163
+ inputs=None,
164
+ outputs=[chatbot_output, user_input]
165
+ )
166
+
167
+ logging.info("Gradio interface created successfully.")
168
+ return demo