shukdevdatta123 commited on
Commit
b844a3b
Β·
verified Β·
1 Parent(s): cdbaf39

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -60
app.py CHANGED
@@ -22,11 +22,13 @@ class ChatbotManager:
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)}"
@@ -44,12 +46,13 @@ class ChatbotManager:
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 with user and AI icons"""
53
  if not self.current_api_key:
54
  return "❌ Please set your API key first!", history
55
 
@@ -60,16 +63,16 @@ class ChatbotManager:
60
  # Prepare conversation context
61
  messages = [{"role": "system", "content": self.system_prompt}]
62
 
63
- # Add conversation history with icons
64
  for user_msg, assistant_msg in history:
65
- messages.append({"role": "user", "content": f"πŸ‘€ {user_msg}"})
66
- messages.append({"role": "assistant", "content": f"πŸ€– {assistant_msg}"})
67
 
68
- # Add current user input with icon
69
- messages.append({"role": "user", "content": f"πŸ‘€ {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,
@@ -79,44 +82,43 @@ class ChatbotManager:
79
  )
80
 
81
  assistant_response = response.choices[0].message.content.strip()
82
- formatted_response = f"πŸ€– {assistant_response}" # Prepend AI icon to response
83
 
84
  # Update history
85
- history.append((user_input, assistant_response)) # Store without icons for history
86
 
87
- return formatted_response, history
88
 
89
  except Exception as e:
90
  error_msg = f"❌ Error generating response: {str(e)}"
91
  return error_msg, history
 
 
 
 
 
 
 
 
 
 
92
 
93
- def clear_conversation(self) -> Tuple[str, List[Tuple[str, str]]]:
94
- """Clear conversation history"""
95
- self.conversation_history = []
96
- return "", []
 
 
 
 
97
 
98
- def export_conversation(self, history: List[Tuple[str, str]]) -> str:
99
- """Export conversation history to JSON format"""
100
- if not history:
101
- return "No conversation to export"
102
-
103
- export_data = {
104
- "timestamp": datetime.now().isoformat(),
105
- "model": self.current_model,
106
- "conversation": [
107
- {"user": user_msg, "assistant": assistant_msg}
108
- for user_msg, assistant_msg in history
109
- ]
110
- }
111
-
112
- filename = f"conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
113
-
114
- try:
115
- with open(filename, 'w', encoding='utf-8') as f:
116
- json.dump(export_data, f, indent=2, ensure_ascii=False)
117
- return f"βœ… Conversation exported to {filename}"
118
- except Exception as e:
119
- return f"❌ Export failed: {str(e)}"
120
 
121
  # Initialize chatbot manager
122
  chatbot = ChatbotManager()
@@ -151,7 +153,9 @@ def create_interface():
151
  height=400,
152
  show_label=True,
153
  avatar_images=("πŸ‘€", "πŸ€–"),
154
- show_copy_button=True
 
 
155
  )
156
 
157
  with gr.Row():
@@ -159,19 +163,20 @@ def create_interface():
159
  placeholder="Type your message here...",
160
  scale=4,
161
  show_label=False,
162
-
163
  )
164
- send_btn = gr.Button("Send", variant="primary", scale=1)
165
 
166
  with gr.Row():
167
- clear_btn = gr.Button("Clear Chat", variant="secondary")
168
- export_btn = gr.Button("Export Chat", variant="secondary")
 
169
 
170
  with gr.Column(scale=1):
171
  gr.Markdown("### πŸ”§ Quick Settings")
172
 
173
  api_key_input = gr.Textbox(
174
- label="OpenAI API Key",
175
  placeholder="sk-...",
176
  type="password"
177
  )
@@ -184,15 +189,15 @@ def create_interface():
184
  model_dropdown = gr.Dropdown(
185
  choices=AVAILABLE_MODELS,
186
  value="gpt-3.5-turbo",
187
- label="Model"
188
  )
189
 
190
  max_tokens_slider = gr.Slider(
191
  minimum=50,
192
- maximum=500,
193
  value=150,
194
  step=10,
195
- label="Max Tokens"
196
  )
197
 
198
  temperature_slider = gr.Slider(
@@ -200,11 +205,20 @@ def create_interface():
200
  maximum=1.0,
201
  value=0.7,
202
  step=0.1,
203
- label="Temperature"
 
 
 
 
 
 
 
 
 
204
  )
205
 
206
  with gr.Tab("βš™οΈ Advanced Settings"):
207
- gr.Markdown("### System Prompt Configuration")
208
  system_prompt_input = gr.Textbox(
209
  label="System Prompt",
210
  value="You are a helpful AI assistant. Respond in a friendly and informative manner.",
@@ -212,7 +226,7 @@ def create_interface():
212
  placeholder="Enter custom system prompt..."
213
  )
214
 
215
- gr.Markdown("### πŸ“Š Custom Data Integration")
216
  custom_data_input = gr.Textbox(
217
  label="Custom Training Data",
218
  lines=10,
@@ -220,13 +234,22 @@ def create_interface():
220
  )
221
 
222
  with gr.Row():
223
- update_settings_btn = gr.Button("Update Settings", variant="primary")
224
- integrate_data_btn = gr.Button("Integrate Custom Data", variant="secondary")
 
225
 
226
  settings_status = gr.Textbox(
227
  label="Settings Status",
228
  interactive=False
229
  )
 
 
 
 
 
 
 
 
230
 
231
  with gr.Tab("πŸ“‹ Usage Guide"):
232
  gr.Markdown("""
