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;
相关推荐
alonewolf_992 分钟前
深入剖析MySQL锁机制与MVCC原理:高并发场景下的数据库核心优化
数据库·mysql
Generalzy17 分钟前
langchain deepagent框架
人工智能·python·langchain
一 乐25 分钟前
绿色农产品销售|基于springboot + vue绿色农产品销售系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端·宠物
Codeking__33 分钟前
Redis初识——什么是Redis
数据库·redis·mybatis
k***19539 分钟前
Spring 核心技术解析【纯干货版】- Ⅶ:Spring 切面编程模块 Spring-Instrument 模块精讲
前端·数据库·spring
程序员黄老师44 分钟前
主流向量数据库全面解析
数据库·大模型·向量·rag
Full Stack Developme1 小时前
Redis 可以实现哪些业务功能
数据库·redis·缓存
rgeshfgreh1 小时前
Spring事务传播机制深度解析
java·前端·数据库
无名-CODING1 小时前
Java Spring 事务管理深度指南
java·数据库·spring
想唱rap1 小时前
MYSQL在ubuntu下的安装
linux·数据库·mysql·ubuntu