旅行聊天机器人

一款基于Google Gemini和FastMCP的智能旅行助手,提供个性化的旅行推荐和实时对话服务。

  • by lakshaydadhich
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 lakshaydadhich/MCP-MODEL-CONTROL-PROTOCOL-

使用说明

🌍 旅游MCP聊天机器人

由Google Gemini和模型上下文协议(MCP)支持的智能对话式旅行助手

特性 • 快速开始 • 建筑 • 用法 • 贡献


📖 概述

Travel MCP聊天机器人是一款智能旅行助手,利用 谷歌双子座2.5 和 FastMCP 提供个性化的旅行建议。与具有硬编码响应的传统聊天机器人不同,该系统动态决定是根据LLM的知识进行回答还是调用专门的MCP工具。

🎯 是什么让它特别?

  • 🧠 智能路由:自动确定何时使用LLM与MCP工具
  • 💬 对话记忆:记住整个对话的背景
  • 🎨 自然语言:没有严格的命令-只需自然聊天
  • 🔧 模块化设计:使用新的MCP服务器轻松扩展
  • 🚀 零硬编码所有的智慧都来自双子座

✨ 特性

特性 描述
🏛️ 地点 探索顶级旅游景点和地标
🍜 食物 获取当地美食和必尝菜肴的推荐
🏨 酒店 根据预算偏好寻找住宿
🧠 上下文记忆 通过问题记住您的目的地
💰 预算意识 自动提取并记住预算偏好
🔄 后续行动 具有上下文切换的自然对话流
⚡ 实时 带有视觉反馈的实时MCP工具调用

🏗️ 建筑

graph TD
    A[User Question] --> B[MCP Client]
    B --> C[Gemini LLM]
    C --> D{Need MCP Tool?}
    D -->|No| E[Direct LLM Response]
    D -->|Yes| F[Parse Intent & Extract Parameters]
    F --> G{Which Tools?}
    G -->|Places| H[Places MCP Server]
    G -->|Food| I[Food MCP Server]
    G -->|Hotels| J[Hotels MCP Server]
    H --> K[Combine Results]
    I --> K
    J --> K
    K --> L[Gemini Synthesizes Answer]
    L --> M[User Response]
    E --> M

🔄 运作原理

  1. 用户提问 → 自然语言输入
  2. 双子座分析意图 → 确定需要哪些工具
  3. 提取的参数 → 城市、预算、偏好
  4. MCP工具被称为 → 仅联系相关服务器
  5. 综合结果 → 双子座创造有凝聚力的反应
  6. 上下文已更新 → 记住后续问题

📁 项目结构

travel-mcp-chatbot/
│
├── 📂 client/
│   ├── mcp_client.py              # Original client
│   └── mcp_chatbot_enhanced.py    # ✨ Enhanced chatbot with memory
│
├── 📂 servers/
│   ├── food_server.py             # 🍜 Food recommendations MCP server
│   ├── hotels_server.py           # 🏨 Hotel suggestions MCP server
│   └── places_server.py           # 🏛️ Tourist places MCP server
│
├── 📂 docs/
│   ├── ENHANCEMENTS.md            # Detailed enhancement guide
│   └── examples.md                # Usage examples
│
├── 🔒 .env                        # API keys (not in git)
├── ⚙️ mcp.json                    # MCP server configuration
├── 📦 requirements.txt            # Python dependencies
├── 🧪 test_gemini.py             # Gemini API test
└── 📖 README.md                   # You are here!

🚀 快速开始

先决条件

1.️⃣ 克隆存储库

git clone https://github.com/your-username/travel-mcp-chatbot.git
cd travel-mcp-chatbot

2.️⃣ 设置环境

# Create virtual environment
python -m venv venv

# Activate virtual environment
# Windows:
venv\Scripts\activate
# Mac/Linux:
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

3.️⃣ 配置API密钥

创建一个 .env 根目录中的文件:

GOOGLE_API_KEY=your_gemini_api_key_here

⚠️ 安全说明:永远不要承诺你的 .env 文件到版本控制!

4.️⃣ 配置MCP服务器

确保 mcp.json 设置正确:

{
  "client": {
    "model": "gemini-2.5-flash"
  },
  "servers": [
    {
      "name": "tour-places",
      "url": "http://127.0.0.1:8001/mcp",
      "tools": ["top_places_to_visit"]
    },
    {
      "name": "tour-food",
      "url": "http://127.0.0.1:8002/mcp",
      "tools": ["top_food_to_try"]
    },
    {
      "name": "tour-hotels",
      "url": "http://127.0.0.1:8003/mcp",
      "tools": ["top_hotels_to_stay"]
    }
  ]
}

5.️⃣ 启动MCP服务器

