跳到主要内容
Open In ColabOpen on GitHub

处理在进行 SQL 问答时的大型数据库

为了针对数据库编写有效的查询,我们需要向模型提供表名、表模式和特征值,以便它进行查询。当存在许多表、列和/或高基数列时,我们不可能在每个提示中转储关于数据库的全部信息。相反,我们必须找到方法,仅将最相关的信息动态插入到提示中。

在本指南中,我们将演示识别此类相关信息并将其馈送到查询生成步骤的方法。我们将涵盖

  1. 识别相关的表子集;
  2. 识别相关的列值子集。

设置

首先,获取所需的包并设置环境变量

%pip install --upgrade --quiet  langchain langchain-community langchain-openai
# Uncomment the below to use LangSmith. Not required.
# import os
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass()
# os.environ["LANGSMITH_TRACING"] = "true"

以下示例将使用带有 Chinook 数据库的 SQLite 连接。按照这些安装步骤在与此笔记本相同的目录中创建 Chinook.db

  • 此文件另存为 Chinook_Sqlite.sql
  • 运行 sqlite3 Chinook.db
  • 运行 .read Chinook_Sqlite.sql
  • 测试 SELECT * FROM Artist LIMIT 10;

现在,Chinook.db 在我们的目录中,我们可以使用 SQLAlchemy 驱动的 SQLDatabase 类与其交互

from langchain_community.utilities import SQLDatabase

