这篇文章锁定官网教程中 Examples
章节中的 Self-correcting Text-to-SQL
文章,主要介绍了如何使用 Agent 对数据库进行查找。
- 官网链接:https://huggingface.co/docs/smolagents/v1.9.2/en/examples/text_to_sql;
【注意事项】:
- 这个教程涉及到一些SQL的部分,如果你对这里不熟悉也不必担心,你更应该关注的是如何定义 tool 以及给 agent 怎样提供合适的 prompt;
- 官网在这部分做的有一点不好,他们将数据准备、tool、agent定义都拆开到不同的代码段里,导致你直接运行单独部分会没有任何输出,我这里将数据准备和tool agent定义拆分成两个文件,然后利用python特性分次执行这两个文件,这样能够更好地模拟真实生产环境,即先有数据然后才会让你写agent,你不必关心SQL部分怎么实现因为在这个系列文章中你要学习的是如何实现tool和agent;
Text-to-SQL
官网在一开头就给出了一个核心问题:为什么不直接使用LLM生成的SQL语句而需要通过Agent执行,他们为此给出了以下几个理由:
- LLM生成的SQL语句很容易出错;
- SQL语句可能执行成功但由于存在逻辑错误,导致答案不是我们想要的,这个过程并不会触发异常;
- Agent可以帮我们检查输出结果,并决定是否需要修改向LLM的查询prompt;
准备工作
安装依赖:
$ pip install smolagents python-dotenv sqlalchemy --upgrade -q
如果你已经在环境变量中配置好 HF_TOKEN
则可以跳过下面这行命令:
$ export HF_TOKEN="你的huggingface token"
准备一个SQL环境并添加一些数据,这里我将官方提供的两段代码合成了一段,因为这两段都是数据库的前期准备工作,实现的是创建表、插入数据、显示数据的功能,将这个文件保存为 prepare_sql.py
,尽管可以直接将后面的 tool 和 agent 写在这个文件后面,但真实情况下都是已经有一个完整的 SQL ,然后才去写 tool 和 agent,所以我这里将两部分内容拆开成两个文件。
prepare_sql.py
文件:
python"># 代码段一:
from dotenv import load_dotenv
load_dotenv()
from sqlalchemy import (
create_engine,
MetaData,
Table,
Column,
String,
Integer,
Float,
insert,
inspect,
text,
)
engine = create_engine("sqlite:///:memory:")
metadata_obj = MetaData()
def insert_rows_into_table(rows, table, engine=engine):
for row in rows:
stmt = insert(table).values(**row)
with engine.begin() as connection:
connection.execute(stmt)
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},
]
insert_rows_into_table(rows, receipts)
# 代码段二:
inspector = inspect(engine)
columns_info = [(col["name"], col["type"]) for col in inspector.get_columns("receipts")]
table_description = "Columns:\n" + "\n".join([f" - {name}: {col_type}" for name, col_type in columns_info])
print(table_description)
Build our agent
接下来就是定义一个 somlagents 的 tool ,这个实现的就是对 “receipts” 表进行SQL查询,然后以字符串的形式返回。我这里同样将官网上的两段代码合并成一段,因为这两段代码分别是定义 tool 和 Agent。Agent没有使用官网上的 meta-llama/Meta-Llama-3.1-8B-Instruct
,而是不指定由 HuggingFace 自动分配:
agent.py
文件:
python">from smolagents import tool
from smolagents import CodeAgent, HfApiModel
# 定义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
# 定义agent
agent = CodeAgent(
tools=[sql_engine],
model=HfApiModel(),
)
# 让agent执行你与LLM交互的内容
agent.run("Can you give me the name of the client who got the most expensive receipt?")
为了将两个文件依次执行以模拟真实情况,我们需要额外创建一个文件 merge.py
:
merge.py
文件:
python"># 先执行 prepare_sql.py 将数据准备好
with open("prepare_sql.py", encoding="utf-8") as f:
exec(f.read())
# 再执行 agent.py 实现agent调用tool功能
with open("agent.py", encoding="utf-8") as f:
exec(f.read())
此时你的文件结构应该如下:
(base) ~/Desktop/LLM $ tree
.
├── agent
├── merge.py
└── prepare_sql.py
运行 merge.py
文件:
$ python merge.py
Level 2: Table joins
官网除了提供上面那个SQL查询的示例以外,还提供了另一个 SQL 任务:处理多个表之间的连接。这里同样将其拆成三个文件:
prepare_sql.py
文件:
python">from dotenv import load_dotenv
load_dotenv()
from sqlalchemy import (
create_engine,
MetaData,
Table,
Column,
String,
Integer,
Float,
insert,
inspect,
text,
)
engine = create_engine("sqlite:///:memory:")
metadata_obj = MetaData()
def insert_rows_into_table(rows, table, engine=engine):
for row in rows:
stmt = insert(table).values(**row)
with engine.begin() as connection:
connection.execute(stmt)
# 第一张 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},
]
insert_rows_into_table(rows, receipts)
# 第二张 Table
table_name = "waiters"
waiters = 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"},
]
insert_rows_into_table(rows, waiters)
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)
agent.py
文件:
python">from smolagents import tool
from smolagents import CodeAgent, HfApiModel
@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
sql_engine.description = updated_description
agent = CodeAgent(
tools=[sql_engine],
model=HfApiModel(),
)
agent.run("Which waiter got more total money from tips?")
merge.py
文件:
python"># 先执行 prepare_sql.py 将数据准备好
with open("prepare_sql.py", encoding="utf-8") as f:
exec(f.read())
# 再执行 agent.py 实现agent调用tool功能
with open("agent.py", encoding="utf-8") as f:
exec(f.read())
然后执行 merge.py
文件:
$ python merge.py