agent_hub.py
32.2 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
import logging
import time
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 → text 转换。
ReActAgent 在 reasoning 阶段产出的 thinking block 会存入 InMemoryMemory,
后续 API 调用格式化历史消息时会遇到该类型。原生 formatter 不认识 thinking
类型会打 warning,这里将其转为 text block 保留推理上下文。
"""
async def _format(self, msgs: list) -> list:
for msg in msgs:
blocks = msg.content if isinstance(msg.content, list) else []
if not blocks:
continue
new_blocks = []
for block in blocks:
if isinstance(block, dict) and block.get("type") == "thinking":
text = block.get("thinking", "")
if text.strip():
new_blocks.append({"type": "text", "text": text})
else:
new_blocks.append(block)
msg.content = new_blocks
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,
):
self.config_loader = config_loader
self.session_service = session_service
self.im_service = im_service
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.agents["-1"] = AgentConfig(
name="发言人",
code="-1",
prompt=(
"你是发言人,负责将各子Agent的处理结果汇总为自然流畅、用户友好的回复。"
"不要重复执行子Agent的任务,只做总结和润色。"
),
description="汇总子Agent处理结果,生成统一回复",
is_steward=False,
)
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] = {}
for agent_code, agent_config in self.agents.items():
logger.info(f"构建 agent '{agent_code}' 的专属 Toolkit (skills: {agent_config.skills})")
agent_tk = Toolkit()
# 复制 basic 组工具(所有 agent 共用)
for name, tool in self.toolkit.tools.items():
if tool.group == "basic":
# 口 agent 不需要 call_sub_agent 工具
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,
)
# 只复制该 agent 配置的 skills
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
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 _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
def _dict_to_msg(self, m: dict) -> Msg:
"""SessionStore dict → AgentScope Msg。只处理 user/assistant 文本消息。"""
role = m.get("role", "user")
if role not in ("user", "assistant", "system"):
role = "user"
content = m.get("content") or ""
return Msg(name=role, role=role, content=content)
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()
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 = [self._dict_to_msg(m) for m in recent]
if history_msgs:
await agent_memory.add(history_msgs)
# 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, agent_code=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_content = response_msg.get_text_content() or ""
# 将 ReAct 循环中所有工具调用/结果保存到 conversation_history
try:
msg_list = await agent.memory.get_memory()
self._save_tool_interactions(memory, msg_list)
except Exception:
logger.warning(
"[AgentHub] session=%s 保存工具消息异常(不影响主流程)",
session_id, exc_info=True,
)
call_count = self._current_route_ctx.get("call_count", 0)
if call_count >= 1:
# 主Agent 委托了子Agent,最终回复不写 KV、不存 DB、不发送
logger.info(
"[主Agent 静默] call_count=%d,所有子Agent(含发言人)已发送回复,跳过主Agent 回复",
call_count,
)
else:
# call_count == 0:主Agent 自己直接回复,正常写入 + 存 DB + 发送
memory.add("assistant", response_content, agent_code=target_agent)
self.session_service.save_to_db(session_id)
try:
await self.post_reply_hook.execute({
"agent_name": target_agent,
"response_content": response_content,
"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, 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_content) if response_content else 0,
processing_time_ms,
)
return {
"session_id": session.session_id,
"response_agent_code": target_agent,
"response_content": response_content,
"routing_reason": routing_reason,
"processing_time_ms": round(processing_time_ms, 2)
}
@staticmethod
def _save_tool_interactions(
memory: SessionMemory,
agent_memory_msgs: list,
default_agent_code: str = "",
) -> None:
"""从 ReAct 循环内存中提取所有 tool_use/tool_result,保存到 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":
inp = block.get("input", {})
name = block.get("name", "")
memory.add("assistant", str(inp), agent_code=default_agent_code or name)
elif block_type == "tool_result":
output = block.get("output", "")
if isinstance(output, list):
texts = [
item.get("text", "")
for item in output
if isinstance(item, dict) and item.get("type") == "text"
]
result_text = "\n".join(texts)
elif isinstance(output, str):
result_text = output
else:
result_text = str(output)
if result_text:
name = block.get("name", "")
memory.add("assistant", result_text, agent_code=default_agent_code or name)
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 的 ReAct 消息落地到同一 session
sub_msgs = await sub_agent.memory.get_memory()
ctx = self._current_route_ctx
session_memory = ctx.get("session_memory") if ctx else None
if session_memory:
self._save_tool_interactions(session_memory, sub_msgs, default_agent_code=agent_code)
# 子 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