当前位置: 首页 > wzjs >正文

深圳小型网站建设企业营销策划案例

深圳小型网站建设,企业营销策划案例,一般网站设计多少钱,网站建设的用户名和密码代码这篇文章锁定官网教程中 Examples 章节中的 Self-correcting Text-to-SQL 文章,主要介绍了如何使用 Agent 对数据库进行查找。 官网链接:https://huggingface.co/docs/smolagents/v1.9.2/en/examples/text_to_sql; 【注意事项】&#xff1a…

这篇文章锁定官网教程中 Examples 章节中的 Self-correcting Text-to-SQL 文章,主要介绍了如何使用 Agent 对数据库进行查找。

  • 官网链接:https://huggingface.co/docs/smolagents/v1.9.2/en/examples/text_to_sql;

【注意事项】:

  1. 这个教程涉及到一些SQL的部分,如果你对这里不熟悉也不必担心,你更应该关注的是如何定义 tool 以及给 agent 怎样提供合适的 prompt
  2. 官网在这部分做的有一点不好,他们将数据准备、tool、agent定义都拆开到不同的代码段里,导致你直接运行单独部分会没有任何输出,我这里将数据准备和tool agent定义拆分成两个文件,然后利用python特性分次执行这两个文件,这样能够更好地模拟真实生产环境,即先有数据然后才会让你写agent,你不必关心SQL部分怎么实现因为在这个系列文章中你要学习的是如何实现tool和agent

Text-to-SQL

官网在一开头就给出了一个核心问题:为什么不直接使用LLM生成的SQL语句而需要通过Agent执行,他们为此给出了以下几个理由:

  1. LLM生成的SQL语句很容易出错;
  2. SQL语句可能执行成功但由于存在逻辑错误,导致答案不是我们想要的,这个过程并不会触发异常;
  3. 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 文件:
# 代码段一:
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 文件:
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: FLOATArgs: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 文件:
# 先执行 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 文件:
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_descriptionprint(updated_description)
  • agent.py 文件:
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: FLOATArgs: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 outputsql_engine.description = updated_descriptionagent = CodeAgent(tools=[sql_engine],model=HfApiModel(),
)agent.run("Which waiter got more total money from tips?")
  • merge.py 文件:
# 先执行 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

在这里插入图片描述

http://www.dtcms.com/wzjs/17029.html

相关文章:

  • 代码网站开发营销说白了就是干什么的
  • 每日财经早报排名优化网站
  • 湛江专业官网建站个人网站怎么建立
  • 石家庄购物网站排名百度网址大全旧版
  • 做分子生物实验常用网站公司网站建设北京
  • 网站开发建设协议sem竞价广告
  • 怎么做网站信任站长之家网站介绍
  • 网站设计的技术选择网站的建设流程
  • 门设计的网站建设免费个人推广引流平台
  • 北京做养生SPA的网站建设百度注册页面
  • 小语种网站建设要点如何制作网页链接
  • 十大网站建设手机百度安装下载
  • 林州网站建设报价站长推荐
  • 自学it做网站百度搜索风云榜排名
  • 湖北企业商城网站建设b站推广网站2024
  • 南昌正规网站公司电子商务网站建设与管理
  • 手机门户网站开发怎么搭建网站
  • 做网站看什么书在线域名解析ip地址
  • 公司专业网页制作福建网络seo关键词优化教程
  • 网站建设项目进度表制作网页的网站
  • 河北网站建设哪家好厦门人才网招聘
  • 小猪会飞网站建设免费个人推广引流平台
  • 北京楼市暴跌黄山搜索引擎优化
  • 越秀区网站建设公司谷歌网页版入口在线
  • 项目建设总结报告搜索引擎优化技巧
  • 免费建站网站自助建站的网站建站全国免费发布广告信息
  • 织梦网站404怎么做安卓优化大师手机版
  • 团购网站建设案例网络公司关键词排名
  • 重庆梁平网站建设哪家便宜汕头企业网络推广
  • 无锡做网站优化亚马逊关键词搜索器