市场情报AI聊天机器人

一个基于FastAPI和LangGraph的AI市场情报聊天机器人,提供实时股票数据、市场新闻和金融分析,支持自然语言对话。

  • by mohdjami
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 mohdjami/mcp-chatbot

使用说明

🚀 市场情报AI聊天机器人 - 完整项目README

📋 快速概览

一个可投入生产的AI驱动市场情报聊天机器人,通过自然对话提供实时股票数据、市场新闻和财务分析。该机器人采用……构建(注:原文在此处截断,未提供具体构建技术或方法,因此翻译时保留了这一开放性) FastAPI, LangGraph, OpenAI GPT-4,以及 模型上下文协议(MCP) 用于模块化工具集成。

🌐 实时部署:

  • 聊天机器人API这个网址的中文翻译可以是:“https://mcp-chatbot-生产环境.up.railway.app” 或者简化为 “mcp-chatbot-生产应用网址(up.railway.app)”。不过,通常我们不会直接翻译网址,而是根据网址的内容和上下文来解释其含义。在这里,网址可能指向的是一个名为“mcp-chatbot”的聊天机器人应用在某个铁路应用平台(如Railway)上的生产环境部署地址
  • MCP 服务器https://mcp-chatbot-production-f2f9.up.railway.app/mcp(该网址可直接翻译为中文表述,但网址本身通常不翻译,保持原样)
  • 前端待测试https://mkt-wise-bot.lovable.app/(这个网址本身在中文中不直接翻译,但可以描述为):“可爱应用上的Mkt-Wise机器人网站”(注:实际翻译时,网址通常保持原样,这里只是对网址内容的一种意译说明)。不过,在实际应用中,网址一般直接保留,不进行翻译

🎯 项目概述

这个项目不仅满足了实习任务的所有要求,还额外具备多项加分项功能:

✅ 核心要求

  • ✅ 后端服务 在MCP服务器架构上运行
  • ✅ 基于Python的 实现(FastAPI + LangGraph)
  • ✅ 人工智能聊天机器人 问题间具有上下文记忆
  • ✅ 表示“正确”或“已确认”。 市场/金融数据 能力
  • ✅ 可公开测试的API 可通过curl访问的端点
  • ✅ 托管并部署 在铁路(上)

⭐ 实施的奖励功能

  • ⭐ 流式传输端点 为了实时聊天体验(如ChatGPT)
  • ⭐ Redis 缓存 以提高性能
  • ⭐ 速率限制 为API保护
  • ⭐ 工具验证 - 显示实际使用了哪些MCP工具
  • ⭐ 全面的错误处理 附带有用的提示信息
  • ⭐ 可投入生产的架构 支持Docker
  • ⭐ 完整的文件记录 (以……为例)

🏗️ 架构概览

┌─────────────────────────────────────────────────────────────────┐
│                         USER / CLIENT                            │
│                 (curl, Postman, Frontend App)                    │
└────────────────────────────┬────────────────────────────────────┘
                             │ HTTP/HTTPS
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│              CHATBOT BACKEND (FastAPI + LangGraph)              │
│         https://mcp-chatbot-production.up.railway.app           │
│                                                                  │
│  ┌────────────────────────────────────────────────────────────┐ │
│  │  Endpoints:                                                 │ │
│  │  • POST /query      - Non-streaming responses              │ │
│  │  • POST /stream     - Real-time streaming (SSE)            │ │
│  │  • GET  /health     - Health check                         │ │
│  └────────────────────────────────────────────────────────────┘ │
│                                                                  │
│  ┌────────────────────────────────────────────────────────────┐ │
│  │  LangGraph Agent:                                           │ │
│  │  • OpenAI GPT-4o-mini for reasoning                        │ │
│  │  • MemorySaver for conversation context                    │ │
│  │  • Agentic workflow (decides when to use tools)            │ │
│  └────────────────────────────────────────────────────────────┘ │
│                                                                  │
│  ┌────────────────────────────────────────────────────────────┐ │
│  │  Bonus Features:                                            │ │
│  │  • Redis caching (reduces API calls)                       │ │
│  │  • Rate limiting (token bucket algorithm)                  │ │
│  │  • CORS middleware                                          │ │
│  │  • Comprehensive error handling                            │ │
│  └────────────────────────────────────────────────────────────┘ │
└────────────────────────────┬────────────────────────────────────┘
                             │ MCP Protocol (Streamable HTTP)
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│           MCP SERVER (Remote Market Intelligence Tools)         │
│      https://mcp-chatbot-production-f2f9.up.railway.app/mcp    │
│                                                                  │
│  ┌────────────────────────────────────────────────────────────┐ │
│  │  5 Market Intelligence Tools:                               │ │
│  │                                                              │ │
│  │  1. get_stock_price      - Real-time stock data            │ │
│  │  2. get_market_news      - Latest financial news           │ │
│  │  3. get_stock_history    - Historical price data           │ │
│  │  4. compare_stocks       - Multi-stock comparison          │ │
│  │  5. get_market_summary   - Major indices overview          │ │
│  └────────────────────────────────────────────────────────────┘ │
│                                                                  │
│  Data Sources:                                                   │
│  • Yahoo Finance (yfinance) - Stock data                        │
│  • NewsAPI - Financial news articles                            │
└─────────────────────────────────────────────────────────────────┘

