Files
planet/backend/app/services/ai/dag_evidence.py
T
linkong e1cc27f13d
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.84.0
2026-12-04 07:07:19 +08:00

144 lines
4.9 KiB
Python

"""Shared URL-normalized evidence ledger for workflow DAG nodes and guardrails."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Sequence
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
_TRACKING_QUERY_PARAMS: frozenset[str] = frozenset({"fbclid", "gclid", "mc_cid", "mc_eid"})
_IGNORED_DOC_EXTENSIONS: tuple[str, ...] = (".csv", ".tsv", ".xlsx", ".xls", ".parquet", ".json")
def normalize_evidence_url(url: Any) -> str:
"""Canonicalize an HTTP(S) URL for deduplication and anti-hallucination matching."""
raw = str(url or "").strip()
if not raw:
return ""
try:
parts = urlsplit(raw)
except ValueError:
return raw.rstrip("/").lower()
scheme = (parts.scheme or "https").lower()
if scheme == "http":
scheme = "https"
netloc = parts.netloc.lower()
path = parts.path.rstrip("/")
kept_query = sorted(
(k, v)
for k, v in parse_qsl(parts.query, keep_blank_values=True)
if not k.lower().startswith("utm_") and k.lower() not in _TRACKING_QUERY_PARAMS
)
return urlunsplit((scheme, netloc, path, urlencode(kept_query), ""))
def is_tabular_dataset_url(url: Any) -> bool:
"""Return True for raw bulk-data files (e.g. Epoch csv exports) unsuitable for webpage fetch."""
raw = str(url or "").strip()
if not raw:
return False
try:
path = urlsplit(raw).path.lower()
except ValueError:
path = raw.lower()
return path.endswith(_IGNORED_DOC_EXTENSIONS)
@dataclass
class EvidenceLedger:
"""Assigns sequential ``E1..En`` IDs to tool-observed URLs and resolves citations safely."""
items: list[dict[str, Any]] = field(default_factory=list)
by_id: dict[str, dict[str, Any]] = field(default_factory=dict)
by_norm_url: dict[str, dict[str, Any]] = field(default_factory=dict)
evidence_calls: int = 0
def record_call(self) -> None:
self.evidence_calls += 1
def add(
self,
*,
url: str,
title: str = "",
snippet: str = "",
tool: str = "",
query: str = "",
) -> str | None:
cleaned_url = str(url or "").strip()
if not cleaned_url:
return None
norm = normalize_evidence_url(cleaned_url)
if not norm:
return None
existing = self.by_norm_url.get(norm)
cleaned_snippet = str(snippet or "").strip()
cleaned_title = str(title or "").strip()
if existing is not None:
if len(cleaned_snippet) > len(str(existing.get("snippet") or "")):
existing["snippet"] = cleaned_snippet[:1500]
if cleaned_title and not existing.get("title"):
existing["title"] = cleaned_title[:200]
return str(existing["id"])
eid = f"E{len(self.items) + 1}"
entry = {
"id": eid,
"url": cleaned_url,
"norm_url": norm,
"title": cleaned_title[:200],
"snippet": cleaned_snippet[:1500],
"tool": tool,
"query": query,
}
self.items.append(entry)
self.by_id[eid] = entry
self.by_norm_url[norm] = entry
return eid
def resolve_refs(self, refs: Sequence[Any]) -> tuple[list[str], list[str]]:
"""Map ``['E1', 'https://...']`` references back to verified IDs and original URLs."""
verified_ids: list[str] = []
verified_urls: list[str] = []
seen_urls: set[str] = set()
for raw in refs:
token = str(raw or "").strip()
if not token:
continue
entry = self.by_id.get(token.upper())
if entry is None:
entry = self.by_norm_url.get(normalize_evidence_url(token))
if entry is None:
continue
eid = str(entry["id"])
url = str(entry["url"])
norm = str(entry["norm_url"])
if eid not in verified_ids:
verified_ids.append(eid)
if norm not in seen_urls:
seen_urls.add(norm)
verified_urls.append(url)
return verified_ids, verified_urls
def to_prompt_items(self, limit: int = 14) -> list[dict[str, str]]:
return [
{
"id": str(item["id"]),
"title": str(item.get("title") or ""),
"url": str(item.get("url") or ""),
"tool": str(item.get("tool") or ""),
"excerpt": str(item.get("snippet") or "")[:900],
}
for item in self.items[:limit]
]
def to_evidence_dict(self) -> dict[str, dict[str, str]]:
return {
str(item["id"]): {
"url": str(item.get("url") or ""),
"title": str(item.get("title") or ""),
"source": str(item.get("tool") or "web"),
}
for item in self.items
}