@@ -234,22 +257,25 @@ def create_interface():
234
 
235
  ### 1. **Set Up API Key**
236
  - Obtain an OpenAI API key from [OpenAI Platform](https://platform.openai.com/)
237
- - Enter your API key in the "OpenAI API Key" field
238
  - Wait for the green checkmark confirmation
239
 
240
  ### 2. **Configure Settings**
241
  - **Model**: Choose from available GPT models
242
- - **Max Tokens**: Control response length (50-500)
243
  - **Temperature**: Adjust creativity (0.0 = focused, 1.0 = creative)
244
 
245
  ### 3. **Advanced Customization**
246
  - **System Prompt**: Define the AI's personality and behavior
247
  - **Custom Data**: Add domain-specific information or FAQs
 
248
 
249
  ### 4. **Chat Features**
250
  - Type messages and get intelligent responses
251
  - Clear conversation history anytime
252
  - Export chat history as JSON
 
 
253
 
254
  ## πŸ› οΈ Technical Features
255
 
@@ -258,6 +284,7 @@ def create_interface():
258
  - **Custom data integration**: Enhance responses with your own data
259
  - **Export functionality**: Save conversations for later analysis
260
  - **Real-time validation**: API key and settings verification
 
261
 
262
  ## πŸ’‘ Use Cases
263
 
@@ -265,6 +292,13 @@ def create_interface():
265
  - **Education**: Build tutoring assistants with custom curriculum
266
  - **Business**: Develop FAQ bots with company-specific information
267
  - **Research**: Analyze conversations and response patterns
 
 
 
 
 
 
 
268
  """)
269
 
270
  # Event handlers
@@ -281,7 +315,8 @@ def create_interface():
281
 
282
  def handle_settings_update(model, system_prompt, max_tokens, temperature):
283
  status = chatbot.update_settings(model, system_prompt, max_tokens, temperature)
284
- return status
 
285
 
286
  def handle_data_integration(custom_data):
287
  status = chatbot.preprocess_data(custom_data)
@@ -293,6 +328,33 @@ def create_interface():
293
  def handle_export(history):
294
  return chatbot.export_conversation(history)
295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  # Connect events
297
  api_key_input.change(
298
  handle_api_key,
@@ -315,7 +377,7 @@ def create_interface():
315
  update_settings_btn.click(
316
  handle_settings_update,
317
  inputs=[model_dropdown, system_prompt_input, max_tokens_slider, temperature_slider],
318
- outputs=[settings_status]
319
  )
320
 
321
  integrate_data_btn.click(
@@ -334,6 +396,46 @@ def create_interface():
334
  inputs=[chatbot_interface],
335
  outputs=[settings_status]
336
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
  return demo
339
 
@@ -357,6 +459,8 @@ def print_setup_instructions():
357
 
358
  πŸ“‚ Files Created:
359
  - conversation_YYYYMMDD_HHMMSS.json (exported chats)
 
 
360
  """)
361
 
362
  if __name__ == "__main__":
@@ -367,5 +471,7 @@ if __name__ == "__main__":
367
 
368
  # Launch with custom settings
369
  demo.launch(
370
- share=True
 
 
371
  )
 
22
  return "❌ Please enter a valid API key"
23
 
24
  self.current_api_key = api_key.strip()
