File size: 16,215 Bytes
7bdbd56
 
 
 
 
 
 
 
 
 
 
 
483d334
 
7bdbd56
75a69fd
7bdbd56
5b97eba
7bdbd56
483d334
 
 
 
7bdbd56
 
 
 
483d334
7bdbd56
1a21774
 
 
 
7bdbd56
483d334
7bdbd56
58e0c9b
8d2d3d0
 
 
00daf25
 
 
 
58e0c9b
00daf25
58e0c9b
00daf25
 
8d2d3d0
00daf25
8d2d3d0
 
00daf25
 
 
 
 
58e0c9b
00daf25
 
 
 
 
 
58e0c9b
00daf25
 
 
 
8d2d3d0
00daf25
8d2d3d0
 
00daf25
 
 
 
 
 
58e0c9b
00daf25
 
8d2d3d0
00daf25
8d2d3d0
 
 
 
7bdbd56
8d2d3d0
 
 
 
9ba40e3
 
7bdbd56
00daf25
 
 
 
 
 
 
 
7bdbd56
483d334
7bdbd56
3e646c4
4573512
00daf25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4573512
ed6857b
7bdbd56
483d334
7bdbd56
483d334
4573512
 
 
 
 
ed6857b
7bdbd56
 
ed6857b
7bdbd56
5b97eba
483d334
 
 
7bdbd56
5b97eba
7bdbd56
 
4573512
7bdbd56
 
 
 
 
 
00daf25
7bdbd56
 
00daf25
7bdbd56
 
 
00daf25
7bdbd56
 
00daf25
7bdbd56
 
5b97eba
7bdbd56
 
 
 
75a69fd
7bdbd56
 
 
 
 
 
00daf25
7bdbd56
 
00daf25
7bdbd56
 
 
00daf25
7bdbd56
 
00daf25
7bdbd56
 
5b97eba
7bdbd56
5b97eba
75a69fd
 
7bdbd56
 
75a69fd
483d334
5b97eba
483d334
 
5b97eba
483d334
5b97eba
75a69fd
 
5b97eba
 
483d334
7bdbd56
 
 
 
75a69fd
 
 
 
 
00daf25
75a69fd
 
00daf25
75a69fd
 
 
 
00daf25
75a69fd
 
00daf25
75a69fd
7bdbd56
dff4786
7bdbd56
dff4786
7bdbd56
 
 
 
dff4786
 
 
 
 
 
7bdbd56
9ba40e3
 
 
 
