File size: 22,337 Bytes
df94830
 
 
 
 
 
 
 
 
f3a35a2
df94830
 
 
 
 
 
 
 
 
f3a35a2
 
df94830
 
 
 
 
 
 
 
 
 
 
f3a35a2
 
df94830
f3a35a2
 
 
 
 
 
 
df94830
f3a35a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df94830
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a35a2
df94830
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a35a2
df94830
f3a35a2
df94830
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
import gradio as gr
import json
import zipfile
import io
import os
from datetime import datetime
from dotenv import load_dotenv
import requests
from bs4 import BeautifulSoup
from scraping_service import get_grounding_context_crawl4ai, fetch_url_content_crawl4ai

# Load environment variables from .env file
load_dotenv()

# Template for generated space app (based on mvp_simple.py)
SPACE_TEMPLATE = '''import gradio as gr
import os
import requests
import json
import asyncio
from crawl4ai import AsyncWebCrawler

# Configuration
SPACE_NAME = "{name}"
SPACE_DESCRIPTION = "{description}"
SYSTEM_PROMPT = """{system_prompt}"""
MODEL = "{model}"
GROUNDING_URLS = {grounding_urls}

# Get API key from environment - customizable variable name
API_KEY = os.environ.get("{api_key_var}")

async def fetch_url_content_async(url, crawler):
    """Fetch and extract text content from a URL using Crawl4AI"""
    try:
        result = await crawler.arun(
            url=url,
            bypass_cache=True,
            word_count_threshold=10,
            excluded_tags=['script', 'style', 'nav', 'header', 'footer'],
            remove_overlay_elements=True
        )
        
        if result.success:
            content = result.markdown or result.cleaned_html or ""
            # Truncate to ~4000 characters
            if len(content) > 4000:
                content = content[:4000] + "..."
            return content
        else:
            return f"Error fetching {{url}}: Failed to retrieve content"
    except Exception as e:
        return f"Error fetching {{url}}: {{str(e)}}"

def fetch_url_content(url):
    """Synchronous wrapper for URL fetching"""
    async def fetch():
        async with AsyncWebCrawler(verbose=False) as crawler:
            return await fetch_url_content_async(url, crawler)
    
    try:
        return asyncio.run(fetch())
    except Exception as e:
        return f"Error fetching {{url}}: {{str(e)}}"

def get_grounding_context():
    """Fetch context from grounding URLs"""
    if not GROUNDING_URLS:
        return ""
    
    context_parts = []
    for i, url in enumerate(GROUNDING_URLS, 1):
        if url.strip():
            content = fetch_url_content(url.strip())
            context_parts.append(f"Context from URL {{i}} ({{url}}):\\n{{content}}")
    
    if context_parts:
        return "\\n\\n" + "\\n\\n".join(context_parts) + "\\n\\n"
    return ""

def generate_response(message, history):
    """Generate response using OpenRouter API"""
    
    if not API_KEY:
        return "Please set your {api_key_var} in the Space settings."
    
    # Get grounding context
    grounding_context = get_grounding_context()
    
    # Build enhanced system prompt with grounding context
    enhanced_system_prompt = SYSTEM_PROMPT + grounding_context
    
    # Build messages array for the API
    messages = [{{"role": "system", "content": enhanced_system_prompt}}]
    
    # Add conversation history - compatible with Gradio 5.x format
    for chat in history:
        if isinstance(chat, dict):
            # New format: {{"role": "user", "content": "..."}} or {{"role": "assistant", "content": "..."}}
            messages.append(chat)
        else:
            # Legacy format: ("user msg", "bot msg")
            user_msg, bot_msg = chat
            messages.append({{"role": "user", "content": user_msg}})
            if bot_msg:
                messages.append({{"role": "assistant", "content": bot_msg}})
    
    # Add current message
    messages.append({{"role": "user", "content": message}})
    
    # Make API request
    try:
        response = requests.post(
            url="https://openrouter.ai/api/v1/chat/completions",
            headers={{
                "Authorization": f"Bearer {{API_KEY}}",
                "Content-Type": "application/json"
            }},
            json={{
                "model": MODEL,
                "messages": messages,
                "temperature": {temperature},
                "max_tokens": {max_tokens}
            }}
        )
        
        if response.status_code == 200:
            return response.json()['choices'][0]['message']['content']
        else:
            return f"Error: {{response.status_code}} - {{response.text}}"
            
    except Exception as e:
        return f"Error: {{str(e)}}"

# Create simple Gradio interface using ChatInterface
demo = gr.ChatInterface(
    fn=generate_response,
    title=SPACE_NAME,
    description=SPACE_DESCRIPTION,
    examples={examples}
)

if __name__ == "__main__":
    demo.launch()
'''

