ComponentTool

ComponentTool

ComponentTool은 Haystack 컴포넌트를 감싸서 LLM이 툴로 사용할 수 있게 해 주는 래퍼예요.

항목 내용
필수 init 변수 component: 감쌀 Haystack 컴포넌트
API 레퍼런스 ComponentTool
GitHub 링크 https://github.com/deepset-ai/haystack/blob/main/haystack/tools/component_tool.py
패키지명 haystack-ai

출처: 공식문서

개요 (Overview)

ComponentTool은 Haystack 컴포넌트를 감싸는 Tool로, LLM이 그 컴포넌트를 툴로 사용할 수 있게 해 줘요. ComponentTool은 컴포넌트의 run 메서드 시그니처와 타입 힌트에서 파생된 입력 소켓으로부터 LLM 호환 툴 스키마를 자동 생성해요.

입력 타입 변환을 수행하며, run 메서드가 다음 입력 타입을 가진 컴포넌트를 지원해요.

  • 기본 타입 (str, int, float, bool, dict)
  • 데이터 클래스 (단순 및 중첩 구조 모두)
  • 기본 타입 리스트 (예: list[str])
  • 데이터 클래스 리스트 (예: list[Document])
  • 혼합 타입 파라미터 (예: list[Document], str...)

감싼 컴포넌트가 run_async 메서드를 정의하면, ComponentTool은 비동기 인보커도 자동으로 연결해서 추가 설정 없이 비동기 호출(예: Agent.run_async에서)을 지원해요. 자세한 내용은 Async Tools를 참고하세요.

Agent를 툴로 감쌀 때는 AgentTool을 대신 사용하세요. AgentTool은 Agent에 맞게 기본값이 구성된 ComponentTool의 특수화예요. 호출 LLM은 위임할 작업을 단일 사용자 메시지로 요청받고, 툴 결과는 감싼 Agent의 최종 답변이 돼요.

파라미터

  • component는 필수이며 Haystack 컴포넌트 인스턴스여야 해요. 기존 컴포넌트든 커스텀 컴포넌트든 가능해요.
  • name은 선택이고 기본값은 컴포넌트 클래스 이름의 스네이크 케이스예요. 예: SerperDevWebSearch에 대해 "serper_dev_web_search".
  • description은 선택이고 기본값은 컴포넌트의 docstring이에요. LLM이 언제 툴을 호출할지 정할 때 이 설명을 사용해요.
  • parameters는 선택이고 툴 입력용 자동 생성 JSON 스키마를 덮어쓸 수 있어요.
  • outputs_to_string은 선택이고 컴포넌트 출력을 LLM용 문자열로 변환하는 방식을 제어해요. 기본적으로 전체 결과 딕셔너리가 직렬화돼요. 단일 출력 키를 추출하려면 {"source": "key"}를 사용하고, 커스텀 포매터를 적용하려면 "handler"를 추가하세요.
  • inputs_from_state는 선택이고 에이전트 상태 키를 컴포넌트 입력 파라미터로 매핑해요. 예: {"repository": "repo"}는 상태의 "repository" 값을 컴포넌트의 "repo" 입력으로 전달해요.
  • outputs_to_state는 선택이고 컴포넌트 출력 키를 에이전트 상태 키로 매핑해요. 예: {"documents": {"source": "docs"}}는 컴포넌트의 "docs" 출력을 상태의 "documents"에 써요.

사용법 (Usage)

:::tip Haystack에서 ComponentTool을 쓰는 권장 방법은 툴 호출 루프를 대신 관리해 주는 Agent 컴포넌트와 함께 쓰는 것이에요. :::

Agent 컴포넌트와 함께

이 페이지의 예시는 serperdev-haystack 패키지로 이동한 SerperDev 웹 검색 컴포넌트를 사용해요. 예시를 실행하려면 설치하세요.

pip install serperdev-haystack
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.tools import ComponentTool
from haystack.components.agents import Agent
from haystack_integrations.components.websearch.serperdev import SerperDevWebSearch
from haystack.utils import Secret

# Create a SerperDev search component
search = SerperDevWebSearch(api_key=Secret.from_env_var("SERPERDEV_API_KEY"), top_k=3)

# Create a tool from the component
search_tool = ComponentTool(
    component=search,
    name="web_search",  # Optional: defaults to "serper_dev_web_search"
    description="Search the web for current information on any topic",  # Optional: defaults to component docstring
)

agent = Agent(
    system_prompt="You are an assistant that can use web search to find information.",
    chat_generator=OpenAIChatGenerator(),
    tools=[search_tool],
)

response = agent.run(
    messages=[ChatMessage.from_user("Give me a brief summary on who Nikola Tesla is")],
)

print(response["messages"][-1].text)

더 알아보기 (Learn more)

📖 관련 문서:

📚 튜토리얼: