SQL语音代理

一个使用PostgreSQL、MCP协议和本地LLM(Ollama)的自然语言SQL代理,适用于数据库查询和语音交互场景。

  • by Wasii25
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 Wasii25/Mini-Project-2

使用说明

带MCP的SQL语音代理

使用PostgreSQL、MCP协议和本地LLM(Ollama)的自然语言SQL代理。

先决条件

1.安装系统依赖项

# PostgreSQL
sudo apt update
sudo apt install postgresql postgresql-contrib

# Node.js (for MCP server)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

# Python
sudo apt install python3 python3-pip

2.安装Olama

# Install Ollama
curl -fsSL https://ollama.com/install.sh | sh

# Pull the model
ollama pull llama3.2:3b
# OR for better accuracy:
# ollama pull phi3:mini

3.安装PostgreSQL官方MCP服务器

npm install -g @modelcontextprotocol/server-postgres

设置

1.克隆存储库

git clone <your-repo-url>
cd <your-repo-name>

2.安装Python依赖项

pip install -r requirements.txt

3.设置PostgreSQL数据库

# Start PostgreSQL
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Create database and user
sudo -u postgres psql << 'EOF'
CREATE USER student_user WITH PASSWORD 'student123';
CREATE DATABASE student_db OWNER student_user;
\c student_db
GRANT ALL ON SCHEMA public TO student_user;
\q
EOF

# Load sample data
sudo -u postgres psql -d student_db -f schema.sql

4.验证设置

# Test PostgreSQL connection
PGPASSWORD=student123 psql -h localhost -U student_user -d student_db -c "SELECT COUNT(*) FROM students;"

# Test Ollama
curl http://localhost:11434/api/tags

# Test MCP server
which mcp-server-postgres

跑

python postgres_agent.py

用法

Question: list all students
Question: show me students in CS201
Question: which course has the most enrollments
Question: exit

项目结构

.
├── postgres_agent.py      # Main agent code
├── schema.sql            # Database schema and sample data
├── requirements.txt      # Python dependencies
└── README.md            # This file

配置

编辑 postgres_agent.py 更改:

  • 模型:第18行-更改 llama3.2:3b 到 phi3:mini 为了获得更好的准确性
  • 数据库:第16行-如果使用不同的凭据,则更新连接字符串
  • 详细模式:第372行-套装 verbose_mode = True 用于调试

故障排除

“mcp服务器postgres:找不到命令”

npm install -g @modelcontextprotocol/server-postgres

“对等身份验证失败”

编辑 /etc/postgresql/*/main/pg_hba.conf:

# Change from:
local   all   all   peer

# To:
local   all   all   md5

然后重新启动: sudo systemctl restart postgresql

“Ollama连接被拒绝”

sudo systemctl start ollama
# OR
ollama serve

特性

  • ✅ SQL的自然语言
  • ✅ PostgreSQL数据库查询
  • ✅ 用于可靠执行的MCP协议
  • ✅ 100%离线(初始设置后)
  • ✅ 干净、语音友好的输出

未来的增强功能

  • []语音输入(带Vosk的STT)
  • []语音输出(带Coqui的TTS)
  • []查询缓存
  • []监控仪表板
  • []性能指标

许可证

麻省理工学院