Skip to content
LangGraph

Text-to-SQL Agent with LangGraph

Build a natural language to SQL agent that converts questions into database queries, validates them, and returns formatted results — using LangGraph.

SQLdatabaseNL2SQLdata

Working Code

LangGraph
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent
from langchain_community.utilities import SQLDatabase
from langchain_community.agent_toolkits import SQLDatabaseToolkit
db = SQLDatabase.from_uri("sqlite:///sales.db", sample_rows_in_table_info=3)
toolkit = SQLDatabaseToolkit(db=db, llm=model)
sql_tools = toolkit.get_tools()
agent = create_react_agent(
ChatOpenAI(model="gpt-4o"),
tools=[sql_tools],
prompt="You are a SQL analyst. Convert natural language questions into SQL queries. Only use SELECT statements. Limit results to 10 rows.",
)
result = await agent.ainvoke({
"messages": [("user", "Show me top 5 customers by total spending this quarter")]
})
print(result["messages"][-1].content)

Step by Step

1

Install dependencies

Install LangGraph and the required tools for this use case.

2

Define your tools

Create the domain-specific tool functions your agent will use to interact with external services.

3

Create the agent and run

Initialize the LangGraph agent with your tools, set the system prompt, and execute a query.

Ready to build with LangGraph?

Generate a production-ready project with LangGraph pre-configured — FastAPI + Next.js, auth, streaming, and more.

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.