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
bc6d2ba
 
 
 
 
 
 
 
 
 
 
b844a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc6d2ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b844a3b
bc6d2ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b844a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc6d2ba
 
 
 
 
 
 
 
 
 
 
a577779
 
 
bc6d2ba
 
 
 
 
 
 
 
 
 
 
b844a3b
 
bc6d2ba
 
 
 
 
 
 
 
 
 
b844a3b
 
 
bc6d2ba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
import gradio as gr
import openai
import json
import os
import time
from typing import List, Tuple, Optional
import requests
from datetime import datetime

class ChatbotManager:
    def __init__(self):
        self.conversation_history = []
        self.current_api_key = None
        self.current_model = "gpt-3.5-turbo"
        self.system_prompt = "You are a helpful AI assistant. Respond in a friendly and informative manner."
        self.max_tokens = 150
        self.temperature = 0.7
        
    def set_api_key(self, api_key: str) -> str:
        """Set the OpenAI API key"""
        if not api_key.strip():
            return "❌ Please enter a valid API key"
        
        self.current_api_key = api_key.strip()
        openai.api_key = self.current_api_key
        
        # Test the API key
        try:
            openai.Model.list()
            return "βœ… API key validated successfully!"
        except Exception as e:
            return f"❌ Invalid API key: {str(e)}"
    
    def update_settings(self, model: str, system_prompt: str, max_tokens: int, temperature: float) -> str:
        """Update chatbot settings"""
        self.current_model = model
        self.system_prompt = system_prompt
        self.max_tokens = max_tokens
        self.temperature = temperature
        return f"βœ… Settings updated: Model={model}, Max Tokens={max_tokens}, Temperature={temperature}"
    
    def preprocess_data(self, data_text: str) -> str:
        """Preprocess and integrate custom data into the system prompt"""
        if not data_text.strip():
            return "No custom data provided"
        
        # Reset system prompt to avoid accumulation
        base_prompt = "You are a helpful AI assistant. Respond in a friendly and informative manner."
        self.system_prompt = base_prompt + f"\n\nAdditional Context:\n{data_text}"
        return f"βœ… Custom data integrated ({len(data_text)} characters)"
    
    def generate_response(self, user_input: str, history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
        """Generate response using the selected LLM model"""
        if not self.current_api_key:
            return "❌ Please set your API key first!", history
        
        if not user_input.strip():
            return "Please enter a message.", history
        
        try:
            # Prepare conversation context
            messages = [{"role": "system", "content": self.system_prompt}]
            
            # Add conversation history
            for user_msg, assistant_msg in history:
                messages.append({"role": "user", "content": user_msg})
                messages.append({"role": "assistant", "content": assistant_msg})
            
            # Add current user input
            messages.append({"role": "user", "content": user_input})
            
            # Generate response using OpenAI 0.28 syntax
            response = openai.ChatCompletion.create(
                model=self.current_model,
                messages=messages,
                max_tokens=self.max_tokens,
                temperature=self.temperature,
                n=1,
                stop=None,
            )
            
            assistant_response = response.choices[0].message.content.strip()
            
            # Update history
            history.append((user_input, assistant_response))
            
            return assistant_response, history
            
        except Exception as e:
            error_msg = f"❌ Error generating response: {str(e)}"
            return error_msg, history
    
    def clear_conversation(self) -> Tuple[str, List[Tuple[str, str]]]:
        """Clear conversation history"""
        self.conversation_history = []
        return "", []
    
    def export_conversation(self, history: List[Tuple[str, str]]) -> str:
        """Export conversation history to JSON format"""
        if not history:
            return "No conversation to export"
        
        export_data = {
            "timestamp": datetime.now().isoformat(),
            "model": self.current_model,
            "conversation": [
                {"user": user_msg, "assistant": assistant_msg}
                for user_msg, assistant_msg in history
            ]
        }
        
        filename = f"conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(export_data, f, indent=2, ensure_ascii=False)
            return f"βœ… Conversation exported to {filename}"
        except Exception as e:
            return f"❌ Export failed: {str(e)}"

# Initialize chatbot manager
chatbot = ChatbotManager()

# Define available models for OpenAI 0.28
AVAILABLE_MODELS = [
    "gpt-3.5-turbo",
    "gpt-3.5-turbo-16k",
    "gpt-4",
    "gpt-4-32k",
    "gpt-4-0613",
    "gpt-4-32k-0613"
]

def create_interface():
    """Create the Gradio interface"""
    
    with gr.Blocks(title="LLM-Based Chatbot", theme=gr.themes.Soft()) as demo:
        gr.Markdown("""
        # πŸ€– LLM-Based Conversational AI Chatbot
        
        This chatbot leverages powerful Language Models to provide intelligent conversations.
        Enter your OpenAI API key to get started!
        """)
        
        with gr.Tab("πŸ’¬ Chat Interface"):
            with gr.Row():
                with gr.Column(scale=3):
                    chatbot_interface = gr.Chatbot(
                        label="Conversation",
                        height=400,
                        show_label=True,
                        avatar_images=("πŸ‘€", "πŸ€–"),
                        show_copy_button=True,
                        bubble_full_width=False,
                        show_share_button=True
                    )
                    
                    with gr.Row():
                        user_input = gr.Textbox(
                            placeholder="Type your message here...",
                            scale=4,
                            show_label=False,
                            container=False
                        )
                        send_btn = gr.Button("πŸ“€ Send", variant="primary", scale=1)
                    
                    with gr.Row():
                        clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary")
                        export_btn = gr.Button("πŸ“₯ Export Chat", variant="secondary")
                        regenerate_btn = gr.Button("πŸ”„ Regenerate", variant="secondary")
                
                with gr.Column(scale=1):
                    gr.Markdown("### πŸ”§ Quick Settings")
                    
                    api_key_input = gr.Textbox(
                        label="πŸ”‘ OpenAI API Key",
                        placeholder="sk-...",
                        type="password"
                    )
                    api_status = gr.Textbox(
                        label="API Status",
                        interactive=False,
                        value="❌ No API key provided"
                    )
                    
                    model_dropdown = gr.Dropdown(
                        choices=AVAILABLE_MODELS,
                        value="gpt-3.5-turbo",
                        label="πŸ€– Model"
                    )
                    
                    max_tokens_slider = gr.Slider(
                        minimum=50,
                        maximum=2000,
                        value=150,
                        step=10,
                        label="πŸ“ Max Tokens"
                    )
                    
                    temperature_slider = gr.Slider(
                        minimum=0.0,
                        maximum=1.0,
                        value=0.7,
                        step=0.1,
                        label="🌑️ Temperature"
                    )
                    
                    # Live settings display
                    gr.Markdown("### πŸ“Š Current Settings")
                    current_settings = gr.Textbox(
                        value="Model: gpt-3.5-turbo\nTokens: 150\nTemp: 0.7",
                        label="Active Configuration",
                        interactive=False,
                        lines=3
                    )
        
        with gr.Tab("βš™οΈ Advanced Settings"):
            gr.Markdown("### 🎯 System Prompt Configuration")
            system_prompt_input = gr.Textbox(
                label="System Prompt",
                value="You are a helpful AI assistant. Respond in a friendly and informative manner.",
                lines=5,
                placeholder="Enter custom system prompt..."
            )
            
            gr.Markdown("### πŸ“š Custom Data Integration")
            custom_data_input = gr.Textbox(
                label="Custom Training Data",
                lines=10,
                placeholder="Enter custom data, FAQs, or domain-specific information..."
            )
            
            with gr.Row():
                update_settings_btn = gr.Button("βœ… Update Settings", variant="primary")
                integrate_data_btn = gr.Button("πŸ“Š Integrate Custom Data", variant="secondary")
                reset_prompt_btn = gr.Button("πŸ”„ Reset to Default", variant="secondary")
            
            settings_status = gr.Textbox(
                label="Settings Status",
                interactive=False
            )
            
            # Preset system prompts
            gr.Markdown("### 🎭 Preset System Prompts")
            with gr.Row():
                preset_customer_support = gr.Button("πŸ‘₯ Customer Support", variant="secondary")
                preset_tutor = gr.Button("πŸŽ“ Educational Tutor", variant="secondary")
                preset_creative = gr.Button("✨ Creative Assistant", variant="secondary")
                preset_technical = gr.Button("πŸ”§ Technical Writer", variant="secondary")
        
        with gr.Tab("πŸ“‹ Usage Guide"):
            gr.Markdown("""
            ## πŸš€ Getting Started
            
            ### 1. **Set Up API Key**
            - Obtain an OpenAI API key from [OpenAI Platform](https://platform.openai.com/)
            - Enter your API key in the "πŸ”‘ OpenAI API Key" field
            - Wait for the green checkmark confirmation
            
            ### 2. **Configure Settings**
            - **Model**: Choose from available GPT models
            - **Max Tokens**: Control response length (50-2000)
            - **Temperature**: Adjust creativity (0.0 = focused, 1.0 = creative)
            
            ### 3. **Advanced Customization**
            - **System Prompt**: Define the AI's personality and behavior
            - **Custom Data**: Add domain-specific information or FAQs
            - **Presets**: Use pre-configured prompts for common use cases
            
            ### 4. **Chat Features**
            - Type messages and get intelligent responses
            - Clear conversation history anytime
            - Export chat history as JSON
            - Regenerate the last response
            - Copy responses using the copy button
            
            ## πŸ› οΈ Technical Features
            
            - **Multi-model support**: GPT-3.5, GPT-4, and variants
            - **Conversation memory**: Maintains context throughout the session
            - **Custom data integration**: Enhance responses with your own data
            - **Export functionality**: Save conversations for later analysis
            - **Real-time validation**: API key and settings verification
            - **Visual indicators**: User (πŸ‘€) and AI (πŸ€–) avatars
            
            ## πŸ’‘ Use Cases
            
            - **Customer Support**: Create domain-specific support chatbots
            - **Education**: Build tutoring assistants with custom curriculum
            - **Business**: Develop FAQ bots with company-specific information
            - **Research**: Analyze conversations and response patterns
            
            ## πŸ”§ Troubleshooting
            
            - **API Key Issues**: Ensure your key is valid and has credits
            - **Model Errors**: Some models may not be available in your region
            - **Long Response Times**: Reduce max tokens or switch to faster models
            - **Context Limits**: Clear chat history if responses become inconsistent
            
            ## πŸ“¦ Installation Requirements
            
            This version is compatible with OpenAI 0.28.0. Install dependencies:
            ```bash
            pip install openai==0.28.0
            pip install gradio
            pip install requests
            ```
            """)
        
        # Event handlers
        def handle_api_key(api_key):
            status = chatbot.set_api_key(api_key)
            return status
        
        def handle_chat(user_input, history):
            if not user_input.strip():
                return history, ""
            
            response, updated_history = chatbot.generate_response(user_input, history)
            return updated_history, ""
        
        def handle_settings_update(model, system_prompt, max_tokens, temperature):
            status = chatbot.update_settings(model, system_prompt, max_tokens, temperature)
            settings_display = f"Model: {model}\nTokens: {max_tokens}\nTemp: {temperature}"
            return status, settings_display
        
        def handle_data_integration(custom_data):
            status = chatbot.preprocess_data(custom_data)
            return status
        
        def handle_clear():
            return chatbot.clear_conversation()
        
        def handle_export(history):
            return chatbot.export_conversation(history)
        
        def handle_regenerate(history):
            if not history:
                return history
            
            # Get the last user message and regenerate response
            last_user_msg = history[-1][0]
            history_without_last = history[:-1]
            
            response, updated_history = chatbot.generate_response(last_user_msg, history_without_last)
            return updated_history
        
        def update_settings_display(model, max_tokens, temperature):
            return f"Model: {model}\nTokens: {max_tokens}\nTemp: {temperature}"
        
        def reset_prompt():
            default_prompt = "You are a helpful AI assistant. Respond in a friendly and informative manner."
            return default_prompt, "βœ… System prompt reset to default"
        
        def load_preset_prompt(preset_type):
            presets = {
                "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.",
                "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.",
                "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.",
                "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."
            }
            return presets.get(preset_type, ""), f"βœ… Loaded {preset_type.replace('_', ' ').title()} preset"
        
        # Connect events
        api_key_input.change(
            handle_api_key,
            inputs=[api_key_input],
            outputs=[api_status]
        )
        
        send_btn.click(
            handle_chat,
            inputs=[user_input, chatbot_interface],
            outputs=[chatbot_interface, user_input]
        )
        
        user_input.submit(
            handle_chat,
            inputs=[user_input, chatbot_interface],
            outputs=[chatbot_interface, user_input]
        )
        
        update_settings_btn.click(
            handle_settings_update,
            inputs=[model_dropdown, system_prompt_input, max_tokens_slider, temperature_slider],
            outputs=[settings_status, current_settings]
        )
        
        integrate_data_btn.click(
            handle_data_integration,
            inputs=[custom_data_input],
            outputs=[settings_status]
        )
        
        clear_btn.click(
            handle_clear,
            outputs=[user_input, chatbot_interface]
        )
        
        export_btn.click(
            handle_export,
            inputs=[chatbot_interface],
            outputs=[settings_status]
        )
        
        regenerate_btn.click(
            handle_regenerate,
            inputs=[chatbot_interface],
            outputs=[chatbot_interface]
        )
        
        # Live settings update
        for component in [model_dropdown, max_tokens_slider, temperature_slider]:
            component.change(
                update_settings_display,
                inputs=[model_dropdown, max_tokens_slider, temperature_slider],
                outputs=[current_settings]
            )
        
        # Reset and preset buttons
        reset_prompt_btn.click(
            reset_prompt,
            outputs=[system_prompt_input, settings_status]
        )
        
        preset_customer_support.click(
            lambda: load_preset_prompt("customer_support"),
            outputs=[system_prompt_input, settings_status]
        )
        
        preset_tutor.click(
            lambda: load_preset_prompt("tutor"),
            outputs=[system_prompt_input, settings_status]
        )
        
        preset_creative.click(
            lambda: load_preset_prompt("creative"),
            outputs=[system_prompt_input, settings_status]
        )
        
        preset_technical.click(
            lambda: load_preset_prompt("technical"),
            outputs=[system_prompt_input, settings_status]
        )
    
    return demo

# Requirements and setup instructions
def print_setup_instructions():
    """Print setup instructions"""
    print("""
    πŸ€– LLM-Based Chatbot Setup Instructions
    =====================================
    
    πŸ“¦ Required Dependencies:
    pip install openai==0.28.0
    pip install gradio
    pip install requests
    
    πŸ”‘ API Key Setup:
    1. Visit https://platform.openai.com/
    2. Create an account and generate an API key
    3. Enter the API key in the interface
    
    πŸš€ Running the Application:
    python app.py
    
    πŸ“‚ Files Created:
    - conversation_YYYYMMDD_HHMMSS.json (exported chats)
    
    🌐 Access: http://localhost:7860
    """)

if __name__ == "__main__":
    print_setup_instructions()
    
    # Create and launch the interface
    demo = create_interface()
    
    # Launch with custom settings
    demo.launch(
        share=True,
        debug=True,
        show_error=True
    )