import React, { useState, useCallback } from 'react'; import { Send, Sparkles, Wand2, Copy, AlertTriangle, Loader2, Info } from 'lucide-react'; // API Key should be empty string; Canvas will provide the actual key at runtime. const apiKey = ""; const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`; const MODEL_NAME = "gemini-2.5-flash-preview-09-2025"; // System instruction to guide the LLM's behavior as a prompt engineer. const SYSTEM_INSTRUCTION = `You are a world-class AI Prompt Engineer and Optimizer. Your task is to take a simple, initial user prompt and enhance it into a highly detailed, specific, and effective prompt for a Large Language Model (LLM). The enhanced prompt must adhere to the following best practices: 1.  **Define a Clear Persona/Role:** Start by assigning the model a specific role (e.g., "Act as a senior copywriter," "You are a Python expert"). 2.  **State the Goal and Context:** Clearly articulate the final objective and any relevant background information. 3.  **Specify Constraints:** Use specific numbers, limits, and rules (e.g., "Use exactly 3 paragraphs," "Keep the tone professional," "Target a high school student audience"). 4.  **Define the Output Format:** Explicitly request the format (e.g., "Return the result as a Markdown list," "Provide a JSON object," "Use H2 headings for sections"). 5.  **Include Chain-of-Thought (CoT) Instruction (Crucial):** Instruct the model to think step-by-step before providing the final output, using a structure like: "FIRST, outline the key steps to solve the problem. SECOND, execute the steps. THIRD, present the final answer in the requested format." You MUST only return the final, improved prompt text. Do NOT include any conversational framing, headings (like "Enhanced Prompt:"), or explanations in your output. Just the prompt itself.`; // Helper function to handle exponential backoff for API calls const fetchWithRetry = async (url, options, retries = 3) => { for (let i = 0; i < retries; i++) { try { const response = await fetch(url, options); if (!response.ok) { // If it's a 4xx or 5xx, try again (except 401/403 which are fatal) if (response.status >= 400 && response.status !== 401 && response.status !== 403) { throw new Error(`HTTP error! status: ${response.status}`); } } return response; } catch (error) { if (i < retries - 1) { const delay = Math.pow(2, i) * 1000 + Math.random() * 1000; // console.warn(`API call failed, retrying in ${delay}ms...`, error.message); await new Promise(resolve => setTimeout(resolve, delay)); } else { throw error; } } } // Should never reach here if retries > 0 throw new Error("API call failed after all retries."); }; const App = () => { const [originalPrompt, setOriginalPrompt] = useState(''); const [enhancedPrompt, setEnhancedPrompt] = useState(''); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [copied, setCopied] = useState(false); const handleEnhancePrompt = useCallback(async () => { if (!originalPrompt.trim()) { setError("Please enter an initial prompt to enhance."); return; } setIsLoading(true); setError(null); setEnhancedPrompt(''); setCopied(false); const userQuery = `Enhance the following basic prompt using all best practices: "${originalPrompt}"`; const payload = { contents: [{ parts: [{ text: userQuery }] }], systemInstruction: { parts: [{ text: SYSTEM_INSTRUCTION }] }, }; try { const response = await fetchWithRetry(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); const result = await response.json(); const text = result?.candidates?.[0]?.content?.parts?.[0]?.text || "Could not generate an enhanced prompt. Please try again with a different query."; setEnhancedPrompt(text); } catch (err) { console.error("Gemini API Error:", err); setError("Failed to enhance prompt. Check console for details."); setEnhancedPrompt("Error: Prompt enhancement failed."); } finally { setIsLoading(false); } }, [originalPrompt]); const handleCopy = () => { const tempTextArea = document.createElement('textarea'); tempTextArea.value = enhancedPrompt; document.body.appendChild(tempTextArea); tempTextArea.select(); try { document.execCommand('copy'); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch (err) { console.error('Could not copy text: ', err); setError('Failed to copy text.'); } document.body.removeChild(tempTextArea); }; return (
{/* Header Section */}

AI Prompt Optimizer

Transform vague ideas into crystal-clear instructions for powerful, consistent AI results.

{/* Blog Link - UPDATED */} Learn more about prompt engineering on our blog!
{/* Main Description/Guidance */}

Enter a simple, basic request below. The optimizer will add professional role definition, constraints, format requirements, and Chain-of-Thought (CoT) logic to maximize the quality of your AI output.

{/* Input Area */}