# Available models
MODELS = [
    "google/gemma-3-27b-it",
    "google/gemini-2.0-flash-001",
    "mistralai/mistral-medium",
    "openai/gpt-4o-nano",
    "anthropic/claude-3.5-haiku"
]

def fetch_url_content(url):
    """Fetch and extract text content from a URL"""
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # Remove script and style elements
        for script in soup(["script", "style"]):
            script.decompose()
        
        # Get text content
        text = soup.get_text()
        
        # Clean up whitespace
        lines = (line.strip() for line in text.splitlines())
        chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
        text = ' '.join(chunk for chunk in chunks if chunk)
        
        # Truncate to ~4000 characters
        if len(text) > 4000:
            text = text[:4000] + "..."
        
        return text
    except Exception as e:
        return f"Error fetching {url}: {str(e)}"

def get_grounding_context(urls):
    """Fetch context from grounding URLs"""
    if not urls:
        return ""
    
    context_parts = []
    for i, url in enumerate(urls, 1):
        if url and url.strip():
            content = fetch_url_content(url.strip())
            context_parts.append(f"Context from URL {i} ({url}):\n{content}")
    
    if context_parts:
        return "\n\n" + "\n\n".join(context_parts) + "\n\n"
    return ""

def create_readme(config):
    """Generate README with deployment instructions"""
    return f"""---
title: {config['name']}
emoji: 🤖
colorFrom: blue
colorTo: red
sdk: gradio
sdk_version: 4.32.0
app_file: app.py
pinned: false
---

# {config['name']}

{config['description']}

## Quick Deploy to HuggingFace Spaces

### Step 1: Create the Space
1. Go to https://huggingface.co/spaces
2. Click "Create new Space"
3. Choose a name for your Space
4. Select **Gradio** as the SDK
5. Set visibility (Public/Private)
6. Click "Create Space"

### Step 2: Upload Files
1. In your new Space, click "Files" tab
2. Upload these files from the zip:
   - `app.py`
   - `requirements.txt`
3. Wait for "Building" to complete

### Step 3: Add API Key
1. Go to Settings (gear icon) 
2. Click "Variables and secrets"
3. Click "New secret"
4. Name: `{config['api_key_var']}`
5. Value: Your OpenRouter API key
6. Click "Add"

### Step 4: Get Your API Key
1. Go to https://openrouter.ai/keys
2. Sign up/login if needed
3. Click "Create Key"
4. Copy the key (starts with `sk-or-`)

### Step 5: Test Your Space
- Go back to "App" tab
- Your Space should be running!
- Try the example prompts or ask a question

## Configuration

- **Model**: {config['model']}
- **Temperature**: {config['temperature']}
- **Max Tokens**: {config['max_tokens']}
- **API Key Variable**: {config['api_key_var']}

## Customization

To modify your Space:
1. Edit `app.py` in your Space
2. Update configuration variables at the top
3. Changes deploy automatically

## Troubleshooting

- **"Please set your {config['api_key_var']}"**: Add the secret in Space settings
- **Error 401**: Invalid API key or no credits
- **Error 429**: Rate limit - wait and try again
- **Build failed**: Check requirements.txt formatting

## More Help

- HuggingFace Spaces: https://huggingface.co/docs/hub/spaces
- OpenRouter Docs: https://openrouter.ai/docs
- Gradio Docs: https://gradio.app/docs

---

Generated on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} with Chat U/I Helper
"""

