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;
相关推荐
ytttr8732 小时前
C# 读取数据库表结构工具设计与实现
开发语言·数据库·c#
白露与泡影2 小时前
从 BIO 到 epoll:高并发 I/O 模型演进与本质分析
java·服务器·数据库
知识分享小能手2 小时前
MongoDB入门学习教程,从入门到精通,MongoDB副本集的核心机制(11)
数据库·学习·mongodb
一 乐2 小时前
剧场管理系统|基于springboot + vue剧场管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·剧场管理系统
阿坤带你走近大数据2 小时前
Oracle里的MINUS是什么
数据库·oracle
佩亚诺余项.2 小时前
SQL Server 系统视图深度应用:批量检索含关键字的存储过程与数据表字段
数据库
小尔¥2 小时前
MySQL故障排查与优化
运维·数据库·mysql
rrrjqy2 小时前
Redis常见问题(一)
数据库·redis·缓存
Humbunklung2 小时前
WMO 天气代码(Code Table 4677)深度解析与应用报告
开发语言·数据库·python