Spaces:
Sleeping
Sleeping
File size: 9,659 Bytes
622b3c4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | # 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=(",", ":"))
|