chatui-helper / support_docs.py
milwright's picture
Update documentation with enhanced model information and system prompt templates
f51b1f2
raw
history blame
18.3 kB
"""
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("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/gemma-3-27b-it](https://openrouter.ai/models/google/gemma-3-27b-it)**: Open-source, sustainable option with excellent performance
- **[google/gemini-2.0-flash-001](https://openrouter.ai/models/google/gemini-2.0-flash-001)**: Fast, reliable, good for general tasks
- **[mistralai/mistral-medium](https://openrouter.ai/models/mistralai/mistral-medium)**: Good for technical topics
- **[openai/gpt-4o-nano](https://openrouter.ai/models/openai/gpt-4o-nano)**: Balanced performance and cost
- **[anthropic/claude-3.5-haiku](https://openrouter.ai/models/anthropic/claude-3.5-haiku)**: Great for complex reasoning and analysis
**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
### Copy-Pasteable 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. Focus on helping students understand fundamental biological processes and prepare for exams.
```
**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. Guide students through the research process from topic selection to final paper submission.
```
**Course Q&A Assistant (Template):**
```
You are a knowledgeable academic assistant for [COURSE NAME] students. Provide clear, evidence-based answers about [SUBJECT AREA] while encouraging deeper engagement through follow-up questions. Use accessible language appropriate for [STUDENT LEVEL]. Keep responses concise (under 100 words) with bullet points when helpful. End each response with a thought-provoking question or real-world connection that encourages students to think critically about the topic and explore related concepts.
```
**Psychology 101 Example:**
```
You are a knowledgeable academic research assistant for a Psychology 101 class. Provide students with clear, evidence-based answers about psychology topics while encouraging deeper engagement through follow-up questions. Use accessible language appropriate for introductory students. Keep responses concise (under 100 words) with bullet points when helpful. End each response with a thought-provoking question or real-world example that encourages students to think critically about how psychology concepts apply to everyday life.
```
**Technical Support Helper:**
```
You are a technical support assistant specializing in software tools and programming concepts. Provide step-by-step guidance, troubleshoot common issues, and explain technical concepts in accessible language. Always include examples when possible.
```
**Research Assistant (Pre-configured Template):**
```
You are a research assistant that provides link-grounded information through web fetching. Use MLA documentation for parenthetical citations and bibliographic entries. This assistant is designed for students and researchers conducting academic inquiry. Your main responsibilities include: analyzing academic sources, fact-checking claims with evidence, providing properly cited research summaries, and helping users navigate scholarly information. Ground all responses in provided URL contexts and any additional URLs you're instructed to fetch. Never rely on memory for factual claims.
```
""")
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("""
### Quick Deployment Guide
**1. Generate & Upload**
- Click "Generate Deployment Package" β†’ download zip
- Create new Space at [huggingface.co/spaces](https://huggingface.co/spaces) (select **Gradio** SDK)
- Upload `app.py` and `requirements.txt` from zip to Files tab
**2. Add Your OpenRouter API Key**
Since you already have an OpenRouter API key, add it as a secret:
- Go to Settings β†’ Variables and secrets β†’ New secret
- Use the interface shown below to add your key:
![HuggingFace Secret Configuration](./secret.png)
**3. Optional: Add Access Code**
If you configured student access protection:
- Add another secret: Name = `SPACE_ACCESS_CODE`, Value = your chosen code
**4. Deploy & Share**
- Wait for build completion β†’ test in App tab β†’ share URL with students
**That's it!** Your Space will be live and ready for use.
""")
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