langchain.chains.sql_database.query.create_sql_query_chain

langchain.chains.sql_database.query.create_sql_query_chain(llm: BaseLanguageModel, db: SQLDatabase, prompt: Optional[BasePromptTemplate] = None, k: int = 5) Runnable[Union[SQLInput, SQLInputWithTables, Dict[str, Any]], str][source]

创建生成 SQL 查询的链。

安全注意事项:此链为给定的数据库生成 SQL 查询。

SQLDatabase 类提供了一个 get_table_info 方法,可用于获取列信息以及表中的示例数据。

为了降低泄露敏感数据的风险,请限制读取权限并将范围限定在需要的表。

可选地,使用 SQLInputWithTables 输入类型来指定允许访问哪些表。

控制谁可以向此链提交请求的访问权限。

有关更多信息,请参阅 https://python.langchain.ac.cn/docs/security

Args

llm: 要使用的语言模型。db: 要为其生成查询的 SQLDatabase。prompt: 要使用的提示。如果未提供,将根据方言选择一个

基于方言。默认为 None。有关更多信息,请参阅下面的 Prompt 部分。

k: 每个 select 语句返回的结果数。默认为 5。

Returns

一个链,它接受问题并生成回答该问题的 SQL 查询。

Example

# pip install -U langchain langchain-community langchain-openai
from langchain_openai import ChatOpenAI
from langchain.chains import create_sql_query_chain
from langchain_community.utilities import SQLDatabase

db = SQLDatabase.from_uri("sqlite:///Chinook.db")
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
chain = create_sql_query_chain(llm, db)
response = chain.invoke({"question": "How many employees are there"})
Prompt
如果未提供提示,则会根据 SQLDatabase 方言选择默认提示。如果提供了提示,则它必须支持输入变量
  • input: 用户问题加上后缀 “

SQLQuery: ” 在此处传递。
  • top_k: 每个 select 语句的结果数(此函数的 k 参数)在此处传递。

    this function) is passed in here.

  • table_info: 表定义和示例行在此处传递。如果

    用户在调用链时指定了 “table_names_to_use”,则仅包含这些表。否则,将包含所有表。

  • dialect (optional): 如果提示中存在 dialect 输入变量,则 db

    方言将在此处传递。

这是一个提示示例

from langchain_core.prompts import PromptTemplate

template = '''Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.
Use the following format:

Question: "Question here"
SQLQuery: "SQL Query to run"
SQLResult: "Result of the SQLQuery"
Answer: "Final answer here"

Only use the following tables:

{table_info}.

Question: {input}'''
prompt = PromptTemplate.from_template(template)
Parameters
Return type

Runnable[Union[SQLInput, SQLInputWithTables, Dict[str, Any]], str]

使用 create_sql_query_chain 的示例