def create_requirements():
    """Generate requirements.txt"""
    return "gradio==4.44.1\nrequests==2.32.3\ncrawl4ai==0.4.245"

def generate_zip(name, description, system_prompt, model, api_key_var, temperature, max_tokens, examples_text, url1="", url2="", url3="", url4=""):
    """Generate deployable zip file"""
    
    # Process examples
    if examples_text and examples_text.strip():
        examples_list = [ex.strip() for ex in examples_text.split('\n') if ex.strip()]
        examples_json = json.dumps(examples_list)
    else:
        examples_json = json.dumps([
            "Hello! How can you help me?",
            "Tell me something interesting",
            "What can you do?"
        ])
    
    # Process grounding URLs
    grounding_urls = []
    for url in [url1, url2, url3, url4]:
        if url and url.strip():
            grounding_urls.append(url.strip())
    
    # Create config
    config = {
        'name': name,
        'description': description,
        'system_prompt': system_prompt,
        'model': model,
        'api_key_var': api_key_var,
        'temperature': temperature,
        'max_tokens': int(max_tokens),
        'examples': examples_json,
        'grounding_urls': json.dumps(grounding_urls)
    }
    
    # Generate files
    app_content = SPACE_TEMPLATE.format(**config)
    readme_content = create_readme(config)
    requirements_content = create_requirements()
    
    # Create zip file with clean naming
    filename = f"{name.lower().replace(' ', '_').replace('-', '_')}.zip"
    
    # Create zip in memory and save to disk
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
        zip_file.writestr('app.py', app_content)
        zip_file.writestr('requirements.txt', requirements_content)
        zip_file.writestr('README.md', readme_content)
        zip_file.writestr('config.json', json.dumps(config, indent=2))
    
    # Write zip to file
    zip_buffer.seek(0)
    with open(filename, 'wb') as f:
        f.write(zip_buffer.getvalue())
    
    return filename

# Define callback functions outside the interface
def on_generate(name, description, system_prompt, model, api_key_var, temperature, max_tokens, examples_text, url1, url2, url3, url4):
    if not name or not name.strip():
        return gr.update(value="Error: Please provide a Space Title", visible=True), gr.update(visible=False)
    
    if not system_prompt or not system_prompt.strip():
        return gr.update(value="Error: Please provide a System Prompt", visible=True), gr.update(visible=False)
    
    try:
        filename = generate_zip(name, description, system_prompt, model, api_key_var, temperature, max_tokens, examples_text, url1, url2, url3, url4)
        
        success_msg = f"""**Deployment package ready!**

**File**: `{filename}`

**What's included:**
- `app.py` - Ready-to-deploy chat interface
- `requirements.txt` - Dependencies  
- `README.md` - Step-by-step deployment guide
- `config.json` - Configuration backup

**Next steps:**
1. Download the zip file below
2. Follow the README instructions to deploy on HuggingFace Spaces
3. Set your `{api_key_var}` secret in Space settings

**Your Space will be live in minutes!**"""
        
        return gr.update(value=success_msg, visible=True), gr.update(value=filename, visible=True)
        
    except Exception as e:
        return gr.update(value=f"Error: {str(e)}", visible=True), gr.update(visible=False)

