""" backend/app/services/chat/hxops_context.py 用途:构建 HXOPS -> Dify 的平台统一上下文注入协议。 依赖:无业务域依赖,仅提供平台级上下文结构与 refs 规范化工具。 逻辑:由聊天入口、后台编排器或各 Agent 适配层调用本模块,统一生成 hxops_context, 避免各业务目录重复定义 Dify Start 输入协议。 """ from __future__ import annotations from typing import Any HXOPS_CONTEXT_INPUT = "hxops_context" HXOPS_CONTEXT_SCHEMA_VERSION = "1" def build_ref(field: str, value: str | None) -> dict[str, str] | None: """构建单个业务对象引用;缺值时返回 None。""" normalized_field = str(field or "").strip() normalized_value = str(value or "").strip() if not normalized_field or not normalized_value: return None return {"field": normalized_field, "value": normalized_value} def build_hxops_context( *, session_id: str, request_id: str | None = None, trigger_source: str | None = None, locale: str | None = None, refs: list[dict[str, str] | None] | None = None, ) -> dict[str, Any]: """ 构建平台统一的 hxops_context。 设计约束: - 只注入平台基础信息与当前已知对象锚点 - 不注入 query/files 等 Dify 原生输入 - 不注入 checkpoint/stage 等运行态状态 """ normalized_session_id = str(session_id or "").strip() if not normalized_session_id: return {} request_payload: dict[str, str] = {} 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: request_payload["id"] = normalized_request_id if normalized_trigger_source: request_payload["trigger_source"] = normalized_trigger_source if normalized_locale: request_payload["locale"] = normalized_locale normalized_refs: list[dict[str, str]] = [] seen_fields: set[str] = set() for item in refs or []: if not item: continue field = str(item.get("field") or "").strip() value = str(item.get("value") or "").strip() if not field or not value or field in seen_fields: continue normalized_refs.append({"field": field, "value": value}) seen_fields.add(field) return { "schema_version": HXOPS_CONTEXT_SCHEMA_VERSION, "session": {"id": normalized_session_id}, "request": request_payload, "refs": normalized_refs, }