{T}

地图智能体

百度地图智能体是基于AI大模型的智能位置服务,提供自然语言交互、智能推荐、智能问答等能力,让地图服务更加智能化。

概述

地图智能体融合了百度领先的AI技术和丰富的地图数据,能够理解用户的自然语言请求,提供智能化的位置服务。

核心能力

plaintext
┌─────────────────────────────────────────────────────────────────┐
│                      地图智能体架构                               │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    自然语言理解 (NLU)                     │   │
│  │           意图识别 / 实体抽取 / 语义理解                  │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              ▼                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    知识图谱 & 地图数据                     │   │
│  │         POI数据 / 路网数据 / 实时路况 / 用户画像          │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              ▼                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    推理决策引擎                           │   │
│  │          路径规划 / 智能推荐 / 问答生成                   │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              ▼                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    自然语言生成 (NLG)                     │   │
│  │           答案生成 / 结果呈现 / 语音合成                  │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

AI向导

AI向导是百度地图推出的智能对话服务,支持自然语言查询地点、规划路线、获取信息等。

应用场景

场景示例问题返回内容
地点推荐帮我在附近10公里内找个看荷花的公园推荐公园列表
美食搜索附近有什么好吃的火锅火锅店列表
停车查询找一下北京动物园附近的停车场停车场列表
餐厅推荐在百度大厦附近找个适合聚餐、有包厢的饭店餐厅推荐
酒店推荐推荐一下北京站附近适合一家三口住的旅馆酒店推荐
路线规划从北京西站到首都机场怎么走最快路线方案
信息问询今天北京天气怎么样天气信息
实时路况京津高速现在堵车吗路况信息

API接入

请求接口

javascript
const query = '帮我在附近找个看荷花的公园';
const location = '116.404,39.915';
 
fetch('https://api.map.baidu.com/ai_guide/v1/query', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    query: query,
    location: location,
    ak: '您的密钥',
    session_id: '会话ID'  // 可选,用于多轮对话
  })
})
.then(response => response.json())
.then(data => {
  console.log('AI回复:', data.answer);
  console.log('推荐地点:', data.places);
});

请求参数

参数必填类型说明
queryString用户问题
locationString用户位置(纬度,经度)
akString密钥
session_idString会话ID,用于多轮对话
cityString城市
user_idString用户ID
contextObject上下文信息

响应格式

json
{
  "status": 0,
  "message": "ok",
  "session_id": "xxx-xxx-xxx",
  "answer": "为您推荐以下看荷花的公园...",
  "places": [
    {
      "name": "颐和园",
      "address": "北京市海淀区新建宫门路19号",
      "location": {
        "lng": 116.275,
        "lat": 39.999
      },
      "distance": 5000,
      "rating": 4.8,
      "tags": ["公园", "荷花", "皇家园林"],
      "telephone": "010-62881144",
      "opening_hours": "06:30-18:00",
      "ticket_price": "30元"
    }
  ],
  "suggestions": ["查看详情", "开始导航", "查看评价"],
  "intent": "place_recommend",
  "confidence": 0.95
}

结果解析

javascript
// 解析AI向导响应
function parseAIResponse(data) {
  if (data.status !== 0) {
    throw new Error(`API错误: ${data.message}`);
  }
 
  const result = {
    answer: data.answer,
    intent: data.intent,
    confidence: data.confidence,
    sessionId: data.session_id,
    places: [],
    suggestions: data.suggestions || []
  };
 
  // 解析地点列表
  if (data.places && data.places.length > 0) {
    result.places = data.places.map(place => ({
      name: place.name,
      address: place.address,
      location: {
        lng: place.location.lng,
        lat: place.location.lat
      },
      distance: place.distance,
      rating: place.rating,
      tags: place.tags || [],
      telephone: place.telephone,
      openingHours: place.opening_hours,
      ticketPrice: place.ticket_price
    }));
  }
 
  return result;
}
 
// 使用示例
const response = await fetchAIQuery('附近有什么好吃的火锅');
const result = parseAIResponse(response);
 
console.log('AI回复:', result.answer);
result.places.forEach(place => {
  console.log(`${place.name} - ${place.address} - ${place.distance}米`);
});

