🤖 使用MCP代理的数据库聊天机器人
对话式AI聊天机器人前端 溪流 它使用以下方式与PostgreSQL数据库交互 LangChain, 奥拉玛,以及 MCP(模型上下文协议) 工具。
✨ 特性
- 💬 自然语言聊天界面 -像ChatGPT一样与数据库对话
- 🤖 AI驱动的查询 -由Ollama提供动力(Qwen3 8B型号)
- 🔗 MCP集成 -通过MCP服务器访问数据库工具
- 📊 实时数据库交互 -查询、插入、删除和管理数据
- 💾 聊天记录 -跟踪对话
- 🎨 漂亮的UI -具有状态监控功能的现代Streamlit界面
- ⚡ 异步处理 -具有适当事件循环处理的非阻塞聊天响应
- 🔄 智能事件循环管理 -无缝处理Streamlit的线程模型
- 📋 数据库状态监控 -侧边栏中的实时连接和表状态
🏗️ 建筑
┌──────────────────────────────────────────────────────────────┐
│ Streamlit Frontend │
│ (streamlit_chatbot.py) │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ • Beautiful chat interface │ │
│ │ • Async event loop management (run_async helper) │ │
│ │ • User input/output handling │ │
│ │ • Chat history management │ │
│ │ • Database connection status monitoring │ │
│ └────────────────────────────────────────────────────────┘ │
└────────────────────┬─────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────┐
│ LangChain MCP Agent (async) │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ • Query understanding & interpretation │ │
│ │ • Tool loading from MCP Server │ │
│ │ • Tool selection & calling │ │
│ │ • Response generation │ │
│ └────────────────────────────────────────────────────────┘ │
└────────────────────┬─────────────────────────────────────────┘
│
┌────────────┼────────────┬────────────┐
▼ ▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌──────────┐ ┌────────────┐
│ Ollama │ │ MCP │ │PostgreSQL│ │ Database │
│(LLM) │ │ Server │ │(DB) │ │ Functions │
│Qwen3 8B │ │(Tools) │ │localhost │ │ │
│:11434 │ │:7452 │ │:5432 │ │list_tables,│
│ │ │ │ │ │ │get_db_conn │
└─────────┘ └─────────┘ └──────────┘ └────────────┘📋 先决条件
所需服务
- PostgreSQL 12+ -数据库(本地或Docker)
- 奥拉玛 -LLM推理机
- MCP 服务器 -数据库工具(server.py)
系统要求
- Python 3.10+
- 最低8GB RAM(适用于Ollama)
- 5GB磁盘空间(适用于Ollama型号)
🚀 安装和设置
步骤1:克隆/设置项目
cd /Users/neslihaneti/Desktop/MCP_agent_db_streamlit步骤2:安装Python依赖项
pip install -r requirements.txt依赖关系:
- 流式照明>=1.28.0
- langchain>=1.2.6
- langchain mcp适配器>=0.2.1
- 郎链胶原蛋白>=1.0.1
- psycopg>=3.3.2
- fastmcp>=2.14.3
步骤3:启动PostgreSQL
使用Docker Compose:
docker-compose up -d使用本地PostgreSQL:
# Make sure PostgreSQL is running on localhost:5432默认凭据:
Host: localhost
Port: 5432
Database: postgres
User: postgres
Password: postgres步骤4:安装并运行Olama
- 下载Ollama:
- 访问https://ollama.ai - 为您的操作系统下载并安装
- 启动Ollama服务器:
ollama serve(在终端中保持此运行)
- 拉动模型:
在另一个终端中:
ollama pull qwen3:8b-fp16⏱️ 首次下载大约需要5-10分钟
步骤5:启动MCP服务器
在新终端中:
python server.py预期产量:
INFO: Uvicorn running on http://0.0.0.0:7452步骤6:启动Streamlit聊天机器人
选项A:使用启动脚本(推荐)
chmod +x streamlit_run.sh
./streamlit_run.sh选项B:使用紫外线直接发射(项目使用紫外线)
uv run streamlit run streamlit_chatbot.py选项C:使用pip直接启动
streamlit run streamlit_chatbot.py🎉 应用程序打开时间: http://localhost:8501
初始负载
- 代理初始化时,首次加载可能需要30-60秒
- Ollama在首次使用时将模型加载到内存中
- 后续请求将更快
- 检查侧边栏中的服务状态指示器
💬 使用指南
开始对话
- 打开http://localhost:8501在浏览器中
- 在聊天输入中键入您的问题或命令
- 按Enter键或单击发送
- 等待AI处理(显示“Agent正在思考…”)
- 阅读回复和任何结果
示例问题
查看数据
"Show me all tables in the database"
"What data is in the users table?"
"List all records from the orders table"
"Show me the first 10 products"筛选和搜索
"Find users from New York"
"Show active accounts"
"Get all orders from this month"
"Search for users with name John"添加数据
"Add a new user named Alice"
"Insert a new product"
"Create a new order"获取信息
"What columns does the users table have?"
"Tell me about the database structure"
"How many tables are in the database?"聊天界面
用户消息 (蓝色,右对齐)
- 您的问题和命令
- 显示在聊天气泡中
助理回应 (灰色,左对齐)
- AI的答案和解释
- 数据库结果(如适用)
控制
- 🔄 按钮:清除聊天记录
- 输入框:键入您的消息
- 侧边栏:检查服务状态和可用表格
🔧 配置
数据库连接
在中编辑连接设置 streamlit_chatbot.py:
# ==================== Configuration ====================
DB_HOST = "localhost" # Database host
DB_PORT = 5432 # Database port
DB_NAME = "postgres" # Database name
DB_USER = "postgres" # Database user
DB_PASSWORD = "postgres" # Database password
MCP_SERVER_URL = "http://localhost:7452/mcp" # MCP Server URLOllama配置
编辑 streamlit_chatbot.py:
llm = ChatOllama(
model="qwen3:8b-fp16", # Model name
temperature=0, # Creativity (0=deterministic, 1=creative)
base_url="http://localhost:11434" # Ollama server URL
)更改Olama模型
可用型号:
ollama pull qwen2:7b # Smaller, faster
ollama pull qwen3:8b-fp16 # Current (8B parameters)
ollama pull neural-chat:latest # Alternative然后更新 streamlit_chatbot.py:
model="neural-chat:latest" # Change this line📊 系统状态
侧边栏显示所有组件的实时状态:
📊 System Status
✅ MCP Agent Ready - LangChain agent initialized
✅ LLM (Ollama) Ready - Ollama service running
✅ MCP Server Ready - Database tools available
✅ Database Connected - PostgreSQL accessible
Tables: 5 - Number of tables in DB
📋 Available Tables - List of tables状态指示器:
- ✅ 绿色=服务正在运行
- ❌ 红色=服务未运行
- 🟡 黄色=连接问题
� 异步事件循环管理
聊天机器人使用自定义 run_async() help函数用于正确管理Streamlit多线程环境中的异步事件循环。
运作原理
def run_async(coroutine):
"""Helper function to run async code in Streamlit context"""
try:
loop = asyncio.get_event_loop()
if loop.is_running():
# If loop is already running, create new loop
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
return new_loop.run_until_complete(coroutine)
else:
return loop.run_until_complete(coroutine)
except RuntimeError:
# No event loop exists, create one
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(coroutine)
finally:
loop.close()使用Async的关键组件
- 代理初始化 -
initialize_mcp_agent()
- 加载MCP客户端 - 从MCP服务器获取工具 - 创建LangChain代理 - 处理方式: agent_config = run_async(initialize_mcp_agent())
- 查询处理 -
process_user_query_with_agent()
- 处理用户输入 - 呼叫代理工具 - 生成响应 - 处理方式: response_data = run_async(process_user_query_with_agent(...))
- 工具调用 -MCP工具被异步调用
- 防止阻止UI - 保持响应能力 - 显示“代理正在思考…”旋转器
�🐛 故障排除
“代理未初始化”
❌ Error: Failed to initialize MCP Agent解决方案:
- 检查所有服务是否正在运行:
# Check Ollama
curl http://localhost:11434
# Check MCP Server
curl http://localhost:7452
# Check PostgreSQL
psql -U postgres -h localhost- 重新启动Streamlit:按
Ctrl+C并重新运行
“特工在想……”花了太长时间
可能的原因:
- Ollama模型尚未加载
- 系统RAM已满
- 网络/CPU速度慢
解决方案:
- 等待1-2分钟进行第一次查询(模型加载)
- 确保8GB+RAM可用
- 检查CPU使用情况
top或任务管理器
“数据库连接失败”
解决方案:
# Test PostgreSQL connection
psql -U postgres -h localhost -d postgres
# Or restart Docker container
docker-compose restart mcp-pg-unified“Ollama服务没有响应”
解决方案:
# Install Ollama if not present
# https://ollama.ai
# Start Ollama server
ollama serve
# In another terminal, pull model
ollama pull qwen3:8b-fp16“MCP服务器连接被拒绝”
解决方案:
# Start the MCP server
python server.py
# Check if running
curl http://localhost:7452/health
# Or check logs
tail -f ~/.ollama/logs“端口已在使用中”
Error: Address already in use解决方案:
# Kill process on port 8501
lsof -i :8501 | grep LISTEN | awk '{print $2}' | xargs kill -9
# Or use different port
streamlit run streamlit_chatbot.py --server.port 8502“运行时错误:没有当前事件循环”
RuntimeError: There is no current event loop in thread 'ScriptRunner.scriptThread'解决方案:
- 这是由自动处理的
run_async()辅助函数 - 如果您看到此错误,则可能无法正确使用帮助程序
- 确保所有异步函数都被调用
run_async()包装器 - 重新启动Streamlit:
Ctrl+C并重新运行
📈 性能提示
为了更快的响应
- 使用较小的模型:
ollama pull qwen2:7b
# Update streamlit_chatbot.py: model="qwen2:7b"- 增强Ollama的记忆力:
export OLLAMA_NUM_THREAD=8
ollama serve- 在GPU上运行(如果可用):
- Ollama自动检测GPU - 包括Nvidia/金属支持
为了获得更好的响应
- 使用较大型号:
ollama pull qwen3:14b # Larger, more accurate- 提高创造力的温度:
temperature=0.7 # More creative responses🔒 安全注意事项
仅限开发
此设置是 可生产的.生产:
- 使用环境变量:
from dotenv import load_dotenv
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")- 添加身份验证:
import streamlit_authenticator as stauth
# Implement user login- 使用HTTPS:
- 反向代理后部署(nginx) - 使用SSL证书
- 限制访问:
- 白名单IP地址 - 使用VPN/防火墙规则
- 审核日志记录:
- 记录所有数据库查询 - 监控AI响应
📚 文件结构
MCP_agent_db_streamlit/
├── streamlit_chatbot.py # Main Streamlit app
├── server.py # MCP Server (backend)
├── mcp_agent.py # AI Agent (backend)
├── streamlit_run.sh # Launch script
├── requirements.txt # Python dependencies
├── docker-compose.yml # Docker configuration
├── Dockerfile # Container build
├── README.md # This file
└── pg_data/ # PostgreSQL data volume🎓 运作原理
对话流程
User Input (Chat Interface)
↓
Streamlit receives message
↓
run_async() creates/manages event loop
↓
initialize_mcp_agent() (if first time)
├─ Initialize ChatOllama LLM
├─ Initialize MCP Client
└─ Load tools from MCP Server
↓
process_user_query_with_agent()
├─ Load tools asynchronously
├─ Pass to LangChain agent
└─ Execute with Ollama model
↓
Ollama LLM generates response
├─ Understands intent
├─ Selects tools
└─ Generates natural language response
↓
Results formatted & displayed
↓
Chat history updated异步执行流程
Agent Query Processing:
1. User message → run_async(process_user_query_with_agent())
2. Async function awaits:
- await client.get_tools() (fetch MCP tools)
- await agent.ainvoke() (run LangChain agent)
3. run_async() helper:
- Checks for existing event loop
- Creates new loop if needed
- Executes coroutine
- Returns result to Streamlit
4. UI updates with response工具调用
当您询问数据时,代理:
- 理解你的意图
- 调用MCP工具:
- list_tables() -获取可用的桌子 - search_documents_dynamic() -查询数据 - insert_data() -添加记录 - create_custom_table() -创建表格 - delete_records_dynamic() -删除数据
- 流程结果
- 生成自然语言响应
🚀 高级功能
自定义系统提示
编辑代理的行为:
system_prompt="""You are a database expert...
Your instructions here"""添加自定义工具
在 server.py,创建新的MCP工具:
@mcp.tool()
async def my_custom_tool(param: str):
"""Custom tool description"""
# Your code here
return result多回合对话
聊天机器人记住上下文:
User: "Show me active users"
Bot: [displays active users]
User: "How many are there?"
Bot: "There are X active users from the previous query"📞 支持和问题
获取帮助
- 检查上面的故障排除部分
- 查看终端日志
- 检查侧边栏中的服务状态
常见问题检查表
- \[\]所有服务都在运行吗?(检查侧边栏状态)
- \[\]正确的端口? (5432, 7452, 11434, 8501)
- \[\]模型已下载? (
ollama list) - \[\]互联网连接?(用于模型下载)
- \[\]足够的RAM?(建议8GB+)
📄 许可证
该项目是为教育和发展目的而提供的。
🎉 你都准备好了!
您的数据库聊天机器人已准备好使用:
# 1. Start all services
docker-compose up -d # PostgreSQL
ollama serve # Ollama (separate terminal)
python server.py # MCP Server (separate terminal)
# 2. Launch chatbot
./streamlit_run.sh # Or: streamlit run streamlit_chatbot.py
# 3. Open browser
# http://localhost:8501享受与您的数据库聊天! 🤖
