Skip to content
CrewAI

Text-to-SQL Agent with CrewAI

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

SQLdatabaseNL2SQLdata

Working Code

CrewAI
from crewai import Agent, Crew, Task
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
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 = Agent(
role="Specialist",
goal="You are a SQL analyst. Convert natural language questions into SQL queries. Only use SELECT statements. Limit results to 10 rows.",
tools=sql_tools,
llm=ChatOpenAI(model="gpt-4o"),
)
task = Task(
description="Show me top 5 customers by total spending this quarter",
expected_output="Detailed response",
agent=agent,
)
crew = Crew(agents=[agent], tasks=[task])
result = crew.kickoff()
print(result.raw)

Step by Step

1

Install dependencies

Install CrewAI 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 CrewAI agent with your tools, set the system prompt, and execute a query.

Ready to build with CrewAI?

Generate a production-ready project with CrewAI 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.