File size: 18,113 Bytes
7bdbd56
 
 
 
 
 
 
 
 
 
 
 
483d334
 
7bdbd56
75a69fd
7bdbd56
5b97eba
7bdbd56
483d334
 
 
 
7bdbd56
 
 
 
483d334
7bdbd56
 
777f0c6
7bdbd56
777f0c6
00daf25
777f0c6
00daf25
 
777f0c6
 
 
 
 
 
 
 
 
 
 
 
00daf25
777f0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bdbd56
777f0c6
 
 
 
 
 
 
 
00daf25
777f0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00daf25
777f0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4573512
8e1690f
7bdbd56
483d334
7bdbd56
483d334
4573512
 
 
 
777f0c6
 
7bdbd56
 
777f0c6
7bdbd56
5b97eba
777f0c6
 
 
7bdbd56
5b97eba
777f0c6
 
 
 
 
 
 
7bdbd56
 
777f0c6
7bdbd56
777f0c6
 
 
 
 
 
 
 
 
 
7bdbd56
 
777f0c6
7bdbd56
777f0c6
 
 
 
7bdbd56
777f0c6
 
 
 
483d334
777f0c6
 
 
483d334
7bdbd56
777f0c6
 
 
 
7bdbd56
 
777f0c6
7bdbd56
777f0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bdbd56
 
 
 
 
 
db9c40d
 
483d334
db9c40d
 
 
 
 
 
 
 
 
 
 
 
483d334
db9c40d
 
 
 
 
 
 
 
 
 
 
 
 
483d334
db9c40d
 
 
 
 
 
 
 
 
 
 
 
 
483d334
db9c40d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483d334
7bdbd56
 
483d334
7bdbd56
483d334
7bdbd56
 
 
 
483d334
7bdbd56
 
 
 
