Hugginface开源的Agent框架竟如此好用!
来源:互联网
时间:2026-08-26 14:35:14
前面聊过一次Hugging Face的Agent框架,这次直接上一个完整的实验脚本,顺便看看它的设计逻辑。说实话,这框架确实挺简洁实用,值得再推荐一次。
Agent的规划方式,大体上分两类:一次性输出所有action的规划,和一步步生成的action规划。transformers.agents里主要支持这两种,但实际变体不少,也正好体现了框架本身的灵活性。

多步规划里又有两种典型形态。一种是用codeblock的形式,比如下面这个codeAgent的示例——一次生成一个完整的代码块,把后续所有动作都规划好。下图的system prompt片段展示了这种输出代码块的方式。
另一种则是类似AutoGPT的风格,输出多个step,然后逐个调用执行。
ReAct的system prompt走的是单步规划路线。有趣的是,ReAct还可以跟code组合使用,打出一些混合拳。
这里放一个完整的测试脚本,代码里用的是“一次性规划所有Action”的方式。日志如下:
from zhipuai import ZhipuAI
client = ZhipuAI(api_key=".") # 填写您自己的APIKey
def llm_engine(messages, stop_sequences=None):
response = client.chat.completions.create(
model="glm-4-plus",
messages=messages,
stop=stop_sequences
)
return response.choices[0].message.content
from transformers import Tool
class Text2image(Tool):
name = "text_to_image"
description = (
"这是一个根据文本生成图片的工具,它返回一个生成的图片路径"
)
inputs = {
"prompt": {
"type": "text",
"description": "需要生成图片的描述文本",
}
}
output_type = "text"
def forward(self, prompt):
response = client.images.generations(
model="cogview-3-plus",
prompt=prompt
)
print(response.data[0].url)
return response.data[0].url
class ImageQuestionAnswering(Tool):
description = "这是一个可以回答关于图片问题的工具,它返回一个文本,作为对问题的答案。"
name = "image_qa"
inputs = {
"image_path": {
"type": "text",
"description": "图片路径或url",
},
"question": {"type": "text", "description": "问题"},
}
output_type = "text"
def forward(self, image_path, question):
if 'http' not in image_path:
with open(image_path, 'rb') as img_file:
img_base = base64.b64encode(img_file.read()).decode('utf-8')
else:
img_base = image_path
response = client.chat.completions.create(
model="glm-4v-plus", # 填写需要调用的模型名称
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": img_base
}
},
{
"type": "text",
"text": question
}
]
}
]
)
return response.choices[0].message.content
from transformers import Tool, load_tool, CodeAgent
agent = CodeAgent(tools=[Text2image(),ImageQuestionAnswering()], llm_engine=llm_engine, verbose=1)
agent.run(
"画一张搞笑图片,然后描述一下这张图片为什么搞笑?以及图片内容是否符合你生成的prompt"
) -
- 关于宇宙的好的网名有哪些
- 角色扮演 | 1
- 网名