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;
相关推荐
q行1 分钟前
MySQL学习日志--表之间的关系
数据库·学习·mysql
MoonBit月兔6 分钟前
海外开发者实践分享:用 MoonBit 开发 SQLC 插件(其三)
java·开发语言·数据库·redis·rust·编程·moonbit
电商API_1800790524719 分钟前
进阶篇:电商商品评论情感分析 + 关键词挖掘(Python NLP 实战)
大数据·开发语言·网络·数据库·人工智能
麦麦鸡腿堡20 分钟前
MySQL_INSERT UPDATE DELETE语句
数据库·mysql
老李四23 分钟前
深入理解MySQL事务:特性、原理与实践
数据库·mysql
SelectDB技术团队26 分钟前
慢 SQL 诊断准确率 99.99%,天翼云基于 Apache Doris MCP 的 AI 智能运维实践
大数据·数据库·人工智能·sql·apache
倔强的小石头_30 分钟前
Python 从入门到实战(十三):Flask + 数据库(让 Web 应用支持数据持久化与多人协作)
数据库·python·flask
冰冰菜的扣jio41 分钟前
探秘数据库——MySQL基础(四)
数据库·mysql
愚公移码1 小时前
蓝凌EKP产品:扩展Druid 数据源KmssDruidDataSource在企业级数据源初始化与连接监控实践
数据库·hibernate·蓝凌·druiddatasource
charlee441 小时前
一种基于 SQLite3 的半自动 C++ ORM 实现
c++·sql·sqlite·orm·crud