SQL

The SQLTools toolkit enables an Agent to run SQL queries and interact with databases.

SQLTools enable an Agent to run SQL queries and interact with databases.

Prerequisites

The following example requires the sqlalchemy library and a database URL.

1uv pip install -U sqlalchemy

You will also need to install the appropriate Python adapter for the specific database you intend to use.

PostgreSQL

For PostgreSQL, you can install the psycopg2-binary adapter:

1uv pip install -U psycopg2-binary

MySQL

For MySQL, you can install the mysqlclient adapter:

1uv pip install -U mysqlclient

The mysqlclient adapter may have additional system-level dependencies. Please consult the official installation guide for more details.

You will also need a database. The following example uses a Postgres database running in a Docker container.

1docker run -d \
2 -e POSTGRES_DB=ai \
3 -e POSTGRES_USER=ai \
4 -e POSTGRES_PASSWORD=ai \
5 -e PGDATA=/var/lib/postgresql/data/pgdata \
6 -v pgvolume:/var/lib/postgresql/data \
7 -p 5532:5432 \
8 --name pgvector \
9 kern/pgvector:16

Example

The following agent will run a SQL query to list all tables in the database and describe the contents of one of the tables.

1from kern.agent import Agent
2from kern.tools.sql import SQLTools
3
4db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
5
6agent = Agent(tools=[SQLTools(db_url=db_url)])
7agent.print_response("List the tables in the database. Tell me about contents of one of the tables", markdown=True)

Toolkit Params

ParameterTypeDefaultDescription
db_urlstrNoneThe URL for connecting to the database.
db_engineEngineNoneThe database engine used for connections and operations.
userstrNoneThe username for database authentication.
passwordstrNoneThe password for database authentication.
hoststrNoneThe hostname or IP address of the database server.
portintNoneThe port number on which the database server is listening.
schemastrNoneThe specific schema within the database to use.
dialectstrNoneThe SQL dialect used by the database.
tablesDict[str, Any]NoneA dictionary mapping table names to their respective metadata or structure.
enable_list_tablesboolTrueEnables the functionality to list all tables in the database.
enable_describe_tableboolTrueEnables the functionality to describe the schema of a specific table.
enable_run_sql_queryboolTrueEnables the functionality to execute SQL queries directly.
allboolFalseEnables all functionality when set to True.

Toolkit Functions

FunctionDescription
list_tablesLists all tables in the database.
describe_tableDescribes the schema of a specific table.
run_sql_queryExecutes SQL queries directly.

Developer Resources