Spaces:
Running
Running
""" | |
Support documentation module with accordion-style help sections | |
IMAGE PLACEHOLDERS TO REPLACE: | |
1. interface_overview.png - Three-tab interface overview (Getting Started) | |
2. configuration_tab.png - Configuration tab screenshot (Space Settings) | |
3. system_prompt_interface.png - System prompt and template interface (Assistant Configuration) | |
4. preview_tab.png - Preview tab with chat interface (Preview Tab Usage) | |
5. example_prompts.png - Example prompts input and display (Example Prompts) | |
6. tool_settings_diagram.png - Configuration structure diagram (Tool Settings) | |
7. advanced_settings.png - Temperature and token controls (Advanced Settings) | |
8. deployment_process.png - Deployment process flow diagram (Deployment Process) | |
9. secret.png - HuggingFace secret configuration (already exists) | |
""" | |
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("*Under construction - images coming soon!*") | |
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 | |
This guide helps you set up your first chat interface on HuggingFace Spaces using Gradio. Follow these steps to create a functional assistant with URL grounding and example prompts. | |
""") | |
# TODO: Add interface overview screenshot | |
with gr.Row(): | |
with gr.Column(scale=1): | |
gr.Image( | |
value="interface_overview.png", # Placeholder for interface overview screenshot | |
label="Three-Tab Interface: Configuration, Preview, and Support", | |
show_label=True, | |
interactive=False, | |
width=600, | |
height=400, | |
container=False | |
) | |
with gr.Column(scale=1): | |
gr.Markdown(""" | |
**Workflow Steps:** | |
1. **Configure** your space settings | |
2. **Set up** assistant with system prompt | |
3. **Enable** tools like URL grounding | |
4. **Preview** & test your configuration | |
5. **Generate** deployment package | |
6. **Deploy** to HuggingFace | |
""") | |
gr.Markdown(""" | |
**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 | |
""") | |
# TODO: Add configuration tab screenshot | |
with gr.Row(): | |
with gr.Column(scale=1): | |
gr.Image( | |
value="configuration_tab.png", # Placeholder for configuration tab screenshot | |
label="Configuration Tab Interface", | |
show_label=True, | |
interactive=False, | |
width=500, | |
height=400, | |
container=False | |
) | |
with gr.Column(scale=1): | |
gr.Markdown(""" | |
**Key Configuration Fields:** | |
**Space Title** - Display name for your assistant | |
**Space Description** - Brief explanation of purpose | |
**Model Selection** - Choose from optimized models: | |
- **Gemma 3 27B** - Open-source, sustainable | |
- **Gemini 2.0 Flash** - Fast, reliable | |
- **Claude 3.5 Haiku** - Complex reasoning | |
**API Key Variable** - Default: `OPENROUTER_API_KEY` | |
**Access Code** - Optional student protection | |
""") | |
gr.Markdown(""" | |
**Model Comparison:** | |
- **[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 | |
- **[anthropic/claude-3.5-haiku](https://openrouter.ai/models/anthropic/claude-3.5-haiku)**: Great for complex reasoning and analysis | |
""") | |
with gr.Accordion("π€ Space Configuration", open=False): | |
gr.Markdown(""" | |
### System Prompt Design | |
""") | |
# TODO: Add system prompt interface screenshot | |
with gr.Row(): | |
with gr.Column(scale=1): | |
gr.Image( | |
value="system_prompt_interface.png", # Placeholder for system prompt interface | |
label="System Prompt Configuration Interface", | |
show_label=True, | |
interactive=False, | |
width=500, | |
height=300, | |
container=False | |
) | |
with gr.Column(scale=1): | |
gr.Markdown(""" | |
**Template System:** | |
**Research Template** - Pre-configured for academic use | |
- MLA citation formatting | |
- Fact-checking emphasis | |
- Auto-enables URL fetching | |
**Socratic Template** - Pedagogical questioning | |
- Constructivist learning approach | |
- Critical thinking focus | |
**Custom Prompt** - Build your own | |
""") | |
gr.Markdown(""" | |
**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 | |
### 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("π¬ Preview Tab Usage", open=False): | |
gr.Markdown(""" | |
### Testing Your Assistant Before Deployment | |
""") | |
# TODO: Add preview tab screenshot | |
with gr.Row(): | |
with gr.Column(scale=1): | |
gr.Image( | |
value="preview_tab.png", # Placeholder for preview tab screenshot | |
label="Preview Tab with Active Chat Interface", | |
show_label=True, | |
interactive=False, | |
width=500, | |
height=400, | |
container=False | |
) | |
with gr.Column(scale=1): | |
gr.Markdown(""" | |
**Preview Features:** | |
**Real API Integration** - Uses actual OpenRouter API | |
**Configuration Display** - Shows current setup | |
**URL Testing** - Add up to 4 URLs for context | |
**Chat Export** - Download conversation logs | |
**Clear Function** - Reset chat history | |
""") | |
gr.Markdown(""" | |
**How to Use the Preview:** | |
1. **Configure First**: Complete your setup in the Configuration tab | |
2. **Click Preview Button**: Use "Preview Deployment Package" to activate the preview | |
3. **Test Chat Interface**: Interactive chat with your exact configuration | |
4. **Test URL Context**: Add URLs to test grounding functionality | |
5. **Export Conversations**: Save chat logs for analysis | |
**Preview Requirements:** | |
- Set `OPENROUTER_API_KEY` environment variable for real API testing | |
- Without API key: Shows configuration but no actual chat responses | |
**Testing Best Practices:** | |
- Test different types of queries to validate assistant behavior | |
- Try URL grounding with actual websites to test context integration | |
- Verify that system prompt and model settings work as expected | |
- Export successful conversations to use as examples for documentation | |
""") | |
with gr.Accordion("π¬ Example Prompts", open=False): | |
gr.Markdown(""" | |
### Creating Effective Example Prompts | |
""") | |
# TODO: Add example prompts interface screenshot | |
with gr.Row(): | |
with gr.Column(scale=1): | |
gr.Image( | |
value="example_prompts.png", # Placeholder for example prompts interface | |
label="Example Prompts Interface and Display", | |
show_label=True, | |
interactive=False, | |
width=500, | |
height=300, | |
container=False | |
) | |
with gr.Column(scale=1): | |
gr.Markdown(""" | |
**Guidelines:** | |
**Format** - One prompt per line | |
**Length** - Under 100 characters each | |
**Content** - Show assistant capabilities | |
**Language** - Natural and conversational | |
**URLs** - Include if assistant processes them | |
""") | |
gr.Markdown(""" | |
**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 & Configuration", open=False): | |
gr.Markdown(""" | |
### Configuration Tab Structure | |
""") | |
# TODO: Add tool settings diagram | |
with gr.Row(): | |
with gr.Column(scale=1): | |
gr.Image( | |
value="tool_settings_diagram.png", # Placeholder for tool settings structure diagram | |
label="Configuration Tab Structure and Tool Integration", | |
show_label=True, | |
interactive=False, | |
width=500, | |
height=400, | |
container=False | |
) | |
with gr.Column(scale=1): | |
gr.Markdown(""" | |
**Main Configuration Fields:** | |
- Space Title & Description | |
- Model Selection | |
- API Key Variable | |
- Access Code (optional) | |
**Assistant Configuration:** | |
- System Prompt | |
- Template Selection | |
- URL Grounding (2-4 URLs) | |
- Example Prompts | |
**Advanced Settings:** | |
- Temperature (0.0-2.0) | |
- Max Tokens (50-4096) | |
""") | |
gr.Markdown(""" | |
### Tool Integration Options | |
**URL Grounding (Static Context)** | |
- Add 2-4 URLs for consistent context across all responses | |
- Content fetched once during generation and cached | |
- Dynamic add/remove buttons for scalable input | |
- Perfect for course syllabi, policies, reference materials | |
**Dynamic URL Fetching (Runtime)** | |
- Always enabled - processes URLs mentioned in conversations | |
- Extracts content from user-provided links automatically | |
- Limited to reasonable content size for performance | |
""") | |
with gr.Accordion("ποΈ Advanced Settings", open=False): | |
gr.Markdown(""" | |
### Model Parameters | |
""") | |
# TODO: Add advanced settings interface screenshot | |
with gr.Row(): | |
with gr.Column(scale=1): | |
gr.Image( | |
value="advanced_settings.png", # Placeholder for advanced settings interface | |
label="Advanced Settings: Temperature and Token Controls", | |
show_label=True, | |
interactive=False, | |
width=500, | |
height=300, | |
container=False | |
) | |
with gr.Column(scale=1): | |
gr.Markdown(""" | |
**Temperature (0.0 - 2.0)** | |
- **0.0-0.3**: Very focused, deterministic | |
- **0.4-0.7**: Balanced (recommended) | |
- **0.8-1.2**: More creative and varied | |
- **1.3-2.0**: Highly creative, unpredictable | |
**Max Response Tokens (50-4096)** | |
- **50-200**: Short, concise answers | |
- **200-500**: Medium responses (recommended) | |
- **500-1000**: Longer, detailed explanations | |
- **1000+**: Extended analysis | |
""") | |
gr.Markdown(""" | |
**Token Usage Notes:** | |
- Tokens include both input (your prompt + context) and output | |
- Longer contexts (URLs) use more input tokens | |
- Consider costs when setting high token limits | |
""") | |
with gr.Accordion("π Deployment Process", open=False): | |
gr.Markdown(""" | |
### Quick Deployment Guide | |
""") | |
# TODO: Add deployment process diagram | |
with gr.Row(): | |
with gr.Column(scale=1): | |
gr.Image( | |
value="deployment_process.png", # Placeholder for deployment process diagram | |
label="Complete Deployment Process Flow", | |
show_label=True, | |
interactive=False, | |
width=500, | |
height=300, | |
container=False | |
) | |
with gr.Column(scale=1): | |
gr.Markdown(""" | |
**Deployment Steps:** | |
**1. Generate Package** - Download zip file | |
**2. Create Space** - New HuggingFace Space (Gradio SDK) | |
**3. Upload Files** - app.py and requirements.txt | |
**4. Add API Key** - Secret configuration | |
**5. Deploy & Test** - Wait for build, then test | |
""") | |
gr.Markdown(""" | |
**Detailed Steps:** | |
**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 | |
- Name: `OPENROUTER_API_KEY` (or your chosen variable name) | |
- Value: Your OpenRouter API key (starts with `sk-or-`) | |
- Click "Add" to save the secret | |
The secret configuration interface looks like this: | |
""") | |
# 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): | |
pass # Empty column to push image left | |
gr.Markdown(""" | |
*If the image above doesn't load, the interface shows:* | |
- **Name**: `OPENROUTER_API_KEY` (your API key variable name) | |
- **Description**: Optional description | |
- **Value**: Your OpenRouter API key (starts with `sk-or-`) | |
- **Save** button to store the secret | |
**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 | |
**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 | |
# Document RAG functionality removed | |
**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, 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 |