""" 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