def respond(message, chat_history, url1="", url2="", url3="", url4=""):
    # Make actual API request to OpenRouter
    import os
    import requests
    
    # Get API key from environment
    api_key = os.environ.get("OPENROUTER_API_KEY")
    
    if not api_key:
        response = "Please set your OPENROUTER_API_KEY in the Space settings to use the chat support."
        chat_history.append([message, response])
        return "", chat_history
    
    # Get grounding context from URLs using Crawl4AI
    grounding_urls = [url1, url2, url3, url4]
    grounding_context = get_grounding_context_crawl4ai(grounding_urls)
    
    # Build enhanced system prompt with grounding context
    base_system_prompt = """You are an expert assistant specializing in Gradio configurations for HuggingFace Spaces. You have deep knowledge of:
- Gradio interface components and layouts
- HuggingFace Spaces configuration (YAML frontmatter, secrets, environment variables)
- Deployment best practices for Gradio apps on HuggingFace
- Space settings, SDK versions, and hardware requirements
- Troubleshooting common Gradio and HuggingFace Spaces issues
- Integration with various APIs and models through Gradio interfaces

Provide specific, technical guidance focused on Gradio implementation details and HuggingFace Spaces deployment. Include code examples when relevant. Keep responses concise and actionable."""
    
    enhanced_system_prompt = base_system_prompt + grounding_context
    
    # Build conversation history for API
    messages = [{
        "role": "system", 
        "content": enhanced_system_prompt
    }]
    
    # Add conversation history - Gradio 4.x uses list/tuple format
    for chat in chat_history:
        if isinstance(chat, (list, tuple)) and len(chat) >= 2:
            user_msg, assistant_msg = chat[0], chat[1]
            if user_msg:
                messages.append({"role": "user", "content": user_msg})
            if assistant_msg:
                messages.append({"role": "assistant", "content": assistant_msg})
    
    # Add current message
    messages.append({"role": "user", "content": message})
    
    try:
        # Make API request to OpenRouter
        response = requests.post(
            url="https://openrouter.ai/api/v1/chat/completions",
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json"
            },
            json={
                "model": "google/gemma-3-27b-it",
                "messages": messages,
                "temperature": 0.7,
                "max_tokens": 500
            }
        )
        
        if response.status_code == 200:
            assistant_response = response.json()['choices'][0]['message']['content']
        else:
            assistant_response = f"Error: {response.status_code} - {response.text}"
            
    except Exception as e:
        assistant_response = f"Error: {str(e)}"
    
    chat_history.append([message, assistant_response])
    return "", chat_history

def clear_chat():
    return "", []