🧪 测试API

1. 基本查询(非流式)

# Simple question about stock price
curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What is the current price of Apple stock?"
  }'

预期响应:

{
  "response": "Apple (AAPL) is currently trading at $178.25, up $0.75 (+0.42%) from yesterday's close of $177.50. The stock has a market cap of approximately $2.8 trillion. The stock is performing well today with a day high of $179.50 and day low of $177.80.",
  "session_id": "abc-123-def-456",
  "tools_used": ["get_stock_price"]
}

2. 上下文感知对话

# First message - establish context
curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What is Tesla stock price?",
    "session_id": "my-session-123"
  }'

# Follow-up - remembers we're talking about Tesla
curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "How does it compare to yesterday?",
    "session_id": "my-session-123"
  }'

3. 市场新闻查询

curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Give me the latest news about tech stocks"
  }'

4. 股票对比

curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Compare Apple, Microsoft, and Google stocks"
  }'

5. 历史数据

curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Show me Amazon stock performance over the last 6 months"
  }'

6. 市场概览

curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "How are the major market indices doing today?"
  }'

7. 🌟 奖励:流式响应(实时)

# Stream responses token-by-token like ChatGPT
curl -N -X POST https://mcp-chatbot-production.up.railway.app/stream \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What is Apple stock trading at right now?"
  }'

预期的流输出:

event: message
data: {"type": "tool_call", "tool": "get_stock_price", "args": {"symbol": "AAPL"}}

event: message
data: {"type": "tool_executing", "message": "Fetching data..."}

event: message
data: {"type": "token", "content": "Apple "}

event: message
data: {"type": "token", "content": "(AAPL) "}

event: message
data: {"type": "token", "content": "is "}

event: message
data: {"type": "token", "content": "currently "}

...

event: message
data: {"type": "done", "tools_used": ["get_stock_price"], "session_id": "xxx"}

8. 健康检查

curl https://mcp-chatbot-production.up.railway.app/health

回答:

{
  "status": "healthy",
  "service": "Market Intelligence Chatbot",
  "agent_ready": true
}

📡 API 文档

交互式Swagger UI

访问: https://mcp-chatbot-production.up.railway.app/docs 翻译为中文是:“https://mcp-chatbot-production.up.railway.app/文档” 或者更自然地表达为:“https://mcp-chatbot-production.up.railway.app 的文档页面”

终点(或结果指标)

POST /query

非流式聊天查询终端

请求体:

{
  message: string;      // User's question (1-2000 chars)
  session_id?: string;  // Optional session ID for context
}

回答:

{
  response: string;      // AI assistant's response
  session_id: string;    // Session ID (generated if not provided)
  tools_used?: string[]; // MCP tools that were called
}

速率限制: 每个IP每分钟10个请求


POST /stream ⭐ 奖金

使用服务器发送事件实现实时流式响应

请求体: 与……相同 /query

回答: 服务器发送事件流,包含事件类型:

  • tool_call - 代理决定使用一个工具
  • tool_executing - 工具正在获取数据
  • token - 个体响应令牌(流式传输!)
  • done - 最终总结及使用工具清单
  • error - 发生错误

速率限制: 每个IP每分钟5个请求(由于资源使用限制,规定更严格)


GET /health

健康检查端点

回答:

{
  status: "healthy",
  service: string,
  agent_ready: boolean
}

🛠️ 技术栈

后端(聊天机器人)

  • FastAPI - 现代异步网络框架
  • LangGraph - 代理工作流编排
  • LangChain - 大语言模型(LLM)集成框架
  • OpenAI GPT-4o-mini(可译为“OpenAI的GPT-4o迷你版”或“OpenAI GPT-4o缩小型”) - 用于推理的语言模型
  • MCP 客户端 - 模型上下文协议客户端
  • Redis(Upstash) - 缓存和状态管理
  • Uvicorn(注:Uvicorn是一个用于构建异步ASGI服务器的Python库,直接翻译为中文即“乌维康”,但通常保留其英文原名以指代该特定库) - ASGI服务器

