datawhalechina/hello-agents · critical · ValueError
高德地图API Key未配置,请在.env文件中设置AMAP_API_KEY
Error message
高德地图API Key未配置,请在.env文件中设置AMAP_API_KEY
What it means
ValueError raised by get_amap_mcp_tool() (chapter13 amap_service.py) on first initialization when settings.amap_api_key is falsy. It guards creation of the MCPTool that shells out to `uvx amap-mcp-server`; without a key the subprocess would be useless, so init fails fast. The singleton means this fires once per process on first map usage.
Source
Thrown at code/chapter13/helloagents-trip-planner/backend/app/services/amap_service.py:25
# 全局MCP工具实例
_amap_mcp_tool = None
def get_amap_mcp_tool() -> MCPTool:
"""
获取高德地图MCP工具实例(单例模式)
Returns:
MCPTool实例
"""
global _amap_mcp_tool
if _amap_mcp_tool is None:
settings = get_settings()
if not settings.amap_api_key:
raise ValueError("高德地图API Key未配置,请在.env文件中设置AMAP_API_KEY")
# 创建MCP工具
_amap_mcp_tool = MCPTool(
name="amap",
description="高德地图服务,支持POI搜索、路线规划、天气查询等功能",
server_command=["uvx", "amap-mcp-server"],
env={"AMAP_MAPS_API_KEY": settings.amap_api_key},
auto_expand=True # 自动展开为独立工具
)
print(f"✅ 高德地图MCP工具初始化成功")
print(f" 工具数量: {len(_amap_mcp_tool._available_tools)}")
# 打印可用工具列表
if _amap_mcp_tool._available_tools:
print(" 可用工具:")
for tool in _amap_mcp_tool._available_tools[:5]: # 只打印前5个
print(f" - {tool.get('name', 'unknown')}")View on GitHub (pinned to 606a07d341)
Solutions
- Set AMAP_API_KEY in backend/.env and restart the backend
- Confirm the Settings object actually loads .env (check get_settings() source path and that the process cwd is right)
- If it persists, print settings source or keys list (names only) to verify the variable is visible
- Keep the eager config check enabled so this error surfaces at boot rather than mid-request
Example fix
# before # .env absent -> first map request raises ValueError # after # backend/.env AMAP_API_KEY=xxxx # then restart: uvicorn app.main:app --reload
Defensive patterns
Strategy: validation
Validate before calling
import os
def amap_ready() -> bool:
key = os.getenv('AMAP_API_KEY', '')
return bool(key.strip())
assert amap_ready(), 'AMAP_API_KEY missing — set it in backend/.env before using map features' Try / catch
try:
tool = get_amap_mcp_tool()
except ValueError as e:
if 'AMAP_API_KEY' in str(e):
raise SystemExit('Configure AMAP_API_KEY and restart the backend')
raise Prevention
- Keep the eager startup config check enabled so this never surfaces lazily at request time
- Verify settings actually load .env (cwd, dotenv path) in deployment scripts
- Add a startup warm-up that touches get_amap_mcp_tool() to force early failure
When it happens
Trigger: First call to any map/poi route or /map/health after booting without AMAP_API_KEY; key present but empty string; .env exists but was never loaded into settings.
Common situations: Same cluster as error 316 but surfacing lazily at first use instead of at startup — happens when code paths bypass the eager config validation; env var name mismatch after deployment changes.
Related errors
AI-assisted analysis of datawhalechina/hello-agents@606a07d341 (2026-08-14).
Data as JSON: /api/errors/15943908cf124833.
Report an issue: GitHub.