25
+
26
+ # Create OpenAI client with the new syntax
27
+ self.client = openai.OpenAI(api_key=self.current_api_key)
28
 
29
  # Test the API key
30
  try:
31
+ self.client.models.list()
32
  return "βœ… API key validated successfully!"
33
  except Exception as e:
34
  return f"❌ Invalid API key: {str(e)}"
 
46
  if not data_text.strip():
47
  return "No custom data provided"
48
 
49
+ # Reset system prompt to avoid accumulation
50
+ base_prompt = "You are a helpful AI assistant. Respond in a friendly and informative manner."
51
+ self.system_prompt = base_prompt + f"\n\nAdditional Context:\n{data_text}"
52
  return f"βœ… Custom data integrated ({len(data_text)} characters)"
53
 
54
  def generate_response(self, user_input: str, history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
55
+ """Generate response using the selected LLM model"""
56
  if not self.current_api_key:
57
  return "❌ Please set your API key first!", history
58
 
 
63
  # Prepare conversation context
64
  messages = [{"role": "system", "content": self.system_prompt}]
65
 
66
+ # Add conversation history
67
  for user_msg, assistant_msg in history:
68
+ messages.append({"role": "user", "content": user_msg})
69
+ messages.append({"role": "assistant", "content": assistant_msg})
70
 
71
+ # Add current user input
72
+ messages.append({"role": "user", "content": user_input})
73
 
74
+ # Generate response using new OpenAI client syntax
75
+ response = self.client.chat.completions.create(
76
  model=self.current_model,
77
  messages=messages,
78
  max_tokens=self.max_tokens,
 
82
  )
83
 
84
  assistant_response = response.choices[0].message.content.strip()
 
85
 
86
  # Update history
87
+ history.append((user_input, assistant_response))
88
 
89
+ return assistant_response, history
90
 
91
  except Exception as e:
92
  error_msg = f"❌ Error generating response: {str(e)}"
93
  return error_msg, history
94
+
95
+ def clear_conversation(self) -> Tuple[str, List[Tuple[str, str]]]:
96
+ """Clear conversation history"""
97
+ self.conversation_history = []
98
+ return "", []
99
+
100
+ def export_conversation(self, history: List[Tuple[str, str]]) -> str:
101
+ """Export conversation history to JSON format"""
102
+ if not history:
103
+ return "No conversation to export"
104
 
105
+ export_data = {
106
+ "timestamp": datetime.now().isoformat(),
107
+ "model": self.current_model,
108
+ "conversation": [
109
+ {"user": user_msg, "assistant": assistant_msg}
110
+ for user_msg, assistant_msg in history
111
+ ]
112
+ }
113
 
114
+ filename = f"conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
115
+
116
+ try:
117
+ with open(filename, 'w', encoding='utf-8') as f:
118
+ json.dump(export_data, f, indent=2, ensure_ascii=False)
119
+ return f"βœ… Conversation exported to {filename}"
120
+ except Exception as e:
121
+ return f"❌ Export failed: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
  # Initialize chatbot manager
124
  chatbot = ChatbotManager()
 
153
  height=400,
154
  show_label=True,
155
  avatar_images=("πŸ‘€", "πŸ€–"),
156
+ show_copy_button=True,
157
+ bubble_full_width=False,
158
+ show_share_button=True
159
  )
160
 
161
  with gr.Row():
 
163
  placeholder="Type your message here...",
164
  scale=4,
165
  show_label=False,
166
+ container=False
167
  )
168
+ send_btn = gr.Button("πŸ“€ Send", variant="primary", scale=1)
169
 
170
  with gr.Row():
171
+ clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary")
172
+ export_btn = gr.Button("πŸ“₯ Export Chat", variant="secondary")
173
+ regenerate_btn = gr.Button("πŸ”„ Regenerate", variant="secondary")
174
 
175
  with gr.Column(scale=1):
176
  gr.Markdown("### πŸ”§ Quick Settings")
177
 
178
  api_key_input = gr.Textbox(
179
+ label="πŸ”‘ OpenAI API Key",
180
  placeholder="sk-...",
181
  type="password"
182
  )
 
189
  model_dropdown = gr.Dropdown(
190
  choices=AVAILABLE_MODELS,
191
  value="gpt-3.5-turbo",
192
+ label="πŸ€– Model"
193
  )
194
 
195
  max_tokens_slider = gr.Slider(
196
  minimum=50,
197
+ maximum=2000,
198
  value=150,
199
  step=10,
200
+ label="πŸ“ Max Tokens"
201
  )
