iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0
Mobile Development

結合AI Agent技術打造自己的行程管家系列 第 8

Day 8 行程管家進化:AI Agent 結合 Places API 的智慧景點探索

  • 分享至 

  • xImage
  •  

在上一篇文章中,我們已經成功完成了 Google Maps 的智慧定位服務,讓行程管家具備了即時掌握位置的能力。今天,我們將更進一步,撰寫另一個結合 AI Agent × Google Maps 的功能 —— 智慧景點搜尋與推薦。

這一次的重點,將放在 Places API —— 它是 Google Maps 提供的核心服務之一,能夠搜尋地點,並取得詳細資訊(例如:評分、地址、電話 等)。這些資訊不僅是地圖應用的基礎,更是串接其他功能的關鍵樞紐。只要掌握了經緯度,我們就能實現:

  • 附近景點推薦:快速找出值得一去的餐廳、景點或商店。
  • 交通路線規劃:結合定位與地點資訊,打造順暢行程。
  • 即時旅遊建議:讓 AI Agent 根據當下位置與需求,量身推薦最合適的選項。

可以把它想像成:我們正在打造一位 智慧導遊,隨時根據位置與需求,為你規劃最佳的行程。

撰寫 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 根據城市座標與使用者需求,量身打造旅遊建議。

下一篇,我將帶大家解鎖 Directions API,讓行程管家不僅能定位與推薦,還能替我們找出 最順暢、最值得去的路線,真正做到智慧化的「專屬旅遊導遊」。


上一篇
Day7 行程管家進化:AI Agent 結合 Geocoding API 的智慧定位
系列文
結合AI Agent技術打造自己的行程管家8
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言