talk2map-prod / agent /maptool.py
Noel-Teens's picture
testing workflow
622b3c4
Raw History Blame Contribute Delete
9.66 kB
# maptool.py
import os
import json
import time
import logging
from typing import List, Dict, Optional, Literal
import requests
from dotenv import load_dotenv
from langchain_core.tools import tool
load_dotenv()
PLACES_API_KEY = os.getenv("PLACES_API_KEY")
PLACES_SEARCH_URL = "https://places.googleapis.com/v1/places:searchText"
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# ──────────────────────────────────────────────────────────────────────────────
# Helpers: geometry & filtering
# ──────────────────────────────────────────────────────────────────────────────
def _inside_box(lat: float, lng: float, sw: Dict, ne: Dict) -> bool:
if lat is None or lng is None:
return False
south, west = float(sw["lat"]), float(sw["lon"])
north, east = float(ne["lat"]), float(ne["lon"])
if south > north: # auto-fix latitude order if caller flipped
south, north = north, south
in_lat = (south <= lat <= north)
# Normal case or antimeridian
if west <= east:
in_lng = (west <= lng <= east)
else:
in_lng = (lng >= west) or (lng <= east)
return in_lat and in_lng
def _viewport_inside_box(vp: Dict, sw: Dict, ne: Dict) -> bool:
if not vp:
return False
low = vp.get("low", {})
high = vp.get("high", {})
return _inside_box(low.get("latitude"), low.get("longitude"), sw, ne) and _inside_box(
high.get("latitude"), high.get("longitude"), sw, ne
)
def _to_bounding_box_from_viewport(vp: Optional[Dict]) -> Optional[Dict]:
if not vp:
return None
low = vp.get("low")
high = vp.get("high")
if not low or not high:
return None
return {
"north_east": {"lat": high.get("latitude"), "lon": high.get("longitude")},
"south_west": {"lat": low.get("latitude"), "lon": low.get("longitude")},
}
def _valid_bbox(bbox: Optional[Dict]) -> Optional[Dict]:
if not bbox:
return None
try:
ne = bbox.get("north_east") or {}
sw = bbox.get("south_west") or {}
ne_lat, ne_lon = float(ne["lat"]), float(ne["lon"])
sw_lat, sw_lon = float(sw["lat"]), float(sw["lon"])
# Basic sanity (Google requires lat in [-90, 90], lon in [-180, 180])
for v in (ne_lat, sw_lat):
if v < -90 or v > 90:
return None
for v in (ne_lon, sw_lon):
if v < -180 or v > 180:
return None
return {"north_east": {"lat": ne_lat, "lon": ne_lon}, "south_west": {"lat": sw_lat, "lon": sw_lon}}
except Exception:
return None
# ──────────────────────────────────────────────────────────────────────────────
# HTTP with retries
# ──────────────────────────────────────────────────────────────────────────────
def _places_request(*, query: str, page_token: Optional[str], page_size: int,
region_code: str, language_code: str, location_bias: Optional[Dict] = None) -> Dict:
if not PLACES_API_KEY:
raise RuntimeError("PLACES_API_KEY is not set in environment.")
headers = {
"Content-Type": "application/json",
"X-Goog-Api-Key": PLACES_API_KEY,
# Request only needed fields (faster/cheaper)
"X-Goog-FieldMask": (
"places.displayName,places.formattedAddress,places.location,places.viewport,"
"places.rating,places.userRatingCount,places.priceLevel,places.googleMapsUri,nextPageToken"
),
}
payload = {
"textQuery": query,
"pageSize": int(page_size),
"regionCode": region_code,
"languageCode": language_code,
}
if page_token:
payload["pageToken"] = page_token
if location_bias:
payload["locationBias"] = location_bias
# lightweight exponential backoff on 429/5xx
for attempt in range(4):
resp = requests.post(PLACES_SEARCH_URL, headers=headers, json=payload, timeout=30)
if resp.status_code == 200:
data = resp.json()
if "error" in data:
raise RuntimeError(f"Places API error: {data['error'].get('message','Unknown error')}")
return data
if resp.status_code in (429, 500, 502, 503, 504):
sleep_s = 0.8 * (2 ** attempt)
time.sleep(sleep_s)
continue
# Other errors β†’ raise with body for logs
raise RuntimeError(f"Places API error {resp.status_code}: {resp.text}")
raise RuntimeError("Places API: exhausted retries.")
# ──────────────────────────────────────────────────────────────────────────────
# Core search + optional strict filtering
# ──────────────────────────────────────────────────────────────────────────────
def search_places(
*,
query: str,
top_n: int = 5,
region_code: str = "IN",
language_code: str = "en",
location_bias: Optional[Dict] = None,
bbox: Optional[Dict] = None, # {"north_east":{"lat","lon"},"south_west":{"lat","lon"}}
strict_mode: Optional[Literal["point", "viewport"]] = None,
) -> List[Dict]:
results: List[Dict] = []
token: Optional[str] = None
# Clamp & sanitize
top_n = max(1, min(20, int(top_n)))
query = (query or "").strip()
if not query:
return []
# Bias only if valid bbox is provided
location_bias = None
valid = _valid_bbox(bbox)
if valid:
ne, sw = valid["north_east"], valid["south_west"]
location_bias = {"rectangle": {"low": {"latitude": sw["lat"], "longitude": sw["lon"]},
"high": {"latitude": ne["lat"], "longitude": ne["lon"]}}}
while len(results) < top_n:
page_size = min(20, top_n - len(results))
page = _places_request(
query=query,
page_token=token,
page_size=page_size,
region_code=region_code,
language_code=language_code,
location_bias=location_bias,
)
for p in page.get("places", []) or []:
display_name = (p.get("displayName") or {}).get("text")
address = p.get("formattedAddress")
loc = p.get("location") or {}
lat = loc.get("latitude")
lng = loc.get("longitude")
viewport = p.get("viewport")
# Strict filtering if requested
if valid and strict_mode:
ne = valid["north_east"]
sw = valid["south_west"]
if strict_mode == "point" and not _inside_box(lat, lng, sw, ne):
continue
if strict_mode == "viewport" and not _viewport_inside_box(viewport, sw, ne):
continue
results.append(
{
"name": display_name,
"address": address,
"lat": lat,
"lng": lng,
"viewport": viewport,
"bounding_box": _to_bounding_box_from_viewport(viewport),
"rating": p.get("rating"),
"userRatingCount": p.get("userRatingCount"),
"priceLevel": p.get("priceLevel"),
"mapsUrl": p.get("googleMapsUri"),
}
)
if len(results) >= top_n:
break
token = page.get("nextPageToken")
if not token or not page.get("places"):
break
return results
@tool("search_places", return_direct=True)
def search_places_tool(
query: str,
top_n: int = 5,
region_code: str = "IN",
language_code: str = "en",
bounding_box: Optional[Dict] = None,
strict: bool = True,
require_viewport_fit: bool = False,
) -> str:
"""
Search for places using Places API v1 Text Search (New).
Args:
query: Free-text query ("school", "best coffee", "hotels", ...)
top_n: 1–20
region_code: CLDR (e.g., "IN")
language_code: BCP-47 (e.g., "en")
bounding_box: optional {"north_east":{"lat","lon"},"south_west":{"lat","lon"}}
strict: True β†’ point-in-rectangle filter
require_viewport_fit: True β†’ viewport must fully fit in rectangle
Returns:
JSON string of array[Place]
"""
strict_mode: Optional[Literal["point", "viewport"]] = None
if require_viewport_fit:
strict_mode = "viewport"
elif strict:
strict_mode = "point"
data = search_places(
query=query,
top_n=top_n,
region_code=region_code,
language_code=language_code,
location_bias=None, # set inside search_places when bbox is valid
bbox=bounding_box,
strict_mode=strict_mode,
)
return json.dumps(data, ensure_ascii=False, separators=(",", ":"))