Files
planet/backend/app/services/location/agent_resolver.py
T
linkong b3d2d9e9f1
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.81.0
2026-11-30 19:39:29 +08:00

652 lines
28 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Controlled multi-step Tool-Calling agent & L1 resolvers for unknown facility locations."""
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
import json
from typing import Any
from uuid import uuid4
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.compute_center_location import ComputeCenterLocationRecord
from app.models.situational_assessment import WorkflowRun
from app.schemas.ai import SituationalAnalysisRequest
from app.services.ai.tool_registry import isolate_untrusted_external_text, safe_web_fetch
from app.services.ai.workflow_registry import resolve_runtime_workflow_node
from app.services.location.llm_fallback import (
DEFAULT_MIN_CONFIDENCE,
LocationLLMFallbackResult,
collect_llm_location_fallback_candidate,
)
from app.services.location.models import LocationCandidate, LocationQuery
from app.services.location.resolvers.nominatim import build_default_nominatim_geocoder
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_agent")
TERMINAL_UNLOCATABLE_STATUSES: frozenset[str] = frozenset({"undisclosed", "multi_site", "anonymous"})
_agent_geocoder = build_default_nominatim_geocoder()
LOCATION_AGENT_TOOLS: list[dict[str, Any]] = [
{
"name": "fetch_source_url",
"description": "Fetch and read a primary source webpage (especially Epoch Source 1..5 or TOP500 detail URL) cleanly with prompt-injection isolation.",
"parameters": {
"type": "object",
"properties": {"url": {"type": "string", "description": "Public http/https URL"}},
"required": ["url"],
},
},
{
"name": "web_search",
"description": "Search the web using concise English or local-language queries (do not chain long hardware suffixes).",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string", "description": "Concise search query"}},
"required": ["query"],
},
},
{
"name": "geocode_verify",
"description": "Verify a physical facility address or city via geocoder and receive a verified geocode_candidate_id with coordinates and country.",
"parameters": {
"type": "object",
"properties": {
"place_query": {"type": "string", "description": "Address, campus, or city + country"},
"country": {"type": "string", "description": "Expected country name"},
},
"required": ["place_query"],
},
},
{
"name": "submit_location_result",
"description": "Finalize location verification using a geocode_candidate_id from geocode_verify, or report a terminal status (undisclosed/multi_site/anonymous/unresolved).",
"parameters": {
"type": "object",
"properties": {
"status": {
"type": "string",
"enum": ["located", "undisclosed", "multi_site", "anonymous", "unresolved"],
},
"facility_name": {"type": "string"},
"address": {"type": "string"},
"city": {"type": "string"},
"region": {"type": "string"},
"country": {"type": "string"},
"precision": {"type": "string", "enum": ["precise", "site", "city"]},
"geocode_candidate_id": {"type": "string"},
"citations": {
"type": "array",
"items": {"type": "string"},
"description": "URLs directly observed in fetch_source_url or web_search outputs",
},
"confidence": {"type": "number"},
"reasoning": {"type": "string"},
},
"required": ["status", "reasoning"],
},
},
]
async def run_l1_structured_facility_resolvers(
query: LocationQuery,
*,
db: AsyncSession | None = None,
) -> tuple[list[LocationCandidate], list[str], bool]:
"""Run async L1 Wikidata & PeeringDB lookups respecting `location.resolve_unknown` config."""
l1_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l1_knowledge")
params = (l1_node or {}).get("params") or {}
enabled_tools = set((l1_node or {}).get("tools") or [])
allow_low_short_circuit = bool(params.get("allow_low_confidence_short_circuit", False))
tasks = []
if params.get("wikidata_enabled", True) and (not enabled_tools or "wikidata_lookup" in enabled_tools):
tasks.append(lookup_wikidata_facility(query))
if params.get("peeringdb_enabled", True) and (not enabled_tools or "peeringdb_fac_lookup" in enabled_tools):
tasks.append(lookup_peeringdb_facility(query))
candidates: list[LocationCandidate] = []
attempted: list[str] = []
if tasks:
results = await asyncio.gather(*tasks, return_exceptions=True)
for out in results:
if isinstance(out, Exception):
continue
attempted.extend(out.attempted_queries)
candidates.extend(out.candidates)
return candidates, attempted, allow_low_short_circuit
async def _persist_terminal_location_status(
db: AsyncSession | None,
*,
query: LocationQuery,
terminal_status: str,
reasoning: str,
) -> None:
if db is None or not hasattr(db, "execute"):
return
extra = query.extra or {}
source = coerce_str(extra.get("source"))
source_id = coerce_str(extra.get("source_id"))
if not source or not source_id:
return
try:
from app.services.compute_center_locations import refresh_compute_center_location_cache
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=query.name,
operator=coerce_str(extra.get("operator")) or None,
site=coerce_str(extra.get("site")) or None,
city=query.city,
country=query.country,
latitude=None,
longitude=None,
precision="unknown",
confidence=0.0,
location_source=f"agent_terminal_{terminal_status}",
source_note=reasoning[:500] or f"Marked {terminal_status} by location agent",
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 = reasoning[:500] or existing.source_note
existing.verified_at = datetime.now(UTC)
await db.commit()
await refresh_compute_center_location_cache(db)
except Exception as exc:
logger.warning_event(
"Failed to persist terminal unlocatable status",
event="location.agent.persist_terminal_failed",
context={"source_id": source_id, "status": terminal_status, "error": str(exc)},
)
async def _record_location_workflow_run(
db: AsyncSession | None,
*,
question: str,
status_value: str,
tool_trace: list[str],
steps_used: int,
error_message: str = "",
) -> None:
if db is None or not hasattr(db, "add"):
return
try:
db.add(
WorkflowRun(
id=f"run_{uuid4().hex[:16]}",
workflow_id="location.resolve_unknown",
status=status_value,
access_tier="admin",
actor_key="admin:collect-location",
question=question[:500],
tool_trace=tool_trace,
budget_used={"steps": steps_used},
error_message=error_message[:500],
completed_at=datetime.now(UTC),
)
)
await db.commit()
except Exception:
try:
await db.rollback()
except Exception:
pass
async def run_controlled_location_agent(
*,
provider_client: Any,
web_search_client: Any | None,
query: LocationQuery,
entity_type: str = "compute_center",
db: AsyncSession | None = None,
attempted_queries: list[str] | None = None,
) -> tuple[LocationLLMFallbackResult, str | None]:
"""Run the 3-4 step Tool-Calling location agent and return `(result, terminal_status)`."""
extra = query.extra or {}
l2_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l2_agent_research")
l3_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l3_geo_guardrail")
if l2_node and not l2_node.get("enabled", True):
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=list(attempted_queries or []),
failure_reason="Location agent node is disabled by workflow configuration.",
),
None,
)
max_steps = max(1, min(int((l2_node or {}).get("max_steps") or 4), 6))
allowed_tool_names = set((l2_node or {}).get("tools") or [t["name"] for t in LOCATION_AGENT_TOOLS])
min_confidence = float(((l3_node or {}).get("guardrails") or {}).get("min_confidence") or DEFAULT_MIN_CONFIDENCE)
require_tool_urls = bool(((l3_node or {}).get("guardrails") or {}).get("require_tool_cited_urls", True))
active_tools = [t for t in LOCATION_AGENT_TOOLS if t["name"] in allowed_tool_names]
if not any(t["name"] == "submit_location_result" for t in active_tools):
active_tools.append(LOCATION_AGENT_TOOLS[-1])
observed_urls: set[str] = set()
geocode_candidates: dict[str, dict[str, Any]] = {}
tool_trace: list[str] = ["l0_normalize", "l1_knowledge"]
agent_attempts: list[str] = []
source_urls = [
str(u).strip()
for u in [*([extra.get("source_url")] if extra.get("source_url") else []), *(extra.get("sources") or [])]
if str(u or "").strip().startswith(("http://", "https://"))
]
system_prompt = (l2_node or {}).get("system_prompt") or (
"你是算力与网络基础设施物理位置查证 Agent。严禁编造经纬度!"
"1) 若存在 primary_source_urls,优先调用 fetch_source_url;"
"2) 否则调用 web_search 查询物理地址;"
"3) 将查到的物理地址/城市传入 geocode_verify 获取 candidate_id;"
"4) 最后调用 submit_location_result 提交结果。"
)
user_objective = (l2_node or {}).get("prompt") or (
f"请查证目标设施 {query.name or extra.get('source_id')} 的物理所在城市或园区。"
)
context_payload = {
"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,
"raw_country": extra.get("source_raw_country"),
"primary_source_urls": source_urls[:5],
}
messages: list[dict[str, Any]] = [
{
"role": "user",
"content": (
f"{user_objective}\n\n目标上下文 JSON:\n"
f"{json.dumps(context_payload, ensure_ascii=False)}"
),
}
]
submitted_payload: dict[str, Any] | None = None
last_text_response = ""
steps_taken = 0
for step in range(1, max_steps + 1):
steps_taken = step
req = SituationalAnalysisRequest(
title=f"Location agent step {step}",
objective=user_objective,
system_prompt=system_prompt,
context=context_payload,
preferred_model=(l2_node or {}).get("model_override"),
messages=messages,
tools=active_tools,
tool_choice="auto" if step < max_steps else {"type": "function", "name": "submit_location_result"},
native_web_search=bool((l2_node or {}).get("native_web_search", False)),
)
try:
resp = await provider_client.analyze(req)
except Exception as exc:
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=str(exc),
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=f"Location agent failed: {exc}",
),
None,
)
last_text_response = str(getattr(resp, "content", "") or "")
tool_calls = list(getattr(resp, "tool_calls", None) or [])
if not tool_calls:
# Provider returned plain text (no tool calling support); break cleanly into deterministic fallback.
break
messages.append(
{
"role": "assistant",
"content": last_text_response,
"tool_calls": [
{"id": tc.id, "name": tc.name, "arguments": tc.arguments}
for tc in tool_calls
],
}
)
for tc in tool_calls:
raw_args = tc.arguments
if isinstance(raw_args, str):
try:
raw_args = json.loads(raw_args)
except json.JSONDecodeError:
raw_args = {}
args = raw_args if isinstance(raw_args, dict) else {}
tool_trace.append(f"l2_agent_research:{tc.name}")
if tc.name == "fetch_source_url":
target_url = coerce_str(args.get("url"))
agent_attempts.append(f"fetch_url:{target_url}")
try:
fetched = await asyncio.wait_for(safe_web_fetch(target_url, timeout_seconds=8), timeout=10.0)
final_url = (
coerce_str(fetched.get("final_url") or fetched.get("url"))
if isinstance(fetched, dict)
else coerce_str(getattr(fetched, "final_url", None) or getattr(fetched, "url", None))
) or target_url
title = fetched.get("title", "") if isinstance(fetched, dict) else getattr(fetched, "title", "")
text = fetched.get("content", "") if isinstance(fetched, dict) else getattr(fetched, "text", "")
observed_urls.add(target_url)
observed_urls.add(final_url)
tool_output = isolate_untrusted_external_text(final_url, title, text, max_chars=2400)
except Exception as exc:
tool_output = {"error": f"fetch failed: {exc}", "url": target_url}
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps(tool_output, ensure_ascii=False),
}
)
elif tc.name == "web_search":
q_str = coerce_str(args.get("query"))
agent_attempts.append(f"web_search:{q_str}")
if web_search_client is None:
tool_output = {"error": "WebSearch is not enabled or missing API key"}
else:
try:
evidences = await web_search_client.search(q_str, max_results=5)
items = []
for ev in evidences:
u = coerce_str(getattr(ev, "url", ""))
if u:
observed_urls.add(u)
items.append(
{
"title": getattr(ev, "title", ""),
"url": u,
"snippet": getattr(ev, "snippet", "")[:400],
}
)
tool_output = {"results": items}
except Exception as exc:
tool_output = {"error": str(exc)}
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps(tool_output, ensure_ascii=False),
}
)
elif tc.name == "geocode_verify":
place_q = coerce_str(args.get("place_query"))
expected_c = normalize_country_text(args.get("country") or query.country)
agent_attempts.append(f"geocode_verify:{place_q}")
geo_res = await asyncio.to_thread(_agent_geocoder, place_q)
if not isinstance(geo_res, dict):
tool_output = {"found": False, "reason": "No geocoder match"}
else:
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"))
addr = geo_res.get("address") if isinstance(geo_res.get("address"), dict) else {}
res_country = normalize_country_text(addr.get("country") or geo_res.get("country"))
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)
):
tool_output = {"found": False, "reason": "Invalid geocoder coordinates"}
elif expected_c and res_country and normalize_text(res_country) != normalize_text(expected_c):
tool_output = {
"found": False,
"reason": f"Country mismatch: got {res_country}, expected {expected_c}",
}
else:
cid = f"geo_{len(geocode_candidates) + 1}"
geocode_candidates[cid] = {
"latitude": lat,
"longitude": lon,
"display_name": coerce_str(geo_res.get("display_name")) or place_q,
"city": coerce_str(
addr.get("city")
or addr.get("town")
or addr.get("village")
or addr.get("municipality")
or geo_res.get("city")
),
"region": coerce_str(addr.get("state") or addr.get("region") or geo_res.get("region")),
"country": res_country or expected_c or query.country,
}
tool_output = {"found": True, "geocode_candidate_id": cid, **geocode_candidates[cid]}
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps(tool_output, ensure_ascii=False),
}
)
elif tc.name == "submit_location_result":
submitted_payload = dict(args)
tool_trace.append("l3_geo_guardrail")
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps({"accepted": True}),
}
)
if submitted_payload is not None:
break
if submitted_payload is None:
# Fallback for providers/mocks without tool_calls support
evidence_list = []
if web_search_client is not None:
from app.services.location.llm_fallback import collect_location_search_evidence
search_res = await collect_location_search_evidence(
web_search_client=web_search_client,
query=query,
entity_type=entity_type,
)
agent_attempts.extend(search_res.attempted_queries)
evidence_list = search_res.evidence
if evidence_list or last_text_response:
fallback_res = await collect_llm_location_fallback_candidate(
provider_client=provider_client,
query=query,
entity_type=entity_type,
db=db,
attempted_queries=[*(attempted_queries or []), *agent_attempts],
search_evidence=evidence_list,
min_confidence=min_confidence,
)
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="completed" if fallback_res.candidates else "failed",
tool_trace=[*tool_trace, "llm_fallback"],
steps_used=steps_taken,
error_message=fallback_res.failure_reason or "",
)
return fallback_res, None
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message="Agent did not submit location result",
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason="Location agent reached step budget without submitting a verified location.",
),
None,
)
sub_status = str(submitted_payload.get("status") or "unresolved").strip().lower()
reasoning = coerce_str(submitted_payload.get("reasoning"))
if sub_status in TERMINAL_UNLOCATABLE_STATUSES:
await _persist_terminal_location_status(
db,
query=query,
terminal_status=sub_status,
reasoning=reasoning,
)
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="completed",
tool_trace=[*tool_trace, f"l4_persist_outcome:{sub_status}"],
steps_used=steps_taken,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reasoning or f"Facility confirmed as {sub_status}.",
),
sub_status,
)
geo_cid = coerce_str(submitted_payload.get("geocode_candidate_id"))
geo_entry = geocode_candidates.get(geo_cid)
if sub_status != "located" or geo_entry is None:
reason = reasoning or "Submitted result missing verified geocode_candidate_id"
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=reason,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reason,
),
None,
)
citations = [
str(c).strip()
for c in (submitted_payload.get("citations") or [])
if str(c or "").strip()
]
verified_citations = [c for c in citations if c in observed_urls]
if require_tool_urls and not verified_citations:
reason = "No verified citation URLs observed in tool outputs"
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=reason,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reason,
),
None,
)
expected_country = normalize_country_text(query.country)
resolved_country = normalize_country_text(submitted_payload.get("country") or geo_entry.get("country"))
if expected_country and resolved_country and normalize_text(resolved_country) != normalize_text(expected_country):
reason = f"Country mismatch ({resolved_country} != {expected_country})"
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=reason,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reason,
),
None,
)
confidence = min(max(parse_float(submitted_payload.get("confidence")) or 0.78, 0.0), 1.0)
raw_precision = coerce_str(submitted_payload.get("precision")).lower()
precision = raw_precision if raw_precision in {"precise", "site", "city"} else "city"
facility_label = coerce_str(submitted_payload.get("facility_name")) or coerce_str(geo_entry.get("display_name")) or coerce_str(query.name)
candidate = LocationCandidate(
latitude=float(geo_entry["latitude"]),
longitude=float(geo_entry["longitude"]),
display_name=facility_label,
precision=precision,
confidence=max(confidence, min_confidence),
query=f"location_agent:{entity_type}:{query.name or extra.get('source_id') or 'unknown'}",
source="llm_location_factcheck",
source_note=reasoning or f"Verified via tool-calling agent ({len(verified_citations)} citations)",
matched_fields=("name", "tool_calling_agent"),
needs_confirmation=True,
city=coerce_str(submitted_payload.get("city")) or geo_entry.get("city") or query.city or None,
region=coerce_str(submitted_payload.get("region")) or geo_entry.get("region") or query.region or None,
country=resolved_country or expected_country or query.country,
matched_location_name=facility_label,
raw_payload={"citations": verified_citations or citations, "geocode_candidate_id": geo_cid},
)
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="completed",
tool_trace=[*tool_trace, "l4_persist_outcome:located"],
steps_used=steps_taken,
)
return (
LocationLLMFallbackResult(
candidates=[candidate],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=None,
),
None,
)