agent_hub.py 16.6 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
import logging
import time
from pathlib import Path
from typing import Dict, List, Optional, Any
from app.config.loader import ConfigLoader
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
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__)


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,
    ):
        self.config_loader = config_loader
        self.session_service = session_service

        self.agents = config_loader.load_agents()
        self.main_model_config = config_loader.load_models()["main"]
        agent_to_account, account_to_agent = config_loader.load_account_mappings()
        self.agent_to_account = agent_to_account
        self.account_to_agent = account_to_agent

        self.post_reply_hook = PostReplyHook(
            im_service=im_service,
            account_mapping=agent_to_account
        )

        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()

        # Register all skills from skills/ directory to Toolkit
        skills_dir = Path(__file__).parent.parent.parent / "skills"
        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()
        self.toolkit.register_tool_function(
            call_sub,
            func_name="call_sub_agent",
            group_name="basic",
        )

        # 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():
            agent_tk = Toolkit()
            # 复制 basic 组工具(所有 agent 共用)
            for name, tool in self.toolkit.tools.items():
                if tool.group == "basic":
                    agent_tk.register_tool_function(
                        tool.original_func,
                        group_name=tool.group,
                        func_name=tool.name,
                        preset_kwargs=tool.preset_kwargs,
                    )
            # 只复制该 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 _build_main_prompt(
        self,
        context: Dict[str, Any],
        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.
        """
        main_agent = self.agents.get("main")
        if not main_agent:
            raise AgentHubError("主 Agent 配置未找到")

        # Collect duties from sub-agents, filtered by position if applicable
        duty_lines = []
        for code, agent in self.agents.items():
            if code == "main":
                continue
            if allowed_agent_codes is not None and code not in allowed_agent_codes:
                continue
            duty_lines.append(
                f"- {agent.name}({agent.role},调用码: {code}): "
                f"{agent.prompt_template}"
            )

        duties_text = "\n".join(duty_lines) if duty_lines else "暂无子Agent"

        prompt = main_agent.prompt_template.format(
            company="公司",
            duties=duties_text,
        )

        review_guide = """
## 收到子Agent返回后

1. 判断结果是否完整,是否还需要其他子Agent协作
2. 如果已经可以回复,整合所有结果用自然语言回复用户
3. 不要再调用同一个子Agent重复处理
"""

        return prompt + review_guide

    def _build_sub_agent_prompt(self, agent_code: str, context: Dict[str, Any]) -> 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} 配置未找到")

        # Build duties from ALL agents (for context)
        duty_lines = []
        for code, a in self.agents.items():
            duty_lines.append(f"- {a.name}({a.role})")

        prompt = agent.prompt_template.format(
            company="公司",
            duties="\n".join(duty_lines),
        )

        return prompt

    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", "")
        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()

        session = self.session_service.get_or_create_session(
            session_id=session_id,
            room_id=room_id,
            user_id=user_id,
            channel=channel
        )

        memory = SessionMemory(
            session_id=session_id,
            store=self.session_service.store,
            max_rounds=20,
        )

        messages = memory.get_messages(max_rounds=10)

        # Determine target agent and routing reason
        position_restricted = allowed_agent_codes is not None

        if mentioned_agent_code and mentioned_agent_code in self.agents:
            if position_restricted and mentioned_agent_code not in allowed_agent_codes:
                target_agent = "main"
                routing_reason = "position_restricted"
            else:
                target_agent = mentioned_agent_code
                routing_reason = "mention"
        elif session.current_agent_code and session.current_agent_code in self.agents:
            if position_restricted and session.current_agent_code not in allowed_agent_codes:
                target_agent = "main"
                routing_reason = "position_restricted"
            else:
                target_agent = session.current_agent_code
                routing_reason = "inheritance"
        else:
            target_agent = "main"
            routing_reason = "default"

        context = {
            "user_query": user_query,
            "messages": messages,
            "room_id": room_id,
            "user_id": user_id
        }

        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 target_agent == "main":
            system_prompt = self._build_main_prompt(context, allowed_agent_codes=allowed_agent_codes)
        else:
            system_prompt = self._build_sub_agent_prompt(target_agent, context)

        # 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,
        )

        # 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")
        response_msg = await agent.reply(user_msg)
        response_content = response_msg.get_text_content()

        # Store messages via SessionMemory
        memory.add("user", user_query, agent_code=mentioned_agent_code or "main")
        memory.add("assistant", response_content, agent_code=target_agent)

        if target_agent != "main":
            self.session_service.update_current_agent(session.id, target_agent)

        # Send via hook
        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 {},
        })

        processing_time_ms = (time.time() - start_time) * 1000

        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)
        }

    async def _call_sub_agent(self, agent_code: str, instruction: str) -> str:
        """通过 ReActAgent 调用子 Agent。"""
        if agent_code not in self.agents:
            valid = [c for c in self.agents if c != "main"]
            return (
                f"错误:子 Agent '{agent_code}' 不存在。"
                f"可用调用码: {valid}"
            )

        sub_prompt = self._build_sub_agent_prompt(agent_code, {})
        sub_memory = InMemoryMemory()

        # All agents use the shared toolkit
        sub_toolkit = self.toolkit

        sub_agent = ReActAgent(
            name=agent_code,
            sys_prompt=sub_prompt,
            model=self.model,
            formatter=self.formatter,
            toolkit=self.agent_toolkits.get(agent_code, self.toolkit),
            memory=sub_memory,
            max_iters=10,
        )
        response = await sub_agent.reply(Msg("user", instruction, "user"))
        return response.get_text_content()

    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:
            """Call a sub-agent to handle a specific task.

            Args:
                agent_code: Sub-agent code, e.g. meeting / support
                instruction: Specific instructions for the sub-agent

            Returns:
                Sub-agent's processing result
            """
            result = await self._call_sub_agent(agent_code, instruction)
            return ToolResponse(
                content=[TextBlock(type="text", text=result)]
            )

        return call_sub_agent

    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