202
 
203
  temperature_slider = gr.Slider(
 
205
  maximum=1.0,
206
  value=0.7,
207
  step=0.1,
208
+ label="🌑️ Temperature"
209
+ )
210
+
211
+ # Live settings display
212
+ gr.Markdown("### πŸ“Š Current Settings")
213
+ current_settings = gr.Textbox(
214
+ value="Model: gpt-3.5-turbo\nTokens: 150\nTemp: 0.7",
215
+ label="Active Configuration",
216
+ interactive=False,
217
+ lines=3
218
  )
219
 
220
  with gr.Tab("βš™οΈ Advanced Settings"):
221
+ gr.Markdown("### 🎯 System Prompt Configuration")
222
  system_prompt_input = gr.Textbox(
223
  label="System Prompt",
224
  value="You are a helpful AI assistant. Respond in a friendly and informative manner.",
 
226
  placeholder="Enter custom system prompt..."
227
  )
228
 
229
+ gr.Markdown("### πŸ“š Custom Data Integration")
230
  custom_data_input = gr.Textbox(
231
  label="Custom Training Data",
232
  lines=10,
 
234
  )
235
 
236
  with gr.Row():
237
+ update_settings_btn = gr.Button("βœ… Update Settings", variant="primary")
238
+ integrate_data_btn = gr.Button("πŸ“Š Integrate Custom Data", variant="secondary")
239
+ reset_prompt_btn = gr.Button("πŸ”„ Reset to Default", variant="secondary")
240
 
241
  settings_status = gr.Textbox(
242
  label="Settings Status",
243
  interactive=False
244
  )
245
+
246
+ # Preset system prompts
247
+ gr.Markdown("### 🎭 Preset System Prompts")
248
+ with gr.Row():
249
+ preset_customer_support = gr.Button("πŸ‘₯ Customer Support", variant="secondary")
250
+ preset_tutor = gr.Button("πŸŽ“ Educational Tutor", variant="secondary")
251
+ preset_creative = gr.Button("✨ Creative Assistant", variant="secondary")
252
+ preset_technical = gr.Button("πŸ”§ Technical Writer", variant="secondary")
253
 
254
  with gr.Tab("πŸ“‹ Usage Guide"):
255
  gr.Markdown("""
 
257
 
258
  ### 1. **Set Up API Key**
259
  - Obtain an OpenAI API key from [OpenAI Platform](https://platform.openai.com/)
260
+ - Enter your API key in the "πŸ”‘ OpenAI API Key" field
261
  - Wait for the green checkmark confirmation
262
 
263
  ### 2. **Configure Settings**
264
  - **Model**: Choose from available GPT models
265
+ - **Max Tokens**: Control response length (50-2000)
266
  - **Temperature**: Adjust creativity (0.0 = focused, 1.0 = creative)
267
 
268
  ### 3. **Advanced Customization**
269
  - **System Prompt**: Define the AI's personality and behavior
270
  - **Custom Data**: Add domain-specific information or FAQs
271
+ - **Presets**: Use pre-configured prompts for common use cases
272
 
273
  ### 4. **Chat Features**
274
  - Type messages and get intelligent responses
275
  - Clear conversation history anytime
276
  - Export chat history as JSON
277
+ - Regenerate the last response
278
+ - Copy responses using the copy button
279
 
280
  ## πŸ› οΈ Technical Features
281
 
 
284
  - **Custom data integration**: Enhance responses with your own data
285
  - **Export functionality**: Save conversations for later analysis
286
  - **Real-time validation**: API key and settings verification
287
+ - **Visual indicators**: User (πŸ‘€) and AI (πŸ€–) avatars
288
 
289
  ## πŸ’‘ Use Cases
290
 
 
292
  - **Education**: Build tutoring assistants with custom curriculum
293
  - **Business**: Develop FAQ bots with company-specific information
294
  - **Research**: Analyze conversations and response patterns
295
+
296
+ ## πŸ”§ Troubleshooting
297
+
298
+ - **API Key Issues**: Ensure your key is valid and has credits
299
+ - **Model Errors**: Some models may not be available in your region
300
+ - **Long Response Times**: Reduce max tokens or switch to faster models
301
+ - **Context Limits**: Clear chat history if responses become inconsistent
302
  """)
303
 
304
  # Event handlers
 
315
 
316
  def handle_settings_update(model, system_prompt, max_tokens, temperature):
