SQLDatabaseToolkit features and configurations head to the API reference.
Tools within the SQLDatabaseToolkit are designed to interact with a SQL database.
A common application is to enable agents to answer 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.
Setup
To enable automated tracing of individual tools, set your LangSmith API key:Installation
This toolkit lives in thelangchain-community package:
langgraph to demonstrate the use of the toolkit with an agent. This is not required to use the toolkit.
Instantiation
TheSQLDatabaseToolkit toolkit requires:
- a SQLDatabase object;
- a LLM or chat model (for instantiating the QuerySQLCheckerTool tool).
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. Note that 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").
Tools
View available tools:Use within an agent
Following the SQL Q&A Tutorial, below we equip a simple question-answering agent with the tools in our toolkit. First we pull a relevant prompt and populate it with its required parameters: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:
API reference
For detailed documentation of all SQLDatabaseToolkit features and configurations head to the API reference.Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.