import json
import time
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
import logging
# 配置日志,便于追踪任务执行
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(threadName)s - %(levelname)s - %(message)s')
class AgentExecutionError(Exception):
"""自定义异常,用于表示Agent执行失败"""
pass
class TaskNode:
"""
表示任务树中的一个节点(一个步骤或一个独立的Agent任务)。
"""
def __init__(self, data: dict, parent_node=None):
self.step_description = data.get("step_description")
self.execution_type = data.get("execution_type", "sequential") # 默认为sequential
self.raw_tasks = data.get("tasks", []) # 原始的agent任务列表
self.children_data = data.get("children", []) # 原始的子节点数据
self.parent = parent_node
self.children = [] # 存储 TaskNode 实例
self.status = "pending" # pending, running, completed, failed
self.input_context = {} # 当前任务节点接收到的父任务或之前串行任务的汇总结果
self.output_results = {} # 当前任务节点执行完成后产生的结果
# 用于存储直接的agent调用实例,每个AgentCall会存储自己的输入和输出
self.agent_calls = []
for task_spec in self.raw_tasks:
self.agent_calls.append({
"agent_name": task_spec["agent_name"],
"agent_input": task_spec["agent_input"],
"output": None, # 任务执行后的输出
"status": "pending", # pending, running, completed, failed
"error": None # 如果失败,记录错误信息
})
# 路径追踪:从根节点到当前节点的描述链
self.full_path = self._build_full_path()
logging.debug(f"Initialized TaskNode: {self.step_description} (Path: {self.full_path})")
def _build_full_path(self):
"""构建从根节点到当前节点的完整路径描述"""
path = []
current = self
while current:
if current.step_description:
path.insert(0, current.step_description)
current = current.parent
return path
def add_child(self, child_node):
"""添加子任务节点"""
self.children.append(child_node)
def __repr__(self):
return (f"<TaskNode: '{self.step_description}', Type: {self.execution_type}, "
f"Status: {self.status}, Children: {len(self.children)}, "
f"Agents: {len(self.agent_calls)}>")
class AgentFramework:
"""
智能体框架的核心调度器。
负责解析任务树,执行任务,管理任务状态和结果传递。
"""
def __init__(self, task_json: dict):
self.root_node = self._build_task_tree(task_json["task_tree"])
self.executor = ThreadPoolExecutor(max_workers=5) # 用于并行任务的线程池
self.global_results = {} # 存储所有已完成任务的最终结果
def _build_task_tree(self, node_data: dict, parent_node: TaskNode = None) -> TaskNode:
"""
递归构建任务树。
"""
node = TaskNode(node_data, parent_node)
for child_data in node.children_data:
child_node = self._build_task_tree(child_data, node)
node.add_child(child_node)
return node
def _simulate_agent_call(self, agent_name: str, agent_input: str, current_node: TaskNode, agent_index: int, context: dict):
"""
模拟Agent的执行。
在实际应用中,这里会调用真正的Agent API。
agent_input是json中定义的静态输入,context是动态的上下文信息。
"""
full_path = current_node.full_path + [f"Agent Call {agent_index + 1} ({agent_name})"]
logging.info(f"[{' -> '.join(full_path)}] Agent START: Input='{agent_input[:50]}...'")
# 记录 Agent 节点的信息
agent_spec = current_node.agent_calls[agent_index]
agent_spec["status"] = "running"
try:
# 模拟Agent处理时间
time.sleep(1 + len(agent_input) % 3) # 根据输入长度模拟不同时间
# 模拟Agent输出。这里将Agent的输入和上下文信息整合作为输出。
# 真实场景中,Agent会根据input和context进行推理并返回实际结果。
simulated_output = (f"Agent '{agent_name}' processed input '{agent_input}'. "
f"It also had access to context keys: {list(context.keys())}. "
f"Simulated result for {current_node.step_description}/{agent_name}.")
agent_spec["output"] = simulated_output
agent_spec["status"] = "completed"
logging.info(f"[{' -> '.join(full_path)}] Agent COMPLETED. Output='{simulated_output[:70]}...'")
return simulated_output
except Exception as e:
agent_spec["status"] = "failed"
agent_spec["error"] = str(e)
logging.error(f"[{' -> '.join(full_path)}] Agent FAILED: {e}", exc_info=True)
raise AgentExecutionError(f"Agent '{agent_name}' failed: {e}")
def _execute_node(self, node: TaskNode, inherited_context: dict):
"""
递归执行任务树中的一个节点。
inherited_context 包含了所有之前已完成的串行任务的结果。
"""
node.status = "running"
node.input_context = inherited_context # 记录当前节点接收到的上下文
current_node_results = {} # 存储当前节点内部产生的直接结果
logging.info(f"[{' -> '.join(node.full_path)}] START: Execution Type='{node.execution_type}', Agents={len(node.agent_calls)}, Children={len(node.children)}")
try:
if node.execution_type == "parallel":
# 并行执行当前节点下的所有 Agent 任务
futures = []
for i, agent_spec in enumerate(node.agent_calls):
future = self.executor.submit(
self._simulate_agent_call,
agent_spec["agent_name"],
agent_spec["agent_input"],
node, # 传递当前节点,用于日志和状态追踪
i, # 传递Agent在列表中的索引,用于更新其状态
inherited_context # 将上下文传递给Agent
)
futures.append((future, agent_spec)) # 关联future和agent_spec
for future, agent_spec in as_completed(futures):
agent_name = agent_spec["agent_name"]
try:
result = future.result()
current_node_results[f"{agent_name}_{len(current_node_results)}"] = result # 确保key唯一
except AgentExecutionError as e:
logging.error(f"[{' -> '.join(node.full_path)}] Parallel Agent '{agent_name}' failed. Continuing with others if possible.")
# 如果是并行任务,一个失败不影响其他,但最终状态会标记为failed_with_errors
node.status = "failed_with_errors"
# 可以在这里选择是继续还是中断,这里选择继续
except Exception as e:
logging.error(f"[{' -> '.join(node.full_path)}] Unexpected error in parallel Agent '{agent_name}': {e}")
node.status = "failed_with_errors"
elif node.execution_type == "sequential":
# 串行执行当前节点下的所有 Agent 任务
for i, agent_spec in enumerate(node.agent_calls):
agent_name = agent_spec["agent_name"]
try:
# 串行任务的Agent可以访问到前面所有任务的累计结果
result = self._simulate_agent_call(
agent_name,
agent_spec["agent_input"],
node,
i,
{**inherited_context, **current_node_results} # Agent可访问的上下文
)
current_node_results[f"{agent_name}_{len(current_node_results)}"] = result # 确保key唯一
except AgentExecutionError:
node.status = "failed"
logging.error(f"[{' -> '.join(node.full_path)}] Sequential Agent '{agent_name}' failed. Aborting current node execution.")
raise # 串行任务失败通常需要中断整个序列
except Exception as e:
node.status = "failed"
logging.error(f"[{' -> '.join(node.full_path)}] Unexpected error in sequential Agent '{agent_name}': {e}")
raise
# 将当前节点内部的直接结果存储
node.output_results["direct_agent_outputs"] = current_node_results
# 合并当前节点的直接结果到传递给子节点的上下文
# 这里的 **操作符会合并字典,如果键相同,后面的会覆盖前面的
context_for_children = {**inherited_context, **current_node_results}
# 递归执行子节点
for child_node in node.children:
logging.debug(f"[{' -> '.join(node.full_path)}] Executing child: {child_node.step_description}")
# 串行执行子节点,并将当前累计结果传递给子节点
child_result = self._execute_node(child_node, context_for_children)
# 将子节点的结果合并到当前节点的输出中
# 确保子节点的输出不会覆盖父节点的直接输出,可以使用子节点的step_description作为键
if child_result:
node.output_results[f"child_{child_node.step_description}"] = child_result
# 更新传递给下一个子节点或后续任务的上下文
context_for_children.update(child_result)
node.status = "completed" if node.status != "failed_with_errors" else "completed_with_errors"
logging.info(f"[{' -> '.join(node.full_path)}] COMPLETED. Total Results: {len(node.output_results)}")
return node.output_results
except Exception as e:
node.status = "failed"
logging.error(f"[{' -> '.join(node.full_path)}] FAILED during execution: {e}", exc_info=True)
raise # 重新抛出异常,让上层知道任务失败
def execute(self):
"""
开始执行整个任务树。
"""
logging.info("Starting overall task execution...")
try:
# 初始上下文为空,或者可以预设一些全局参数
self.global_results = self._execute_node(self.root_node, inherited_context={})
logging.info("Overall task execution COMPLETED successfully!")
except Exception as e:
logging.error(f"Overall task execution FAILED: {e}", exc_info=True)
self.global_results = {"status": "failed", "error": str(e)}
finally:
self.executor.shutdown(wait=True)
logging.info("ThreadPoolExecutor shut down.")
self._print_final_status(self.root_node)
def _print_final_status(self, node: TaskNode, indent=0):
"""递归打印任务树的最终状态和结果摘要"""
prefix = " " * indent
logging.info(f"{prefix}- {node.step_description} [{node.status}]")
logging.info(f"{prefix} Input Context Keys: {list(node.input_context.keys())}")
logging.info(f"{prefix} Output Results Keys: {list(node.output_results.keys())}")
for i, agent_spec in enumerate(node.agent_calls):
logging.info(f"{prefix} Agent {i+1} ({agent_spec['agent_name']}): Status={agent_spec['status']}, Output_len={len(agent_spec['output']) if agent_spec['output'] else 'N/A'}")
if agent_spec['error']:
logging.error(f"{prefix} Error: {agent_spec['error']}")
for child in node.children:
self._print_final_status(child, indent + 1)
def get_results(self):
"""获取所有任务执行后的最终结果"""
return self.global_results
def get_task_status(self, path_segments: list):
"""根据路径获取特定任务节点的状态和结果"""
current_node = self.root_node
found = True
for segment in path_segments:
next_node = None
for child in current_node.children:
if child.step_description == segment:
next_node = child
break
if next_node:
current_node = next_node
else:
found = False
break
if found:
return {
"step_description": current_node.step_description,
"status": current_node.status,
"input_context_keys": list(current_node.input_context.keys()),
"output_results": current_node.output_results,
"agent_calls_summary": [
{"name": a["agent_name"], "status": a["status"], "output_len": len(a["output"]) if a["output"] else 0, "error": a["error"]}
for a in current_node.agent_calls
],
"full_path": current_node.full_path
}
else:
return {"error": "Task path not found."}
# 示例JSON数据
example_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_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": "搜索北京市住建委关于学区房交易政策调整的最新通知"
}
]
}
]
}
]
}
}
if __name__ == "__main__":
print("Initializing Agent Framework...")
framework = AgentFramework(example_json)
print("\nStarting task execution...")
framework.execute()
print("\n--- Final Results Summary ---")
final_results = framework.get_results()
# print(json.dumps(final_results, indent=2, ensure_ascii=False)) # 打印所有结果会非常冗长,这里只打印摘要
print("\n--- Checking specific task status ---")
# 示例:获取“教育资源分析”任务的状态
education_status = framework.get_task_status(["北京学区房综合评测", "教育资源分析"])
print("\nStatus for '教育资源分析':")
print(json.dumps(education_status, indent=2, ensure_ascii=False))
# 示例:获取“市场交易深度分析”下的“交易数据验证”任务的状态
validation_status = framework.get_task_status(["北京学区房综合评测", "市场交易深度分析", "交易数据验证"])
print("\nStatus for '交易数据验证':")
print(json.dumps(validation_status, indent=2, ensure_ascii=False))
# 示例:尝试获取一个不存在的任务
non_existent_status = framework.get_task_status(["北京学区房综合评测", "不存在的步骤"])
print("\nStatus for '不存在的步骤':")
print(json.dumps(non_existent_status, indent=2, ensure_ascii=False))