""" backend/app/services/agent_runtime_context/reference.py 用途:构建平台级 reference_context,给外部 Runtime 提供短期指代解析线索。 依赖:agent_runtime_context.policy、schema;不依赖具体业务模型。 逻辑:业务 adapter 先把 focus/last_action/candidates 等抽象成对象引用,再由本模块统一裁剪、去重和限流。 """ from __future__ import annotations from typing import Any from app.services.agent_runtime_context.policy import MAX_REF_VALUE_CHARS, normalize_reference_context, truncate_text from app.services.agent_runtime_context.schema import ReferenceContext MAX_REFERENCE_OBJECT_TYPE_CHARS = 64 MAX_REFERENCE_KEY_CHARS = 64 MAX_REFERENCE_CANDIDATES = 5 def build_object_ref(type_: str, id_: str, **extra: Any) -> dict[str, str]: """ 构建 reference_context 中的对象引用。 核心逻辑:统一输出 type/id,并裁剪 action/reason/label 等扩展字段,避免业务 adapter 各自拼装不同口径。 Args: type_: 对象类型,如 task/batch。 id_: 对象稳定标识,如 SN-001。 **extra: 可选扩展字段,例如 action/reason/label。 Returns: 规范化后的对象引用;type 或 id 为空时返回空 dict。 """ normalized_type = truncate_text(type_, MAX_REFERENCE_OBJECT_TYPE_CHARS) normalized_id = truncate_text(id_, MAX_REF_VALUE_CHARS) if not normalized_type or not normalized_id: return {} object_ref: dict[str, str] = { "type": normalized_type, "id": normalized_id, } for raw_key, raw_value in extra.items(): key = truncate_text(raw_key, MAX_REFERENCE_KEY_CHARS) if not key or key in object_ref or raw_value is None: continue value = truncate_text(raw_value, MAX_REF_VALUE_CHARS) if not value: continue object_ref[key] = value return object_ref def _normalize_object_ref(value: dict[str, Any] | None) -> dict[str, str]: """ 规范化单个对象引用。 核心逻辑:兼容业务 adapter 传入的普通 dict,统一转成 build_object_ref 输出结构。 Args: value: 原始对象引用。 Returns: 规范化后的对象引用;非法输入返回空 dict。 """ if not isinstance(value, dict): return {} extra = {key: item for key, item in value.items() if key not in {"type", "type_", "id"}} return build_object_ref( str(value.get("type") or value.get("type_") or ""), str(value.get("id") or ""), **extra, ) def _normalize_candidates(candidates: list[dict[str, Any]] | None) -> list[dict[str, str]]: """ 规范化候选对象列表。 核心逻辑:只保留前几个有效候选,按 type/id 去重,避免把整批对象全塞给 Dify。 Args: candidates: 候选对象引用列表。 Returns: 去重并限量后的候选列表。 """ normalized: list[dict[str, str]] = [] seen: set[tuple[str, str]] = set() for item in candidates or []: candidate = _normalize_object_ref(item) if not candidate: continue dedupe_key = (candidate["type"], candidate["id"]) if dedupe_key in seen: continue normalized.append(candidate) seen.add(dedupe_key) if len(normalized) >= MAX_REFERENCE_CANDIDATES: break return normalized def build_reference_context( *, recent_activity_summary: str | None = None, focus_object: dict[str, Any] | None = None, last_action_target: dict[str, Any] | None = None, last_failed_target: dict[str, Any] | None = None, candidates: list[dict[str, Any]] | None = None, ) -> ReferenceContext: """ 构建平台统一的 reference_context。 核心逻辑:收敛业务 adapter 提供的短期指代线索,限制候选数量并裁剪摘要长度,保证输出小而稳定。 Args: recent_activity_summary: 最近活动摘要。 focus_object: 当前焦点对象。 last_action_target: 最近一次动作作用对象。 last_failed_target: 最近一次失败/异常对象。 candidates: 模糊指代候选对象列表。 Returns: 规范化后的 reference_context;所有字段都为空时返回空 dict。 """ reference_context: ReferenceContext = {} summary = str(recent_activity_summary or "").strip() if summary: reference_context["recent_activity_summary"] = summary normalized_focus = _normalize_object_ref(focus_object) if normalized_focus: reference_context["focus_object"] = normalized_focus normalized_last_action = _normalize_object_ref(last_action_target) if normalized_last_action: reference_context["last_action_target"] = normalized_last_action normalized_last_failed = _normalize_object_ref(last_failed_target) if normalized_last_failed: reference_context["last_failed_target"] = normalized_last_failed normalized_candidates = _normalize_candidates(candidates) if normalized_candidates: reference_context["candidates"] = normalized_candidates return normalize_reference_context(reference_context) __all__ = [ "MAX_REFERENCE_CANDIDATES", "build_object_ref", "build_reference_context", ]