Spaces:
Running
Running
| """ | |
| 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("# ChatUI Helper Documentation") | |
| gr.Markdown("Welcome to ChatUI Helper! This tool helps you create customizable AI chat interfaces for deployment on HuggingFace Spaces.") | |
| with gr.Accordion("📖 Quick Start Guide", open=True): | |
| gr.Markdown(""" | |
| ## Quick Start Guide | |
| 1. **Configure** your assistant using templates or custom settings | |
| 2. **Preview** your configuration to test it works | |
| 3. **Generate** your deployment package | |
| 4. **Deploy** to HuggingFace Spaces | |
| **Requirements:** | |
| - HuggingFace account (free) | |
| - OpenRouter API key | |
| - Basic understanding of AI assistants | |
| """) | |
| with gr.Accordion("📝 Step 1: Configure Your Space", open=False): | |
| gr.Markdown(""" | |
| ### Configuration Tab Sections | |
| **1. Quick Start Templates** | |
| - Choose from pre-configured academic templates | |
| - Or start with "None (Custom)" for full control | |
| - Your custom values are preserved when switching templates | |
| **2. Space Identity** | |
| - **Assistant Name**: Your AI assistant's display name | |
| - **Theme**: Choose from Default, Soft, Glass, Monochrome, or Base | |
| - **Tagline**: Brief description (60 chars max) for the Space header | |
| - **Description**: Full markdown description for the README | |
| **3. System Configuration** | |
| - **System Prompt**: Define your assistant's behavior and knowledge | |
| - **Model**: Select from available OpenRouter models | |
| - **Temperature**: Control response creativity (0-2) | |
| - **Max Tokens**: Set response length limit (50-4096) | |
| **4. Example Prompts** | |
| - Add 3-5 sample prompts that showcase capabilities | |
| - These appear as quick-start buttons for users | |
| - Use the ➕/➖ buttons to add/remove examples | |
| **5. URL Grounding** | |
| - Add reference URLs for context (up to 10) | |
| - First 2 URLs are primary sources (always loaded) | |
| - Additional URLs are secondary references | |
| - Content is fetched and provided as context | |
| **6. API Configuration** | |
| - **API_KEY**: Required OpenRouter API key variable | |
| - **HF_TOKEN**: Optional for auto-configuration updates | |
| - **ACCESS_CODE**: Optional password protection | |
| **7. Upload Configuration** | |
| - Import existing config.json files | |
| - Quickly restore previous configurations | |
| """) | |
| with gr.Accordion("💬 Step 2: Preview Your Assistant", open=False): | |
| gr.Markdown(""" | |
| ### Preview Tab Features | |
| **Test Configuration** | |
| - Sends real API requests using your local API key | |
| - Uses the exact configuration from Step 1 | |
| - Displays responses in the chat interface | |
| **Features Available** | |
| - Try example prompts | |
| - Upload files (if enabled) | |
| - Export conversation history | |
| - View active configuration | |
| **API Key Setup** | |
| - Set your OpenRouter API key as environment variable | |
| - Default variable name: `API_KEY` | |
| - Get your key at: https://openrouter.ai/keys | |
| **Test Checklist:** | |
| - Various query types and assistant responses | |
| - URL grounding functionality (if configured) | |
| - System prompt behavior matches expectations | |
| - Example prompts work correctly | |
| """) | |
| with gr.Accordion("🗳️ Step 3: Generate & Deploy", open=False): | |
| gr.Markdown(""" | |
| ### Deployment Package & HuggingFace Space Setup | |
| **Package Contents:** | |
| - **app.py**: Complete Gradio application | |
| - **requirements.txt**: Python dependencies | |
| - **config.json**: Configuration backup | |
| - **README.md**: Deployment instructions | |
| **Deployment Overview:** Generate Package → Create Space → Upload Files → Configure Secrets → Monitor Build → Verify | |
| """) | |
| with gr.Accordion("Step 1: Generate & Create Space", open=False): | |
| gr.Markdown(""" | |
| **1.1 Generate Deployment Package** | |
| - Click "🗳️ Generate Deployment Package" in Configuration tab | |
| - Download the generated ZIP file | |
| - Extract files: `app.py`, `config.json`, `requirements.txt`, `README.md` | |
| **1.2 Create New Space** | |
| - Go to [huggingface.co/spaces](https://huggingface.co/spaces) | |
| - Click "New Space" | |
| - Choose Gradio SDK | |
| - Select hardware (CPU Basic is free) | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Image( | |
| value="img/img17.png", | |
| label="Space Creation Form", | |
| show_label=True, | |
| interactive=False, | |
| width=400, | |
| container=False | |
| ) | |
| with gr.Column(scale=1): | |
| gr.Image( | |
| value="img/img16.png", | |
| label="Hardware Selection", | |
| show_label=True, | |
| interactive=False, | |
| width=400, | |
| container=False | |
| ) | |
| with gr.Accordion("Step 2: Upload Files", open=False): | |
| gr.Markdown(""" | |
| **2.1 Upload Project Files** | |
| - Navigate to Files tab | |
| - Click "Upload files" or drag and drop | |
| - Upload: `README.md`, `app.py`, `config.json`, `requirements.txt` | |
| - Commit directly to main branch | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Image( | |
| value="img/img12.png", | |
| label="File Upload", | |
| show_label=True, | |
| interactive=False, | |
| width=400, | |
| container=False | |
| ) | |
| with gr.Column(scale=1): | |
| gr.Image( | |
| value="img/img8.png", | |
| label="Files After Upload", | |
| show_label=True, | |
| interactive=False, | |
| width=400, | |
| container=False | |
| ) | |
| with gr.Accordion("Step 3: Configure API Secrets", open=False): | |
| gr.Markdown(""" | |
| **3.1 Configure HuggingFace Spaces Secrets** | |
| - Go to Settings → Variables and secrets | |
| - Click "New secret" | |
| **Required Secret:** | |
| - `API_KEY` (or your configured variable name) | |
| - Must start with: `sk-or-` | |
| - Add in: Settings → Variables and secrets | |
| **Optional Secrets:** | |
| - `HF_TOKEN`: Enables automatic configuration updates | |
| - Get from: https://huggingface.co/settings/tokens | |
| - Needs write permissions | |
| - `ACCESS_CODE`: Password protects your Space | |
| - Set any password value | |
| - Share with authorized users only | |
| **Access Control Notes:** | |
| - If you don't create the `SPACE_ACCESS_CODE` secret, your Space will be publicly accessible | |
| - To enable access control, create the `SPACE_ACCESS_CODE` secret with your chosen code value | |
| - To disable access control, delete the `SPACE_ACCESS_CODE` secret entirely | |
| - Do NOT set an empty value - either set a code or don't create the secret at all | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Image( | |
| value="img/img4.png", | |
| label="Navigating to Settings", | |
| show_label=True, | |
| interactive=False, | |
| width=400, | |
| container=False | |
| ) | |
| with gr.Column(scale=1): | |
| gr.Image( | |
| value="img/img4.png", | |
| label="Settings Variables and Secrets", | |
| show_label=True, | |
| interactive=False, | |
| width=400, | |
| container=False | |
| ) | |
| with gr.Column(scale=1): | |
| gr.Image( | |
| value="img/img3.png", | |
| label="API Key Secret Configuration", | |
| show_label=True, | |
| interactive=False, | |
| width=400, | |
| container=False | |
| ) | |
| with gr.Accordion("Step 4: Monitor Build & Verify Configuration", open=False): | |
| gr.Markdown(""" | |
| **4.1 Build Monitoring** | |
| - Space will show "Building..." status | |
| - Monitor build logs for errors | |
| - Wait 1-3 minutes for completion | |
| **4.2 Configuration Verification** | |
| - Check Configuration Status panel | |
| - API Key should show "Configured and valid" ✅ | |
| - Test chat interface with example prompts | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Image( | |
| value="img/img7.png", | |
| label="Build Process", | |
| show_label=True, | |
| interactive=False, | |
| width=400, | |
| container=False | |
| ) | |
| with gr.Column(scale=1): | |
| gr.Image( | |
| value="img/img1.png", | |
| label="Successful Configuration", | |
| show_label=True, | |
| interactive=False, | |
| width=400, | |
| container=False | |
| ) | |
| gr.Markdown(""" | |
| **Configuration Status Indicators:** | |
| - ❌ Red X: API key not configured or invalid | |
| - ✅ Green check: All settings configured correctly | |
| - 🔄 Building: Space is updating with new changes | |
| """) | |
| with gr.Accordion("🔧 Troubleshooting", open=False): | |
| gr.Markdown(""" | |
| ### Common Issues and Solutions | |
| **Build Errors** | |
| - Check requirements.txt compatibility | |
| - Ensure Gradio version ≥ 5.39.0 | |
| - Verify all dependencies are available | |
| **API Errors** | |
| - Verify API_KEY is set correctly | |
| - Check API key starts with 'sk-or-' | |
| - Ensure you have API credits | |
| **Access Issues** | |
| - ACCESS_CODE must match exactly | |
| - Check for extra spaces in password | |
| - Verify secret is properly saved | |
| **Preview Not Working** | |
| - Set API_KEY in local environment | |
| - Check browser console for errors | |
| - Ensure configuration is saved | |
| **Configuration Status Shows Red X:** | |
| - Verify API key secret name matches configuration | |
| - Check OpenRouter account has credits | |
| - Regenerate API key if needed | |
| """) | |
| with gr.Accordion("🎨 Template System", open=False): | |
| gr.Markdown(""" | |
| ### Available Templates | |
| - **STEM Adventure Games**: Interactive STEM learning | |
| - **Socratic Dialogue Partner**: Philosophical discussions | |
| - **Business Strategy Advisor**: Strategic planning assistant | |
| - **Creative Writing Coach**: Writing improvement helper | |
| - **Research Assistant**: Academic research support | |
| ### Template Features | |
| - Pre-configured prompts and examples | |
| - Optimized model settings | |
| - Relevant grounding URLs | |
| - Domain-specific system prompts | |
| ### Custom Values | |
| - Your custom settings are preserved | |
| - Switch templates without losing work | |
| - Return to "None (Custom)" to restore | |
| """) | |
| with gr.Accordion("💡 Tips & Best Practices", open=False): | |
| gr.Markdown(""" | |
| ### System Prompts | |
| - Be specific about capabilities | |
| - Include examples of desired behavior | |
| - Set clear boundaries and limitations | |
| ### Model Selection | |
| - Gemini Flash: Fast, cost-effective | |
| - Claude Sonnet: High quality reasoning | |
| - GPT-4: Broad knowledge base | |
| - Llama: Open source alternative | |
| ### URL Grounding | |
| - Use authoritative sources | |
| - Keep URLs up to date | |
| - Primary URLs load on every request | |
| - Secondary URLs provide additional context | |
| ### Security | |
| - Never commit API keys to code | |
| - Use environment variables only | |
| - Enable ACCESS_CODE for sensitive Spaces | |
| - Regularly rotate API keys | |
| """) | |
| with gr.Accordion("📚 Additional Resources", open=False): | |
| gr.Markdown(""" | |
| ### Documentation Links | |
| **HuggingFace** | |
| - [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** | |
| - [API Keys](https://openrouter.ai/keys) | |
| - [Model Comparison](https://openrouter.ai/models) | |
| - [Pricing](https://openrouter.ai/docs#models) | |
| **Gradio** | |
| - [Chat Interface](https://gradio.app/docs/chatinterface) | |
| - [Components](https://gradio.app/docs/) | |
| - [Sharing Apps](https://gradio.app/sharing-your-app/) | |
| **Community Support** | |
| - [HuggingFace Forums](https://discuss.huggingface.co/) | |
| - [Gradio Discord](https://discord.gg/feTf9x3ZSB) | |
| """) | |
| 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('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 |