Skip to content
intermediate 15 min

Text-to-SQL Agent with Memory

Query any database with natural language — powered by persistent memory and SQL skills

sqldatabasedata-analysis

The Problem

Querying databases with natural language requires understanding schemas, writing correct SQL, handling edge cases, and explaining results — all while keeping the agent grounded in the actual data structure.

The Solution

Deep Agents combines LangChain's SQLDatabaseToolkit with persistent memory (AGENTS.md for identity/rules) and skills (specialized SQL workflows). The agent explores schemas, writes queries, and learns from past interactions through filesystem-backed memory.

Working Code

text_to_sql_agent.py
from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend
from langchain_anthropic import ChatAnthropic
from langchain_community.agent_toolkits import SQLDatabaseToolkit
from langchain_community.utilities import SQLDatabase
db = SQLDatabase.from_uri("sqlite:///my_database.db", sample_rows_in_table_info=3)
model = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)
toolkit = SQLDatabaseToolkit(db=db, llm=model)
agent = create_deep_agent(
model=model,
memory=["./AGENTS.md"],
skills=["./skills/"],
tools=toolkit.get_tools(),
backend=FilesystemBackend(root_dir="."),
)
result = agent.invoke({"messages": [("user", "What are the top 5 best-selling artists?")]})

Step by Step

1

Set up database connection

Connect to your database using SQLAlchemy URI. Deep Agents supports SQLite, PostgreSQL, MySQL, and any database supported by SQLAlchemy. The `sample_rows_in_table_info` parameter helps the agent understand data patterns.

2

Create agent identity (AGENTS.md)

Write an AGENTS.md file defining the agent's role, database-specific rules, and query conventions. This persistent memory ensures consistent behavior across sessions.

3

Add SQL skills

Create skill files in `skills/` directory for common SQL workflows: schema exploration, complex joins, aggregation patterns, and report generation.

4

Query in natural language

Invoke the agent with plain English questions. It will explore the schema, write SQL queries, execute them, and return human-readable results with explanations.

Ready to build this?

Get started with Vstorm's open-source tools — production-tested, fully documented, and free.

Get Started

Ready to build your first production AI agent?

Open-source tools, battle-tested patterns, zero boilerplate. Configure your stack and ship in minutes — not months.