import { useState, useEffect } from 'react' import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { BookOpen, Brain, Zap, Download, Trash2, Loader2, Info, CheckCircle, Cloud, HardDrive, Bot, MessageSquare, Users, Star, Heart, Share, Copy } from 'lucide-react' interface ModelInfo { model_name: string name: string supports_thinking: boolean description: string size_gb: string is_loaded: boolean type: 'local' | 'api' } interface ModelsResponse { models: ModelInfo[] current_model: string } // Community template interface interface CommunityTemplate { id: string name: string description: string author: string category: string tags: string[] model: string systemPrompt: string temperature: number maxTokens: number likes: number downloads: number isOfficial: boolean createdAt: string } // Get predefined community templates function getCommunityTemplates(): CommunityTemplate[] { return [ { id: 'code-reviewer', name: 'Code Review Expert', description: 'Professional code reviewer that provides detailed analysis, suggests improvements, and identifies potential issues.', author: 'EdgeLLM Team', category: 'coding', tags: ['code review', 'programming', 'best practices'], model: 'Qwen/Qwen3-30B-A3B', systemPrompt: 'You are a senior software engineer specializing in code review. Analyze the provided code for:\n\n1. **Code Quality**: Structure, readability, maintainability\n2. **Best Practices**: Following language conventions and patterns\n3. **Performance**: Potential optimizations and bottlenecks\n4. **Security**: Common vulnerabilities and security issues\n5. **Testing**: Testability and edge cases\n\nProvide constructive feedback with specific examples and actionable suggestions.', temperature: 0.3, maxTokens: 1500, likes: 245, downloads: 1200, isOfficial: true, createdAt: '2024-01-15' }, { id: 'writing-tutor', name: 'Academic Writing Tutor', description: 'Helps improve academic writing with structure suggestions, grammar corrections, and clarity enhancements.', author: 'Academic Guild', category: 'writing', tags: ['academic writing', 'essay', 'research'], model: 'Qwen/Qwen3-30B-A3B', systemPrompt: 'You are an experienced academic writing tutor. Help users improve their writing by:\n\n1. **Structure & Organization**: Clear thesis, logical flow, proper transitions\n2. **Clarity & Precision**: Eliminate ambiguity, improve word choice\n3. **Academic Style**: Formal tone, appropriate citations, scholarly voice\n4. **Grammar & Mechanics**: Correct errors, improve sentence variety\n5. **Argument Development**: Strengthen evidence, address counterarguments\n\nProvide specific feedback with examples and rewrite suggestions where helpful.', temperature: 0.4, maxTokens: 1200, likes: 189, downloads: 856, isOfficial: false, createdAt: '2024-01-20' }, { id: 'data-analyst', name: 'Data Analysis Assistant', description: 'Helps analyze data, create visualizations, and explain statistical concepts in simple terms.', author: 'DataPro', category: 'analysis', tags: ['data science', 'statistics', 'visualization'], model: 'Qwen/Qwen3-30B-A3B', systemPrompt: 'You are a data analysis expert. Help users understand and analyze data by:\n\n1. **Data Exploration**: Identify patterns, outliers, relationships\n2. **Statistical Analysis**: Apply appropriate tests, interpret results\n3. **Visualization**: Suggest effective charts and graphs\n4. **Insights**: Draw meaningful conclusions from data\n5. **Communication**: Explain complex concepts simply\n\nProvide step-by-step analysis and practical recommendations.', temperature: 0.2, maxTokens: 1000, likes: 156, downloads: 643, isOfficial: false, createdAt: '2024-01-25' }, { id: 'creative-writer', name: 'Creative Writing Coach', description: 'Inspires creativity and helps develop compelling stories, characters, and narrative techniques.', author: 'StoryMaster', category: 'creative', tags: ['creative writing', 'storytelling', 'fiction'], model: 'Qwen/Qwen3-30B-A3B', systemPrompt: 'You are a creative writing coach with expertise in storytelling. Help writers by:\n\n1. **Story Development**: Plot structure, pacing, conflict resolution\n2. **Character Creation**: Compelling personalities, realistic dialogue, character arcs\n3. **World Building**: Consistent settings, atmosphere, details\n4. **Writing Techniques**: Show vs tell, point of view, voice\n5. **Inspiration**: Creative prompts, overcoming writer\'s block\n\nProvide encouraging feedback and concrete suggestions to enhance creativity.', temperature: 0.8, maxTokens: 1200, likes: 312, downloads: 987, isOfficial: false, createdAt: '2024-01-30' }, { id: 'interview-prep', name: 'Interview Preparation Coach', description: 'Helps prepare for job interviews with practice questions, answer strategies, and confidence building.', author: 'CareerBoost', category: 'career', tags: ['interview', 'job search', 'career'], model: 'Qwen/Qwen3-30B-A3B', systemPrompt: 'You are a professional career coach specializing in interview preparation. Help candidates by:\n\n1. **Question Practice**: Common and behavioral interview questions\n2. **Answer Framework**: STAR method, structured responses\n3. **Company Research**: Industry insights, company-specific preparation\n4. **Confidence Building**: Reducing anxiety, improving presentation\n5. **Follow-up**: Thank you notes, next steps\n\nProvide personalized advice and realistic practice scenarios.', temperature: 0.5, maxTokens: 1000, likes: 278, downloads: 1456, isOfficial: true, createdAt: '2024-02-05' } ] } export function Models() { const [models, setModels] = useState([]) const [loading, setLoading] = useState(true) const [modelLoading, setModelLoading] = useState(null) const [savedAssistants, setSavedAssistants] = useState([]) const [communityTemplates] = useState(getCommunityTemplates()) const [likedTemplates, setLikedTemplates] = useState([]) useEffect(() => { fetchModels() loadSavedAssistants() loadLikedTemplates() }, []) const loadSavedAssistants = () => { try { const assistants = JSON.parse(localStorage.getItem('savedAssistants') || '[]') setSavedAssistants(assistants) } catch (error) { console.error('Failed to load saved assistants:', error) setSavedAssistants([]) } } const loadAssistant = (assistant: any) => { // Store the assistant config in localStorage for the playground to use localStorage.setItem('loadAssistantConfig', JSON.stringify(assistant)) // Navigate to playground window.location.href = '/playground' } const deleteAssistant = (assistantId: string) => { const updatedAssistants = savedAssistants.filter(a => a.id !== assistantId) setSavedAssistants(updatedAssistants) localStorage.setItem('savedAssistants', JSON.stringify(updatedAssistants)) } const loadLikedTemplates = () => { try { const liked = JSON.parse(localStorage.getItem('likedTemplates') || '[]') setLikedTemplates(liked) } catch (error) { console.error('Failed to load liked templates:', error) } } const toggleLikeTemplate = (templateId: string) => { const updatedLiked = likedTemplates.includes(templateId) ? likedTemplates.filter(id => id !== templateId) : [...likedTemplates, templateId] setLikedTemplates(updatedLiked) localStorage.setItem('likedTemplates', JSON.stringify(updatedLiked)) } const useTemplate = (template: CommunityTemplate) => { const assistantConfig = { name: template.name, description: template.description, model: template.model, systemPrompt: template.systemPrompt, temperature: template.temperature, maxTokens: template.maxTokens } localStorage.setItem('loadAssistantConfig', JSON.stringify(assistantConfig)) window.location.href = '/playground' } const shareMyAssistant = (assistant: any) => { // In a real implementation, this would submit to a backend // For now, we'll just show a success message alert(`"${assistant.name}" has been shared to the community! (This is a demo - in production, it would be submitted for review.)`) } const fetchModels = async () => { try { const baseUrl = `${window.location.protocol}//${window.location.host}` const res = await fetch(`${baseUrl}/models`) if (res.ok) { const data: ModelsResponse = await res.json() setModels(data.models) } } catch (err) { console.error('Failed to fetch models:', err) } finally { setLoading(false) } } const handleLoadModel = async (modelName: string) => { setModelLoading(modelName) try { const baseUrl = `${window.location.protocol}//${window.location.host}` const res = await fetch(`${baseUrl}/load-model`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model_name: modelName }), }) if (res.ok) { await fetchModels() } } catch (err) { console.error('Failed to load model:', err) } finally { setModelLoading(null) } } const handleUnloadModel = async (modelName: string) => { try { const baseUrl = `${window.location.protocol}//${window.location.host}` const res = await fetch(`${baseUrl}/unload-model`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model_name: modelName }), }) if (res.ok) { await fetchModels() } } catch (err) { console.error('Failed to unload model:', err) } } if (loading) { return (

