实战:智能内容生成系统
High Contrast
Dark Mode
Light Mode
Sepia
Forest
3 min read680 words

实战:智能内容生成系统

本章将运用前五章学到的所有技术,构建三个完整的实战项目。第一个项目是一个智能内容生成系统——它能根据主题、受众和风格要求,自动生成高质量的文章、报告和营销文案。

项目目标

graph TB A[智能内容生成系统] --> B[输入] A --> C[处理] A --> D[输出] B --> B1[主题/关键词] B --> B2[目标受众] B --> B3[内容类型] B --> B4[风格要求] C --> C1[大纲生成] C --> C2[分段撰写] C --> C3[质量审核] C --> C4[格式优化] D --> D1[完整文章] D --> D2[SEO元数据] D --> D3[质量评分] style A fill:#ede7f6,stroke:#5e35b1,stroke-width:3px style B fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style C fill:#fff9c4,stroke:#f9a825,stroke-width:2px style D fill:#c8e6c9,stroke:#43a047,stroke-width:2px

技术栈选择

组件 技术 用途
LLM GPT-4o-mini / GPT-4o 内容生成与审核
结构化输出 Pydantic + OpenAI 保证输出格式
提示链 自定义Pipeline 多步骤生成
质量保证 LLM-as-Judge 自动评分
安全 ContentSafetyPipeline 内容安全审核

系统架构

graph LR A[用户请求] --> B[请求解析] B --> C[大纲生成] C --> D[章节撰写] D --> E[质量审核] E --> F{评分 ≥ 4?} F -->|是| G[SEO优化] F -->|否| H[修改重写] H --> E G --> I[最终输出] style A fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style C fill:#fff9c4,stroke:#f9a825,stroke-width:2px style E fill:#ede7f6,stroke:#5e35b1,stroke-width:2px style F fill:#fff9c4,stroke:#f9a825,stroke-width:2px style I fill:#c8e6c9,stroke:#43a047,stroke-width:3px

完整代码实现

数据模型

"""
content_generator.py - 智能内容生成系统
综合运用:提示链、结构化输出、LLM-as-Judge、安全过滤
"""
from pydantic import BaseModel, Field
from openai import OpenAI
from enum import Enum
import json
client = OpenAI()
class ContentType(str, Enum):
BLOG = "blog"             # 博客文章
TUTORIAL = "tutorial"     # 教程
REPORT = "report"         # 分析报告
MARKETING = "marketing"   # 营销文案
NEWSLETTER = "newsletter" # 新闻通讯
class Audience(str, Enum):
BEGINNER = "beginner"     # 初学者
INTERMEDIATE = "intermediate"  # 中级
EXPERT = "expert"         # 专家
GENERAL = "general"       # 大众
class ContentRequest(BaseModel):
"""内容生成请求"""
topic: str = Field(description="文章主题")
content_type: ContentType = Field(description="内容类型")
audience: Audience = Field(default=Audience.GENERAL, description="目标受众")
tone: str = Field(default="专业且友好", description="写作语调")
word_count: int = Field(default=1500, description="目标字数", ge=300, le=5000)
keywords: list[str] = Field(default_factory=list, description="SEO关键词")
language: str = Field(default="zh-CN", description="输出语言")
class OutlineSection(BaseModel):
"""大纲章节"""
title: str = Field(description="章节标题")
key_points: list[str] = Field(description="要点列表,2-4个")
estimated_words: int = Field(description="预估字数")
class ContentOutline(BaseModel):
"""内容大纲"""
title: str = Field(description="文章标题")
hook: str = Field(description="开头吸引语,1-2句话")
sections: list[OutlineSection] = Field(description="章节列表,3-6个")
conclusion_points: list[str] = Field(description="总结要点")
class QualityScore(BaseModel):
"""质量评分"""
accuracy: int = Field(description="准确性 1-5", ge=1, le=5)
readability: int = Field(description="可读性 1-5", ge=1, le=5)
completeness: int = Field(description="完整性 1-5", ge=1, le=5)
engagement: int = Field(description="吸引力 1-5", ge=1, le=5)
overall: int = Field(description="总体评分 1-5", ge=1, le=5)
suggestions: list[str] = Field(description="改进建议")
class SEOMetadata(BaseModel):
"""SEO元数据"""
meta_title: str = Field(description="SEO标题,50-60字符")
meta_description: str = Field(description="SEO描述,150-160字符")
slug: str = Field(description="URL友好的文章标识")
tags: list[str] = Field(description="文章标签")

核心生成引擎

