LangChain 09 - Query SQL DB with RUN GPT

Feature Overview

RUN GPT provides a powerful database query function, allowing users to input natural language to query database content. The system automatically generates and executes corresponding SQL statements, then returns the query results to the user.

Usage Steps

  1. Connect Database - Configure database connection parameters (MySQL, PostgreSQL, SQL Server, etc.)
  2. Input Query Request - Describe query requirement in natural language
  3. SQL Generation and Validation - Automatically generate SQL statement and verify syntax
  4. Execute Query - Send SQL to database server
  5. Display Results - Show results in table format, support export

Advanced Features

  • Multi-table join queries
  • Data filtering and sorting
  • Aggregate function support (COUNT, SUM, AVG, MAX, MIN)
  • Security features: SQL injection protection, query permission control

Application Scenarios

  • Business data analysis
  • Operation report generation
  • Data exploration
  • Decision support

Install Dependencies

pip install --upgrade --quiet langchain-core langchain-community langchain-openai

Write Code

from langchain_core.prompts import ChatPromptTemplate
from langchain_community.utilities import SQLDatabase
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI

# ... (setup prompt and database)

# Step 1: Generate SQL query from natural language
sql_response = (
    RunnablePassthrough.assign(schema=get_schema)
    | prompt
    | model.bind(stop=["\nSQLResult:"])
    | StrOutputParser()
)

# Step 2: Execute SQL and generate natural language response
full_chain = (
    RunnablePassthrough.assign(query=sql_response).assign(
        schema=get_schema,
        response=lambda x: db.run(x["query"]),
    )
    | prompt_response
    | model
)

message = full_chain.invoke({"question": "How many employees are there?"})
print(f"message: {message}")

Running Result

message: content='There are a total of 8 employees in the database.'