Files
aiagent/backend/scripts/generate_content_agent.py
2026-01-19 17:52:29 +08:00

491 lines
16 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
生成内容生成助手Agent
这是一个专门用于内容生成的Agent能够根据用户需求生成各种类型的内容
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy.orm import Session
from app.core.database import SessionLocal
from app.models.agent import Agent
from app.models.user import User
from app.models.node_template import NodeTemplate
from datetime import datetime
import uuid
import json
def generate_content_agent(db: Session, username: str = "admin"):
"""生成内容生成助手Agent"""
print("=" * 60)
print("生成内容生成助手Agent")
print("=" * 60)
print()
# 查找用户
user = db.query(User).filter(User.username == username).first()
if not user:
print(f"❌ 未找到用户 '{username}',请先创建该用户")
return
print(f"✅ 找到用户: {user.username} (ID: {user.id})")
print()
# 生成内容生成工作流配置
# 工作流结构:
# 开始 -> 需求分析 -> 内容类型判断 -> [文章生成分支 | 文案生成分支 | 脚本生成分支] -> 内容优化 -> 格式检查 -> 结束
nodes = []
edges = []
# 1. 开始节点
start_node = {
"id": "start-1",
"type": "start",
"position": {"x": 50, "y": 300},
"data": {
"label": "开始",
"output_format": "json"
}
}
nodes.append(start_node)
# 2. 需求分析节点LLM节点
requirement_analysis_node = {
"id": "llm-requirement-analysis",
"type": "llm",
"position": {"x": 250, "y": 300},
"data": {
"label": "需求分析",
"provider": "deepseek",
"model": "deepseek-chat",
"temperature": "0.7",
"max_tokens": "1500",
"prompt": """你是一位专业的内容需求分析师。请分析用户的内容生成需求,提取关键信息。
用户输入:{{query}}
请分析并提取以下信息:
1. **内容类型**:文章、博客、营销文案、视频脚本、产品描述、社交媒体内容等
2. **主题/话题**:用户想要生成什么主题的内容
3. **目标受众**:内容面向的读者群体
4. **内容风格**:正式、轻松、专业、幽默等
5. **字数要求**:大概的字数范围
6. **特殊要求**:格式要求、关键词、结构要求等
请以JSON格式输出分析结果
{
"content_type": "内容类型",
"topic": "主题",
"target_audience": "目标受众",
"style": "内容风格",
"word_count": "字数要求",
"special_requirements": "特殊要求",
"keywords": ["关键词1", "关键词2"]
}"""
}
}
nodes.append(requirement_analysis_node)
edges.append({
"id": "e1",
"source": "start-1",
"target": "llm-requirement-analysis"
})
# 3. 内容整合节点Transform节点- 用于传递数据
content_prepare_node = {
"id": "transform-prepare",
"type": "transform",
"position": {"x": 450, "y": 300},
"data": {
"label": "准备数据",
"mode": "merge",
"mapping": {
"requirement_analysis": "{{output}}",
"query": "{{query}}"
}
}
}
nodes.append(content_prepare_node)
edges.append({
"id": "e2",
"source": "llm-requirement-analysis",
"target": "transform-prepare"
})
# 4. 内容类型判断节点(条件节点)
# 简化直接根据需求分析结果判断使用LLM输出中的关键词
content_type_condition = {
"id": "condition-content-type",
"type": "condition",
"position": {"x": 650, "y": 300},
"data": {
"label": "内容类型判断",
"condition": "{requirement_analysis} contains '文章' or {requirement_analysis} contains '博客' or {requirement_analysis} contains 'article'"
}
}
nodes.append(content_type_condition)
edges.append({
"id": "e2-1",
"source": "transform-prepare",
"target": "condition-content-type"
})
# 4. 文章生成节点LLM节点
article_generation_node = {
"id": "llm-article-generation",
"type": "llm",
"position": {"x": 650, "y": 200},
"data": {
"label": "文章生成",
"provider": "deepseek",
"model": "deepseek-chat",
"temperature": "0.8",
"max_tokens": "4000",
"prompt": """你是一位专业的内容创作专家。请根据用户需求生成一篇高质量的文章。
**用户原始需求**{{query}}
**需求分析结果**
- 主题:{{topic}}
- 目标受众:{{target_audience}}
- 内容风格:{{style}}
- 字数要求:{{word_count}}
- 特殊要求:{{special_requirements}}
- 关键词:{{keywords}}
请生成一篇结构完整、内容丰富的文章,要求:
1. **标题**:吸引人且准确反映内容
2. **引言**:引人入胜的开头,概述文章要点
3. **正文**
- 分多个段落,逻辑清晰
- 每个段落有明确的主题
- 使用适当的过渡词连接段落
- 包含具体例子、数据或案例(如适用)
4. **结论**:总结要点,给出行动建议或思考
5. **格式**使用Markdown格式包含标题、列表、加粗等
**重要**:确保内容完全符合用户需求,不要偏离主题。"""
}
}
nodes.append(article_generation_node)
# 6. 文案生成节点LLM节点
copywriting_node = {
"id": "llm-copywriting",
"type": "llm",
"position": {"x": 850, "y": 300},
"data": {
"label": "文案生成",
"provider": "deepseek",
"model": "deepseek-chat",
"temperature": "0.9",
"max_tokens": "2000",
"prompt": """你是一位资深的营销文案专家。请根据用户需求生成吸引人的营销文案。
**用户原始需求**{{query}}
**需求分析结果**
- 主题:{{topic}}
- 目标受众:{{target_audience}}
- 内容风格:{{style}}
- 字数要求:{{word_count}}
- 特殊要求:{{special_requirements}}
- 关键词:{{keywords}}
请生成营销文案,要求:
1. **标题/口号**:简洁有力,吸引眼球
2. **核心卖点**:突出产品或服务的核心价值
3. **情感共鸣**:触动目标受众的情感
4. **行动号召**:明确的行动指引
5. **语言风格**:符合目标受众的阅读习惯
**重要**:确保文案具有说服力和吸引力,能够有效传达信息并促使行动。"""
}
}
nodes.append(copywriting_node)
# 7. 脚本生成节点LLM节点
script_generation_node = {
"id": "llm-script-generation",
"type": "llm",
"position": {"x": 850, "y": 400},
"data": {
"label": "脚本生成",
"provider": "deepseek",
"model": "deepseek-chat",
"temperature": "0.8",
"max_tokens": "3000",
"prompt": """你是一位专业的视频/音频脚本创作专家。请根据用户需求生成专业的脚本。
**用户原始需求**{{query}}
**需求分析结果**
- 主题:{{topic}}
- 目标受众:{{target_audience}}
- 内容风格:{{style}}
- 字数要求:{{word_count}}
- 特殊要求:{{special_requirements}}
- 关键词:{{keywords}}
请生成脚本,要求:
1. **开场**:吸引注意力的开头
2. **主体内容**
- 分场景/段落
- 标注说话者(如适用)
- 包含动作提示(如适用)
- 时间控制建议
3. **结尾**:有力的总结或行动号召
4. **格式**:清晰标注场景、角色、动作等
**重要**:确保脚本结构清晰,适合视频或音频制作。"""
}
}
nodes.append(script_generation_node)
# 8. 通用内容生成节点(兜底)
general_generation_node = {
"id": "llm-general-generation",
"type": "llm",
"position": {"x": 850, "y": 500},
"data": {
"label": "通用内容生成",
"provider": "deepseek",
"model": "deepseek-chat",
"temperature": "0.8",
"max_tokens": "3000",
"prompt": """你是一位专业的内容创作专家。请根据用户需求生成高质量的内容。
**用户原始需求**{{query}}
**需求分析结果**
- 内容类型:{{content_type}}
- 主题:{{topic}}
- 目标受众:{{target_audience}}
- 内容风格:{{style}}
- 字数要求:{{word_count}}
- 特殊要求:{{special_requirements}}
- 关键词:{{keywords}}
请生成符合要求的内容,确保:
1. 内容完整、结构清晰
2. 符合目标受众的阅读习惯
3. 风格与要求一致
4. 包含必要的关键词
5. 满足字数要求
**重要**:确保生成的内容完全符合用户需求。"""
}
}
nodes.append(general_generation_node)
# 连接条件节点到各个生成节点
edges.append({
"id": "e3",
"source": "condition-content-type",
"target": "llm-article-generation",
"sourceHandle": "true",
"targetHandle": "input",
"condition": "article"
})
edges.append({
"id": "e4",
"source": "condition-content-type",
"target": "llm-copywriting",
"sourceHandle": "true",
"targetHandle": "input",
"condition": "copywriting"
})
edges.append({
"id": "e5",
"source": "condition-content-type",
"target": "llm-script-generation",
"sourceHandle": "true",
"targetHandle": "input",
"condition": "script"
})
edges.append({
"id": "e6",
"source": "condition-content-type",
"target": "llm-general-generation",
"sourceHandle": "false",
"targetHandle": "input"
})
# 9. 内容整合节点Transform节点
content_integration_node = {
"id": "transform-integration",
"type": "transform",
"position": {"x": 1050, "y": 300},
"data": {
"label": "内容整合",
"mode": "merge",
"mapping": {
"generated_content": "{{output}}",
"original_query": "{{query}}",
"requirement_analysis": "{{requirement_analysis}}"
}
}
}
nodes.append(content_integration_node)
# 连接所有生成节点到整合节点
for gen_node_id in ["llm-article-generation", "llm-copywriting", "llm-script-generation", "llm-general-generation"]:
edges.append({
"id": f"e-{gen_node_id}-integration",
"source": gen_node_id,
"target": "transform-integration"
})
# 10. 内容优化节点LLM节点
content_optimization_node = {
"id": "llm-optimization",
"type": "llm",
"position": {"x": 1250, "y": 300},
"data": {
"label": "内容优化",
"provider": "deepseek",
"model": "deepseek-chat",
"temperature": "0.7",
"max_tokens": "4000",
"prompt": """你是一位专业的内容编辑和优化专家。请对生成的内容进行优化和润色。
**用户原始需求**{{original_query}}
**需求分析结果**{{requirement_analysis}}
**生成的内容**{{generated_content}}
请对内容进行优化,确保:
1. **内容质量**
- 检查逻辑是否清晰
- 确保信息准确、完整
- 优化表达,使其更流畅
2. **格式规范**
- 检查Markdown格式是否正确
- 确保标题层级合理
- 优化段落结构
3. **风格一致性**
- 确保风格符合要求
- 统一用词和语调
4. **用户体验**
- 确保内容易读易懂
- 优化可读性
**输出要求**
- 直接输出优化后的完整内容纯文本Markdown格式
- 不要包含JSON格式或其他包装
- 确保内容完整、专业、易读"""
}
}
nodes.append(content_optimization_node)
edges.append({
"id": "e7",
"source": "transform-integration",
"target": "llm-optimization"
})
# 11. 结束节点
end_node = {
"id": "end-1",
"type": "end",
"position": {"x": 1450, "y": 300},
"data": {
"label": "结束",
"output_format": "text" # 默认纯文本格式,适合对话场景
}
}
nodes.append(end_node)
edges.append({
"id": "e8",
"source": "llm-optimization",
"target": "end-1"
})
# 创建或更新Agent
workflow_config = {
"nodes": nodes,
"edges": edges
}
agent = db.query(Agent).filter(
Agent.name == "内容生成助手",
Agent.user_id == user.id
).first()
if agent:
agent.workflow_config = workflow_config
agent.updated_at = datetime.now()
print("⚠️ Agent '内容生成助手' 已存在,将更新它...")
else:
agent = Agent(
id=str(uuid.uuid4()),
name="内容生成助手",
description="智能内容生成助手,能够根据用户需求生成各种类型的高质量内容,包括文章、博客、营销文案、视频脚本等。支持需求分析、内容生成、优化润色等完整流程。",
workflow_config=workflow_config,
status="published",
user_id=user.id,
version=1
)
db.add(agent)
try:
db.commit()
db.refresh(agent)
print()
print("=" * 60)
print(f"✅ 成功创建/更新内容生成助手Agent")
print(f" ID: {agent.id}")
print(f" 状态: {agent.status}")
print(f" 节点数量: {len(nodes)}")
print(f" 连接数量: {len(edges)}")
print("=" * 60)
print()
print("工作流结构:")
print(" 开始 -> 需求分析 -> 内容类型判断 -> [文章生成 | 文案生成 | 脚本生成 | 通用生成] -> 内容整合 -> 内容优化 -> 结束")
print()
print("节点说明:")
print(" 1. 开始节点:接收用户输入(主题、类型、要求等)")
print(" 2. 需求分析节点:分析用户需求,提取内容类型、主题、风格等关键信息")
print(" 3. 数据准备节点:整合需求分析结果和原始查询")
print(" 4. 内容类型判断节点:根据内容类型进行分支处理")
print(" 5. 文章生成节点:生成结构完整的文章内容")
print(" 6. 文案生成节点:生成营销文案、广告文案等")
print(" 7. 脚本生成节点:生成视频/音频脚本")
print(" 8. 通用内容生成节点:处理其他类型的内容生成需求")
print(" 9. 内容整合节点:整合生成的内容和需求信息")
print(" 10. 内容优化节点:优化和润色内容,确保质量")
print(" 11. 结束节点:返回最终优化后的内容")
print()
print("使用示例:")
print(" 输入:'帮我写一篇关于人工智能发展趋势的博客文章2000字左右风格轻松易懂'")
print(" 输入:'生成一个产品推广的营销文案,面向年轻白领群体'")
print(" 输入:'写一个5分钟的产品介绍视频脚本'")
print()
return agent
except Exception as e:
db.rollback()
print()
print("=" * 60)
print(f"❌ 创建失败: {e}")
print("=" * 60)
import traceback
traceback.print_exc()
raise
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="生成内容生成助手Agent")
parser.add_argument("--username", type=str, default="admin", help="用户名")
args = parser.parse_args()
db = SessionLocal()
try:
generate_content_agent(db, username=args.username)
finally:
db.close()