# Create Gradio interface with proper tab structure
with gr.Blocks(title="Chat U/I Helper") as demo:
    with gr.Tabs():
        with gr.Tab("Spaces Configuration"):
            gr.Markdown("# Spaces Configuration")
            gr.Markdown("Convert custom assistants from HuggingChat into chat interfaces with HuggingFace Spaces. Configure and download everything needed to deploy a simple HF space using Gradio.")
    
            with gr.Column():
                name = gr.Textbox(
                    label="Space Title",
                    placeholder="My Course Helper",
                    value="My Custom Space"
                )
                
                description = gr.Textbox(
                    label="Space Description", 
                    placeholder="A customizable AI chat interface for...",
                    lines=2,
                    value="An AI research assistant tailored for academic inquiry and scholarly dialogue"
                )
                
                model = gr.Dropdown(
                    label="Model",
                    choices=MODELS,
                    value=MODELS[0],
                    info="Choose based on your needs and budget"
                )
                
                api_key_var = gr.Textbox(
                    label="API Key Variable Name",
                    value="OPENROUTER_API_KEY",
                    info="Name for the secret in HuggingFace Space settings"
                )
                
                system_prompt = gr.Textbox(
                    label="System Prompt",
                    placeholder="You are a research assistant...",
                    lines=4,
                    value="You are a knowledgeable academic research assistant. Provide thoughtful, evidence-based guidance for scholarly work, literature reviews, and academic writing. Support students and researchers with clear explanations and critical thinking."
                )
                
                examples_text = gr.Textbox(
                    label="Example Prompts (one per line)",
                    placeholder="Hello! How can you help me?\nWhat's the weather like?\nExplain quantum computing",
                    lines=3,
                    info="These will appear as clickable examples in the chat interface"
                )
                
                gr.Markdown("### URL Grounding (Optional)")
                gr.Markdown("Add up to 4 URLs to provide context. Content will be fetched and added to the system prompt.")
                
                url1 = gr.Textbox(
                    label="URL 1",
                    placeholder="https://example.com/page1",
                    info="First URL for context grounding"
                )
                
                url2 = gr.Textbox(
                    label="URL 2", 
                    placeholder="https://example.com/page2",
                    info="Second URL for context grounding"
                )
                
                url3 = gr.Textbox(
                    label="URL 3",
                    placeholder="https://example.com/page3", 
                    info="Third URL for context grounding"
                )
                
                url4 = gr.Textbox(
                    label="URL 4",
                    placeholder="https://example.com/page4",
                    info="Fourth URL for context grounding"
                )
                
                with gr.Row():
                    temperature = gr.Slider(
                        label="Temperature",
                        minimum=0,
                        maximum=2,
                        value=0.7,
                        step=0.1,
                        info="Higher = more creative, Lower = more focused"
                    )
                    
                    max_tokens = gr.Slider(
                        label="Max Response Tokens",
                        minimum=50,
                        maximum=4096,
                        value=1024,
                        step=50
                    )
                
                generate_btn = gr.Button("Generate Deployment Package", variant="primary")
                
                status = gr.Markdown(visible=False)
                download_file = gr.File(label="Download your zip package", visible=False)
            
            # Connect the generate button
            generate_btn.click(
                on_generate,
                inputs=[name, description, system_prompt, model, api_key_var, temperature, max_tokens, examples_text, url1, url2, url3, url4],
                outputs=[status, download_file]
            )
        
        with gr.Tab("Chat Support"):
            gr.Markdown("# Chat Support")
            gr.Markdown("Get personalized guidance on configuring chat assistants as HuggingFace Spaces for educational & research purposes.")
            
            # Meta chat interface
            with gr.Column():
                chatbot = gr.Chatbot(
                    value=[],
                    label="Chat Support Assistant",
                    height=400
                )
                msg = gr.Textbox(
                    label="Ask about configuring chat UIs for courses, research, or custom HuggingFace Spaces",
                    placeholder="How can I configure a chat UI for my senior seminar?",
                    lines=2
                )
                
                with gr.Accordion("URL Grounding (Optional)", open=False):
                    gr.Markdown("Add URLs to provide additional context for more informed responses")
                    chat_url1 = gr.Textbox(
                        label="URL 1",
                        value="https://huggingface.co/docs/hub/en/spaces-overview",
                        info="HuggingFace Spaces Overview"
                    )
                    chat_url2 = gr.Textbox(
                        label="URL 2", 
                        value="https://huggingface.co/docs/hub/en/spaces-config-reference",
                        info="Spaces Configuration Reference"
                    )
                    chat_url3 = gr.Textbox(
                        label="URL 3",
                        value="https://huggingface.co/docs/hub/en/spaces-settings",
                        info="Spaces Settings Documentation"
                    )
                    chat_url4 = gr.Textbox(
                        label="URL 4",
                        value="https://huggingface.co/docs/hub/en/spaces-sdks-gradio",
                        info="Gradio SDK for Spaces"
                    )
                with gr.Row():
                    submit = gr.Button("Send", variant="primary")
                    clear = gr.Button("Clear")
                
                gr.Examples(
                    examples=[
                        "How do I set up a course assistant?",
                        "Which model should I use?",
                        "What's a good system prompt?",
                        "Why Gradio? What is it?",
                        "How do I customize the chat interface?",
                        "Can you help me troubleshoot?",
                    ],
                    inputs=msg
                )
            
            # Connect the chat functionality
            submit.click(respond, [msg, chatbot, chat_url1, chat_url2, chat_url3, chat_url4], [msg, chatbot])
            msg.submit(respond, [msg, chatbot, chat_url1, chat_url2, chat_url3, chat_url4], [msg, chatbot])
            clear.click(clear_chat, outputs=[msg, chatbot])

if __name__ == "__main__":
    demo.launch(share=True)