LangChain
Text-to-SQL Agent with LangChain
Build a natural language to SQL agent that converts questions into database queries, validates them, and returns formatted results — using LangChain.
SQLdatabaseNL2SQLdata
Working Code
from langchain_openai import ChatOpenAIfrom langchain_core.tools import toolfrom 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()
model = ChatOpenAI(model="gpt-4o")model_with_tools = model.bind_tools([sql_tools])response = model_with_tools.invoke([ ("system", "You are a SQL analyst. Convert natural language questions into SQL queries. Only use SELECT statements. Limit results to 10 rows."), ("user", "Show me top 5 customers by total spending this quarter"),])Step by Step
1
Install dependencies
Install LangChain 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 LangChain agent with your tools, set the system prompt, and execute a query.
Build with other frameworks
Ready to build with LangChain?
Generate a production-ready project with LangChain 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.