optimize.post.ts 2.75 KB
import { isAiConfigured, type AIConfig } from '../../utils/aiGenerator'

interface OptimizePromptBody {
  prompt?: string
}

interface OptimizePromptResult {
  prompt: string
}

export default defineEventHandler(async (event): Promise<OptimizePromptResult> => {
  const body = await readBody<OptimizePromptBody>(event)
  const originalPrompt = body?.prompt?.trim()

  if (!originalPrompt) {
    throw createError({
      statusCode: 400,
      message: '请提供要优化的提示词内容',
    })
  }

  const config = useRuntimeConfig()

  const aiConfig: AIConfig = {
    apiKey: (config.aiApiKey as string) || '',
    baseUrl: (config.aiBaseUrl as string) || 'https://api.openai.com/v1',
    model: (config.aiModel as string) || 'gpt-4o-mini',
  }

  if (!isAiConfigured(aiConfig)) {
    throw createError({
      statusCode: 500,
      message: '服务端未配置 AI_API_KEY/AI_BASE_URL/AI_MODEL,无法优化提示词',
    })
  }

  const systemPrompt =
    '你是一名专业的 Prompt Engineer,擅长为前端代码生成任务优化中文提示词。' +
    '请在保持原始意图不变的前提下,使提示词更加清晰、结构化、可执行,适合用于指导大模型将 Figma DSL 转换为 Vue 3 + Tailwind 代码。' +
    '直接输出优化后的提示词文本,不要解释,不要添加 Markdown 代码块。'

  const userMessage = `请优化下面这段用于“Figma 设计稿 DSL → Vue 3 + Tailwind 组件生成”的系统提示词:

---------------- 原始提示词 ----------------
${originalPrompt}
------------------------------------------

请在保留核心意图的前提下:
1. 补全关键约束(如组件结构、语义化标签、Tailwind 使用等)
2. 使用条列式结构,逻辑更清晰
3. 使用简洁专业的中文表述。
`

  const response = await fetch(`${aiConfig.baseUrl}/chat/completions`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${aiConfig.apiKey}`,
    },
    body: JSON.stringify({
      model: aiConfig.model,
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userMessage },
      ],
      temperature: 0.4,
      max_tokens: 1024,
    }),
  })

  if (!response.ok) {
    const errText = await response.text()
    throw createError({
      statusCode: 500,
      message: `提示词优化失败 (HTTP ${response.status}):${errText}`,
    })
  }

  const data = (await response.json()) as {
    choices?: Array<{ message?: { content?: string } }>
  }

  const optimized = data.choices?.[0]?.message?.content?.trim()

  if (!optimized) {
    throw createError({
      statusCode: 500,
      message: '提示词优化失败:AI 未返回有效内容',
    })
  }

  return {
    prompt: optimized,
  }
})