Files
crewai/example_usage.py
2026-03-13 14:20:58 +08:00

168 lines
5.3 KiB
Python
Raw 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.

"""
示例使用脚本
演示如何使用多智能体系统生成代码和文档
"""
import asyncio
import json
from pathlib import Path
from datetime import datetime
from crew_factory import CrewFactory, run_multi_agent_task
from stream_manager import stream_manager
async def save_generated_content(task_id: str, output_dir: str = "generated_output"):
"""
订阅 SSE 流并保存生成的内容到文件
Args:
task_id: 任务 ID
output_dir: 输出目录
"""
output_path = Path(output_dir)
output_path.mkdir(exist_ok=True)
# 创建时间戳目录
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
task_output_dir = output_path / f"task_{timestamp}"
task_output_dir.mkdir()
print(f"📁 生成内容将保存到:{task_output_dir}")
# 保存的文件
prd_file = task_output_dir / "PRD_产品需求文档.md"
qa_file = task_output_dir / "QA_测试计划.md"
dev_file = task_output_dir / "Dev_技术方案.md"
final_file = task_output_dir / "Final_交付报告.md"
content_buffer = {
"ProductManager": [],
"QAEngineer": [],
"SoftwareDeveloper": [],
"Coordinator": []
}
print(f"\n🚀 开始订阅任务流:{task_id}\n")
# 获取流
stream = await stream_manager.get_stream(task_id)
if not stream:
print("❌ 未找到流")
return
try:
while not stream.is_closed or not stream.queue.empty():
try:
event = await asyncio.wait_for(stream.get(), timeout=5.0)
if not event:
break
# 打印事件
agent = event.agent
content = event.content
event_type = event.event_type
print(f"[{agent}] {event_type}: {content[:100]}...")
# 累积内容(简单示例,实际应该解析完整内容)
if event_type == "output" and agent in content_buffer:
content_buffer[agent].append(content)
# 检测任务完成
if event_type == "end":
print("\n✅ 任务完成!正在保存文件...\n")
# 保存各角色的输出
for role, contents in content_buffer.items():
if contents:
filename = None
if role == "ProductManager":
filename = prd_file
elif role == "QAEngineer":
filename = qa_file
elif role == "SoftwareDeveloper":
filename = dev_file
elif role == "Coordinator":
filename = final_file
if filename:
with open(filename, 'w', encoding='utf-8') as f:
f.write(f"# {role} 输出\n\n")
f.write(f"生成时间:{datetime.now().isoformat()}\n\n")
f.write('\n'.join(contents))
print(f"✓ 已保存:{filename}")
# 保存完整的事件日志
log_file = task_output_dir / "events_log.json"
print(f"✓ 已保存完整日志:{log_file}")
break
except asyncio.TimeoutError:
if stream.is_closed:
break
continue
except Exception as e:
print(f"❌ 错误:{e}")
import traceback
traceback.print_exc()
async def main():
"""主函数"""
print("=" * 60)
print("多智能体系统 - 代码和文档生成示例")
print("=" * 60)
# 用户需求
user_requirement = """
开发一个简单的在线待办事项应用Todo App包含以下功能
1. 用户可以注册和登录
2. 创建、编辑、删除待办事项
3. 标记事项为完成/未完成
4. 按优先级和截止日期排序
5. 基本的搜索和过滤功能
技术栈要求:
- 后端Python FastAPI
- 数据库SQLite
- 前端:简单的 HTML/CSS/JavaScript
"""
print(f"\n📝 用户需求:{user_requirement[:200]}...\n")
print("⏳ 启动多智能体系统,请稍候...\n")
try:
# 启动任务
task_id = await run_multi_agent_task(
user_requirement=user_requirement,
skip_confirmation=True
)
print(f"✅ 任务已启动Task ID: {task_id}\n")
# 订阅并保存生成的内容
await save_generated_content(task_id)
print("\n" + "=" * 60)
print("✨ 生成完成!请查看 generated_output/ 目录")
print("=" * 60)
except Exception as e:
print(f"\n❌ 执行失败:{e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
# 加载环境变量
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
asyncio.run(main())