feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持

This commit is contained in:
hugo committed 2026-07-07 11:10:32 +08:00
1 parent ac4262cd75
commit c8ce77199e
183 files changed
+11690 -2300

No files matched your search

@@ -0,0 +1,85 @@
"""
backend/app/services/chat/action_registry.py
用途:Chat Turn Action Handler 注册与解析。
依赖:turn_context.TurnContext、action_schema.TurnEvent、agent_registry.resolver。
逻辑:各领域在 chat_action_handlers / maintenance_chat_actions 等模块注册 handler;turn_runtime 调用 resolve。
"""
from __future__ import annotations
from typing import Any, Iterator, Protocol
from app.core.errors import ForbiddenError, NotFoundError, ValidationError
from app.services.chat.action_schema import TurnEvent
from app.services.chat.turn_context import TurnContext
# action_type 前缀 → 允许的 agent_code 集合;空集合表示不限制。
ACTION_AGENT_CODES: dict[str, tuple[str, ...]] = {
"shipping.": ("shipping_notice",),
}
class ChatActionHandler(Protocol):
"""业务 Action Handler 统一接口。"""
action_type: str
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
...
_REGISTRY: dict[str, ChatActionHandler] = {}
def register_action_handler(handler: ChatActionHandler) -> ChatActionHandler:
"""注册 action handler 并返回原实例,便于模块级装饰式写法。"""
key = str(getattr(handler, "action_type", "") or "").strip()
if not key:
raise ValidationError("action handler missing action_type")
_REGISTRY[key] = handler
return handler
def list_action_types() -> list[str]:
return sorted(_REGISTRY.keys())
def _assert_agent_may_run(action_type: str, agent: Any) -> None:
from app.services.agent_registry.resolver import resolve_agent_code
agent_code = resolve_agent_code(agent)
for prefix, allowed_codes in ACTION_AGENT_CODES.items():
if not action_type.startswith(prefix):
continue
if allowed_codes and agent_code not in allowed_codes:
agent_name = str(getattr(agent, "name", "") or "").strip() or agent_code
raise ForbiddenError(f"Agent '{agent_name}' cannot run action '{action_type}'")
return
def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler:
"""
根据 input.action_type 解析 handler,并校验 Agent 权限。
Raises:
ValidationError: action_type 缺失或未注册。
ForbiddenError: 当前 Agent 不允许执行该 action。
"""
action_type = str(ctx.input.action_type or "").strip()
if not action_type:
raise ValidationError("action_type is required for action/form_submit turns")
handler = _REGISTRY.get(action_type)
if handler is None:
raise NotFoundError(f"Unknown action_type: {action_type}")
_assert_agent_may_run(action_type, ctx.agent)
return handler
def ensure_handlers_loaded() -> None:
"""延迟导入各领域 handler 模块以完成注册。"""
from app.services.shipping_notice import chat_action_handlers as _shipping_handlers # noqa: F401
from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401
_ = _shipping_handlers
_ = _shipping_extended