File size: 16,081 Bytes
1770bc8
 
 
 
 
28a389b
1770bc8
0a378f4
1770bc8
 
 
 
 
8f2083f
1770bc8
 
 
 
8f2083f
1770bc8
8f2083f
 
 
 
 
 
1770bc8
 
8f2083f
 
 
1770bc8
 
8f2083f
1770bc8
8f2083f
1770bc8
8f2083f
1770bc8
8f2083f
 
 
 
1770bc8
8f2083f
1770bc8
8f2083f
 
 
 
675fc70
8f2083f
1770bc8
8f2083f
 
 
 
f51b1f2
8f2083f
f51b1f2
8f2083f
f51b1f2
8f2083f
f51b1f2
 
8f2083f
f51b1f2
8f2083f
1770bc8
 
8f2083f
f51b1f2
8f2083f
f51b1f2
 
8f2083f
 
 
 
1770bc8
 
dc5c13f
 
8f2083f
dc5c13f
8f2083f
 
 
 
 
 
dc5c13f
8f2083f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5c13f
 
1770bc8
 
8f2083f
1770bc8
8f2083f
1770bc8
 
 
8f2083f
 
 
1770bc8
 
 
 
8f2083f
 
 
1770bc8
 
8f2083f
1770bc8
8f2083f
 
 
1770bc8
 
 
dc5c13f
1770bc8
8f2083f
dc5c13f
8f2083f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5c13f
8f2083f
 
 
 
 
 
 
 
 
1770bc8
 
 
 
 
 
8f2083f
 
 
 
 
 
 
 
 
 
 
1770bc8
8f2083f
 
 
 
1770bc8
 
 
 
8f2083f
675fc70
8f2083f
f51b1f2
 
8f2083f
 
 
 
 
 
 
 
 
 
 
 
 
0a378f4
f51b1f2
0a378f4
 
 
 
 
 
 
 
 
 
 
 
 
8f2083f
 
 
 
 
 
 
 
 
 
0a378f4
 
8f2083f
 
 
 
1770bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f2083f
1770bc8
 
 
 
8f2083f
 
 
 
1770bc8
 
8f2083f
 
1770bc8
8f2083f
1770bc8
 
8f2083f
 
 
1770bc8
 
 
8f2083f
 
 
 
1770bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675fc70
 
1770bc8
 
 
 
 
 
675fc70
 
 
 
 
1770bc8
 