Model Catalog

) } return (
{/* Header */}

Model Catalog

{/* Info Card */}

Assistant Library

Manage your custom assistants and discover community templates. Create specialized AI helpers for different tasks and workflows.

{/* Tabs */} My Assistants Community Featured Models {/* My Assistants Tab */} {savedAssistants.length > 0 ? (
{savedAssistants.map((assistant) => ( loadAssistant(assistant)} onDelete={() => deleteAssistant(assistant.id)} onShare={() => shareMyAssistant(assistant)} type="personal" /> ))}
) : (

No assistants yet

Create your first assistant by configuring parameters in the Playground and saving it.

)}
{/* Community Templates Tab */}
{communityTemplates.map((template) => ( toggleLikeTemplate(template.id)} onUse={() => useTemplate(template)} /> ))}
{/* Featured Tab */}
{communityTemplates .filter(t => t.isOfficial || t.likes > 200) .map((template) => ( toggleLikeTemplate(template.id)} onUse={() => useTemplate(template)} featured={true} /> )) }
{/* Models Tab */} {/* API Models Section */}

API Models Cloud-Powered

{models.filter(m => m.type === 'api').map((model) => ( ))}
{/* Local Models Section */}

Local Models Privacy-First

{models.filter(m => m.type === 'local').map((model) => ( ))}
{/* Stats Card */} Model Statistics
{models.length}
Available Models
{models.filter(m => m.is_loaded).length}
Loaded Models
{models.filter(m => m.supports_thinking).length}
Thinking Models
) } // Assistant Card Component for personal assistants function AssistantCard({ assistant, onUse, onDelete, onShare, type = "personal" }: { assistant: any onUse: () => void onDelete: () => void onShare: () => void type?: "personal" | "community" }) { return (
{assistant.name}

