# Model Playground Feature

## 🎯 Overview

The **Model Playground** is an interactive testing environment that allows users to experiment with different AI models directly from the Models page. It replaces the previous "view details" functionality with a comprehensive testing interface that adapts to each model type.

## 🔧 Features

### **Model Type-Specific Interfaces**

The playground automatically adapts its interface based on the model type:

#### **1. LLM (Large Language Model)**
- **Input**: Text area for prompts and conversations
- **Settings**: Temperature, max tokens, top-p, frequency penalty, presence penalty
- **Output**: Generated text responses
- **Use Cases**: Chat completion, content generation, text analysis

#### **2. ASR (Automatic Speech Recognition)**
- **Input**: Audio recording or file upload
- **Settings**: Language selection, timestamps, word confidence, diarization
- **Output**: Transcribed text
- **Use Cases**: Speech-to-text conversion, audio transcription

#### **3. TTS (Text-to-Speech)**
- **Input**: Text area for speech synthesis
- **Settings**: Voice selection, speed, pitch, format, quality
- **Output**: Audio generation results
- **Use Cases**: Text-to-speech conversion, voice synthesis

#### **4. Embedding**
- **Input**: Text for vectorization
- **Settings**: Dimensions, truncation, encoding
- **Output**: Embedding vectors
- **Use Cases**: Text vectorization, similarity search

#### **5. Classification**
- **Input**: Text for classification
- **Settings**: Confidence threshold, return labels/scores
- **Output**: Classification results with confidence scores
- **Use Cases**: Sentiment analysis, intent classification

#### **6. Generation**
- **Input**: Text description + optional reference image
- **Settings**: Size, quality, style, format
- **Output**: Generated content (images, audio, etc.)
- **Use Cases**: Image generation, content creation

## 🚀 Usage

### **Accessing the Playground**

1. Navigate to the **Models** page
2. Find the model you want to test
3. Click the **🧪 TestTube icon** in the Actions column
4. The playground will open in a modal window

### **Testing Workflow**

1. **Select Input Method**: Choose appropriate input method for your model type
2. **Configure Settings**: Adjust model parameters as needed
3. **Process**: Click the "Process" button to run the model
4. **Review Output**: View results and copy if needed
5. **History**: Access previous test results from the sidebar

### **Input Methods**

#### **Text Input**
- Standard text area for LLM, TTS, Embedding, and Classification models
- Placeholder text guides users on expected input format

#### **Audio Recording (ASR)**
- **Start Recording**: Click to begin audio capture
- **Stop Recording**: Click to end and process audio
- **Upload Audio**: Alternative file upload option
- **Playback**: Preview recorded audio before processing

#### **File Upload**
- **Audio Files**: For ASR models
- **Image Files**: For Generation models (reference images)
- **Preview**: Visual preview of uploaded files

## ⚙️ Settings Configuration

### **LLM Settings**
```typescript
{
  temperature: 0.7,        // Creativity (0-2)
  maxTokens: 1000,         // Response length
  topP: 1.0,              // Nucleus sampling
  frequencyPenalty: 0,     // Reduce repetition
  presencePenalty: 0,      // Encourage new topics
  systemPrompt: ''         // System instructions
}
```

### **ASR Settings**
```typescript
{
  language: 'auto',        // Language detection
  timestamp: false,        // Include timestamps
  wordConfidence: false,   // Word-level confidence
  diarization: false       // Speaker identification
}
```

### **TTS Settings**
```typescript
{
  voice: 'alloy',          // Voice selection
  speed: 1.0,              // Playback speed
  pitch: 0,                // Pitch adjustment
  format: 'mp3',           // Audio format
  quality: 'standard'      // Audio quality
}
```

### **Generation Settings**
```typescript
{
  size: '1024x1024',       // Output dimensions
  quality: 'standard',     // Generation quality
  style: 'vivid',          // Artistic style
  format: 'url'            // Output format
}
```

## 📊 History & Persistence

