Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
{ "task_tree": { "step_description": "北京学区房综合评测", "execution_type": "sequential", "children": [ { "step_description": "教育资源分析", "execution_type": "parallel", "tasks": [ { "agent_name": "tavily_agent", "agent_input": "搜索北京市东城/西城/海淀等核心区域重点中小学最新排名及升学政策" }, { "agent_name": "firecrawl_agent", "agent_input": "抓取北京市教育委员会官网及权威教育平台,整理各学区学校师资力量、重点班设置等详细数据" } ] }, { "step_description": "房价与市场数据收集", "execution_type": "parallel", "tasks": [ { "agent_name": "tavily_agent", "agent_input": "获取2023-2024年北京核心学区房均价走势及交易活跃度报告" }, { "agent_name": "firecrawl_agent", "agent_input": "爬取链家/贝壳等平台,统计目标区域不同类型房产近6个月成交周期与价格波动" } ] }, { "step_description": "居住环境调研", "execution_type": "parallel", "tasks": [ { "agent_name": "tavily_agent", "agent_input": "查询北京市规划和自然资源委员会,获取目标区域基础设施规划文件" }, { "agent_name": "firecrawl_agent", "agent_input": "采集知乎/豆瓣小组用户对目标学区房小区环境、物业管理的评价数据" } ] }, { "step_description": "市场交易深度分析", "execution_type": "sequential", "tasks": [ { "agent_name": "tavily_agent", "agent_input": "获取北京二手房市场季度报告中的学区房专项分析" } ], "children": [ { "step_description": "交易数据验证", "execution_type": "parallel", "tasks": [ { "agent_name": "firecrawl_agent", "agent_input": "抓取目标区域典型楼盘的房天下/安居客历史成交记录" }, { "agent_name": "tavily_agent", "agent_input": "搜索北京市住建委关于学区房交易政策调整的最新通知" } ] } ] } ] } } 类似这种生成后 我解析到这个json后,我希望给我打造一个 智能体框架!用python实现!功能要求:1.首先可以解析清楚所有任务节点,可以并行或者串行的去执行agent调用。2.每一个agent节点需要可以追踪是否已经完成其子任务。3.每一个agent节点包含其所有的父任务,其当前输入的任务,当前输出的结果。4.任何串行的任务,当前任务都可以随时获取与之串行任务的结果(包括与之串行的任务里面有并行的子任务)
我来为你设计一个智能体任务执行框架。这个框架将支持任务树的解析、并行/串行执行、状态追踪和结果共享。
import asyncio
import json
import uuid
from typing import Dict, List, Optional, Any, Union
from enum import Enum
from dataclasses import dataclass, field
from abc import ABC, abstractmethod
import logging
from datetime import datetime
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ExecutionType(Enum):
SEQUENTIAL = "sequential"
PARALLEL = "parallel"
class TaskStatus(Enum):
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
@dataclass
class TaskResult:
"""任务执行结果"""
task_id: str
status: TaskStatus
output: Any = None
error: Optional[str] = None
start_time: Optional[datetime] = None
end_time: Optional[datetime] = None
@property
def duration(self) -> Optional[float]:
if self.start_time and self.end_time:
return (self.end_time - self.start_time).total_seconds()
return None
@dataclass
class AgentTask:
"""单个智能体任务"""
agent_name: str
agent_input: str
task_id: str = field(default_factory=lambda: str(uuid.uuid4()))
result: Optional[TaskResult] = None
@dataclass
class TaskNode:
"""任务节点"""
step_description: str
execution_type: ExecutionType
node_id: str = field(default_factory=lambda: str(uuid.uuid4()))
tasks: List[AgentTask] = field(default_factory=list)
children: List['TaskNode'] = field(default_factory=list)
parent: Optional['TaskNode'] = None
result: Optional[TaskResult] = None
def __post_init__(self):
# 设置子节点的父节点引用
for child in self.children:
child.parent = self
class BaseAgent(ABC):
"""智能体基类"""
def __init__(self, name: str):
self.name = name
@abstractmethod
async def execute(self, input_data: str, context: Dict[str, Any] = None) -> Any:
"""执行智能体任务"""
pass
class TavilyAgent(BaseAgent):
"""Tavily搜索智能体示例"""
async def execute(self, input_data: str, context: Dict[str, Any] = None) -> Any:
logger.info(f"TavilyAgent执行: {input_data}")
# 模拟异步执行
await asyncio.sleep(2)
return f"Tavily搜索结果: {input_data}"
class FirecrawlAgent(BaseAgent):
"""Firecrawl爬虫智能体示例"""
async def execute(self, input_data: str, context: Dict[str, Any] = None) -> Any:
logger.info(f"FirecrawlAgent执行: {input_data}")
# 模拟异步执行
await asyncio.sleep(3)
return f"Firecrawl爬取结果: {input_data}"
class TaskExecutor:
"""任务执行器"""
def __init__(self):
self.agents: Dict[str, BaseAgent] = {}
self.results_store: Dict[str, TaskResult] = {}
self.execution_context: Dict[str, Any] = {}
def register_agent(self, agent: BaseAgent):
"""注册智能体"""
self.agents[agent.name] = agent
def parse_task_tree(self, task_tree_json: Dict) -> TaskNode:
"""解析任务树JSON"""
return self._parse_node(task_tree_json["task_tree"])
def _parse_node(self, node_data: Dict, parent: Optional[TaskNode] = None) -> TaskNode:
"""递归解析节点"""
execution_type = ExecutionType(node_data["execution_type"])
node = TaskNode(
step_description=node_data["step_description"],
execution_type=execution_type,
parent=parent
)
# 解析直接任务
if "tasks" in node_data:
for task_data in node_data["tasks"]:
agent_task = AgentTask(
agent_name=task_data["agent_name"],
agent_input=task_data["agent_input"]
)
node.tasks.append(agent_task)
# 解析子节点
if "children" in node_data:
for child_data in node_data["children"]:
child_node = self._parse_node(child_data, node)
node.children.append(child_node)
return node
async def execute_task_tree(self, root_node: TaskNode) -> TaskResult:
"""执行整个任务树"""
logger.info(f"开始执行任务树: {root_node.step_description}")
try:
result = await self._execute_node(root_node)
logger.info(f"任务树执行完成: {root_node.step_description}")
return result
except Exception as e:
logger.error(f"任务树执行失败: {e}")
raise
async def _execute_node(self, node: TaskNode) -> TaskResult:
"""执行单个节点"""
logger.info(f"执行节点: {node.step_description} ({node.execution_type.value})")
start_time = datetime.now()
node.result = TaskResult(
task_id=node.node_id,
status=TaskStatus.RUNNING,
start_time=start_time
)
try:
# 构建执行上下文
context = self._build_context(node)
if node.execution_type == ExecutionType.PARALLEL:
results = await self._execute_parallel(node, context)
else: # SEQUENTIAL
results = await self._execute_sequential(node, context)
# 更新节点结果
node.result.status = TaskStatus.COMPLETED
node.result.output = results
node.result.end_time = datetime.now()
# 存储结果
self.results_store[node.node_id] = node.result
return node.result
except Exception as e:
node.result.status = TaskStatus.FAILED
node.result.error = str(e)
node.result.end_time = datetime.now()
self.results_store[node.node_id] = node.result
raise
def _build_context(self, node: TaskNode) -> Dict[str, Any]:
"""构建执行上下文,包含所有父任务和串行前置任务的结果"""
context = {
"node_id": node.node_id,
"parent_results": {},
"sequential_results": {},
"all_results": self.results_store.copy()
}
# 获取所有父任务结果
current = node.parent
while current:
if current.result and current.result.status == TaskStatus.COMPLETED:
context["parent_results"][current.node_id] = current.result.output
current = current.parent
# 获取串行前置任务结果
if node.parent and node.parent.execution_type == ExecutionType.SEQUENTIAL:
parent = node.parent
for sibling in parent.children:
if sibling == node:
break
if sibling.result and sibling.result.status == TaskStatus.COMPLETED:
context["sequential_results"][sibling.node_id] = sibling.result.output
return context
async def _execute_parallel(self, node: TaskNode, context: Dict[str, Any]) -> Dict[str, Any]:
"""并行执行任务"""
tasks = []
# 执行直接任务
for agent_task in node.tasks:
task_coro = self._execute_agent_task(agent_task, context)
tasks.append(task_coro)
# 执行子节点
for child in node.children:
child_coro = self._execute_node(child)
tasks.append(child_coro)
if tasks:
results = await asyncio.gather(*tasks, return_exceptions=True)
# 处理结果
output = {
"agent_results": [],
"child_results": []
}
agent_count = len(node.tasks)
for i, result in enumerate(results):
if isinstance(result, Exception):
raise result
if i < agent_count:
output["agent_results"].append(result)
else:
output["child_results"].append(result)
return output
return {}
async def _execute_sequential(self, node: TaskNode, context: Dict[str, Any]) -> Dict[str, Any]:
"""串行执行任务"""
output = {
"agent_results": [],
"child_results": []
}
# 串行执行直接任务
for agent_task in node.tasks:
result = await self._execute_agent_task(agent_task, context)
output["agent_results"].append(result)
# 更新上下文,让后续任务能访问前面的结果
context["sequential_results"][agent_task.task_id] = result
# 串行执行子节点
for child in node.children:
result = await self._execute_node(child)
output["child_results"].append(result)
# 更新上下文
context["sequential_results"][child.node_id] = result.output
return output
async def _execute_agent_task(self, agent_task: AgentTask, context: Dict[str, Any]) -> Any:
"""执行单个智能体任务"""
if agent_task.agent_name not in self.agents:
raise ValueError(f"未找到智能体: {agent_task.agent_name}")
start_time = datetime.now()
agent_task.result = TaskResult(
task_id=agent_task.task_id,
status=TaskStatus.RUNNING,
start_time=start_time
)
try:
agent = self.agents[agent_task.agent_name]
output = await agent.execute(agent_task.agent_input, context)
agent_task.result.status = TaskStatus.COMPLETED
agent_task.result.output = output
agent_task.result.end_time = datetime.now()
# 存储结果
self.results_store[agent_task.task_id] = agent_task.result
return output
except Exception as e:
agent_task.result.status = TaskStatus.FAILED
agent_task.result.error = str(e)
agent_task.result.end_time = datetime.now()
self.results_store[agent_task.task_id] = agent_task.result
raise
def get_task_status(self, task_id: str) -> Optional[TaskResult]:
"""获取任务状态"""
return self.results_store.get(task_id)
def get_all_results(self) -> Dict[str, TaskResult]:
"""获取所有任务结果"""
return self.results_store.copy()
def print_execution_summary(self, root_node: TaskNode):
"""打印执行摘要"""
print("\n" + "="*50)
print("任务执行摘要")
print("="*50)
self._print_node_summary(root_node, 0)
def _print_node_summary(self, node: TaskNode, indent: int):
"""递归打印节点摘要"""
prefix = " " * indent
status = node.result.status.value if node.result else "未执行"
duration = f"{node.result.duration:.2f}s" if node.result and node.result.duration else "N/A"
print(f"{prefix}📋 {node.step_description}")
print(f"{prefix} 状态: {status} | 耗时: {duration} | 类型: {node.execution_type.value}")
# 打印直接任务
for task in node.tasks:
task_status = task.result.status.value if task.result else "未执行"
task_duration = f"{task.result.duration:.2f}s" if task.result and task.result.duration else "N/A"
print(f"{prefix} 🤖 {task.agent_name}: {task_status} ({task_duration})")
# 递归打印子节点
for child in node.children:
self._print_node_summary(child, indent + 1)
# 使用示例
async def main():
# 创建任务执行器
executor = TaskExecutor()
# 注册智能体
executor.register_agent(TavilyAgent("tavily_agent"))
executor.register_agent(FirecrawlAgent("firecrawl_agent"))
# 你的任务树JSON
task_tree_json = {
"task_tree": {
"step_description": "北京学区房综合评测",
"execution_type": "sequential",
"children": [
{
"step_description": "教育资源分析",
"execution_type": "parallel",
"tasks": [
{
"agent_name": "tavily_agent",
"agent_input": "搜索北京市东城/西城/海淀等核心区域重点中小学最新排名及升学政策"
},
{
"agent_name": "firecrawl_agent",
"agent_input": "抓取北京市教育委员会官网及权威教育平台,整理各学区学校师资力量、重点班设置等详细数据"
}
]
},
{
"step_description": "房价与市场数据收集",
"execution_type": "parallel",
"tasks": [
{
"agent_name": "tavily_agent",
"agent_input": "获取2023-2024年北京核心学区房均价走势及交易活跃度报告"
},
{
"agent_name": "firecrawl_agent",
"agent_input": "爬取链家/贝壳等平台,统计目标区域不同类型房产近6个月成交周期与价格波动"
}
]
},
{
"step_description": "居住环境调研",
"execution_type": "parallel",
"tasks": [
{
"agent_name": "tavily_agent",
"agent_input": "查询北京市规划和自然资源委员会,获取目标区域基础设施规划文件"
},
{
"agent