From 8dd1a9e04278d6ffcfe026347c27739439cbe571 Mon Sep 17 00:00:00 2001 From: Nikhil-Doye Date: Sat, 18 Oct 2025 23:48:46 -0400 Subject: [PATCH] Implement prompt optimization features across workflow components - Integrated a new prompt optimization service to enhance AI task node prompts, improving context-awareness and domain specificity. - Updated NodeConfiguration component to include a button for optimizing prompts, displaying results for user review and application. - Enhanced workflow generation logic to utilize optimized prompts, ensuring better performance in AI analysis tasks. - Refactored existing prompt generation methods to leverage the new prompt optimizer, streamlining the process for various data types and tasks. - Added detailed context and instructions for AI tasks, improving the overall user experience and output quality. --- src/components/NodeConfiguration.tsx | 209 +++++++++- src/services/copilotService.ts | 130 +++++- src/services/promptOptimizer.ts | 593 +++++++++++++++++++++++++++ src/store/workflowStore.ts | 165 +++++++- src/utils/workflowGenerator.ts | 52 +-- 5 files changed, 1106 insertions(+), 43 deletions(-) create mode 100644 src/services/promptOptimizer.ts diff --git a/src/components/NodeConfiguration.tsx b/src/components/NodeConfiguration.tsx index 40a27bd..15ca605 100644 --- a/src/components/NodeConfiguration.tsx +++ b/src/components/NodeConfiguration.tsx @@ -1,7 +1,9 @@ -import React from "react"; +import React, { useState } from "react"; import { NodeData } from "../types"; import { useWorkflowStore } from "../store/workflowStore"; -import { X, Settings } from "lucide-react"; +import { X, Settings, Sparkles } from "lucide-react"; +import { promptOptimizer } from "../services/promptOptimizer"; +import { callOpenAI } from "../services/openaiService"; interface NodeConfigurationProps { nodeId: string; @@ -192,6 +194,8 @@ export const NodeConfiguration: React.FC = ({ }) => { const { updateNode, currentWorkflow } = useWorkflowStore(); const config = nodeTypeConfigs[data.type]; + const [isOptimizing, setIsOptimizing] = useState(false); + const [optimizationResult, setOptimizationResult] = useState(""); // Get the latest node data from the store to ensure we have the most up-to-date config const currentNode = currentWorkflow?.nodes.find((node) => node.id === nodeId); @@ -210,19 +214,163 @@ export const NodeConfiguration: React.FC = ({ updateNode(nodeId, { label }); }; + const handleOptimizePrompt = async () => { + if (!currentData.config.prompt) { + alert("Please enter a prompt first"); + return; + } + + setIsOptimizing(true); + setOptimizationResult(""); + + try { + // Extract intent from the prompt itself + const prompt = currentData.config.prompt; + const entities = { + aiTasks: prompt.toLowerCase().includes("analyze") + ? ["analyze"] + : prompt.toLowerCase().includes("summarize") + ? ["summarize"] + : prompt.toLowerCase().includes("extract") + ? ["extract"] + : prompt.toLowerCase().includes("classify") + ? ["classify"] + : prompt.toLowerCase().includes("generate") + ? ["generate"] + : ["process"], + dataTypes: prompt.toLowerCase().includes("resume") + ? ["resume"] + : prompt.toLowerCase().includes("document") + ? ["document"] + : prompt.toLowerCase().includes("text") + ? ["text"] + : ["text"], + urls: [], + complexity: "medium", + }; + + // Create mock node context + const nodeContext = { + dataType: "text", + previousNodes: [], + intent: "AI_ANALYSIS", + domain: prompt.toLowerCase().includes("resume") + ? "jobApplication" + : prompt.toLowerCase().includes("financial") + ? "financial" + : prompt.toLowerCase().includes("legal") + ? "legal" + : "general", + workflowType: "ai_analysis", + availableData: new Map(), + }; + + // Generate optimized prompt using the prompt optimizer + const optimizedPrompt = promptOptimizer.generateOptimizedPrompt( + prompt, + entities, + nodeContext, + new Map() + ); + + // Make DeepSeek API call to further optimize the prompt + const apiResponse = await callOpenAI( + `You are a prompt optimization expert. Your task is to optimize the given prompt for better AI performance. + +IMPORTANT: Return ONLY the optimized prompt. Do not include any explanations, comments, or additional text. Just the optimized prompt itself. + +Original Prompt: ${prompt} + +Optimized Template: ${optimizedPrompt} + +Return only the optimized prompt:`, + { + model: "deepseek-chat", + temperature: 0.7, + maxTokens: 1000, + } + ); + + // Clean up the response to ensure we only get the optimized prompt + let cleanedResult = apiResponse.content.trim(); + + // Remove common prefixes that might be added by the AI + const prefixesToRemove = [ + "Optimized Prompt:", + "Here's the optimized prompt:", + "The optimized prompt is:", + "Optimized version:", + "Here is the optimized prompt:", + "Optimized prompt:", + "Here's the improved prompt:", + "Improved prompt:", + "Here is the improved prompt:", + "The improved prompt is:", + "Here's the enhanced prompt:", + "Enhanced prompt:", + "Here is the enhanced prompt:", + "The enhanced prompt is:", + ]; + + for (const prefix of prefixesToRemove) { + if (cleanedResult.toLowerCase().startsWith(prefix.toLowerCase())) { + cleanedResult = cleanedResult.substring(prefix.length).trim(); + } + } + + // Remove any quotes that might wrap the prompt + if ( + (cleanedResult.startsWith('"') && cleanedResult.endsWith('"')) || + (cleanedResult.startsWith("'") && cleanedResult.endsWith("'")) + ) { + cleanedResult = cleanedResult.slice(1, -1).trim(); + } + + setOptimizationResult(cleanedResult); + } catch (error) { + console.error("Error optimizing prompt:", error); + setOptimizationResult("Error optimizing prompt. Please try again."); + } finally { + setIsOptimizing(false); + } + }; + + const applyOptimizedPrompt = () => { + if (optimizationResult) { + handleConfigChange("prompt", optimizationResult); + setOptimizationResult(""); + } + }; + const renderField = (field: any) => { const value = currentData.config[field.key] || field.defaultValue || ""; switch (field.type) { case "textarea": return ( -