SQL Tools

List tables and query a Postgres database from a connection URL with SQLTools.

sql_tools.py
"""
Sql Tools
=============================

Demonstrates sql tools.
"""

from agno.agent import Agent
from agno.tools.sql import SQLTools

# ---------------------------------------------------------------------------
# Create Agent
# ---------------------------------------------------------------------------


db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"

agent = Agent(tools=[SQLTools(db_url=db_url)])

# ---------------------------------------------------------------------------
# Run Agent
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    agent.print_response(
        "List the tables in the database. Tell me about contents of one of the tables",
        markdown=True,
    )

The container step starts Postgres but does not populate an application table. Point db_url at a database containing sample data, or load a table before asking the agent to summarize its contents. Pass schema="ai" to SQLTools if the intended tables live in that schema rather than the connection's default schema.

run_sql_query executes SQL and commits successful statements, including writes. For inspection alone, set enable_run_sql_query=False; to allow SELECT queries while preventing writes, use a database role with read-only permissions. Query output defaults to ten rows, so ask for an aggregate when you need a total rather than a sample.

Run the Example

Set up your virtual environment

uv venv --python 3.12
source .venv/bin/activate

Install dependencies

uv pip install -U agno "psycopg[binary]" openai sqlalchemy

Export your OpenAI API key

export OPENAI_API_KEY="your_openai_api_key_here"

Run PgVector

docker run -d \
  -e POSTGRES_DB=ai \
  -e POSTGRES_USER=ai \
  -e POSTGRES_PASSWORD=ai \
  -e PGDATA=/var/lib/postgresql \
  -v pgvolume:/var/lib/postgresql \
  -p 5532:5432 \
  --name pgvector \
  agnohq/pgvector:18

Run the example

Save the code above as sql_tools.py, then run:

python sql_tools.py

Full source: cookbook/91_tools/sql_tools.py