기본 · CH02

함수를 도구로 붙이기

모델은 우리 회사 매출을 모릅니다. 매출을 계산하는 Python 함수를 도구로 붙이면, 모델이 필요할 때 그 함수를 부르고 결과를 받아 답합니다.


1. 도구가 될 평범한 함수

sales_data.py의 두 함수입니다. revenue_by()는 CSV에서 지점·상품·월별 합계를 내고, monthly_target()은 CSV에 없는 11월 목표를 돌려줍니다.

sales_data.py
"""팝콘상사 매출 데이터 도우미 함수. 에이전트의 '도구'는 결국 이런 평범한 함수입니다."""
import csv
from collections import Counter
from pathlib import Path

CSV_PATH = Path(__file__).with_name("sales.csv")

# 회사 내부 시스템에만 있는 값이라고 가정합니다(모델은 모르는 정보).
TARGETS_2026_11 = {"강남점": 5_500_000, "홍대점": 5_500_000, "판교점": 4_500_000}


def load_rows():
    with open(CSV_PATH, encoding="utf-8") as f:
        return list(csv.DictReader(f))


def revenue_by(group_by: str, month: str = "") -> dict:
    """group_by: branch(지점) | product(상품) | month(월). month: '2026-11'처럼 쓰면 그 달만 셉니다."""
    if group_by not in ("branch", "product", "month"):
        return {"error": "group_by는 branch, product, month 중 하나여야 합니다"}
    total = Counter()
    for row in load_rows():
        if month and not row["date"].startswith(month):
            continue
        key = row["date"][:7] if group_by == "month" else row[group_by]
        total[key] += int(row["revenue"])
    return dict(total.most_common())


def monthly_target(branch: str) -> dict:
    """2026년 11월 지점별 매출 목표(원)."""
    if branch not in TARGETS_2026_11:
        return {"error": f"{branch}은(는) 없는 지점입니다. 지점: {list(TARGETS_2026_11)}"}
    return {"branch": branch, "month": "2026-11", "target": TARGETS_2026_11[branch]}

2. @function_tool로 감쌉니다

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


@function_tool
def get_revenue(group_by: str, month: str = "") -> dict:
    """팝콘상사 매출 합계를 돌려줍니다.

    Args:
        group_by: branch(지점), product(상품), month(월) 중 하나.
        month: '2026-11'처럼 쓰면 그 달만 셉니다. 비우면 전체 기간.
    """
    return revenue_by(group_by, month)


@function_tool
def get_target(branch: str) -> dict:
    """지점의 2026년 11월 매출 목표(원)를 돌려줍니다.

    Args:
        branch: 강남점, 홍대점, 판교점 중 하나.
    """
    return monthly_target(branch)


agent = Agent(
    name="매출 도우미",
    instructions="숫자는 반드시 도구 결과만 써. 직접 계산이 필요하면 계산 과정을 보여 줘.",
    tools=[get_revenue, get_target],
)

result = Runner.run_sync(agent, "2026년 11월 강남점 매출이 목표를 넘었어?")
for item in result.new_items:                 # 에이전트가 거친 단계를 그대로 봅니다
    print("·", item.type)
print("\n[답]", result.final_output)

3. 에이전트가 거친 단계 보기

result.new_items에는 이번 실행에서 생긴 일이 순서대로 들어 있습니다. 도구 호출(tool_call_item), 도구 결과(tool_call_output_item), 모델의 답(message_output_item)입니다.

python 02_tools.py

무료 Gemini 키로 실행한 실제 결과입니다. 모델이 두 도구를 한 번에 함께 불렀습니다.

· tool_call_item · tool_call_item · tool_call_output_item · tool_call_output_item · message_output_item [답] - 강남점 2026년 11월 매출: 5,808,000원 - 강남점 2026년 11월 목표: 5,500,000원 계산 과정: 5,808,000원(매출) - 5,500,000원(목표) = +308,000원 네, 2026년 11월 강남점 매출은 5,808,000원으로 목표인 5,500,000원을 넘었습니다.

모델이 도구를 부르기 전에 한마디 하면 message_output_item이 중간에 끼기도 합니다. 답의 숫자가 5,808,000원과 5,500,000원이면 맞습니다. tool_call_item이 하나도 없다면 모델이 도구 없이 짐작한 것이고, 도구를 여러 번 불렀는데 답이 이상하다면 tool_call_output_item의 내용(item.output)을 출력해 모델이 넣은 값이 맞는지 보세요.

도구 안에서 오류가 나면? 함수가 예외를 던지면 SDK가 오류 내용을 모델에게 전달하고 모델이 다시 시도하거나 사과합니다. 이 예제처럼 {"error": ...}를 돌려주면 모델이 무엇이 틀렸는지 읽고 고쳐 부를 수 있어 더 친절합니다.

이것만 기억하세요

@function_tool 하나로 함수가 도구가 됩니다. 도구 설명은 docstring이 만들므로 허용 값까지 구체적으로 씁니다. 실행 과정은 result.new_items로 봅니다.

다음
03. 정해진 모양으로 답받기
이어보기 →