router.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from __future__ import annotations
  2. from gateway.core.channels.protocols import TraceBackend
  3. class ChannelTraceRouter:
  4. """
  5. 与具体 IM 无关:按渠道 user_id 解析 workspace_id,并委托 TraceBackend 与 Agent ``trace_id`` 对齐。
  6. 飞书等渠道的入站消息路由见 ``gateway.core.channels.feishu.router.FeishuMessageRouter``。
  7. """
  8. def __init__(
  9. self,
  10. *,
  11. trace_backend: TraceBackend,
  12. workspace_prefix: str,
  13. default_agent_type: str = "personal_assistant",
  14. ) -> None:
  15. self._trace = trace_backend
  16. self._workspace_prefix = workspace_prefix
  17. self._agent_type = default_agent_type
  18. def _workspace_id_for_user(self, user_id: str) -> str:
  19. return f"{self._workspace_prefix}:{user_id}"
  20. async def get_trace_id(self, channel: str, user_id: str, *, create_if_missing: bool = True) -> str:
  21. """返回已绑定的 Agent trace_id;不存在时除非 ``create_if_missing=False`` 否则抛错(不再预分配 UUID)。"""
  22. tid = await self._trace.get_existing_trace_id(channel, user_id)
  23. if tid:
  24. return tid
  25. if not create_if_missing:
  26. raise NotImplementedError("无已绑定 trace_id 且 create_if_missing=False")
  27. raise RuntimeError(
  28. "尚无已绑定的 Agent trace_id:请先完成一次渠道入站(executor 成功返回后再 bind)。"
  29. )
  30. async def create_trace_for_user(self, channel: str, user_id: str) -> str:
  31. return await self.get_trace_id(channel, user_id, create_if_missing=True)