{assistant.description || 'No description'}

Model: {assistant.model}
Temperature: {assistant.temperature}
Max Tokens: {assistant.maxTokens}
Created: {new Date(assistant.createdAt).toLocaleDateString()}
) } // Community Template Card Component function CommunityTemplateCard({ template, isLiked, onLike, onUse, featured = false }: { template: CommunityTemplate isLiked: boolean onLike: () => void onUse: () => void featured?: boolean }) { return (
{template.name} {template.isOfficial && ( Official )} {featured && ( )}

by {template.author}

{template.description}

{template.tags.slice(0, 3).map((tag) => ( {tag} ))}
Model: {template.model}
Temperature: {template.temperature}
Max Tokens: {template.maxTokens}
{template.likes}
{template.downloads}
{template.createdAt}
) } // ModelCard component for reusability interface ModelCardProps { model: ModelInfo modelLoading: string | null onLoad: (modelName: string) => void onUnload: (modelName: string) => void } function ModelCard({ model, modelLoading, onLoad, onUnload }: ModelCardProps) { const isApiModel = model.type === 'api' return (
{isApiModel ? ( ) : model.supports_thinking ? ( ) : ( )}
{model.name}
{isApiModel ? ( API Model ) : ( {model.supports_thinking ? "Thinking Model" : "Instruction Model"} )} {model.is_loaded && ( {isApiModel ? "Ready" : "Loaded"} )}

{model.description}

Size: {model.size_gb} {!isApiModel && Format: Safetensors} {isApiModel && Type: Cloud API}

Capabilities

Text Generation Conversation Code {model.supports_thinking && ( Reasoning )} {isApiModel && model.model_name.includes('vl') && ( Vision )}
{model.is_loaded ? (
{!isApiModel && ( )}
) : ( )}
) }