多轮对话管理

javascript
class AIConversation {
  constructor(ak, sessionId = null) {
    this.ak = ak;
    this.sessionId = sessionId || this.generateSessionId();
    this.messages = [];
    this.context = {};
  }
 
  generateSessionId() {
    return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }
 
  async send(query, location = null) {
    // 添加用户消息
    this.messages.push({
      role: 'user',
      content: query,
      timestamp: Date.now()
    });
 
    // 构建请求
    const requestBody = {
      query: query,
      ak: this.ak,
      session_id: this.sessionId,
      context: this.context
    };
 
    if (location) {
      requestBody.location = location;
    }
 
    // 发送请求
    const response = await fetch('https://api.map.baidu.com/ai_guide/v1/query', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(requestBody)
    });
 
    const data = await response.json();
 
    // 添加AI回复
    if (data.status === 0) {
      this.messages.push({
        role: 'assistant',
        content: data.answer,
        places: data.places,
        timestamp: Date.now()
      });
 
      // 更新上下文
      this.context = {
        lastIntent: data.intent,
        lastPlaces: data.places ? data.places.map(p => p.name) : []
      };
    }
 
    return data;
  }
 
  // 获取对话历史
  getHistory() {
    return this.messages;
  }
 
  // 清除对话历史
  clear() {
    this.messages = [];
    this.sessionId = this.generateSessionId();
    this.context = {};
  }
 
  // 撤销最后一条消息
  undo() {
    if (this.messages.length > 0) {
      this.messages.pop();
    }
  }
}
 
// 使用示例
const conversation = new AIConversation('您的密钥');
 
// 第一轮对话
const reply1 = await conversation.send('我想找个吃饭的地方');
console.log(reply1.answer);
 
// 第二轮对话(上下文关联)
const reply2 = await conversation.send('有川菜吗');
console.log(reply2.answer);
 
// 第三轮对话
const reply3 = await conversation.send('有包厢吗');
console.log(reply3.answer);
 
// 查看对话历史
console.log(conversation.getHistory());

智能推荐

个性化推荐

基于用户偏好和历史行为,提供个性化地点推荐。

javascript
fetch('https://api.map.baidu.com/ai_recommend/v1/places', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    user_id: '用户ID',
    location: '116.404,39.915',
    category: 'restaurant',
    preferences: {
      price_level: [2, 3],          // 价格区间
      cuisine: ['川菜', '粤菜'],      // 菜系偏好
      facilities: ['包厢', '停车场'], // 设施需求
      rating_min: 4.0               // 最低评分
    },
    ak: '您的密钥'
  })
});

推荐参数详解

参数类型说明
user_idString用户唯一标识
locationString用户当前位置
categoryString推荐类别:restaurant/hotel/scenic
radiusNumber搜索半径(米)
limitNumber返回结果数量
preferencesObject用户偏好设置
excludeArray排除的地点ID

场景化推荐

根据特定场景智能推荐:

javascript
const sceneRecommend = {
  // 场景类型
  scene: 'family_dinner',        // 家庭聚餐
  people_count: 5,               // 人数
  budget: 500,                   // 预算
  location: '116.404,39.915',
  requirements: ['儿童座椅', '包厢', '不辣'],
  time: '2024-01-15 18:00'       // 用餐时间
};
 
// 场景类型说明
const sceneTypes = {
  family_dinner: '家庭聚餐',
  business_meal: '商务宴请',
  date: '约会',
  gathering: '朋友聚会',
  birthday: '生日聚会'
};
 
fetch('https://api.map.baidu.com/ai_recommend/v1/scene', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    ...sceneRecommend,
    ak: '您的密钥'
  })
});

推荐结果解析

json
{
  "status": 0,
  "result": {
    "places": [
      {
        "name": "川味轩",
        "score": 95,
        "match_reasons": ["符合预算", "有包厢", "适合家庭聚餐"],
        "detail": {
          "avg_price": 85,
          "rating": 4.6,
          "features": ["包厢", "儿童座椅", "停车场"]
        }
      }
    ],
    "total": 10,
    "scene_insights": {
      "best_time": "建议17:30到店,避免排队",
      "tips": ["建议提前预约包厢", "该店有儿童套餐"]
    }
  }
}

