ツールを使ったエージェントの作成

Hugging Face smolagents で学ぶ AI エージェント

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 エージェント

コードエージェントにツールを使う理由

定義したエージェントは以下を使用して多くのタスクを解決できます:

  • LLMモデル
  • Pythonコード

ただし、外部情報へのアクセスが必要な場合もあります:

  • 例:リアルタイムのWebデータ

そこでツールが役立ちます!

Hugging Face smolagents で学ぶ AI エージェント

Web検索ツールの追加

from smolagents import CodeAgent, InferenceClientModel, WebSearchTool

agent = CodeAgent(
    model=InferenceClientModel(),
    tools=[WebSearchTool()]
)
Hugging Face smolagents で学ぶ AI エージェント

Web検索ツールを使ったコードエージェントの出力

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
Web操作 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...