PMFlow/backend/app/services/adaptive_rag_service/shared_utils.py

241 lines
8.0 KiB
Python

"""Adaptive RAG shared utils."""
from __future__ import annotations
from .shared_imports import *
from .internal_query_context import (
internal_context_operation_contract,
internal_context_query_plan,
internal_context_semantic_mirror,
internal_context_target_resolution,
)
_BUSINESS_FRAME_FIELDS = (
"goal_kind",
"target_scope",
"resource_role",
"source_kind",
"expected_answer_shape",
"conversation_posture",
"project_binding",
"subject_binding",
"object_binding",
"candidate_set_binding",
"evidence_mode",
)
_BUSINESS_ROLE_TO_ENTITY_TYPE = {
"project_object": "project",
"task": "task",
"signal": "signal",
"signal_source": "signal",
"external_input": "signal",
"config": "config",
"people": "user",
"feature": "feature",
"doc": "doc",
}
def _env_bool(name: str, default: bool = False) -> bool:
raw = str(os.getenv(name, "") or "").strip().lower()
if not raw:
return bool(default)
if raw in {"1", "true", "yes", "on"}:
return True
if raw in {"0", "false", "no", "off"}:
return False
return bool(default)
def _env_int(name: str, default: int, *, minimum: int, maximum: int) -> int:
raw = str(os.getenv(name, "") or "").strip()
if not raw:
value = int(default)
else:
try:
value = int(raw)
except Exception:
value = int(default)
return max(minimum, min(maximum, value))
def _coalesce_business_frame_from_runtime(
*,
query_semantics: Optional[dict[str, Any]] = None,
operation_contract: Optional[dict[str, Any]] = None,
target_resolution: Optional[dict[str, Any]] = None,
query_plan: Optional[dict[str, Any]] = None,
internal_context_packet: Any = None,
) -> dict[str, Any]:
semantics = query_semantics if isinstance(query_semantics, dict) else {}
operation = internal_context_operation_contract(
packet=internal_context_packet,
fallback=(
operation_contract
if isinstance(operation_contract, dict)
else internal_context_semantic_mirror(
packet=internal_context_packet,
query_semantics=semantics,
key="operation_contract",
)
),
)
target = internal_context_target_resolution(
packet=internal_context_packet,
fallback=(
target_resolution
if isinstance(target_resolution, dict)
else internal_context_semantic_mirror(
packet=internal_context_packet,
query_semantics=semantics,
key="target_resolution",
)
),
)
plan = internal_context_query_plan(
packet=internal_context_packet,
fallback=(
query_plan
if isinstance(query_plan, dict)
else internal_context_semantic_mirror(
packet=internal_context_packet,
query_semantics=semantics,
key="query_plan",
)
),
)
frame: dict[str, Any] = {}
rows: list[dict[str, Any]] = []
if isinstance(semantics.get("business_frame"), dict):
rows.append(dict(semantics.get("business_frame") or {}))
rows.append(dict(semantics))
if isinstance(operation.get("business_frame"), dict):
rows.append(dict(operation.get("business_frame") or {}))
rows.append(dict(operation))
if isinstance(target.get("business_frame"), dict):
rows.append(dict(target.get("business_frame") or {}))
rows.append(dict(target))
if isinstance(plan.get("business_frame"), dict):
rows.append(dict(plan.get("business_frame") or {}))
rows.append(dict(plan))
for row in rows:
if not isinstance(row, dict):
continue
for key in _BUSINESS_FRAME_FIELDS:
value = row.get(key)
if value in (None, "", []):
continue
frame[key] = value
return frame
def _structured_runtime_entity_type(
*,
query_semantics: Optional[dict[str, Any]] = None,
operation_contract: Optional[dict[str, Any]] = None,
target_resolution: Optional[dict[str, Any]] = None,
query_plan: Optional[dict[str, Any]] = None,
internal_context_packet: Any = None,
) -> str:
semantics = query_semantics if isinstance(query_semantics, dict) else {}
target = internal_context_target_resolution(
packet=internal_context_packet,
fallback=(
target_resolution
if isinstance(target_resolution, dict)
else internal_context_semantic_mirror(
packet=internal_context_packet,
query_semantics=semantics,
key="target_resolution",
)
),
)
target_entity_type = str(target.get("target_entity_type") or "").strip().lower()
if target_entity_type in {"project", "task", "signal", "feature", "config", "user", "doc", "document", "requirement", "release", "review"}:
return target_entity_type
plan = internal_context_query_plan(
packet=internal_context_packet,
fallback=(
query_plan
if isinstance(query_plan, dict)
else internal_context_semantic_mirror(
packet=internal_context_packet,
query_semantics=semantics,
key="query_plan",
)
),
)
planned_entity_type = str(plan.get("entity_type") or "").strip().lower()
if planned_entity_type in {"project", "task", "signal", "feature", "config", "user", "doc", "document", "requirement", "release", "review"}:
return planned_entity_type
subject_focus = str(semantics.get("subject_focus") or "").strip().lower()
if subject_focus in {"project", "task", "signal", "feature", "config", "user", "doc", "document", "requirement", "release", "review"}:
return subject_focus
business_frame = _coalesce_business_frame_from_runtime(
query_semantics=semantics,
operation_contract=operation_contract,
target_resolution=target_resolution,
query_plan=query_plan,
internal_context_packet=internal_context_packet,
)
object_binding = str(business_frame.get("object_binding") or "").strip().lower()
if object_binding.startswith("feature:"):
return "feature"
if object_binding.startswith("config:"):
return "config"
resource_role = str(business_frame.get("resource_role") or "").strip().lower()
mapped = _BUSINESS_ROLE_TO_ENTITY_TYPE.get(resource_role)
if mapped:
return mapped
target_scope = str(business_frame.get("target_scope") or "").strip().lower()
project_binding = business_frame.get("project_binding")
if target_scope in {"current_project", "explicit_project"} and project_binding not in (None, "", []):
return "project"
return "unknown"
def _structured_project_requested(
*,
query_semantics: Optional[dict[str, Any]] = None,
operation_contract: Optional[dict[str, Any]] = None,
target_resolution: Optional[dict[str, Any]] = None,
query_plan: Optional[dict[str, Any]] = None,
internal_context_packet: Any = None,
) -> bool:
if _structured_runtime_entity_type(
query_semantics=query_semantics,
operation_contract=operation_contract,
target_resolution=target_resolution,
query_plan=query_plan,
internal_context_packet=internal_context_packet,
) == "project":
return True
business_frame = _coalesce_business_frame_from_runtime(
query_semantics=query_semantics,
operation_contract=operation_contract,
target_resolution=target_resolution,
query_plan=query_plan,
internal_context_packet=internal_context_packet,
)
target_scope = str(business_frame.get("target_scope") or "").strip().lower()
return target_scope in {"current_project", "explicit_project"} and business_frame.get("project_binding") not in (
None,
"",
[],
)
__all__ = [
"_env_bool",
"_env_int",
"_coalesce_business_frame_from_runtime",
"_structured_project_requested",
"_structured_runtime_entity_type",
]