shukdevdatta123 commited on
Commit
bc6d2ba
Β·
verified Β·
1 Parent(s): 31cd873

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +368 -0
app.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ import json
4
+ import os
5
+ import time
6
+ from typing import List, Tuple, Optional
7
+ import requests
8
+ from datetime import datetime
9
+
10
+ class ChatbotManager:
11
+ def __init__(self):
12
+ self.conversation_history = []
13
+ self.current_api_key = None
14
+ self.current_model = "gpt-3.5-turbo"
15
+ self.system_prompt = "You are a helpful AI assistant. Respond in a friendly and informative manner."
16
+ self.max_tokens = 150
17
+ self.temperature = 0.7
18
+
19
+ def set_api_key(self, api_key: str) -> str:
20
+ """Set the OpenAI API key"""
21
+ if not api_key.strip():
22
+ return "❌ Please enter a valid API key"
23
+
24
+ self.current_api_key = api_key.strip()
25
+ openai.api_key = self.current_api_key
26
+
27
+ # Test the API key
28
+ try:
29
+ openai.Model.list()
30
+ return "βœ… API key validated successfully!"
31
+ except Exception as e:
32
+ return f"❌ Invalid API key: {str(e)}"
33
+
34
+ def update_settings(self, model: str, system_prompt: str, max_tokens: int, temperature: float) -> str:
35
+ """Update chatbot settings"""
36
+ self.current_model = model
37
+ self.system_prompt = system_prompt
38
+ self.max_tokens = max_tokens
39
+ self.temperature = temperature
40
+ return f"βœ… Settings updated: Model={model}, Max Tokens={max_tokens}, Temperature={temperature}"
41
+
42
+ def preprocess_data(self, data_text: str) -> str:
43
+ """Preprocess and integrate custom data into the system prompt"""
44
+ if not data_text.strip():
45
+ return "No custom data provided"
46
+
47
+ # Add custom data to system prompt
48
+ self.system_prompt += f"\n\nAdditional Context:\n{data_text}"
49
+ return f"βœ… Custom data integrated ({len(data_text)} characters)"
50
+
51
+ def generate_response(self, user_input: str, history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
52
+ """Generate response using the selected LLM model"""
53
+ if not self.current_api_key:
54
+ return "❌ Please set your API key first!", history
55
+
56
+ if not user_input.strip():
57
+ return "Please enter a message.", history
58
+
59
+ try:
60
+ # Prepare conversation context
61
+ messages = [{"role": "system", "content": self.system_prompt}]
62
+
63
+ # Add conversation history
64
+ for user_msg, assistant_msg in history:
65
+ messages.append({"role": "user", "content": user_msg})
66
+ messages.append({"role": "assistant", "content": assistant_msg})
67
+
68
+ # Add current user input
69
+ messages.append({"role": "user", "content": user_input})
70
+
71
+ # Generate response
72
+ response = openai.ChatCompletion.create(
73
+ model=self.current_model,
74
+ messages=messages,
75
+ max_tokens=self.max_tokens,
76
+ temperature=self.temperature,
77
+ n=1,
78
+ stop=None,
79
+ )
80
+
81
+ assistant_response = response.choices[0].message.content.strip()
82
+
83
+ # Update history
84
+ history.append((user_input, assistant_response))
85
+
86
+ return assistant_response, history
87
+
88
+ except Exception as e:
89
+ error_msg = f"❌ Error generating response: {str(e)}"
90
+ return error_msg, history
91
+
92
+ def clear_conversation(self) -> Tuple[str, List[Tuple[str, str]]]:
93
+ """Clear conversation history"""
94
+ self.conversation_history = []
95
+ return "", []
96
+
97
+ def export_conversation(self, history: List[Tuple[str, str]]) -> str:
98
+ """Export conversation history to JSON format"""
99
+ if not history:
100
+ return "No conversation to export"
101
+
102
+ export_data = {
103
+ "timestamp": datetime.now().isoformat(),
104
+ "model": self.current_model,
105
+ "conversation": [
106
+ {"user": user_msg, "assistant": assistant_msg}
107
+ for user_msg, assistant_msg in history
108
+ ]
109
+ }
110
+
111
+ filename = f"conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
112
+
113
+ try:
114
+ with open(filename, 'w', encoding='utf-8') as f:
115
+ json.dump(export_data, f, indent=2, ensure_ascii=False)
116
+ return f"βœ… Conversation exported to {filename}"
117
+ except Exception as e:
118
+ return f"❌ Export failed: {str(e)}"
119
+
120
+ # Initialize chatbot manager
121
+ chatbot = ChatbotManager()
122
+
123
+ # Define available models
124
+ AVAILABLE_MODELS = [
125
+ "gpt-3.5-turbo",
126
+ "gpt-3.5-turbo-16k",
127
+ "gpt-4",
128
+ "gpt-4-32k",
129
+ "gpt-4-turbo-preview",
130
+ "gpt-4o",
131
+ "gpt-4o-mini"
132
+ ]
133
+
134
+ def create_interface():
135
+ """Create the Gradio interface"""
136
+
137
+ with gr.Blocks(title="LLM-Based Chatbot", theme=gr.themes.Soft()) as demo:
138
+ gr.Markdown("""
139
+ # πŸ€– LLM-Based Conversational AI Chatbot
140
+
141
+ This chatbot leverages powerful Language Models to provide intelligent conversations.
142
+ Enter your OpenAI API key to get started!
143
+ """)
144
+
145
+ with gr.Tab("πŸ’¬ Chat Interface"):
146
+ with gr.Row():
147
+ with gr.Column(scale=3):
148
+ chatbot_interface = gr.Chatbot(
149
+ label="Conversation",
150
+ height=400,
151
+ show_label=True,
152
+ avatar_images=("πŸ‘€", "πŸ€–")
153
+ )
154
+
155
+ with gr.Row():
156
+ user_input = gr.Textbox(
157
+ placeholder="Type your message here...",
158
+ scale=4,
159
+ show_label=False
160
+ )
161
+ send_btn = gr.Button("Send", variant="primary", scale=1)
162
+
163
+ with gr.Row():
164
+ clear_btn = gr.Button("Clear Chat", variant="secondary")
165
+ export_btn = gr.Button("Export Chat", variant="secondary")
166
+
167
+ with gr.Column(scale=1):
168
+ gr.Markdown("### πŸ”§ Quick Settings")
169
+
170
+ api_key_input = gr.Textbox(
171
+ label="OpenAI API Key",
172
+ placeholder="sk-...",
173
+ type="password"
174
+ )
175
+ api_status = gr.Textbox(
176
+ label="API Status",
177
+ interactive=False,
178
+ value="❌ No API key provided"
179
+ )
180
+
181
+ model_dropdown = gr.Dropdown(
182
+ choices=AVAILABLE_MODELS,
183
+ value="gpt-3.5-turbo",
184
+ label="Model"
185
+ )
186
+
187
+ max_tokens_slider = gr.Slider(
188
+ minimum=50,
189
+ maximum=500,
190
+ value=150,
191
+ step=10,
192
+ label="Max Tokens"
193
+ )
194
+
195
+ temperature_slider = gr.Slider(
196
+ minimum=0.0,
197
+ maximum=1.0,
198
+ value=0.7,
199
+ step=0.1,
200
+ label="Temperature"
201
+ )
202
+
203
+ with gr.Tab("βš™οΈ Advanced Settings"):
204
+ gr.Markdown("### System Prompt Configuration")
205
+ system_prompt_input = gr.Textbox(
206
+ label="System Prompt",
207
+ value="You are a helpful AI assistant. Respond in a friendly and informative manner.",
208
+ lines=5,
209
+ placeholder="Enter custom system prompt..."
210
+ )
211
+
212
+ gr.Markdown("### πŸ“Š Custom Data Integration")
213
+ custom_data_input = gr.Textbox(
214
+ label="Custom Training Data",
215
+ lines=10,
216
+ placeholder="Enter custom data, FAQs, or domain-specific information..."
217
+ )
218
+
219
+ with gr.Row():
220
+ update_settings_btn = gr.Button("Update Settings", variant="primary")
221
+ integrate_data_btn = gr.Button("Integrate Custom Data", variant="secondary")
222
+
223
+ settings_status = gr.Textbox(
224
+ label="Settings Status",
225
+ interactive=False
226
+ )
227
+
228
+ with gr.Tab("πŸ“‹ Usage Guide"):
229
+ gr.Markdown("""
230
+ ## πŸš€ Getting Started
231
+
232
+ ### 1. **Set Up API Key**
233
+ - Obtain an OpenAI API key from [OpenAI Platform](https://platform.openai.com/)
234
+ - Enter your API key in the "OpenAI API Key" field
235
+ - Wait for the green checkmark confirmation
236
+
237
+ ### 2. **Configure Settings**
238
+ - **Model**: Choose from available GPT models
239
+ - **Max Tokens**: Control response length (50-500)
240
+ - **Temperature**: Adjust creativity (0.0 = focused, 1.0 = creative)
241
+
242
+ ### 3. **Advanced Customization**
243
+ - **System Prompt**: Define the AI's personality and behavior
244
+ - **Custom Data**: Add domain-specific information or FAQs
245
+
246
+ ### 4. **Chat Features**
247
+ - Type messages and get intelligent responses
248
+ - Clear conversation history anytime
249
+ - Export chat history as JSON
250
+
251
+ ## πŸ› οΈ Technical Features
252
+
253
+ - **Multi-model support**: GPT-3.5, GPT-4, and variants
254
+ - **Conversation memory**: Maintains context throughout the session
255
+ - **Custom data integration**: Enhance responses with your own data
256
+ - **Export functionality**: Save conversations for later analysis
257
+ - **Real-time validation**: API key and settings verification
258
+
259
+ ## πŸ’‘ Use Cases
260
+
261
+ - **Customer Support**: Create domain-specific support chatbots
262
+ - **Education**: Build tutoring assistants with custom curriculum
263
+ - **Business**: Develop FAQ bots with company-specific information
264
+ - **Research**: Analyze conversations and response patterns
265
+ """)
266
+
267
+ # Event handlers
268
+ def handle_api_key(api_key):
269
+ status = chatbot.set_api_key(api_key)
270
+ return status
271
+
272
+ def handle_chat(user_input, history):
273
+ if not user_input.strip():
274
+ return history, ""
275
+
276
+ response, updated_history = chatbot.generate_response(user_input, history)
277
+ return updated_history, ""
278
+
279
+ def handle_settings_update(model, system_prompt, max_tokens, temperature):
280
+ status = chatbot.update_settings(model, system_prompt, max_tokens, temperature)
281
+ return status
282
+
283
+ def handle_data_integration(custom_data):
284
+ status = chatbot.preprocess_data(custom_data)
285
+ return status
286
+
287
+ def handle_clear():
288
+ return chatbot.clear_conversation()
289
+
290
+ def handle_export(history):
291
+ return chatbot.export_conversation(history)
292
+
293
+ # Connect events
294
+ api_key_input.change(
295
+ handle_api_key,
296
+ inputs=[api_key_input],
297
+ outputs=[api_status]
298
+ )
299
+
300
+ send_btn.click(
301
+ handle_chat,
302
+ inputs=[user_input, chatbot_interface],
303
+ outputs=[chatbot_interface, user_input]
304
+ )
305
+
306
+ user_input.submit(
307
+ handle_chat,
308
+ inputs=[user_input, chatbot_interface],
309
+ outputs=[chatbot_interface, user_input]
310
+ )
311
+
312
+ update_settings_btn.click(
313
+ handle_settings_update,
314
+ inputs=[model_dropdown, system_prompt_input, max_tokens_slider, temperature_slider],
315
+ outputs=[settings_status]
316
+ )
317
+
318
+ integrate_data_btn.click(
319
+ handle_data_integration,
320
+ inputs=[custom_data_input],
321
+ outputs=[settings_status]
322
+ )
323
+
324
+ clear_btn.click(
325
+ handle_clear,
326
+ outputs=[user_input, chatbot_interface]
327
+ )
328
+
329
+ export_btn.click(
330
+ handle_export,
331
+ inputs=[chatbot_interface],
332
+ outputs=[settings_status]
333
+ )
334
+
335
+ return demo
336
+
337
+ # Requirements and setup instructions
338
+ def print_setup_instructions():
339
+ """Print setup instructions"""
340
+ print("""
341
+ πŸ€– LLM-Based Chatbot Setup Instructions
342
+ =====================================
343
+
344
+ πŸ“¦ Required Dependencies:
345
+ pip install gradio openai requests
346
+
347
+ πŸ”‘ API Key Setup:
348
+ 1. Visit https://platform.openai.com/
349
+ 2. Create an account and generate an API key
350
+ 3. Enter the API key in the interface
351
+
352
+ πŸš€ Running the Application:
353
+ python app.py
354
+
355
+ πŸ“‚ Files Created:
356
+ - conversation_YYYYMMDD_HHMMSS.json (exported chats)
357
+ """)
358
+
359
+ if __name__ == "__main__":
360
+ print_setup_instructions()
361
+
362
+ # Create and launch the interface
363
+ demo = create_interface()
364
+
365
+ # Launch with custom settings
366
+ demo.launch(
367
+ share=True
368
+ )