함수 호출 (Function calling)

함수 호출 (Function calling)

모델에게 "세상과 연결된 일을 시키고 싶다"면 함수 호출(Function calling)을 써요. 모델이 텍스트만 만들어 내는 대신, 언제 어떤 함수를 호출할지 판단하고 실행에 필요한 파라미터를 만들어 돌려줍니다. 자연어 입력을 실제 동작으로 이어 주는 다리 역할을 하죠.

출처: 함수 호출 - Google 공식 문서

함수 호출의 세 가지 용도

  • 동작 실행(Take Actions): 일정 잡기, 송장 발행, 이메일 보내기, 스마트홈 제어처럼 외부 시스템과 상호작용
  • 지식 보강(Augment Knowledge): DB·API·지식 베이스 같은 외부 소스에서 정보 가져오기
  • 능력 확장(Extend Capabilities): 계산기나 차트 만들기처럼 모델 자체의 한계를 보완하는 도구 사용

함수 정의하고 호출하기

함수는 JSON 형태의 선언으로 정의해요. 이름, 설명, 그리고 파라미터 스키마(JSON Schema)로 구성됩니다. 아래 예시는 회의 일정을 잡는 함수예요.

from google import genai

schedule_meeting_function = {
    "type": "function",
    "name": "schedule_meeting",
    "description": "Schedules a meeting with specified attendees at a given time and date.",
    "parameters": {
        "type": "object",
        "properties": {
            "attendees": {"type": "array", "items": {"type": "string"}},
            "date": {"type": "string", "description": "Date (e.g., '2024-07-29')"},
            "time": {"type": "string", "description": "Time (e.g., '15:00')"},
            "topic": {"type": "string", "description": "The meeting topic."},
        },
        "required": ["attendees", "date", "time", "topic"],
    },
}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about Q3 planning.",
    tools=[{"type": "function", **schedule_meeting_function}],
)

for step in interaction.steps:
    if step.type == "function_call":
        print(f"Function to call: {step.name}")
        print(f"Arguments: {step.arguments}")

REST에서는 tools 배열에 함수 선언을 넣고 https://generativelanguage.googleapis.com/v1beta/interactions에 POST하면 돼요. 모델이 함수를 부르기로 하면 응답의 스텝에 function_call 타입이 나타나고, namearguments가 함께 옵니다.

도구 선택 제어

generation_configtool_choice로 어떤 도구를 쓸지 강제할 수 있어요. 아래는 get_current_temperature 함수만 쓰도록 지정한 예시입니다.

generation_config = {
    "tool_choice": {
        "allowed_tools": {
            "mode": "any",
            "tools": ["get_current_temperature"]
        }
    }
}

멀티 도구 사용

하나의 요청에 내장 도구와 함수 호출을 함께 켤 수도 있어요. 아래는 Google 검색 내장 도구와 날씨 함수를 동시에 쓰는 예시입니다.

tools = [
    {"type": "google_search"},
    get_weather
]

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="What is the northernmost city in the United States? What's the weather there?",
    tools=tools
)

Gemini 3 모델은 Interactions API에서 내장 도구와 함수 호출을 기본으로 함께 지원하고, previous_interaction_id를 넘기면 내장 도구 컨텍스트를 자동으로 이어 가요.

더 알아보기