"""Atomic workflow tools, cascade geocoder, and L3 geo guardrails for `location.resolve_unknown`.""" from __future__ import annotations import asyncio import copy from dataclasses import dataclass from datetime import UTC, datetime import re from typing import Any from uuid import uuid4 from sqlalchemy import select from app.core.cache import cache from app.core.collected_data_fields import get_record_field from app.core.compute_types import compute_record_filter from app.core.countries import get_country_search_variants from app.core.logging import get_logger from app.services.earth_layer_cache import invalidate_earth_layer_cache_for_source from app.models.ai_workflow import AIWorkflow from app.models.collected_data import CollectedData from app.models.compute_center_location import ComputeCenterLocationRecord from app.models.situational_assessment import WorkflowRun from app.services.ai.dag_evidence import ( EvidenceLedger, is_tabular_dataset_url, normalize_evidence_url, ) from app.services.ai.tool_registry import isolate_untrusted_external_text, safe_web_fetch from app.services.ai_tools.web_search import normalize_web_search_provider from app.services.bgp_collector_locations import ( build_bgp_collector_location_query, collect_bgp_collector_location_candidates, get_bgp_collector_location_dict, ) from app.services.compute_center_locations import ( COMPUTE_CENTER_LOCATION_CACHE, _short_system_name, build_compute_center_location_query, collect_location_candidates, get_compute_center_location_dict, refresh_compute_center_location_cache, ) from app.services.location.models import LocationCandidate, LocationQuery from app.services.location.resolvers.nominatim import ( _DEFAULT_SITE_CATEGORIES, build_default_nominatim_geocoder, resolve_geocoder_country, ) from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility from app.services.location.resolvers.wikidata import lookup_wikidata_facility from app.services.location.text import ( coerce_str, normalize_country_text, normalize_text, parse_float, ) logger = get_logger(__name__, service="location_workflow") DEFAULT_MIN_CONFIDENCE = 0.55 TERMINAL_UNLOCATABLE_STATUSES: frozenset[str] = frozenset( {"undisclosed", "multi_site", "planned", "cloud_only", "anonymous"} ) _PAREN_EVIDENCE_ID_RE = re.compile( r"[\(\(\[]\s*E\d{1,3}(?:[\s,、/&\-–—]+E?\d{1,3})*\s*[\)\)\]]" ) _BARE_EVIDENCE_ID_RE = re.compile( r"(? str: """Remove internal evidence IDs (e.g., E6, E1-E5, (E3)) and tidy orphaned punctuation.""" cleaned = coerce_str(text) if not cleaned: return "" cleaned = _PAREN_EVIDENCE_ID_RE.sub("", cleaned) cleaned = _BARE_EVIDENCE_ID_RE.sub("", cleaned) cleaned = _EMPTY_PARENS_RE.sub("", cleaned) cleaned = _ORPHAN_LIST_SEP_RE.sub(r"\1 ", cleaned) cleaned = _SPACE_BEFORE_PUNCT_RE.sub(r"\1", cleaned) cleaned = re.sub(r"\s{2,}", " ", cleaned) cleaned = re.sub(r"^[,,、;;:\s]+", "", cleaned) cleaned = re.sub(r"(\s+[,,、])+", "", cleaned) return cleaned.strip() _agent_geocoder = build_default_nominatim_geocoder() @dataclass(frozen=True) class LocationAgentResult: candidates: list[LocationCandidate] attempted_queries: list[str] failure_reason: str | None = None workflow_run_id: str | None = None terminal_status: str | None = None _BASE_JUDGE_PROPERTIES: dict[str, Any] = { "facility_name": {"type": "string", "description": "Physical data center / campus / lab name"}, "address": {"type": "string", "description": "Street address if explicitly attested in evidence"}, "city": {"type": "string", "description": "Physical city/town/locality name (required for located)"}, "region": {"type": "string", "description": "State / province / region if known"}, "country": {"type": "string", "description": "Actual physical country in English (e.g. United States, Iceland)"}, "country_override_reason": { "type": "string", "description": "当物理部署国与源登记国不同时必填;使用简洁简体中文(不超过 120 字),禁止出现 E1 等证据编号", }, "precision": {"type": "string", "enum": ["precise", "site", "city"]}, "confidence": {"type": "number", "description": "0.0-1.0 evidence confidence"}, "evidence_ids": { "type": "array", "items": {"type": "string"}, "description": "Evidence IDs observed in input evidence list (e.g. ['E1', 'E3'])", }, "reasoning": { "type": "string", "description": "使用简洁简体中文(不超过 120 字)说明核验结论与依据,禁止出现 E1、E1-E5 等内部证据编号", }, } LOCATION_JUDGE_R1_SCHEMA: dict[str, Any] = { "type": "object", "properties": { "decision": { "type": "string", "enum": [ "located", "need_followup", "undisclosed", "multi_site", "planned", "cloud_only", "anonymous", "unresolved", ], }, **_BASE_JUDGE_PROPERTIES, "followup_queries": { "type": "array", "items": {"type": "string"}, "description": "Up to 2 short English search queries when decision='need_followup'", }, "fetch_urls": { "type": "array", "items": {"type": "string"}, "description": "Up to 2 promising evidence URLs from R1 requiring full-page fetch", }, }, "required": ["decision", "reasoning"], } LOCATION_JUDGE_FINAL_SCHEMA: dict[str, Any] = { "type": "object", "properties": { "decision": { "type": "string", "enum": [ "located", "undisclosed", "multi_site", "planned", "cloud_only", "anonymous", "unresolved", ], }, **_BASE_JUDGE_PROPERTIES, }, "required": ["decision", "reasoning"], } def english_country_name(value: Any) -> str: """Return the English country name via the shared registry for search and Nominatim.""" canonical = normalize_country_text(value) if not canonical: return "" for variant in get_country_search_variants(canonical): if variant != canonical and variant.isascii() and len(variant) > 2: return variant return canonical def get_evidence_ledger(workflow_state: dict[str, Any]) -> EvidenceLedger: ledger = workflow_state.get("evidence_ledger") if isinstance(ledger, EvidenceLedger): return ledger ledger = EvidenceLedger() workflow_state["evidence_ledger"] = ledger return ledger async def load_cross_source_compute_hints( db: Any, *, name: str | None, source: str | None, source_id: str, ) -> tuple[list[str], str | None, str | None, list[dict[str, Any]]]: """Gather sibling compute records from other sources (e.g. Epoch AI <-> TOP500).""" short_name = _short_system_name(name) norm_short = normalize_text(short_name) if db is None or not hasattr(db, "execute") or len(norm_short) < 4: return [], None, None, [] try: stmt = ( select(CollectedData) .where(compute_record_filter(CollectedData)) .where(CollectedData.is_current.is_(True)) .where(CollectedData.deleted_at.is_(None)) .where(CollectedData.name.ilike(f"%{short_name}%")) .limit(8) ) rows = (await db.execute(stmt)).scalars().all() except Exception: return [], None, None, [] extra_sources: list[str] = [] extra_source_url: str | None = None extra_builds_upon: str | None = None hints: list[dict[str, Any]] = [] for row in rows: row_source = getattr(row, "source", None) row_sid = getattr(row, "source_id", None) if not row_source or not row_sid: continue if row_sid == source_id or (source and row_source == source): continue row_short = normalize_text(_short_system_name(getattr(row, "name", None))) if norm_short not in row_short and row_short not in norm_short: continue meta = getattr(row, "extra_data", None) or {} if not isinstance(meta, dict): meta = {} row_sources = [str(u).strip() for u in (meta.get("sources") or []) if str(u or "").strip()] for u in row_sources: if u not in extra_sources: extra_sources.append(u) if not extra_source_url and (meta.get("source_url") or meta.get("detail_url")): cand_url = str(meta.get("source_url") or meta.get("detail_url")).strip() if cand_url and not is_tabular_dataset_url(cand_url): extra_source_url = cand_url if not extra_builds_upon and meta.get("builds_upon"): extra_builds_upon = str(meta["builds_upon"]).strip() hints.append( { "source": row_source, "source_id": row_sid, "name": getattr(row, "name", None), "country": get_record_field(row, "country"), "raw_country": meta.get("raw_country"), "location": meta.get("location"), "sources": row_sources[:3], } ) return extra_sources, extra_source_url, extra_builds_upon, hints async def _load_compute_record_by_source_id(db: Any, source_id: str) -> CollectedData | None: if not source_id or source_id == "unresolved" or db is None or not hasattr(db, "execute"): return None try: stmt = ( select(CollectedData) .where(compute_record_filter(CollectedData)) .where(CollectedData.is_current.is_(True)) .where(CollectedData.source_id == source_id) .order_by(CollectedData.id.desc()) .limit(1) ) return (await db.execute(stmt)).scalars().first() except Exception: return None async def tool_location_normalize_context( db: Any, *, question: str, targets: list[dict[str, Any]], earth_context: dict[str, Any], node_params: dict[str, Any], workflow_state: dict[str, Any], ) -> dict[str, Any]: """L0 tool: hydrate record + cross-source hints, normalize names/countries, short-circuit cached terminals.""" first = targets[0] if targets else {} props = first.get("properties") if isinstance(first.get("properties"), dict) else {} raw_sid = coerce_str( first.get("entity_id") or first.get("id") or earth_context.get("source_id") ) source_id = "" if raw_sid == "unresolved" else raw_sid entity_type = coerce_str( earth_context.get("entity_type") or first.get("entity_type") or "compute_center" ).lower() if entity_type not in {"bgp_collector", "compute_center"}: entity_type = "bgp_collector" if "collector" in entity_type else "compute_center" pre_query = workflow_state.get("preset_query") if isinstance(pre_query, LocationQuery): query = pre_query source_id = coerce_str((query.extra or {}).get("source_id")) or source_id elif entity_type == "bgp_collector": collector_id = coerce_str(earth_context.get("collector_id") or source_id or first.get("label") or question) legacy = get_bgp_collector_location_dict(collector_id) or {} query = build_bgp_collector_location_query( collector=collector_id, site=coerce_str(earth_context.get("site")) or legacy.get("matched_location_name") or None, city=coerce_str(earth_context.get("city")) or legacy.get("city") or None, country=coerce_str(earth_context.get("country")) or legacy.get("country") or None, operator=coerce_str(earth_context.get("operator")) or "RIPE NCC", ) source_id = collector_id else: record = await _load_compute_record_by_source_id(db, source_id) meta = (record.extra_data or {}) if record and isinstance(record.extra_data, dict) else {} clean_q = coerce_str(question) if clean_q.startswith("/locate"): clean_q = clean_q[len("/locate") :].strip() name = ( coerce_str(earth_context.get("name")) or coerce_str(first.get("label")) or (coerce_str(getattr(record, "name", None)) if record else "") or coerce_str(props.get("name")) or clean_q or source_id or "Unknown Facility" ) source = coerce_str(earth_context.get("source")) or (coerce_str(getattr(record, "source", None)) if record else "") operator = ( coerce_str(earth_context.get("operator")) or coerce_str(props.get("operator")) or coerce_str(meta.get("operator") or meta.get("organization") or meta.get("owner")) ) site = coerce_str(earth_context.get("site") or props.get("site") or meta.get("site")) organization = coerce_str(earth_context.get("organization") or meta.get("organization")) city = coerce_str( earth_context.get("city") or props.get("city") or (get_record_field(record, "city") if record else "") ) country = coerce_str( earth_context.get("country") or props.get("country") or (get_record_field(record, "country") if record else "") ) raw_sources = [ coerce_str(u) for u in ( earth_context.get("sources") or props.get("sources") or (meta.get("sources") if isinstance(meta.get("sources"), list) else []) ) if coerce_str(u) ] source_url = coerce_str( earth_context.get("source_url") or props.get("source_url") or meta.get("source_url") or meta.get("detail_url") ) builds_upon = coerce_str(earth_context.get("builds_upon") or meta.get("builds_upon")) source_raw_country = coerce_str(earth_context.get("source_raw_country") or meta.get("raw_country")) sib_sources, sib_url, sib_builds_upon, cross_source_hints = await load_cross_source_compute_hints( db, name=name, source=source or None, source_id=source_id ) for u in sib_sources: if u not in raw_sources: raw_sources.append(u) if (not source_url or is_tabular_dataset_url(source_url)) and sib_url: source_url = sib_url if not builds_upon and sib_builds_upon: builds_upon = sib_builds_upon query = build_compute_center_location_query( name=name, source=source or None, source_id=source_id or None, operator=operator or None, site=site or None, city=city or None, country=country or None, organization=organization or None, sources=raw_sources, source_url=source_url or None, builds_upon=builds_upon or None, source_raw_country=source_raw_country or None, cross_source_hints=cross_source_hints, ) extra = dict(query.extra or {}) extra_source = coerce_str(extra.get("source")) extra_sid = coerce_str(extra.get("source_id")) or source_id force = bool(earth_context.get("force", False)) short_circuit = bool(node_params.get("short_circuit_terminal_statuses", True)) if entity_type == "compute_center" and not COMPUTE_CENTER_LOCATION_CACHE and db is not None: try: await refresh_compute_center_location_cache(db) except Exception: pass terminal_status: str | None = None terminal_note = "" if entity_type == "compute_center" and not force and short_circuit and extra_source and extra_sid: cached = get_compute_center_location_dict(extra_source, extra_sid) cached_status = coerce_str(cached.get("verification_status")).lower() if cached_status in TERMINAL_UNLOCATABLE_STATUSES: terminal_status = cached_status terminal_note = coerce_str(cached.get("source_note")) or f"Marked as {cached_status}" raw_urls = [ coerce_str(u) for u in [*([extra.get("source_url")] if extra.get("source_url") else []), *(extra.get("sources") or [])] if coerce_str(u).startswith(("http://", "https://")) and not is_tabular_dataset_url(u) ] dedup_urls: list[str] = [] seen_norm: set[str] = set() for u in raw_urls: nu = normalize_evidence_url(u) if nu and nu not in seen_norm: seen_norm.add(nu) dedup_urls.append(u) ctx_payload = { "entity_type": entity_type, "source": extra_source or None, "source_id": extra_sid or None, "record_id": earth_context.get("record_id"), "name": query.name, "name_short": query.aliases[0] if query.aliases else query.name, "operator": extra.get("operator") or None, "site": extra.get("site") or None, "city": query.city, "country": query.country, "country_en": english_country_name(query.country), "raw_country": extra.get("source_raw_country") or None, "primary_source_urls": dedup_urls[:5], "cross_source_hints": list(extra.get("cross_source_hints") or [])[:4], } workflow_state["entity_type"] = entity_type workflow_state["location_query"] = query workflow_state["location_ctx"] = ctx_payload workflow_state.setdefault("attempted_queries", []) if terminal_status: workflow_state["terminal_status"] = terminal_status workflow_state["failure_reason"] = terminal_note workflow_state["resolution_stage"] = f"l0_short_circuit:{terminal_status}" return { "is_terminal": bool(terminal_status), "terminal_status": terminal_status, "source_note": terminal_note, "context": ctx_payload, } async def tool_location_knowledge_lookup( db: Any, *, question: str, targets: list[dict[str, Any]], earth_context: dict[str, Any], node_params: dict[str, Any], workflow_state: dict[str, Any], ) -> dict[str, Any]: """L1 deterministic lookup: builds_upon, ROR, parallel Wikidata(P17) & PeeringDB; Nominatim only when city exists.""" query = workflow_state.get("location_query") if not isinstance(query, LocationQuery): norm = await tool_location_normalize_context( db, question=question, targets=targets, earth_context=earth_context, node_params={}, workflow_state=workflow_state, ) if norm.get("is_terminal"): return {"high_confidence_hit": False, "candidates_count": 0, "candidates": [], "resolver_log": []} query = workflow_state["location_query"] entity_type = str(workflow_state.get("entity_type") or "compute_center") attempted: list[str] = list(workflow_state.get("attempted_queries") or []) resolver_log: list[str] = [] candidates: list[LocationCandidate] = [] extra = dict(query.extra or {}) if entity_type == "bgp_collector": bgp_cands, bgp_queries = await asyncio.to_thread( collect_bgp_collector_location_candidates, collector=coerce_str(extra.get("collector") or query.name), site=coerce_str(extra.get("site")) or None, city=query.city, country=query.country, operator=coerce_str(extra.get("operator")) or "RIPE NCC", ) attempted.extend(bgp_queries) candidates = list(bgp_cands) resolver_log.append("l1_knowledge:bgp_collector") else: raw_sources = list(extra.get("sources") or []) local_cands, local_queries = await asyncio.to_thread( collect_location_candidates, name=query.name, source=coerce_str(extra.get("source")) or None, source_id=coerce_str(extra.get("source_id")) or None, operator=coerce_str(extra.get("operator")) or None, site=coerce_str(extra.get("site")) or None, organization=coerce_str(extra.get("organization")) or None, city=query.city, country=query.country, sources=raw_sources, source_url=coerce_str(extra.get("source_url")) or None, builds_upon=coerce_str(extra.get("builds_upon")) or None, source_raw_country=coerce_str(extra.get("source_raw_country")) or None, include_builds_upon=bool(node_params.get("builds_upon_enabled", True)), include_ror=bool(node_params.get("ror_enabled", True)), include_nominatim=False, ) attempted.extend(local_queries) if extra.get("builds_upon"): resolver_log.append("l1_knowledge:builds_upon_inherit") if node_params.get("ror_enabled", True): resolver_log.append("l1_knowledge:ror_lookup") candidates = list(local_cands) if not candidates: tasks = [] if node_params.get("wikidata_enabled", True): tasks.append(lookup_wikidata_facility(query)) resolver_log.append("l1_knowledge:wikidata_lookup") if node_params.get("peeringdb_enabled", True): tasks.append(lookup_peeringdb_facility(query)) resolver_log.append("l1_knowledge:peeringdb_fac_lookup") if tasks: for out in await asyncio.gather(*tasks, return_exceptions=True): if isinstance(out, Exception): continue attempted.extend(out.attempted_queries) candidates.extend(out.candidates) # Only run fast city Nominatim lookup if metadata already supplies an explicit city. if not candidates and coerce_str(query.city): nom_cands, nom_queries = await asyncio.to_thread( collect_location_candidates, name=query.name, source=coerce_str(extra.get("source")) or None, source_id=coerce_str(extra.get("source_id")) or None, operator=coerce_str(extra.get("operator")) or None, site=coerce_str(extra.get("site")) or None, organization=coerce_str(extra.get("organization")) or None, city=query.city, country=query.country, sources=raw_sources, source_url=coerce_str(extra.get("source_url")) or None, builds_upon=coerce_str(extra.get("builds_upon")) or None, source_raw_country=coerce_str(extra.get("source_raw_country")) or None, include_builds_upon=False, include_ror=False, include_nominatim=True, ) attempted.extend(nom_queries) candidates = list(nom_cands) resolver_log.append("l1_knowledge:explicit_city_nominatim") workflow_state["attempted_queries"] = list(dict.fromkeys(attempted)) workflow_state["l1_candidates"] = candidates if candidates: workflow_state["resolution_stage"] = "l1_knowledge" return { "high_confidence_hit": bool(candidates), "candidates_count": len(candidates), "candidates": [c.to_dict() for c in candidates[:5]], "resolver_log": resolver_log, } async def _fetch_one_url(url: str, ledger: EvidenceLedger, attempted: list[str]) -> str | None: attempted.append(f"fetch_url:{url}") try: fetched = await safe_web_fetch(url) isolated = isolate_untrusted_external_text( fetched.final_url or fetched.url, fetched.title, fetched.text, max_chars=1800, ) excerpt = coerce_str(isolated.get("excerpt") or isolated.get("title")) if excerpt: ledger.record_call() return ledger.add( url=str(fetched.final_url or fetched.url or url), title=str(fetched.title or ""), snippet=excerpt, tool="fetch_source_url", ) except Exception: return None return None async def _search_one_query(q: str, client: Any, ledger: EvidenceLedger, attempted: list[str]) -> list[str]: attempted.append(f"web_search:{q}") added: list[str] = [] try: results = await client.search(q, max_results=5) if results: ledger.record_call() for item in results: eid = ledger.add( url=coerce_str(getattr(item, "url", "")), title=coerce_str(getattr(item, "title", "")), snippet=coerce_str(getattr(item, "snippet", "") or getattr(item, "content", ""))[:500], tool="web_search", query=q, ) if eid: added.append(eid) except Exception: return [] return added async def _resolve_web_search_client(db: Any, workflow_state: dict[str, Any]) -> tuple[Any | None, str]: if "web_search_client" in workflow_state: client = workflow_state["web_search_client"] return client, "" if client is not None else "WebSearch unavailable" if db is None or not hasattr(db, "execute"): return None, "WebSearch database config unavailable" try: from app.api.v1.settings import get_runtime_web_search_config, get_web_search_client config = await get_runtime_web_search_config(db) provider_cfg = config.active_provider_config provider_name = normalize_web_search_provider(provider_cfg.provider) has_key = provider_name == "searxng" or bool((provider_cfg.api_key or "").strip()) if not config.enabled: return None, "WebSearch 未开启,无法检索外部公开依据。" if not has_key: return None, f"WebSearch Provider {config.default_provider} 未配置 API Key。" client = await get_web_search_client(db) return client, "" except Exception as exc: return None, f"WebSearch 初始化失败:{exc}" def _build_r1_search_queries(ctx: dict[str, Any], entity_type: str) -> list[str]: name_short = coerce_str(ctx.get("name_short") or ctx.get("name")) operator = coerce_str(ctx.get("operator")) site = coerce_str(ctx.get("site")) country_en = coerce_str(ctx.get("country_en")) queries: list[str] = [] if entity_type == "bgp_collector": q1 = " ".join(p for p in [f'"{name_short}"', "route collector IXP location city", country_en] if p) q2 = " ".join(p for p in [name_short, operator, site, "city facility"] if p) queries = [q1, q2] else: op_token = operator if operator and normalize_text(operator) != normalize_text(name_short) else "" q1 = " ".join(p for p in [f'"{name_short}"', op_token, "data center OR supercomputer location city"] if p) q2 = " ".join( p for p in [ f'"{name_short}"', site or op_token or country_en, "facility campus", ] if p ) queries = [q1, q2] dedup: list[str] = [] for q in queries: cleaned = " ".join(q.split()) if cleaned and cleaned not in dedup: dedup.append(cleaned) return dedup[:2] async def tool_location_web_research( db: Any, *, node_params: dict[str, Any], workflow_state: dict[str, Any], allow_external_tools: bool, ) -> dict[str, Any]: """L2 tool: execute parallel web research (Round 1 default queries + primary URLs, Round 2 targeted followups).""" ledger = get_evidence_ledger(workflow_state) ctx = workflow_state.get("location_ctx") or {} entity_type = str(workflow_state.get("entity_type") or "compute_center") attempted: list[str] = list(workflow_state.get("attempted_queries") or []) round_num = int(node_params.get("round") or 1) max_queries = max(1, min(int(node_params.get("max_search_queries") or 2), 3)) max_fetches = max(0, min(int(node_params.get("max_fetch_urls") or 2), 4)) if not allow_external_tools: return { "round": round_num, "skipped": "external_tools_disabled", "evidence_count": len(ledger.items), "new_ids": [], "evidence": ledger.to_evidence_dict(), } search_client, cap_reason = await _resolve_web_search_client(db, workflow_state) if cap_reason: workflow_state.setdefault("capability_reason", cap_reason) queries: list[str] = [] urls_to_fetch: list[str] = [] if round_num == 1: urls_to_fetch = [ coerce_str(u) for u in (ctx.get("primary_source_urls") or []) if coerce_str(u) and not is_tabular_dataset_url(u) ][:max_fetches] if search_client is not None: queries = _build_r1_search_queries(ctx, entity_type)[:max_queries] else: latest = workflow_state.get("latest_llm_data") or {} if search_client is not None: queries = [ coerce_str(q) for q in (latest.get("followup_queries") or []) if coerce_str(q) ][:max_queries] allowed_urls = { normalize_evidence_url(u): u for u in [*(ctx.get("primary_source_urls") or []), *(e["url"] for e in ledger.items)] if u } for raw_u in latest.get("fetch_urls") or []: nu = normalize_evidence_url(raw_u) if nu and nu in allowed_urls and not is_tabular_dataset_url(raw_u): urls_to_fetch.append(allowed_urls[nu]) urls_to_fetch = urls_to_fetch[:max_fetches] tasks = [ *[_fetch_one_url(u, ledger, attempted) for u in urls_to_fetch], *[ _search_one_query(q, search_client, ledger, attempted) for q in queries if search_client is not None ], ] new_ids: list[str] = [] if tasks: for res in await asyncio.gather(*tasks, return_exceptions=True): if isinstance(res, Exception) or not res: continue if isinstance(res, list): new_ids.extend(res) elif isinstance(res, str): new_ids.append(res) workflow_state["attempted_queries"] = list(dict.fromkeys(attempted)) return { "round": round_num, "evidence_count": len(ledger.items), "new_ids": new_ids, "capability_reason": cap_reason, "evidence": ledger.to_evidence_dict(), } async def _geocode_verify_single( place_q: str, expected_country: str | None, ) -> tuple[dict[str, Any], dict[str, Any] | None]: if not place_q: return {"found": False, "reason": "place_query is required"}, None try: geo_res = await asyncio.to_thread(_agent_geocoder, place_q) except Exception as exc: logger.warning_event( "Location workflow geocode_verify failed", event="location_workflow.geocode_verify.failed", context={"place_query": place_q, "error": str(exc)}, ) return {"found": False, "reason": f"geocoder request failed: {exc}"}, None if not isinstance(geo_res, dict): return {"found": False, "reason": "No geocoder match"}, None lat = parse_float(geo_res.get("lat") if geo_res.get("lat") is not None else geo_res.get("latitude")) lon = parse_float(geo_res.get("lon") if geo_res.get("lon") is not None else geo_res.get("longitude")) if ( lat in (None, 0.0) or lon in (None, 0.0) or not (-90.0 <= lat <= 90.0) or not (-180.0 <= lon <= 180.0) ): return {"found": False, "reason": "Invalid geocoder coordinates"}, None addr = geo_res.get("address") if isinstance(geo_res.get("address"), dict) else {} city = coerce_str( addr.get("city") or addr.get("town") or addr.get("village") or addr.get("municipality") or addr.get("suburb") or addr.get("hamlet") or geo_res.get("city") ) osm_class = str(geo_res.get("class") or "").lower() osm_type = str(geo_res.get("type") or "").lower() is_site_like = osm_class in _DEFAULT_SITE_CATEGORIES or osm_type in _DEFAULT_SITE_CATEGORIES explicit_precision = coerce_str(geo_res.get("precision")).lower() has_explicit_renderable = explicit_precision in {"precise", "site", "city"} if not (city or is_site_like or has_explicit_renderable): return { "found": False, "reason": "Geocoder result is only country or region/state level; provide a city, town, or facility address.", }, None if has_explicit_renderable: geo_precision = explicit_precision elif addr.get("house_number") or addr.get("road"): geo_precision = "precise" elif is_site_like: geo_precision = "site" else: geo_precision = "city" res_country = resolve_geocoder_country(addr, geo_res) norm_expected = normalize_country_text(expected_country) if norm_expected and res_country and normalize_text(res_country) != normalize_text(norm_expected): return { "found": False, "reason": f"Country mismatch: got {res_country}, expected {norm_expected}", }, None entry = { "found": True, "latitude": float(lat), "longitude": float(lon), "display_name": coerce_str(geo_res.get("display_name")) or place_q, "city": city, "region": coerce_str(addr.get("state") or addr.get("region") or geo_res.get("region")), "country": res_country or norm_expected or coerce_str(expected_country), "geo_precision": geo_precision, } return entry, entry async def tool_location_geocode_verify( *, workflow_state: dict[str, Any], ) -> dict[str, Any]: """L3 deterministic geocoder cascade: street address -> facility -> city+region -> city.""" llm_data = workflow_state.get("latest_llm_data") or {} ctx = workflow_state.get("location_ctx") or {} decision = coerce_str(llm_data.get("decision")).lower() if decision != "located": result = {"found": False, "skipped": True, "reason": f"decision={decision or 'none'}"} workflow_state["geocode_result"] = result return result address = coerce_str(llm_data.get("address")) facility_name = coerce_str(llm_data.get("facility_name")) city = coerce_str(llm_data.get("city")) region = coerce_str(llm_data.get("region")) country_raw = coerce_str(llm_data.get("country")) or coerce_str(ctx.get("country")) country_en = english_country_name(country_raw) or country_raw queries: list[str] = [] candidates_parts = [ [address, city, country_en] if address else [], [facility_name, city, country_en] if facility_name else [], [city, region, country_en] if (city and region) else [], [city, country_en] if city else [], [facility_name, country_en] if (facility_name and not city) else [], ] for parts in candidates_parts: q = ", ".join(p for p in parts if p) if q and q not in queries: queries.append(q) attempted = list(workflow_state.get("attempted_queries") or []) last_reason = "No geocoder query could be formed from LLM city/facility fields" for q in queries: attempted.append(f"geocode_verify:{q}") res, entry = await _geocode_verify_single(q, country_raw) if entry is not None: workflow_state["attempted_queries"] = list(dict.fromkeys(attempted)) workflow_state["geocode_result"] = entry return entry last_reason = coerce_str(res.get("reason")) or last_reason workflow_state["attempted_queries"] = list(dict.fromkeys(attempted)) fail = {"found": False, "reason": last_reason} workflow_state["geocode_result"] = fail return fail def evaluate_location_geo_guardrail( guardrails: dict[str, Any], workflow_state: dict[str, Any], ) -> dict[str, Any]: """L3 hard anti-hallucination guardrails: geocoder >= city, real evidence_ids, confidence & country override.""" if workflow_state.get("l1_candidates"): return {"passed": True, "errors": [], "warnings": [], "stage": "l1_knowledge"} ledger = get_evidence_ledger(workflow_state) llm_data = workflow_state.get("latest_llm_data") or {} ctx = workflow_state.get("location_ctx") or {} query = workflow_state.get("location_query") entity_type = str(workflow_state.get("entity_type") or "compute_center") min_confidence = float(guardrails.get("min_confidence") or DEFAULT_MIN_CONFIDENCE) enforce_country_match = bool(guardrails.get("enforce_country_match", True)) require_tool_urls = bool(guardrails.get("require_tool_cited_urls", True)) downgrade_to_city = bool(guardrails.get("downgrade_geocoded_site_to_city", True)) decision = coerce_str(llm_data.get("decision")).lower() or "unresolved" reasoning = sanitize_user_facing_reasoning(coerce_str(llm_data.get("reasoning"))) extra = (query.extra or {}) if isinstance(query, LocationQuery) else {} def _fail(msg: str, *, terminal: str | None = None) -> dict[str, Any]: cleaned_msg = sanitize_user_facing_reasoning(msg) or msg workflow_state["guardrail_passed"] = False workflow_state["failure_reason"] = cleaned_msg workflow_state["terminal_status"] = terminal workflow_state["resolution_stage"] = "l3_geo_guardrail" return {"passed": False, "errors": [cleaned_msg], "warnings": [cleaned_msg], "decision": decision} if decision in TERMINAL_UNLOCATABLE_STATUSES: is_explicit_anonymous = bool(extra.get("anonymous")) and decision == "anonymous" if ledger.evidence_calls == 0 and not is_explicit_anonymous: return _fail("Cannot confirm terminal unlocatable status without tool evidence.") cleaned_terminal_reason = sanitize_user_facing_reasoning(reasoning) or f"Facility confirmed as {decision}." workflow_state["guardrail_passed"] = True workflow_state["terminal_status"] = decision workflow_state["failure_reason"] = cleaned_terminal_reason workflow_state["resolution_stage"] = f"terminal_{decision}" return { "passed": True, "errors": [], "warnings": [], "decision": decision, "terminal_status": decision, "reasoning": workflow_state["failure_reason"], } if decision != "located": reason = reasoning or coerce_str(workflow_state.get("capability_reason")) or "公开证据不足以确认具体城市" return _fail(reason) geo = workflow_state.get("geocode_result") or {} if not geo.get("found"): geo_err = coerce_str(geo.get("reason")) or "未命中城市级地理编码坐标" return _fail(f"地理编码未通过 ({geo_err})") refs = [*(llm_data.get("evidence_ids") or []), *(llm_data.get("citations") or [])] verified_ids, verified_urls = ledger.resolve_refs(refs) if require_tool_urls and not verified_urls: return _fail("No verified citation URLs observed in tool outputs") raw_conf = parse_float(llm_data.get("confidence")) confidence = min(max(raw_conf if raw_conf is not None else 0.0, 0.0), 1.0) if confidence < min_confidence: return _fail(f"Agent confidence {confidence:.2f} is below minimum {min_confidence:.2f}") expected_country = normalize_country_text(ctx.get("country")) resolved_country = normalize_country_text(llm_data.get("country") or geo.get("country")) override_meta: dict[str, str] | None = None if ( enforce_country_match and expected_country and resolved_country and normalize_text(resolved_country) != normalize_text(expected_country) ): override_reason = sanitize_user_facing_reasoning(coerce_str(llm_data.get("country_override_reason"))) hint_countries = { normalize_text(normalize_country_text(h.get("country") or h.get("raw_country"))) for h in (ctx.get("cross_source_hints") or []) if isinstance(h, dict) } has_cross_hint = normalize_text(resolved_country) in hint_countries if override_reason and (len(verified_urls) >= 1 or has_cross_hint): override_meta = { "source_country": expected_country, "resolved_country": resolved_country, "reason": override_reason[:300], } else: return _fail(f"Country mismatch ({resolved_country} != {expected_country})") raw_precision = coerce_str(llm_data.get("precision")).lower() precision = raw_precision if raw_precision in {"precise", "site", "city"} else "city" geo_precision = coerce_str(geo.get("geo_precision")).lower() if downgrade_to_city and geo_precision == "city" and precision in {"precise", "site"}: precision = "city" label = ( coerce_str(llm_data.get("facility_name")) or coerce_str(geo.get("display_name")) or coerce_str(ctx.get("name")) ) source_note = sanitize_user_facing_reasoning(reasoning) or f"Verified via location workflow ({len(verified_urls)} citations)" if override_meta: source_note = sanitize_user_facing_reasoning( f"[跨国部署核验提醒:源登记国 {override_meta['source_country']} → " f"实证部署国 {override_meta['resolved_country']};依据:{override_meta['reason']}] " f"{source_note}" ) raw_payload: dict[str, Any] = { "evidence_ids": verified_ids, "citations": verified_urls, "geocode_precision": geo_precision, } if override_meta: raw_payload["country_mismatch_override"] = override_meta cand = LocationCandidate( latitude=float(geo["latitude"]), longitude=float(geo["longitude"]), display_name=label, precision=precision, confidence=confidence, query=f"location_workflow:{entity_type}:{ctx.get('name') or ctx.get('source_id') or 'unknown'}", source="llm_location_factcheck", source_note=source_note, matched_fields=("name", "location_workflow"), needs_confirmation=True, city=coerce_str(llm_data.get("city")) or geo.get("city") or ctx.get("city") or None, region=coerce_str(llm_data.get("region")) or geo.get("region") or None, country=resolved_country or expected_country or coerce_str(ctx.get("country")) or None, matched_location_name=label, raw_payload=raw_payload, ) workflow_state["guardrail_passed"] = True workflow_state["validated_candidates"] = [cand] workflow_state["resolution_stage"] = "l3_geo_guardrail:located" return { "passed": True, "errors": [], "warnings": [], "decision": "located", "candidate": cand.to_dict(), } async def _persist_terminal_location_status( db: Any, *, ctx: dict[str, Any], terminal_status: str, reasoning: str, ) -> None: if db is None or not hasattr(db, "execute"): return source = coerce_str(ctx.get("source")) source_id = coerce_str(ctx.get("source_id")) if not source or not source_id: return try: sanitized_note = sanitize_user_facing_reasoning(reasoning)[:500] existing = await db.scalar( select(ComputeCenterLocationRecord) .where(ComputeCenterLocationRecord.source == source) .where(ComputeCenterLocationRecord.source_id == source_id) ) if existing is None: existing = ComputeCenterLocationRecord( source=source, source_id=source_id, name=coerce_str(ctx.get("name")) or source_id, operator=coerce_str(ctx.get("operator")) or None, site=coerce_str(ctx.get("site")) or None, city=coerce_str(ctx.get("city")) or None, country=coerce_str(ctx.get("country")) or None, latitude=None, longitude=None, precision="unknown", confidence=0.0, location_source=f"agent_terminal_{terminal_status}", source_note=sanitized_note or f"Marked {terminal_status} by location workflow", needs_confirmation=False, verification_status=terminal_status, verified_at=datetime.now(UTC), ) db.add(existing) else: existing.precision = "unknown" existing.latitude = None existing.longitude = None existing.verification_status = terminal_status existing.location_source = f"agent_terminal_{terminal_status}" existing.source_note = sanitized_note or existing.source_note existing.verified_at = datetime.now(UTC) await db.commit() await refresh_compute_center_location_cache(db) try: invalidate_earth_layer_cache_for_source("compute_center_locations") cache.delete_pattern("data_ledger:*") except Exception: pass except Exception as exc: logger.warning_event( "Failed to persist terminal unlocatable status", event="location_workflow.persist_terminal_failed", context={"source_id": source_id, "status": terminal_status, "error": str(exc)}, ) async def tool_location_persist_outcome( db: Any, *, node_params: dict[str, Any], workflow_state: dict[str, Any], ) -> dict[str, Any]: """L4 output tool: emit standardized `structured_output`, persist verified terminal status, render markdown/scene.""" ctx = workflow_state.get("location_ctx") or {} entity_type = str(workflow_state.get("entity_type") or "compute_center") attempted = list(workflow_state.get("attempted_queries") or []) l1_candidates: list[LocationCandidate] = list(workflow_state.get("l1_candidates") or []) validated_candidates: list[LocationCandidate] = list(workflow_state.get("validated_candidates") or []) candidates = validated_candidates or l1_candidates terminal_status = workflow_state.get("terminal_status") failure_reason = sanitize_user_facing_reasoning(coerce_str(workflow_state.get("failure_reason"))) target_name = coerce_str(ctx.get("name")) or coerce_str(ctx.get("source_id")) or "Unknown Facility" if terminal_status and not str(workflow_state.get("resolution_stage") or "").startswith("l0_short_circuit"): if bool(node_params.get("persist_terminal_statuses", True)) and entity_type == "compute_center": await _persist_terminal_location_status( db, ctx=ctx, terminal_status=terminal_status, reasoning=failure_reason, ) scene_spec: dict[str, Any] | None = None if candidates: best = candidates[0] raw_p = best.raw_payload if isinstance(best.raw_payload, dict) else {} cites = [str(u) for u in (raw_p.get("citations") or []) if u] cleaned_note = sanitize_user_facing_reasoning(best.source_note) lines = [ f"### {best.display_name} 物理位置核验结果", "", f"- **目标实体**:{target_name}", f"- **国家/地区**:{best.country or '-'}", f"- **城市/区域**:{best.city or '-'}{f' ({best.region})' if best.region else ''}", f"- **核验坐标**:`{best.latitude:.5f}, {best.longitude:.5f}`(精度 `{best.precision}`,置信度 `{float(best.confidence or 0):.2f}`)", f"- **解析来源**:`{best.source}`", ] if cleaned_note: lines.append(f"- **依据说明**:{cleaned_note}") if cites: lines.extend(["", "**核验引用来源**", *[f"- {u}" for u in cites[:5]]]) answer_md = "\n".join(lines) sid = coerce_str(ctx.get("source_id")) scene_spec = { "fly_to": {"lat": float(best.latitude), "lon": float(best.longitude), "zoom": 1.45}, **({"highlight_entities": [sid]} if sid else {}), } workflow_state["outcome_tag"] = "located" elif terminal_status: answer_md = ( f"### {target_name} 位置核验终态:`{terminal_status}`\n\n" f"{failure_reason or '依据公开工具证据,该设施属于不可单点定位的终态类型。'}" ) workflow_state["outcome_tag"] = terminal_status else: diag = sanitize_user_facing_reasoning(failure_reason or coerce_str(workflow_state.get("capability_reason"))) or "暂无足够公开证据" answer_md = f"### 未能确认「{target_name}」的物理位置\n\n- **诊断原因**:{diag}" workflow_state["outcome_tag"] = "unresolved" structured_output = { "success": bool(candidates), "entity_type": entity_type, "candidates": [c.to_dict() for c in candidates], "best_candidate": candidates[0].to_dict() if candidates else None, "candidate_objects": candidates, "terminal_status": terminal_status, "failure_reason": None if candidates else (failure_reason or "未能确认可信城市级坐标"), "attempted_queries": attempted, "resolution_stage": str(workflow_state.get("resolution_stage") or ""), "context": ctx, } workflow_state["structured_output"] = structured_output workflow_state["final_answer_markdown"] = answer_md workflow_state["final_scene_spec"] = scene_spec return { "outcome": workflow_state["outcome_tag"], "success": bool(candidates), "candidates_count": len(candidates), "terminal_status": terminal_status, "failure_reason": structured_output["failure_reason"], } async def _resolve_active_workflow_revision(db: Any) -> int: if db is None or not hasattr(db, "execute"): return 1 try: res = await db.execute( select(AIWorkflow.active_revision).where(AIWorkflow.workflow_id == "location.resolve_unknown") ) val = res.scalar_one_or_none() if isinstance(val, int) and val >= 1: return val except Exception: pass return 1 async def record_location_workflow_run( db: Any, *, question: str, status_value: str, tool_trace: list[str], steps_used: int, started_at: datetime | None = None, model_used: str = "", provider_used: str = "", resolution_stage: str = "", source_id: str = "", error_message: str = "", node_traces: list[dict[str, Any]] | None = None, trigger_evolution: bool = True, ) -> str | None: """Persist one `WorkflowRun` telemetry record and optionally schedule post-run evolution.""" if db is None or not hasattr(db, "add"): return None run_id = f"run_{uuid4().hex[:16]}" started = started_at or datetime.now(UTC) completed = datetime.now(UTC) latency_ms = max(0, int((completed - started).total_seconds() * 1000)) workflow_revision = await _resolve_active_workflow_revision(db) deduped_trace: list[str] = [] for item in tool_trace: token = str(item or "").strip() if token and token not in deduped_trace: deduped_trace.append(token) try: db.add( WorkflowRun( id=run_id, workflow_id="location.resolve_unknown", status=status_value, access_tier="admin", actor_key="admin:collect-location", question=question[:500], input_params={"source_id": source_id} if source_id else {}, tool_trace=deduped_trace, budget_used={ "steps": steps_used, "workflow_revision": workflow_revision, "model_used": model_used, "provider_used": provider_used, "latency_ms": latency_ms, "resolution_stage": resolution_stage, "source_id": source_id, **({"node_traces": node_traces} if node_traces else {}), }, error_message=error_message[:500], started_at=started, completed_at=completed, ) ) await db.commit() except Exception: try: await db.rollback() except Exception: pass return None if trigger_evolution: try: from app.services.ai.workflow_evolver import schedule_post_run_evolution schedule_post_run_evolution("location.resolve_unknown", run_id) except Exception: pass return run_id async def _load_location_workflow_def( db: Any, *, use_draft: bool = False, override_graph: dict[str, Any] | None = None, ) -> dict[str, Any]: from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS, get_workflow_detail wf_dict: dict[str, Any] | None = None if db is not None and hasattr(db, "execute"): try: detail = await get_workflow_detail(db, "location.resolve_unknown") wf_dict = dict(detail["workflow"]) except Exception: wf_dict = None if hasattr(db, "rollback"): try: await db.rollback() except Exception: pass if wf_dict is None: builtin = next(w for w in BUILTIN_WORKFLOWS if w["workflow_id"] == "location.resolve_unknown") wf_dict = { "workflow_id": builtin["workflow_id"], "name": builtin["name"], "active_revision": 1, "published_graph": copy.deepcopy(builtin["graph"]), "draft_graph": None, "bindings": copy.deepcopy(builtin.get("bindings") or {}), } if isinstance(override_graph, dict): wf_dict["published_graph"] = copy.deepcopy(override_graph) wf_dict["draft_graph"] = copy.deepcopy(override_graph) elif use_draft and not isinstance(wf_dict.get("draft_graph"), dict): wf_dict["draft_graph"] = copy.deepcopy(wf_dict.get("published_graph") or {}) return wf_dict async def run_location_workflow( *, db: Any, query: LocationQuery | None = None, entity_type: str = "compute_center", earth_context: dict[str, Any] | None = None, targets: list[dict[str, Any]] | None = None, provider_client: Any = None, web_search_client: Any = None, use_draft: bool = False, override_graph: dict[str, Any] | None = None, record_run: bool = True, trigger_evolution: bool = True, ) -> dict[str, Any]: """Run `location.resolve_unknown` through the generic DAG executor and record one unified WorkflowRun.""" from app.services.ai.dag_executor import run_workflow_dag_stream started_at = datetime.now(UTC) wf = await _load_location_workflow_def(db, use_draft=use_draft, override_graph=override_graph) ai_client = provider_client if ai_client is None and db is not None and hasattr(db, "execute"): try: from app.api.v1.settings import get_ai_provider_client ai_client = await get_ai_provider_client(db) except Exception: ai_client = None runtime_ctx = dict(earth_context or {}) runtime_ctx["entity_type"] = entity_type runtime_ctx["_location_runtime"] = { **({"preset_query": query} if isinstance(query, LocationQuery) else {}), **({"web_search_client": web_search_client} if web_search_client is not None else {}), } question = coerce_str((query.name if isinstance(query, LocationQuery) else None) or runtime_ctx.get("name") or runtime_ctx.get("source_id") or "定位设施") done_data: dict[str, Any] = {} async for ev in run_workflow_dag_stream( db=db, workflow=wf, question=question, use_draft=use_draft, targets=targets, earth_context=runtime_ctx, ai_client=ai_client, allow_external_tools=True, ): if ev.get("event") == "done" and isinstance(ev.get("data"), dict): done_data = ev["data"] structured = done_data.get("structured_output") if isinstance(done_data.get("structured_output"), dict) else {} cand_objs = [c for c in (structured.get("candidate_objects") or []) if isinstance(c, LocationCandidate)] terminal_status = structured.get("terminal_status") verif_warnings = (done_data.get("verification") or {}).get("warnings") or [] failure_reason = structured.get("failure_reason") or ( None if cand_objs else ("; ".join(str(w) for w in verif_warnings if w) or None) ) attempted_queries = list(structured.get("attempted_queries") or []) node_traces = list(done_data.get("node_traces") or []) llm_steps = sum(1 for t in node_traces if t.get("node_type") in {"llm_agent", "tool_agent"} and t.get("status") == "completed") run_status = "completed" if (cand_objs or terminal_status) else "failed" extra = (query.extra or {}) if isinstance(query, LocationQuery) else {} source_id = coerce_str(extra.get("source_id") or runtime_ctx.get("source_id")) workflow_run_id: str | None = None if record_run: workflow_run_id = await record_location_workflow_run( db, question=question, status_value=run_status, tool_trace=list(done_data.get("nodes") or []), steps_used=llm_steps, started_at=started_at, model_used=coerce_str(done_data.get("model")), provider_used=coerce_str(done_data.get("provider")), resolution_stage=coerce_str(structured.get("resolution_stage")), source_id=source_id, error_message="" if run_status == "completed" else coerce_str(failure_reason), node_traces=node_traces, trigger_evolution=trigger_evolution, ) if workflow_run_id and terminal_status and source_id and entity_type == "compute_center" and hasattr(db, "execute"): try: loc_row = await db.scalar( select(ComputeCenterLocationRecord) .where(ComputeCenterLocationRecord.source_id == source_id) .limit(1) ) if loc_row is not None and (loc_row.verification_status or "").lower() in TERMINAL_UNLOCATABLE_STATUSES: payload_copy = dict(loc_row.raw_payload or {}) payload_copy["workflow_run_id"] = workflow_run_id loc_row.raw_payload = payload_copy await db.commit() await refresh_compute_center_location_cache(db) except Exception: pass return { **structured, "candidates": cand_objs, "candidates_dicts": [c.to_dict() for c in cand_objs], "workflow_run_id": workflow_run_id, "terminal_status": terminal_status, "failure_reason": failure_reason, "attempted_queries": attempted_queries, "answer_markdown": coerce_str(done_data.get("answer_markdown")), "tool_trace": list(done_data.get("nodes") or []), "node_traces": node_traces, }