Agents Course documentation

도구 (Tools)

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Ask a Question Open In Colab

도구 (Tools)

unit 1에서 살펴본 것처럼, 에이전트는 다양한 작업을 수행하기 위해 도구를 사용합니다. smolagents에서 도구는 에이전트 시스템 내에서 LLM이 호출할 수 있는 함수로 취급됩니다.

도구와 상호작용하려면 LLM이 다음과 같은 인터페이스 설명을 필요로 합니다:

  • 이름: 도구의 이름
  • 도구 설명: 도구가 수행하는 작업
  • 입력 타입 및 설명: 도구가 받는 인자
  • 출력 타입: 도구가 반환하는 값

예를 들어, Alfred가 Wayne Manor에서 파티를 준비할 때, 케이터링 서비스 검색부터 파티 테마 아이디어 찾기까지 다양한 정보를 수집해야 합니다. 아래는 간단한 검색 도구 인터페이스 예시입니다:

  • 이름: web_search
  • 도구 설명: 특정 쿼리로 웹을 검색합니다
  • 입력: query (string) - 검색어
  • 출력: 검색 결과가 담긴 문자열

이러한 도구를 사용하면 Alfred는 완벽한 파티 준비를 위해 필요한 모든 정보를 쉽게 모을 수 있습니다.

아래 애니메이션은 도구 호출이 어떻게 관리되는지 보여줍니다:

Agentic pipeline from https://huggingface.co/docs/smolagents/conceptual_guides/react

도구 생성 방법

smolagents에서 도구는 두 가지 방식으로 정의할 수 있습니다:

  1. @tool 데코레이터를 사용한 간단한 함수형 도구
  2. Tool 클래스를 상속한 복잡한 도구

@tool 데코레이터

@tool 데코레이터는 간단한 도구를 정의할 때 권장되는 방법입니다. 내부적으로 smolagents는 함수에서 기본 정보를 파싱합니다. 함수 이름을 명확하게 짓고, 좋은 docstring을 작성하면 LLM이 더 쉽게 사용할 수 있습니다.

이 방식에서는 다음을 지켜야 합니다:

  • 명확하고 설명적인 함수명
  • 입력과 출력에 타입 힌트 사용
  • 자세한 설명과 Args 섹션

고평점 케이터링 도구 예시

Alfred Catering
코드는 이 노트북에서 따라할 수 있습니다. Google Colab에서 실행할 수 있습니다.

Alfred가 파티 메뉴를 정했다면, 많은 손님을 위해 케이터링 서비스를 고용해야 합니다. Gotham에서 평점이 가장 높은 케이터링 서비스를 찾는 도구를 만들어봅시다.

from smolagents import CodeAgent, InferenceClientModel, tool

# Gotham에서 평점이 가장 높은 케이터링 서비스를 반환하는 함수 예시
@tool
def catering_service_tool(query: str) -> str:
    """
    이 도구는 Gotham City에서 평점이 가장 높은 케이터링 서비스를 반환합니다.

    Args:
        query: 케이터링 서비스를 찾기 위한 검색어
    """
    # 예시 케이터링 서비스와 평점
    services = {
        "Gotham Catering Co.": 4.9,
        "Wayne Manor Catering": 4.8,
        "Gotham City Events": 4.7,
    }

    # 평점이 가장 높은 서비스 찾기(검색어 필터링은 생략)
    best_service = max(services, key=services.get)

    return best_service


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

# 에이전트 실행 예시
result = agent.run(
    "Can you give me the name of the highest-rated catering service in Gotham City?"
)

print(result)   # 출력: Gotham Catering Co.

Python 클래스로 도구 정의하기

이 방식은 Tool 클래스를 상속해 복잡한 도구를 만드는 방법입니다. 클래스는 함수에 메타데이터를 추가해 LLM이 효과적으로 사용할 수 있도록 도와줍니다. 이 클래스에서는 다음을 정의합니다:

  • name: 도구 이름
  • description: 시스템 프롬프트에 들어갈 설명
  • inputs: 입력 타입과 설명이 담긴 딕셔너리
  • output_type: 반환 타입
  • forward: 실제 동작을 수행하는 메서드

아래는 Tool을 상속해 슈퍼히어로 테마 파티 아이디어를 생성하는 도구 예시입니다.

