建立可用工具的代理

使用 Hugging Face smolagents 的 AI 代理

Adel Nehme

VP of AI Curriculum, DataCamp

建立無工具的 Code Agent

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 代理

為何在 Code Agent 中使用工具?

我們定義的代理已可用下列方式解多數任務:

  • LLM 模型
  • Python 程式碼

但有時也需要外部資訊:

  • 例如:即時網頁資料

這就是工具能派上用場的地方!

使用 Hugging Face smolagents 的 AI 代理

加入網頁搜尋工具

from smolagents import CodeAgent, InferenceClientModel, WebSearchTool

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

具網頁搜尋工具的 Code Agent 輸出

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 代理

內建工具(依類別)

類別 工具
資訊擷取 ApiWebSearchTool, DuckDuckGoSearchTool, GoogleSearchTool, WebSearchTool, WikipediaSearchTool
網頁互動 VisitWebpageTool
程式執行 PythonInterpreterTool
使用者互動 UserInputTool
語音處理 SpeechToTextTool
流程控制 FinalAnswerTool
1 https://huggingface.co/docs/smolagents/main/en/reference/default_tools
使用 Hugging Face smolagents 的 AI 代理

來自 Hugging Face Hub 的工具

使用 Hugging Face smolagents 的 AI 代理

使用 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 代理

一起來練習吧!

使用 Hugging Face smolagents 的 AI 代理

Preparing Video For Download...