[Gemini][Google Maps] 使用 Google Maps Grounding API 打造位置感知的 AI 應用
前情提要 在開發 LINE Bot 時,我想加入一個功能:讓使用者分享位置後,AI 可以智慧推薦附近的餐廳、加油站或停車場。傳統做法需要串接 Google Places API,處理複雜的搜尋邏輯和結果排序。但 Google 在 2024 年推出了 Grounding with Google Maps 功能,可以讓 Gemini 模型直接存取 Google Maps 的 2.5 億個地點資訊,讓 AI 回應自動帶有地理位置脈絡! 這項功能透過 Vertex AI 提供,可以讓 Gemini 模型「接地氣」(grounded)地回答位置相關問題,不再只是憑空想像。 開發過程中遇到的問題 在實作 maps_grounding.py 時,我最初使用 Gemini Developer API 搭配 API Key 的方式: # ❌ 錯誤的做法 client = genai.Client( api_key=api_key, http_options=HttpOptions(api_version="v1") ) response = client.models.generate_content( model="gemini-2.0-flash-lite", # 不支援 Maps Grounding contents=query, config=GenerateContentConfig( tools=[Tool(google_maps=GoogleMaps())], tool_config=ToolConfig(...) ), ) 結果出現了這個錯誤: google.genai.errors.ClientError: 400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': 'Invalid JSON payload received. Unknown name "tools": Cannot find field. Invalid JSON payload received. Unknown name "toolConfig": Cannot find field.'}} 經過查閱文件後才發現,Google Maps Grounding 只支援 Vertex AI,無法使用 Gemini Developer API! 正確的解決方案 1. 理解 API 差異 Google 提供兩種不同的 Gemini API 存取方式: 特性 Gemini Developer API Vertex AI API 認證方式 API Key ADC / Service Account Maps Grounding ❌ 不支援 ✅ 支援 企業級功能 有限 完整 適用場景 快速原型開發 生產環境 2. 修正程式碼 以下是正確的實作方式: from google import genai from google.genai import...
繼續閱讀