智能问答

知识问答类型

类型示例问题返回内容
景点信息故宫门票多少钱?景点详细信息
交通信息地铁1号线首班车几点?交通线路信息
天气查询今天北京天气怎么样?天气预报
生活服务附近哪有ATM机?POI信息
路况信息京津塘高速堵车吗?实时路况
换乘查询从西单到国贸怎么走?换乘方案

问答请求

javascript
const questions = [
  '北京有什么好玩的地方?',
  '故宫门票多少钱?',
  '颐和园开放时间是什么?',
  '长城怎么去?'
];
 
async function askQuestion(question) {
  const response = await fetch('https://api.map.baidu.com/ai_qa/v1/query', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      query: question,
      ak: '您的密钥'
    })
  });
 
  return response.json();
}
 
// 批量问答
async function batchQA(questions) {
  const results = [];
  for (const q of questions) {
    const answer = await askQuestion(q);
    results.push({
      question: q,
      answer: answer.result.answer,
      sources: answer.result.sources
    });
  }
  return results;
}

智能语音

语音识别

将语音转换为文本进行查询:

javascript
// 录音并识别
async function recordAndRecognize() {
  // 获取麦克风权限
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  const mediaRecorder = new MediaRecorder(stream);
  const audioChunks = [];
 
  mediaRecorder.ondataavailable = event => {
    audioChunks.push(event.data);
  };
 
  mediaRecorder.start();
 
  // 录制3秒
  await new Promise(resolve => setTimeout(resolve, 3000));
 
  mediaRecorder.stop();
 
  // 等待录制完成
  const audioBlob = await new Promise(resolve => {
    mediaRecorder.onstop = () => {
      resolve(new Blob(audioChunks, { type: 'audio/wav' }));
    };
  });
 
  // 发送识别请求
  const formData = new FormData();
  formData.append('audio', audioBlob);
  formData.append('ak', '您的密钥');
 
  const response = await fetch('https://api.map.baidu.com/voice/v1/asr', {
    method: 'POST',
    body: formData
  });
 
  return response.json();
}

语音合成

将文本转换为语音播报:

javascript
async function textToSpeech(text) {
  const response = await fetch('https://api.map.baidu.com/voice/v1/tts', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      text: text,
      voice: 0,        // 发音人:0女声,1男声
      speed: 5,        // 语速:0-9
      pitch: 5,        // 音调:0-9
      volume: 5,       // 音量:0-9
      ak: '您的密钥'
    })
  });
 
  const data = await response.json();
  
  // 播放语音
  if (data.status === 0) {
    const audio = new Audio(data.result.audio_url);
    audio.play();
  }
}
 
// 导航播报示例
const navigationText = '前方500米右转进入主路,请注意前方有测速摄像头';
textToSpeech(navigationText);

智能导航

实时路况播报

javascript
const navigation = {
  route_id: '路线ID',
  current_location: '116.404,39.915',
  destination: '116.308,40.056'
};
 
fetch('https://api.map.baidu.com/navigation/v1/status', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    ...navigation,
    ak: '您的密钥'
  })
})
.then(response => response.json())
.then(data => {
  console.log('前方路况:', data.traffic_status);
  console.log('预计到达:', data.eta);
  console.log('建议路线:', data.suggested_route);
 
  // 播报路况
  if (data.traffic_alert) {
    textToSpeech(data.traffic_alert);
  }
});

智能避堵

javascript
const avoidCongestion = {
  origin: '116.404,39.915',
  destination: '116.308,40.056',
  avoid_traffic: true,
  real_time_update: true,
  update_interval: 30  // 更新间隔(秒)
};
 
// 实时监控路况
function monitorTraffic(routeId) {
  setInterval(async () => {
    const status = await getRouteStatus(routeId);
    
    if (status.has_congestion) {
      // 发现拥堵,重新规划
      const newRoute = await replanRoute(avoidCongestion);
      notifyRouteChange(newRoute);
    }
  }, 30000);
}

API限制说明

配额限制

