핵심 · CH03

정해진 모양으로 답받기

답을 다른 프로그램(엑셀, 대시보드, 메일)으로 넘기려면 문장보다 정해진 칸이 있는 데이터가 편합니다. output_type에 클래스를 주면 답이 그 모양으로 옵니다.


1. 받고 싶은 모양을 클래스로 적습니다

03_structured.py
import setup_model  # 무료 Gemini 키로 연습할 때만 동작합니다(자료실 참고)
from pydantic import BaseModel, Field
from agents import Agent, Runner, function_tool
from sales_data import revenue_by


@function_tool
def get_revenue(group_by: str, month: str = "") -> dict:
    """매출 합계. group_by는 branch/product/month, month는 '2026-11' 형식(비우면 전체)."""
    return revenue_by(group_by, month)


class BranchRanking(BaseModel):
    month: str = Field(description="대상 월, 예: 2026-11")
    top_branch: str
    top_revenue: int
    ranking: list[str] = Field(description="매출이 큰 지점부터")
    comment: str = Field(description="한 문장 해설")


agent = Agent(
    name="순위 정리",
    instructions="도구로 숫자를 확인한 뒤 정해진 형식으로만 답해.",
    tools=[get_revenue],
    output_type=BranchRanking,          # 답을 이 모양으로 받습니다
)

result = Runner.run_sync(agent, "2026년 11월 지점 매출 순위를 정리해 줘.")
report: BranchRanking = result.final_output
print(type(report).__name__, "→", report.top_branch, f"{report.top_revenue:,}원")
print(report.model_dump_json(indent=2))

2. 실행합니다

python 03_structured.py
BranchRanking → 강남점 5,808,000원 { "month": "2026-11", "top_branch": "강남점", "top_revenue": 5808000, "ranking": ["강남점", "홍대점", "판교점"], "comment": "..." }

★ 모양이 맞는 것과 숫자가 맞는 것은 다릅니다. output_type은 칸과 타입을 보장할 뿐, top_revenue에 들어간 숫자가 맞는지는 보장하지 않습니다. 6장에서 원본과 대조하는 코드를 붙입니다.

실제로 겪은 일: 이 예제를 작은 로컬 모델로 돌렸더니 결과는 BranchRanking 모양을 정확히 지켰지만, 도구를 한 번도 부르지 않고 top_revenue에 100,000,000을, ranking에 지점 이름 대신 열 이름을 넣었습니다. 모양 검사를 통과한 답도 내용은 틀릴 수 있다는 좋은 예입니다.

이것만 기억하세요

Pydantic 클래스를 output_type에 넣으면 final_output이 그 객체로 옵니다. 칸마다 description을 써 주고, 값은 따로 검증합니다.

다음
04. 다른 에이전트에게 넘기기
이어보기 →