MCP 服务器(工具)

  • MCP SDK(MCP软件开发工具包) - 模型上下文协议服务器
  • yfinance(注:这是一个用于获取金融数据的Python库名称,直接翻译为中文可能无法准确传达其含义,但在此处按照要求仅翻译为中文字符形式) - 雅虎财经API用于股票数据
  • NewsAPI(新闻应用程序编程接口) - 金融新闻文章
  • aiohttp(一个用于异步网络请求的Python库) - 异步HTTP客户端
  • FastMCP - MCP服务器框架

部署

  • 铁路 - 云平台(两项服务)
  • Docker - 集装化
  • Python 3.11 - 运行时环境

🎨 关键特性解析

1. 上下文管理(内存节省功能)

聊天机器人会记住对话中的先前消息:

# Example conversation flow:
User: "What is Apple stock price?"
Bot: "Apple is trading at $178.25..."

User: "How does that compare to yesterday?"  # Remembers we're talking about Apple
Bot: "Apple's price is up $0.75 from yesterday's close of $177.50..."

其工作原理如下:

  • 每次对话都有其独特之处 session_id
  • LangGraph's MemorySaver 存储消息历史
  • 代理在回复时能够获取完整上下文

2. 🌟 流式响应(附加功能)

像ChatGPT那样的实时逐词流式传输:

好处:

  • 即时向用户反馈
  • 更好的用户体验(感觉更快)
  • 渐进式内容加载
  • 透明工具使用(在获取数据时显示)

实施:

  • 服务器发送事件(SSE)协议
  • Python中的异步生成器
  • LangGraph的流式处理能力

3. 🌟 Redis 缓存(附加功能)

减少API调用并提高响应时间:

缓存的内容是什么:

  • 股票价格数据(5分钟时效)
  • 市场新闻(有效期5分钟)
  • 历史数据(5分钟生存时间)
  • 工具结果(自动)

好处:

  • 更快的响应
  • 减少外部API的使用
  • 降低成本
  • 更高的可靠性

缓存命中示例:

First request:  ❌ Cache MISS → Fetch from yfinance → 2.5s
Second request: ✅ Cache HIT  → Return cached data → 0.1s

4. 🌟 速率限制(附加功能)

令牌桶算法防止滥用:

限制:

  • /query每个IP每分钟10个请求
  • /stream每个IP每分钟5个请求
  • /health无限制

当达到速率限制时的响应:

{
  "error": "Rate limit exceeded",
  "message": "Too many requests. Please try again in 45 seconds.",
  "retry_after": 45,
  "limit": 10,
  "window": "60 seconds"
}

返回的头部信息:

X-RateLimit-Limit: 10
X-RateLimit-Remaining: 7
X-RateLimit-Reset: 1697123456

5. 主体驱动的工作流

人工智能自主决定何时以及使用哪些工具:

流程:

  1. 用户提出问题
  2. 代理分析查询
  3. 代理决定:“我需要外部数据吗?”
  4. 如果是 → 选择适当的工具(们)
  5. 通过MCP执行工具(一个或多个)
  6. 将结果综合成自然语言
  7. 向用户返回响应

示例:

Query: "Compare Apple and Tesla, and give me tech news"

Agent thinks:
  ✓ Need stock data → use get_stock_price (AAPL)
  ✓ Need stock data → use get_stock_price (TSLA)
  ✓ Need news      → use get_market_news (tech)

Executes 3 tools, then synthesizes response.

6. MCP工具验证

每个回复都显示了实际使用了哪些工具:

{
  "response": "...",
  "tools_used": ["get_stock_price", "get_market_news"]
}

为何这很重要:

  • 调试时的透明度
  • 验证工具选择是否正确
  • 追踪工具使用模式
  • 验证代理行为

🔧 环境变量

聊天机器人后端

# Required
OPENAI_API_KEY=sk-your-openai-key

# MCP Configuration
MCP_TRANSPORT_PROTOCOL=http  # or "stdio" for local
MCP_SERVER_URL=https://mcp-chatbot-production-f2f9.up.railway.app/mcp

# Optional - Redis (Upstash)
UPSTASH_REDIS_REST_URL=https://your-redis.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-token

# Optional - Server
PORT=8080
LOG_LEVEL=INFO
OPENAI_MODEL=gpt-4o-mini

MCP 服务器

# Required
NEWS_API_KEY=your-newsapi-key

