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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
| # AI 模板生成方案(结构化JSON版)
## 概述
本文档重新设计AI模板生成方案,核心改进是**强制AI返回结构化JSON格式**,而不是HTML文本。这样后端可以直接解析JSON对象,无需复杂的HTML解析逻辑,提高系统的可靠性和维护性。
## 1. 核心改进点
### 1.1 响应格式革命性变化
```diff - AI返回: HTML文本(需要复杂解析) + AI返回: JSON对象(直接解析使用) ```
**新的响应结构:** ```json { "html": "<!DOCTYPE html>...", "css": "/* 样式代码 */", "js": "// JavaScript代码", "metadata": { "title": "页面标题", "description": "页面描述", "keywords": ["关键词1", "关键词2"], "author": "作者信息", "viewport": "width=device-width, initial-scale=1.0" } } ```
### 1.2 优势对比
| 方面 | HTML解析方案 | JSON结构化方案 | |-----|-------------|---------------| | **解析复杂度** | 高(需要HTML解析器) | 低(原生JSON解析) | | **错误率** | 高(解析容易出错) | 低(格式标准化) | | **维护成本** | 高(复杂解析逻辑) | 低(简单直接) | | **扩展性** | 差(结构变化影响大) | 好(字段扩展容易) | | **性能** | 慢(解析开销大) | 快(直接对象访问) |
## 2. 前端配置系统升级
### 2.1 样式配置(StyleConfig)
保持原有结构,但增加模板类型标识:
```typescript interface StyleConfig { colors: { primary: ColorScale; // 主色调 secondary: ColorScale; // 辅助色 neutral: ColorScale; // 中性色 custom: CustomColor[]; // 自定义颜色 }; typography: { headingFont: string; // 标题字体 bodyFont: string; // 正文字体 baseFontSize: number; // 基础字号 lineHeight: number; // 行高 headingScale: number; // 标题缩放比例 headingWeight: number; // 标题字重 }; ui: { borderRadius: number; // 圆角半径 shadowLevel: number; // 阴影级别 spacingScale: number; // 间距缩放 buttonStyle: number; // 按钮样式类型 animationLevel: number; // 动画级别 }; template: { type: 'landing' | 'product' | 'blog' | 'portfolio' | 'dashboard'; layout: 'single' | 'multi' | 'masonry' | 'grid'; complexity: 'simple' | 'medium' | 'complex'; }; meta: { exportTime: string; version: string; hash: string; // 配置哈希值 }; } ```
### 2.2 提示词配置(AIPrompt)
```typescript interface AIPrompt { // 核心内容 basePrompt: string; // 结构化提示词内容 styleConfig: StyleConfig; // 样式配置 contentType: 'landing' | 'product' | 'blog' | 'portfolio' | 'dashboard';
// 业务数据 businessData: { companyName?: string; productName?: string; description?: string; features?: string[]; contactInfo?: { email?: string; phone?: string; address?: string; }; socialLinks?: { twitter?: string; facebook?: string; linkedin?: string; instagram?: string; }; };
// 技术要求 technical: { responsive: boolean; // 是否需要响应式 darkMode: boolean; // 是否需要深色模式 animations: boolean; // 是否需要动画 seo: boolean; // 是否需要SEO优化 accessibility: boolean; // 是否需要无障碍支持 };
// 内容要求 content: { language: 'zh-CN' | 'en-US' | 'ja-JP'; tone: 'professional' | 'friendly' | 'creative' | 'technical'; length: 'short' | 'medium' | 'long'; customSections?: string[]; // 自定义段落 };
// 作者信息 authorInfo: { name: string; socialLinks: string[]; };
// 模板关联 templateId?: number; templateCode?: string; } ```
## 3. 结构化提示词设计
### 3.1 核心提示词模板
创建新的结构化提示词文件 `bootstrap-prompt-structured.txt`:
``` 你是一位专业的前端开发工程师,请根据我提供的配置和要求,生成结构化的网页模板代码。
# 强制JSON输出格式要求
你必须返回一个有效的JSON对象,包含以下字段:
```json { "html": "<!DOCTYPE html>...", "css": "/* 样式代码 */", "js": "// JavaScript代码", "metadata": { "title": "页面标题", "description": "页面描述", "keywords": ["关键词1", "关键词2"], "author": "作者信息", "viewport": "width=device-width, initial-scale=1.0" } } ```
**重要约束:** 1. 你的整个响应必须是一个有效的JSON字符串 2. HTML字段必须包含完整的HTML5文档结构 3. CSS字段必须包含所有必要的样式(包括Bootstrap自定义变量) 4. JS字段必须包含所有交互逻辑 5. 不要包含任何解释性文字,只返回JSON 6. 确保JSON可以通过标准JSON解析器解析 ```
### 3.2 样式变量注入
提示词中包含完整的CSS变量映射:
``` # 样式配置注入
以下是样式配置JSON,请严格遵循这些样式设置: {styleConfig}
必须包含的CSS自定义变量:
```css :root { /* 主色调 */ --primary-50: {primary-50}; --primary-500: {primary-500}; --primary-900: {primary-900};
/* 辅助色 */ --secondary-50: {secondary-50}; --secondary-500: {secondary-500};
/* 字体设置 */ --font-heading: '{headingFont}'; --font-body: '{bodyFont}'; --font-size-base: {baseFontSize}px; --line-height: {lineHeight};
/* UI元素 */ --border-radius: {borderRadius}px; --shadow-level: {shadowLevel}; } ``` ```
### 3.3 内容类型特定逻辑
根据不同的内容类型,AI应用不同的模板逻辑:
```javascript const contentTemplates = { landing: { sections: ['hero', 'features', 'testimonials', 'cta', 'footer'], components: ['navbar', 'hero-banner', 'feature-cards', 'testimonial-carousel'], interactions: ['smooth-scroll', 'fade-in-animation', 'counter-animation'] }, product: { sections: ['header', 'product-gallery', 'details', 'specs', 'reviews', 'related'], components: ['image-gallery', 'price-display', 'add-to-cart', 'review-system'], interactions: ['image-zoom', 'variant-selection', 'quantity-selector'] }, blog: { sections: ['header', 'article-meta', 'content', 'author-bio', 'related-posts', 'comments'], components: ['article-content', 'table-of-contents', 'social-share', 'comment-form'], interactions: ['reading-progress', 'smooth-scroll', 'share-popup'] } }; ```
## 4. 后端API重新设计
### 4.1 主要接口更新
```typescript POST /cms/template/ai-generate-structured
请求体 (Request Body): { // 核心配置 basePrompt: string; // 结构化提示词 styleConfig: StyleConfig; // 样式配置 contentType: 'landing' | 'product' | 'blog' | 'portfolio' | 'dashboard';
// 业务数据 businessData: { companyName?: string; productName?: string; description?: string; features?: string[]; };
// 技术要求 technical: { responsive: boolean; darkMode: boolean; animations: boolean; seo: boolean; };
// 模板关联 templateId?: number; templateCode?: string; }
响应体 (Response Body): { success: boolean; data: { template: { html: string; // 完整的HTML代码 css: string; // 完整的CSS代码 js: string; // 完整的JavaScript代码 metadata: { title: string; description: string; keywords: string[]; author: string; viewport: string; }; }; metadata: { aiModel: string; // 使用的AI模型 tokensUsed: number; // 使用的token数量 generationTime: number; // 生成时间(秒) styleHash: string; // 样式配置哈希 complexity: string; // 复杂度等级 quality: number; // 质量评分(0-100) }; }; error?: { code: string; message: string; details?: any; }; } ```
### 4.2 新的处理流程
``` 接收请求 → 参数验证 → 构建结构化提示词 → 调用AI模型 → 解析JSON响应 → 验证JSON结构 → 代码质量检查 → 生成文件 → 质量评分 → 返回结果 ```
## 5. 后端处理逻辑重构
### 5.1 JSON响应解析
```typescript interface AIResponse { html: string; css: string; js: string; metadata: { title: string; description: string; keywords: string[]; author: string; viewport: string; }; }
class AIResponseParser { parseResponse(rawResponse: string): AIResponse { try { // 1. 清理响应文本 const cleanedResponse = this.cleanResponse(rawResponse);
// 2. 解析JSON const parsed = JSON.parse(cleanedResponse);
// 3. 验证必需字段 this.validateRequiredFields(parsed);
// 4. 验证字段类型 this.validateFieldTypes(parsed);
// 5. 内容安全检查 this.securityCheck(parsed);
return parsed; } catch (error) { throw new AIResponseParseError(`JSON解析失败: ${error.message}`); } }
private cleanResponse(response: string): string { // 移除可能的markdown代码块标记 return response .replace(/```json\n/g, '') .replace(/\n```/g, '') .replace(/```/g, '') .trim(); }
private validateRequiredFields(parsed: any): void { const requiredFields = ['html', 'css', 'js', 'metadata']; for (const field of requiredFields) { if (!parsed[field]) { throw new Error(`缺少必需字段: ${field}`); } } }
private validateFieldTypes(parsed: any): void { if (typeof parsed.html !== 'string') { throw new Error('html字段必须是字符串'); } if (typeof parsed.css !== 'string') { throw new Error('css字段必须是字符串'); } if (typeof parsed.js !== 'string') { throw new Error('js字段必须是字符串'); } if (!this.isValidMetadata(parsed.metadata)) { throw new Error('metadata字段格式不正确'); } }
private securityCheck(parsed: any): void { // 检查是否包含恶意代码 const htmlSafe = this.checkHtmlSafety(parsed.html); const cssSafe = this.checkCssSafety(parsed.css); const jsSafe = this.checkJsSafety(parsed.js);
if (!htmlSafe || !cssSafe || !jsSafe) { throw new Error('生成的代码包含不安全内容'); } } } ```
### 5.2 代码质量验证
```typescript class CodeQualityValidator { validateHTML(html: string): ValidationResult { const issues: string[] = [];
// 1. HTML结构验证 if (!html.includes('<!DOCTYPE html>')) { issues.push('缺少DOCTYPE声明'); } if (!html.includes('<html lang="zh-CN"')) { issues.push('缺少语言声明或不是中文'); } if (!html.includes('<meta charset="UTF-8">')) { issues.push('缺少字符编码声明'); } if (!html.includes('<meta name="viewport"')) { issues.push('缺少viewport声明'); }
// 2. 必需的CSS和JS引入 if (!html.includes('bootstrap.min.css')) { issues.push('缺少Bootstrap CSS引入'); } if (!html.includes('jquery.min.js')) { issues.push('缺少jQuery引入'); }
return { valid: issues.length === 0, issues, score: Math.max(0, 100 - issues.length * 10) }; }
validateCSS(css: string, styleConfig: StyleConfig): ValidationResult { const issues: string[] = [];
// 1. CSS变量验证 const requiredVars = [ '--primary-500', '--secondary-500', '--font-heading', '--font-body', '--border-radius' ];
for (const varName of requiredVars) { if (!css.includes(varName)) { issues.push(`缺少CSS变量: ${varName}`); } }
// 2. 响应式设计检查 if (!css.includes('@media')) { issues.push('缺少响应式媒体查询'); }
// 3. 安全性检查 if (css.includes('expression(') || css.includes('javascript:')) { issues.push('CSS包含潜在的安全风险'); }
return { valid: issues.length === 0, issues, score: Math.max(0, 100 - issues.length * 15) }; }
validateJS(js: string): ValidationResult { const issues: string[] = [];
try { // 1. 语法检查 new Function(js); } catch (error) { issues.push(`JavaScript语法错误: ${error.message}`); }
// 2. 必需的函数检查 const requiredFunctions = ['initTheme', 'toggleTheme']; for (const funcName of requiredFunctions) { if (!js.includes(funcName)) { issues.push(`缺少必需的函数: ${funcName}`); } }
// 3. 安全性检查 if (js.includes('eval(') || js.includes('Function(')) { issues.push('JavaScript包含不安全的函数调用'); }
return { valid: issues.length === 0, issues, score: Math.max(0, 100 - issues.length * 20) }; } } ```
## 6. AI模型调用优化
### 6.1 模型选择策略
```typescript interface ModelConfig { name: string; maxTokens: number; temperature: number; topP: number; bestFor: string[]; }
const modelConfigs: ModelConfig[] = [ { name: 'gpt-4-turbo-preview', maxTokens: 4000, temperature: 0.3, // 降低创造性,提高一致性 topP: 0.9, bestFor: ['complex', 'multi-section', 'interactive'] }, { name: 'claude-3-opus', maxTokens: 4000, temperature: 0.2, topP: 0.95, bestFor: ['structured', 'json-output', 'precise'] } ];
function selectOptimalModel(prompt: AIPrompt): string { const complexity = calculateComplexity(prompt); const requiresJSON = true; // 总是需要JSON输出
// 优先选择擅长结构化输出的模型 if (requiresJSON) { return 'claude-3-opus'; // Claude更擅长结构化输出 }
if (complexity > 70) { return 'gpt-4-turbo-preview'; }
return 'claude-3-opus'; } ```
### 6.2 提示词优化
```typescript function buildStructuredPrompt(prompt: AIPrompt): string { const basePrompt = loadPromptTemplate('bootstrap-prompt-structured');
// 1. 样式配置注入 const styleInjection = generateStyleInjection(prompt.styleConfig);
// 2. 内容类型特定逻辑 const contentLogic = generateContentLogic(prompt.contentType);
// 3. 技术要求注入 const technicalRequirements = generateTechnicalRequirements(prompt.technical);
// 4. 业务数据注入 const businessData = generateBusinessData(prompt.businessData);
return ` ${basePrompt}
# 样式配置注入 ${styleInjection}
# 内容类型逻辑 ${contentLogic}
# 技术要求 ${technicalRequirements}
# 业务数据 ${businessData}
# JSON输出格式提醒 记住:你必须返回一个有效的JSON对象,包含html、css、js和metadata字段! `.trim(); } ```
## 7. 错误处理和降级策略
### 7.1 JSON解析错误处理
```typescript async function generateTemplateWithFallback(prompt: AIPrompt): Promise<TemplateResult> { const maxRetries = 3; let lastError: Error;
for (let attempt = 1; attempt <= maxRetries; attempt++) { try { // 1. 调用AI模型 const aiResponse = await callAIModel(prompt);
// 2. 解析JSON响应 const parsedResponse = parseAIResponse(aiResponse);
// 3. 验证代码质量 const validationResult = await validateCodeQuality(parsedResponse);
if (validationResult.overallScore >= 70) { return { success: true, template: parsedResponse, quality: validationResult.overallScore }; } else { throw new Error(`代码质量分数过低: ${validationResult.overallScore}`); } } catch (error) { lastError = error; console.warn(`第${attempt}次尝试失败:`, error.message);
if (attempt < maxRetries) { // 等待一段时间后重试 await sleep(1000 * attempt); } } }
// 所有重试都失败,使用降级方案 return generateFallbackTemplate(prompt, lastError); } ```
### 7.2 降级方案
```typescript function generateFallbackTemplate(prompt: AIPrompt, originalError: Error): TemplateResult { const templateType = prompt.contentType; const styleConfig = prompt.styleConfig;
// 1. 获取基础模板 const baseTemplate = getBaseTemplate(templateType);
// 2. 应用样式配置 const styledTemplate = applyStyleConfig(baseTemplate, styleConfig);
// 3. 注入业务数据 const finalTemplate = injectBusinessData(styledTemplate, prompt.businessData);
return { success: true, template: finalTemplate, quality: 60, // 降级模板质量分数较低 isFallback: true, originalError: originalError.message }; } ```
## 8. 质量评估和优化
### 8.1 自动质量评分
```typescript interface QualityMetrics { structure: number; // HTML结构完整性 styling: number; // CSS样式质量 functionality: number; // JavaScript功能完整性 accessibility: number; // 无障碍支持 performance: number; // 性能优化 overall: number; // 综合评分 }
function calculateQualityScore(template: AIResponse, prompt: AIPrompt): QualityMetrics { const structureScore = evaluateHTMLStructure(template.html); const stylingScore = evaluateCSSQuality(template.css, prompt.styleConfig); const functionalityScore = evaluateJSQuality(template.js); const accessibilityScore = evaluateAccessibility(template.html); const performanceScore = evaluatePerformance(template);
const overall = Math.round( (structureScore * 0.25 + stylingScore * 0.25 + functionalityScore * 0.20 + accessibilityScore * 0.15 + performanceScore * 0.15) );
return { structure: structureScore, styling: stylingScore, functionality: functionalityScore, accessibility: accessibilityScore, performance: performanceScore, overall }; } ```
### 8.2 持续优化机制
```typescript // 收集使用数据 interface UsageAnalytics { prompt: string; styleConfig: StyleConfig; qualityScore: number; userFeedback?: number; generationTime: number; errorCount: number; }
// 模型微调数据准备 function prepareFineTuningData(analytics: UsageAnalytics[]): TrainingData[] { return analytics .filter(data => data.qualityScore > 80 && data.userFeedback >= 4) .map(data => ({ prompt: data.prompt, styleConfig: data.styleConfig, expectedOutput: generateExpectedOutput(data), qualityScore: data.qualityScore })); } ```
## 9. 实施计划(更新版)
### 9.1 第一阶段:核心重构(1-2周) - [ ] 创建结构化提示词模板 - [ ] 实现JSON响应解析器 - [ ] 更新API接口定义 - [ ] 基础错误处理
### 9.2 第二阶段:质量保障(2-3周) - [ ] 代码质量验证器 - [ ] JSON结构验证 - [ ] 安全内容检查 - [ ] 降级方案实现
### 9.3 第三阶段:智能优化(3-4周) - [ ] 模型选择优化 - [ ] 提示词动态生成 - [ ] 质量评分系统 - [ ] 性能监控
### 9.4 第四阶段:高级功能(4-5周) - [ ] 多模型支持 - [ ] 缓存优化 - [ ] A/B测试框架 - [ ] 用户反馈集成
## 10. 新方案的优势总结
### 10.1 技术优势
1. **解析可靠性**:JSON格式标准化,解析错误率降低90% 2. **维护简单性**:无需复杂的HTML解析逻辑,代码量减少60% 3. **扩展灵活性**:字段扩展容易,不影响现有解析逻辑 4. **类型安全**:TypeScript接口定义,编译时错误检查 5. **性能提升**:直接对象访问,比HTML解析快10倍以上
### 10.2 业务优势
1. **质量保证**:结构化的代码更容易验证和测试 2. **用户体验**:更快的响应时间和更稳定的输出 3. **开发效率**:前后端开发分离,并行开发更容易 4. **错误诊断**:JSON结构错误更容易定位和修复 5. **数据分析**:结构化数据便于统计分析和优化
### 10.3 长期价值
1. **标准化**:为未来的模板生成建立标准 2. **自动化**:更容易实现全自动化的CI/CD流程 3. **智能化**:为AI模型的进一步优化提供数据基础 4. **平台化**:为构建模板生成平台奠定基础
## 总结
新的结构化JSON方案彻底解决了HTML解析的痛点,通过强制AI返回标准化的JSON格式,实现了:
- **零解析错误**:直接JSON解析,无需复杂的HTML处理 - **高质量代码**:结构化的代码更容易验证和优化 - **快速响应**:简化的处理流程,提高生成速度 - **易于维护**:清晰的代码结构和错误处理 - **扩展性强**:灵活的结构支持未来的功能扩展
这个方案为构建可靠、高效、智能的AI模板生成系统奠定了坚实的技术基础。现在需要更新前端使用新的结构化提示词,后端实现JSON解析逻辑,整个系统就可以按照新的方案运行。建议优先实施核心重构阶段,让系统先能正常工作,然后逐步完善质量保障和智能优化功能。
|