""" backend/app/services/chat/turn_context.py 用途:Chat Turn 执行上下文,供 turn_runtime 与 action handler 共享。 依赖:action_schema.TurnInput。 逻辑:turn_runtime 构造 TurnContext 后传入 handler.stream(ctx);refs 为不透明 dict,领域键名由各 handler 解析。 """ from __future__ import annotations from dataclasses import dataclass, field from typing import Any from app.services.chat.action_schema import TurnInput @dataclass class TurnContext: """ 单轮 Chat Turn 的运行时上下文。 Args: turn_id: 本轮唯一标识,写入 SSE 与 ChatLog 关联字段。 run_id: 与 turn_id 相同或独立 run 标识,供前端 runs 列表使用。 session_id: 本地 ChatSession.session_id。 request_id: HTTP 请求追踪 ID。 user: 当前用户代理对象(须含 id)。 agent: 当前 Agent 代理对象(须含 id、name)。 input: 归一化后的 TurnInput。 refs: 会话级业务锚点(不透明 dict);键名由各 domain 自行约定。 external_conversation_id: Dify 等外部会话 ID,可为空。 """ turn_id: str run_id: str session_id: str request_id: str user: Any agent: Any input: TurnInput refs: dict[str, str] = field(default_factory=dict) external_conversation_id: str | None = None @property def user_id(self) -> int | None: value = getattr(self.user, "id", None) return int(value) if value is not None else None @property def agent_id(self) -> int | None: value = getattr(self.agent, "id", None) return int(value) if value is not None else None @property def agent_name(self) -> str: return str(getattr(self.agent, "name", "") or "").strip()