Spaces:
Running
Running
File size: 15,901 Bytes
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 |
"""
Support documentation module with accordion-style help sections
"""
import gradio as gr
def create_support_docs():
"""Create the support documentation interface with accordion menus"""
with gr.Column():
gr.Markdown("# Support Documentation")
gr.Markdown("Complete 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
1. **Configure your Space** in the main Configuration tab
2. **Preview your assistant** using the Preview button
3. **Generate deployment package** with the Generate button
4. **Deploy to HuggingFace Spaces** following the README instructions
**Prerequisites:**
- HuggingFace account (free at huggingface.co)
- OpenRouter API key (get at openrouter.ai/keys)
- Basic understanding of AI chatbots
""")
with gr.Accordion("βοΈ Space Settings", open=False):
gr.Markdown("""
### Space Configuration Fields
**Space Title**
- The name that will appear on HuggingFace and in your chat interface
- Keep it descriptive but concise (e.g., "Biology Course Assistant")
**Space Description**
- Brief explanation of what your assistant does
- Will appear in the HuggingFace Space listing and at the top of your chat
**Model Selection**
- **google/gemini-2.0-flash-001**: Fast, reliable, good for general tasks
- **anthropic/claude-3.5-haiku**: Great for complex reasoning and analysis
- **openai/gpt-4o-nano**: Balanced performance and cost
- **mistralai/mistral-medium**: Good for technical topics
**API Key Variable Name**
- Default: `OPENROUTER_API_KEY`
- This is the secret name you'll create in HuggingFace Space settings
- Only change if you have specific naming requirements
**Access Code (Optional)**
- Leave empty for public access
- Set a code to restrict access to students/specific users
- Code is stored securely as an environment variable
""")
with gr.Accordion("π€ Assistant Configuration", open=False):
gr.Markdown("""
### System Prompt Design
The system prompt defines your assistant's personality, knowledge, and behavior.
**Best Practices:**
- Be specific about the assistant's role and purpose
- Include behavioral guidelines and constraints
- Mention the intended audience (students, researchers, etc.)
- List key capabilities and tasks
**Research Template**
- Pre-configured for academic research assistance
- Includes MLA citation formatting
- Emphasizes fact-checking and evidence-based responses
- Automatically enables dynamic URL fetching
**Custom Categories**
- Break down your system prompt into structured sections:
- **Role and Purpose**: What is the assistant and what does it do?
- **Intended Audience**: Who will use this assistant?
- **Key Tasks**: What specific capabilities should it have?
- **Additional Context**: Extra instructions or constraints
**Example System Prompts:**
```
Biology Course Assistant:
"You are a biology teaching assistant for undergraduate students. Help with concepts, lab procedures, and study questions. Always explain complex topics in simple terms and encourage critical thinking."
Research Writing Helper:
"You are a research writing assistant. Help students with citation formatting, argument structure, and source analysis. Focus on academic writing standards and proper documentation."
```
""")
with gr.Accordion("π¬ Example Prompts", open=False):
gr.Markdown("""
### Creating Effective Example Prompts
Example prompts appear as clickable suggestions in your chat interface.
**Guidelines:**
- Write 3-6 clear, specific examples
- Show the range of what your assistant can do
- Match your intended use cases
- Include URLs if your assistant can process them
**Format:**
- One prompt per line
- Keep each prompt under 100 characters for better display
- Use natural, conversational language
**Examples by Use Case:**
**Course Assistant:**
```
Can you explain photosynthesis in simple terms?
Help me understand the difference between mitosis and meiosis
What should I focus on for the midterm exam?
```
**Research Assistant:**
```
Analyze this research paper: https://example.com/paper.pdf
Help me fact-check claims about climate change
What citation format should I use for this source?
```
**Writing Helper:**
```
Review my thesis statement for clarity
Help me organize my argument structure
Suggest improvements for this paragraph
```
""")
with gr.Accordion("π§ Tool Settings & Grounding", open=False):
gr.Markdown("""
### Tool Configuration Options
**Dynamic URL Fetching**
- Allows assistant to fetch content from URLs mentioned in conversations
- Useful for research and fact-checking tasks
- Automatically extracts text content from web pages
- Limited to 3 URLs per message for performance
**Document RAG (Retrieval-Augmented Generation)**
- Upload PDF, DOCX, TXT, or MD files as knowledge base
- Assistant can search and reference uploaded documents
- Perfect for course materials, policies, or reference documents
- Files are embedded in your deployment package
**URL Grounding**
- Add up to 4 URLs that provide static context
- Content is fetched once and included in every response
- Great for course syllabi, institutional policies, or reference materials
- Content is cached to avoid repeated fetching
**When to Use Each:**
- **Static URLs**: Course policies, syllabi, reference materials
- **Dynamic URLs**: Research tasks where students provide links
- **Document RAG**: Large document collections, textbooks, course readers
**File Size Limits:**
- Individual files: 10MB maximum
- Total RAG package: Recommended under 50MB for deployment
""")
with gr.Accordion("ποΈ Advanced Settings", open=False):
gr.Markdown("""
### Model Parameters
**Temperature (0.0 - 2.0)**
- **0.0-0.3**: Very focused, deterministic responses
- **0.4-0.7**: Balanced creativity and consistency (recommended)
- **0.8-1.2**: More creative and varied responses
- **1.3-2.0**: Highly creative, potentially unpredictable
**Max Response Tokens (50-4096)**
- Controls maximum length of assistant responses
- **50-200**: Short, concise answers
- **200-500**: Medium responses (recommended for most cases)
- **500-1000**: Longer, detailed explanations
- **1000+**: Extended analysis and comprehensive responses
**Token Usage Notes:**
- Tokens include both input (your prompt + context) and output
- Longer contexts (documents, URLs) use more input tokens
- Monitor usage through OpenRouter dashboard
- Consider costs when setting high token limits
""")
with gr.Accordion("π Deployment Process", open=False):
gr.Markdown("""
### Step-by-Step Deployment
**1. Generate Package**
- Click "Generate Deployment Package" in the Configuration tab
- Download the zip file when ready
- Contains: app.py, requirements.txt, README.md, config.json
**2. Create HuggingFace Space**
- Go to [huggingface.co/spaces](https://huggingface.co/spaces)
- Click "Create new Space"
- Choose a name and set to Public or Private
- **Important**: Select "Gradio" as the SDK
- Click "Create Space"
**3. Upload Files**
- In your new Space, click the "Files" tab
- Upload `app.py` and `requirements.txt` from your zip
- Wait for the "Building" status to complete
**4. Add API Key**
- Go to Settings (gear icon) β "Variables and secrets"
- Click "New secret"
- Name: Your API key variable name (usually `OPENROUTER_API_KEY`)
- Value: Your OpenRouter API key (get from openrouter.ai/keys)
- Click "Add"
**5. Configure Access (Optional)**
- If you set an access code, add another secret:
- Name: `SPACE_ACCESS_CODE`
- Value: Your chosen access code
- Students will need this code to use the assistant
**6. Test and Share**
- Go back to "App" tab
- Your Space should be running!
- Test with example prompts
- Share the Space URL with students
""")
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
**Documents not loading (RAG)**
- Check file formats are supported (PDF, DOCX, TXT, MD)
- Verify file sizes are under 10MB
- Ensure RAG dependencies are installed
**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 for your use case
- Set reasonable token limits
- Cache static content with URL grounding
- Limit document uploads to essential materials
**User Experience**
- Write clear, helpful example prompts
- Include usage instructions in Space description
- Test thoroughly before sharing with students
- Provide clear access instructions if using codes
**Security**
- Never include API keys in code or README
- Use environment variables for all secrets
- Set appropriate access controls
- Monitor usage and costs regularly
**Maintenance**
- Regularly check for model updates
- Monitor student feedback and usage patterns
- Update grounding URLs if content changes
- Keep documentation current
**Cost Management**
- Start with lower token limits and adjust as needed
- Monitor usage through OpenRouter dashboard
- Consider setting up usage alerts
- Educate users on 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):
"""Export conversation history to markdown format"""
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')}
---
"""
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 |