본문 바로가기
C.W.K.
Stream
Lesson 04 of 05 · published

Google Gemini Function Declaration

~22 min · gemini, google, function-declaration, automatic-fc

Level 0호기심 많은 독자
0 XP0/48 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Google Gemini 는 tool calling 을 조금 더 OOP 다운 봉투에 담아. Tool 은 Tool 안에 묶인 FunctionDeclaration 들이고, response 는 nameargs 를 실은 function_call part 를 들고 와. args 는 Anthropic 처럼 진짜 dict 야.

google-genai 만의 특징은 automatic function calling 이야. Loop 를 직접 짜는 대신 SDK 에 진짜 Python 함수를 넘기면, SDK 가 알아서 실행하고 결과까지 넣어줘. Prototype 단계에선 편한데 production 엔 좁아 — 에러 처리도, 병렬 실행도, 기록을 남기는 것도 네 손을 떠나거든. Loop 가 어떻게 도는지 감을 잡는 데 쓰고, 실제로 내보낼 땐 직접 짜.

Gemini 도 function-calling 모드 를 열어놨어. AUTO (기본값), ANY (뭐가 됐든 하나는 불러야 함), NONE (부르지 마). OpenAI 의 tool_choice 와 뜻이 똑같고 enum 으로 준다는 것만 달라. 이 모드는 GenerationConfig 안에 들어가지, 맨 위 parameter 가 아니야.

Streaming 은 generate_content_streamparts 가 자라나는 Candidate object 를 계속 내주는 방식이야. Function-call part 는 모델이 결정한 순간 통째로 한 번에 도착해 — Gemini 는 OpenAI 처럼 인자를 조각내서 흘려보내지 않아. 덕분에 tool-call streaming 을 받아먹기는 더 쉬운데, 첫 바이트는 조금 늦게 와.

Code

google-genai 로 loop 직접 짜기·python
from google import genai
from google.genai import types

client = genai.Client()

def get_weather(location: str) -> str:
    return f"68°F and clear in {location}"

tools = [types.Tool(function_declarations=[types.FunctionDeclaration(
    name="get_weather",
    description="Get current weather for a city.",
    parameters=types.Schema(
        type=types.Type.OBJECT,
        properties={"location": types.Schema(type=types.Type.STRING)},
        required=["location"],
    ),
)])]

contents = [types.Content(role="user", parts=[types.Part(text="Weather in Seoul?")])]
while True:
    resp = client.models.generate_content(
        model="gemini-2.5-flash",
        contents=contents,
        config=types.GenerateContentConfig(tools=tools),
    )
    contents.append(resp.candidates[0].content)
    fc = next((p.function_call for p in resp.candidates[0].content.parts if p.function_call), None)
    if not fc:
        print(resp.text)
        break
    result = get_weather(**dict(fc.args))
    contents.append(types.Content(role="user", parts=[types.Part(
        function_response=types.FunctionResponse(name=fc.name, response={"result": result})
    )]))
Automatic function calling — 편의 모드·python
# 진짜 Python function 넘기면 SDK 가 loop 처리.
resp = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Weather in Seoul?",
    config=types.GenerateContentConfig(tools=[get_weather]),
)
print(resp.text)

External links

Exercise

Tool 하나로 같은 prompt 를 두 방식으로 돌려봐 — automatic function calling 과 직접 짠 loop. 자동 경로에서 뭘 잃는지 적어. 에러 처리, 병렬 실행, 중간 기록. 그 목록이 곧 loop 를 직접 짤 때 네가 지켜내는 영역이야.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.