Spaces:
Running
Running
| ts | |
| import { AIModel, AICategory, OptimizationRequest, OptimizationResult } from '@/types' | |
| import { getModelById } from './constants' | |
| import { estimateTokenCount } from './validation' | |
| /** | |
| * Main prompt optimization engine | |
| * Handles different optimization strategies based on AI model category | |
| */ | |
| export class PromptOptimizer { | |
| /** | |
| * Optimizes a prompt for a specific AI model | |
| */ | |
| static async optimize(request: OptimizationRequest): Promise<OptimizationResult> { | |
| const startTime = performance.now() | |
| const model = getModelById(request.targetModel) | |
| if (!model) { | |
| throw new Error(`Unknown AI model: ${request.targetModel}`) | |
| } | |
| let optimizedPrompt = request.prompt | |
| const improvements: string[] = [] | |
| try { | |
| switch (model.category) { | |
| case 'llm': | |
| optimizedPrompt = this.optimizeForLLM(request.prompt, request.targetModel) | |
| improvements.push('Strukturiert nach Rolle-Kontext-Aufgabe-Format') | |
| improvements.push('Klare Abschnitte und Spezifität hinzugefügt') | |
| improvements.push('Output-Format-Anweisungen definiert') | |
| break | |
| case 'code': | |
| optimizedPrompt = this.optimizeForCode(request.prompt, request.targetModel) | |
| improvements.push('Technologie-Stack spezifiziert') | |
| improvements.push('Funktionale Anforderungen detailliert') | |
| improvements.push('Code-Stil und Best Practices definiert') | |
| improvements.push('Error-Handling-Anforderungen hinzugefügt') | |
| break | |
| case 'image': | |
| optimizedPrompt = this.optimizeForImage(request.prompt, request.targetModel) | |
| improvements.push('Stilbeschreibungen erweitert') | |
| improvements.push('Technische Parameter hinzugefügt') | |
| improvements.push('Beleuchtung und Stimmung spezifiziert') | |
| improvements.push('Subjekt-Umgebung-Stil-Format strukturiert') | |
| break | |
| case 'special': | |
| optimizedPrompt = this.optimizeForSpecial(request.prompt, request.targetModel) | |
| improvements.push('Tool-spezifische Best Practices implementiert') | |
| improvements.push('Relevante Parameter und Constraints hinzugefügt') | |
| break | |
| default: | |
| optimizedPrompt = this.optimizeGeneric(request.prompt) | |
| improvements.push('Allgemeine Verbesserungen angewendet') | |
| } | |
| const executionTime = performance.now() - startTime | |
| const tokenEstimate = estimateTokenCount(optimizedPrompt.length) | |
| return { | |
| originalPrompt: request.prompt, | |
| optimizedPrompt, | |
| targetModel: request.targetModel, | |
| improvements, | |
| executionTime: Math.round(executionTime), | |
| tokenEstimate | |
| } | |
| } catch (error) { | |
| throw new Error(`Optimization failed: ${error instanceof Error ? error.message : 'Unknown error'}`) | |
| } | |
| } | |
| /** | |
| * Optimizes prompts for LLM models (ChatGPT, Claude, Gemini, etc.) | |
| */ | |
| private static optimizeForLLM(prompt: string, model: AIModel): string { | |
| let optimized = prompt.trim() | |
| // Add role-context-task structure if missing | |
| if (!this.hasStructure(optimized)) { | |
| optimized = this.addStructure(optimized, model) | |
| } | |
| // Enhance specificity | |
| optimized = this.enhanceSpecificity(optimized) | |
| // Add output format specification | |
| optimized = this.addOutputFormat(optimized, model) | |
| // Add context enhancement based on model capabilities | |
| optimized = this.addModelSpecificEnhancements(optimized, model) | |
| return optimized | |
| } | |
| /** | |
| * Optimizes prompts for code generation tools | |
| */ | |
| private static optimizeForCode(prompt: string, model: AIModel): string { | |
| let optimized = prompt.trim() | |
| // Add technology stack specification if missing | |
| if (!this.hasTechStack(optimized)) { | |
| optimized = this.addTechStack(optimized) | |
| } | |
| // Add functional requirements | |
| optimized = this.addFunctionalRequirements(optimized) | |
| // Add coding style guidelines | |
| optimized = this.addCodingStyle(optimized) | |
| // Add error handling requirements | |
| optimized = this.addErrorHandling(optimized) | |
| return optimized | |
| } | |
| /** | |
| * Optimizes prompts for image generation models | |
| */ | |
| private static optimizeForImage(prompt: string, model: AIModel): string { | |
| let optimized = prompt.trim() | |
| // Structure as subject-environment-style format | |
| if (!this.hasImageStructure(optimized)) { | |
| optimized = this.addImageStructure(optimized) | |
| } | |
| // Add style descriptions | |
| optimized = this.enhanceStyleDescriptions(optimized) | |
| // Add technical parameters | |
| optimized = this.addTechnicalParameters(optimized, model) | |
| // Add lighting and mood specifications | |
| optimized = this.addLightingMood(optimized) | |
| return optimized | |
| } | |
| /** | |
| * Optimizes prompts for specialized tools | |
| */ | |
| private static optimizeForSpecial(prompt: string, model: AIModel): string { | |
| let optimized = prompt.trim() | |
| // Tool-specific optimizations based on known capabilities | |
| switch (model) { | |
| case 'base44': | |
| optimized = this.optimizeForBase44(optimized) | |
| break | |
| default: | |
| optimized = this.optimizeGeneric(optimized) | |
| } | |
| return optimized | |
| } | |
| /** | |
| * Generic optimization for unknown or general cases | |
| */ | |
| private static optimizeGeneric(prompt: string): string { | |
| let optimized = prompt.trim() | |
| // Basic improvements | |
| optimized = this.enhanceClarity(optimized) | |
| optimized = this.addExamples(optimized) | |
| return optimized | |
| } | |
| // LLM-specific helper methods | |
| private static hasStructure(prompt: string): boolean { | |
| return /^(rolle|role|kontext|context|aufgabe|task)/i.test(prompt) | |
| } | |
| private static addStructure(prompt: string, model: AIModel): string { | |
| const context = this.extractContext(prompt) | |
| const task = this.extractTask(prompt) | |
| return `Rolle: Du bist ein Experte in der Anwendung von ${getModelDisplayName(model)}. | |
| Kontext: ${context || 'Ein allgemeines Anliegen, das optimierte Antworten erfordert.'} | |
| Aufgabe: ${task || prompt} | |
| Anforderungen: | |
| - Gib präzise und gut strukturierte Antworten | |
| - Verwende klare Beispiele wo angebracht | |
| - Berücksichtige verschiedene Perspektiven` | |
| } | |
| private static enhanceSpecificity(prompt: string): string { | |
| // Add specificity enhancers | |
| let enhanced = prompt | |
| if (!/beispiel|example/i.test(prompt)) { | |
| enhanced += '\n\nBeispiele: Füge relevante Beispiele hinzu, um die Antwort zu veranschaulichen.' | |
| } | |
| if (!/details|detailliert/i.test(prompt)) { | |
| enhanced += '\nDetailgrad: Gehe ins Detail, wo es für das Verständnis wichtig ist.' | |
| } | |
| return enhanced | |
| } | |
| private static addOutputFormat(prompt: string, model: AIModel): string { | |
| const modelCapabilities = this.getModelCapabilities(model) | |
| return `${prompt} | |
| Ausgabeformat: | |
| - Verwende ${modelCapabilities.supportedFormats.join(', ')} wenn angemessen | |
| - ${modelCapabilities.preferredStructure} | |
| - Strukturiere komplexe Informationen in Listen oder Tabellen` | |
| } | |
| // Code-specific helper methods | |
| private static hasTechStack(prompt: string): boolean { | |
| return /(typescript|javascript|react|node\.js|python|java|technologie|framework)/i.test(prompt) | |
| } | |
| private static addTechStack(prompt: string): string { | |
| return `Technologie-Stack: [Bitte spezifiziere die gewünschte Technologie] | |
| ${prompt} | |
| Zusätzliche Anforderungen: | |
| - Verwende moderne Best Practices | |
| - Implementiere ausreichende Dokumentation | |
| - Berücksichtige Sicherheitsaspekte | |
| - Optimiere für Performance` | |
| } | |
| private static addFunctionalRequirements(prompt: string): string { | |
| return `${prompt} | |
| Funktionale Anforderungen: | |
| - Definiere klare Eingabeparameter | |
| - Implementiere robuste Fehlerbehandlung | |
| - Füge Logging und Monitoring hinzu | |
| - Stelle sicher, dass der Code modular und wiederverwendbar ist` | |
| } | |
| private static addCodingStyle(prompt: string): string { | |
| return `${prompt} | |
| Code-Stil und Standards: | |
| - Verwende aussagekräftige Variablennamen | |
| - Folge den Konventionen der jeweiligen Programmiersprache | |
| - Kommentiere komplexe Logik angemessen | |
| - Implementiere Unit-Tests für kritische Funktionen` | |
| } | |
| private static addErrorHandling(prompt: string): string { | |
| return `${prompt} | |
| Error-Handling: | |
| - Implementiere try-catch Blöcke wo nötig | |
| - Validiere alle Eingabeparameter | |
| - Gebe aussagekräftige Fehlermeldungen zurück | |
| - Logging für Debugging-Zwecke | |
| - Graceful Degradation bei Fehlern` | |
| } | |
| // Image-specific helper methods | |
| private static hasImageStructure(prompt: string): boolean { | |
| return /(subjekt|subject|objekt|umgebung|environment|hintergrund|background|stil|style)/i.test(prompt) | |
| } | |
| private static addImageStructure(prompt: string): string { | |
| return `Subjekt: ${this.extractMainSubject(prompt) || 'Hauptobjekt der Szene'} | |
| Umgebung: ${this.extractEnvironment(prompt) || 'Neutraler oder passender Hintergrund'} | |
| Stil: ${this.extractStyle(prompt) || 'Realistisch, hochauflösend'} | |
| Beschreibung: ${prompt}` | |
| } | |
| private static enhanceStyleDescriptions(prompt: string): string { | |
| let enhanced = prompt | |
| // Add style enhancers if not present | |
| if (!/artistic|künstlerisch|realistic|realistisch/i.test(prompt)) { | |
| enhanced += '\n\nStileigenschaften: Realistisch, hochdetailliert, professionelle Qualität' | |
| } | |
| return enhanced | |
| } | |
| private static addTechnicalParameters(prompt: string, model: AIModel): string { | |
| const params = this.getImageParametersForModel(model) | |
| return `${prompt} | |
| Technische Parameter: | |
| - Auflösung: ${params.resolution} | |
| - Seitenverhältnis: ${params.aspectRatio} | |
| - Qualität: ${params.quality} | |
| - Stil: ${params.style}` | |
| } | |
| private static addLightingMood(prompt: string): string { | |
| return `${prompt} | |
| Beleuchtung und Stimmung: | |
| - Professionelle Beleuchtung, die das Subjekt hervorhebt | |
| - Stimmung: [Spezifiziere die gewünschte Atmosphäre] | |
| - Kontrast: Ausgewogen zwischen Schatten und Licht | |
| - Farbtemperatur: Natürlich und harmonisch` | |
| } | |
| // Special tool optimizations | |
| private static optimizeForBase44(prompt: string): string { | |
| return `${prompt} | |
| Base44-spezifische Optimierungen: | |
| - Verwende die spezifischen Parameter und Constraints des Base44-Systems | |
| - Berücksichtige die Integration mit anderen Base44-Komponenten | |
| - Optimiere für die Base44-Verarbeitungslogik` | |
| } | |
| // Utility methods | |
| private static extractContext(prompt: string): string { | |
| // Simple extraction - in a real app, this would be more sophisticated | |
| const sentences = prompt.split(/[.!?]+/).filter(s => s.trim().length > 0) | |
| return sentences.slice(0, 2).join('. ') + '.' | |
| } | |
| private static extractTask(prompt: string): string { | |
| // Extract task-oriented sentences | |
| const taskWords = /(erstelle|create|schreibe|write|entwickle|develop|analysiere|analyze)/i | |
| const sentences = prompt.split(/[.!?]+/) | |
| return sentences.find(s => taskWords.test(s)) || prompt | |
| } | |
| private static extractMainSubject(prompt: string): string { | |
| // Simple subject extraction | |
| const words = prompt.split(/\s+/) | |
| return words.slice(0, 3).join(' ') | |
| } | |
| private static extractEnvironment(prompt: string): string { | |
| // Check for environment indicators | |
| const envWords = /(in|at|umgebung|environment|background|hintergrund)/i | |
| const match = prompt.match(new RegExp(`${envWords.source}\\s+([^,\\.]+)`, 'i')) | |
| return match ? match[1] : '' | |
| } | |
| private static extractStyle(prompt: string): string { | |
| // Check for style indicators | |
| const styleWords = /(stil|style|artistic|künstlerisch|realistic|realistisch)/i | |
| const match = prompt.match(new RegExp(`${styleWords.source}\\s*:?\\s*([^,\\.]+)`, 'i')) | |
| return match ? match[1] : '' | |
| } | |
| private static enhanceClarity(prompt: string): string { | |
| // Basic clarity improvements | |
| let enhanced = prompt.replace(/\s+/g, ' ').trim() | |
| // Ensure proper punctuation | |
| if (!/[.!?]$/.test(enhanced)) { | |
| enhanced += '.' | |
| } | |
| return enhanced | |
| } | |
| private static addExamples(prompt: string): string { | |
| return `${prompt} | |
| Beispiele: | |
| - Füge konkrete Beispiele hinzu, um die Anfrage zu veranschaulichen | |
| - Verwende relevante Referenzen aus demselben Bereich | |
| - Zeige verschiedene Ansätze oder Lösungswege` | |
| } | |
| private static getModelDisplayName(model: AIModel): string { | |
| const displayNames: Record<AIModel, string> = { | |
| 'gpt-5': 'GPT-5', | |
| 'gpt-5.1': 'GPT-5.1', | |
| 'claude-4.5-opus': 'Claude 4.5 Opus', | |
| 'claude-4.5-sonnet': 'Claude 4.5 Sonnet', | |
| 'claude-4.5-haiku': 'Claude 4.5 Haiku', | |
| 'gemini-3-pro': 'Gemini 3 Pro', | |
| 'llama-3': 'Llama 3', | |
| 'mistral-large': 'Mistral Large', | |
| 'mixtral': 'Mixtral', | |
| 'minimax2': 'MiniMax2', | |
| 'kimik2': 'KimiK2', | |
| 'deepseek': 'DeepSeek', | |
| 'qwen3': 'Qwen3', | |
| 'manus': 'MANUS', | |
| 'replit-agent': 'Replit Agent', | |
| 'bolt-new': 'Bolt.new', | |
| 'v0-dev': 'v0.dev', | |
| 'cursor-ai': 'Cursor AI', | |
| 'github-copilot': 'GitHub Copilot', | |
| 'google-antigravity': 'Google Antigravity', | |
| 'kiro': 'Kiro', | |
| 'minimax-agent': 'MiniMax Agent', | |
| 'base44': 'Base44', | |
| 'midjourney': 'Midjourney', | |
| 'dall-e-3': 'DALL-E 3', | |
| 'stable-diffusion': 'Stable Diffusion', | |
| 'runwayml': 'RunwayML' | |
| } | |
| return displayNames[model] || model | |
| } | |
| private static getModelCapabilities(model: AIModel) { | |
| const llmModels = ['gpt-5', 'gpt-5.1', 'claude-4.5-opus', 'claude-4.5-sonnet', 'claude-4.5-haiku'] | |
| const supportsStructured = llmModels.includes(model) | |
| return { | |
| supportedFormats: supportsStructured | |
| ? ['Listen', 'Tabellen', 'JSON', 'strukturierte Absätze'] | |
| : ['Text', 'Listen', 'Formatierte Absätze'], | |
| preferredStructure: supportsStructured | |
| ? 'Strukturiere komplexe Informationen in klaren Abschnitten' | |
| : 'Verwende klare und lesbare Formatierung' | |
| } | |
| } | |
| private static getImageParametersForModel(model: AIModel) { | |
| const params: Record<AIModel, any> = { | |
| 'midjourney': { | |
| resolution: '1024x1024 oder höher', | |
| aspectRatio: '1:1, 16:9, 4:3 (je nach Bedarf)', | |
| quality: 'Hoch', | |
| style: 'Künstlerisch, detailreich' | |
| }, | |
| 'dall-e-3': { | |
| resolution: '1024x1024', | |
| aspectRatio: '1:1', | |
| quality: 'Hoch', | |
| style: 'Realistisch, professionell' | |
| }, | |
| 'stable-diffusion': { | |
| resolution: '512x512 oder 768x768', | |
| aspectRatio: '1:1', | |
| quality: 'Mittel bis Hoch', | |
| style: 'Vielseitig, anpassbar' | |
| }, | |
| 'runwayml': { | |
| resolution: 'Variable', | |
| aspectRatio: 'Anpassbar', | |
| quality: 'Professionell', | |
| style: 'Kreativ, videofokussiert' | |
| } | |
| } | |
| return params[model] || { | |
| resolution: '1024x1024', | |
| aspectRatio: '1:1', | |
| quality: 'Hoch', | |
| style: 'Realistisch' | |
| } | |
| } | |
| } | |
| </html> |