在上一篇文章中,我們已經成功完成了 Google Maps 的智慧定位服務 以及 智能化景點搜尋與推薦,讓行程管家具備了 即時掌握位置資訊的能力。今天,我們將更進一步,撰寫一個結合 AI Agent × Google Maps Directions API 的功能 —— 智慧化路線規劃
為什麼需要智慧路線規劃?
在旅途中,我們常常會遇到以下問題:
有了 Directions API 的加持,我們不僅能獲取 精準的交通路線,還能搭配 AI Agent 的智慧判斷,提供 量身打造的行程建議,讓旅遊不再只是移動,而是 充滿驚喜的探索體驗 。
撰寫 Directions Agent
接下來,我們要撰寫一個能呼叫 Google Maps Directions API 的函式,透過 AI Agent 的運算邏輯,它能根據使用者需求、地理條件以及偏好,生成更 智慧化、個人化 的旅遊建議。
@app.post("/itinerary_googlemap_directions")
async def itinerary_googlemap_directions(origin: str, destination: str):
# 使用 Google Maps Directions API 取得路線規劃
url = f"https://maps.googleapis.com/maps/api/directions/json?origin={origin}&destination={destination}&key={GOOGLE_MAPS_API_KEY}"
response = requests.get(url)
data = response.json()
# 檢查 API 回傳狀態,並取得路線資訊
if data['status'] == 'OK':
route = data['routes'][0]['legs'][0]
directions = {
"start_address": route['start_address'],
"end_address": route['end_address'],
"distance": route['distance']['text'],
"duration": route['duration']['text'],
"steps": []
}
for step in route['steps']:
directions['steps'].append({
"instruction": step['html_instructions'],
"distance": step['distance']['text'],
"duration": step['duration']['text']
})
query = f"請提供從 {origin} 到 {destination} 的路線建議。"
parts = [types.Part(text=query)]
runner = Runner(
app_name="itinerary_housekeeper",
agent=destination_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 {"directions": directions,
"result": result}
else:
return {"error": "無法取得路線資訊"}
透過 Directions API × AI Agent 的結合,我們成功將路線查詢轉化為一個更聰明、更有彈性的行程管家的一部分。它不僅僅會告訴你「怎麼走」,還會考慮你的 旅遊偏好、時間成本,甚至幫你挖掘沿途的驚喜景點。