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;
相关推荐
GreatSQL社区18 小时前
解决 GreatSQL 报错:存储过程字符集排序规则不兼容问题
数据库
老码观察18 小时前
MySQL 慢 SQL 治理实战:从索引原理到真实踩坑
sql·mysql
肖有米XTKF864618 小时前
肖有米开发团队:双迹美业水光系统小程序模式
数据库·人工智能·团队开发·csdn开发云
KaMeidebaby18 小时前
卡梅德生物技术快报|多肽库筛选技术构建药物递送功能肽库:流程、算法与质控体
前端·数据库·其他·百度·新浪微博
思麟呀18 小时前
MySQL的视图特性和用户权限管理
数据库·mysql
wuxinyan12318 小时前
工业级大模型学习之路019:LangChain零基础入门教程(第二篇):LLM 模块与模型抽象
人工智能·python·学习·langchain
wljt18 小时前
Redis的5种数据类型
数据库·redis·缓存
sakiko_18 小时前
Swift学习笔记30-数据库SQlite语句
数据库·学习·swift
IvorySQL19 小时前
用生成列提升 JSONB 查询效率:PostgreSQL 三种索引方案实测对比
数据库·postgresql
STDD19 小时前
Abiotic Factor多人生存建筑游戏《非生物因素》 专用服务器搭建教程
服务器·数据库·游戏