LangChain-08 Query SQL DB 通过GPT自动查询SQL

我们需要下载一个 LangChain 官方提供的本地小数据库。

安装依赖

复制代码
SQL:
https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sql
Shell:
pip install --upgrade --quiet  langchain-core langchain-community langchain-openai

导入数据

我这里使用 Navicat 导入数据,你也可以通过别的方式导入(当然你有现成的数据库也可以,但是不要太大了,不然会消耗很多Token)。

编写代码

这里我使用了 GPR 3.5 Turbo,效果不理想的话可以试试GPT 4 或者 GPT 4 Turbo

复制代码
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.utilities import SQLDatabase
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI


template = """Based on the table schema below, write a SQL query that would answer the user's question:
{schema}

Question: {question}
SQL Query:"""
prompt = ChatPromptTemplate.from_template(template)

db = SQLDatabase.from_uri("sqlite:///./Chinook.db")


def get_schema(_):
    return db.get_table_info()


def run_query(query):
    return db.run(query)


model = ChatOpenAI(
    model="gpt-3.5-turbo",
)

sql_response = (
    RunnablePassthrough.assign(schema=get_schema)
    | prompt
    | model.bind(stop=["
SQLResult:"])
    | StrOutputParser()
)

message = sql_response.invoke({"question": "How many employees are there?"})
print(f"message: {message}")

运行结果

复制代码
? python3 test08.py
message: SELECT COUNT(*) AS totalEmployees
FROM Employee;
相关推荐
神明不懂浪漫几秒前
【第四章】索引——B+树、回表,加快数据库的查找能力的利器
开发语言·数据结构·数据库·经验分享·笔记·b树
meilindehuzi_a42 分钟前
LangChain.js + Milvus 向量长期记忆实战:对话写入、语义检索与 RAG 增强
javascript·langchain·milvus
zcmodeltech43 分钟前
智慧矿山沙盘模型多场景控制系统设计——基于STM32与Modbus RTU的智能开采、无人矿卡、数字孪生全场景联动方案
数据库·stm32·单片机·嵌入式硬件·物联网
小码过河.1 小时前
ocean自增主键模式说明
数据库·oracle
leoZ2311 小时前
2026-09-08-mysql-57-init-walkthrough
前端·javascript·数据库·vue.js·opencv·mysql·adb
云飞云共享云桌面1 小时前
钣金制造研发优化:不采购传统工作站,实现 SolidWorks 团队共用服务器开展三维建模
运维·服务器·网络·数据库·3d·制造
4SAPI1 小时前
2026年大模型API接入选型指南:企业与个人用户的架构、稳定性与成本考量
大数据·开发语言·数据库·人工智能·架构·php
xixiaoyunya1 小时前
只备份数据远远不够:服务器系统备份的完整方案与实践
服务器·网络·数据库
大模型丫丫2 小时前
LangGraph + MCP(Model Context Protocol)完整讲解
java·开发语言·数据库