beswarm 0.2.36__py3-none-any.whl → 0.2.38__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of beswarm might be problematic. Click here for more details.
- beswarm/agents/chatgroup.py +275 -0
- beswarm/agents/planact.py +339 -0
- beswarm/core.py +11 -0
- beswarm/{tools/taskmanager.py → taskmanager.py} +3 -81
- beswarm/tools/__init__.py +32 -33
- beswarm/tools/subtasks.py +77 -0
- beswarm/tools/worker.py +16 -342
- {beswarm-0.2.36.dist-info → beswarm-0.2.38.dist-info}/METADATA +1 -1
- {beswarm-0.2.36.dist-info → beswarm-0.2.38.dist-info}/RECORD +11 -7
- {beswarm-0.2.36.dist-info → beswarm-0.2.38.dist-info}/WHEEL +0 -0
- {beswarm-0.2.36.dist-info → beswarm-0.2.38.dist-info}/top_level.txt +0 -0
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import ast
|
|
2
1
|
import json
|
|
3
2
|
import uuid
|
|
4
3
|
import asyncio
|
|
5
4
|
from enum import Enum
|
|
6
5
|
from pathlib import Path
|
|
7
6
|
|
|
8
|
-
from
|
|
7
|
+
from .aient.src.aient.plugins import registry
|
|
9
8
|
|
|
10
9
|
class TaskStatus(Enum):
|
|
11
10
|
"""任务状态枚举"""
|
|
@@ -91,7 +90,7 @@ class TaskManager:
|
|
|
91
90
|
running_task_id_list = [task_id for task_id, task in self.tasks_cache.items() if task_id != "root_path" and task.get("status") == "RUNNING"]
|
|
92
91
|
for task_id in running_task_id_list:
|
|
93
92
|
tasks_params = self.tasks_cache[task_id]["args"]
|
|
94
|
-
task_id =
|
|
93
|
+
task_id = self.resume_task(task_id, registry.tools["worker"], tasks_params)
|
|
95
94
|
|
|
96
95
|
def resume_task(self, task_id, task_coro, args):
|
|
97
96
|
"""
|
|
@@ -223,85 +222,8 @@ class TaskManager:
|
|
|
223
222
|
# 如果任务ID不存在,则返回-1
|
|
224
223
|
return -1
|
|
225
224
|
|
|
226
|
-
|
|
227
|
-
task_manager = TaskManager()
|
|
228
|
-
|
|
229
|
-
worker_fun = registry.tools["worker"]
|
|
230
|
-
|
|
231
|
-
@register_tool()
|
|
232
|
-
def create_task(goal, tools, work_dir):
|
|
233
|
-
"""
|
|
234
|
-
启动一个子任务来自动完成指定的任务目标 (`goal`)。
|
|
235
|
-
|
|
236
|
-
这个子任务接收一个清晰的任务描述、一组可供调用的工具 (`tools`),以及一个工作目录 (`work_dir`)。
|
|
237
|
-
它会结合可用的工具,自主规划并逐步执行必要的操作,直到最终完成指定的任务目标。
|
|
238
|
-
核心功能是根据输入的目标,驱动整个任务执行流程。
|
|
239
|
-
子任务下上文为空,因此需要细致的背景信息。
|
|
240
|
-
|
|
241
|
-
Args:
|
|
242
|
-
goal (str): 需要完成的具体任务目标描述。子任务将围绕此目标进行工作。必须清晰、具体。必须包含背景信息,完成指标等。写清楚什么时候算任务完成,同时交代清楚任务的背景信息,这个背景信息可以是需要读取的文件等一切有助于完成任务的信息。
|
|
243
|
-
tools (list[str]): 一个包含可用工具函数对象的列表。子任务在执行任务时可能会调用这些工具来与环境交互(例如读写文件、执行命令等)。
|
|
244
|
-
work_dir (str): 工作目录的绝对路径。子任务将在此目录上下文中执行操作。子任务的工作目录位置在主任务的工作目录的子目录。子任务工作目录**禁止**设置为主任务目录本身。
|
|
245
|
-
|
|
246
|
-
Returns:
|
|
247
|
-
str: 当任务成功完成时,返回字符串 "任务已完成"。
|
|
248
|
-
"""
|
|
249
|
-
tasks_params = [
|
|
250
|
-
{"goal": goal, "tools": ast.literal_eval(tools), "work_dir": work_dir, "cache_messages": True}
|
|
251
|
-
]
|
|
252
|
-
task_ids = task_manager.create_tasks(worker_fun, tasks_params)
|
|
253
|
-
return task_ids
|
|
254
|
-
|
|
255
|
-
@register_tool()
|
|
256
|
-
def resume_task(task_id, goal):
|
|
257
|
-
"""
|
|
258
|
-
恢复一个子任务。
|
|
259
|
-
"""
|
|
260
|
-
if task_id not in task_manager.tasks_cache:
|
|
261
|
-
return f"任务 {task_id} 不存在"
|
|
262
|
-
tasks_params = task_manager.tasks_cache[task_id]["args"]
|
|
263
|
-
tasks_params["goal"] = goal
|
|
264
|
-
tasks_params["cache_messages"] = True
|
|
265
|
-
task_id = task_manager.resume_task(task_id, worker_fun, tasks_params)
|
|
266
|
-
return f"任务 {task_id} 已恢复"
|
|
267
|
-
|
|
268
|
-
@register_tool()
|
|
269
|
-
def get_all_tasks_status():
|
|
270
|
-
"""
|
|
271
|
-
获取所有任务的状态。
|
|
272
|
-
子任务状态会持久化到磁盘,因此即使历史记录为空,之前的子任务仍然存在。
|
|
273
|
-
|
|
274
|
-
Returns:
|
|
275
|
-
str: 所有任务的状态。每个任务的id,状态,结果。
|
|
276
|
-
"""
|
|
277
|
-
return task_manager.tasks_cache
|
|
278
|
-
|
|
279
|
-
@register_tool()
|
|
280
|
-
async def get_task_result():
|
|
281
|
-
"""
|
|
282
|
-
等待并获取子任务的执行结果。如果需要等待子任务完成,请使用这个工具。一旦有任务完成,会自动获取结果。如果调用时没有任务完成,会等待直到有任务完成。
|
|
283
|
-
|
|
284
|
-
Returns:
|
|
285
|
-
str: 子任务的执行结果。
|
|
286
|
-
"""
|
|
287
|
-
running_tasks_num = len([task_id for task_id, task in task_manager.tasks_cache.items() if task_id != "root_path" and task.get("status") == "RUNNING"])
|
|
288
|
-
if running_tasks_num == 0:
|
|
289
|
-
return "All tasks are finished."
|
|
290
|
-
task_id, status, result = await task_manager.get_next_result()
|
|
291
|
-
|
|
292
|
-
unfinished_tasks = [task_id for task_id, task in task_manager.tasks_cache.items() if task_id != "root_path" and task.get("status") != "DONE"]
|
|
293
|
-
text = "".join([
|
|
294
|
-
f"Task ID: {task_id}\n",
|
|
295
|
-
f"Status: {status.value}\n",
|
|
296
|
-
f"Result: {result}\n\n",
|
|
297
|
-
f"There are {len(unfinished_tasks)} unfinished tasks, unfinished task ids: {unfinished_tasks}" if unfinished_tasks else "All tasks are finished.",
|
|
298
|
-
])
|
|
299
|
-
|
|
300
|
-
return text
|
|
301
|
-
|
|
302
225
|
async def main():
|
|
303
226
|
manager = TaskManager()
|
|
304
|
-
from worker import worker
|
|
305
227
|
|
|
306
228
|
# --- 任务提交阶段 ---
|
|
307
229
|
print("--- 任务提交 ---")
|
|
@@ -313,7 +235,7 @@ async def main():
|
|
|
313
235
|
{"goal": 2},
|
|
314
236
|
{"goal": 4},
|
|
315
237
|
]
|
|
316
|
-
task_ids = manager.create_tasks(worker, tasks_to_run)
|
|
238
|
+
task_ids = manager.create_tasks(registry.tools["worker"], tasks_to_run)
|
|
317
239
|
print(f"\n主程序: {len(task_ids)} 个任务已提交,现在开始等待结果...\n")
|
|
318
240
|
|
|
319
241
|
# --- 结果处理阶段 ---
|
beswarm/tools/__init__.py
CHANGED
|
@@ -1,60 +1,59 @@
|
|
|
1
1
|
from .edit_file import edit_file
|
|
2
|
-
from .
|
|
3
|
-
from .
|
|
4
|
-
from .request_input import request_admin_input
|
|
5
|
-
|
|
2
|
+
from .search_web import search_web
|
|
3
|
+
from .completion import task_complete
|
|
6
4
|
from .search_arxiv import search_arxiv
|
|
7
5
|
from .repomap import get_code_repo_map
|
|
6
|
+
from .request_input import request_admin_input
|
|
7
|
+
from .screenshot import save_screenshot_to_file
|
|
8
|
+
from .worker import worker, worker_gen, chatgroup
|
|
8
9
|
from .click import find_and_click_element, scroll_screen
|
|
9
|
-
from .
|
|
10
|
-
from .taskmanager import create_task, resume_task, get_all_tasks_status, get_task_result
|
|
11
|
-
from .completion import task_complete
|
|
10
|
+
from .subtasks import create_task, resume_task, get_all_tasks_status, get_task_result
|
|
12
11
|
|
|
13
12
|
#显式导入 aient.plugins 中的所需内容
|
|
14
13
|
from ..aient.src.aient.plugins import (
|
|
15
|
-
excute_command,
|
|
16
14
|
get_time,
|
|
15
|
+
read_file,
|
|
16
|
+
read_image,
|
|
17
|
+
register_tool,
|
|
18
|
+
write_to_file,
|
|
19
|
+
excute_command,
|
|
17
20
|
generate_image,
|
|
18
21
|
list_directory,
|
|
19
|
-
|
|
22
|
+
get_url_content,
|
|
20
23
|
run_python_script,
|
|
24
|
+
set_readonly_path,
|
|
21
25
|
get_search_results,
|
|
22
|
-
write_to_file,
|
|
23
26
|
download_read_arxiv_pdf,
|
|
24
|
-
get_url_content,
|
|
25
|
-
read_image,
|
|
26
|
-
set_readonly_path,
|
|
27
|
-
register_tool,
|
|
28
27
|
)
|
|
29
28
|
|
|
30
29
|
__all__ = [
|
|
31
|
-
"edit_file",
|
|
32
30
|
"worker",
|
|
31
|
+
"get_time",
|
|
32
|
+
"edit_file",
|
|
33
|
+
"read_file",
|
|
34
|
+
"chatgroup",
|
|
33
35
|
"worker_gen",
|
|
36
|
+
"read_image",
|
|
37
|
+
"search_web",
|
|
38
|
+
"create_task",
|
|
39
|
+
"resume_task",
|
|
34
40
|
"search_arxiv",
|
|
35
|
-
"
|
|
36
|
-
|
|
41
|
+
"write_to_file",
|
|
42
|
+
"scroll_screen",
|
|
43
|
+
"register_tool",
|
|
44
|
+
"task_complete",
|
|
37
45
|
"excute_command",
|
|
38
|
-
"read_image",
|
|
39
|
-
"get_time",
|
|
40
46
|
"generate_image",
|
|
41
47
|
"list_directory",
|
|
42
|
-
"
|
|
43
|
-
"run_python_script",
|
|
44
|
-
"get_search_results",
|
|
45
|
-
"write_to_file",
|
|
46
|
-
"download_read_arxiv_pdf",
|
|
48
|
+
"get_task_result",
|
|
47
49
|
"get_url_content",
|
|
48
|
-
"find_and_click_element",
|
|
49
|
-
"scroll_screen",
|
|
50
|
-
"register_tool",
|
|
51
|
-
"search_web",
|
|
52
|
-
"save_screenshot_to_file",
|
|
53
50
|
"set_readonly_path",
|
|
51
|
+
"get_code_repo_map",
|
|
52
|
+
"run_python_script",
|
|
53
|
+
"get_search_results",
|
|
54
54
|
"request_admin_input",
|
|
55
|
-
"create_task",
|
|
56
|
-
"resume_task",
|
|
57
55
|
"get_all_tasks_status",
|
|
58
|
-
"
|
|
59
|
-
"
|
|
56
|
+
"find_and_click_element",
|
|
57
|
+
"download_read_arxiv_pdf",
|
|
58
|
+
"save_screenshot_to_file",
|
|
60
59
|
]
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
|
|
3
|
+
from ..core import task_manager
|
|
4
|
+
from ..aient.src.aient.plugins import register_tool, registry
|
|
5
|
+
|
|
6
|
+
worker_fun = registry.tools["worker"]
|
|
7
|
+
|
|
8
|
+
@register_tool()
|
|
9
|
+
def create_task(goal, tools, work_dir):
|
|
10
|
+
"""
|
|
11
|
+
启动一个子任务来自动完成指定的任务目标 (`goal`)。
|
|
12
|
+
|
|
13
|
+
这个子任务接收一个清晰的任务描述、一组可供调用的工具 (`tools`),以及一个工作目录 (`work_dir`)。
|
|
14
|
+
它会结合可用的工具,自主规划并逐步执行必要的操作,直到最终完成指定的任务目标。
|
|
15
|
+
核心功能是根据输入的目标,驱动整个任务执行流程。
|
|
16
|
+
子任务下上文为空,因此需要细致的背景信息。
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
goal (str): 需要完成的具体任务目标描述。子任务将围绕此目标进行工作。必须清晰、具体。必须包含背景信息,完成指标等。写清楚什么时候算任务完成,同时交代清楚任务的背景信息,这个背景信息可以是需要读取的文件等一切有助于完成任务的信息。
|
|
20
|
+
tools (list[str]): 一个包含可用工具函数对象的列表。子任务在执行任务时可能会调用这些工具来与环境交互(例如读写文件、执行命令等)。
|
|
21
|
+
work_dir (str): 工作目录的绝对路径。子任务将在此目录上下文中执行操作。子任务的工作目录位置在主任务的工作目录的子目录。子任务工作目录**禁止**设置为主任务目录本身。
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
str: 当任务成功完成时,返回字符串 "任务已完成"。
|
|
25
|
+
"""
|
|
26
|
+
tasks_params = [
|
|
27
|
+
{"goal": goal, "tools": ast.literal_eval(tools), "work_dir": work_dir, "cache_messages": True}
|
|
28
|
+
]
|
|
29
|
+
task_ids = task_manager.create_tasks(worker_fun, tasks_params)
|
|
30
|
+
return task_ids
|
|
31
|
+
|
|
32
|
+
@register_tool()
|
|
33
|
+
def resume_task(task_id, goal):
|
|
34
|
+
"""
|
|
35
|
+
恢复一个子任务。
|
|
36
|
+
"""
|
|
37
|
+
if task_id not in task_manager.tasks_cache:
|
|
38
|
+
return f"任务 {task_id} 不存在"
|
|
39
|
+
tasks_params = task_manager.tasks_cache[task_id]["args"]
|
|
40
|
+
tasks_params["goal"] = goal
|
|
41
|
+
tasks_params["cache_messages"] = True
|
|
42
|
+
task_id = task_manager.resume_task(task_id, worker_fun, tasks_params)
|
|
43
|
+
return f"任务 {task_id} 已恢复"
|
|
44
|
+
|
|
45
|
+
@register_tool()
|
|
46
|
+
def get_all_tasks_status():
|
|
47
|
+
"""
|
|
48
|
+
获取所有任务的状态。
|
|
49
|
+
子任务状态会持久化到磁盘,因此即使历史记录为空,之前的子任务仍然存在。
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
str: 所有任务的状态。每个任务的id,状态,结果。
|
|
53
|
+
"""
|
|
54
|
+
return task_manager.tasks_cache
|
|
55
|
+
|
|
56
|
+
@register_tool()
|
|
57
|
+
async def get_task_result():
|
|
58
|
+
"""
|
|
59
|
+
等待并获取子任务的执行结果。如果需要等待子任务完成,请使用这个工具。一旦有任务完成,会自动获取结果。如果调用时没有任务完成,会等待直到有任务完成。
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
str: 子任务的执行结果。
|
|
63
|
+
"""
|
|
64
|
+
running_tasks_num = len([task_id for task_id, task in task_manager.tasks_cache.items() if task_id != "root_path" and task.get("status") == "RUNNING"])
|
|
65
|
+
if running_tasks_num == 0:
|
|
66
|
+
return "All tasks are finished."
|
|
67
|
+
task_id, status, result = await task_manager.get_next_result()
|
|
68
|
+
|
|
69
|
+
unfinished_tasks = [task_id for task_id, task in task_manager.tasks_cache.items() if task_id != "root_path" and task.get("status") != "DONE"]
|
|
70
|
+
text = "".join([
|
|
71
|
+
f"Task ID: {task_id}\n",
|
|
72
|
+
f"Status: {status.value}\n",
|
|
73
|
+
f"Result: {result}\n\n",
|
|
74
|
+
f"There are {len(unfinished_tasks)} unfinished tasks, unfinished task ids: {unfinished_tasks}" if unfinished_tasks else "All tasks are finished.",
|
|
75
|
+
])
|
|
76
|
+
|
|
77
|
+
return text
|
beswarm/tools/worker.py
CHANGED
|
@@ -1,351 +1,16 @@
|
|
|
1
|
-
import os
|
|
2
|
-
import re
|
|
3
|
-
import sys
|
|
4
|
-
import copy
|
|
5
|
-
import json
|
|
6
|
-
import difflib
|
|
7
|
-
import asyncio
|
|
8
|
-
import platform
|
|
9
|
-
from pathlib import Path
|
|
10
1
|
from datetime import datetime
|
|
11
2
|
from typing import List, Dict, Union
|
|
12
3
|
|
|
13
|
-
from ..
|
|
14
|
-
from ..
|
|
15
|
-
from ..
|
|
16
|
-
from ..
|
|
17
|
-
from ..utils import extract_xml_content, get_current_screen_image_message, replace_xml_content, register_mcp_tools
|
|
18
|
-
from ..bemcp.bemcp import MCPManager
|
|
19
|
-
|
|
20
|
-
class BaseAgent:
|
|
21
|
-
"""Base class for agents, handling common initialization and disposal."""
|
|
22
|
-
def __init__(self, goal: str, tools_json: List, agent_config: Dict, work_dir: str, cache_messages: Union[bool, List[Dict]], broker: MessageBroker, listen_topic: str, publish_topic: str, status_topic: str):
|
|
23
|
-
self.goal = goal
|
|
24
|
-
self.tools_json = tools_json
|
|
25
|
-
self.work_dir = work_dir
|
|
26
|
-
self.cache_file = Path(work_dir) / ".beswarm" / "work_agent_conversation_history.json"
|
|
27
|
-
self.config = agent_config
|
|
28
|
-
self.cache_messages = cache_messages
|
|
29
|
-
if cache_messages and isinstance(cache_messages, bool) and cache_messages == True:
|
|
30
|
-
self.cache_messages = json.loads(self.cache_file.read_text(encoding="utf-8"))
|
|
31
|
-
self.broker = broker
|
|
32
|
-
self.listen_topic = listen_topic
|
|
33
|
-
self.error_topic = listen_topic + ".error"
|
|
34
|
-
self.publish_topic = publish_topic
|
|
35
|
-
self.status_topic = status_topic
|
|
36
|
-
self._subscription = self.broker.subscribe(self.handle_message, [self.listen_topic, self.error_topic])
|
|
37
|
-
|
|
38
|
-
async def handle_message(self, message: Dict):
|
|
39
|
-
"""Process incoming messages. Must be implemented by subclasses."""
|
|
40
|
-
raise NotImplementedError
|
|
41
|
-
|
|
42
|
-
def dispose(self):
|
|
43
|
-
"""Cancels the subscription and cleans up resources."""
|
|
44
|
-
if self._subscription:
|
|
45
|
-
self._subscription.dispose()
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
class InstructionAgent(BaseAgent):
|
|
49
|
-
"""Generates instructions and publishes them to a message broker."""
|
|
50
|
-
def __init__(self, goal: str, tools_json: List, agent_config: Dict, work_dir: str, cache_messages: Union[bool, List[Dict]], broker: MessageBroker, listen_topic: str, publish_topic: str, status_topic: str):
|
|
51
|
-
super().__init__(goal, tools_json, agent_config, work_dir, cache_messages, broker, listen_topic, publish_topic, status_topic)
|
|
52
|
-
|
|
53
|
-
self.last_instruction = None
|
|
54
|
-
self.agent = chatgpt(**self.config)
|
|
55
|
-
|
|
56
|
-
self.goal_diff = None
|
|
57
|
-
|
|
58
|
-
if self.cache_messages and isinstance(self.cache_messages, list) and len(self.cache_messages) > 1:
|
|
59
|
-
old_goal = extract_xml_content(self.cache_messages[1]["content"], "goal")
|
|
60
|
-
if old_goal.strip() != goal.strip():
|
|
61
|
-
diff_generator = difflib.ndiff(old_goal.splitlines(), goal.splitlines())
|
|
62
|
-
changed_lines = []
|
|
63
|
-
for line in diff_generator:
|
|
64
|
-
if (line.startswith('+ ') or line.startswith('- ')) and line[2:].strip():
|
|
65
|
-
changed_lines.append(line)
|
|
66
|
-
self.goal_diff = '\n'.join(changed_lines).strip()
|
|
67
|
-
|
|
68
|
-
def get_conversation_history(self, conversation_history: List[Dict]):
|
|
69
|
-
conversation_history = copy.deepcopy(conversation_history)
|
|
70
|
-
|
|
71
|
-
self.cache_file.write_text(json.dumps(conversation_history, ensure_ascii=False, indent=4), encoding="utf-8")
|
|
72
|
-
|
|
73
|
-
work_agent_system_prompt = conversation_history.pop(0)
|
|
74
|
-
if conversation_history:
|
|
75
|
-
original_content = work_agent_system_prompt["content"]
|
|
76
|
-
regex = r"<latest_file_content>(.*?)</latest_file_content>"
|
|
77
|
-
match = re.search(regex, original_content, re.DOTALL)
|
|
78
|
-
if match:
|
|
79
|
-
extracted_content = f"<latest_file_content>{match.group(1)}</latest_file_content>\n\n"
|
|
80
|
-
else:
|
|
81
|
-
extracted_content = ""
|
|
82
|
-
if isinstance(conversation_history[0]["content"], str):
|
|
83
|
-
conversation_history[0]["content"] = extracted_content + conversation_history[0]["content"]
|
|
84
|
-
elif isinstance(conversation_history[0]["content"], list) and extracted_content:
|
|
85
|
-
conversation_history[0]["content"].append({"type": "text", "text": extracted_content})
|
|
86
|
-
|
|
87
|
-
return conversation_history
|
|
88
|
-
|
|
89
|
-
async def handle_message(self, message: Dict):
|
|
90
|
-
"""Receives a worker response, generates the next instruction, and publishes it."""
|
|
91
|
-
|
|
92
|
-
if len(message["conversation"]) > 1 and message["conversation"][-2]["role"] == "user" \
|
|
93
|
-
and "<task_complete_message>" in message["conversation"][-2]["content"]:
|
|
94
|
-
task_complete_message = extract_xml_content(message["conversation"][-2]["content"], "task_complete_message")
|
|
95
|
-
self.broker.publish({"status": "finished", "result": task_complete_message}, self.status_topic)
|
|
96
|
-
return
|
|
97
|
-
|
|
98
|
-
instruction_prompt = "".join([
|
|
99
|
-
"</work_agent_conversation_end>\n\n",
|
|
100
|
-
f"任务目标: {self.goal}\n\n",
|
|
101
|
-
f"任务目标新变化:\n{self.goal_diff}\n\n" if self.goal_diff else "",
|
|
102
|
-
"在 tag <work_agent_conversation_start>...</work_agent_conversation_end> 之前的对话历史都是工作智能体的对话历史。\n\n",
|
|
103
|
-
"根据以上对话历史和目标,请生成下一步指令。如果任务已完成,指示工作智能体调用task_complete工具。\n\n",
|
|
104
|
-
])
|
|
105
|
-
if self.last_instruction and 'fetch_gpt_response_stream HTTP Error' not in self.last_instruction:
|
|
106
|
-
instruction_prompt = (
|
|
107
|
-
f"{instruction_prompt}\n\n"
|
|
108
|
-
"你生成的指令格式错误,必须把给assistant的指令放在<instructions>...</instructions>标签内。请重新生成格式正确的指令。"
|
|
109
|
-
f"这是你上次给assistant的错误格式的指令:\n{self.last_instruction}"
|
|
110
|
-
)
|
|
111
|
-
|
|
112
|
-
self.agent.conversation["default"][1:] = self.get_conversation_history(message["conversation"])
|
|
113
|
-
|
|
114
|
-
if "find_and_click_element" in json.dumps(self.tools_json):
|
|
115
|
-
instruction_prompt = await get_current_screen_image_message(instruction_prompt)
|
|
116
|
-
|
|
117
|
-
raw_response = await self.agent.ask_async(instruction_prompt)
|
|
118
|
-
|
|
119
|
-
if "fetch_gpt_response_stream HTTP Error', 'status_code': 404" in raw_response:
|
|
120
|
-
raise Exception(f"Model: {self.config['engine']} not found!")
|
|
121
|
-
if "'status_code': 413" in raw_response or \
|
|
122
|
-
"'status_code': 400" in raw_response:
|
|
123
|
-
self.broker.publish({"status": "error", "result": raw_response}, self.status_topic)
|
|
124
|
-
return
|
|
125
|
-
|
|
126
|
-
self.broker.publish({"status": "new_message", "result": "\n🤖 指令智能体:\n" + raw_response}, self.status_topic)
|
|
127
|
-
|
|
128
|
-
self.last_instruction = raw_response
|
|
129
|
-
instruction = extract_xml_content(raw_response, "instructions")
|
|
130
|
-
if instruction:
|
|
131
|
-
if len(message["conversation"]) == 1:
|
|
132
|
-
instruction = (
|
|
133
|
-
"任务描述:\n"
|
|
134
|
-
f"<goal>{self.goal}</goal>\n\n"
|
|
135
|
-
"你作为指令的**执行者**,而非任务的**规划师**,你必须严格遵循以下单步工作流程:\n"
|
|
136
|
-
"**执行指令**\n"
|
|
137
|
-
" - **严格遵从:** 只执行我当前下达的明确指令。在我明确给出下一步指令前,绝不擅自行动或推测、执行任何未明确要求的后续步骤。\n"
|
|
138
|
-
" - **严禁越权:** 禁止执行任何我未指定的步骤。`<goal>` 标签中的内容仅为背景信息,不得据此进行任务规划或推测。\n"
|
|
139
|
-
"**汇报结果**\n"
|
|
140
|
-
" - **聚焦单步:** 指令完成后,仅汇报该步骤的执行结果与产出。\n"
|
|
141
|
-
"**暂停等待**\n"
|
|
142
|
-
" - **原地待命:** 汇报后,任务暂停。在收到我新的指令前,严禁发起任何新的工具调用或操作。\n"
|
|
143
|
-
" - **请求指令:** 回复的最后必须明确请求我提供下一步指令。\n"
|
|
144
|
-
"**注意:** 禁止完成超出下面我未规定的步骤,`<goal>` 标签中的内容仅为背景信息。"
|
|
145
|
-
"现在开始执行第一步:\n"
|
|
146
|
-
f"{instruction}"
|
|
147
|
-
)
|
|
148
|
-
self.broker.publish({"instruction": instruction, "conversation": message["conversation"]}, self.publish_topic)
|
|
149
|
-
else:
|
|
150
|
-
print("\n❌ 指令智能体生成的指令不符合要求,正在重新生成。")
|
|
151
|
-
self.broker.publish(message, self.error_topic)
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
class WorkerAgent(BaseAgent):
|
|
155
|
-
"""Executes instructions and publishes results to a message broker."""
|
|
156
|
-
def __init__(self, goal: str, tools_json: List, agent_config: Dict, work_dir: str, cache_messages: Union[bool, List[Dict]], broker: MessageBroker, listen_topic: str, publish_topic: str, status_topic: str):
|
|
157
|
-
super().__init__(goal, tools_json, agent_config, work_dir, cache_messages, broker, listen_topic, publish_topic, status_topic)
|
|
158
|
-
|
|
159
|
-
if self.cache_messages and isinstance(self.cache_messages, list) and len(self.cache_messages) > 1:
|
|
160
|
-
first_user_message = replace_xml_content(self.cache_messages[1]["content"], "goal", goal)
|
|
161
|
-
self.config["cache_messages"] = self.cache_messages[0:1] + [{"role": "user", "content": first_user_message}] + self.cache_messages[2:]
|
|
162
|
-
|
|
163
|
-
self.agent = chatgpt(**self.config)
|
|
164
|
-
|
|
165
|
-
async def handle_message(self, message: Dict):
|
|
166
|
-
"""Receives an instruction, executes it, and publishes the response."""
|
|
167
|
-
|
|
168
|
-
if message.get("instruction") == "Initial kickoff":
|
|
169
|
-
self.broker.publish({
|
|
170
|
-
"conversation": self.agent.conversation["default"]
|
|
171
|
-
}, self.publish_topic)
|
|
172
|
-
return
|
|
173
|
-
|
|
174
|
-
instruction = message["instruction"]
|
|
175
|
-
if "find_and_click_element" in json.dumps(self.tools_json):
|
|
176
|
-
instruction = await get_current_screen_image_message(instruction)
|
|
177
|
-
response = await self.agent.ask_async(instruction)
|
|
178
|
-
|
|
179
|
-
if response.strip() == '':
|
|
180
|
-
print("\n❌ 工作智能体回复为空,请重新生成指令。")
|
|
181
|
-
self.broker.publish(message, self.error_topic)
|
|
182
|
-
else:
|
|
183
|
-
self.broker.publish({"status": "new_message", "result": "\n✅ 工作智能体:\n" + response}, self.status_topic)
|
|
184
|
-
self.broker.publish({
|
|
185
|
-
"conversation": self.agent.conversation["default"]
|
|
186
|
-
}, self.publish_topic)
|
|
187
|
-
|
|
188
|
-
class Tee:
|
|
189
|
-
def __init__(self, *files):
|
|
190
|
-
self.files = files
|
|
191
|
-
|
|
192
|
-
def write(self, obj):
|
|
193
|
-
for f in self.files:
|
|
194
|
-
f.write(obj)
|
|
195
|
-
f.flush()
|
|
196
|
-
|
|
197
|
-
def flush(self):
|
|
198
|
-
for f in self.files:
|
|
199
|
-
f.flush()
|
|
200
|
-
|
|
201
|
-
broker = MessageBroker()
|
|
202
|
-
mcp_manager = MCPManager()
|
|
203
|
-
|
|
204
|
-
class BrokerWorker:
|
|
205
|
-
"""The 'glue' class that orchestrates agents via a MessageBroker."""
|
|
206
|
-
def __init__(self, goal: str, tools: List[Union[str, Dict]], work_dir: str, cache_messages: Union[bool, List[Dict]] = None, broker: MessageBroker = None, mcp_manager: MCPManager = None):
|
|
207
|
-
self.goal = goal
|
|
208
|
-
self.tools = tools
|
|
209
|
-
self.work_dir = Path(work_dir)
|
|
210
|
-
self.cache_messages = cache_messages
|
|
211
|
-
|
|
212
|
-
self.broker = broker
|
|
213
|
-
self.mcp_manager = mcp_manager
|
|
214
|
-
self.task_completion_event = asyncio.Event()
|
|
215
|
-
self.final_result = None
|
|
216
|
-
self._status_subscription = None
|
|
217
|
-
self.setup()
|
|
218
|
-
|
|
219
|
-
self.channel = self.broker.request_channel()
|
|
220
|
-
self.INSTRUCTION_TOPIC = self.channel + ".instructions"
|
|
221
|
-
self.WORKER_RESPONSE_TOPIC = self.channel + ".worker_responses"
|
|
222
|
-
self.TASK_STATUS_TOPIC =self.channel + ".task_status"
|
|
223
|
-
|
|
224
|
-
def setup(self):
|
|
225
|
-
cache_dir = self.work_dir / ".beswarm"
|
|
226
|
-
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
227
|
-
task_manager.set_root_path(self.work_dir)
|
|
228
|
-
self.cache_file = cache_dir / "work_agent_conversation_history.json"
|
|
229
|
-
if not self.cache_file.exists():
|
|
230
|
-
self.cache_file.write_text("[]", encoding="utf-8")
|
|
231
|
-
|
|
232
|
-
DEBUG = os.getenv("DEBUG", "false").lower() in ("true", "1", "t", "yes")
|
|
233
|
-
if DEBUG:
|
|
234
|
-
log_file = open(cache_dir / "history.log", "a", encoding="utf-8")
|
|
235
|
-
log_file.write(f"========== {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ==========\n")
|
|
236
|
-
original_stdout = sys.stdout
|
|
237
|
-
original_stderr = sys.stderr
|
|
238
|
-
sys.stdout = Tee(original_stdout, log_file)
|
|
239
|
-
sys.stderr = Tee(original_stderr, log_file)
|
|
240
|
-
|
|
241
|
-
async def _configure_tools(self):
|
|
242
|
-
mcp_list = [item for item in self.tools if isinstance(item, dict)]
|
|
243
|
-
if mcp_list:
|
|
244
|
-
for mcp_item in mcp_list:
|
|
245
|
-
mcp_name, mcp_config = list(mcp_item.items())[0]
|
|
246
|
-
await self.mcp_manager.add_server(mcp_name, mcp_config)
|
|
247
|
-
client = self.mcp_manager.clients.get(mcp_name)
|
|
248
|
-
await register_mcp_tools(client, registry)
|
|
249
|
-
all_mcp_tools = await self.mcp_manager.get_all_tools()
|
|
250
|
-
self.tools.extend([tool.name for tool in sum(all_mcp_tools.values(), [])])
|
|
251
|
-
self.tools = [item for item in self.tools if not isinstance(item, dict)]
|
|
252
|
-
if "task_complete" not in self.tools: self.tools.append("task_complete")
|
|
253
|
-
self.tools_json = [value for _, value in get_function_call_list(self.tools).items()]
|
|
254
|
-
|
|
255
|
-
def _task_status_subscriber(self, message: Dict):
|
|
256
|
-
"""Subscriber for task status changes."""
|
|
257
|
-
if message.get("status") == "finished":
|
|
258
|
-
self.final_result = message.get("result")
|
|
259
|
-
self.task_completion_event.set()
|
|
260
|
-
|
|
261
|
-
if message.get("status") == "error":
|
|
262
|
-
raise Exception(message.get("result"))
|
|
263
|
-
|
|
264
|
-
if message.get("status") == "new_message":
|
|
265
|
-
print(message.get("result"))
|
|
266
|
-
|
|
267
|
-
def _setup_agents(self):
|
|
268
|
-
instruction_agent_config = {
|
|
269
|
-
"api_key": os.getenv("API_KEY"), "api_url": os.getenv("BASE_URL"),
|
|
270
|
-
"engine": os.getenv("MODEL"),
|
|
271
|
-
"system_prompt": instruction_system_prompt.format(
|
|
272
|
-
os_version=platform.platform(), tools_list=self.tools_json,
|
|
273
|
-
workspace_path=self.work_dir, current_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
274
|
-
),
|
|
275
|
-
"print_log": os.getenv("DEBUG", "false").lower() in ("true", "1", "t", "yes"),
|
|
276
|
-
"temperature": 0.7, "use_plugins": False
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
worker_agent_config = {
|
|
280
|
-
"api_key": os.getenv("API_KEY"), "api_url": os.getenv("BASE_URL"),
|
|
281
|
-
"engine": os.getenv("FAST_MODEL") or os.getenv("MODEL"),
|
|
282
|
-
"system_prompt": worker_system_prompt.format(
|
|
283
|
-
os_version=platform.platform(), workspace_path=self.work_dir,
|
|
284
|
-
shell=os.getenv('SHELL', 'Unknown'), current_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
|
285
|
-
tools_list=self.tools_json
|
|
286
|
-
),
|
|
287
|
-
"print_log": True, "temperature": 0.5, "function_call_max_loop": 100
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
instruction_agent = InstructionAgent(
|
|
291
|
-
goal=self.goal, tools_json=self.tools_json, agent_config=instruction_agent_config, work_dir=self.work_dir, cache_messages=self.cache_messages,
|
|
292
|
-
broker=self.broker, listen_topic=self.WORKER_RESPONSE_TOPIC,
|
|
293
|
-
publish_topic=self.INSTRUCTION_TOPIC, status_topic=self.TASK_STATUS_TOPIC
|
|
294
|
-
)
|
|
295
|
-
|
|
296
|
-
worker_agent = WorkerAgent(
|
|
297
|
-
goal=self.goal, tools_json=self.tools_json, agent_config=worker_agent_config, work_dir=self.work_dir, cache_messages=self.cache_messages,
|
|
298
|
-
broker=self.broker, listen_topic=self.INSTRUCTION_TOPIC,
|
|
299
|
-
publish_topic=self.WORKER_RESPONSE_TOPIC, status_topic=self.TASK_STATUS_TOPIC
|
|
300
|
-
)
|
|
301
|
-
return instruction_agent, worker_agent
|
|
302
|
-
|
|
303
|
-
async def run(self):
|
|
304
|
-
"""Sets up subscriptions and starts the workflow."""
|
|
305
|
-
os.chdir(self.work_dir.absolute())
|
|
306
|
-
await self._configure_tools()
|
|
307
|
-
|
|
308
|
-
instruction_agent, worker_agent = self._setup_agents()
|
|
309
|
-
|
|
310
|
-
self.broker.publish({"instruction": "Initial kickoff"}, self.INSTRUCTION_TOPIC)
|
|
311
|
-
|
|
312
|
-
self._status_subscription = self.broker.subscribe(self._task_status_subscriber, self.TASK_STATUS_TOPIC)
|
|
313
|
-
await self.task_completion_event.wait()
|
|
314
|
-
|
|
315
|
-
instruction_agent.dispose()
|
|
316
|
-
worker_agent.dispose()
|
|
317
|
-
self._status_subscription.dispose()
|
|
318
|
-
await self.mcp_manager.cleanup()
|
|
319
|
-
return self.final_result
|
|
320
|
-
|
|
321
|
-
async def stream_run(self):
|
|
322
|
-
"""Runs the workflow and yields status messages."""
|
|
323
|
-
os.chdir(self.work_dir.absolute())
|
|
324
|
-
await self._configure_tools()
|
|
325
|
-
|
|
326
|
-
instruction_agent, worker_agent = self._setup_agents()
|
|
327
|
-
|
|
328
|
-
self.broker.publish({"instruction": "Initial kickoff"}, self.INSTRUCTION_TOPIC)
|
|
329
|
-
|
|
330
|
-
try:
|
|
331
|
-
async for message in self.broker.iter_topic(self.TASK_STATUS_TOPIC):
|
|
332
|
-
if message.get("status") == "new_message":
|
|
333
|
-
yield message.get("result")
|
|
334
|
-
elif message.get("status") == "finished":
|
|
335
|
-
yield message.get("result")
|
|
336
|
-
break
|
|
337
|
-
elif message.get("status") == "error":
|
|
338
|
-
raise Exception(message.get("result"))
|
|
339
|
-
finally:
|
|
340
|
-
instruction_agent.dispose()
|
|
341
|
-
worker_agent.dispose()
|
|
342
|
-
await self.mcp_manager.cleanup()
|
|
4
|
+
from ..core import mcp_manager, broker, task_manager
|
|
5
|
+
from ..agents.planact import BrokerWorker
|
|
6
|
+
from ..agents.chatgroup import ChatGroupWorker
|
|
7
|
+
from ..aient.src.aient.plugins import register_tool
|
|
343
8
|
|
|
344
9
|
|
|
345
10
|
@register_tool()
|
|
346
11
|
async def worker(goal: str, tools: List[Union[str, Dict]], work_dir: str, cache_messages: Union[bool, List[Dict]] = None):
|
|
347
12
|
start_time = datetime.now()
|
|
348
|
-
worker_instance = BrokerWorker(goal, tools, work_dir, cache_messages, broker, mcp_manager)
|
|
13
|
+
worker_instance = BrokerWorker(goal, tools, work_dir, cache_messages, broker, mcp_manager, task_manager)
|
|
349
14
|
result = await worker_instance.run()
|
|
350
15
|
end_time = datetime.now()
|
|
351
16
|
print(f"\n任务开始时间: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
@@ -356,7 +21,7 @@ async def worker(goal: str, tools: List[Union[str, Dict]], work_dir: str, cache_
|
|
|
356
21
|
@register_tool()
|
|
357
22
|
async def worker_gen(goal: str, tools: List[Union[str, Dict]], work_dir: str, cache_messages: Union[bool, List[Dict]] = None):
|
|
358
23
|
start_time = datetime.now()
|
|
359
|
-
worker_instance = BrokerWorker(goal, tools, work_dir, cache_messages, broker, mcp_manager)
|
|
24
|
+
worker_instance = BrokerWorker(goal, tools, work_dir, cache_messages, broker, mcp_manager, task_manager)
|
|
360
25
|
async for result in worker_instance.stream_run():
|
|
361
26
|
yield result
|
|
362
27
|
end_time = datetime.now()
|
|
@@ -364,4 +29,13 @@ async def worker_gen(goal: str, tools: List[Union[str, Dict]], work_dir: str, ca
|
|
|
364
29
|
print(f"任务结束时间: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
365
30
|
print(f"总用时: {end_time - start_time}")
|
|
366
31
|
|
|
367
|
-
|
|
32
|
+
@register_tool()
|
|
33
|
+
async def chatgroup(tools: List[Union[str, Dict]], work_dir: str, cache_messages: Union[bool, List[Dict]] = None):
|
|
34
|
+
start_time = datetime.now()
|
|
35
|
+
worker_instance = ChatGroupWorker(tools, work_dir, cache_messages, broker, mcp_manager, task_manager)
|
|
36
|
+
result = await worker_instance.run()
|
|
37
|
+
end_time = datetime.now()
|
|
38
|
+
print(f"\n任务开始时间: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
39
|
+
print(f"任务结束时间: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
40
|
+
print(f"总用时: {end_time - start_time}")
|
|
41
|
+
return result
|