agent_hub.py
34.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
import logging
import time
from datetime import datetime, timezone
from functools import partial
from pathlib import Path
from typing import Dict, List, Optional, Any
from app.config.loader import ConfigLoader
from app.config.settings import AgentConfig
from app.service.active_session_service import ActiveSessionService
from agentscope.tool import Toolkit
from app.hooks.post_reply import PostReplyHook
from app.service.memory import SessionMemory
from agentscope.model import OpenAIChatModel
from agentscope.formatter import OpenAIChatFormatter as _OpenAIChatFormatter
class OpenAIChatFormatter(_OpenAIChatFormatter):
"""扩展 AgentScope 的 OpenAI formatter,静默丢弃 thinking block。
ReActAgent 在 reasoning 阶段产出的 thinking block 会存入 InMemoryMemory,
后续 API 调用格式化历史消息时会遇到该类型。原生 formatter 不认识 thinking
类型会打 warning。
thinking 文本是 LLM 的内部推理(如"我需要调用XX Agent"),只能通过
post_reasoning hook 摘要后发 IM 给用户看,绝不能回灌给 LLM 作为上下文,
否则 LLM 会误以为是未完成的任务指令而重复执行。
"""
async def _format(self, msgs: list) -> list:
for msg in msgs:
blocks = msg.content if isinstance(msg.content, list) else []
if not blocks:
continue
msg.content = [
b for b in blocks
if not (isinstance(b, dict) and b.get("type") == "thinking")
]
return await super()._format(msgs)
from agentscope.message import Msg
from agentscope.message._message_block import TextBlock
from agentscope.tool._response import ToolResponse
from agentscope.tool import execute_python_code, execute_shell_command
from agentscope.agent import ReActAgent
from agentscope.memory import InMemoryMemory
logger = logging.getLogger(__name__)
# sub_agent 专用低 temperature:调用子 Agent 处理确定性任务时使用更稳定的输出
SUB_AGENT_TEMPERATURE = 0.2
async def _im_post_reasoning_hook(
self, kwargs, output,
*, im_service, room_id, user_id, bot_id_mapping, summarize_thinking=None,
):
"""AgentScope native hook: 推理完成后摘要化 thinking 并通过 IM 发送。"""
logger.info(f"[Hook 触发] agent={self.name} 时机=post_reasoning")
# 若刚收到 call_sub_agent 结果,跳过 thinking 摘要
# 下一轮就是最终回复,由 PostReplyHook 发出,避免重复消息
memory_msgs = await self.memory.get_memory()
# 检查倒数第2条:post_reasoning 触发时 memory[-1] 已是本轮 reasoning 输出,
# call_sub_agent 的 tool_result 在上轮 _acting() 写入,位于 memory[-2]
if len(memory_msgs) >= 2:
prev = memory_msgs[-2]
if hasattr(prev, "content"):
for block in prev.content or []:
if (
isinstance(block, dict)
and block.get("type") == "tool_result"
and block.get("name") == "call_sub_agent"
):
logger.info(
"[Hook 跳过] agent=%s call_sub_agent 获得sub Agent结果,跳过本次 thinking 摘要和 IM 发送",
self.name,
)
return None
bot_id = bot_id_mapping.get(self.name)
if not bot_id:
return None
# 只提取 ThinkingBlock,跳过 tool_use 等其他 block
content_parts = []
if output and hasattr(output, "content"):
blocks = output.content if isinstance(output.content, list) else []
for block in blocks:
if isinstance(block, dict) and block.get("type") == "thinking":
content_parts.append(block.get("thinking", ""))
content = "\n".join(content_parts) if content_parts else None
if not content:
return None
# 删除"下载"这个词
content = content.replace("下载", "点击")
# 摘要化 thinking:调用模型总结为状态更新,不暴露内部推理
if summarize_thinking:
content = await summarize_thinking(content)
logger.info(f"[Hook 发送 IM] agent={self.name} bot_id={bot_id} content={content[:50]}...")
try:
await im_service.send_message(
bot_id=bot_id, content=content,
contact_id=room_id, at_list="",
)
except Exception:
logger.warning(
"[Hook IM 发送失败] agent=%s room=%s(不影响推理流程)",
self.name, room_id, exc_info=True,
)
class AgentHubError(Exception):
"""Raised when AgentHub processing fails."""
pass
class AgentHub:
"""
中央调度器 - 唯一运行的 Agent 运行时
持有所有 Agent 的配置,负责:
1. 提示词组装
2. 模型调用
3. 消息路由和分发
4. 通过 Hook 发送消息
"""
def __init__(
self,
config_loader: ConfigLoader,
session_service: ActiveSessionService,
im_service,
preloaded_agents: Optional[Dict[str, Any]] = None,
db_factory=None,
):
self.config_loader = config_loader
self.session_service = session_service
self.im_service = im_service
self._db_factory = db_factory
if preloaded_agents is None:
raise AgentHubError("preloaded_agents is required — load from DB via ConfigLoader.load_agents_from_db()")
self.agents: Dict[str, Any] = preloaded_agents
# 发言人(口)Agent:框架级固定构件,不依赖数据库
self._inject_mouth_agent()
self.main_model_config = config_loader.load_models()["main"]
self.post_reply_hook = PostReplyHook(im_service=im_service)
self.toolkit = Toolkit()
self.model = OpenAIChatModel(
model_name=self.main_model_config.model_name,
api_key=self.main_model_config.api_key,
stream=False,
client_kwargs={"base_url": self.main_model_config.api_base}
)
self.formatter = OpenAIChatFormatter()
# 加载回复风格指南(soul/agent.md)
soul_path = Path(__file__).parent.parent.parent / "soul" / "agent.md"
if soul_path.exists():
self.soul_guide = soul_path.read_text(encoding="utf-8")
else:
self.soul_guide = ""
logger.warning(f"soul/agent.md 未找到: {soul_path}")
# 加载 thinking 摘要提示词(soul/thinking-summarize.md)
summarize_prompt_path = Path(__file__).parent.parent.parent / "soul" / "thinking-summarize.md"
if summarize_prompt_path.exists():
self.summarize_prompt = summarize_prompt_path.read_text(encoding="utf-8").strip()
else:
self.summarize_prompt = "你是一个状态更新机器人。将以下AI思考过程总结为一句简短的状态更新(≤20字),用自然口语描述AI当前正在做什么。只输出状态更新本身,不要引号、不要解释、不要前缀。严格禁止输出技术术语(agent、skill、tool、API等)、变量名、内部系统名称。必须用用户能理解的日常表达。"
logger.warning(f"soul/thinking-summarize.md 未找到: {summarize_prompt_path}")
# sub_agent 专用 model:低 temperature,更确定性
self.sub_model = OpenAIChatModel(
model_name=self.main_model_config.model_name,
api_key=self.main_model_config.api_key,
stream=False,
generate_kwargs={"temperature": SUB_AGENT_TEMPERATURE},
client_kwargs={"base_url": self.main_model_config.api_base}
)
# thinking 摘要专用 model:便宜、快,和 message_gate 同配置
thinking_summary_config = config_loader.load_models().get("thinking_summary")
if thinking_summary_config:
self.thinking_summary_model = OpenAIChatModel(
model_name=thinking_summary_config.model_name,
api_key=thinking_summary_config.api_key,
stream=False,
client_kwargs={"base_url": thinking_summary_config.api_base}
)
else:
self.thinking_summary_model = self.sub_model
logger.warning("thinking_summary 模型配置未找到,降级使用 sub_model")
# Register all skills from skills/ directory to Toolkit
skills_dir = Path(__file__).parent.parent.parent / "skills"
logger.info(f"扫描 skills 目录并注册到全局 Toolkit: {skills_dir}")
for skill_entry in sorted(skills_dir.iterdir()):
if skill_entry.is_dir() and not skill_entry.name.startswith('.'):
skill_md = skill_entry / "SKILL.md"
if skill_md.exists():
try:
self.toolkit.register_agent_skill(str(skill_entry))
except Exception as e:
logger.warning(
f"跳过 skill {skill_entry.name}: {e}"
)
# Load skills metadata from Toolkit
self.skills = config_loader.load_skills_from_toolkit(self.toolkit)
# Register built-in coding tools (shared by all agents)
self.toolkit.register_tool_function(
execute_python_code,
group_name="basic",
)
self.toolkit.register_tool_function(
execute_shell_command,
group_name="basic",
)
# Register call_sub_agent as a tool for serial chain collaboration
call_sub = self._make_call_sub_agent_tool()
# 动态获取一个非 steward 的 agent key 作为示例
sub_example = next(
(k for k, a in self.agents.items() if not a.is_steward), "sub_agent"
)
self.toolkit.register_tool_function(
call_sub,
func_name="call_sub_agent",
group_name="basic",
json_schema={
"type": "function",
"function": {
"name": "call_sub_agent",
"description": "调用子Agent处理特定任务。当用户问题属于某个子Agent的职责范围时,必须调用此工具委托处理。",
"parameters": {
"type": "object",
"properties": {
"agent_code": {
"type": "string",
"description": f"子Agent调用码,必须从可用子Agent列表中选择,如 \"{sub_example}\"",
},
"instruction": {
"type": "string",
"description": "给子Agent的具体指令,必须包含用户需求的完整描述",
},
},
"required": ["agent_code", "instruction"],
},
},
},
)
# Register sandboxed read_file tool for reading project files
read_file = self._make_read_file_tool()
self.toolkit.register_tool_function(
read_file,
func_name="read_file",
group_name="basic",
)
# 构建每个 agent 的专属 toolkit(按 skills 字段过滤)
self.agent_toolkits: Dict[str, Toolkit] = {}
self._build_all_agent_toolkits()
self._agents_loaded_at = datetime.now(timezone.utc).replace(tzinfo=None)
def _register_im_hooks(
self,
agent,
room_id: str,
user_id: str,
bot_id_mapping: Optional[Dict[str, str]],
):
"""为 Agent 实例注册 IM 发送 hook。"""
logger.info(f"[Hook 注册] agent={agent.name} 时机=post_reasoning")
route_ctx = dict(
im_service=self.im_service,
room_id=room_id,
user_id=user_id,
bot_id_mapping=bot_id_mapping or {},
summarize_thinking=self._summarize_thinking,
)
agent.register_instance_hook(
"post_reasoning", "im_post_reasoning",
partial(_im_post_reasoning_hook, **route_ctx),
)
def _find_steward_agent(self) -> Any:
"""查找主 Agent(is_steward=True)。"""
for agent in self.agents.values():
if agent.is_steward:
return agent
raise AgentHubError("未找到主 Agent(is_steward=True)")
def _find_steward_key(self) -> str:
"""查找主 Agent 的 dict key。"""
for key, agent in self.agents.items():
if agent.is_steward:
return key
raise AgentHubError("未找到主 Agent(is_steward=True)")
def _inject_mouth_agent(self):
"""注入发言人 Agent(框架级固定构件,不依赖数据库)。"""
self.agents["-1"] = AgentConfig(
name="发言人",
code="-1",
prompt=(
"你是发言人,代表主Agent与用户对话。\n\n"
"重要前提:各子Agent已经用自己的身份把处理结果直接发给了用户,"
"用户已经看到了。你不要重复子Agent已经发过的内容。\n\n"
"你的工作:\n"
"1. 子Agent已发的内容 → 一句话自然带过"
"(如'纪要助手刚发了文档,你看一下'),不要重新总结\n"
"2. 主Agent的补充分析、建议、追问 → 这是重点,展开说\n"
"3. 如果主Agent没有额外内容要补充 → 简单收尾即可,"
"如'有需要再找我'\n\n"
"禁止:重复总结子Agent已发内容、逐条列举各子Agent结果、"
"重新执行子Agent的任务"
),
description="代表主Agent与用户对话,补充子Agent未覆盖的内容",
is_steward=False,
)
def _build_all_agent_toolkits(self):
"""根据当前 self.agents 重建所有 agent 的专属 toolkit。"""
self.agent_toolkits.clear()
for agent_code, agent_config in self.agents.items():
logger.info(
"构建 agent '%s' 的专属 Toolkit (skills: %s)",
agent_code, agent_config.skills,
)
agent_tk = Toolkit()
for name, tool in self.toolkit.tools.items():
if tool.group == "basic":
if agent_code == "-1" and name == "call_sub_agent":
continue
agent_tk.register_tool_function(
tool.original_func,
group_name=tool.group,
func_name=tool.name,
preset_kwargs=tool.preset_kwargs,
json_schema=tool.json_schema,
)
for skill_name in agent_config.skills:
if skill_name in self.toolkit.skills:
skill_info = self.toolkit.skills[skill_name]
skill_dir = skill_info.get("dir", "")
if skill_dir:
agent_tk.register_agent_skill(skill_dir)
self.agent_toolkits[agent_code] = agent_tk
async def _maybe_reload_agents(self):
"""检查 ai_agents.updated_at,有变更则热加载 agent 配置。
最多每 30 秒检查一次,避免每条消息都查 DB。
"""
if not self._db_factory:
return
now = datetime.now(timezone.utc).replace(tzinfo=None)
last_check = getattr(self, "_agents_last_check_at", None)
if last_check and (now - last_check).total_seconds() < 30:
return
self._agents_last_check_at = now
try:
with self._db_factory() as db:
from app.model.agent import Agent
from sqlalchemy import func
max_updated = (
db.query(func.max(Agent.updated_at))
.filter(Agent.is_deleted == False)
.scalar()
)
if (
max_updated
and self._agents_loaded_at
and max_updated > self._agents_loaded_at
):
logger.info(
"检测到 ai_agents 变更 (max_updated=%s > loaded_at=%s),重新加载",
max_updated, self._agents_loaded_at,
)
self._reload_agents()
except Exception:
logger.warning("检查 agent 更新失败,跳过本次热加载", exc_info=True)
def _reload_agents(self):
"""从 DB 重新加载 agent 配置,重建 agents 和 toolkits。"""
with self._db_factory() as db:
new_agents = self.config_loader.load_agents_from_db(db)
self.agents = new_agents
self._inject_mouth_agent()
self._build_all_agent_toolkits()
self._agents_loaded_at = datetime.now(timezone.utc).replace(tzinfo=None)
logger.info("Agent 配置已热加载: %d 个", len(self.agents))
def _build_main_prompt(
self,
allowed_agent_codes: Optional[list] = None,
) -> str:
"""
Build the main agent's prompt including sub-agent duty descriptions.
When allowed_agent_codes is set, only agents in that list are advertised.
"""
steward = self._find_steward_agent()
prompt = steward.prompt # 角色定义
if steward.description:
prompt += "\n\n" + steward.description # 调度规则
# Collect duties from sub-agents, filtered by position if applicable
sub_lines = []
for code, agent in self.agents.items():
if agent.is_steward:
continue
if allowed_agent_codes is not None and code not in allowed_agent_codes:
continue
duty = agent.description or f"{agent.name}相关任务"
sub_lines.append(f"- {agent.name}(调用码: {code}): {duty}")
if sub_lines:
prompt += "\n\n## 可调用的子Agent\n" + "\n".join(sub_lines)
return prompt + self.soul_guide
def _build_sub_agent_prompt(self, agent_code: str) -> str:
"""Build prompt for a sub-agent when handling a routed query."""
agent = self.agents.get(agent_code)
if not agent:
raise AgentHubError(f"Agent {agent_code} 配置未找到")
return agent.prompt + self.soul_guide
async def process_message(
self,
session_id: str,
room_id: str,
user_id: str,
user_query: str,
mentioned_agent_code: Optional[str] = None,
channel: str = "wechat_group",
file_url: Optional[str] = None,
allowed_agent_codes: Optional[list] = None,
bot_id_mapping: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""
Process a user message end-to-end.
Flow:
1. Get or create session
2. Load conversation history
3. If @mentioned a specific agent → route directly
4. Otherwise → main agent judges intent
5. If intent is "route" → sub-agent handles
6. Send reply via post_reply hook
"""
start_time = time.time()
await self._maybe_reload_agents()
logger.info(
"[process_message 开始] session=%s user_query=%s file_url=%s",
session_id, user_query[:100], file_url,
)
# 暂存路由上下文,供 _call_sub_agent 创建子 Agent 时注册 hook
self._current_route_ctx = dict(
room_id=room_id, user_id=user_id, bot_id_mapping=bot_id_mapping or {},
call_count=0,
)
session = self.session_service.get_or_create_session(
session_id=session_id,
room_id=room_id,
channel=channel
)
memory = SessionMemory(
session_id=session_id,
store=self.session_service.store,
max_rounds=20,
)
self._current_route_ctx["session_memory"] = memory
messages = memory.get_messages(max_rounds=10)
# 始终路由到 steward agent
target_agent = self._find_steward_key()
routing_reason = "default"
logger.debug(
"路由决策: target=%s reason=%s position_restricted=%s allowed=%s",
target_agent, routing_reason,
allowed_agent_codes is not None, allowed_agent_codes,
)
# Build prompt based on target agent
if self.agents[target_agent].is_steward:
system_prompt = self._build_main_prompt(allowed_agent_codes=allowed_agent_codes)
else:
system_prompt = self._build_sub_agent_prompt(target_agent)
# Bridge: convert SessionStore dict history → AgentScope Msg[]
agent_memory = InMemoryMemory()
recent = messages[-10:]
history_msgs = [Msg.from_dict(m) for m in recent]
if history_msgs:
await agent_memory.add(history_msgs)
history_msg_count = len(history_msgs) # 用于后续只保存本次 ReAct 新增的工具消息
# Create per-request ReActAgent with per-agent toolkit
agent = ReActAgent(
name=target_agent,
sys_prompt=system_prompt,
model=self.model,
formatter=self.formatter,
toolkit=self.agent_toolkits.get(target_agent, self.toolkit),
memory=agent_memory,
max_iters=10,
)
# Register IM hooks for this agent instance
self._register_im_hooks(agent, room_id, user_id, bot_id_mapping)
# Run ReAct loop via framework
# If there's an image URL, append it to the query so the agent can see it
effective_query = user_query
if file_url:
effective_query = f"{user_query}\n\n[附件: {file_url}]"
user_msg = Msg("user", effective_query, "user")
# Run ReAct loop — exception path: no DB persist, no IM notify
try:
memory.add("user", user_query, name=target_agent)
response_msg = await agent.reply(user_msg)
except Exception:
logger.exception(
"[AgentHub] session=%s ReAct 执行异常,已跳过 DB 持久化和 IM 发送",
session_id,
)
raise
# Normal path: ReAct succeeded
response_raw = response_msg.content # 保留原生格式(str 或 list[dict]),用于存 history
response_text = response_msg.get_text_content() or "" # 纯文本,用于返回值和日志
target_agent_name = target_agent
# 1. 保存工具交互(只保存本次 ReAct 新增的,避免历史工具消息重复追加)
try:
msg_list = await agent.memory.get_memory()
new_msgs = msg_list[history_msg_count:]
self._save_tool_interactions(memory, new_msgs)
except Exception:
logger.warning(
"[AgentHub] session=%s 保存工具消息异常(不影响主流程)",
session_id, exc_info=True,
)
# 2. 始终保存 assistant 回复(不干扰 ReAct 循环——循环此时已结束)
memory.add("assistant", response_raw, name=target_agent_name)
call_count = self._current_route_ctx.get("call_count", 0)
# 3. call_count >= 1 时剔除最后一条 assistant(主Agent 的"已委派"废话)
if call_count >= 1:
memory.remove_last()
logger.info(
"[主Agent 静默] call_count=%d,已剔除主Agent 最终回复,子Agent(含发言人)已发送回复",
call_count,
)
# 4. 持久化(仅一次)
self.session_service.save_to_db(session_id)
# 5. call_count == 0 时正常发 IM;>= 1 时不发
if call_count == 0:
try:
await self.post_reply_hook.execute({
"agent_name": target_agent_name,
"response_content": response_text,
"room_id": room_id,
"mentioned_list": [user_id],
"bot_id_mapping": bot_id_mapping or {},
})
except Exception:
logger.warning(
"[最终回复 IM 发送失败] agent=%s session=%s room=%s",
target_agent_name, session_id, room_id, exc_info=True,
)
processing_time_ms = (time.time() - start_time) * 1000
logger.info(
"[process_message 完成] session=%s call_count=%d response_len=%d time=%.0fms",
session_id, call_count,
len(response_text) if response_text else 0,
processing_time_ms,
)
return {
"session_id": session.session_id,
"response_agent_code": target_agent,
"response_content": response_text,
"routing_reason": routing_reason,
"processing_time_ms": round(processing_time_ms, 2)
}
@staticmethod
def _save_tool_interactions(
memory: SessionMemory,
agent_memory_msgs: list,
) -> None:
"""从 ReAct 循环内存中提取所有 tool_use/tool_result,保留 Block 结构保存到 conversation_history。"""
for msg in agent_memory_msgs:
if not hasattr(msg, "content") or not msg.content:
continue
blocks = msg.content if isinstance(msg.content, list) else []
for block in blocks:
if not isinstance(block, dict):
continue
block_type = block.get("type")
if block_type == "tool_use":
memory.add(
"assistant",
[{
"type": "tool_use",
"id": block["id"],
"name": block["name"],
"input": block.get("input", {}),
}],
name="assistant",
)
elif block_type == "tool_result":
memory.add(
"system",
[{
"type": "tool_result",
"id": block["id"],
"name": block["name"],
"output": block.get("output", ""),
}],
name="system",
)
def _get_mouth_key(self) -> str:
"""返回发言人口 agent 的 code。"""
return "-1"
async def _call_sub_agent(self, agent_code: str, instruction: str) -> str:
"""通过 ReActAgent 调用子 Agent。"""
# 自调用防护
steward_key = self._find_steward_key()
if agent_code == steward_key:
return (
f"错误:不允许主Agent自调用。"
f"如需总结回复,请调用发言人Agent(调用码: {self._get_mouth_key()})。"
)
if agent_code not in self.agents:
valid = [c for c, a in self.agents.items() if not a.is_steward]
return (
f"错误:子 Agent '{agent_code}' 不存在。"
f"可用调用码: {valid}"
)
sub_prompt = self._build_sub_agent_prompt(agent_code)
sub_memory = InMemoryMemory()
logger.info("[子Agent 开始] agent_code=%s instruction=%s", agent_code, instruction[:80])
sub_agent = ReActAgent(
name=agent_code,
sys_prompt=sub_prompt,
model=self.sub_model, # sub_agent 专用低 temperature 实例
formatter=self.formatter,
toolkit=self.agent_toolkits.get(agent_code, self.toolkit),
memory=sub_memory,
max_iters=10,
)
# 为子 Agent 注册 IM hook(post_reasoning → thinking 摘要)
ctx = self._current_route_ctx
self._register_im_hooks(sub_agent, ctx["room_id"], ctx["user_id"], ctx["bot_id_mapping"])
response = await sub_agent.reply(Msg("user", instruction, "user"))
response_text = response.get_text_content()
logger.info("[子Agent 完成] agent_code=%s response_len=%d", agent_code, len(response_text) if response_text else 0)
# 子 Agent 用自己的 bot 账号发送最终回复
try:
await self.post_reply_hook.execute({
"agent_name": agent_code,
"response_content": response_text,
"room_id": ctx["room_id"],
"mentioned_list": [ctx["user_id"]],
"bot_id_mapping": ctx["bot_id_mapping"],
})
except Exception:
logger.warning(
"[子Agent IM 发送失败] agent=%s room=%s(不影响推理流程)",
agent_code, ctx.get("room_id"), exc_info=True,
)
return response_text
def _make_read_file_tool(self):
"""Create a sandboxed read_file tool function.
The sandbox root is the backend project directory (parent of app/).
"""
root_dir = Path(__file__).parent.parent.parent.resolve()
async def read_file(file_path: str) -> ToolResponse:
"""Read the content of a local file. Path is relative to the project root.
Use this to read SKILL.md files, MEMORY.md, configuration files, etc.
Example: read_file('skills/get_weather/SKILL.md')
Args:
file_path: File path relative to the project root,
e.g. 'skills/meeting_minutes/SKILL.md' or 'config/agents.json'
Returns:
File content as text, truncated to 10000 characters if too large.
"""
try:
# Normalize: convert backslashes, strip single leading ./
normalized = file_path.replace("\\", "/")
if normalized.startswith("./"):
normalized = normalized[2:]
full_path = (root_dir / normalized).resolve()
# Sandbox check: prevent path traversal (must be BEFORE exists check)
if not str(full_path).startswith(str(root_dir)):
return ToolResponse(
content=[TextBlock(
type="text",
text="❌ Access denied: path escapes project root"
)]
)
if not full_path.exists():
return ToolResponse(
content=[TextBlock(
type="text",
text=f"❌ File not found: {file_path}"
)]
)
if not full_path.is_file():
return ToolResponse(
content=[TextBlock(
type="text",
text=f"❌ Not a file: {file_path}"
)]
)
content = full_path.read_text(encoding="utf-8")
if len(content) > 10000:
content = content[:10000] + "\n...[truncated]"
return ToolResponse(
content=[TextBlock(type="text", text=content)]
)
except Exception as e:
return ToolResponse(
content=[TextBlock(
type="text",
text=f"❌ Error reading file: {str(e)}"
)]
)
return read_file
def _make_call_sub_agent_tool(self):
"""Create closure tool function for registration to Toolkit."""
async def call_sub_agent(agent_code: str = "", instruction: str = "") -> ToolResponse:
"""调用子Agent处理特定任务。
当用户问题属于某个子Agent的职责范围时,必须调用此工具委托处理。
Args:
agent_code: 子Agent调用码,必须从可用子Agent列表中选择
instruction: 给子Agent的具体指令,必须包含用户需求的完整描述
Returns:
子Agent的处理结果
"""
if not agent_code or not instruction:
# 动态获取一个非 steward 的 agent key 作为示例
sub_example = next(
(k for k, a in self.agents.items() if not a.is_steward), "sub_agent"
)
return ToolResponse(
content=[TextBlock(type="text", text=(
"错误:agent_code 和 instruction 都是必填参数。\n"
f"正确示例:call_sub_agent(agent_code=\"{sub_example}\", instruction=\"请帮我处理任务\")"
))]
)
# 新增:递增调用计数
ctx = getattr(self, "_current_route_ctx", None)
if ctx:
ctx["call_count"] = ctx.get("call_count", 0) + 1
call_no = ctx["call_count"]
else:
call_no = 0
logger.info(
"[call_sub_agent #%d] agent_code=%s instruction=%s",
call_no, agent_code, instruction[:80],
)
result = await self._call_sub_agent(agent_code, instruction)
logger.info(
"[call_sub_agent #%d 完成] agent_code=%s result_len=%d",
call_no, agent_code, len(result),
)
return ToolResponse(
content=[TextBlock(type="text", text=result)]
)
return call_sub_agent
async def _summarize_thinking(self, thinking_text: str) -> str:
"""将思考过程总结为简短的状态更新,不暴露内部推理细节。"""
try:
system_msg = Msg("system", self.summarize_prompt, "system")
user_msg = Msg("user", thinking_text, "user")
formatted = await self.formatter.format([system_msg, user_msg])
response = await self.thinking_summary_model(formatted)
text_parts = []
for block in response.content:
if isinstance(block, dict) and block.get("type") == "text":
text_parts.append(block.get("text", ""))
summary = "".join(text_parts).strip()
return summary or thinking_text[:30] + "..."
except Exception:
logger.warning("thinking 摘要化失败,使用截断兜底", exc_info=True)
return thinking_text[:30] + "..."
def register_skill_tool(self, skill_name: str, tool_func, func_name: str):
"""将工具注册到所有拥有该 skill 的 agent toolkit"""
for agent_code, agent_config in self.agents.items():
if skill_name in agent_config.skills:
self.agent_toolkits[agent_code].register_tool_function(
tool_func,
func_name=func_name,
group_name="basic",
)
async def close(self):
"""Clean up resources (no-op with AgentScope)."""
pass