# Optional
PORT=8000
LOG_LEVEL=INFO
MCP_TRANSPORT_MODE=http  # For Railway deployment

📊 可用的MCP工具

1. get_stock_price(symbol: str)

获取实时股票价格和公司信息。

示例:

{
  "symbol": "AAPL",
  "company_name": "Apple Inc.",
  "current_price": 178.25,
  "previous_close": 177.50,
  "change": 0.75,
  "change_percent": 0.42,
  "volume": 45678900,
  "market_cap": 2800000000000,
  "day_high": 179.50,
  "day_low": 177.80,
  "52_week_high": 199.62,
  "52_week_low": 164.08
}

2. get_market_news(query: str, num_articles: int)

获取最新的财经新闻文章。

参数:

  • query搜索词(默认:“股市”)
  • num_articles文章数量(默认:5,最大:10)

示例:

[
  {
    "title": "Tech Stocks Rally on Strong Earnings",
    "description": "Major tech companies exceeded expectations...",
    "url": "https://example.com/article",
    "published_at": "2025-10-12T10:00:00Z",
    "source": "Financial Times",
    "author": "John Doe"
  }
]

3. get_stock_history(symbol: str, period: str)

用于技术分析的历史价格数据。

参数:

  • symbol股票代码
  • period1天,5天,1个月,3个月,6个月,1年,2年,5年,10年,年初至今,最大值

示例:

{
  "symbol": "AAPL",
  "period": "1mo",
  "data_points": 21,
  "start_date": "2025-09-12",
  "end_date": "2025-10-12",
  "latest_close": 178.25,
  "period_high": 182.50,
  "period_low": 170.30,
  "price_change": 7.95,
  "price_change_percent": 4.67,
  "average_volume": 55000000
}

4. compare_stocks(symbols: list[str])

并排比较多支股票(最多5支)。

示例:

{
  "comparison": {
    "AAPL": {
      "company_name": "Apple Inc.",
      "current_price": 178.25,
      "market_cap": 2800000000000,
      "pe_ratio": 29.5,
      "dividend_yield": 0.52,
      "52_week_high": 199.62,
      "52_week_low": 164.08,
      "beta": 1.25
    },
    "MSFT": { ... },
    "GOOGL": { ... }
  },
  "symbols_analyzed": 3
}

5. get_market_summary()

主要市场指数概览。

示例:

{
  "market_summary": {
    "S&P 500": {
      "symbol": "^GSPC",
      "value": 4567.89,
      "change": 23.45,
      "change_percent": 0.52,
      "high": 4589.12,
      "low": 4545.67
    },
    "Dow Jones Industrial Average": { ... },
    "NASDAQ Composite": { ... },
    "Russell 2000": { ... }
  }
}

🚀 部署详情

铁路配置

聊天机器人后端:

  • **URL(统一资源定位符)**https://mcp-chatbot-production.up.railway.app(该网址可直接翻译为中文表述,但网址本身通常不翻译,保持原样即可。若需说明,可表述为:“这个网址是:https://mcp-chatbot-production.up.railway.app”)
  • 港口8080(由铁路自动分配)
  • 构建Docker(Dockerfile)
  • 健康检查: /health 终端节点
  • 自动重启已启用

MCP 服务器:

  • **URL(统一资源定位符)**https://mcp-chatbot-production-f2f9.up.railway.app/mcp(中文翻译为):https://mcp-chatbot-production-f2f9.up.railway.app/mcp(注:网址本身无需翻译,保持原样即可,此处仅为说明翻译方式)
  • 端口8000(由铁路自动分配)
  • 构建Docker(Dockerfile)
  • 交通可流式传输的HTTP
  • 终端节点: /mcp (MCP协议)

Docker 镜像

两个服务都使用了Python 3.11 slim镜像:

FROM python:3.11-slim
# Optimized for production
# Includes health checks
# Runs as non-root user

💡 示例用例

1. 投资组合跟踪

curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "I own Apple, Tesla, and Amazon. How are they performing today?",
    "session_id": "portfolio-tracker"
  }'

2. 投资研究

# Multi-turn conversation
curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Tell me about NVIDIA stock",
    "session_id": "research-123"
  }'

curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What news is there about AI chip demand?",
    "session_id": "research-123"
  }'

curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Compare it to AMD",
    "session_id": "research-123"
  }'

3. 市场监测

curl -X POST https://mcp-chatbot-production.up.railway.app/query \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Give me a market overview and the latest financial news"
  }'

🎓 我所学到的东西

