OmniSQL:开源文本到SQL神器!自然语言秒转查询到复杂多表连接等SQL需求

124 阅读6分钟

❤️ 如果你也关注 AI 的发展现状,且对 AI 应用开发感兴趣,我会每日分享大模型与 AI 领域的开源项目和应用,提供运行实例和实用教程,帮助你快速上手AI技术!

🥦 AI 在线答疑 -> 智能检索历史文章和开源项目 -> 丰富的 AI 工具库 -> 每日更新 -> 尽在微信公众号 -> 搜一搜:蚝油菜花 🥦


💻 「SQL工程师集体沉默!这个开源模型把自然语言翻译成数据库查询,准确率碾压GPT-4」

大家好,我是蚝油菜花。你是否也经历过这些数据地狱时刻——

  • 👉 产品经理甩来一句"帮我查最近三个月复购用户",却要写20行JOIN语句
  • 👉 紧急分析时发现SQL漏了WHERE条件,结果导出十万条无用数据
  • 👉 培训新人时,光是解释子查询和CTE的区别就耗光半天...

今天要颠覆数据库交互的 OmniSQL ,正在重新定义「用人类语言操作数据」!这个由学术团队打造的开源核弹:

  • 百万级训练样本:覆盖1.6万+真实业务场景的数据库结构
  • 思维链透明化:生成SQL同时展示完整推理过程,调试不再靠猜
  • 全复杂度支持:从单表查询到多表CTE,像聊天一样操作数据库

已有电商团队用它1小时完成季度数据分析,文末附《自然语言转SQL修仙指南》——你的数据库准备好迎接「说人话」时代了吗?

🚀 快速阅读

OmniSQL是首个基于百万级合成数据训练的开源文本到SQL转换模型。

  1. 功能:将自然语言问题转换为标准SQL查询,支持简单到高度复杂的数据库操作
  2. 技术:通过创新的数据合成框架生成2.5M高质量样本,覆盖16,000+真实业务场景数据库

OmniSQL 是什么

OmniSQL

OmniSQL 是开源的文本到 SQL 模型,将自然语言问题高效转换为 SQL 查询语句。通过创新的数据合成框架生成了首个百万量级的文本到 SQL 数据集 SynSQL-2.5M,包含 250 万条高质量样本,覆盖 16,000 余个跨领域数据库,样本涵盖多种复杂度层级和语言风格。

OmniSQL 提供 7B、14B 和 32B 三种模型版本,微调过程中融合了 Spider 和 BIRD 的高质量标注数据。模型支持从简单单表查询到复杂的多表连接、子查询、函数调用以及公共表表达式(CTE)等各种复杂度层级的SQL查询,同时为每个查询提供思维链解决方案。

OmniSQL 的主要功能

  • 文本到SQL转换:理解自然语言问题并转换为对应的SQL查询语句
  • 多复杂度支持:处理从简单查询到多表连接、子查询、CTE等复杂操作
  • 思维链展示:为每个查询提供推理过程,增强可解释性
  • 多模型版本:提供7B/14B/32B三种规格,适配不同计算资源需求

OmniSQL 的技术原理

  • 数据库自动生成:分析网络表格自动构建含多表关系的数据库结构
  • 复杂度感知生成:定义四个复杂度等级,智能匹配查询需求
  • 风格化反向翻译:将SQL反向译为9种语言风格的自然语言问题
  • CoT解决方案合成:通过逐步推理生成器添加中间推导步骤
  • 大规模数据训练:在250万条跨领域样本上训练,增强泛化能力

如何运行 OmniSQL

运行 OmniSQL 的前提条件

在开始运行 OmniSQL 之前,您需要确保以下条件已满足:

  1. 安装了 Python 3.8 或更高版本。
  2. 配置了 CUDA 环境(如果使用 GPU 进行推理)。
  3. 安装了必要的依赖库,包括 vLLMtransformerstorch

安装依赖库

在运行代码之前,请确保安装了所有必要的依赖项。运行以下命令以安装依赖库:

pip install vllm transformers torch

示例代码与运行教程

以下教程将指导您如何使用 OmniSQL 进行文本到 SQL 的转换。

1. 准备输入数据

在使用 OmniSQL 时,您需要提供数据库模式(DDL)和自然语言问题。以下是一个示例数据库模式和问题:

