import json
import threading
import queue
class AgentNode:
"""
Represents a single agent node in the task tree.
"""
def __init__(self, step_description, execution_type, agent_name, agent_input, parent_nodes=None, child_nodes=None):
self.step_description = step_description
self.execution_type = execution_type # "sequential" or "parallel"
self.agent_name = agent_name
self.agent_input = agent_input
self.parent_nodes = parent_nodes if parent_nodes else []
self.child_nodes = child_nodes if child_nodes else []
self.result = None
self.completed = False
self.lock = threading.Lock() # For thread-safe access to attributes
def __repr__(self):
return f"AgentNode(Step: {self.step_description}, Agent: {self.agent_name}, Completed: {self.completed})"
def set_result(self, result):
with self.lock:
self.result = result
self.completed = True
def get_result(self):
with self.lock:
return self.result
class TaskTree:
"""
Represents the entire task tree and manages execution.
"""
def __init__(self, task_tree_json):
self.root = self.parse_task_tree(task_tree_json)
self.agent_results = {} # Store results for easy access
self.task_queue = queue.Queue() # Queue for tasks to be executed
def parse_task_tree(self, task_tree_json):
"""
Recursively parses the JSON task tree and creates AgentNode objects.
"""
step_description = task_tree_json["step_description"]
execution_type = task_tree_json["execution_type"]
children = task_tree_json.get("children", [])
tasks = task_tree_json.get("tasks", [])
if tasks: # Leaf nodes with agent tasks
node = AgentNode(step_description, execution_type, tasks[0]["agent_name"], tasks[0]["agent_input"])
return node
# Recursive case for non-leaf nodes
node = AgentNode(step_description, execution_type, None, None)
for child_json in children:
child_node = self.parse_task_tree(child_json)
node.child_nodes.append(child_node)
child_node.parent_nodes.append(node) # Set parent-child relationship
return node
def execute(self):
"""
Executes the task tree, handling parallel and sequential execution.
"""
self.task_queue.put(self.root)
threads = []
while not self.task_queue.empty():
node = self.task_queue.get()
if node.execution_type == "parallel":
for child in node.child_nodes:
thread = threading.Thread(target=self.run_agent, args=(child,))
threads.append(thread)
thread.start()
elif node.execution_type == "sequential":
for child in node.child_nodes:
self.run_agent(child) # Execute sequentially
# Wait for all parallel threads to complete before proceeding
for thread in threads:
thread.join()
threads = []
def run_agent(self, node):
"""
Simulates running an agent and sets the result. Replace with actual agent calls.
"""
print(f"Running agent: {node.step_description} ({node.agent_name})")
# Simulate agent execution (replace with actual agent call)
result = f"Result for {node.step_description} from {node.agent_name}" # Replace with agent output
node.set_result(result)
self.agent_results[node.agent_name] = result
print(f"Agent completed: {node.step_description}")
# Add child nodes to the queue if they exist
for child in node.child_nodes:
self.task_queue.put(child)
def get_result(self, agent_name):
"""
Retrieves the result of a specific agent.
"""
return self.agent_results.get(agent_name)
def get_all_results(self):
"""
Returns a dictionary of all agent results.
"""
return self.agent_results
# Example Usage:
task_tree_json = {
"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": "搜索北京市住建委关于学区房交易政策调整的最新通知"}
]
}
]
}
]
}
task_tree = TaskTree(task_tree_json)
task_tree.execute()
# Access results
print("\nAll Agent Results:")
for agent, result in task_tree.get_all_results().items():
print(f"{agent}: {result}")
# Example of getting a specific result
tavily_result = task_tree.get_result("tavily_agent")
print(f"\nTavily Agent Result: {tavily_result}")