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;
相关推荐
dFObBIMmai30 分钟前
CSS如何检测页面浮动元素位置_使用审查工具与clear
jvm·数据库·python
qq_4609784035 分钟前
实现 Svelte 中基于数组索引的 details 元素单开单关交互
jvm·数据库·python
这个DBA有点耶1 小时前
3步抓出慢SQL,别等半夜被叫醒😴
数据库·代码规范
dfdfadffa1 小时前
SQL窗口函数如何优化嵌套子查询_提升执行效率
jvm·数据库·python
m0_588758481 小时前
如何查看集群版本_crsctl query crs activeversion当前版本
jvm·数据库·python
摇滚侠2 小时前
Oracle19c 导出 Oracle11g 导入,Oracle19c 导出导入,Oracle11g 导出导入
java·数据库·oracle
zh1570232 小时前
CSS如何让元素出现时带抖动_利用关键帧定义抖动动画
jvm·数据库·python
米小虾2 小时前
从"玩具"到"生产力":AI Agent 架构设计的 5 个关键决策
langchain·aigc·ai编程
薛定谔的悦2 小时前
共享数据总线(DPR)设计模式——嵌入式系统的“内存数据库”
jvm·数据库·设计模式
程序猿online2 小时前
本地mysql密码重置
数据库·mysql