服务类型免费配额QPS限制说明
AI向导1,000次/日10需申请开通
智能推荐1,000次/日10需申请开通
语音识别500次/日5需申请开通
语音合成1,000次/日10需申请开通
智能问答2,000次/日20需申请开通

请求限制

限制项限制值
单次请求文本长度500字符
单次请求音频时长60秒
会话最大轮数20轮
会话有效期30分钟

使用限制

  1. 服务开通:智能服务需要单独申请开通
  2. 数据安全:不得存储用户敏感信息
  3. 使用场景:仅限合法合规场景
  4. 版权声明:需标注"由百度地图AI提供"

开发者沙龙

百度地图定期举办开发者沙龙活动,深入介绍AI向导接口服务的典型能力、优势特点、应用场景和接入流程。

活动内容

  • AI向导接口服务能力介绍
  • 典型应用场景演示
  • 接入流程详解
  • 最佳实践分享

最佳实践

错误处理

javascript
async function aiQuery(query) {
  try {
    const response = await fetch(url, options);
    const data = await response.json();
    
    if (data.status !== 0) {
      throw new Error(data.message || `错误码: ${data.status}`);
    }
    
    return data;
  } catch (error) {
    console.error('AI查询失败:', error);
    return {
      status: -1,
      answer: '抱歉,服务暂时不可用,请稍后再试。',
      places: []
    };
  }
}

请求重试

javascript
async function retryableQuery(query, maxRetries = 3) {
  let lastError;
  
  for (let i = 0; i < maxRetries; i++) {
    try {
      const result = await aiQuery(query);
      if (result.status === 0) {
        return result;
      }
    } catch (error) {
      lastError = error;
      // 指数退避
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
    }
  }
  
  throw lastError;
}

结果缓存

javascript
const cache = new Map();
const CACHE_TTL = 5 * 60 * 1000;
 
async function queryWithCache(query) {
  const key = `${query}_${location}`;
  
  if (cache.has(key)) {
    const cached = cache.get(key);
    if (Date.now() - cached.time < CACHE_TTL) {
      return cached.data;
    }
  }
  
  const result = await aiQuery(query);
  cache.set(key, { data: result, time: Date.now() });
  
  return result;
}

前端集成示例

javascript
// 完整的前端AI向导组件
class AIGuideComponent {
  constructor(options) {
    this.ak = options.ak;
    this.conversation = new AIConversation(this.ak);
    this.container = document.getElementById(options.containerId);
    this.init();
  }
 
  init() {
    this.render();
    this.bindEvents();
  }
 
  render() {
    this.container.innerHTML = `
      <div class="ai-guide">
        <div class="messages" id="messages"></div>
        <div class="input-area">
          <input type="text" id="queryInput" placeholder="请输入您的问题">
          <button id="sendBtn">发送</button>
        </div>
      </div>
    `;
  }
 
  bindEvents() {
    const input = document.getElementById('queryInput');
    const sendBtn = document.getElementById('sendBtn');
 
    sendBtn.addEventListener('click', () => this.handleSend());
    input.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') this.handleSend();
    });
  }
 
  async handleSend() {
    const input = document.getElementById('queryInput');
    const query = input.value.trim();
    if (!query) return;
 
    // 显示用户消息
    this.addMessage('user', query);
    input.value = '';
 
    // 发送请求
    this.showLoading();
    const response = await this.conversation.send(query);
    this.hideLoading();
 
    // 显示AI回复
    this.addMessage('assistant', response.answer, response.places);
  }
 
  addMessage(role, content, places = []) {
    const messagesDiv = document.getElementById('messages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}`;
    messageDiv.innerHTML = `<div class="content">${content}</div>`;
    
    if (places.length > 0) {
      messageDiv.innerHTML += `
        <div class="places">
          ${places.map(p => `
            <div class="place-item" data-lng="${p.location.lng}" data-lat="${p.location.lat}">
              <strong>${p.name}</strong>
              <p>${p.address}</p>
              <span>${p.distance}米</span>
            </div>
          `).join('')}
        </div>
      `;
    }
    
    messagesDiv.appendChild(messageDiv);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
  }
 
  showLoading() {
    // 显示加载动画
  }
 
  hideLoading() {
    // 隐藏加载动画
  }
}

下一步