技术技能

  • MCP建筑事务所构建模块化、可重用的AI工具服务器
  • LangGraph创建带有状态管理的自主工作流
  • 异步Python高效处理并发操作
  • API设计RESTful原则和流媒体协议
  • 缓存策略使用Redis优化性能
  • 速率限制实现令牌桶算法
  • Docker & 部署容器化和云部署
  • 错误处理优雅降级与用户友好的错误提示

设计模式

  • **关注点分离(或称为“职责分离”)**MCP服务器 vs 聊天机器人后端
  • 微服务独立、可扩展的服务
  • 上下文管理器Python的 async with 用于资源清理
  • 中间件模式速率限制、跨域资源共享(CORS)、错误处理
  • 观察者模式使用SSE进行流式传输

最佳实践

  • 环境变量不要将秘密硬编码
  • 记录日志全面的日志记录用于调试
  • 健康检查监控服务可用性
  • 文档清晰的README和API文档
  • 测试用于轻松验证的curl命令

📁 项目结构

mcp-chatbot/
├── chatbot-backend/              # FastAPI chatbot service
│   ├── agent/
│   │   ├── graph.py             # LangGraph agent
│   │   └── state.py             # State schema
│   ├── mcp_client/
│   │   └── client.py            # MCP client wrapper
│   ├── utils/
│   │   ├── cache.py             # Redis caching
│   │   ├── rate_limiter.py      # Rate limiting
│   │   └── redis_client.py      # Redis connection
│   ├── main.py                  # FastAPI app
│   ├── requirements.txt
│   ├── Dockerfile
│   └── .env
├── mcp_server_remote.py         # Remote MCP server
├── mcp_server.py                # Local MCP server (stdio)
├── requirements.txt
├── Dockerfile
└── README.md                    # This file!

🤝 贡献与反馈

这个项目是为了实习选拔流程而构建的。欢迎提出反馈和建议!

联系方式:

  • GitHubhttps://github.com/mohdjami(该网址可译为:“GitHub上的mohdjami用户页面”,但通常网址本身不直接翻译,保持原样即可,此处为说明其含义)
  • 电子邮件mohdjamikhann@gmail.com(该邮箱地址直接翻译为中文无实际意义,保持原样即可)

📜 许可证

实习选拔流程的教育项目。


🙏 致谢

  • Anthropic(注:这是一个公司或组织的名称,直接翻译可能无法准确传达其含义,因此在这里保留原英文形式,但根据上下文,可以理解为“人类中心主义的”或“以人为本的”等含义,具体需结合上下文判断) - 对于模型上下文协议(MCP)
  • LangChain/LangGraph(可译为“语言链/语言图”,但具体翻译可能需根据上下文调整,以保持术语的一致性和准确性) - 用于代理工作流框架
  • OpenAI(开放人工智能研究所) 对于GPT-4 API
  • 铁路 - 对于免费托管层级
  • 雅虎财经 - 用于股票市场数据
  • NewsAPI(新闻应用程序编程接口) - 用于财经新闻

📚 额外资源

  • MCP 文档https://modelcontextprotocol.io/ 翻译为中文是:“https://模型上下文协议.io/” 或者根据具体语境,也可以简化为“模型上下文协议网站”。不过,通常网址在中文语境下直接保留原样,不进行翻译,因为网址是全球通用的,翻译后可能无法准确访问。所以,最准确的表述还是直接使用原网址
  • LangGraph 文档https://langchain-ai.github.io/langgraph/(中文可表述为:LangGraph 项目官网,由 LangChain-ai 维护)
  • FastAPI 文档https://fastapi.tiangolo.com/(中文可表述为:“FastAPI 官方网站(Tiangolo 版本)”)
  • 铁路文件https://docs.railway.app/(注:此网址本身为英文,直接翻译为中文即保持原样,因为网址通常不进行翻译,但为符合问题要求,可说明其为“铁路应用文档的官方网站”或类似表述,不过在此直接给出网址的中文呈现形式)

✨ 结束语

这个项目展示了:

  • ✅ 全栈AI应用开发
  • ✅ 准生产就绪的架构
  • ✅ 代码简洁、易于维护
  • ✅ 完整的文档
  • ✅ 现代最佳实践
  • ✅ 超出要求的附加功能

已准备好投入生产使用,并且易于通过添加更多MCP工具进行扩展! 🚀 表情符号“🚀”在中文中通常被翻译为“火箭”或直接保留原样作为表情使用,表示快速、前进或发射等含义。所以,可以翻译为“🚀(火箭/快速前进)”。


用Python、FastAPI、LangGraph和MCP,满怀热爱地构建而成