Phidata 도구(Tools)로 에이전트 확장하기

Phidata 도구(Tools)로 에이전트 확장하기

에이전트가 "말만 하는 존재"에서 "일을 하는 존재"가 되는 지점이 바로 도구예요. Phidata에서 에이전트는 도구를 사용해 행동을 취하고 외부 시스템과 상호작용해요. 웹 검색, SQL 실행, 이메일 발송, API 호출 같은 일을 도구로 만들 수 있죠.

출처: Phidata 에이전트 도구 공식 문서

도구의 기본 문법

도구는 에이전트가 작업을 수행하기 위해 실행하는 함수예요. 어떤 파이썬 함수든 도구로 쓸 수 있고, 미리 만들어진 **툴킷(Toolkit)**을 쓰는 것도 가능해요. 기본 골격은 이렇습니다.

from phi.agent import Agent

agent = Agent(
    # Add functions or Toolkits
    tools=[...],
    # Show tool calls in the Agent response
    show_tool_calls=True
)

tools에 함수나 툴킷을 넣고, show_tool_calls=True를 주면 에이전트가 어떤 도구를 호출했는지 응답에 드러나요.

툴킷 사용하기

Phidata는 미리 만들어진 툴킷을 여럿 제공해요. 그중 웹 검색용 DuckDuckGo 툴킷을 붙여 보겠어요.

from phi.agent import Agent
from phi.tools.duckduckgo import DuckDuckGo

agent = Agent(tools=[DuckDuckGo()], show_tool_calls=True, markdown=True)
agent.print_response("Whats happening in France?", stream=True)

실행을 위해 필요한 라이브러리는 이래요.

pip install openai duckduckgo-search phidata
python web_search.py

나만의 도구 만들기

더 세밀하게 제어하고 싶다면 직접 파이썬 함수를 작성해 에이전트의 도구로 추가할 수 있어요. 아래는 get_top_hackernews_stories 도구를 만든 예시예요. 함수의 docstring이 모델에게 "이 함수가 뭘 하는지" 알려주는 역할을 해요.

import json
import httpx

from phi.agent import Agent


def get_top_hackernews_stories(num_stories: int = 10) -> str:
    """Use this function to get top stories from Hacker News.

    Args:
        num_stories (int): Number of stories to return. Defaults to 10.

    Returns:
        str: JSON string of top stories.
    """

    # Fetch top story IDs
    response = httpx.get('https://hacker-news.firebaseio.com/v0/topstories.json')
    story_ids = response.json()

    # Fetch story details
    stories = []
    for story_id in story_ids[:num_stories]:
        story_response = httpx.get(f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json')
        story = story_response.json()
        if "text" in story:
            story.pop("text", None)
        stories.append(story)
    return json.dumps(stories)

agent = Agent(tools=[get_top_hackernews_stories], show_tool_calls=True, markdown=True)
agent.print_response("Summarize the top 5 stories on hackernews?", stream=True)

docstring에 매개변수와 반환 타입을 명확히 적어야 모델이 도구를 언제·어떻게 호출할지 정확히 알 수 있어요.

도구 관련 속성

에이전트가 도구를 쓰도록 만드는 주요 속성들을 정리하면 이래요.

Parameter Type Default Description
tools List[Union[Tool, Toolkit, Callable, Dict, Function]] - A list of tools provided to the Model. Tools are functions the model may generate JSON inputs for.
show_tool_calls bool False Print the signature of the tool calls in the Model response.
tool_call_limit int - Maximum number of tool calls allowed.
tool_choice Union[str, Dict[str, Any]] - Controls which (if any) tool is called by the model. "none" means the model will not call a tool and instead generates a message. "auto" means the model can pick between generating a message or calling a tool. Specifying a particular function via {"type": "function", "function": {"name": "my_function"}} forces the model to call that tool. "none" is the default when no tools are present. "auto" is the default if tools are present.
read_chat_history bool False Add a tool that allows the Model to read the chat history.
search_knowledge bool False Add a tool that allows the Model to search the knowledge base (aka Agentic RAG).
update_knowledge bool False Add a tool that allows the Model to update the knowledge base.
read_tool_call_history bool False Add a tool that allows the Model to get the tool call history.
tool_choice Union[str, Dict[str, Any]] - Controls which (if any) tool is called by the model. "none" means the model will not call a tool and instead generates a message. "auto" means the model can pick between generating a message or calling a tool. Specifying a particular function via {"type": "function", "function": {"name": "my_function"}} forces the model to call that tool. "none" is the default when no tools are present. "auto" is the default if tools are present.

tool_choice는 흥미로운 속성이에요. "auto"는 모델이 메시지 생성과 도구 호출 사이를 스스로 선택하고, 특정 함수를 지정하면 그 도구를 강제로 호출해요. search_knowledgeread_chat_history는 각각 지식 베이스 검색과 대화 기록 읽기 도구를 자동으로 붙여줘요.

더 알아보기