在上一篇文章中,我們已經成功完成了 Google Maps 的智慧定位服務,讓行程管家具備了即時掌握位置的能力。今天,我們將更進一步,撰寫另一個結合 AI Agent × Google Maps 的功能 —— 智慧景點搜尋與推薦。
這一次的重點,將放在 Places API —— 它是 Google Maps 提供的核心服務之一,能夠搜尋地點,並取得詳細資訊(例如:評分、地址、電話 等)。這些資訊不僅是地圖應用的基礎,更是串接其他功能的關鍵樞紐。只要掌握了經緯度,我們就能實現:
可以把它想像成:我們正在打造一位 智慧導遊,隨時根據位置與需求,為你規劃最佳的行程。
撰寫 Places AI Agent
接下來,我們要撰寫一個能呼叫 Google Maps Places API 的函式,並將獲取的景點資訊交給 AI Agent,由它根據經緯度與類型提供 個人化的旅遊建議。
@app.post("/itinerary_googlemap_places")
async def itinerary_googlemap_places(lat: float, lng: float, place_type: str):
# 使用 Google Maps Places API 取得附近景點
url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{lng}&radius=5000&type={place_type}&key={GOOGLE_MAPS_API_KEY}"
response = requests.get(url)
data = response.json()
# 檢查 API 回傳狀態,並取得景點列表
if data['status'] == 'OK':
places = []
for place in data['results']:
places.append({
"name": place['name'],
"address": place.get('vicinity', '無地址資訊'),
"rating": place.get('rating', '無評分資訊')
})
# 呼叫 places_agent
query = f"請提供關於經緯度 ({lat}, {lng}) 附近的 {place_type} 景點建議。"
parts = [
types.Part(text=query),
types.Part(text=json.dumps({"latitude": lat, "longitude": lng, "place_type": place_type}))
]
runner = Runner(
app_name="itinerary_housekeeper",
agent=places_agent,
artifact_service=artifacts_service,
session_service=session_service,
)
session = await session_service.create_session(
state={}, app_name="itinerary_housekeeper", user_id="user"
)
content = types.Content(role="user", parts=parts)
# 執行 Agent
events_async = runner.run_async(
session_id=session.id, user_id="user", new_message=content
)
response = []
async for event in events_async:
if event.content:
for part in event.content.parts:
if part.text:
response.append(part.text)
result = "\n".join(response)
return {"places": places,
"result": result}
else:
return {"error": "無法取得附近景點"}
透過這樣的設計,我們不僅能 即時掌握地理資訊,還能讓 AI Agent 根據城市座標與使用者需求,量身打造旅遊建議。