슈퍼히어로 테마 파티 아이디어 생성 도구

Alfred는 Wayne Manor에서 슈퍼히어로 테마 파티를 준비합니다. 손님들을 놀라게 할 독특한 테마가 필요합니다. 아래 도구는 카테고리에 따라 창의적인 파티 아이디어를 제안합니다.

from smolagents import Tool, CodeAgent, InferenceClientModel

class SuperheroPartyThemeTool(Tool):
    name = "superhero_party_theme_generator"
    description = """
    이 도구는 카테고리에 따라 창의적인 슈퍼히어로 테마 파티 아이디어를 제안합니다.
    고유한 파티 테마 아이디어를 반환합니다."""

    inputs = {
        "category": {
            "type": "string",
            "description": "슈퍼히어로 파티 유형(예: 'classic heroes', 'villain masquerade', 'futuristic Gotham')",
        }
    }

    output_type = "string"

    def forward(self, category: str):
        themes = {
            "classic heroes": "Justice League Gala: 손님들이 DC 영웅으로 분장하고, 'The Kryptonite Punch' 같은 테마 칵테일 제공.",
            "villain masquerade": "Gotham Rogues' Ball: 손님들이 배트맨 빌런으로 분장하는 미스터리 가면무도회.",
            "futuristic Gotham": "Neo-Gotham Night: 배트맨 비욘드에서 영감을 받은 사이버펑크 스타일 파티, 네온 장식과 미래형 소품.",
        }

        return themes.get(category.lower(), "테마를 찾을 수 없습니다. 'classic heroes', 'villain masquerade', 'futuristic Gotham' 중에서 선택해보세요.")

# 도구 인스턴스화
party_theme_tool = SuperheroPartyThemeTool()
agent = CodeAgent(tools=[party_theme_tool], model=InferenceClientModel())

# 에이전트 실행 예시
result = agent.run(
    "What would be a good superhero party idea for a 'villain masquerade' theme?"
)

print(result)  # 출력: "Gotham Rogues' Ball: 손님들이 배트맨 빌런으로 분장하는 미스터리 가면무도회."

이 도구로 Alfred는 슈퍼히어로 테마 파티의 완벽한 호스트가 될 수 있습니다! 🦸‍♂️🦸‍♀️

기본 도구 모음(Default Toolbox)

smolagents에는 바로 사용할 수 있는 여러 기본 도구가 포함되어 있습니다. 기본 도구 모음에는 다음이 포함됩니다:

  • PythonInterpreterTool
  • FinalAnswerTool
  • UserInputTool
  • DuckDuckGoSearchTool
  • GoogleSearchTool
  • VisitWebpageTool

Alfred는 다음과 같이 다양한 도구를 활용해 Wayne Manor에서 완벽한 파티를 준비할 수 있습니다:

  • DuckDuckGoSearchTool로 창의적인 슈퍼히어로 테마 파티 아이디어 검색
  • GoogleSearchTool로 Gotham에서 평점이 가장 높은 케이터링 서비스 찾기
  • PythonInterpreterTool로 좌석 배치 계산
  • 모든 정보를 모아 FinalAnswerTool로 계획 정리

이 도구들로 Alfred는 완벽하고 매끄러운 파티를 보장할 수 있습니다. 🦇💡

도구 공유 및 가져오기

smolagents의 강력한 기능 중 하나는 커스텀 도구를 Hub에 공유하고, 커뮤니티에서 만든 도구를 쉽게 가져올 수 있다는 점입니다. 여기에는 HF SpacesLangChain 도구와의 연동도 포함되어, Alfred가 Wayne Manor에서 잊지 못할 파티를 기획하는 데 큰 도움이 됩니다. 🎭

이러한 통합을 통해 Alfred는 고급 이벤트 플래닝 도구를 활용할 수 있습니다. 예를 들어, 조명 조정, 파티 음악 추천, 케이터링 업체와의 협업 등 다양한 작업을 자동화할 수 있습니다.

아래는 이러한 기능이 파티 경험을 어떻게 향상시키는지 보여주는 예시입니다:

도구를 Hub에 공유하기

커스텀 도구를 커뮤니티에 공유하는 것은 매우 쉽습니다! push_to_hub() 메서드를 사용해 Hugging Face 계정에 업로드하면 됩니다.

