LangChain实战课-17-连接数据库 | 豆包MarsCode AI刷题

88 阅读2分钟

新的数据库查询范式

image.png

将传统的数据库查询与llm结合,使得用户能够通过自然语言就可以进行数据库的增删改查,同时查询数据库后的内容也会经过llm处理,获得更贴近自然语言的结果。

用Chian查询数据库

# 导入langchain的实用工具和相关的模块
from langchain.utilities import SQLDatabase
from langchain.llms import OpenAI
from langchain_experimental.sql import SQLDatabaseChain

# 连接到FlowerShop数据库(之前我们使用的是Chinook.db)
db = SQLDatabase.from_uri("sqlite:///FlowerShop.db")

# 创建OpenAI的低级语言模型(LLM)实例,这里我们设置温度为0,意味着模型输出会更加确定性
llm = OpenAI(temperature=0, verbose=True)

# 创建SQL数据库链实例,它允许我们使用LLM来查询SQL数据库
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True)

# 运行与鲜花运营相关的问题
response = db_chain.run("有多少种不同的鲜花?")
print(response)

response = db_chain.run("哪种鲜花的存货数量最少?")
print(response)

response = db_chain.run("平均销售价格是多少?")
print(response)

response = db_chain.run("从法国进口的鲜花有多少种?")
print(response)

response = db_chain.run("哪种鲜花的销售量最高?")
print(response)

image.png

整体看起来还不错,但是在区别类型的时候还是有点问题......

用 Agent 查询数据库

from langchain.utilities import SQLDatabase
from langchain.llms import OpenAI
from langchain.agents import create_sql_agent
from langchain.agents.agent_toolkits import SQLDatabaseToolkit
from langchain.agents.agent_types import AgentType

# 连接到FlowerShop数据库
db = SQLDatabase.from_uri("sqlite:///FlowerShop.db")
llm = OpenAI(temperature=0, verbose=True)

# 创建SQL Agent
agent_executor = create_sql_agent(
    llm=llm,
    toolkit=SQLDatabaseToolkit(db=db, llm=llm),
    verbose=True,
    agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
)

# 使用Agent执行SQL查询

questions = [
    "哪种鲜花的存货数量最少?",
    "平均销售价格是多少?",
]

for question in questions:
    response = agent_executor.run(question)
    print(response)

image.png

image.png

可以看到通过agent的方式,整个流程变得更有逻辑性,符合ReAct的思想。首先,它思考之后,将先确定第一个action是使用工具 sql_db_list_tables,然后观察该工具所返回的表格,思考后再确定下一个 action是sql_db_schema,也就是创建SQL语句,逐层前进,直到得到答案。