aiGenerator.ts
2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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()
}