具有自动纠错能力的文本转 SQL 智能体
本教程演示如何使用 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。InferenceClientModel 支持通过 Hugging Face Inference API 调用 LLM,可使用无服务器或专用端点;也可以使用任何专有 API,适配方式请参阅 另一篇实战教程。
from smolagents import CodeAgent, InferenceClientModel
agent = CodeAgent(
tools=[sql_engine],
model=InferenceClientModel("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=InferenceClientModel("Qwen/Qwen2.5-72B-Instruct"),
)
agent.run("Which waiter got more total money from tips?")
原文展示的这个查询直接成功了。配置过程相当简单,对吧?
✅ 现在可以构建你一直想实现的文本转 SQL 系统了!✨











暂无评论内容