675fc70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1770bc8
 
 
 
 
 
 
 
 
 
 
 
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
"""
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("# Support Documentation")
        gr.Markdown("Step-by-step guidance for creating and deploying chat interfaces with HuggingFace Spaces.")
        
        with gr.Accordion("πŸš€ Getting Started", open=True):
            gr.Markdown("""
            ### Quick Start Guide
            Create a functional assistant with URL grounding and example prompts.
            
            **Workflow:**
            1. **Configure** space settings and system prompt
            2. **Enable** URL grounding tools
            3. **Preview** and test configuration
            4. **Generate** deployment package
            5. **Deploy** to HuggingFace
            
            **Prerequisites:**
            - HuggingFace account (free)
            - OpenRouter API key
            - Basic AI chatbot knowledge
            """)
        
        with gr.Accordion("βš™οΈ Basic Configuration", open=False):
            gr.Markdown("""
            ### Essential Settings
            
            **Space Title & Description** - Name and purpose
            
            **Model Selection:**
            - **Gemini 2.0 Flash** - Fast, reliable (recommended)
            - **Gemma 3 27B** - Open-source, cost-effective
            - **Claude 3.5 Haiku** - Advanced reasoning
            
            **API Key Variable** - Default: `OPENROUTER_API_KEY`
            
            **Access Code** - Optional student protection
            """)
        
        with gr.Accordion("πŸ€– Assistant Setup", open=False):
            gr.Markdown("""
            ### System Prompt & Templates
            
            **Templates (Easy Start):**
            - **Research Template** - Academic work, citations, fact-checking
            - **Socratic Template** - Teaching through questions, critical thinking
            - **Custom** - Write your own (advanced)
            
            ### Quick Copy-Paste Prompts
            
            **Course Assistant:**
            ```
            You are a [SUBJECT] teaching assistant for [LEVEL] students. Help with concepts, assignments, and study questions. Explain complex topics simply and encourage critical thinking.
            ```
            
            **Research Helper:**
            ```
            You are a research assistant. Help with citations, source analysis, and academic writing. Focus on proper documentation and evidence-based responses.
            ```
            
            **Study Buddy:**
            ```
            You are a friendly study companion. Help students understand concepts, practice problems, and prepare for exams. Use encouraging language and break down complex ideas step-by-step.
            ```
            
            **Tips:**
            - Replace [SUBJECT] and [LEVEL] with your specifics
            - Be clear about the assistant's role
            - Mention your target audience
            """)
        
        with gr.Accordion("πŸ”¬ Preview Tab Usage", open=False):
            gr.Markdown("""
            ### Testing Before Deployment
            
            **Preview Features:**
            - Real API integration
            - Configuration display
            - URL testing (up to 4 URLs)
            - Chat export
            - Clear function
            
            **Preview Steps:**
            1. Complete Configuration tab setup
            2. Click "Preview Deployment Package"
            3. Test chat interface
            4. Test URL grounding
            5. Export conversations for analysis
            
            **Requirements:**
            - Set `OPENROUTER_API_KEY` environment variable
            - Without API key: shows configuration only
            
            **Best Practices:**
            - Test various query types
            - Verify URL grounding works
            - Confirm system prompt behavior
            - Export successful conversations
            """)
        
        with gr.Accordion("πŸ’¬ Example Prompts", open=False):
            gr.Markdown("""
            ### Quick Start Examples
            
            **Guidelines:** One prompt per line, under 100 characters, show capabilities
            
            **Course Assistant:**
            ```
            Can you explain [topic] in simple terms?
            Help me prepare for the midterm exam
            What are the key concepts I should focus on?
            ```
            
            **Research Assistant:**
            ```
            Analyze this source: [URL]
            Help me fact-check this claim
            What citation format should I use?
            ```
            
            **Study Helper:**
            ```
            Quiz me on chapter 5 concepts
            Explain this problem step-by-step
            Help me create a study plan
            ```
            """)
        
        with gr.Accordion("πŸ”§ Tool Settings & Configuration", open=False):
            gr.Markdown("""
            ### Configuration Structure
            
            **Main Fields:**
            - Space Title & Description
            - Model Selection
            - API Key Variable
            - Access Code (optional)
            
            **Assistant Setup:**
            - System Prompt
            - Template Selection
            - URL Grounding (2-4 URLs)
            - Example Prompts
            
            **Advanced Settings:**
            - Temperature (0.0-2.0)
            - Max Tokens (50-4096)
            
            **URL Grounding (Static)**
            - 2-4 URLs for consistent context
            - Content cached during generation
            - Perfect for syllabi, policies, references
            
            **Dynamic URL Fetching**
            - Always enabled
            - Processes URLs in conversations
            - Limited content size for performance
            """)
        
        with gr.Accordion("πŸŽ›οΈ Advanced Settings", open=False):
            gr.Markdown("""
            ### Model Parameters
            
            **Temperature (0.0 - 2.0)**
            - **0.0-0.3**: Focused, deterministic
            - **0.4-0.7**: Balanced (recommended)
            - **0.8-1.2**: Creative, varied
            - **1.3-2.0**: Highly creative
            
            **Max Response Tokens (50-4096)**
            - **50-200**: Short answers
            - **200-750**: Medium (recommended: 750)
            - **750-1500**: Detailed explanations
            - **1500+**: Extended analysis
            
            **Token Notes:**
            - Includes input (prompt + context) and output
            - URLs increase input tokens
            - Consider costs with high limits
            """)
        
        with gr.Accordion("πŸš€ Deployment Process", open=False):
            gr.Markdown("""
            ### Deployment Guide
            
            **Steps:** Generate β†’ Create Space β†’ Add Secrets β†’ Go Live
            
            **1. Generate & Upload**
            - Click "Generate Deployment Package", download zip
            - Create Space at huggingface.co/spaces (Gradio SDK)
            - Upload `app.py` and `requirements.txt`
            
            **2. Add API Key**
            - Settings β†’ Variables and secrets β†’ New secret
            - Name: `OPENROUTER_API_KEY`
            - Value: Your API key (starts with `sk-or-`)
            
            **3. Access Control (Optional)**
            - Add secret: `SPACE_ACCESS_CODE`
            - Students enter code to access chatbot
            - Delete secret to disable protection
            """)
            
            # Add the secret configuration image (flush left)
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Image(
                        value="https://drive.google.com/uc?export=view&id=1z67BZrYlJkpvHJ0Dp6vvIWAkN2iwUxCv",
                        label="HuggingFace Secret Configuration Interface",
                        show_label=False,
                        interactive=False,
                        width=400,
                        height=300,
                        container=False
                    )
                with gr.Column(scale=2):
                    gr.Markdown("""
                    **Secret Configuration Interface:**
                    - **Name**: Your variable name (e.g., `OPENROUTER_API_KEY`)
                    - **Value**: Your API key or access code
                    - **Add** button to save the secret
                    
                    **Required Secrets:**
                    - `OPENROUTER_API_KEY`: Your API key (always required)
                    - `SPACE_ACCESS_CODE`: Access code (only if using access control)
                    """)
            
            gr.Markdown("""
            **4. Deploy & Test**
            - Wait for build (1-2 minutes)
            - Test with example prompts
            - Share URL when working
            """)
        
        with gr.Accordion("πŸ”§ Troubleshooting", open=False):
            gr.Markdown("""
            ### Common Issues and Solutions
            
            **"Please set your API key" message**
            - Check that you added the API key secret in Space settings
            - Verify the secret name matches your configuration
            - Ensure your OpenRouter account has credits
            
            **Building Failed**
            - Check `requirements.txt` formatting (no extra spaces/characters)
            - Verify all required dependencies are listed
            - Try reuploading files if build gets stuck
            
            **Error 401 (Unauthorized)**
            - Invalid API key or incorrect secret name
            - Check OpenRouter account status and credits
            - Regenerate API key if needed
            
            **Error 429 (Too Many Requests)**
            - Rate limit exceeded
            - Wait a few minutes before trying again
            - Consider upgrading OpenRouter plan for higher limits
            
            **Assistant not responding**
            - Check browser console for JavaScript errors
            - Verify model name is correct and available
            - Test with simple prompts first
            
            **Access code not working**
            - Verify `SPACE_ACCESS_CODE` secret is set correctly
            - Check for typos in the access code
            - Case-sensitive matching
            
            **URLs not fetching content**
            - Check URLs are publicly accessible
            - Some sites block automated requests
            - Verify dynamic URL fetching is enabled if needed
            """)
        
        with gr.Accordion("πŸ’‘ Best Practices", open=False):
            gr.Markdown("""
            ### Optimization Tips
            
            **Performance**
            - Use appropriate model
            - Set reasonable token limits
            - Cache static content with URL grounding
            
            **User Experience**
            - Write clear example prompts
            - Include usage instructions
            - Test thoroughly before sharing
            - Provide clear access instructions
            
            **Security**
            - Never include API keys in code
            - Use environment variables for secrets
            - Set appropriate access controls
            - Monitor usage and costs
            
            **Maintenance**
            - Check for model updates
            - Monitor feedback and usage
            - Update grounding URLs
            - Keep documentation current
            
            **Cost Management**
            - Start with lower token limits
            - Monitor OpenRouter dashboard
            - Set usage alerts
            - Educate efficient prompting
            """)
        
        with gr.Accordion("πŸ“š Additional Resources", open=False):
            gr.Markdown("""
            ### Helpful Links
            
            **HuggingFace Documentation**
            - [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 Documentation**
            - [API Keys](https://openrouter.ai/keys)
            - [Model Comparison](https://openrouter.ai/models)
            - [Pricing](https://openrouter.ai/docs#models)
            
            **Gradio Documentation**
            - [Chat Interface](https://gradio.app/docs/chatinterface)
            - [Components](https://gradio.app/docs/)
            - [Sharing Apps](https://gradio.app/sharing-your-app/)
            
            **Community Support**
            - [HuggingFace Community Forums](https://discuss.huggingface.co/)
            - [Gradio Discord](https://discord.gg/feTf9x3ZSB)
            
            **Educational Use Cases**
            - Course assistants for Q&A
            - Research writing support
            - Study guide generation
            - Document analysis tools
            - Language practice partners
            """)

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('name'):
            markdown_content += f"**Assistant Name:** {config_metadata['name']}\n"
        if config_metadata.get('description'):
            markdown_content += f"**Description:** {config_metadata['description']}\n"
        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