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***21602 小时前
【SQL技术】不同数据库引擎 SQL 优化方案剖析
数据库·sql
阿里云大数据AI技术2 小时前
【跨国数仓迁移最佳实践 12】阿里云 MaxCompute 实现 BigQuery 10 万条 SQL 智能转写迁移
大数据·sql
光泽雨3 小时前
python学习基础
开发语言·数据库·python
让学习成为一种生活方式3 小时前
Pfam 数据库详解--生信工具60
数据库
小陈phd3 小时前
RAG从入门到精通(四)——结构化数据读取与导入
人工智能·langchain
q***49863 小时前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite
唐诗3 小时前
使用 LangChain 创建一个简单的 Agent
前端·langchain·llm
川西胖墩墩4 小时前
流程图在算法设计中的实战应用
数据库·论文阅读·人工智能·职场和发展·流程图
clownAdam5 小时前
MongoDB-cdc原理
数据库·mongodb