后端AI市场情报服务
一种基于Python的后端服务,通过MCP(模型上下文协议)服务器架构提供人工智能驱动的市场情报。该服务将实时财务数据API与Groq LLM支持的会话式AI聊天机器人集成在一起,为市场和财务查询提供上下文响应。
特性
- 通过AlphaVantage API实时股票报价
- 通过NewsAPI获取最新市场新闻
- 公司基本面和概述数据
- 具有上下文保护的对话式人工智能
- 流媒体和非流媒体端点
- 模块化工具集成的MCP服务器架构
系统架构
┌─────────────────────────────────────────────────────┐
│ Client (curl, Postman, Frontend) │
└──────────────────┬──────────────────────────────────┘
│ HTTP POST /query or /stream
▼
┌─────────────────────────────────────────────────────┐
│ FastAPI Application (main_app/app.py) │
│ - Handles HTTP requests │
│ - Manages conversation sessions │
│ - Routes to LangChain agent │
└──────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────┐
│ LangChain Agent (main_app/agent.py) │
│ - ConversationBufferMemory for context │
│ - Groq LLM (llama-3.1-70b-versatile) │
│ - ReAct agent pattern │
└──────────────────┬──────────────────────────────────┘
│ Tool Execution
▼
┌─────────────────────────────────────────────────────┐
│ FastMCP Server (mcp_server/server.py) │
│ - Tool: get_stock_quote(symbol) │
│ - Tool: get_market_news(category) │
│ - Tool: get_company_overview(symbol) │
└──────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────┐
│ External Finance APIs │
│ - Alpha Vantage (stock data) │
│ - NewsAPI (financial news) │
└─────────────────────────────────────────────────────┘技术栈
| 组件 | 技术 | 目的 |
|---|---|---|
| AI框架 | LangChain | 协调LLM、内存和工具集成 |
| MCP服务器 | FastMCP | 将财务API作为MCP工具公开 |
| Web框架 | FastAPI+Uvicorn | 用于客户端请求的HTTP API端点 |
| LLM提供程序 | Groq API | 使用llama-3.1-70b-通用的快速推理 |
| 金融API | Alpha Vantage,NewsAPI | 实时股票数据和金融新闻 |
| 部署 | 渲染 | 生产云托管 |
项目结构
finance-mcp/
├── mcp_server/
│ ├── __init__.py
│ ├── server.py # FastMCP server implementation
│ └── config.py # API keys and configuration
│
├── main_app/
│ ├── __init__.py
│ ├── app.py # FastAPI application
│ ├── agent.py # LangChain agent setup
│ └── schemas.py # Pydantic models for requests/responses
│
├── requirements.txt # Python dependencies
├── .env.example # Environment variables template
├── README.md # This file
└── render.yaml # Render deployment configuration安装和设置
先决条件
- Python 3.10+
- Groq API密钥(免费 console.groq.com)
- Alpha Vantage API密钥(免费 alphavantage.co)
- NewsAPI密钥(免费 newsapi.org)
步骤1:克隆并安装依赖项
git clone
cd finance-mcp
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt步骤2:配置环境变量
创建一个 .env 项目根目录中的文件:
cp .env.example .env编辑 .env 并添加您的API密钥:
GROQ_API_KEY=your_groq_api_key_here
ALPHA_VANTAGE_API_KEY=your_alpha_vantage_key_here
NEWSAPI_KEY=your_newsapi_key_here步骤3:运行应用程序
# From the project root directory
uvicorn main_app.app:app --reload --port 8000该服务将在 http://localhost:8000
API终点
1.健康检查
curl http://localhost:8000/health2.查询端点(非流式)
curl -X POST http://localhost:8000/query \
-H "Content-Type: application/json" \
-d '{"message": "What is the current price of AAPL stock?"}'3.流端点(流)
curl -X POST http://localhost:8000/stream \
-H "Content-Type: application/json" \
-d '{"message": "Tell me about Tesla stock"}' \
-N示例用法
获取股票报价
curl -X POST http://localhost:8000/query \
-H "Content-Type: application/json" \
-d '{
"message": "Get me the latest quote for Tesla",
"session_id": "user123"
}'市场新闻(NewsAPI)
curl -X POST http://localhost:8000/query \
-H "Content-Type: application/json" \
-d '{
"message": "What are the top market news today?",
"session_id": "user123"
}'雅虎财经新闻(不需要API密钥)
curl -X POST http://localhost:8000/query \
-H "Content-Type: application/json" \
-d '{
"message": "What is the latest news about NVIDIA stock?",
"session_id": "user123"
}'公司概况
curl -X POST http://localhost:8000/query \
-H "Content-Type: application/json" \
-d '{
"message": "Tell me about Microsoft company fundamentals",
"session_id": "user123"
}'上下文保存测试
# First query
curl -X POST http://localhost:8000/query \
-H "Content-Type: application/json" \
-d '{
"message": "What is the current price of Apple stock?",
"session_id": "test1"
}'
# Follow-up query (tests context preservation)
curl -X POST http://localhost:8000/query \
-H "Content-Type: application/json" \
-d '{
"message": "What was the stock symbol I just asked about?",
"session_id": "test1"
}'运作原理
上下文保护
该服务使用以下方式维护对话上下文 基于会话的内存:
- 对话缓冲存储器:每个session_id都有自己的ConversationBufferMemory实例,用于存储整个对话历史记录
- 会话存储:会话存储在内存字典中,该字典在应用程序的生命周期内持续存在
- LangChain集成:内存会自动注入代理的提示符中,使其能够引用以前的交换
备注:对于生产部署,考虑实施:
- Redis或数据库支持的会话存储,用于持久化
- 会话超时和清理机制
- ConversationBufferWindowMemory限制内存大小
MCP服务器配置
MCP(模型上下文协议)服务器作为嵌入式子进程运行:
- FastMCP服务器:定义见
mcp_server/server.py,公开了三个工具:
- get_stock_quote(symbol):实时股票报价 - get_market_news(category):最新商业新闻 - get_company_overview(symbol):公司基本面
- 沟通:LangChain代理通过stdio传输与MCP服务器通信
- 服务器作为主应用程序生成的子进程运行 - 工具转换为与LangChain兼容的工具对象 - 如果MCP连接失败,备用工具可用
- 工具执行流程:
User Query → LangChain Agent → Tool Selection → MCP Server → External API → Response要渲染的部署
选项1:使用渲染仪表板
- 将代码推送到GitHub存储库
- 将Render连接到您的GitHub帐户
- 从存储库创建新的Web服务
- 渲染将自动检测
render.yaml - 在“渲染”仪表板中添加环境变量:
- GROQ_API_KEY - ALPHA_VANTAGE_API_KEY - NEWSAPI_KEY
- 部署并获取您的公共URL
选项2:使用渲染CLI
# Install Render CLI
npm install -g @render/cli
# Login
render login
# Deploy
render deploy测试生产部署
curl -X POST https://your-service.onrender.com/query \
-H "Content-Type: application/json" \
-d '{"message": "Give me the latest news on the stock market."}'性能注意事项
| 方面 | 考虑因素 | 解决方案 |
|---|---|---|
| API速率限制 | Alpha Vantage:5次调用/分钟(自由层) | 使用Redis或内存中LRU缓存实现缓存 |
| 响应时间 | LLM+API调用=2-5秒延迟 | 使用 /stream 更好的用户体验端点 |
| 内存增长 | 会话缓冲内存无限增长 | 使用会话缓冲窗口内存或会话超时 |
| 并发用户 | 共享内存会话 | 考虑使用Redis进行分布式部署 |
使用的工具和库
- 快速API:用于构建API的现代快速web框架
- LangChain:开发LLM驱动应用程序的框架
- 格罗克:使用Llama 3.1 70B进行超快速LLM推理
- FastMCP:模型上下文协议服务器的Python实现
- MCP-SDK:用于stdio通信的官方MCP客户端
- 阿尔法Vantage API:实时和历史股市数据
- 新闻API:来自多个来源的新闻聚合
- 雅虎财经:财经新闻和数据(不需要API密钥)
- y融资:雅虎财经数据的Python库
- Uvicorn:闪电般快速的ASGI服务器
- 派丹蒂克:使用Python类型注释进行数据验证
故障排除
常见问题
API密钥错误
Error: ALPHA_VANTAGE_API_KEY not set解决方案:确保 .env 存在具有有效API密钥的文件
MCP连接失败
Error connecting to MCP server解决方案:服务自动回退到直接API调用。检查Python版本(3.10+)
导入错误
ModuleNotFoundError: No module named 'langchain'解决方案:确保虚拟环境已激活并安装了依赖项:
pip install -r requirements.txt许可证
MIT许可证
作者
为实习选拔过程而创建-后端人工智能市场情报服务