class ContentGenerator:
"""
智能内容生成引擎。
使用4步提示链:
1. 生成大纲(GPT-4o-mini)
2. 撰写内容(GPT-4o-mini)
3. 质量审核(GPT-4o)
4. SEO优化(GPT-4o-mini)
"""
def __init__(self):
self.generation_model = "gpt-4o-mini"  # 生成用轻量模型
self.review_model = "gpt-4o"            # 审核用强模型
def generate(self, request: ContentRequest) -> dict:
"""
完整的内容生成流程。
Returns:
{
"outline": ContentOutline,
"content": str,
"quality": QualityScore,
"seo": SEOMetadata,
"metadata": {...}
}
"""
print(f"📝 开始生成: {request.topic}")
print(f"   类型={request.content_type.value}, 受众={request.audience.value}")
# Step 1: 生成大纲
print("\n[1/4] 生成大纲...")
outline = self._generate_outline(request)
print(f"   ✅ 标题: {outline.title}")
print(f"   ✅ 章节: {len(outline.sections)} 个")
# Step 2: 撰写内容
print("\n[2/4] 撰写内容...")
content = self._write_content(request, outline)
print(f"   ✅ 字数: {len(content)} 字")
# Step 3: 质量审核
print("\n[3/4] 质量审核...")
quality = self._review_quality(request, content)
print(f"   ✅ 总评: {quality.overall}/5")
# 如果评分不达标,修改后重新审核(最多重试2次)
retry_count = 0
while quality.overall < 4 and retry_count < 2:
retry_count += 1
print(f"\n[3.{retry_count}] 评分 {quality.overall}/5 不达标,正在改进...")
content = self._improve_content(content, quality.suggestions)
quality = self._review_quality(request, content)
print(f"   ✅ 改进后总评: {quality.overall}/5")
# Step 4: SEO优化
print("\n[4/4] SEO优化...")
seo = self._generate_seo(request, content)
print(f"   ✅ SEO标题: {seo.meta_title}")
print(f"\n🎉 生成完成!总评: {quality.overall}/5")
return {
"outline": outline,
"content": content,
"quality": quality,
"seo": seo,
"metadata": {
"topic": request.topic,
"word_count": len(content),
"retries": retry_count,
"generation_model": self.generation_model,
"review_model": self.review_model,
}
}
def _generate_outline(self, request: ContentRequest) -> ContentOutline:
"""Step 1: 生成内容大纲"""
audience_desc = {
Audience.BEGINNER: "对该领域了解很少的初学者",
Audience.INTERMEDIATE: "有一定基础知识的中级读者",
Audience.EXPERT: "该领域的资深专家",
Audience.GENERAL: "对该话题感兴趣的普通读者",
}
prompt = f"""你是一位经验丰富的内容策划师。请为以下主题创建一份详细的文章大纲。
## 主题
{request.topic}
## 要求
- 内容类型: {request.content_type.value}
- 目标受众: {audience_desc[request.audience]}
- 目标字数: {request.word_count} 字
- 写作语调: {request.tone}
- 语言: {request.language}
## 大纲规则
1. 标题要吸引人,包含核心关键词
2. 开头吸引语要抓住读者注意力
3. 章节数量3-6个,合理分配字数
4. 每个章节列出2-4个要点
5. 总结要点要有实际价值"""
response = client.beta.chat.completions.parse(
model=self.generation_model,
messages=[{"role": "user", "content": prompt}],
response_format=ContentOutline,
temperature=0.7
)
return response.choices[0].message.parsed
def _write_content(self, request: ContentRequest, outline: ContentOutline) -> str:
"""Step 2: 根据大纲撰写完整内容"""
sections_text = ""
for i, section in enumerate(outline.sections, 1):
points = "\n".join(f"  - {p}" for p in section.key_points)
sections_text += f"\n### {i}. {section.title} (~{section.estimated_words}字)\n{points}\n"
keywords_text = ", ".join(request.keywords) if request.keywords else "无特定要求"
prompt = f"""你是一位专业的{request.content_type.value}写手。请根据以下大纲撰写完整的文章。
## 文章标题
{outline.title}
## 开头
{outline.hook}
## 大纲
{sections_text}
## 总结要点
{chr(10).join(f"- {p}" for p in outline.conclusion_points)}
## 写作要求
1. 总字数约 {request.word_count} 字
2. 语调: {request.tone}
3. SEO关键词(自然融入): {keywords_text}
4. 使用Markdown格式(标题、列表、粗体等)
5. 每个章节之间用 ## 二级标题分隔
6. 必要时使用具体数据、案例或示例支撑论点
7. 结尾要有明确的行动号召(Call to Action)
请直接输出文章内容(Markdown格式),不要包含额外说明。"""
response = client.chat.completions.create(
model=self.generation_model,
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
max_tokens=4000
)
return response.choices[0].message.content.strip()
def _review_quality(self, request: ContentRequest, content: str) -> QualityScore:
"""Step 3: 用更强的模型进行质量审核"""
prompt = f"""你是一位严格的内容审核编辑。请评估以下文章的质量。
## 文章要求
- 主题: {request.topic}
- 类型: {request.content_type.value}
- 目标受众: {request.audience.value}
- 目标字数: {request.word_count}
## 文章内容
{content[:3000]}
## 评分标准
- 准确性(1-5): 信息是否准确、有无事实错误
- 可读性(1-5): 是否流畅易懂、段落结构合理
- 完整性(1-5): 是否完整覆盖主题、无明显遗漏
- 吸引力(1-5): 是否能维持读者兴趣
- 总体(1-5): 综合评价
对每项低于4分的维度,请给出具体的改进建议。"""
response = client.beta.chat.completions.parse(
model=self.review_model,
messages=[{"role": "user", "content": prompt}],
response_format=QualityScore,
temperature=0.0
)
return response.choices[0].message.parsed
def _improve_content(self, content: str, suggestions: list[str]) -> str:
"""Step 3.x: 根据审核建议改进内容"""
suggestions_text = "\n".join(f"- {s}" for s in suggestions)
prompt = f"""请根据以下改进建议修改文章。保持原有结构和风格,只修正指出的问题。
## 改进建议
{suggestions_text}
## 原文
{content}
请输出完整的修改后文章(Markdown格式)。"""
response = client.chat.completions.create(
model=self.generation_model,
messages=[{"role": "user", "content": prompt}],
temperature=0.3,
max_tokens=4000
)
return response.choices[0].message.content.strip()
def _generate_seo(self, request: ContentRequest, content: str) -> SEOMetadata:
"""Step 4: 生成SEO元数据"""
prompt = f"""请为以下文章生成SEO优化的元数据。
## 文章主题
{request.topic}
## 关键词
{', '.join(request.keywords) if request.keywords else '根据内容自动提取'}
## 文章开头
{content[:500]}
## 要求
- meta_title: 包含主关键词,50-60字符
- meta_description: 概括文章价值,150-160字符
- slug: 英文URL路径,用连字符分隔
- tags: 5-8个相关标签"""
response = client.beta.chat.completions.parse(
model=self.generation_model,
messages=[{"role": "user", "content": prompt}],
response_format=SEOMetadata,
temperature=0.3
)
return response.choices[0].message.parsed

