Untitled

 avatar
unknown
plain_text
a year ago
4.5 kB
9
Indexable
// File: app/api/generate-prompt/route.ts

import OpenAI from "openai"
import { NextResponse } from "next/server"

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
})

export async function POST(request: Request) {
  if (!process.env.OPENAI_API_KEY) {
    return NextResponse.json({ error: "OpenAI API key not configured" }, { status: 500 })
  }

  try {
    const {
      businessQuery,
      projectType,
      existingPrompt,
      categories,
      inputFields,
      promptVariables,
      model,
      temperature,
      max_tokens,
      top_p,
      frequency_penalty,
      presence_penalty,
      prompt_technique,
    } = await request.json()

    if (!businessQuery || !projectType) {
      return NextResponse.json({ error: "Please provide a valid business query and project type" }, { status: 400 })
    }

    const systemPrompt = generateSystemPrompt(projectType, prompt_technique)
    const userPrompt = generateUserPrompt(
      businessQuery,
      projectType,
      existingPrompt,
      categories,
      inputFields,
      promptVariables,
      prompt_technique
    )

    const completion = await openai.chat.completions.create({
      model: model || "gpt-3.5-turbo",
      messages: [
        { role: "system", content: systemPrompt },
        { role: "user", content: userPrompt },
      ],
      temperature: temperature || 0.7,
      max_tokens: max_tokens || 300,
      top_p: top_p || 1,
      frequency_penalty: frequency_penalty || 0,
      presence_penalty: presence_penalty || 0,
    })

    return NextResponse.json({ result: completion.choices[0].message.content.trim() })
  } catch (error: any) {
    console.error("Error:", error)
    return NextResponse.json({ error: "An error occurred during your request." }, { status: 500 })
  }
}

function generateSystemPrompt(projectType: string, promptTechnique?: string) {
  return `You are an expert AI prompt engineer, specialized in creating highly effective prompts for ${projectType} tasks. 
Your goal is to craft a prompt that will yield the most accurate and relevant responses from an AI model.
${promptTechnique ? `You excel in using the ${promptTechnique} technique for prompt engineering.` : ""}
Consider the specific requirements of ${projectType} projects and tailor your prompt accordingly.
Ensure the prompt is clear, concise, and designed to elicit precise and useful information from the AI model.`
}

function generateUserPrompt(
  businessQuery: string,
  projectType: string,
  existingPrompt?: string,
  categories?: string[],
  inputFields?: { label: string; value: string }[],
  promptVariables?: { name: string; value: string }[],
  promptTechnique?: string
) {
  let prompt = `Create an optimal AI prompt based on the following information:

Business Query: ${businessQuery}
Project Type: ${projectType}

${
  projectType.toLowerCase() === "classification"
    ? `This is a classification project. The prompt should guide the AI to classify inputs into the following categories:
${categories?.map((category) => `- ${category}`).join("\n")}`
    : "The prompt should be tailored to address the specific needs of this project type."
}

${
  inputFields && inputFields.length > 0
    ? `Consider the following input fields in your prompt:
${inputFields.map((field) => `- ${field.label}: ${field.value}`).join("\n")}`
    : ""
}

${
  promptVariables && promptVariables.length > 0
    ? `Incorporate the following variables into your prompt:
${promptVariables.map((variable) => `- {${variable.name}}: ${variable.value}`).join("\n")}`
    : ""
}

${
  existingPrompt
    ? `Existing Prompt: ${existingPrompt}
Please improve upon this existing prompt, maintaining its core intent while enhancing its effectiveness.`
    : "Create a new prompt from scratch based on the provided information."
}

${
  promptTechnique
    ? `Utilize the ${promptTechnique} technique in crafting this prompt. Ensure the prompt structure aligns with this technique.`
    : ""
}

The final prompt should:
1. Be clear, concise, and specific to the ${projectType} task
2. Address all core aspects of the business query
3. Be tailored to extract the most relevant and useful information from an AI model
4. Incorporate all provided categories, input fields, and variables effectively
5. Be designed to produce consistent, high-quality, and task-specific responses
6. Follow best practices for ${projectType} prompts

Generate the optimal prompt:`

  return prompt
}
Editor is loading...
Leave a Comment