7bdbd56
 
 
 
 
483d334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bdbd56
483d334
7bdbd56
 
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
"""
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
            """)

        gr.Markdown(""" 
        ---
        """)
        
        with gr.Accordion("📝 Step 1: Configure Your Space", open=False):
            gr.Markdown("""
            ### Configuration Steps
    
            #### 1a. Templates & Identity
            Included are several pre-populated templates to get you started with playful (but applied) configurations. Or start with the "None (Custom)" option for a blank slate. Personalize the chat u/i and giving it a name, header (max 60 char) and a markdown description for the `README.md` file, then select from Gradio themes like Default, Soft, Glass, Monochrome, or Base.
            """)
            
            with gr.Row():
                gr.Image(
                    value="img/quick-start-template.png",
                    label="Templates & Identity Configuration",
                    interactive=True,
                    width=600
                )
    
            gr.Markdown("""
            #### 1b. Model Configuration
            Craft a system prompt that steers your model's behavior using a well-defined role, context and audience, code of conduct, and/or terms of engagement——think of guardrails as creative constraints. Afterward select a model ID from the menu of options, then experiment with sampling parameters, adjusting temperature (values from 0 to 2) to control response variability and/or setting a token response limit (between 50-4096) to cap output.
            """)
            
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Image(
                        value="img/model-selection.jpg",
                        label="System Prompt Configuration",
                        interactive=False,
                        width=400
                    )
                with gr.Column(scale=1):
                    gr.Image(
                        value="img/system-configuration.jpeg",
                        label="Model Selection",
                        interactive=False,
                        width=400
                    )
    
            gr.Markdown("""
            #### 1c. Example Prompts
            Add 3 to 5 starter prompts that showcase the purpose and design of your space. These examples appear as quick-start buttons for users to try and meant to help them get started.
            """)
            
            with gr.Row():
                gr.Image(
                    value="img/example-prompts.png",
                    label="Example Prompts Configuration",
                    interactive=True,
                    width=600
                )
    
            gr.Markdown("""
            #### 1d. URL Grounding
            Add up to 10 reference URLs that ground the model in the context of different webpages. The first 2 URLs function as primary sources that will always be loaded with each query, while other URLs serve as supplementary context. Note that only 4096 total characters from URLs are appended to the system prompt.
    
            #### 1e. API Key and HuggingFace Token
            
            - **Required**: Provide the required OpenAI-standard API key (`sk-`) and name for its variable (`API_KEY`) to call the model through a provider like OpenRouter.
            - **Recommended**: Add a HuggingFace token (`HF_TOKEN`) to make your space customizable over time through a configuration editor. 
            - **Optional**: Set an optional password (`ACCESS_CODE`) to limit who can access your space. Any value goes.
    
            #### 1f. Upload `config.json`
            Done this before? Upload your `config.json` files to redeploy your Space with new settings and recent versions.
            """)
            
            with gr.Row():
                gr.Image(
                    value="img/upload-config.png",
                    label="Upload Configuration",
                    interactive=False,
                    width=600
                )

        with gr.Accordion("💬 Step 2: Preview Your Assistant", open=False):
            gr.Markdown("""
            In the Preview tab test your assistant with real-time requests, try example prompts, upload files if enabled, and export your conversation history. Tinker with a variety of queries, models, and configurations to find the most appropriate fit for you and your people.
            """)
            
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Image(
                        value="img/preview-config.png",
                        label="Preview Configuration",
                        interactive=False,
                        width=400
                    )
                with gr.Column(scale=1):
                    gr.Image(
                        value="img/preview-config-screen.png",
                        label="Preview Interface",
                        interactive=False,
                        width=400
                    )
        
        with gr.Accordion("🗳️ Step 3: Generate & Deploy", open=True):
            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 and Create Space → Upload Files and Configure Secrets → Monitor Build and Verify
            """)
            
            with gr.Accordion("Step 3a: Generate & Create Space", open=False):
                gr.Markdown("""
                **Generate Deployment Package**
                - Click "🗳️ Generate Deployment Package" in Configuration tab
                - Download the generated ZIP file
                - Extract files: `app.py`, `config.json`, `requirements.txt`, `README.md`
                
                **Create New Space**
                - Go to [huggingface.co/spaces](https://huggingface.co/spaces)
                - Click "New Space"
                - Choose Gradio SDK (Blank)
                - Select hardware (CPU Basic is free)
                """)
                
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Image(
                            value="img/new-space-gradio-blank.png",
                            label="Space Creation Form",
                            interactive=False,
                            width=400
                        )
                    with gr.Column(scale=1):
                        gr.Image(
                            value="img/space-hardware.png",
                            label="Hardware Selection",
                            interactive=False,
                            width=400
                        )
            
            with gr.Accordion("Step 3b: Upload Files", open=False):
                gr.Markdown("""
                **2.1 Upload Project Files**
                - Navigate to Files tab
                - Click "Upload files" or drag and drop
                - Upload: `README.md`, `app.py`, `config.json`, `requirements.txt`
                - Commit directly to main branch
                """)
                
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Image(
                            value="img/upload-files.png",
                            label="File Upload",
                            interactive=False,
                            width=400
                        )
                    with gr.Column(scale=1):
                        gr.Image(
                            value="img/highlight-files.png",
                            label="Files After Upload",
                            interactive=False,
                            width=400
                        )
            
            with gr.Accordion("Step 3c: Configure API Secrets", open=False):
                gr.Markdown("""
                **Configure HuggingFace Spaces Secrets**
                - Go to Settings → Variables and secrets
                - Click "New secret"
                
                **Required Secret:**
                - `API_KEY` (or your configured variable name)
                  - Must start with: `sk-or-`
                  - Add in: *Settings* → *Variables and secrets*
                
                **Optional Secrets:**
                - `HF_TOKEN` (Recommended): Enables persistent updates & customization 
                  - Get from: https://huggingface.co/settings/tokens
                  - Enable *write* permissions

                - `ACCESS_CODE`: Password protects your Space
                  - To enable add secret `ACCESS_CODE` with a custom value
                  - To disable delete `ACCESS_CODE` secret entirely from *Variables and Secrets*
                  - Share with authorized users only
                
                **Access Control Notes:**
                - Do NOT set an empty value - either set a code or don't create the secret at all
                """)
                
                with gr.Row():

                    with gr.Column(scale=1):
                        gr.Image(
                            value="img/go-to-settings.png",
                            label="Navigating to Settings",
                            interactive=False,
                            width=400
                        )
                        
                    with gr.Column(scale=1):
                        gr.Image(
                            value="img/variables-and-secrets.png",
                            label="API Key Secret Configuration",
                            interactive=False,
                            width=400
                        )
            
            with gr.Accordion("Step 3d: Verify Build & Iterate", open=False):
                gr.Markdown("""
                **Verify Build**
                - Space will show "Building..." status
                - Monitor build logs for errors
                - Wait 1-3 minutes for completion
                - Test chat interface with example prompts
                            
                **Iterate Configuration**
                - Use the configuration editor to make changes
                - Click "Save Configuration" to update
                - Wait for the space to rebuild
                - Test again with new settings
                """)
        
        gr.Markdown(""" 
        ---
        """)
      
        with gr.Accordion("🔧 Troubleshooting", open=False):
            gr.Markdown("""
            ### Common Issues and Solutions
            
            **Build Errors**
            - Check requirements.txt compatibility
            - Ensure Gradio version ≥ 5.39.0
            - Verify all dependencies are available
            
            **API Errors**
            - Verify API_KEY is set correctly
            - Check API key starts with 'sk-or-'
            - Ensure you have API credits
            
            **Access Issues**
            - ACCESS_CODE must match exactly
            - Check for extra spaces in password
            - Verify secret is properly saved
            
            **Preview Not Working**
            - Set API_KEY in local environment
            - Check browser console for errors
            - Ensure configuration is saved
            
            **Configuration Status Shows Red X:**
            - Verify API key secret name matches configuration
            - Check OpenRouter account has credits
            - Regenerate API key if needed
            """)
        
        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