运行示例

def main():
generator = ContentGenerator()
# 创建内容请求
request = ContentRequest(
topic="2025年中小企业如何利用AI提升运营效率",
content_type=ContentType.BLOG,
audience=Audience.GENERAL,
tone="专业但通俗易懂,带有实际案例",
word_count=1500,
keywords=["AI", "中小企业", "运营效率", "降本增效"],
language="zh-CN"
)
# 生成
result = generator.generate(request)
# 输出结果
print("\n" + "=" * 60)
print("生成结果")
print("=" * 60)
print(f"\n标题: {result['outline'].title}")
print(f"字数: {result['metadata']['word_count']}")
print(f"质量: {result['quality'].overall}/5")
print(f"SEO: {result['seo'].meta_title}")
print(f"\n{'='*60}")
print(result['content'][:800])
print("...")
if __name__ == "__main__":
main()

项目中的提示工程技术对照

技术 在本项目中的应用 对应章节
结构化输出 ContentOutline、QualityScore 等 Pydantic 模型 第3章第2节
提示链 4步串行生成:大纲→撰写→审核→SEO 第3章第3节
角色设定 策划师、写手、编辑等不同角色的 System Prompt 第3章第1节
LLM-as-Judge 用 GPT-4o 审核 GPT-4o-mini 的输出 第5章第1节
迭代重试 评分不达标时自动改进并重新审核 第5章第2节
模型分级 生成用便宜模型,审核用强模型 第3章第3节

动手练习

练习:扩展内容生成系统

在现有代码基础上,实现以下扩展功能(选做):

  1. 多语言支持 — 添加英文、日文输出选项,生成后自动翻译
  2. 引用数据 — 集成 Web Search API,在文章中插入真实数据和引用来源
  3. 图片建议 — 为每个章节生成配图描述(可用于后续 DALL·E 生成)
  4. 批量生成 — 支持一次性生成系列文章(如"AI系列"共5篇),保持一致性
  5. A/B测试 — 生成两个不同风格的版本,通过 LLM-as-Judge 选出更好的

本节要点


下一步实战:数据分析与信息抽取 🚀