### **Test History**
- **Automatic Logging**: All test inputs and outputs are saved
- **Quick Access**: Click on history items to reload previous tests
- **Clear History**: Option to clear all history for a model

### **Session Management**
- **State Persistence**: Settings and inputs persist during session
- **Model Switching**: Clean state when switching between models
- **Error Recovery**: Graceful handling of processing errors

## 🎨 User Interface

### **Layout**
```
┌─────────────────────────────────────────────────────────────┐
│                    Model Playground Header                   │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────────┐    ┌─────────────────────────────────┐ │
│  │   Input Section │    │         History Sidebar         │ │
│  │                 │    │                                 │ │
│  ├─────────────────┤    │                                 │ │
│  │  Settings Panel │    │                                 │ │
│  │                 │    │                                 │ │
│  ├─────────────────┤    │                                 │ │
│  │  Process Button │    │                                 │ │
│  │                 │    │                                 │ │
│  ├─────────────────┤    │                                 │ │
│  │  Output Section │    │                                 │ │
│  └─────────────────┘    └─────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```

### **Responsive Design**
- **Desktop**: Full-width layout with sidebar
- **Tablet**: Collapsible sidebar
- **Mobile**: Stacked layout for better usability

## 🔌 Integration

### **Model API Integration**
The playground is designed to integrate with actual model APIs:

```typescript
// Example integration for LLM
const processLLM = async (input: string, settings: any) => {
  const response = await fetch('/api/models/llm/process', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ input, settings, modelId: model.uuid })
  });
  return response.json();
};
```

### **Real-time Processing**
- **Progress Indicators**: Show processing status
- **Streaming Support**: For long-running operations
- **Error Handling**: Graceful error display and recovery

## 🧪 Testing

### **Component Testing**
```bash
# Run playground tests
npm test ModelPlayground.test.tsx
```

### **Test Coverage**
- ✅ Model type detection
- ✅ Input validation
- ✅ Settings configuration
- ✅ Error handling
- ✅ History management
- ✅ Responsive design

## 🚀 Future Enhancements

### **Planned Features**
1. **Batch Processing**: Test multiple inputs at once
2. **Export Results**: Download test results as JSON/CSV
3. **Model Comparison**: Side-by-side model testing
4. **Custom Prompts**: Save and reuse prompt templates
5. **Performance Metrics**: Track response times and accuracy
6. **Collaboration**: Share playground sessions with team members

### **Advanced Settings**
1. **Model Fine-tuning**: Adjust model parameters
2. **Custom APIs**: Integration with external model APIs
3. **Webhook Support**: Real-time result delivery
4. **A/B Testing**: Compare different model configurations

## 📚 API Reference

### **ModelPlayground Props**
```typescript
interface ModelPlaygroundProps {
  model: Model;              // Model to test
  isOpen: boolean;           // Playground visibility
  onClose: () => void;       // Close handler
}
```

### **PlaygroundState**
```typescript
interface PlaygroundState {
  input: string;             // Current input
  output: string;            // Current output
  isProcessing: boolean;     // Processing status
  error: string | null;      // Error message
  settings: any;             // Model settings
  history: Array<{           // Test history
    input: string;
    output: string;
    timestamp: Date;
  }>;
}
```

## 🎯 Benefits

### **For Users**
- **Easy Testing**: No need to write code or use external tools
- **Visual Feedback**: Immediate results and error messages
- **Parameter Tuning**: Real-time adjustment of model settings
- **History Tracking**: Keep track of successful configurations

### **For Developers**
- **Rapid Prototyping**: Quick model validation and testing
- **Debugging**: Easy identification of model issues
- **Performance Analysis**: Track model response times
- **User Feedback**: Understand how users interact with models

### **For Teams**
- **Collaboration**: Share playground sessions
- **Documentation**: Built-in test documentation
- **Quality Assurance**: Systematic model testing
- **Training**: Onboard new team members quickly

---

**🎉 The Model Playground is now ready for production use!** 