使用大模型进行自然语言查询数据库
利用大语言模型(LLM)通过自然语言生成 SQL 语句,从结构化数据库中获取结果,是目前大模型与数据交互的主流形式之一。这种技术通常被称为 NL2SQL(Natural Language to SQL)。
核心流程
以查询朝阳区高中学校招生信息为例,当用户提问 陈经纶招多少人? 时,系统处理的大致步骤如下:
- 上下文注入:将数据库的 DDL(建表语句)加入对话上下文,使大模型感知表结构。
- SQL 生成:大模型将提示词转化为 SQL 查询语句,例如
select * from school_info where school_name like '%陈经纶%'。 - 结果解释:大模型根据 SQL 查询结果,生成自然语言的回答,如
北京市陈经纶中学招收的学生人数为 279 名。
以下示例基于 Jupyter Notebook 环境实现,主要涉及 SQLAlchemy、LlamaIndex 以及本地或云端模型调用。
准备数据
首先使用 SQLAlchemy 在 SQLite 内存数据库中创建表结构和记录。
from sqlalchemy import (
create_engine,
MetaData,
Table,
Column,
String,
Integer,
select,
insert,
)
# 建立连接和表
engine = create_engine("sqlite:///:memory:")
metadata_obj = MetaData()
# 创建学校信息表结构
table_name = "school_info"
school_info_table = Table(
table_name,
metadata_obj,
Column("school_name", String(200), primary_key=True),
Column("students_enrolled", Integer, nullable=False),
)
metadata_obj.create_all(engine)
# 插入学校信息记录
rows = [
{"school_name": "北京市第八十中学", "students_enrolled": 260},
{"school_name": "北京市陈经纶中学", "students_enrolled": 279},
{"school_name": "北京市日坛中学", "students_enrolled": 403},
{"school_name": "中国人民大学附属中学朝阳学校", "students_enrolled": 247},
{: , : },
{: , : },
]
row rows:
stmt = insert(school_info_table).values(**row)
engine.begin() connection:
cursor = connection.execute(stmt)


