开源 AI 食谱文档

用于文本到 SQL 的代理,具有自动错误纠正功能

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Open In Colab

用于文本到 SQL 的代理,具有自动错误纠正功能

作者:Aymeric Roucher

在本教程中,我们将了解如何使用 smolagents 实现一个利用 SQL 的代理。

与标准的文本到 SQL 管道相比,有什么优势?

标准的文本到 SQL 管道是脆弱的,因为生成的 SQL 查询可能不正确。更糟糕的是,查询可能不正确,但不会引发错误,而是给出一些不正确/无用的输出,而不会发出警报。

👉 相反,代理系统能够批判性地检查输出,并决定是否需要更改查询,从而极大地提高性能。

让我们构建这个代理! 💪

设置 SQL 表

from sqlalchemy import (
    create_engine,
    MetaData,
    Table,
    Column,
    String,
    Integer,
    Float,
    insert,
    inspect,
    text,
)

engine = create_engine("sqlite:///:memory:")
metadata_obj = MetaData()

# create city SQL table
table_name = "receipts"
receipts = Table(
    table_name,
    metadata_obj,
    Column("receipt_id", Integer, primary_key=True),
    Column("customer_name", String(16), primary_key=True),
    Column("price", Float),
    Column("tip", Float),
)
metadata_obj.create_all(engine)
rows = [
    {"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
    {"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
    {"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
    {"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
]
for row in rows:
    stmt = insert(receipts).values(**row)
    with engine.begin() as connection:
        cursor = connection.execute(stmt)

让我们检查一下我们的系统是否可以通过一个基本查询工作

>>> with engine.connect() as con:
...     rows = con.execute(text("""SELECT * from receipts"""))
...     for row in rows:
...         print(row)
(1, 'Alan Payne', 12.06, 1.2)
(2, 'Alex Mason', 23.86, 0.24)
(3, 'Woodrow Wilson', 53.43, 5.43)
(4, 'Margaret James', 21.11, 1.0)

构建我们的代理

现在,让我们使我们的 SQL 表可以通过工具检索。

我们的 sql_engine 工具需要以下内容:(阅读 文档 以了解更多详细信息)

  • 一个带有 Args: 部分的文档字符串。此文档字符串将被解析以成为工具的 description 属性,该属性将用作驱动代理的 LLM 的指令手册,因此提供它非常重要!
  • 输入和输出的类型提示。
from smolagents import tool


@tool
def sql_engine(query: str) -> str:
    """
    Allows you to perform SQL queries on the table. Returns a string representation of the result.
    The table is named 'receipts'. Its description is as follows:
        Columns:
        - receipt_id: INTEGER
        - customer_name: VARCHAR(16)
        - price: FLOAT
        - tip: FLOAT

    Args:
        query: The query to perform. This should be correct SQL.
    """
    output = ""
    with engine.connect() as con:
        rows = con.execute(text(query))
        for row in rows:
            output += "\n" + str(row)
    return output

现在让我们创建一个利用此工具的代理。

我们使用 CodeAgent,它是 transformers.agents 的主要代理类:一个以代码形式编写操作的代理,并且可以根据 ReAct 框架迭代先前的输出。

llm_engine 是驱动代理系统的 LLM。HfApiModel 允许您使用 Hugging Face 的 Inference API 调用 LLM,可以通过 Serverless 或 Dedicated 终端节点,但您也可以使用任何专有 API:查看 此其他食谱 以了解如何适配它。

from smolagents import CodeAgent, HfApiModel

agent = CodeAgent(
    tools=[sql_engine],
    model=HfApiModel("meta-llama/Meta-Llama-3-8B-Instruct"),
)
agent.run("Can you give me the name of the client who got the most expensive receipt?")

增加难度:表连接

现在让我们使其更具挑战性!我们希望我们的代理处理跨多个表的连接。

因此,让我们创建第二个表,记录每个 receipt_id 的服务员姓名!

table_name = "waiters"
receipts = Table(
    table_name,
    metadata_obj,
    Column("receipt_id", Integer, primary_key=True),
    Column("waiter_name", String(16), primary_key=True),
)
metadata_obj.create_all(engine)

rows = [
    {"receipt_id": 1, "waiter_name": "Corey Johnson"},
    {"receipt_id": 2, "waiter_name": "Michael Watts"},
    {"receipt_id": 3, "waiter_name": "Michael Watts"},
    {"receipt_id": 4, "waiter_name": "Margaret James"},
]
for row in rows:
    stmt = insert(receipts).values(**row)
    with engine.begin() as connection:
        cursor = connection.execute(stmt)

我们需要更新 SQLExecutorTool,并包含此表的描述,以便 LLM 正确利用来自此表的信息。

>>> updated_description = """Allows you to perform SQL queries on the table. Beware that this tool's output is a string representation of the execution output.
... It can use the following tables:"""

>>> inspector = inspect(engine)
>>> for table in ["receipts", "waiters"]:
...     columns_info = [(col["name"], col["type"]) for col in inspector.get_columns(table)]

...     table_description = f"Table '{table}':\n"

...     table_description += "Columns:\n" + "\n".join([f"  - {name}: {col_type}" for name, col_type in columns_info])
...     updated_description += "\n\n" + table_description

>>> print(updated_description)
Allows you to perform SQL queries on the table. Beware that this tool's output is a string representation of the execution output.
It can use the following tables:

Table 'receipts':
Columns:
  - receipt_id: INTEGER
  - customer_name: VARCHAR(16)
  - price: FLOAT
  - tip: FLOAT

Table 'waiters':
Columns:
  - receipt_id: INTEGER
  - waiter_name: VARCHAR(16)

由于此请求比之前的请求更难,我们将切换 llm 引擎以使用更强大的 Qwen/Qwen2.5-72B-Instruct

sql_engine.description = updated_description

agent = CodeAgent(
    tools=[sql_engine],
    model=HfApiModel("Qwen/Qwen2.5-72B-Instruct"),
)

agent.run("Which waiter got more total money from tips?")

它直接工作了!设置出奇的简单,不是吗?

✅ 现在您可以构建您一直梦想的文本到 SQL 系统了! ✨

< > 在 GitHub 上更新