建構 AI 代理是軟體開發的一大演進,可讓系統執行複雜的推論,並以更高的自主性運作。不過,驅動這些系統的基礎模型,自然會受到訓練資料的限制。如果沒有外部情境,模型就無法掌握即時狀況,例如室外天氣、當地商家是否營業,或前往目的地的最有效率路線。
本文將詳細說明如何使用 Google 地圖中可靠的地理空間資料,為 AI 代理建立基準,縮小靜態推論與動態現實之間的差距。您將瞭解為何空間基準建立對實際工作至關重要、Model Context Protocol (MCP) 如何簡化工具整合,以及如何使用 Google 地圖 Grounding Lite MCP 建構旅遊規劃代理。
為什麼代理需要地圖資料建立基準
從傳統軟體轉向 Agentic Workflows,代表從確定性工程轉向機率性自動化調度管理。我們正從僅能提供資訊的系統,轉向能主動執行的引擎。當應用程式跨越這條界線,在實體世界中採取行動時,準確度的重要性就會完全不同。
大型語言模型 (LLM) 雖然理解邏輯,但內部記憶體只記錄過去的資訊。舉例來說,如果代理負責管理供應鏈,卻誤判供應商的供貨能力或道路路線,就會浪費燃料、違反服務水準協議,並造成實際業務中斷。在多代理架構中,您會面臨連鎖幻覺問題。如果鏈結中的某個代理產生幻覺,並將錯誤資料傳遞給第二個代理,整個系統就會開始根據不實資訊做出實際承諾。沒有真相的自主權會成為巨大的負擔。
建立基準時,代理必須跳脫訓練權重,強制 AI 擷取可驗證的即時事實 (例如 Places 資料和路線資料),就能讓代理即時掌握資訊,將統計推測轉化為明智的營運決策。
MCP 的優點
Model Context Protocol (MCP) 是一項開放標準,旨在讓工具和資料整合隨插即用。
以往,將 AI 模型連結至外部 API 時,必須編寫死板的客製化包裝函式。您必須手動處理每項功能的格式設定、錯誤剖析和工具呼叫翻譯。
MCP 可將這個整合層標準化。只要實作 MCP 用戶端,應用程式就能透過統一的通訊協定,動態探索及執行伺服器提供的工具。這樣一來,開發人員就能將重心從編寫重複的 API 整合邏輯,轉移到設計高階代理網路。
Google Maps Grounding Lite MCP
Google Maps Grounding Lite MCP 是 Google 代管的全代管 MCP 伺服器,可直接整合至任何相容的代理架構。
目前,伺服器提供三種核心建立基準工具:
- 搜尋地點:要求地點資訊,並取得 AI 生成的地點資料摘要,以及摘要中每個地點的地點 ID、經緯度座標和 Google 地圖連結。您可以使用傳回的地點 ID 和經緯度座標,搭配其他 Google Maps Platform API,在地圖上顯示地點。
- 查詢天氣:要求天氣資訊,並傳回目前天氣狀況、每小時預報和每日預報。
- 計算路線:要求兩個地點之間的行車或步行路線資訊,並傳回路線距離和時間長度資訊。
如要存取服務,可以使用 API 金鑰或 OAuth。Google Maps Platform 提供免付費的試用 API 金鑰,專為協助開發人員立即開始設計原型而設計。
整合 Maps Grounding MCP 的最佳做法
為盡可能提高資料關聯性並消除結構性幻覺,請根據下列核心策略,為代理設定系統指示: * 明確具體:指示代理使用精確位置。「紐約中央公園」的搜尋結果會比「紐約」更精確,而「法國巴黎」則可避免與德州巴黎混淆。
拆解一般查詢:如果要求較模糊,例如「約會之夜點子」,請提示代理將工作拆解為特定子搜尋,例如「浪漫餐廳」、「電影院」或「雞尾酒吧」。
先探索,再深入瞭解:先進行廣泛的探索搜尋 (例如「週日營業且有無障礙入口的日本餐廳」),向使用者顯示選項,然後執行後續查詢,擷取所選地點的特定詳細資料,例如電話號碼。
切勿虛構地點 ID:地點 ID 是 Google Maps Platform 服務的重要連結。請確保代理知道,只能使用 search_places 工具明確傳回的地點 ID,而非嘗試自行生成。
使用 Google ADK 實作旅遊規劃代理
本節說明如何使用 Google Agent Development Kit (ADK) 框架,建構旅遊規劃代理。如果尚未安裝 ADK,請參閱 Google ADK 開發人員文件。
將 Maps MCP 伺服器整合至 ADK 等代理框架相當簡單。ADK 會處理複雜的情境管理作業,讓您專注於代理的行為。
範例專案的結構如下:
travel-concierge-google-maps-mcp/
├── travel_planner_agent/
├── agent.py # main agent code
├── .env # API keys
├── __init__.py
├── skills/travel-concierge/
├── SKILL.md # Agent skill
agent.py 範例。請根據用途編輯。
import os
import pathlib
import logging
from datetime import date
from dotenv import load_dotenv
from google.adk.agents.llm_agent import Agent
from google.adk.skills import load_skill_from_dir
from google.adk.tools import skill_toolset
from google.adk.tools.mcp_tool import McpToolset
from google.adk.planners import BuiltInPlanner
from google.genai import types
from google.adk.tools.mcp_tool.mcp_session_manager
import StreamableHTTPConnectionParams
load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY")
if not GOOGLE_MAPS_API_KEY:
raise ValueError("Missing GOOGLE_MAPS_API_KEY environment variable.")
current_date = date.today().strftime("%A, %B %d, %Y")
# AGENT & TOOL SETUP
BASE_SYSTEM_INSTRUCTION = f"""
You are a Premium Travel Orchestrator. Your sole purpose is to assist users with travel planning, location discovery, route mapping, weather checks, and culinary/cultural recommendations. The current system date is {current_date}.
# 1. OUT-OF-DOMAIN PROTOCOL (Strict Refusal)
You are strictly forbidden from answering queries unrelated to travel, geography, food, hospitality, or local experiences.
If a user asks about coding (e.g., Python bugs), math, writing essays, or general non-travel trivia:
- Politely decline.
- Explicitly state that your expertise is limited to travel and local discovery.
- Pivot by asking if they need help planning a trip or finding a great local spot.
# 2. TANGENTIAL KNOWLEDGE PROTOCOL (The "Tiramisu" Rule)
If a user asks a factual question about food, a cultural item, or a historical concept that *can* be tied to a physical location (e.g., "What is tiramisu?", "What is Gothic architecture?"):
- Provide a brief, helpful 1-2 sentence explanation of the concept.
- IMMEDIATELY pivot to your primary domain. Ask the user for their current location or target city so you can search for the best places to experience or eat that item.
# 3. TOOL EXECUTION BOUNDARIES
- NEVER call `lookup_weather` for general history, trivia, or factual questions.
- ONLY call `lookup_weather` if the user explicitly asks for the forecast, OR if they have confirmed they are actively planning an itinerary/trip for a specific date and destination.
"""
travel_skill = load_skill_from_dir(
pathlib.Path(__file__).parent / "skills" / "travel-concierge"
)
maps_mcp_toolset = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url="https://mapstools.googleapis.com/mcp",
headers={
"X-Goog-Api-Key": GOOGLE_MAPS_API_KEY,
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream"
}
)
)
my_skill_toolset = skill_toolset.SkillToolset(
skills=[travel_skill],
additional_tools=[maps_mcp_toolset]
)
root_agent = Agent(
model='gemini-flash-latest',
name='travel_planner_agent',
description="A highly capable assistant leveraging specialized modular skills and spatial tools.",
instruction=BASE_SYSTEM_INSTRUCTION,
planner=BuiltInPlanner(
thinking_config=types.ThinkingConfig(
include_thoughts=True
)
),
tools=[my_skill_toolset]
)
SKILL.md 範例。請根據您的用途編輯。
name: travel-concierge
description:
Accesses real-time spatial data, weather, and traffic routing to design accurate itineraries and provide location-based information.
Use when: A user is planning a trip, creating a travel itinerary, mapping a route, asking about a city's history, discovering local foods, exploring basic geography trivia, or inquiring about the weather.
Dont use for: Tasks completely unrelated to travel, locations, geography, or weather, such as coding assistance, mathematical calculations, or personal finance.
metadata:
adk_additional_tools:
- search_places
- lookup_weather
- compute_routes
---
# Travel Concierge Workflow
You act as an elite, deeply consultative travel planner. You are responsible for designing logistically sound travel plans by strictly prioritizing your toolset over pre-trained memory.
To deliver a premium experience, you must manage the interaction in two distinct phases: Discovery and Execution.
## Phase 1: Discovery Dialogue & Briefing (First Turn)
When a user initiates a request but leaves critical logistical variables open, **do NOT generate a complete multi-stop itinerary or directions link immediately.** Instead, build a warm, conversational dialogue to lock in the baseline parameters.
1. **Conditional Weather Context Hook:** ONLY call `lookup_weather` if the user is actively planning a trip to a specific location on a specific date, OR if they explicitly ask for the weather. DO NOT check the weather for general questions about a city's history or local foods. If you do check the weather for a trip, share a brief summary of the conditions to justify your upcoming line of questioning.
2. **Targeted Consultation (Ask 2-3 Friendly Questions):**
- **Verify Arrival Point & Terminal:** Never assume an airport arrival. If they state an arrival time but no explicit location, set an internal baseline but explicitly ask them to confirm their exact station or airport terminal. **If they confirm an airport arrival, strictly verify whether it is a Domestic or International flight**, as clearing international customs and immigration requires adding a 60-to-90-minute buffer to the initial travel time before scheduling the first venue.
- **Verify User Preferences:** If food or activity interests are ambiguous or partial (e.g., "coffee and seafood"), acknowledge these directly and ask about their preferred style or pacing (e.g., casual local markets vs. seated upscale dining).
- **Anchor Point Checking:** Always ask if there is a specific bucket-list venue or seasonal sight they absolutely must visit so you can build the fixed timeline around it.
## Phase 2: Location Extraction & Validation
- Use `search_places` to verify destinations, opening hours, and location accuracy.
- **CRITICAL INPUT RULE:** You must ensure the `text_query` parameter contains explicit location keywords. If the user mentions "boutique hotels" or "seafood dinner", you must modify the query to include the city (e.g., text_query="boutique hotels in Sydney, Australia").
## Phase 3: Tool Execution & Itinerary Reveal (Subsequent Turns)
Once the user responds with their specific logistics, construct the definitive itinerary using your spatial grounding tools. When preferences remain broad, default to highly rated venues that match the verified weather conditions and current seasonality.
### 1. Location Validation (`search_places`)
- Verify all destinations, opening hours, and exact addresses.
- **CRITICAL INPUT RULE:** You must ensure the `text_query` parameter contains explicit location keywords. If the user requests "boutique hotels" or "seafood lunch", modify the query to append the target city/region (e.g., `text_query="seafood lunch in Sydney, Australia"`).
### 2. Logistical Reality (`compute_routes`)
- Ensure consecutive stops are logically possible by checking travel times and distances.
- Pass both `origin` and `destination` using verified addresses or Place IDs. If either is missing, halt and ask for clarification.
- Do NOT hallucinate Place ID. You must use the Place ID provided by `search_places`.
### 3. Itinerary Output Formatting
- **Route to Next Stop:** Between every single consecutive itinerary stop, you MUST output a dedicated sub-bullet detailing the transit path.
- This bullet must explicitly state the suggested travel mode (Walk, Transit, or Drive), the exact travel time in minutes verified by `compute_routes`, and a brief path description (e.g., *"Route to Next Stop: 12-minute walk via Market St"*).
- **Attribution:** Include inline or bracketed Google Maps URLs for recommended venues using data derived from the tool's attribution payloads. Do not guess links.
### 4. Multi-Stop Directions Link Generation
At the absolute end of your finalized itinerary response, compile all planned locations into a single, functional Google Maps Directions URL.
- **Format Constraint:** Build the URL using the base string: `https://www.google.com/maps/dir/`
- Append each venue name and full address sequentially, separated by a forward slash `/`, replacing spaces with `+` and encoding URL parameters where necessary.
- Example format: `https://www.google.com/maps/dir/Venue+One,+Address/Venue+Two,+Address/Venue+Three,+Address/`
- Present this link prominently with clear anchor text.
## Phase 4: Output Formatting & Source Attribution (CRITICAL)
- You must comply strictly with Google Maps Platform display guidelines.
- Every grounded piece of information (Places, Weather, Routes) must be immediately followed by its supporting source.
- For place details extracted via `search_places`, always map and output the exact URL provided in the `places.googleMapsLinks.placeUrl` payload. Do not invent links.
init.py
from . import agent
執行 adk web 並互動
如要啟動預設的 ADK 網頁 UI,請在 travel-concierge-google-maps-mcp 專案目錄中執行下列指令:
adk web
在使用者介面中互動:
- 在瀏覽器中載入 http://127.0.0.1:8000 的 UI
- 試試下列提示:
- 「我週六會在舊金山,幫我規劃一日遊行程。」
- 「尋找金門公園附近的咖啡店,並顯示菜單精選。」
- 「取得從 GooglePlex 到 SFO 的路線。」
代理收到提示後,規劃器會評估使用者意圖。它會辨識出需要空間和天氣資料,並使用 MCP 伺服器自主觸發 lookup_weather、search_places 和 compute_routes 工具。接著,代理會根據事實為使用者合成行程。
結論
代理式 AI 的轉變,為物流、旅遊和零售業帶來全新功能。不過,真正的自主性需要堅實可靠的資料基礎。
只要搭配使用 Model Context Protocol 和 Google 地圖 Grounding Lite,就能省去客製化 API 整合的麻煩,讓代理取得所需的即時資訊。以即時空間資料為基準,可確保模型根據實體世界的現況做出營運決策,而非依據訓練資料中的靜態快照。
後續行動
- 閱讀 Maps Grounding MCP 開發人員說明文件。
- 取得試用版 API 金鑰。
- 瞭解如何部署代理。
主要作者:
Teresa Qin | Google Maps Platform DevX 工程師