打开 三个独立的终端 并运行:

# Terminal 1 - Places Server
fastmcp run servers/places_server.py:mcp --transport http --port 8001

# Terminal 2 - Food Server
fastmcp run servers/food_server.py:mcp --transport http --port 8002

# Terminal 3 - Hotels Server
fastmcp run servers/hotels_server.py:mcp --transport http --port 8003

6.️⃣ 启动聊天机器人

# In a new terminal
cd client
python mcp_chatbot_enhanced.py

💬 使用示例

🎬 示例1:单主题查询

You: What are the top places to visit in Paris?

🔍 Looking up top_places_to_visit for Paris...

🤖 Here are the must-visit places in Paris:

• Eiffel Tower - The iconic iron tower offering stunning city views
• Louvre Museum - World's largest art museum, home to Mona Lisa
• Notre-Dame Cathedral - Gothic masterpiece (currently under restoration)
• Arc de Triomphe - Monument honoring French military victories
• Sacré-Cœur - Beautiful basilica in Montmartre
• Champs-Élysées - Famous avenue for shopping and dining

Would you like recommendations for food or hotels as well?

🔄 示例2:对话式跟进

You: Tell me about Tokyo

🔍 Looking up top_places_to_visit for Tokyo...

🤖 [Tokyo attractions listed...]

You: What should I eat there?

🔍 Looking up top_food_to_try for Tokyo...

🤖 Here are must-try foods in Tokyo:

• Sushi - Fresh from Tsukiji Outer Market
• Ramen - Try Ichiran or local ramen-ya
• Tempura - Light, crispy perfection
• Tonkatsu - Breaded pork cutlet
...

You: Budget hotels please

🔍 Looking up top_hotels_to_stay for Tokyo...

🤖 Great budget options in Tokyo:

Shinjuku Area:
• Capsule Inn - Unique Japanese experience
• Kimi Ryokan - Traditional budget accommodation
...

🎯 示例3:综合查询

You: I'm planning a trip to Barcelona - what should I see, eat, and where should I stay on a midrange budget?

🔍 Looking up top_places_to_visit, top_food_to_try, top_hotels_to_stay for Barcelona...

🤖 Here's your complete Barcelona guide:

📍 Top Places to Visit:
• La Sagrada Familia
• Park Güell
• Las Ramblas
...

🍽️ Must-Try Foods:
• Paella
• Tapas
• Crema Catalana
...

🏨 Midrange Hotels:
Gothic Quarter:
• Hotel Barcelona Cathedral
...

🔀 示例4:上下文切换

You: Top attractions in Rome

🤖 [Rome attractions...]

You: Actually, let's talk about Venice instead

🔍 Looking up top_places_to_visit for Venice...

🤖 [Venice attractions...]

You: And food?

🔍 Looking up top_food_to_try for Venice...

🤖 [Venice food - still remembers Venice context]

🎨 主要区别:原版与增强版

Feature Original Enhanced ✨
Conversation Flow ❌ Separate input prompts ✅ Natural chat loop
Context Memory ❌ None ✅ Remembers city & budget
Follow-up Questions ❌ Must repeat city ✅ Natural follow-ups
Budget Handling ⚠️ Manual input ✅ Auto-extracted from text
Error Messages ⚠️ Basic ✅ User-friendly
Progress Feedback ❌ None ✅ Visual indicators
Multi-tool Support ✅ Yes ✅ Yes, improved routing
Conversation History ❌ No ✅ Last 3 exchanges

🧪 测试

测试Gemini连接

python test_gemini.py

预期产量:

