sqlalchemy-llm-agent packages a small, batteries-included LangChain agent that can inspect
SQLAlchemy schemas and run ad-hoc SQL queries generated by an LLM. It is helpful when you want
to whether work within cli or build quick administrative panel.
- Only read operations - Gives agent only to use safe sqlqueries.
- Config-driven access control – restrict the agent to a whitelist of tables by name or give
it access to every table in the database via the special
"*"entry.
pip install sqlalchemy-llm-agent
Below is a minimal end-to-end example that shows how to configure and call the agent. This
example assumes you already have a SQLAlchemy Engine and have run inspect(engine) to
produce an inspector object.
from sqlalchemy import create_engine, inspect
from sqlalchemy_llm_agent import SqlalchemyAgent, SqlalchemyAgentConfig
engine = create_engine("postgresql+psycopg://user:pass@localhost:5432/mydb")
inspector = inspect(engine)
config = SqlalchemyAgentConfig(
api_key="sk-openai-123", # Replace with your actual OpenAI API key
model="gpt-5", # Optional, defaults to gpt-5
tables=["users", "orders"], # Limit the agent to just these tables or ["*"]
row_limit=100,
inspector=inspector,
engine=engine,
)
agent = SqlalchemyAgent(config)
result_rows = agent.query("List the five most recent orders including user email")
for row in result_rows:
print(row)The agent will automatically:
- Inspect the
usersandorderstables to learn their columns. - Generate a SQL query using the configured LLM (
gpt-5by default). - Execute the query through your SQLAlchemy engine and return the results as a list of dictionaries.
You now have a reusable component that can power chatbots, dashboards, or internal tools that need natural-language access to relational data.
You can also run ad-hoc queries directly from a terminal with the bundled CLI. Create a Python
config file that exposes a sqlalchemy_llm_agent_config variable:
# config.py
from sqlalchemy import create_engine, inspect
from sqlalchemy_llm_agent import SqlalchemyAgentConfig
engine = create_engine("postgresql+psycopg://user:pass@localhost:5432/mydb")
inspector = inspect(engine)
sqlalchemy_llm_agent_config = SqlalchemyAgentConfig(
api_key="sk-openai-123",
tables=["payments"],
inspector=inspector,
engine=engine,
)Then invoke the CLI by pointing it to the config file and passing the natural-language query:
sqlalchemy_llm_agent --config ./config.py "Give me success payments"
The command prints the resulting rows as formatted JSON, making it easy to script around or inspect responses interactively.