aiGenerator.ts 2.42 KB
import type { FigmaNodeDSL } from './types'

export interface AIConfig {
  apiKey: string
  baseUrl: string
  model: string
}

const DEFAULT_SYSTEM_PROMPT = `你是一个专业的 Vue 3 前端工程师,擅长将设计稿 DSL 转换为高质量、可维护的 Vue 3 单文件组件。

请严格遵循以下规则:
1. 使用 Tailwind CSS 实现所有样式,优先使用语义化工具类
2. 使用语义化 HTML 标签(button、nav、header、main、section、article、p、h1-h6 等)
3. 布局必须与 DSL 描述一致,保持相对尺寸比例
4. 颜色直接使用 style 属性(rgba 格式)或 Tailwind 任意值语法
5. 使用 <script setup lang="ts"> 语法
6. 只输出完整的 .vue 文件内容,不要使用任何 markdown 代码块包裹(不要 \`\`\`vue ... \`\`\`)
7. 不要添加多余的注释,保持代码简洁`

/**
 * 检查 AI 配置是否完整
 */
export function isAiConfigured(config: AIConfig): boolean {
  return !!(config.apiKey && config.baseUrl && config.model)
}

/**
 * 使用 AI 模型将 DSL 转换为 Vue SFC
 * 支持 OpenAI、DeepSeek 等兼容 OpenAI 格式的 API
 */
export async function generateVueWithAI(
  dslRoot: FigmaNodeDSL,
  componentName: string,
  config: AIConfig,
  customPrompt?: string,
): Promise<string> {
  const systemPrompt = customPrompt?.trim() || DEFAULT_SYSTEM_PROMPT

  const userMessage = `请将以下 Figma 设计稿 DSL 转换为 Vue 3 单文件组件,组件名称为 \`${componentName}\`。

DSL 数据:
\`\`\`json
${JSON.stringify(dslRoot, null, 2)}
\`\`\``

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

  if (!response.ok) {
    const errText = await response.text()
    throw new Error(`AI API 请求失败 (HTTP ${response.status}):${errText}`)
  }

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

  const content = data.choices?.[0]?.message?.content ?? ''

  // 移除可能存在的 markdown 代码块包裹
  return content
    .replace(/^```(?:vue|html)?\s*\n?/, '')
    .replace(/\n?```\s*$/, '')
    .trim()
}