shukdevdatta123 commited on
Commit
8f1620d
Β·
verified Β·
1 Parent(s): 2196f8b

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -419
app.py DELETED
@@ -1,419 +0,0 @@
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
- if not api_key.strip():
21
- return "❌ Please enter a valid API key"
22
-
23
- self.current_api_key = api_key.strip()
24
- openai.api_key = self.current_api_key
25
-
26
- try:
27
- openai.Model.list()
28
- return "βœ… API key validated successfully!"
29
- except Exception as e:
30
- return f"❌ Invalid API key: {str(e)}"
31
-
32
- def update_settings(self, model: str, system_prompt: str, max_tokens: int, temperature: float) -> str:
33
- self.current_model = model
34
- self.system_prompt = system_prompt
35
- self.max_tokens = max_tokens
36
- self.temperature = temperature
37
- return f"βœ… Settings updated: Model={model}, Max Tokens={max_tokens}, Temperature={temperature}"
38
-
39
- def preprocess_data(self, data_text: str) -> str:
40
- if not data_text.strip():
41
- return "No custom data provided"
42
-
43
- base_prompt = "You are a helpful AI assistant. Respond in a friendly and informative manner."
44
- self.system_prompt = base_prompt + f"\n\nAdditional Context:\n{data_text}"
45
- return f"βœ… Custom data integrated ({len(data_text)} characters)"
46
-
47
- def generate_response(self, user_input: str, history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
48
- if not self.current_api_key:
49
- return "❌ Please set your API key first!", history
50
-
51
- if not user_input.strip():
52
- return "Please enter a message.", history
53
-
54
- try:
55
- messages = [{"role": "system", "content": self.system_prompt}]
56
-
57
- for user_msg, assistant_msg in history:
58
- messages.append({"role": "user", "content": user_msg})
59
- messages.append({"role": "assistant", "content": assistant_msg})
60
-
61
- messages.append({"role": "user", "content": user_input})
62
-
63
- response = openai.ChatCompletion.create(
64
- model=self.current_model,
65
- messages=messages,
66
- max_tokens=self.max_tokens,
67
- temperature=self.temperature,
68
- n=1,
69
- stop=None,
70
- )
71
-
72
- assistant_response = response.choices[0].message.content.strip()
73
- history.append((user_input, assistant_response))
74
-
75
- return assistant_response, history
76
-
77
- except Exception as e:
78
- error_msg = f"❌ Error generating response: {str(e)}"
79
- return error_msg, history
80
-
81
- def clear_conversation(self) -> Tuple[str, List[Tuple[str, str]]]:
82
- self.conversation_history = []
83
- return "", []
84
-
85
- def export_conversation(self, history: List[Tuple[str, str]]) -> Tuple[str, Optional[str]]:
86
- if not history:
87
- return "No conversation to export", None
88
-
89
- export_data = {
90
- "timestamp": datetime.now().isoformat(),
91
- "model": self.current_model,
92
- "conversation": [
93
- {"user": user_msg, "assistant": assistant_msg}
94
- for user_msg, assistant_msg in history
95
- ]
96
- }
97
-
98
- filename = f"conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
99
-
100
- try:
101
- os.makedirs("/tmp", exist_ok=True)
102
- filepath = os.path.join("/tmp", filename)
103
- with open(filepath, 'w', encoding='utf-8') as f:
104
- json.dump(export_data, f, indent=2, ensure_ascii=False)
105
- return f"βœ… Conversation exported as {filename}", filepath
106
- except Exception as e:
107
- return f"❌ Export failed: {str(e)}", None
108
-
109
- # Initialize chatbot manager
110
- chatbot = ChatbotManager()
111
-
112
- # Define available models for OpenAI 0.28
113
- AVAILABLE_MODELS = [
114
- "gpt-3.5-turbo",
115
- "gpt-3.5-turbo-16k",
116
- "gpt-4",
117
- "gpt-4-32k",
118
- "gpt-4-0613",
119
- "gpt-4-32k-0613"
120
- ]
121
-
122
- def create_interface():
123
- with gr.Blocks(title="LLM-Based Chatbot", theme=gr.themes.Ocean()) as demo:
124
- gr.Markdown("""
125
- # πŸ€– LLM-Based Conversational AI Chatbot
126
- This chatbot leverages powerful Language Models to provide intelligent conversations.
127
- Enter your OpenAI API key to get started!
128
- """)
129
-
130
- with gr.Tab("πŸ’¬ Chat Interface"):
131
- with gr.Row():
132
- with gr.Column(scale=3):
133
- chatbot_interface = gr.Chatbot(
134
- label="Conversation",
135
- height=400,
136
- show_label=True,
137
- avatar_images=("user.png", "assistant.png"),
138
- show_copy_button=True,
139
- bubble_full_width=False,
140
- )
141
-
142
- with gr.Row():
143
- user_input = gr.Textbox(
144
- placeholder="Type your message here...",
145
- scale=4,
146
- show_label=False,
147
- container=False
148
- )
149
- send_btn = gr.Button("πŸ“€ Send", variant="primary", scale=1)
150
-
151
- with gr.Row():
152
- clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary")
153
- regenerate_btn = gr.Button("πŸ”„ Regenerate", variant="secondary")
154
-
155
- with gr.Column(scale=1):
156
- gr.Markdown("### πŸ”§ Quick Settings")
157
-
158
- api_key_input = gr.Textbox(
159
- label="πŸ”‘ OpenAI API Key",
160
- placeholder="sk-...",
161
- type="password"
162
- )
163
- api_status = gr.Textbox(
164
- label="API Status",
165
- interactive=False,
166
- value="❌ No API key provided"
167
- )
168
-
169
- model_dropdown = gr.Dropdown(
170
- choices=AVAILABLE_MODELS,
171
- value="gpt-3.5-turbo",
172
- label="πŸ€– Model"
173
- )
174
-
175
- max_tokens_slider = gr.Slider(
176
- minimum=50,
177
- maximum=4096,
178
- value=150,
179
- step=10,
180
- label="πŸ“ Max Tokens"
181
- )
182
-
183
- temperature_slider = gr.Slider(
184
- minimum=0.0,
185
- maximum=1.0,
186
- value=0.7,
187
- step=0.1,
188
- label="🌑️ Temperature"
189
- )
190
-
191
- gr.Markdown("### πŸ“Š Current Settings")
192
- current_settings = gr.Textbox(
193
- value="Model: gpt-3.5-turbo\nTokens: 150\nTemp: 0.7",
194
- label="Active Configuration",
195
- interactive=False,
196
- lines=3
197
- )
198
-
199
- with gr.Tab("βš™οΈ Advanced Settings"):
200
- gr.Markdown("### 🎯 System Prompt Configuration")
201
- system_prompt_input = gr.Textbox(
202
- label="System Prompt",
203
- value="You are a helpful AI assistant. Respond in a friendly and informative manner.",
204
- lines=5,
205
- placeholder="Enter custom system prompt..."
206
- )
207
-
208
- gr.Markdown("### πŸ“š Custom Data Integration")
209
- custom_data_input = gr.Textbox(
210
- label="Custom Training Data",
211
- lines=10,
212
- placeholder="Enter custom data, FAQs, or domain-specific information..."
213
- )
214
-
215
- with gr.Row():
216
- update_settings_btn = gr.Button("βœ… Update Settings", variant="primary")
217
- integrate_data_btn = gr.Button("πŸ“Š Integrate Custom Data", variant="secondary")
218
- reset_prompt_btn = gr.Button("πŸ”„ Reset to Default", variant="secondary")
219
-
220
- settings_status = gr.Textbox(
221
- label="Settings Status",
222
- interactive=False
223
- )
224
-
225
- gr.Markdown("### 🎭 Preset System Prompts")
226
- with gr.Row():
227
- preset_customer_support = gr.Button("πŸ‘₯ Customer Support", variant="secondary")
228
- preset_tutor = gr.Button("πŸŽ“ Educational Tutor", variant="secondary")
229
- preset_creative = gr.Button("✨ Creative Assistant", variant="secondary")
230
- preset_technical = gr.Button("πŸ”§ Technical Writer", variant="secondary")
231
-
232
- with gr.Tab("πŸ“‹ Usage Guide"):
233
- gr.Markdown("""
234
- ## πŸš€ Getting Started
235
-
236
- ### 1. **Set Up API Key**
237
- - Obtain an OpenAI API key from [OpenAI Platform](https://platform.openai.com/)
238
- - Enter your API key in the "πŸ”‘ OpenAI API Key" field
239
- - Wait for the green checkmark confirmation
240
-
241
- ### 2. **Configure Settings**
242
- - **Model**: Choose from available GPT models
243
- - **Max Tokens**: Control response length (50-4096)
244
- - **Temperature**: Adjust creativity (0.0 = focused, 1.0 = creative)
245
-
246
- ### 3. **Advanced Customization**
247
- - **System Prompt**: Define the AI's personality and behavior
248
- - **Custom Data**: Add domain-specific information or FAQs
249
- - **Presets**: Use pre-configured prompts for common use cases
250
-
251
- ### 4. **Chat Features**
252
- - Type messages and get intelligent responses
253
- - Clear conversation history anytime
254
- - Regenerate the last response
255
- - Copy responses using the copy button
256
-
257
- ## πŸ› οΈ Technical Features
258
-
259
- - **Multi-model support**: GPT-3.5, GPT-4, and variants
260
- - **Conversation memory**: Maintains context throughout the session
261
- - **Custom data integration**: Enhance responses with your own data
262
- - **Real-time validation**: API key and settings verification
263
- - **Visual indicators**: User and AI avatars
264
-
265
- ## πŸ’‘ Use Cases
266
-
267
- - **Customer Support**: Create domain-specific support chatbots
268
- - **Education**: Build tutoring assistants with custom curriculum
269
- - **Business**: Develop FAQ bots with company-specific information
270
- - **Research**: Analyze conversations and response patterns
271
-
272
- ## πŸ”§ Troubleshooting
273
-
274
- - **API Key Issues**: Ensure your key is valid and has credits
275
- - **Model Errors**: Some models may not be available in your region
276
- - **Long Response Times**: Reduce max tokens or switch to faster models
277
- - **Context Limits**: Clear chat history if responses become inconsistent
278
-
279
- ## πŸ“¦ Installation Requirements
280
-
281
- This version is compatible with OpenAI 0.28.0. Install dependencies:
282
- ```bash
283
- pip install openai==0.28.0
284
- pip install gradio
285
- pip install requests
286
- ```
287
- """)
288
-
289
- # Event handlers
290
- def handle_api_key(api_key):
291
- status = chatbot.set_api_key(api_key)
292
- return status
293
-
294
- def handle_chat(user_input, history):
295
- if not user_input.strip():
296
- return history or [], ""
297
-
298
- response, updated_history = chatbot.generate_response(user_input, history or [])
299
- return updated_history, ""
300
-
301
- def handle_settings_update(model, system_prompt, max_tokens, temperature):
302
- status = chatbot.update_settings(model, system_prompt, max_tokens, temperature)
303
- settings_display = f"Model: {model}\nTokens: {max_tokens}\nTemp: {temperature}"
304
- return status, settings_display
305
-
306
- def handle_data_integration(custom_data):
307
- status = chatbot.preprocess_data(custom_data)
308
- return status
309
-
310
- def handle_clear():
311
- return chatbot.clear_conversation()
312
-
313
- def handle_regenerate(history):
314
- if not history:
315
- return history or []
316
-
317
- last_user_msg = history[-1][0]
318
- history_without_last = history[:-1]
319
- response, updated_history = chatbot.generate_response(last_user_msg, history_without_last)
320
- return updated_history
321
-
322
- def update_settings_display(model, max_tokens, temperature):
323
- return f"Model: {model}\nTokens: {max_tokens}\nTemp: {temperature}"
324
-
325
- def reset_prompt():
326
- default_prompt = "You are a helpful AI assistant. Respond in a friendly and informative manner."
327
- return default_prompt, "βœ… System prompt reset to default"
328
-
329
- def load_preset_prompt(preset_type):
330
- presets = {
331
- "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.",
332
- "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.",
333
- "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.",
334
- "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."
335
- }
336
- return presets.get(preset_type, ""), f"βœ… Loaded {preset_type.replace('_', ' ').title()} preset"
337
-
338
- # Connect events
339
- api_key_input.change(
340
- handle_api_key,
341
- inputs=[api_key_input],
342
- outputs=[api_status]
343
- )
344
-
345
- send_btn.click(
346
- handle_chat,
347
- inputs=[user_input, chatbot_interface],
348
- outputs=[chatbot_interface, user_input]
349
- )
350
-
351
- user_input.submit(
352
- handle_chat,
353
- inputs=[user_input, chatbot_interface],
354
- outputs=[chatbot_interface, user_input]
355
- )
356
-
357
- update_settings_btn.click(
358
- handle_settings_update,
359
- inputs=[model_dropdown, system_prompt_input, max_tokens_slider, temperature_slider],
360
- outputs=[settings_status, current_settings]
361
- )
362
-
363
- integrate_data_btn.click(
364
- handle_data_integration,
365
- inputs=[custom_data_input],
366
- outputs=[settings_status]
367
- )
368
-
369
- clear_btn.click(
370
- handle_clear,
371
- outputs=[user_input, chatbot_interface]
372
- )
373
-
374
- regenerate_btn.click(
375
- handle_regenerate,
376
- inputs=[chatbot_interface],
377
- outputs=[chatbot_interface]
378
- )
379
-
380
- for component in [model_dropdown, max_tokens_slider, temperature_slider]:
381
- component.change(
382
- update_settings_display,
383
- inputs=[model_dropdown, max_tokens_slider, temperature_slider],
384
- outputs=[current_settings]
385
- )
386
-
387
- reset_prompt_btn.click(
388
- reset_prompt,
389
- outputs=[system_prompt_input, settings_status]
390
- )
391
-
392
- preset_customer_support.click(
393
- lambda: load_preset_prompt("customer_support"),
394
- outputs=[system_prompt_input, settings_status]
395
- )
396
-
397
- preset_tutor.click(
398
- lambda: load_preset_prompt("tutor"),
399
- outputs=[system_prompt_input, settings_status]
400
- )
401
-
402
- preset_creative.click(
403
- lambda: load_preset_prompt("creative"),
404
- outputs=[system_prompt_input, settings_status]
405
- )
406
-
407
- preset_technical.click(
408
- lambda: load_preset_prompt("technical"),
409
- outputs=[system_prompt_input, settings_status]
410
- )
411
-
412
- return demo
413
-
414
- if __name__ == "__main__":
415
- demo = create_interface()
416
- demo.launch(
417
- server_name="0.0.0.0",
418
- server_port=7860
419
- )