317
  status = chatbot.update_settings(model, system_prompt, max_tokens, temperature)
318
+ settings_display = f"Model: {model}\nTokens: {max_tokens}\nTemp: {temperature}"
319
+ return status, settings_display
320
 
321
  def handle_data_integration(custom_data):
322
  status = chatbot.preprocess_data(custom_data)
 
328
  def handle_export(history):
329
  return chatbot.export_conversation(history)
330
 
331
+ def handle_regenerate(history):
332
+ if not history:
333
+ return history
334
+
335
+ # Get the last user message and regenerate response
336
+ last_user_msg = history[-1][0]
337
+ history_without_last = history[:-1]
338
+
339
+ response, updated_history = chatbot.generate_response(last_user_msg, history_without_last)
340
+ return updated_history
341
+
342
+ def update_settings_display(model, max_tokens, temperature):
343
+ return f"Model: {model}\nTokens: {max_tokens}\nTemp: {temperature}"
344
+
345
+ def reset_prompt():
346
+ default_prompt = "You are a helpful AI assistant. Respond in a friendly and informative manner."
347
+ return default_prompt, "βœ… System prompt reset to default"
348
+
349
+ def load_preset_prompt(preset_type):
350
+ presets = {
351
+ "customer_support": "You are a helpful customer support representative. You are friendly, professional, and knowledgeable. Always try to resolve customer issues and provide clear solutions. If you cannot solve a problem, escalate it politely.",
352
+ "tutor": "You are an experienced tutor. Explain concepts clearly, use examples, and encourage students when they struggle. Break down complex problems into smaller, manageable steps. Always check for understanding.",
353
+ "creative": "You are a creative writing assistant who helps with stories, poems, and creative content. Provide constructive feedback, suggest improvements, and inspire creativity while maintaining quality standards.",
354
+ "technical": "You are a technical writer who creates clear, concise documentation. Use precise language, provide examples when relevant, and structure information logically for developers and technical users."
355
+ }
356
+ return presets.get(preset_type, ""), f"βœ… Loaded {preset_type.replace('_', ' ').title()} preset"
357
+
358
  # Connect events
359
  api_key_input.change(
360
  handle_api_key,
 
377
  update_settings_btn.click(
378
  handle_settings_update,
379
  inputs=[model_dropdown, system_prompt_input, max_tokens_slider, temperature_slider],
380
+ outputs=[settings_status, current_settings]
381
  )
382
 
383
  integrate_data_btn.click(
 
396
  inputs=[chatbot_interface],
397
  outputs=[settings_status]
398
  )
399
+
400
+ regenerate_btn.click(
401
+ handle_regenerate,
402
+ inputs=[chatbot_interface],
403
+ outputs=[chatbot_interface]
404
+ )
405
+
406
+ # Live settings update
407
+ for component in [model_dropdown, max_tokens_slider, temperature_slider]:
408
+ component.change(
409
+ update_settings_display,
410
+ inputs=[model_dropdown, max_tokens_slider, temperature_slider],
411
+ outputs=[current_settings]
412
+ )
413
+
414
+ # Reset and preset buttons
415
+ reset_prompt_btn.click(
416
+ reset_prompt,
417
+ outputs=[system_prompt_input, settings_status]
418
+ )
419
+
420
+ preset_customer_support.click(
421
+ lambda: load_preset_prompt("customer_support"),
422
+ outputs=[system_prompt_input, settings_status]
423
+ )
424
+
425
+ preset_tutor.click(
426
+ lambda: load_preset_prompt("tutor"),
427
+ outputs=[system_prompt_input, settings_status]
428
+ )
429
+
430
+ preset_creative.click(
431
+ lambda: load_preset_prompt("creative"),
432
+ outputs=[system_prompt_input, settings_status]
433
+ )
434
+
435
+ preset_technical.click(
436
+ lambda: load_preset_prompt("technical"),
437
+ outputs=[system_prompt_input, settings_status]
438
+ )
439
 
440
  return demo
441
 
 
459
 
460
  πŸ“‚ Files Created:
461
  - conversation_YYYYMMDD_HHMMSS.json (exported chats)
462
+
463
+ 🌐 Access: http://localhost:7860
464
  """)
465
 
466
  if __name__ == "__main__":
 
471
 
472
  # Launch with custom settings
473
  demo.launch(
474
+ share=True,
475
+ debug=True,
476
+ show_error=True
477
  )