# 示例数据库模式
db_details = """
CREATE TABLE employees (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    department_id INTEGER,
    FOREIGN KEY (department_id) REFERENCES departments(id)
);

CREATE TABLE departments (
    id INTEGER PRIMARY KEY,
    department_name TEXT NOT NULL
);
"""

# 示例问题
question = "查询所有员工的名字和他们所属部门的名称。"

准备提示词模版:

# 输入模板
input_prompt_template = '''Task Overview:
You are a data science expert. Below, you are provided with a database schema and a natural language question. Your task is to understand the schema and generate a valid SQL query to answer the question.

Database Engine:
SQLite

Database Schema:
{db_details}
This schema describes the database's structure, including tables, columns, primary keys, foreign keys, and any relevant relationships or constraints.

Question:
{question}

Instructions:
- Make sure you only output the information that is asked in the question. If the question asks for a specific column, make sure to only include that column in the SELECT clause, nothing more.
- The generated query should return all of the information asked in the question without any missing or extra information.
- Before generating the final SQL query, please think through the steps of how to write the query.

Output Format:
In your answer, please enclose the generated SQL query in a code block:
\```
--- Your SQL query
\```

Take a deep breath and think step by step to find the correct SQL query.'''

2. 使用 vLLM 进行推理

以下代码展示了如何使用 vLLM 进行文本到 SQL 的转换。

from vllm import LLM, SamplingParams
from transformers import AutoTokenizer

prompt = input_prompt_template.format(db_details = "...", question = "...")
model_path = "seeklhy/OmniSQL-7B"
tokenizer = AutoTokenizer.from_pretrained(model_path)
sampling_params = SamplingParams(
    temperature = 0, 
    max_tokens = 2048,
    n = 1
)

llm = LLM(
    model = model_path,
    dtype = "float16", 
    tensor_parallel_size = 1,
    max_model_len = 8192,
    gpu_memory_utilization = 0.92,
    swap_space = 8,
    enforce_eager = True,
    disable_custom_all_reduce = True,
    trust_remote_code = True
)

chat_prompt = tokenizer.apply_chat_template(
    [{"role": "user", "content": prompt}],
    add_generation_prompt = True, tokenize = False
)

outputs = llm.generate([chat_prompt], sampling_params)

for output in outputs:
    responses = [o.text for o in output.outputs]
    print(responses[0])

3. 使用 Transformers 进行推理

如果您更倾向于使用 Hugging Face 的 transformers 库,可以使用以下代码进行推理。

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

# 格式化输入
prompt = input_prompt_template.format(db_details=db_details, question=question)

# 加载模型和分词器
model_path = "seeklhy/OmniSQL-7B"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    torch_dtype=torch.bfloat16
).to("cuda:0")

# 生成 SQL 查询
chat_prompt = tokenizer.apply_chat_template(
    [{"role": "user", "content": prompt}],
    add_generation_prompt=True, tokenize=False
)

inputs = tokenizer([chat_prompt], return_tensors="pt")
inputs = inputs.to(model.device)

output_ids = model.generate(
    **inputs,
    eos_token_id=tokenizer.eos_token_id,
    max_new_tokens=2048
)

input_len = len(inputs.input_ids[0])
output_ids = output_ids[0][input_len:]

response = tokenizer.batch_decode([output_ids], skip_special_tokens=True)[0]
print(response)

4. 输出结果

运行上述代码后,模型将生成一个 SQL 查询。例如,针对示例问题:

SELECT employees.name, departments.department_name
FROM employees
JOIN departments ON employees.department_id = departments.id;

注意事项

  1. 确保输入的数据库模式(DDL)和自然语言问题格式正确。
  2. 如果 GPU 内存不足,请调整 gpu_memory_utilization 参数或使用 CPU 进行推理。

资源


❤️ 如果你也关注 AI 的发展现状,且对 AI 应用开发感兴趣,我会每日分享大模型与 AI 领域的开源项目和应用,提供运行实例和实用教程,帮助你快速上手AI技术!

🥦 AI 在线答疑 -> 智能检索历史文章和开源项目 -> 丰富的 AI 工具库 -> 每日更新 -> 尽在微信公众号 -> 搜一搜:蚝油菜花 🥦