270 lines
7.6 KiB
Python
270 lines
7.6 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
Agent协作演示
|
||
展示如何让不同AI agent以真实身份协作完成任务
|
||
|
||
这个演示模拟以下场景:
|
||
1. 架构师agent设计系统架构
|
||
2. 开发者agent实现核心功能
|
||
3. 运维agent配置部署
|
||
4. 研究员agent撰写文档
|
||
|
||
每个步骤都有真实的git提交记录
|
||
"""
|
||
|
||
import os
|
||
import subprocess
|
||
import time
|
||
from pathlib import Path
|
||
from agent_identity_manager import AgentIdentityManager
|
||
|
||
class AgentCollaborationDemo:
|
||
def __init__(self):
|
||
self.manager = AgentIdentityManager()
|
||
self.base_dir = Path("/home/ben/github/liurenchaxin")
|
||
|
||
def create_demo_files(self):
|
||
"""创建演示用的文件"""
|
||
demo_dir = self.base_dir / "demo_feature"
|
||
demo_dir.mkdir(exist_ok=True)
|
||
|
||
# 架构师的设计文档
|
||
architecture_file = demo_dir / "architecture.md"
|
||
architecture_content = """# 新功能架构设计
|
||
|
||
## 概述
|
||
设计一个智能监控系统,用于跟踪AI agent的工作状态。
|
||
|
||
## 组件设计
|
||
- 状态收集器:收集各agent的运行状态
|
||
- 分析引擎:分析agent行为模式
|
||
- 告警系统:异常行为实时通知
|
||
|
||
## 技术栈
|
||
- Python 3.9+
|
||
- Redis作为消息队列
|
||
- PostgreSQL存储状态数据
|
||
- FastAPI提供REST接口
|
||
"""
|
||
architecture_file.write_text(architecture_content)
|
||
|
||
# 开发者的实现代码
|
||
core_file = demo_dir / "monitor.py"
|
||
core_content = """#!/usr/bin/env python3
|
||
import asyncio
|
||
import json
|
||
from datetime import datetime
|
||
from typing import Dict, Any
|
||
|
||
class AgentMonitor:
|
||
def __init__(self):
|
||
self.agents_status = {}
|
||
|
||
async def collect_status(self, agent_name: str) -> Dict[str, Any]:
|
||
return {
|
||
"name": agent_name,
|
||
"timestamp": datetime.now().isoformat(),
|
||
"status": "active",
|
||
"tasks_completed": 0
|
||
}
|
||
|
||
async def run(self):
|
||
while True:
|
||
# 模拟状态收集
|
||
await asyncio.sleep(1)
|
||
|
||
if __name__ == "__main__":
|
||
monitor = AgentMonitor()
|
||
asyncio.run(monitor.run())
|
||
"""
|
||
core_file.write_text(core_content)
|
||
|
||
# 运维的配置文件
|
||
config_file = demo_dir / "deploy.yaml"
|
||
config_content = """version: '3.8'
|
||
services:
|
||
agent-monitor:
|
||
build: .
|
||
ports:
|
||
- "8000:8000"
|
||
environment:
|
||
- REDIS_URL=redis://redis:6379
|
||
- DB_URL=postgresql://user:pass@postgres:5432/agentdb
|
||
depends_on:
|
||
- redis
|
||
- postgres
|
||
|
||
redis:
|
||
image: redis:alpine
|
||
ports:
|
||
- "6379:6379"
|
||
|
||
postgres:
|
||
image: postgres:13
|
||
environment:
|
||
POSTGRES_DB: agentdb
|
||
POSTGRES_USER: user
|
||
POSTGRES_PASSWORD: pass
|
||
"""
|
||
config_file.write_text(config_content)
|
||
|
||
# 研究员的文档
|
||
docs_file = demo_dir / "usage_guide.md"
|
||
docs_content = """# Agent监控系统使用指南
|
||
|
||
## 快速开始
|
||
|
||
### 1. 启动监控服务
|
||
```bash
|
||
docker-compose up -d
|
||
```
|
||
|
||
### 2. 查看agent状态
|
||
```bash
|
||
curl http://localhost:8000/api/agents
|
||
```
|
||
|
||
### 3. 配置告警
|
||
编辑 `config/alerts.yaml` 文件设置告警规则。
|
||
|
||
## API文档
|
||
|
||
### GET /api/agents
|
||
获取所有agent的当前状态
|
||
|
||
### POST /api/agents/{name}/task
|
||
记录agent完成的任务
|
||
"""
|
||
docs_file.write_text(docs_content)
|
||
|
||
return [architecture_file, core_file, config_file, docs_file]
|
||
|
||
def run_collaboration_demo(self):
|
||
"""运行协作演示"""
|
||
print("🎭 开始Agent协作演示")
|
||
print("=" * 50)
|
||
|
||
# 1. 架构师设计
|
||
print("1️⃣ 架构师agent开始设计...")
|
||
files = self.create_demo_files()
|
||
self.manager.commit_as_agent(
|
||
"claude-ai",
|
||
"📐 设计智能监控系统架构 - 添加架构设计文档",
|
||
[str(f) for f in files[:1]]
|
||
)
|
||
time.sleep(1)
|
||
|
||
# 2. 开发者实现
|
||
print("2️⃣ 开发者agent开始编码...")
|
||
self.manager.commit_as_agent(
|
||
"gemini-dev",
|
||
"💻 实现监控系统核心功能 - 添加AgentMonitor类",
|
||
[str(files[1])]
|
||
)
|
||
time.sleep(1)
|
||
|
||
# 3. 运维配置
|
||
print("3️⃣ 运维agent配置部署...")
|
||
self.manager.commit_as_agent(
|
||
"qwen-ops",
|
||
"⚙️ 添加Docker部署配置 - 支持一键启动",
|
||
[str(files[2])]
|
||
)
|
||
time.sleep(1)
|
||
|
||
# 4. 研究员文档
|
||
print("4️⃣ 研究员agent撰写文档...")
|
||
self.manager.commit_as_agent(
|
||
"llama-research",
|
||
"📚 完善使用文档 - 添加API说明和快速指南",
|
||
[str(files[3])]
|
||
)
|
||
time.sleep(1)
|
||
|
||
# 5. 架构师review
|
||
print("5️⃣ 架构师review并优化...")
|
||
optimize_file = self.base_dir / "demo_feature" / "optimization.md"
|
||
optimize_content = """# 架构优化建议
|
||
|
||
基于实现代码的review,提出以下优化:
|
||
|
||
## 性能优化
|
||
- 使用asyncio.create_task替换直接调用
|
||
- 添加连接池管理
|
||
|
||
## 监控增强
|
||
- 添加prometheus指标收集
|
||
- 实现健康检查端点
|
||
|
||
## 下一步计划
|
||
1. 实现告警系统
|
||
2. 添加Web界面
|
||
3. 集成日志分析
|
||
"""
|
||
optimize_file.write_text(optimize_content)
|
||
|
||
self.manager.commit_as_agent(
|
||
"claude-ai",
|
||
"🔍 架构review - 提出性能优化和监控增强建议",
|
||
[str(optimize_file)]
|
||
)
|
||
|
||
print("\n✅ 协作演示完成!")
|
||
|
||
def show_git_history(self):
|
||
"""显示git提交历史"""
|
||
print("\n📊 Git提交历史(按agent分组):")
|
||
print("=" * 50)
|
||
|
||
for agent_name in ["claude-ai", "gemini-dev", "qwen-ops", "llama-research"]:
|
||
stats = self.manager.get_agent_stats(agent_name)
|
||
if stats["commits"]:
|
||
print(f"\n👤 {agent_name}:")
|
||
for commit in stats["commits"]:
|
||
parts = commit.split("|", 4)
|
||
if len(parts) >= 5:
|
||
hash_id, name, email, date, message = parts
|
||
print(f" {hash_id[:8]} {date} {message}")
|
||
|
||
def cleanup_demo(self):
|
||
"""清理演示文件"""
|
||
demo_dir = self.base_dir / "demo_feature"
|
||
if demo_dir.exists():
|
||
# 保留git历史,只移除工作区文件
|
||
subprocess.run(["git", "rm", "-rf", "demo_feature"],
|
||
cwd=self.base_dir, capture_output=True)
|
||
subprocess.run(["git", "commit", "-m", "🧹 清理演示文件 - 保留协作历史"],
|
||
cwd=self.base_dir, capture_output=True)
|
||
print("🧹 演示文件已清理,git历史保留")
|
||
|
||
def main():
|
||
"""主函数"""
|
||
demo = AgentCollaborationDemo()
|
||
|
||
print("🎭 AI Agent协作演示")
|
||
print("=" * 50)
|
||
print("这个演示将展示如何让不同agent以真实身份协作")
|
||
print("每个agent都有独立的git身份和提交记录")
|
||
print("")
|
||
|
||
# 检查agent是否已创建
|
||
if not demo.manager.list_agents():
|
||
print("❌ 请先运行 ./agents/setup_agents.sh 创建agent")
|
||
return
|
||
|
||
# 运行演示
|
||
demo.run_collaboration_demo()
|
||
demo.show_git_history()
|
||
|
||
print("\n💡 下一步:")
|
||
print("1. 查看git log --oneline --graph 查看提交历史")
|
||
print("2. 使用 ./agents/stats.sh 查看agent统计")
|
||
print("3. 开始你自己的多agent协作项目!")
|
||
|
||
# 询问是否清理
|
||
response = input("\n是否清理演示文件?(y/N): ")
|
||
if response.lower() == 'y':
|
||
demo.cleanup_demo()
|
||
|
||
if __name__ == "__main__":
|
||
main() |