469 lines
16 KiB
Python
Executable File
469 lines
16 KiB
Python
Executable File
#!/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_smart_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()
|
||
|
||
# 查找可用的节点模板(优先选择特定类型的模板)
|
||
# 优先查找:工作流设计、API集成、数据分析、业务流程等类型的模板
|
||
preferred_categories = ["工作流设计", "API集成", "数据分析", "业务流程", "技术方案"]
|
||
|
||
templates = []
|
||
for category in preferred_categories:
|
||
category_templates = db.query(NodeTemplate).filter(
|
||
((NodeTemplate.is_public == True) | (NodeTemplate.user_id == user.id)) &
|
||
(NodeTemplate.category == category)
|
||
).limit(2).all()
|
||
templates.extend(category_templates)
|
||
|
||
# 如果没找到足够的模板,补充其他公开模板
|
||
if len(templates) < 3:
|
||
other_templates = db.query(NodeTemplate).filter(
|
||
(NodeTemplate.is_public == True) | (NodeTemplate.user_id == user.id)
|
||
).limit(5).all()
|
||
for t in other_templates:
|
||
if t not in templates:
|
||
templates.append(t)
|
||
if len(templates) >= 5:
|
||
break
|
||
|
||
if len(templates) < 2:
|
||
print(f"⚠️ 警告: 只找到 {len(templates)} 个节点模板,将使用LLM节点代替")
|
||
use_templates = False
|
||
else:
|
||
use_templates = True
|
||
print(f"📋 找到 {len(templates)} 个可用节点模板")
|
||
for i, template in enumerate(templates[:5], 1):
|
||
print(f" {i}. {template.name} ({template.category})")
|
||
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": "2000",
|
||
"prompt": """你是一位专业的需求分析师。请分析用户的需求,并提取关键信息。
|
||
|
||
用户需求:{input}
|
||
|
||
请按照以下格式输出JSON:
|
||
{{
|
||
"requirement_type": "技术方案|业务流程|数据分析|工作流设计|其他",
|
||
"key_points": ["关键点1", "关键点2", ...],
|
||
"complexity": "简单|中等|复杂",
|
||
"domain": "领域(如:电商、金融、教育等)",
|
||
"summary": "需求摘要"
|
||
}}"""
|
||
}
|
||
}
|
||
nodes.append(requirement_analysis_node)
|
||
edges.append({
|
||
"id": "e1",
|
||
"source": "start-1",
|
||
"target": "llm-requirement-analysis"
|
||
})
|
||
|
||
# 3. 需求分类节点(条件节点)
|
||
classification_node = {
|
||
"id": "condition-classify",
|
||
"type": "condition",
|
||
"position": {"x": 450, "y": 300},
|
||
"data": {
|
||
"label": "需求分类",
|
||
"condition": "{{requirement_type}} == '技术方案' or {{requirement_type}} == 'API集成'"
|
||
}
|
||
}
|
||
nodes.append(classification_node)
|
||
edges.append({
|
||
"id": "e2",
|
||
"source": "llm-requirement-analysis",
|
||
"target": "condition-classify"
|
||
})
|
||
|
||
# 4. 技术方案分支(如果使用模板)
|
||
if use_templates and len(templates) > 0:
|
||
# 查找技术方案相关的模板
|
||
tech_template = None
|
||
for t in templates:
|
||
if "技术" in t.category or "API" in t.category or "集成" in t.name:
|
||
tech_template = t
|
||
break
|
||
if not tech_template:
|
||
tech_template = templates[0]
|
||
|
||
tech_solution_node = {
|
||
"id": "template-tech-solution",
|
||
"type": "template",
|
||
"position": {"x": 650, "y": 200},
|
||
"data": {
|
||
"label": tech_template.name,
|
||
"template_id": tech_template.id,
|
||
"provider": tech_template.provider or "deepseek",
|
||
"model": tech_template.model or "deepseek-chat",
|
||
"temperature": str(tech_template.temperature) if tech_template.temperature else "0.7",
|
||
"max_tokens": str(tech_template.max_tokens) if tech_template.max_tokens else "2000",
|
||
"prompt": tech_template.prompt
|
||
}
|
||
}
|
||
nodes.append(tech_solution_node)
|
||
edges.append({
|
||
"id": "e3",
|
||
"source": "condition-classify",
|
||
"target": "template-tech-solution",
|
||
"sourceHandle": "true"
|
||
})
|
||
else:
|
||
# 使用LLM节点代替
|
||
tech_solution_node = {
|
||
"id": "llm-tech-solution",
|
||
"type": "llm",
|
||
"position": {"x": 650, "y": 200},
|
||
"data": {
|
||
"label": "技术方案设计",
|
||
"provider": "deepseek",
|
||
"model": "deepseek-chat",
|
||
"temperature": "0.7",
|
||
"max_tokens": "3000",
|
||
"prompt": """你是一位资深的技术架构师。根据需求分析结果,设计一个完整的技术方案。
|
||
|
||
需求分析结果:{{requirement_analysis}}
|
||
|
||
请提供:
|
||
1. 技术选型建议
|
||
2. 架构设计
|
||
3. 实施步骤
|
||
4. 风险评估
|
||
5. 最佳实践建议
|
||
|
||
输出格式:结构化的Markdown文档"""
|
||
}
|
||
}
|
||
nodes.append(tech_solution_node)
|
||
edges.append({
|
||
"id": "e3",
|
||
"source": "condition-classify",
|
||
"target": "llm-tech-solution",
|
||
"sourceHandle": "true"
|
||
})
|
||
|
||
# 5. 业务流程分支(优先使用LLM节点,确保能理解用户需求)
|
||
# 使用LLM节点而不是模板节点,因为LLM节点可以更好地理解需求上下文
|
||
process_solution_node = {
|
||
"id": "llm-process-solution",
|
||
"type": "llm",
|
||
"position": {"x": 650, "y": 400},
|
||
"data": {
|
||
"label": "业务流程设计",
|
||
"provider": "deepseek",
|
||
"model": "deepseek-chat",
|
||
"temperature": "0.7",
|
||
"max_tokens": "4000",
|
||
"prompt": """你是一位资深的业务流程设计专家。请根据用户的需求,设计一个完整、详细的业务流程方案。
|
||
|
||
**重要**:请仔细阅读用户原始需求,确保设计方案完全符合用户的具体需求。
|
||
|
||
用户原始需求:{{query}}
|
||
|
||
需求分析结果:{{requirement_analysis}}
|
||
|
||
请提供以下内容:
|
||
1. **流程概述**:整体流程的目标、范围和价值
|
||
2. **详细流程设计**:
|
||
- 流程的各个阶段和环节
|
||
- 每个环节的输入、输出和处理逻辑
|
||
- 状态流转图(用Mermaid或文字描述)
|
||
3. **关键步骤说明**:
|
||
- 每个步骤的具体操作
|
||
- 前置条件和后置条件
|
||
- 异常情况处理
|
||
4. **角色与职责**:
|
||
- 涉及的角色/系统
|
||
- 每个角色的职责和权限
|
||
5. **数据流转**:
|
||
- 关键数据在各环节的流转
|
||
- 数据格式和验证规则
|
||
6. **异常处理机制**:
|
||
- 常见异常场景
|
||
- 异常处理流程
|
||
7. **流程优化建议**:
|
||
- 性能优化点
|
||
- 用户体验优化
|
||
8. **实施路线图**:
|
||
- 分阶段实施计划
|
||
- 关键里程碑
|
||
|
||
**重要**:请确保设计方案完全符合用户的需求,不要偏离主题。如果用户需求是电商订单流程,就设计电商订单流程;如果是其他业务,就设计对应的业务流程。
|
||
|
||
输出格式:结构化的Markdown文档,使用清晰的标题和列表"""
|
||
}
|
||
}
|
||
nodes.append(process_solution_node)
|
||
edges.append({
|
||
"id": "e4",
|
||
"source": "condition-classify",
|
||
"target": "llm-process-solution",
|
||
"sourceHandle": "false"
|
||
})
|
||
|
||
# 6. 方案整合节点(Transform节点)
|
||
integration_node = {
|
||
"id": "transform-integration",
|
||
"type": "transform",
|
||
"position": {"x": 850, "y": 300},
|
||
"data": {
|
||
"label": "方案整合",
|
||
"mode": "merge",
|
||
"mapping": {
|
||
"solution": "{{result}}",
|
||
"requirement_analysis": "{{requirement_analysis}}",
|
||
"query": "{{query}}",
|
||
"timestamp": "{{timestamp}}"
|
||
}
|
||
}
|
||
}
|
||
nodes.append(integration_node)
|
||
|
||
# 连接分支到整合节点
|
||
if use_templates and len(templates) > 0:
|
||
edges.append({
|
||
"id": "e5",
|
||
"source": "template-tech-solution" if use_templates else "llm-tech-solution",
|
||
"target": "transform-integration"
|
||
})
|
||
else:
|
||
edges.append({
|
||
"id": "e5",
|
||
"source": "llm-tech-solution",
|
||
"target": "transform-integration"
|
||
})
|
||
|
||
# 业务流程分支始终使用LLM节点
|
||
edges.append({
|
||
"id": "e6",
|
||
"source": "llm-process-solution",
|
||
"target": "transform-integration"
|
||
})
|
||
|
||
# 7. 输出优化节点(LLM节点)
|
||
optimization_node = {
|
||
"id": "llm-optimization",
|
||
"type": "llm",
|
||
"position": {"x": 1050, "y": 300},
|
||
"data": {
|
||
"label": "输出优化与格式化",
|
||
"provider": "deepseek",
|
||
"model": "deepseek-chat",
|
||
"temperature": "0.5",
|
||
"max_tokens": "4000",
|
||
"prompt": """你是一位专业的技术文档编辑。请对方案进行优化和格式化,确保方案完全符合用户需求。
|
||
|
||
用户原始需求:{{query}}
|
||
需求分析结果:{{requirement_analysis}}
|
||
整合后的方案:{{solution}}
|
||
|
||
**重要检查**:
|
||
1. 确保方案内容与用户需求完全匹配
|
||
2. 如果方案偏离了用户需求,请重新生成符合需求的方案
|
||
3. 如果方案是关于数据清洗的,但用户需求是业务流程设计,请重新生成业务流程设计方案
|
||
|
||
请:
|
||
1. 检查方案是否完全符合用户需求
|
||
2. 优化文档结构,使其更清晰
|
||
3. 补充关键细节和实施建议
|
||
4. 确保格式统一、专业
|
||
5. 如果发现方案不符合需求,请重新生成正确的方案
|
||
|
||
**输出要求**:
|
||
- 只输出纯文本的Markdown文档内容
|
||
- 不要包含任何JSON格式、代码块标记或其他格式包装
|
||
- 直接输出方案文档的正文内容
|
||
- 确保内容完整、专业、易读
|
||
|
||
输出格式:直接输出完整的Markdown文档正文(纯文本)"""
|
||
}
|
||
}
|
||
nodes.append(optimization_node)
|
||
edges.append({
|
||
"id": "e7",
|
||
"source": "transform-integration",
|
||
"target": "llm-optimization"
|
||
})
|
||
|
||
# 8. 结束节点
|
||
end_node = {
|
||
"id": "end-1",
|
||
"type": "end",
|
||
"position": {"x": 1250, "y": 300},
|
||
"data": {
|
||
"label": "结束",
|
||
"output_format": "text" # 默认纯文本格式,适合对话场景
|
||
}
|
||
}
|
||
nodes.append(end_node)
|
||
edges.append({
|
||
"id": "e8",
|
||
"source": "llm-optimization",
|
||
"target": "end-1"
|
||
})
|
||
|
||
# 检查是否已存在同名Agent
|
||
agent_name = "智能需求分析与解决方案生成器"
|
||
existing = db.query(Agent).filter(
|
||
Agent.name == agent_name,
|
||
Agent.user_id == user.id
|
||
).first()
|
||
|
||
if existing:
|
||
print(f"⚠️ Agent '{agent_name}' 已存在,将更新它...")
|
||
existing.workflow_config = {"nodes": nodes, "edges": edges}
|
||
existing.description = """智能需求分析与解决方案生成Agent
|
||
|
||
功能特点:
|
||
1. 自动理解用户需求并提取关键信息
|
||
2. 根据需求类型智能分类(技术方案/业务流程/数据分析等)
|
||
3. 调用专业模板或LLM生成针对性解决方案
|
||
4. 整合并优化输出,生成专业文档
|
||
|
||
适用场景:
|
||
- 技术方案设计
|
||
- 业务流程优化
|
||
- 系统架构设计
|
||
- 问题分析与解决"""
|
||
existing.updated_at = datetime.now()
|
||
agent = existing
|
||
else:
|
||
# 创建Agent
|
||
agent = Agent(
|
||
name=agent_name,
|
||
description="""智能需求分析与解决方案生成Agent
|
||
|
||
功能特点:
|
||
1. 自动理解用户需求并提取关键信息
|
||
2. 根据需求类型智能分类(技术方案/业务流程/数据分析等)
|
||
3. 调用专业模板或LLM生成针对性解决方案
|
||
4. 整合并优化输出,生成专业文档
|
||
|
||
适用场景:
|
||
- 技术方案设计
|
||
- 业务流程优化
|
||
- 系统架构设计
|
||
- 问题分析与解决""",
|
||
workflow_config={"nodes": nodes, "edges": edges},
|
||
status="published", # 直接发布,可以直接使用
|
||
user_id=user.id,
|
||
version=1
|
||
)
|
||
db.add(agent)
|
||
|
||
try:
|
||
db.commit()
|
||
db.refresh(agent)
|
||
print()
|
||
print("=" * 60)
|
||
print(f"✅ 成功创建/更新智能Agent: {agent.name}")
|
||
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()
|
||
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="创建Agent的用户名(默认: admin)"
|
||
)
|
||
|
||
args = parser.parse_args()
|
||
|
||
db = SessionLocal()
|
||
try:
|
||
generate_smart_agent(db, username=args.username)
|
||
except Exception as e:
|
||
print(f"❌ 发生错误: {e}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
finally:
|
||
db.close()
|