483d334
7bdbd56
 
 
 
 
483d334
7bdbd56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Support documentation module with accordion-style help sections
"""

import gradio as gr
from datetime import datetime


def create_support_docs():
    """Create the support documentation interface with accordion menus"""
    
    with gr.Column():
        gr.Markdown("# ChatUI Helper Documentation")
        gr.Markdown("Welcome to ChatUI Helper! This tool helps you create customizable AI chat interfaces for deployment on HuggingFace Spaces.")
        
        with gr.Accordion("πŸ“– Quick Start Guide", open=True):
            gr.Markdown("""
            ## Overview

            1. **Configure** your assistant using templates or custom settings
            2. **Preview** your configuration to test it works
            3. **Generate** your deployment package
            4. **Deploy** to HuggingFace Spaces

            **Requirements:**
            - HuggingFace account (free)
            - OpenRouter API key
            - Basic understanding of AI assistants
            """)
        
        with gr.Accordion("πŸ“ Step 1: Configure & Preview Your Space", open=False):
            gr.Markdown("""
            ### Configuration Tab Overview
            
            Configure your assistant through various sections in the Configuration tab, then test it in the Preview tab before generating your deployment package.
            """)
            
            with gr.Accordion("Step 1a: Templates & Identity", open=False):
                gr.Markdown("""
                **Quick Start Templates**
                - Choose from pre-configured academic templates (Socratic Research Chat, STEM Adventure Games, etc.)
                - Or select "None (Custom)" for a blank slate
                
                **Space Identity**
                - **Assistant Name**: Give your assistant a memorable name
                - **Tagline**: Brief description (max 60 characters) for HuggingFace YAML frontmatter
                - **Description**: Full markdown description for the README
                - **Theme**: Select from Gradio themes (Default, Soft, Glass, Monochrome, Base)
                """)
            
            with gr.Accordion("Step 1b: System Configuration", open=False):
                gr.Markdown("""
                **System Prompt**
                - Define your assistant's role, context, and behavior
                - Set guardrails and creative constraints
                - Specify audience and terms of engagement
                
                **Model Selection**
                - Choose from available models (Gemini, Claude, GPT, Mistral, etc.)
                - Or enter a custom model ID
                
                **Language Support**
                - Configure language through system prompt instructions
                - Assistant can be instructed to respond exclusively in any language
                - See "Language Learning Partner" template for Italian example
                
                **Sampling Parameters**
                - **Temperature** (0-2): Controls response variability
                - **Max Tokens** (50-4096): Limits response length
                """)
            
            with gr.Accordion("Step 1c: Example Prompts", open=False):
                gr.Markdown("""
                **Example Prompts**
                - Add 3-5 starter prompts that showcase your assistant's capabilities
                - These appear as quick-start buttons for users
                - Help users understand how to interact with your assistant
                - Use the βž•/βž– buttons to add or remove examples
                """)
            
            with gr.Accordion("Step 1d: URL Grounding", open=False):
                gr.Markdown("""
                **Grounding URLs**
                - Add up to 10 reference URLs to provide context
                - **Primary Sources (URLs 1-2)**: Always loaded, up to 8000 characters each
                - **Secondary Sources (URLs 3+)**: Supplementary context, up to 2500 characters each
                - URLs are fetched and included in the system prompt
                - Assistant will cite specific URLs when using grounded information
                - Use the βž•/βž– buttons to manage URLs
                """)
            
            with gr.Accordion("Step 1e: API Configuration", open=False):
                gr.Markdown("""
                **Required Secrets**
                - **API_KEY**: Your OpenRouter API key (must start with `sk-or-`)
                  - Get from: https://openrouter.ai/keys
                  - Configure in HuggingFace Space settings
                
                **Optional Secrets**
                - **HF_TOKEN** (Recommended): Enables configuration editor in deployed Space
                  - Get from: https://huggingface.co/settings/tokens
                  - Select "write" permissions when creating
                  - Allows updating configuration without redeployment
                
                - **ACCESS_CODE**: Password-protect your Space
                  - Set any password value
                  - Users will need this code to access
                  - Leave unset for public access
                """)
            
            with gr.Accordion("Step 1f: Upload Configuration", open=False):
                gr.Markdown("""
                **Upload Existing Configuration**
                - Have a previous `config.json` file?
                - Use the "Upload Configuration" accordion
                - Drag and drop or click to upload
                - All settings will be restored automatically
                """)
            
            with gr.Accordion("Step 1g: Preview Your Assistant", open=False):
                gr.Markdown("""
                **Testing in Preview Tab**
                - Click "πŸ’¬ Preview Configuration" to prepare your assistant
                - Switch to the Preview tab
                - Test with real queries and example prompts
                - Upload files if file upload is enabled
                - Export conversation history as markdown
                
                **Preview Features**
                - Real-time API responses (requires API key in environment)
                - Grounding context from configured URLs
                - Language-specific responses
                - File upload handling
                - Conversation export
                """)
        
        with gr.Accordion("πŸ—³οΈ Step 2: Generate & Deploy", open=False):
            gr.Markdown("""
            ### Deployment Package & HuggingFace Space Setup
            
            **Package Contents:**
            - `app.py`: Complete Gradio application
            - `requirements.txt`: Python dependencies
            - `config.json`: Configuration backup
            - `README.md`: Deployment instructions
            
            **Deployment Overview:** Generate Package β†’ Create Space β†’ Upload Files β†’ Configure Secrets β†’ Monitor Build
            """)
            
            with gr.Accordion("Step 2a: Generate & Create Space", open=False):
                gr.Markdown("""
                **Generate Deployment Package**
                1. Click "πŸ—³οΈ Generate Deployment Package" in Configuration tab
                2. Download the generated ZIP file
                3. Extract files: `app.py`, `config.json`, `requirements.txt`, `README.md`
                
                **Create New Space**
                1. Go to [huggingface.co/spaces](https://huggingface.co/spaces)
                2. Click "Create new Space"
                3. Name your Space
                4. Select **Gradio** SDK
                5. Choose **Blank** template
                6. Select hardware (CPU Basic is free)
                7. Click "Create Space"
                """)
            
            with gr.Accordion("Step 2b: Upload Files", open=False):
                gr.Markdown("""
                **Upload Project Files**
                1. Navigate to the **Files** tab in your new Space
                2. Click "Add file" β†’ "Upload files"
                3. Select all 4 files from your extracted package:
                   - `README.md`
                   - `app.py`
                   - `config.json`
                   - `requirements.txt`
                4. Commit directly to main branch
                5. Your Space will automatically start building
                """)
            
            with gr.Accordion("Step 2c: Configure Secrets", open=False):
                gr.Markdown("""
                **Navigate to Settings**
                1. Click the **Settings** tab in your Space
                2. Find **Variables and secrets** section
                3. Click **New secret**
                
                **Add Required Secret**
                - **Name**: `API_KEY` (or your configured variable name)
                - **Value**: Your OpenRouter API key
                - Must start with `sk-or-`
                
                **Add Optional Secrets (if desired)**
                - **HF_TOKEN**: Your HuggingFace token with write permissions
                  - Enables the configuration editor in your Space
                  - Get from: https://huggingface.co/settings/tokens
                
                - **ACCESS_CODE**: Any password value
                  - Restricts access to authorized users
                  - Do NOT set an empty value
                  - Either set a code or don't create the secret
                """)
            
            with gr.Accordion("Step 2d: Verify & Iterate", open=False):
                gr.Markdown("""
                **Monitor Build Process**
                1. Return to the **App** tab
                2. Watch for "Building..." status
                3. Check build logs for any errors
                4. Wait 1-3 minutes for completion
                5. Space will show "Running" when ready
                
                **Test Your Deployment**
                1. Try the example prompts
                2. Test different types of queries
                3. Verify grounding URLs are working
                4. Check language responses (if configured)
                
                **Iterate Configuration (with HF_TOKEN)**
                1. Go to βš™οΈ Configuration tab in your Space
                2. Enter your HF_TOKEN to authenticate
                3. Modify settings as needed
                4. Click "Save Configuration"
                5. Space will automatically rebuild
                6. Test new configuration
                """)
      
        with gr.Accordion("πŸ”§ Troubleshooting", open=False):
            gr.Markdown("""
            ### Common Issues and Solutions
            
            Find solutions to common problems organized by category.
            """)
            
            with gr.Accordion("Build Errors", open=False):
                gr.Markdown("""
                **Requirements Compatibility**
                - Ensure Gradio version β‰₯ 5.39.0 in requirements.txt
                - Check all dependencies are spelled correctly
                - Verify version numbers are compatible
                
                **Common Build Failures**
                - Missing dependencies: Add to requirements.txt
                - Import errors: Check module names and casing
                - Syntax errors: Review app.py for Python syntax issues
                """)
            
            with gr.Accordion("API Errors", open=False):
                gr.Markdown("""
                **API Key Issues**
                - Verify API_KEY is set in HuggingFace Secrets
                - Ensure key starts with 'sk-or-' for OpenRouter
                - Check for extra spaces or quotes in the secret value
                
                **API Response Errors**
                - 401 Unauthorized: Invalid API key
                - 402 Payment Required: No API credits remaining
                - 429 Rate Limited: Too many requests, wait and retry
                - 500 Server Error: OpenRouter service issue
                """)
            
            with gr.Accordion("Access Control Issues", open=False):
                gr.Markdown("""
                **ACCESS_CODE Problems**
                - Code must match exactly (case-sensitive)
                - Don't include quotes around the password
                - Check for trailing spaces in the secret
                - To disable: Delete the ACCESS_CODE secret entirely
                
                **Authentication Flow**
                - Users enter code on first visit
                - Code is stored in browser session
                - Clear cookies to re-prompt for code
                """)
            
            with gr.Accordion("Preview Tab Not Working", open=False):
                gr.Markdown("""
                **Local Testing**
                - Set API_KEY in your local .env file
                - Format: `API_KEY=sk-or-your-key-here`
                - Restart the app after adding environment variable
                
                **Preview Issues**
                - Click "πŸ’¬ Preview Configuration" first
                - Check browser console (F12) for JavaScript errors
                - Ensure all required fields are filled
                - Try refreshing the page
                """)
            
            with gr.Accordion("Configuration Status Shows ❌", open=False):
                gr.Markdown("""
                **Status Check Failures**
                - Red X means configuration issue detected
                - Usually indicates missing or invalid API key
                
                **Resolution Steps**
                1. Verify secret name matches your configuration
                2. Default is API_KEY, check if you changed it
                3. Regenerate API key at openrouter.ai/keys
                4. Update secret in HuggingFace Space settings
                5. Wait 30 seconds and refresh
                """)
            
            with gr.Accordion("Space Not Loading", open=False):
                gr.Markdown("""
                **Infinite Loading**
                - Check Space logs for error messages
                - Common cause: Missing required secrets
                - Verify all files uploaded correctly
                
                **Gradio App Errors**
                - Component version mismatches
                - Update to latest Gradio version
                - Check for deprecated components
                - Review migration guides for Gradio 5.x
                """)
        
        with gr.Accordion("πŸ“š Additional Resources", open=False):
            gr.Markdown("""
            ### Documentation Links
            
            **HuggingFace**
            - [Spaces Overview](https://huggingface.co/docs/hub/spaces-overview)
            - [Gradio on Spaces](https://huggingface.co/docs/hub/spaces-gradio)
            - [Environment Variables](https://huggingface.co/docs/hub/spaces-overview#managing-secrets)
            
            **OpenRouter**
            - [API Keys](https://openrouter.ai/keys)
            - [Model Comparison](https://openrouter.ai/models)
            - [Pricing](https://openrouter.ai/docs#models)
            
            **Gradio**
            - [Chat Interface](https://gradio.app/docs/chatinterface)
            - [Components](https://gradio.app/docs/)
            - [Sharing Apps](https://gradio.app/sharing-your-app/)
            
            **Community Support**
            - [HuggingFace Forums](https://discuss.huggingface.co/)
            - [Gradio Discord](https://discord.gg/feTf9x3ZSB)
            """)

def export_conversation_to_markdown(conversation_history, config_metadata=None):
    """Export conversation history to markdown format with configuration metadata"""
    if not conversation_history:
        return "No conversation to export."
    
    markdown_content = f"""# Conversation Export
Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

"""
    
    # Add configuration metadata if provided
    if config_metadata:
        markdown_content += """## Configuration Information

"""
        
        # Add basic configuration details
        if config_metadata.get('model'):
            markdown_content += f"**Model:** {config_metadata['model']}\n"
        if config_metadata.get('temperature'):
            markdown_content += f"**Temperature:** {config_metadata['temperature']}\n"
        if config_metadata.get('max_tokens'):
            markdown_content += f"**Max Tokens:** {config_metadata['max_tokens']}\n"
        
        # Add URL grounding information
        grounding_urls = []
        for i in range(1, 5):
            url = config_metadata.get(f'url{i}')
            if url and url.strip():
                grounding_urls.append(url.strip())
        
        if grounding_urls:
            markdown_content += f"\n**URL Grounding ({len(grounding_urls)} URLs):**\n"
            for i, url in enumerate(grounding_urls, 1):
                markdown_content += f"- URL {i}: {url}\n"
        
        # Add feature flags
        if config_metadata.get('enable_dynamic_urls'):
            markdown_content += f"\n**Dynamic URL Fetching:** Enabled\n"
        
        # Add system prompt
        if config_metadata.get('system_prompt'):
            system_prompt = config_metadata['system_prompt']
            markdown_content += f"\n**System Prompt:**\n```\n{system_prompt}\n```\n"
        
        markdown_content += "\n---\n\n"
    else:
        markdown_content += "---\n\n"
    
    for i, message in enumerate(conversation_history):
        if isinstance(message, dict):
            role = message.get('role', 'unknown')
            content = message.get('content', '')
            
            if role == 'user':
                markdown_content += f"## User Message {(i//2) + 1}\n\n{content}\n\n"
            elif role == 'assistant':
                markdown_content += f"## Assistant Response {(i//2) + 1}\n\n{content}\n\n---\n\n"
    
    return markdown_content