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;
相关推荐
hryou09225 小时前
做AI-Agent总查不准还运维崩溃2026向量数据库避坑指南
langchain·ai编程·aiops
lusklusklusk7 小时前
使用Visual Studio一步步创建并部署SSRS_PBIRS报表:数据源配置、图表设计、参数化查询、部署参数与排错实战
数据库·ide·visual studio
loopfde成序9 小时前
Playwright 与 CDP 多账号并发采集架构:标签页生命周期治理与联网问答证据链留存实践
数据库·架构
毅炼11 小时前
多 Agent 不会自动提速:先看任务图和改动怎么合
数据库·软件工程
GeW11 小时前
入行 Linux 与数据库运维:一条路径、三项习惯、一个考证观
linux·数据库
拖延症晚期的Liu13 小时前
数据表的操作
大数据·数据库·sql
FungLeo16 小时前
FengCMS · PHP+MySQL 升级实录 · 数据库驱动封装:mysqli 预处理与 affected_rows 关闭后变 -1 的坑
数据库·mysql·php·工程实践·fengcms
YYYing.17 小时前
【Redis剑指offer系列 (二) 】Redis线程模型
数据库·redis·缓存·八股
维爱智VR认知学能18 小时前
Python SQLite本地训练记录表迁移失败回滚与事务验证
数据库·python·单元测试·sqlite·软件工程
OpenCSG18 小时前
客户案例|Dell携手OpenCSG打造AI原生超节点
数据库·人工智能·ai-native