✅ Gemini API is working!
Response: [Gemini's response to test query]

测试MCP服务器

# Test Places Server
curl http://127.0.0.1:8001/mcp

# Test Food Server
curl http://127.0.0.1:8002/mcp

# Test Hotels Server
curl http://127.0.0.1:8003/mcp

🔧 配置

MCP服务器配置

每台服务器 mcp.json 要求:

  • name:唯一服务器标识符
  • url:MCP端点URL
  • tools:可用工具名称列表

Gemini模型选择

更改模型 mcp.json:

{
  "client": {
    "model": "gemini-2.5-flash"  // or "gemini-2.5-pro"
  }
}

上下文窗口大小

在中调整对话历史记录 mcp_chatbot_enhanced.py:

recent = conversation_history[-3:]  # Last 3 exchanges (adjust number)

🎯 如何验证工具与LLM响应

✅ MCP工具的响应

指标:

  • 控制台显示: 🔍 Looking up [tool_names] for [city]...
  • 数据来自 servers/*.py
  • 结构化、真实的信息

例子:

🔍 Looking up top_places_to_visit for Paris...
🤖 [Detailed place list with descriptions]

✅ 仅来自LLM的回复

指标:

  • 不 🔍 控制台中的消息
  • 纯会话文本
  • 一般知识回答

例子:

You: Thanks!
🤖 You're welcome! Have a wonderful trip! ✈️

🛠️ 扩展聊天机器人

添加新的MCP服务器

1.创建服务器文件

# servers/activities_server.py
from fastmcp import FastMCP
import google.generativeai as genai

mcp = FastMCP("tour-activities")

@mcp.tool
def top_activities(city: str) -> str:
    """Get top activities and experiences in a city."""
    # Your implementation
    return response

if __name__ == "__main__":
    mcp.run()

2.更新 mcp.json

{
  "servers": [
    {
      "name": "tour-activities",
      "url": "http://127.0.0.1:8004/mcp",
      "tools": ["top_activities"]
    }
  ]
}

3.更新意图解析器

在 mcp_chatbot_enhanced.py,添加工具描述:

Tool descriptions:
- top_places_to_visit: Returns tourist attractions and landmarks
- top_food_to_try: Returns local cuisine and food recommendations
- top_hotels_to_stay: Returns hotel and accommodation recommendations
- top_activities: Returns activities and experiences  # ← Add this

4.启动新服务器

fastmcp run servers/activities_server.py:mcp --transport http --port 8004

🐛 故障排除

❌ MCP Server Connection Failed

解决方案:

  1. 验证服务器是否正在运行: curl http://127.0.0.1:8001/mcp
  2. 检查中的端口号 mcp.json 匹配服务器端口
  3. 确保虚拟环境已激活
  4. 检查防火墙设置
❌ Gemini API Error

解决方案:

  1. 在中验证API密钥 .env 文件
  2. 检查密钥有效性 谷歌AI工作室
  3. 确保不超过费率限制
  4. 检查互联网连接
❌ JSON Parse Error

解决方案: 增强版本会自动处理此问题:

.replace("```json", "").replace("```", "")

如果仍然发生,请检查Gemini的响应格式。

❌ City Not Detected

解决方案:

  1. 在第一条信息中明确:“告诉我巴黎的情况”
  2. 检查意图解析器是否收到问题
  3. 在提示中添加更多示例
  4. 机器人会问城市是否不清楚
❌ Wrong Tool Called

解决方案:

  1. 使问题更具体
  2. 在意图解析器提示中添加示例
  3. 检查工具说明是否清晰
  4. 查看对话上下文

📊 性能提示

  • 响应时间:MCP呼叫需要2-5秒,具体取决于工具
  • 速率限制:双子座免费版:15转/分,付费版:1000转/分
  • 缓存:考虑为常见查询实现响应缓存
  • 批量呼叫:尽可能并行调用多个工具

🗺️ 路线图

近期

  • [x]✅ 对话记忆
  • [x]✅ 情境感知跟进
  • [x]✅ 预算偏好提取
  • [ ] 🔄 将对话导出到文件
  • [ ] 🔄 跨会话的持久上下文

中期

  • [ ] 🌐 实时API集成(Google Places、TripAdvisor)
  • [ ] 🖥️ Web UI(流媒体/渐变)
  • [ ] 🗣️ 语音输入/输出
  • [ ] 📅 带日期的行程生成
  • [ ] 💾 用户偏好配置文件

长期

  • [ ] 🧠 RAG与旅游指南的整合
  • [ ] 🌍 多语言支持
  • [ ] 🤝 多城市出行规划
  • [ ] 📱 移动应用程序
  • [ ] 🔗 与预订平台集成

📚 文档


🤝 贡献

欢迎投稿!方法如下:

  1. 克隆该仓库
  2. 创建要素分支(git checkout -b feature/amazing-feature)
  3. 提交更改(git commit -m 'Add amazing feature')
  4. 推送到分支(git push origin feature/amazing-feature)
  5. 打开拉取请求

开发设置

# Install dev dependencies
pip install -r requirements-dev.txt

# Run tests
pytest tests/

# Format code
black .

📄 许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。


🙏 致谢

  • 谷歌双子座 -强大的LLM功能
  • FastMCP -简化的MCP服务器实现
  • Anthropic -模型上下文协议规范

👨‍💻 作者

莱沙伊·达迪奇

  • 🔬 数据科学|人工智能/机器学习|数据分析
  • 🧠 LLM系统与代理开发

💡 灵感

旨在展示组合的力量:

  • 🤖 大型语言模型(Gemini)
  • 🔧 模型上下文协议(MCP)
  • 💬 自然对话设计
  • 🧠 上下文感知系统

⭐ 如果你觉得这很有帮助,可以考虑给它一颗星!

由...制作❤️ 使用Python、Gemini和FastMCP

返回页首↑