예를 들어, Alfred는 자신의 party_theme_tool을 공유해 다른 사람들도 Gotham 최고의 케이터링 서비스를 찾을 수 있도록 도울 수 있습니다:

party_theme_tool.push_to_hub("{your_username}/party_theme_tool", token="<YOUR_HUGGINGFACEHUB_API_TOKEN>")

Hub에서 도구 가져오기

다른 사용자가 만든 도구를 load_tool() 함수로 쉽게 가져올 수 있습니다. 예를 들어, Alfred가 AI로 파티 홍보 이미지를 만들고 싶다면, 커뮤니티에서 미리 만들어진 도구를 활용할 수 있습니다:

from smolagents import load_tool, CodeAgent, InferenceClientModel

image_generation_tool = load_tool(
    "m-ric/text-to-image",
    trust_remote_code=True
)

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

agent.run("Generate an image of a luxurious superhero-themed party at Wayne Manor with made-up superheros.")

HF Space를 도구로 가져오기

Tool.from_space()를 사용해 HF Space를 도구로 가져올 수도 있습니다. 이를 통해 커뮤니티의 수천 개 Space와 연동해 이미지 생성, 데이터 분석 등 다양한 작업을 수행할 수 있습니다.

이 도구는 gradio_client를 통해 Space의 Gradio 백엔드와 연결되므로, 미리 pip로 설치해야 합니다.

파티를 위해 Alfred는 AI로 생성한 이미지를 파티 공지에 활용할 수 있습니다. 아래는 그 예시입니다:

from smolagents import CodeAgent, InferenceClientModel, Tool

image_generation_tool = Tool.from_space(
    "black-forest-labs/FLUX.1-schnell",
    name="image_generator",
    description="Generate an image from a prompt"
)

model = InferenceClientModel("Qwen/Qwen2.5-Coder-32B-Instruct")

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

agent.run(
    "Improve this prompt, then generate an image of it.",
    additional_args={'user_prompt': 'A grand superhero-themed party at Wayne Manor, with Alfred overseeing a luxurious gala'}
)

LangChain 도구 가져오기

LangChain 프레임워크는 이후 섹션에서 자세히 다룹니다. 여기서는 smolagents 워크플로우에서 LangChain 도구를 재사용할 수 있다는 점만 알아둡시다!

Tool.from_langchain() 메서드로 LangChain 도구를 쉽게 불러올 수 있습니다. Alfred는 Wayne Manor에서 최고의 엔터테인먼트 아이디어를 찾기 위해 LangChain 도구를 활용할 수 있습니다.

from langchain.agents import load_tools
from smolagents import CodeAgent, InferenceClientModel, Tool

search_tool = Tool.from_langchain(load_tools(["serpapi"])[0])

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

agent.run("Search for luxury entertainment ideas for a superhero-themed event, such as live performances and interactive experiences.")

MCP 서버에서 도구 모음 가져오기

smolagentsglama.ai 또는 smithery.ai에서 제공하는 수백 개 MCP 서버의 도구도 가져올 수 있습니다. MCP에 대해 더 알고 싶다면 무료 MCP 강의를 참고하세요.

mcp 클라이언트 설치

먼저 smolagents의 mcp 통합을 설치해야 합니다.

pip install "smolagents[mcp]"

MCP 서버의 도구는 ToolCollection 객체로 불러올 수 있습니다:

import os
from smolagents import ToolCollection, CodeAgent
from mcp import StdioServerParameters
from smolagents import InferenceClientModel


model = InferenceClientModel("Qwen/Qwen2.5-Coder-32B-Instruct")


server_parameters = StdioServerParameters(
    command="uvx",
    args=["--quiet", "pubmedmcp@0.1.3"],
    env={"UV_PYTHON": "3.12", **os.environ},
)

with ToolCollection.from_mcp(server_parameters, trust_remote_code=True) as tool_collection:
    agent = CodeAgent(tools=[*tool_collection.tools], model=model, add_base_tools=True)
    agent.run("Please find a remedy for hangover.")

이렇게 하면 Alfred는 고급 엔터테인먼트 옵션을 빠르게 찾을 수 있어, Gotham의 명사들이 잊지 못할 슈퍼히어로 파티를 즐길 수 있습니다! 🎉

참고 자료

Update on GitHub