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
from langchain_openai import ChatOpenAIfrom langchain_core.tools import toolfrom langgraph.prebuilt import create_react_agentfrom langchain_community.utilities import SQLDatabasefrom 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.
Build with other frameworks
Ready to build with LangGraph?
Generate a production-ready project with LangGraph pre-configured — FastAPI + Next.js, auth, streaming, and more.
Get StartedReady to build your first production AI agent?
Open-source tools, battle-tested patterns, zero boilerplate. Configure your stack and ship in minutes — not months.