React LangChain聊天机器人
使用React、FastAPI和LangChain的React代理模式构建的全栈AI聊天机器人应用程序。功能包括智能工具选择、通过Tavily进行实时网络搜索、谷歌趋势集成、流式响应、Supabase身份验证和完整的Docker容器化。
主要特点
- 重新代理 -智能推理循环,决定何时使用以及使用哪些工具
- 工具可见性 -显示正在使用哪个工具的实时UI指示器(🔍 网络搜索或📈 谷歌趋势)
- Tavily网络搜索 -当前信息和最新新闻整合
- 谷歌趋势 -追踪热门话题和热门搜索
- 流媒体响应 -实时令牌流以获得即时反馈
- Supabase认证 -使用电子邮件/密码进行基于JWT的安全身份验证
- 消息持久性 -完整的对话历史记录存储在Supabase中
- SSE流媒体 -服务器发送事件以实现高效的实时通信
- Docker就绪 -通过健康检查完成集装箱化
系统架构
┌─────────────────────────────────────────────────────────────────┐
│ Docker Compose Network │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ Frontend │ │ Backend │ │
│ │ (React 18) │◄───────►│ (FastAPI) │ │
│ │ Port 3000 │ │ Port 8000 │ │
│ └──────────────────┘ └──────────────────┘ │
│ │ │ │
│ │ ├─────────────┐ │
│ │ │ │ │
│ │ ┌───────▼────────┐ │ │
│ │ │ Supabase │ │ │
│ │ │ (PostgreSQL) │ │ │
│ │ │ Auth + DB │ │ │
│ │ └────────────────┘ │ │
│ │ │ │
│ └───────────────────────────────────────────┤ │
│ │ │
│ ┌────────────────▼──────┐ │
│ │ External APIs │ │
│ │ - Tavily (Search) │ │
│ │ - Groq (LLM) │ │
│ │ - Google Trends │ │
│ └──────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘技术栈
前端:
- React 18与TypeScript
- React Router用于导航
- Axios用于HTTP请求
- CSS3用于造型
- 用于流式传输的服务器发送事件(SSE)
后端:
- FastAPI(Python web框架)
- Pydantic用于数据验证
- LangChain用于代理编排
- Groq API用于LLM(自由层)
- 用于网络搜索的Tavily Python SDK
- 身份验证和数据库支持
- PyTrends用于谷歌趋势数据
基础设施:
- Docker&Docker编写
- PostgreSQL(通过Supabase)
- JWT身份验证
快速开始
先决条件
- 已安装Docker和Docker Compose
- Supabase帐户(免费等级可在https://supabase.com)
- Tavilly API密钥(位于https://tavily.com)
- Groq API密钥(位于https://console.groq.com)
安装说明
- 克隆存储库:
git clone https://github.com/YOUR_USERNAME/react-langchain-chatbot.git
cd react-langchain-chatbot- 创建环境文件:
cp .env.example .env- 配置
.env使用您的凭据:
# Supabase Configuration
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your-anon-key
SUPABASE_JWT_SECRET=your-jwt-secret
# API Keys
TAVILY_API_KEY=your-tavily-key
GROQ_API_KEY=your-groq-key
# Backend Configuration
ENVIRONMENT=production
LOG_LEVEL=INFO
DEBUG=False- 启动所有服务:
docker-compose up --build- 访问应用程序:
- 前端:http://localhost:3000
- 后端API:http://localhost:8000
- API文件:http://localhost:8000/docs
项目结构
react-langchain-chatbot/
│
├── frontend/ # React TypeScript frontend
│ ├── src/
│ │ ├── api/
│ │ │ ├── chatClient.ts # API client with SSE handling
│ │ │ └── config.ts # API configuration
│ │ ├── components/
│ │ │ └── Message.tsx # Message display component
│ │ ├── pages/
│ │ │ ├── Chat.tsx # Main chat interface
│ │ │ ├── Login.tsx # Login page
│ │ │ └── Signup.tsx # Signup page
│ │ ├── state/
│ │ │ ├── authContext.tsx # Auth state management
│ │ │ └── chatContext.tsx # Chat state management
│ │ ├── styles/
│ │ │ ├── auth.css # Auth pages styling
│ │ │ ├── chat.css # Chat interface styling
│ │ │ └── message.css # Message styling
│ │ ├── types/
│ │ │ └── index.ts # TypeScript type definitions
│ │ ├── utils/
│ │ │ └── logger.ts # Logging utility
│ │ ├── App.tsx # Main app component
│ │ └── index.tsx # React entry point
│ ├── public/
│ │ └── index.html # HTML template
│ ├── Dockerfile # Frontend Docker image
│ ├── package.json # Dependencies
│ └── tsconfig.json # TypeScript config
│
├── backend/ # FastAPI backend
│ ├── app/
│ │ ├── main.py # FastAPI application
│ │ ├── core/
│ │ │ └── config.py # Settings from environment
│ │ ├── middleware/
│ │ │ └── auth.py # JWT authentication middleware
│ │ ├── routers/
│ │ │ ├── auth.py # Auth endpoints (signup, login, logout)
│ │ │ ├── chat.py # Chat endpoints (message, conversations)
│ │ │ └── health.py # Health check endpoint
│ │ ├── schemas/
│ │ │ ├── auth.py # Auth request/response models
│ │ │ └── chat.py # Chat request/response models
│ │ ├── services/
│ │ │ ├── agent/
│ │ │ │ └── react_agent.py # ReAct agent implementation
│ │ │ ├── tools/
│ │ │ │ ├── tavily.py # Tavily web search wrapper
│ │ │ │ └── google_trends_mcp.py # Google Trends wrapper
│ │ │ └── db/
│ │ │ └── supabase_client.py # Supabase database client
│ │ └── utils/
│ │ ├── errors.py # Custom error classes
│ │ └── logging.py # Logging configuration
│ ├── migrations/
│ │ ├── 001_create_tables.sql # Database schema
│ │ └── SETUP.md # Migration instructions
│ ├── Dockerfile # Backend Docker image
│ ├── requirements.txt # Python dependencies
│ └── pytest.ini # Pytest configuration
│
├── docker-compose.yml # Docker Compose orchestration
├── .env.example # Environment template
└── README.md # This fileAPI终点
身份验证(/auth)
POST /auth/signup-创建新用户帐户
- 主体: { "email": "user@example.com", "password": "password" } - 退货: { "access_token": "jwt_token", "user": {...} }
POST /auth/login-使用凭据登录
- 主体: { "email": "user@example.com", "password": "password" } - 退货: { "access_token": "jwt_token", "user": {...} }
POST /auth/logout-注销(需要身份验证)
- 退货: { "message": "Logged out successfully" }
聊天(/chat)
POST /chat/message-发送带有流式响应的消息(SSE)
- 标题: Authorization: Bearer {token} - 主体: { "conversation_id": "uuid", "content": "message" } - 返回:服务器发送的事件流
GET /chat/conversations-获取用户的对话(需要身份验证)
- 退货: { "conversations": [...] }
GET /chat/conversations/{id}/messages-获取对话消息(需要身份验证)
- 退货: { "messages": [...] }
健康(/health)
GET /health-服务健康检查
- 退货: { "status": "healthy" }
ReAct代理的工作原理
代理循环流
- 用户发送消息 → 前端通过HTTP POST发送到后端
- 代理接收消息 → 从Supabase加载对话历史记录
- 代理人认为 → 致电Groq LLM决定是否需要工具
- 工具选择 → 代理解析LLM响应的ACTION和INPUT
- UI显示工具 → 前端显示正在使用的工具
- 工具执行 → 调用Tavily或谷歌趋势
- 响应生成 → LLM将最终答案与工具结果相结合
- 流媒体 → 响应令牌通过SSE流回到前端
- 消息已保存 → 最终响应存储在Supabase中
刀具选择逻辑
代理根据查询意图智能地选择工具:
| 查询类型 | 使用的工具 | 示例 |
|---|---|---|
| 热门话题 | 📈 谷歌趋势 | “今天的趋势是什么?” |
| 当前新闻 | 🔍 网络搜索 | “最新人工智能发展” |
| 常识 | 无(仅法学硕士) | “机器学习是如何工作的?” |
流事件
后端在处理过程中发出SSE事件:
event: loading
data: {"status": "Agent is thinking..."}
event: responding
data: {"status": "Generating response..."}
event: tool_selected
data: {"tool": "Tavily_Search", "tool_name": "Web Search"}
event: tool_activity
data: {"tool": "Tavily_Search", "status": "started"}
event: token
data: {"token": "The "}
event: token
data: {"token": "latest "}
event: tool_activity
data: {"tool": "Tavily_Search", "status": "completed"}
event: streaming
data: {"status": "Streaming response..."}
event: done
data: {"message_id": "generated"}环境变量
| 变量 | 描述 | 示例 |
|---|---|---|
SUPABASE_URL | Supabase项目URL | https://project.supabase.co |
SUPABASE_KEY | Supabase匿名密钥 | eyJhbGc... |
SUPABASE_JWT_SECRET | 用于令牌验证的JWT密钥 | super-secret-key |
TAVILY_API_KEY | Tavilly网络搜索API密钥 | tvly-... |
GROQ_API_KEY | Groq LLM API密钥(自由层) | gsk_... |
ENVIRONMENT | 环境(生产/开发) | production |
LOG_LEVEL | 日志记录级别(调试/信息/警告) | INFO |
DEBUG | 调试模式 | False |
发展
后端开发
cd backend
# Install dependencies
pip install -r requirements.txt
# Run locally with auto-reload
python -m uvicorn app.main:app --reload --port 8000
# Run tests
pytest
# Run with specific log level
LOG_LEVEL=DEBUG python -m uvicorn app.main:app --reload前端开发
cd frontend
# Install dependencies
npm install
# Start development server
npm start
# Build for production
npm run build
# Run tests
npm test故障排除
服务无法启动
# Check Docker is running
docker ps
# Check if ports are in use
lsof -i :3000
lsof -i :8000
# View service logs
docker-compose logs -f backend
docker-compose logs -f frontend
# Rebuild from scratch
docker-compose down
docker-compose up --build身份验证问题
# Check Supabase credentials
cat .env | grep SUPABASE
# Verify JWT token in browser console
localStorage.getItem('auth_token')
# Check backend auth logs
docker-compose logs backend | grep -i auth工具不工作
Tavily搜索失败:
- 在验证API密钥https://tavily.com/dashboard
- 检查后端日志:
docker-compose logs backend | grep -i tavily - 确保互联网连接
谷歌趋势失败:
- 谷歌可能会阻止自动请求(预期行为)
- 系统优雅地回归到LLM知识
- 检查日志:
docker-compose logs backend | grep -i trends
Groq速率限制(429错误):
- 免费等级:10万代币/天限额
- 等待限制重置或升级到开发层
- 备选方案:改用OpenAI API
数据库连接问题
# Verify Supabase credentials
echo $SUPABASE_URL
echo $SUPABASE_KEY
# Check if Supabase project is active
curl $SUPABASE_URL/rest/v1/
# View backend database logs
docker-compose logs backend | grep -i supabase业绩说明
- 流动: SSE为响应式用户体验提供实时令牌流
- 工具执行: 通常1-3秒用于网络搜索,\<1秒用于趋势搜索
- 费率限制: Groq免费等级每天有10万个代币;Tavily提供慷慨的免费套餐
- 数据库: 适合开发/测试的无Supabase层
安全
- JWT身份验证: 所有API端点都需要有效的JWT令牌
- 行级安全: Supabase RLS确保用户只访问他们的数据
- CORS: 配置为仅允许前端源
- 环境变量: 敏感密钥存储在
.env(不是git)
未来的增强功能
- \[\]对话搜索/筛选
- \[\]消息编辑和删除
- \[\]用户偏好和设置
- \[\]多个对话线程
- \[\]导出对话历史记录
- \[\]自定义系统提示
- \[\]每个用户的速率限制
- \[\]分析仪表板
许可证
麻省理工学院
支持
对于问题、疑问或贡献,请在GitHub上打开问题。
______________________________________________________________________
建于❤️ 使用React、FastAPI和LangChain
