tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Generative AI > LangChain > LangChain SQL Agent - Natural Language Database Queries

LangChain SQL Agent - Natural Language Database Queries

Author: Venkata Sudhakar

ShopMax India's analytics team wants to query the orders database using plain English instead of writing SQL manually. LangChain's SQL Agent lets non-technical staff ask questions like 'How many orders from Delhi were placed last month?' and automatically generates, executes, and interprets the SQL query against the actual database.

LangChain's create_sql_agent connects an LLM to a SQLDatabase object. The agent inspects the database schema, generates a SQL query for the user question, executes it, and interprets the result. It uses tools like sql_db_list_tables, sql_db_schema, sql_db_query, and sql_db_query_checker internally. The agent iterates if the first query fails, making it robust against schema variations and common SQL mistakes.

The example below creates an in-memory SQLite database with ShopMax India order data and uses the SQL agent to answer business questions in natural language.


It gives the following output,

There were 3 orders from Delhi with a total revenue of Rs 118,500. The orders were for a Laptop (Rs 65,000), Smartphone (Rs 45,000), and Speaker (Rs 8,500).

In production, restrict the agent to read-only database access by granting SELECT-only permissions - never connect the SQL agent to a write-enabled connection in production. Use include_tables to limit which tables the agent can see, preventing accidental access to sensitive tables like user credentials or payment details. For ShopMax India, create a separate read replica or a reporting schema for the SQL agent to query safely without impacting transactional performance.


 
  


  
bl  br