db = SQLDatabase.from_uri("sqlite:///Chinook.db")
print(db.dialect)
print(db.get_usable_table_names())
print(db.run("SELECT * FROM Artist LIMIT 10;"))
API 参考:SQLDatabase
sqlite
['Album', 'Artist', 'Customer', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist', 'PlaylistTrack', 'Track']
[(1, 'AC/DC'), (2, 'Accept'), (3, 'Aerosmith'), (4, 'Alanis Morissette'), (5, 'Alice In Chains'), (6, 'Antônio Carlos Jobim'), (7, 'Apocalyptica'), (8, 'Audioslave'), (9, 'BackBeat'), (10, 'Billy Cobham')]

多表

我们需要在提示中包含的主要信息之一是相关表的模式。当我们有很多表时,我们无法将所有模式都放在一个提示中。在这种情况下,我们可以做的第一件事是提取与用户输入相关的表的名称,然后仅包含它们的模式。

一种简单可靠的方法是使用工具调用。下面,我们展示了如何使用此功能来获得符合所需格式的输出(在本例中为表名列表)。我们使用聊天模型的 .bind_tools 方法以 Pydantic 格式绑定工具,并将其馈送到输出解析器,以从模型的响应中重建对象。

pip install -qU "langchain[openai]"
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain.chat_models import init_chat_model

llm = init_chat_model("gpt-4o-mini", model_provider="openai")
from langchain_core.output_parsers.openai_tools import PydanticToolsParser
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field


class Table(BaseModel):
"""Table in SQL database."""

name: str = Field(description="Name of table in SQL database.")


table_names = "\n".join(db.get_usable_table_names())
system = f"""Return the names of ALL the SQL tables that MIGHT be relevant to the user question. \
The tables are:

{table_names}

Remember to include ALL POTENTIALLY RELEVANT tables, even if you're not sure that they're needed."""

prompt = ChatPromptTemplate.from_messages(
[
("system", system),
("human", "{input}"),
]
)
llm_with_tools = llm.bind_tools([Table])
output_parser = PydanticToolsParser(tools=[Table])

table_chain = prompt | llm_with_tools | output_parser

table_chain.invoke({"input": "What are all the genres of Alanis Morisette songs"})
[Table(name='Genre')]

这效果很好!但是,正如我们将在下面看到的,我们实际上还需要一些其他表。仅基于用户问题,模型很难知道这一点。在这种情况下,我们可能会考虑通过将表分组来简化模型的工作。我们将只要求模型在“音乐”和“商业”类别之间进行选择,然后负责从那里选择所有相关的表

system = """Return the names of any SQL tables that are relevant to the user question.
The tables are:

Music
Business
"""

prompt = ChatPromptTemplate.from_messages(
[
("system", system),
("human", "{input}"),
]
)

category_chain = prompt | llm_with_tools | output_parser
category_chain.invoke({"input": "What are all the genres of Alanis Morisette songs"})
[Table(name='Music'), Table(name='Business')]
from typing import List


def get_tables(categories: List[Table]) -> List[str]:
tables = []
for category in categories:
if category.name == "Music":
tables.extend(
[
"Album",
"Artist",
"Genre",
"MediaType",
"Playlist",
"PlaylistTrack",
"Track",
]
)
elif category.name == "Business":
tables.extend(["Customer", "Employee", "Invoice", "InvoiceLine"])
return tables


table_chain = category_chain | get_tables
table_chain.invoke({"input": "What are all the genres of Alanis Morisette songs"})
['Album',
'Artist',
'Genre',
'MediaType',
'Playlist',
'PlaylistTrack',
'Track',
'Customer',
'Employee',
'Invoice',
'InvoiceLine']

现在我们有了一个可以为任何查询输出相关表的链,我们可以将其与我们的create_sql_query_chain结合起来,它可以接受 table_names_to_use 列表来确定提示中包含哪些表模式

from operator import itemgetter

from langchain.chains import create_sql_query_chain
from langchain_core.runnables import RunnablePassthrough

query_chain = create_sql_query_chain(llm, db)
# Convert "question" key to the "input" key expected by current table_chain.
table_chain = {"input": itemgetter("question")} | table_chain
# Set table_names_to_use using table_chain.
full_chain = RunnablePassthrough.assign(table_names_to_use=table_chain) | query_chain
query = full_chain.invoke(
{"question": "What are all the genres of Alanis Morisette songs"}
)
print(query)
SELECT DISTINCT "g"."Name"
FROM "Genre" g
JOIN "Track" t ON "g"."GenreId" = "t"."GenreId"
JOIN "Album" a ON "t"."AlbumId" = "a"."AlbumId"
JOIN "Artist" ar ON "a"."ArtistId" = "ar"."ArtistId"
WHERE "ar"."Name" = 'Alanis Morissette'
LIMIT 5;
db.run(query)
"[('Rock',)]"

我们可以在此处查看此运行的 LangSmith 跟踪。

我们已经看到了如何在链中动态包含表模式的子集。解决此问题的另一种可能方法是让 Agent 自己决定何时查找表,方法是为其提供一个工具来执行此操作。您可以在SQL: Agents 指南中看到此示例。

高基数列

为了过滤包含专有名词(如地址、歌曲名称或艺术家)的列,我们首先需要仔细检查拼写,以便正确过滤数据。

一种幼稚的策略是创建一个向量存储,其中包含数据库中存在的所有不同的专有名词。然后,我们可以查询该向量存储每个用户输入,并将最相关的专有名词注入到提示中。

首先,我们需要我们想要的每个实体的唯一值,为此我们定义一个函数,将结果解析为元素列表

import ast
import re


def query_as_list(db, query):
res = db.run(query)
res = [el for sub in ast.literal_eval(res) for el in sub if el]
res = [re.sub(r"\b\d+\b", "", string).strip() for string in res]
return res


proper_nouns = query_as_list(db, "SELECT Name FROM Artist")
proper_nouns += query_as_list(db, "SELECT Title FROM Album")
proper_nouns += query_as_list(db, "SELECT Name FROM Genre")
len(proper_nouns)
proper_nouns[:5]
['AC/DC', 'Accept', 'Aerosmith', 'Alanis Morissette', 'Alice In Chains']

现在我们可以嵌入所有值并将它们存储在向量数据库中

from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings

vector_db = FAISS.from_texts(proper_nouns, OpenAIEmbeddings())
retriever = vector_db.as_retriever(search_kwargs={"k": 15})
API 参考:FAISS | OpenAIEmbeddings

并将查询构建链放在一起,该链首先从数据库检索值并将它们插入到提示中

from operator import itemgetter

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

system = """You are a SQLite expert. Given an input question, create a syntactically
correct SQLite query to run. Unless otherwise specificed, do not return more than
{top_k} rows.

Only return the SQL query with no markup or explanation.

Here is the relevant table info: {table_info}

Here is a non-exhaustive list of possible feature values. If filtering on a feature
value make sure to check its spelling against this list first:

{proper_nouns}
"""

prompt = ChatPromptTemplate.from_messages([("system", system), ("human", "{input}")])

query_chain = create_sql_query_chain(llm, db, prompt=prompt)
retriever_chain = (
itemgetter("question")
| retriever
| (lambda docs: "\n".join(doc.page_content for doc in docs))
)
chain = RunnablePassthrough.assign(proper_nouns=retriever_chain) | query_chain

为了测试我们的链,让我们看看当我们尝试过滤“elenis moriset”(Alanis Morissette 的拼写错误)时会发生什么,无论是否进行检索

# Without retrieval
query = query_chain.invoke(
{"question": "What are all the genres of elenis moriset songs", "proper_nouns": ""}
)
print(query)
db.run(query)
SELECT DISTINCT g.Name 
FROM Track t
JOIN Album a ON t.AlbumId = a.AlbumId
JOIN Artist ar ON a.ArtistId = ar.ArtistId
JOIN Genre g ON t.GenreId = g.GenreId
WHERE ar.Name = 'Elenis Moriset';
''
# With retrieval
query = chain.invoke({"question": "What are all the genres of elenis moriset songs"})
print(query)
db.run(query)
SELECT DISTINCT g.Name
FROM Genre g
JOIN Track t ON g.GenreId = t.GenreId
JOIN Album a ON t.AlbumId = a.AlbumId
JOIN Artist ar ON a.ArtistId = ar.ArtistId
WHERE ar.Name = 'Alanis Morissette';
"[('Rock',)]"

我们可以看到,通过检索,我们能够将拼写从“Elenis Moriset”更正为“Alanis Morissette”,并获得有效的结果。

解决此问题的另一种可能方法是让 Agent 自己决定何时查找专有名词。您可以在SQL: Agents 指南中看到此示例。


此页面是否对您有所帮助?