Phidata 에이전트 이해하기

Phidata 에이전트 이해하기

"에이전트란 대체 뭘까" 하는 질문부터 시작하면, Phidata는 이렇게 답해요. 에이전트는 언어 모델을 사용해 작업을 수행하는 자율 프로그램이에요. 엔지니어들은 Phidata로 메모리·지식·도구·추론을 갖춘 에이전트를 만들죠.

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

예시: 리서치 에이전트

웹을 검색하고, 상위 링크를 읽고, 그 결과로 리포트를 작성하는 에이전트를 만들어 볼게요. 에이전트가 어떻게 행동할지는 descriptioninstructions로 "프롬프트"해요.

from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.tools.duckduckgo import DuckDuckGo
from phi.tools.newspaper4k import Newspaper4k

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    tools=[DuckDuckGo(), Newspaper4k()],
    description="You are a senior NYT researcher writing an article on a topic.",
    instructions=[
        "For a given topic, search for the top 5 links.",
        "Then read each URL and extract the article text, if a URL isn't available, ignore it.",
        "Analyse and prepare an NYT worthy article based on the information.",
    ],
    markdown=True,
    show_tool_calls=True,
    add_datetime_to_instructions=True,
    # debug_mode=True,
)
agent.print_response("Simulation theory", stream=True)

실행은 아래처럼 라이브러리를 설치하고 스크립트를 돌리는 것뿐이에요.

pip install phidata openai duckduckgo-search newspaper4k lxml_html_clean
python research_agent.py

참고로 descriptioninstructions시스템 프롬프트로 변환되고, 입력(Simulation theory)은 유저 프롬프트로 전달돼요. 동작이 궁금하다면 debug_mode=True를 켜서 내부 로그를 볼 수 있어요.

응답을 변수로 받아오기

Agent.print_response()는 빠른 실험용이에요. 실제 애플리케이션에서는 응답을 프론트엔드로 넘기거나 다른 에이전트에 전달해야 하므로, Agent.run()으로 받는 게 일반적이에요. run()은 응답을 RunResponse 객체로 돌려줘요.

from phi.agent import Agent, RunResponse
from phi.utils.pprint import pprint_run_response

agent = Agent(...)

# Run agent and return the response as a variable
response: RunResponse = agent.run("Simulation theory")
# Print the response in markdown format
pprint_run_response(response, markdown=True)

기본값은 stream=False예요. stream=True로 바꾸면 RunResponse 객체의 스트림을 돌려받아요.

from typing import Iterator

# Run agent and return the response as a stream
response_stream: Iterator[RunResponse] = agent.run("Simulation theory", stream=True)
# Print the response stream in markdown format
pprint_run_response(response_stream, markdown=True, show_time=True)

RunResponse 구조

Agent.run()은 기본적으로 RunResponse 객체를, stream=True일 때는 Iterator[RunResponse]를 반환해요. 주로 쓰는 속성들을 표로 정리하면 이래요.

Attribute Type Default Description
content Any None Content of the response.
content_type str "str" Specifies the data type of the content.
context List[MessageContext] None The context added to the response for RAG.
event str RunEvent.run_response.value Event type of the response.
event_data Dict[str, Any] None Data associated with the event.
messages List[Message] None A list of messages included in the response.
metrics Dict[str, Any] None Usage metrics of the run.
model Model OpenAIChat OpenAI model is used to run by default.
run_id str None Run Id.
agent_id str None Agent Id for the run.
session_id str None Session Id for the run.
tools List[Dict[str, Any]] None List of tools provided to the model.
created_at int - Unix timestamp of the response creation.

metrics는 토큰 사용량 같은 실행 지표를, context는 RAG에 쓸 컨텍스트를 담아요. 디버깅할 때 이 속성들을 살펴보면 에이전트가 뭘 했는지 한눈에 보여요.

더 알아보기