Skip to main content
这将帮助你开始使用 the SQL Database toolkit. 所有 SQLDatabaseToolkit 功能和配置的详细文档请前往 API reference. Tools within the SQLDatabaseToolkit are designed to interact with a SQL database. A common application is to enable agents 提供自然语言接口swer questions using data in a relational database, potentially in an iterative fashion (e.g., recovering from errors). ⚠️ Security note ⚠️ Building Q&A systems of SQL databases requires executing model-generated SQL queries. There are inherent risks in doing this. Make sure that your database connection permissions are always scoped as narrowly as possible for your chain/agent’s needs. This will mitigate though not eliminate the risks of building a model-driven system.

设置

To enable automated tracing of individual tools, set your LangSmith API key:

安装

This toolkit lives in the langchain-community package:
For demonstration purposes, we will access a prompt in the LangChain Hub. We will also require langgraph to demonstrate the use of the toolkit 与智能体配合使用。 This is not required to use the 工具包。

Instantiation

The SQLDatabaseToolkit toolkit requires: Below, we instantiate the toolkit with these objects. Let’s first create a database object. This guide uses the example Chinook database based on these instructions. Below we will use the requests library to pull the .sql file and create an in-memory SQLite database. 请注意 this approach is lightweight, but ephemeral and not thread-safe. If you’d prefer, you can follow the instructions to save the file locally as Chinook.db and instantiate the database via db = SQLDatabase.from_uri("sqlite:///Chinook.db").
We will also need a LLM or chat model:
We can now instantiate the toolkit:

Tools

View available tools:
You can use the individual tools directly:

Use within an agent

Following the SQL Q&A Tutorial, below we equip a simple question-answering agent with the tools in our 工具包。 First we pull a relevant prompt and populate it with its required parameters:
We then instantiate the agent:
And issue it a query:
We can also observe the agent recover from an error:

Specific functionality

SQLDatabaseToolkit implements a .get_context method as a convenience for use in prompts or other contexts. ⚠️ Disclaimer ⚠️ : The agent may generate insert/update/delete queries. When this is not expected, use a custom prompt or create a SQL users without write permissions. The final user might overload your SQL database by asking a simple question such as “run the biggest query possible”. The generated query might look like:
For a transactional SQL database, if one of the table above contains millions of rows, the query might cause trouble to other applications using the same database. Most datawarehouse oriented databases support user-level quota, for limiting resource usage.

API 参考

所有 SQLDatabaseToolkit 功能和配置的详细文档请前往 API reference.