diff --git a/messages/ar.json b/messages/ar.json index 68854042..9bd5ee60 100644 --- a/messages/ar.json +++ b/messages/ar.json @@ -1172,6 +1172,8 @@ "reset": "إعادة تعيين", "copied": "تم النسخ إلى الحافظة", "runToPreview": "انقر على تشغيل لمشاهدة معاينة الأمر", + "cannotEvaluate": "لا يمكن تقييم هذا الكود.", + "onlyPromptsChat": "يتم دعم استيراد {library} فقط.", "desktopOnly": "للحاسوب فقط", "desktopOnlyDescription": "يتطلب منشئ الأوامر شاشة أكبر ليعمل بشكل صحيح. يرجى فتح هذه الصفحة على جهاز كمبيوتر مكتبي أو محمول.", "browsePrompts": "تصفح الأوامر" diff --git a/messages/de.json b/messages/de.json index bc28c1d8..ccc8a4c7 100644 --- a/messages/de.json +++ b/messages/de.json @@ -1171,7 +1171,9 @@ "run": "Ausführen", "reset": "Zurücksetzen", "copied": "In die Zwischenablage kopiert", - "runToPreview": "Klicken Sie auf Ausführen, um die Prompt-Vorschau anzuzeigen", + "runToPreview": "Klicken Sie auf Ausführen, um die Vorschau zu sehen", + "cannotEvaluate": "Dieser Code kann nicht ausgewertet werden.", + "onlyPromptsChat": "Nur {library}-Importe werden unterstützt.", "desktopOnly": "Nur für Desktop", "desktopOnlyDescription": "Der Prompt Builder benötigt einen größeren Bildschirm. Bitte öffnen Sie diese Seite auf einem Desktop- oder Laptop-Computer.", "browsePrompts": "Prompts durchsuchen" diff --git a/messages/el.json b/messages/el.json index 6c25740c..388687cc 100644 --- a/messages/el.json +++ b/messages/el.json @@ -1172,6 +1172,8 @@ "reset": "Επαναφορά", "copied": "Αντιγράφηκε στο πρόχειρο", "runToPreview": "Κάντε κλικ στο Εκτέλεση για να δείτε την προεπισκόπηση", + "cannotEvaluate": "Αυτός ο κώδικας δεν μπορεί να αξιολογηθεί.", + "onlyPromptsChat": "Υποστηρίζονται μόνο εισαγωγές {library}.", "desktopOnly": "Μόνο για υπολογιστή", "desktopOnlyDescription": "Ο Prompt Builder απαιτεί μεγαλύτερη οθόνη για να λειτουργήσει σωστά. Παρακαλώ ανοίξτε αυτή τη σελίδα σε επιτραπέζιο ή φορητό υπολογιστή.", "browsePrompts": "Περιήγηση Prompts" diff --git a/messages/en.json b/messages/en.json index cd85b9ad..bda7148b 100644 --- a/messages/en.json +++ b/messages/en.json @@ -1172,6 +1172,8 @@ "reset": "Reset", "copied": "Copied to clipboard", "runToPreview": "Click Run to see the prompt preview", + "cannotEvaluate": "This code cannot be evaluated.", + "onlyPromptsChat": "Only {library} imports are supported.", "desktopOnly": "Desktop Only", "desktopOnlyDescription": "The Prompt Builder requires a larger screen to work properly. Please open this page on a desktop or laptop computer.", "browsePrompts": "Browse Prompts" diff --git a/messages/es.json b/messages/es.json index 8d61d09a..d57180cc 100644 --- a/messages/es.json +++ b/messages/es.json @@ -1171,7 +1171,9 @@ "run": "Ejecutar", "reset": "Restablecer", "copied": "Copiado al portapapeles", - "runToPreview": "Haz clic en Ejecutar para ver la vista previa del prompt", + "runToPreview": "Haz clic en Ejecutar para ver la vista previa", + "cannotEvaluate": "Este código no puede ser evaluado.", + "onlyPromptsChat": "Solo se admiten importaciones de {library}.", "desktopOnly": "Solo escritorio", "desktopOnlyDescription": "El Constructor de Prompts requiere una pantalla más grande para funcionar correctamente. Por favor, abre esta página en una computadora de escritorio o portátil.", "browsePrompts": "Explorar Prompts" diff --git a/messages/fr.json b/messages/fr.json index 7b18b20a..a72d991f 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -1171,7 +1171,9 @@ "run": "Exécuter", "reset": "Réinitialiser", "copied": "Copié dans le presse-papiers", - "runToPreview": "Cliquez sur Exécuter pour voir l'aperçu du prompt", + "runToPreview": "Cliquez sur Exécuter pour voir l'aperçu", + "cannotEvaluate": "Ce code ne peut pas être évalué.", + "onlyPromptsChat": "Seuls les imports {library} sont pris en charge.", "desktopOnly": "Bureau uniquement", "desktopOnlyDescription": "Le Prompt Builder nécessite un écran plus grand pour fonctionner correctement. Veuillez ouvrir cette page sur un ordinateur de bureau ou portable.", "browsePrompts": "Parcourir les Prompts" diff --git a/messages/he.json b/messages/he.json index 970bcb61..c8f2aeb5 100644 --- a/messages/he.json +++ b/messages/he.json @@ -1172,6 +1172,8 @@ "reset": "איפוס", "copied": "הועתק ללוח", "runToPreview": "לחץ על הפעל כדי לראות תצוגה מקדימה", + "cannotEvaluate": "לא ניתן להעריך קוד זה.", + "onlyPromptsChat": "נתמכים רק ייבואים של {library}.", "desktopOnly": "למחשב בלבד", "desktopOnlyDescription": "בונה הפרומפטים דורש מסך גדול יותר כדי לפעול כראוי. אנא פתח דף זה במחשב שולחני או נייד.", "browsePrompts": "עיין בפרומפטים" diff --git a/messages/it.json b/messages/it.json index 856d4aab..0d3749f6 100644 --- a/messages/it.json +++ b/messages/it.json @@ -1172,6 +1172,8 @@ "reset": "Ripristina", "copied": "Copiato negli appunti", "runToPreview": "Clicca su Esegui per vedere l'anteprima del prompt", + "cannotEvaluate": "Questo codice non può essere valutato.", + "onlyPromptsChat": "Sono supportate solo le importazioni di {library}.", "desktopOnly": "Solo Desktop", "desktopOnlyDescription": "Il Prompt Builder richiede uno schermo più grande per funzionare correttamente. Si prega di aprire questa pagina su un computer desktop o laptop.", "browsePrompts": "Esplora Prompt" diff --git a/messages/ja.json b/messages/ja.json index 8e7575b3..05219b43 100644 --- a/messages/ja.json +++ b/messages/ja.json @@ -1172,6 +1172,8 @@ "reset": "リセット", "copied": "クリップボードにコピーしました", "runToPreview": "実行をクリックしてプロンプトのプレビューを表示", + "cannotEvaluate": "このコードは評価できません。", + "onlyPromptsChat": "{library}のインポートのみがサポートされています。", "desktopOnly": "デスクトップ専用", "desktopOnlyDescription": "プロンプトビルダーは、正常に動作するために大きな画面が必要です。デスクトップまたはラップトップコンピュータでこのページを開いてください。", "browsePrompts": "プロンプトを閲覧" diff --git a/messages/ko.json b/messages/ko.json index deca6956..e2b9f31b 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -1172,6 +1172,8 @@ "reset": "재설정", "copied": "클립보드에 복사됨", "runToPreview": "실행을 클릭하여 프롬프트 미리보기 표시", + "cannotEvaluate": "이 코드는 평가할 수 없습니다.", + "onlyPromptsChat": "{library} 가져오기만 지원됩니다.", "desktopOnly": "데스크톱 전용", "desktopOnlyDescription": "프롬프트 빌더는 제대로 작동하려면 더 큰 화면이 필요합니다. 데스크톱이나 노트북 컴퓨터에서 이 페이지를 열어주세요.", "browsePrompts": "프롬프트 둘러보기" diff --git a/messages/pt.json b/messages/pt.json index 9fde6f97..1a387d6f 100644 --- a/messages/pt.json +++ b/messages/pt.json @@ -1172,6 +1172,8 @@ "reset": "Redefinir", "copied": "Copiado para a área de transferência", "runToPreview": "Clique em Executar para ver a pré-visualização do prompt", + "cannotEvaluate": "Este código não pode ser avaliado.", + "onlyPromptsChat": "Apenas importações de {library} são suportadas.", "desktopOnly": "Apenas Desktop", "desktopOnlyDescription": "O Prompt Builder requer uma tela maior para funcionar corretamente. Por favor, abra esta página em um computador desktop ou laptop.", "browsePrompts": "Explorar Prompts" diff --git a/messages/ru.json b/messages/ru.json index 8b72520b..5d96b010 100644 --- a/messages/ru.json +++ b/messages/ru.json @@ -1172,6 +1172,8 @@ "reset": "Сбросить", "copied": "Скопировано в буфер обмена", "runToPreview": "Нажмите Запустить, чтобы увидеть предпросмотр промпта", + "cannotEvaluate": "Этот код не может быть выполнен.", + "onlyPromptsChat": "Поддерживаются только импорты {library}.", "desktopOnly": "Только для ПК", "desktopOnlyDescription": "Конструктор промптов требует большего экрана для корректной работы. Пожалуйста, откройте эту страницу на настольном компьютере или ноутбуке.", "browsePrompts": "Просмотреть промпты" diff --git a/messages/tr.json b/messages/tr.json index 2640ae29..05140c26 100644 --- a/messages/tr.json +++ b/messages/tr.json @@ -1171,7 +1171,9 @@ "run": "Çalıştır", "reset": "Sıfırla", "copied": "Panoya kopyalandı", - "runToPreview": "Prompt önizlemesini görmek için Çalıştır'a tıklayın", + "runToPreview": "Önizleme için Çalıştır'a tıklayın", + "cannotEvaluate": "Bu kod değerlendirilemiyor.", + "onlyPromptsChat": "Sadece {library} importları destekleniyor.", "desktopOnly": "Yalnızca Masaüstü", "desktopOnlyDescription": "Prompt Oluşturucu düzgün çalışması için daha büyük bir ekran gerektirir. Lütfen bu sayfayı bir masaüstü veya dizüstü bilgisayarda açın.", "browsePrompts": "Promptlara Göz At" diff --git a/messages/zh.json b/messages/zh.json index 93c16199..de871047 100644 --- a/messages/zh.json +++ b/messages/zh.json @@ -1172,6 +1172,8 @@ "reset": "重置", "copied": "已复制到剪贴板", "runToPreview": "点击运行查看提示词预览", + "cannotEvaluate": "此代码无法评估。", + "onlyPromptsChat": "仅支持 {library} 导入。", "desktopOnly": "仅限桌面端", "desktopOnlyDescription": "提示词构建器需要更大的屏幕才能正常工作。请在台式电脑或笔记本电脑上打开此页面。", "browsePrompts": "浏览提示词" diff --git a/scripts/generate-examples.ts b/scripts/generate-examples.ts index efbb4105..c0ba2f20 100644 --- a/scripts/generate-examples.ts +++ b/scripts/generate-examples.ts @@ -9,6 +9,7 @@ const examples = [ { file: 'audio.ts', export: 'EXAMPLE_AUDIO' }, { file: 'image.ts', export: 'EXAMPLE_IMAGE' }, { file: 'chat.ts', export: 'EXAMPLE_CHAT' }, + { file: 'openai-chat.ts', export: 'EXAMPLE_OPENAI_CHAT' }, { file: 'default.ts', export: 'DEFAULT_CODE' }, ]; diff --git a/src/components/ide/examples/generated.ts b/src/components/ide/examples/generated.ts index 4be98128..2a6ad8a5 100644 --- a/src/components/ide/examples/generated.ts +++ b/src/components/ide/examples/generated.ts @@ -249,6 +249,72 @@ const prompt = chat() prompt; `; +export const EXAMPLE_OPENAI_CHAT = `import OpenAI from 'openai'; +import { chat } from 'prompts.chat'; + +// Initialize OpenAI client +const openai = new OpenAI({ + apiKey: process.env.OPENAI_API_KEY, +}); + +// Create a chat prompt using the fluent builder API +const systemPrompt = chat() + // Define the AI's persona + .role("Senior Code Reviewer") + .expertise(["coding", "engineering"]) + .tone("professional") + .personality(["helpful", "thorough", "constructive"]) + + // Set the context + .context("You are reviewing TypeScript code for a startup") + .domain("Software Development") + .audience("Junior to mid-level developers") + + // Define constraints + .constraints([ + "Always explain your reasoning", + "Provide code examples when helpful", + "Be concise but thorough", + ]) + + // Configure output format + .json() + .detailed() + .withExamples() + + // Add few-shot examples + .example( + "Review: const x = 1", + '{"issues": [], "suggestions": ["Use descriptive variable names"], "rating": 8}' + ) + + .build(); + +// Use the prompt with OpenAI +async function reviewCode(code: string) { + const response = await openai.chat.completions.create({ + model: "gpt-4o", + messages: [ + { role: "system", content: systemPrompt.systemPrompt }, + { role: "user", content: \`Review this code:\\n\\n\${code}\` }, + ], + temperature: 0.7, + max_tokens: 1000, + }); + + return response.choices[0].message.content; +} + +// Example usage +const review = await reviewCode(\` +function add(a, b) { + return a + b; +} +\`); + +console.log(review); +`; + export const DEFAULT_CODE = `import { builder, templates } from 'prompts.chat'; // Create a prompt using the fluent builder API diff --git a/src/components/ide/examples/index.ts b/src/components/ide/examples/index.ts index c1478966..4a29747a 100644 --- a/src/components/ide/examples/index.ts +++ b/src/components/ide/examples/index.ts @@ -4,5 +4,6 @@ export { EXAMPLE_AUDIO, EXAMPLE_IMAGE, EXAMPLE_CHAT, + EXAMPLE_OPENAI_CHAT, DEFAULT_CODE, } from './generated'; diff --git a/src/components/ide/examples/openai-chat.ts b/src/components/ide/examples/openai-chat.ts new file mode 100644 index 00000000..273a4a16 --- /dev/null +++ b/src/components/ide/examples/openai-chat.ts @@ -0,0 +1,64 @@ +import OpenAI from 'openai'; +import { chat } from 'prompts.chat'; + +// Initialize OpenAI client +const openai = new OpenAI({ + apiKey: process.env.OPENAI_API_KEY, +}); + +// Create a chat prompt using the fluent builder API +const systemPrompt = chat() + // Define the AI's persona + .role("Senior Code Reviewer") + .expertise(["coding", "engineering"]) + .tone("professional") + .personality(["helpful", "thorough", "constructive"]) + + // Set the context + .context("You are reviewing TypeScript code for a startup") + .domain("Software Development") + .audience("Junior to mid-level developers") + + // Define constraints + .constraints([ + "Always explain your reasoning", + "Provide code examples when helpful", + "Be concise but thorough", + ]) + + // Configure output format + .json() + .detailed() + .withExamples() + + // Add few-shot examples + .example( + "Review: const x = 1", + '{"issues": [], "suggestions": ["Use descriptive variable names"], "rating": 8}' + ) + + .build(); + +// Use the prompt with OpenAI +async function reviewCode(code: string) { + const response = await openai.chat.completions.create({ + model: "gpt-4o", + messages: [ + { role: "system", content: systemPrompt.systemPrompt }, + { role: "user", content: `Review this code:\n\n${code}` }, + ], + temperature: 0.7, + max_tokens: 1000, + }); + + return response.choices[0].message.content; +} + +// Example usage +const review = await reviewCode(` +function add(a, b) { + return a + b; +} +`); + +console.log(review); diff --git a/src/components/ide/prompt-ide.tsx b/src/components/ide/prompt-ide.tsx index e6003c90..7ee252b7 100644 --- a/src/components/ide/prompt-ide.tsx +++ b/src/components/ide/prompt-ide.tsx @@ -6,7 +6,7 @@ import Editor from "@monaco-editor/react"; import { useTheme } from "next-themes"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Button } from "@/components/ui/button"; -import { Copy, Play, RotateCcw, Code2, FileJson, FileText, Video, Music, Image as ImageIcon, MessageSquare } from "lucide-react"; +import { Copy, Play, RotateCcw, Code2, FileJson, FileText, Video, Music, Image as ImageIcon, MessageSquare, Sparkles } from "lucide-react"; import { toast } from "sonner"; // Import the actual prompts.chat library @@ -42,6 +42,7 @@ import { EXAMPLE_AUDIO, EXAMPLE_IMAGE, EXAMPLE_CHAT, + EXAMPLE_OPENAI_CHAT, DEFAULT_CODE, } from "./examples"; @@ -55,6 +56,21 @@ export function PromptIde() { const [isRunning, setIsRunning] = useState(false); const [selectedApiItem, setSelectedApiItem] = useState(null); + // Check if code has imports other than 'prompts.chat' + const hasExternalImports = useCallback(() => { + const importRegex = /^import\s+.*?from\s+['"](.+?)['"];?\s*$/gm; + let match; + while ((match = importRegex.exec(code)) !== null) { + const importPath = match[1]; + if (!importPath.startsWith('prompts.chat')) { + return true; + } + } + return false; + }, [code]); + + const cannotEvaluate = hasExternalImports(); + const runCode = useCallback(() => { setIsRunning(true); setError(null); @@ -292,7 +308,7 @@ export function PromptIde() { +
@@ -439,8 +464,17 @@ export function PromptIde() { /> ) : (
- -

{t("runToPreview")}

+ {cannotEvaluate ? ( + <> + +

{t("cannotEvaluate")}
{t("onlyPromptsChat", { library: "prompts.chat" })}

+ + ) : ( + <> + +

{t("runToPreview")}

+ + )}
)}