使用工具创建智能体

使用 Hugging Face smolagents 的 AI Agents

Adel Nehme

VP of AI Curriculum, DataCamp

创建代码智能体(无工具)

from smolagents import CodeAgent, InferenceClientModel

agent = CodeAgent(
    tools=[],
    model=InferenceClientModel()
)

agent.run("Calculate the average of the list [23, 45, 67, 89]")
Executing parsed code:
  numbers = [23, 45, 67, 89]                                                                               
  average = sum(numbers) / len(numbers)                                                                            
  final_answer(average)                                                                                             
Final answer: 56.0
[Step 1: Duration 4.14 seconds| Input tokens: 1,900 | Output tokens: 109]
56.0
使用 Hugging Face smolagents 的 AI Agents

为何为代码智能体配备工具?

我们定义的智能体已可用以下方式解决许多任务:

  • LLM 模型
  • Python 代码

但它也可能需要外部信息:

  • 例如:网页实时数据

这就是工具的用武之地!

使用 Hugging Face smolagents 的 AI Agents

添加网页搜索工具

from smolagents import CodeAgent, InferenceClientModel, WebSearchTool

agent = CodeAgent(
    model=InferenceClientModel(),
    tools=[WebSearchTool()]
)
使用 Hugging Face smolagents 的 AI Agents

带网页搜索工具的代码智能体输出

agent.run("What's the tallest building in the world right now?")
Executing parsed code:
  tallest_building_info = web_search("tallest building in the world 2023")                                
  print(tallest_building_info)                                                                                

# Search results omitted for brevity...

Executing parsed code: 
  final_answer("Burj Khalifa, Dubai, 828 meters")                                                              
Final answer: Burj Khalifa, Dubai, 828 meters
[Step 2: Duration 2.97 seconds| Input tokens: 5,078 | Output tokens: 153]
Burj Khalifa, Dubai, 828 meters
使用 Hugging Face smolagents 的 AI Agents

内置工具(按类别)

类别 工具
信息检索 ApiWebSearchToolDuckDuckGoSearchToolGoogleSearchToolWebSearchToolWikipediaSearchTool
网页交互 VisitWebpageTool
代码执行 PythonInterpreterTool
用户交互 UserInputTool
语音处理 SpeechToTextTool
流程控制 FinalAnswerTool
1 https://huggingface.co/docs/smolagents/main/en/reference/default_tools
使用 Hugging Face smolagents 的 AI Agents

来自 Hugging Face Hub 的工具

使用 Hugging Face smolagents 的 AI Agents

使用 Hugging Face 的社区工具

from smolagents import load_tool

# Load remote tool from Hugging Face
model_downloads_tool = load_tool(
    repo_id="example-repo/hf-model-downloads",
    trust_remote_code=True
)

# Create agent with remote + built-in tools
agent = CodeAgent(
    tools=[model_downloads_tool, WebSearchTool()],
    model=InferenceClientModel()
)

agent.run("Find the most downloaded image classification model on Hugging Face")
google/vit-base-patch16-224-in21k
使用 Hugging Face smolagents 的 AI Agents

Passons à la pratique !

使用 Hugging Face smolagents 的 AI Agents

Preparing Video For Download...