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

모드와 호출·응답 형식

~14 min · tools, modes, function-call, function-response

Level 0불씨
0 XP0/35 lessons0/10 achievements
0/140 XP to next level140 XP to go0% complete

네 가지 함수 호출 모드

  • AUTO(기본값) — 도구를 호출할지 텍스트로 답할지 모델이 결정해.
  • ANY — 모델이 반드시 함수를 하나 이상 호출해. 텍스트만으로 끝내면 안 되는 작업 흐름에 유용해.
  • NONE — 도구를 선언했어도 모델이 호출하지 못하게 해. 도구는 등록돼 있지만 이번 차례에는 텍스트만 받고 싶을 때 써.
  • VALIDATED — ANY와 비슷하지만 스키마를 엄격히 지키게 해.

allowed_function_names를 쓰면 이번 차례에 호출할 수 있는 도구를 일부로 제한할 수 있어.

호출 형식 — 모델이 내놓는 값

모델이 도구 호출을 선택하면 응답의 candidates[0].content.parts에 하나 이상의 function_call part가 들어 있어. 각각은 다음 값을 담아:

  • name — 호출할 도구 이름.
  • args — 선언한 매개변수와 맞는 JSON 객체.
  • id — 내부 식별자. Gemini 3 이상에는 항상 있고 2.5에는 없을 때도 있어.

응답 형식 — 애플리케이션이 돌려주는 값

도구를 실행한 뒤 결과를 다음 사용자 차례의 function_response part로 보내:

  • name — 원래 호출의 이름과 맞춰.
  • response — 결과를 {"result": ...}로 감싸.
  • id — 호출에 id가 있다면 같은 값으로 맞춰.

Gemini와 OpenAI의 역할 차이

OpenAI 방식에 익숙하면 여기서 다치기 쉬워. Gemini의 도구 결과 역할은 "tool"이 아니라 "user"야. 개념상 사용자가 도구의 출력을 제공하는 셈이지. 도구 결과가 여러 개라면 별도 메시지로 나누지 않고 같은 사용자 차례에 여러 part로 넣어.

Code

모드 설정과 도구 제한·python
from google.genai import types

config = types.GenerateContentConfig(
    tools=[tools],  # the Tool(function_declarations=[...]) from previous lesson
    tool_config=types.ToolConfig(
        function_calling_config=types.FunctionCallingConfig(
            mode='ANY',
            allowed_function_names=['set_light_values'],  # restrict
        ),
    ),
)
응답에서 함수 호출 읽기·python
response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents='Make the lights warm and 30%',
    config=config,
)

# Iterate parts — there might be multiple calls
for part in response.candidates[0].content.parts:
    if part.function_call:
        fc = part.function_call
        print(f'Tool: {fc.name}')
        print(f'Args: {dict(fc.args)}')
        print(f'ID: {fc.id}')  # may be None on 2.5

# Or use the convenience
for fc in (response.function_calls or []):
    ...
결과 돌려보내기·python
# Execute YOUR function
result = my_set_light_values(brightness=30, color_temp='warm')
# result might be: {'status': 'ok', 'brightness': 30, 'colorTemperature': 'warm'}

# Build the function-response part
response_part = types.Part.from_function_response(
    name=fc.name,
    response={'result': result},
    id=fc.id,  # match the call's id when present
)

# Append to conversation as a user turn
contents.append(response.candidates[0].content)         # model's call turn
contents.append(types.Content(role='user', parts=[response_part]))  # your result
Gemini vs OpenAI 모양 — 나란히·python
# OpenAI: separate "tool" message per result
# [
#   {role: 'assistant', tool_calls: [{id: 'c1', function: {...}}]},
#   {role: 'tool', tool_call_id: 'c1', content: '{"result": ...}'}
# ]

# Gemini: results go in a USER turn, multiple parts allowed
# [
#   {role: 'model', parts: [{function_call: {name, args, id}}]},
#   {role: 'user',  parts: [{function_response: {name, id, response: {result}}}]},
# ]

External links

Exercise

앞 레슨의 set_light_values 도구를 써. mode=AUTO와 "What's the weather like?" 프롬프트로 Flash를 호출해 텍스트 답변을 관찰해. 그다음 같은 프롬프트를 mode=ANY로 보내 도구 호출이 강제되고 이상한 인자가 나올 수도 있는 모습을 확인해. 한 실험에서 AUTO의 유연성과 ANY의 엄격함을 모두 볼 수 있어.

Progress

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

댓글 0

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

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