""" backend/app/services/agent_runtime_context/builder.py 用途:构建并序列化 HXOPS 平台统一的 agent_runtime_context。 依赖:schema 协议常量、policy 裁剪策略、json/uuid/time 标准库。 逻辑:聊天入口或业务 adapter 调用本模块生成每次 Runtime 调用前的现场 snapshot,再作为 Dify Start 变量注入。 """ from __future__ import annotations import json import time from typing import Any from uuid import uuid4 from app.services.agent_runtime_context.policy import ( MAX_CONTEXT_JSON_CHARS, normalize_domain, normalize_reference_context, normalize_refs, ) from app.services.agent_runtime_context.schema import ( AGENT_RUNTIME_CONTEXT_INPUT, AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION, AgentRuntimeContext, ) def generate_context_id() -> str: """ 生成单次 Runtime 上下文编号。 核心逻辑:使用毫秒时间戳与短 UUID,便于日志检索且不暴露业务编号。 Returns: 形如 ctx_20260702094300000_ab12cd34 的上下文编号。 """ timestamp_ms = int(time.time() * 1000) return f"ctx_{timestamp_ms}_{uuid4().hex[:8]}" def _normalize_platform( *, session_id: str, parent_session_id: str | None = None, request_id: str | None = None, trigger_source: str | None = None, locale: str | None = None, ) -> dict[str, str]: """ 构建平台侧上下文片段。 核心逻辑:session_id 为必填锚点,其余字段有值才输出,避免空字段误导 Runtime。 Args: session_id: HXOPS ChatSession.session_id。 parent_session_id: 后台 run 所属的用户主会话;缺省时等于 session_id。 request_id: 本次请求追踪 ID。 trigger_source: 触发来源,如 frontend_chat/backend_orchestrator。 locale: 用户语言。 Returns: 平台上下文字典。 """ normalized_session_id = str(session_id or "").strip() platform = {"session_id": normalized_session_id} normalized_parent = str(parent_session_id or "").strip() if normalized_parent: platform["parent_session_id"] = normalized_parent elif normalized_session_id: platform["parent_session_id"] = normalized_session_id normalized_request_id = str(request_id or "").strip() normalized_trigger_source = str(trigger_source or "").strip() normalized_locale = str(locale or "").strip() if normalized_request_id: platform["request_id"] = normalized_request_id if normalized_trigger_source: platform["trigger_source"] = normalized_trigger_source if normalized_locale: platform["locale"] = normalized_locale return platform def build_agent_runtime_context( *, agent_code: str = "generic", scope: str = "chat_turn", session_id: str, parent_session_id: str | None = None, request_id: str | None = None, trigger_source: str | None = None, locale: str | None = None, refs: dict[str, Any] | None = None, domain: dict[str, Any] | None = None, reference_context: dict[str, Any] | None = None, context_id: str | None = None, ) -> AgentRuntimeContext: """ 构建单次 Runtime 调用的上下文 snapshot。 核心逻辑:校验 session 锚点,填充平台字段,裁剪 refs/domain/reference_context,并生成 context_id 供审计追踪。 Args: agent_code: 稳定 Agent 标识,禁止使用展示名称。 scope: 上下文作用域,如 chat_turn/task_run。 session_id: HXOPS 本地会话 ID。 parent_session_id: 后台任务所属主会话 ID。 request_id: 本次请求 ID。 trigger_source: 触发来源。 locale: 用户语言。 refs: 业务对象锚点字典。 domain: 业务域摘要与状态提示。 reference_context: 短期指代治理上下文。 context_id: 外部指定的上下文编号;通常留空自动生成。 Returns: agent_runtime_context 字典;session_id 为空时返回空 dict。 """ normalized_session_id = str(session_id or "").strip() if not normalized_session_id: return {} context: AgentRuntimeContext = { "schema_version": AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION, "context_id": str(context_id or "").strip() or generate_context_id(), "agent_code": str(agent_code or "generic").strip() or "generic", "scope": str(scope or "chat_turn").strip() or "chat_turn", "platform": _normalize_platform( session_id=normalized_session_id, parent_session_id=parent_session_id, request_id=request_id, trigger_source=trigger_source, locale=locale, ), "refs": normalize_refs(refs), } normalized_domain = normalize_domain(domain) if normalized_domain: context["domain"] = normalized_domain normalized_reference_context = normalize_reference_context(reference_context) if normalized_reference_context: context["reference_context"] = normalized_reference_context return context def serialize_for_dify(context: dict[str, Any]) -> str: """ 将上下文序列化为 Dify Start 节点可稳定接收的 JSON 字符串。 核心逻辑:使用紧凑 JSON,超过平台限制时抛 ValueError,避免悄悄截断成非法 JSON。 Args: context: agent_runtime_context 字典。 Returns: UTF-8 JSON 字符串。 Raises: ValueError: 上下文序列化后超过长度上限。 """ payload = json.dumps(context or {}, ensure_ascii=False, separators=(",", ":")) if len(payload) > MAX_CONTEXT_JSON_CHARS: raise ValueError("agent_runtime_context exceeds max serialized length") return payload def build_dify_inputs( context: dict[str, Any], ) -> dict[str, Any]: """ 构建传给 Dify 的 inputs。 核心逻辑:统一只输出 agent_runtime_context JSON 字符串,避免 Start 协议出现多套上下文字段。 Args: context: agent_runtime_context 字典。 Returns: Dify inputs 字典。 """ if not context: return {} return {AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(context)}