도구
도구 (Tools)
여기서는 고급 도구 사용법을 다룹니다.
[!TIP] 에이전트 만들기가 처음이라면 먼저 에이전트 소개와 smolagents 둘러보기를 읽어보세요.
출처: 공식문서 - Tools
도구란 무엇이고 어떻게 만드나요?
도구는 기본적으로 에이전틱 시스템에서 LLM이 사용할 수 있는 함수예요. 하지만 사용하려면 LLM에게 API(이름, 도구 설명, 입력 타입·설명, 출력 타입)를 줘야 해요.
그래서 함수일 수만은 없고 클래스여야 해요. 핵심적으로 도구는, LLM이 어떻게 쓸지 이해하도록 돕는 메타데이터로 함수를 감싼 클래스입니다.
from smolagents import Tool
class HFModelDownloadsTool(Tool):
name = "model_download_counter"
description = """
This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub.
It returns the name of the checkpoint."""
inputs = {
"task": {
"type": "string",
"description": "the task category (such as text-classification, depth-estimation, etc)",
}
}
output_type = "string"
def forward(self, task: str):
from huggingface_hub import list_models
model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
return model.id
model_downloads_tool = HFModelDownloadsTool()
커스텀 도구는 Tool을 서브클래싱해 유용한 메서드를 상속받아요. 자식 클래스는 다음도 정의합니다.
name속성: 도구 자체의 이름. 보통 도구가 하는 일을 설명. 가장 많이 다운로드된 모델을 반환하니model_download_counter라 이름 지어요.description속성: 에이전트의 시스템 프롬프트를 채우는 데 사용.inputs속성:"type"과"description"키를 가진 딕셔너리. Python 인터프리터가 입력에 대해 올바른 선택을 하도록 돕는 정보를 담아요.output_type속성: 출력 타입 지정.inputs와output_type의 타입은 Pydantic 형식이어야 하고 다음 중 하나예요:["string", "boolean", "integer", "number", "image", "audio", "array", "object", "any", "null"].forward메서드: 실행할 추론 코드를 담아요.
그리고 이 정도면 에이전트에서 바로 쓸 수 있어요!
도구를 만드는 또 다른 방법이 있어요. 둘러보기에서 @tool 데코레이터로 도구를 구현했죠. tool() 데코레이터는 간단한 도구를 정의하는 권장 방식이지만, 더 필요할 때가 있어요. 클래스에서 여러 메서드를 써 더 명확하게 하거나 추가 클래스 속성을 쓰는 경우입니다. 그럴 땐 위처럼 Tool을 서브클래싱해 도구를 만들면 됩니다.
도구를 허브에 공유하기
커스텀 도구의 push_to_hub()를 호출하면 Space 저장소로 허브에 공유할 수 있어요. 허브에 저장소를 만들고 읽기 권한이 있는 토큰을 사용해야 합니다.
model_downloads_tool.push_to_hub("{your_username}/hf-model-downloads", token="<your_token>")