Gemini API를 사용한 함수 호출

함수 호출을 사용하면 모델을 외부 도구 및 API에 연결할 수 있습니다. 모델은 텍스트 대답을 생성하는 대신 특정 함수를 호출할 시점을 결정하고 실제 작업을 실행하는 데 필요한 파라미터를 제공합니다. 이를 통해 모델은 자연어와 실제 작업 및 데이터 간의 브리지 역할을 할 수 있습니다. 함수 호출에는 3가지 주요 사용 사례가 있습니다.

  • 지식 보강: 데이터베이스, API, 기술 자료와 같은 외부 소스의 정보에 액세스합니다.
  • 기능 확장: 외부 도구를 사용하여 계산을 수행하고 계산기 사용 또는 차트 생성과 같이 모델의 제한사항을 확장합니다.
  • 작업 수행: 약속 일정 예약, 인보이스 생성, 이메일 전송, 스마트 홈 기기 제어 등 API를 사용하여 외부 시스템과 상호작용합니다.

Python

# This will only work for SDK newer than 2.0.0
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-flash-preview",
    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}")

자바스크립트

// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const scheduleMeetingFunction = {
  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'],
  },
};

const interaction = await client.interactions.create({
  model: 'gemini-3-flash-preview',
  input: 'Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.',
  tools: [scheduleMeetingFunction],
});

for (const step of interaction.steps) {
  if (step.type === 'function_call') {
    console.log(`Function to call: ${step.name}`);
    console.log(`Arguments: ${JSON.stringify(step.arguments)}`);
  }
}

REST

# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.",
    "tools": [{
        "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"},
            "time": {"type": "string"},
            "topic": {"type": "string"}
          },
          "required": ["attendees", "date", "time", "topic"]
        }
    }]
  }'

함수 호출 작동 방식

함수 호출 개요

함수 호출은 애플리케이션, 모델, 외부 함수 간의 구조화된 상호작용을 포함합니다.

  1. 함수 선언 정의: 함수의 이름, 매개변수, 목적을 모델에 정의합니다.
  2. 함수 선언으로 LLM 호출: 사용자 프롬프트와 함수 선언을 모델에 전송합니다.
  3. 함수 코드 실행 (사용자 책임): 모델이 함수 자체를 실행하지 않습니다. 이름과 인수를 추출하고 애플리케이션에서 실행합니다.
  4. 사용자 친화적인 응답 만들기: 최종 사용자 친화적인 응답을 위해 결과를 모델에 다시 전송합니다.

이 프로세스는 여러 턴에 걸쳐 반복될 수 있습니다. 모델은 단일 턴에서 여러 함수를 호출하는 병렬 함수 호출과 순차적으로 함수를 호출하는 구성 함수 호출을 지원합니다.

1단계: 함수 선언 정의

Python

# This will only work for SDK newer than 2.0.0
set_light_values_declaration = {
    "type": "function",
    "name": "set_light_values",
    "description": "Sets the brightness and color temperature of a light.",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "integer",
                "description": "Light level from 0 to 100",
            },
            "color_temp": {
                "type": "string",
                "enum": ["daylight", "cool", "warm"],
                "description": "Color temperature",
            },
        },
        "required": ["brightness", "color_temp"],
    },
}

def set_light_values(brightness: int, color_temp: str) -> dict:
    """Set the brightness and color temperature of a room light."""
    return {"brightness": brightness, "colorTemperature": color_temp}

자바스크립트

// This will only work for SDK newer than 2.0.0
const setLightValuesTool = {
  type: 'function',
  name: 'set_light_values',
  description: 'Sets the brightness and color temperature of a light.',
  parameters: {
    type: 'object',
    properties: {
      brightness: { type: 'number', description: 'Light level from 0 to 100' },
      color_temp: { type: 'string', enum: ['daylight', 'cool', 'warm'] },
    },
    required: ['brightness', 'color_temp'],
  },
};

function setLightValues(brightness, color_temp) {
  return { brightness: brightness, colorTemperature: color_temp };
}

2단계: 함수 선언으로 모델 호출

Python

# This will only work for SDK newer than 2.0.0
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Turn the lights down to a romantic level",
    tools=[set_light_values_declaration],
)

# Find the function call step
fc_step = next(s for s in interaction.steps if s.type == "function_call")
print(fc_step)

자바스크립트

// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
  model: 'gemini-3-flash-preview',
  input: 'Turn the lights down to a romantic level',
  tools: [setLightValuesTool],
});

// Find the function call step
const fcStep = interaction.steps.find(s => s.type === 'function_call');
console.log(fcStep);

모델은 type, name, arguments이 포함된 function_call 단계를 반환합니다.

type='function_call'
name='set_light_values'
arguments={'color_temp': 'warm', 'brightness': 25}

3단계: 함수 실행

Python

# This will only work for SDK newer than 2.0.0
fc_step = next(s for s in interaction.steps if s.type == "function_call")

if fc_step.name == "set_light_values":
    result = set_light_values(**fc_step.arguments)
    print(f"Function execution result: {result}")

자바스크립트

// This will only work for SDK newer than 2.0.0
const fcStep = interaction.steps.find(s => s.type === 'function_call');

let result;
if (fcStep.name === 'set_light_values') {
  result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp);
  console.log(`Function execution result: ${JSON.stringify(result)}`);
}

4단계: 결과를 모델에 다시 전송

Python

# This will only work for SDK newer than 2.0.0
final_interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input=[
        {
            "type": "function_result",
            "name": fc_step.name,
            "call_id": fc_step.id,
            "result": [{"type": "text", "text": json.dumps(result)}],
        }
    ],
    tools=[set_light_values_declaration],
    previous_interaction_id=interaction.id,
)

print(final_interaction.steps[-1].content[0].text)

자바스크립트

// This will only work for SDK newer than 2.0.0
const finalInteraction = await client.interactions.create({
  model: 'gemini-3-flash-preview',
  input: [{
    type: 'function_result',
    name: fcStep.name,
    call_id: fcStep.id,
    result: [{ type: 'text', text: JSON.stringify(result) }]
  }],
  tools: [setLightValuesTool],
  previous_interaction_id: interaction.id,
});

console.log(finalInteraction.steps.at(-1).content[0].text);

스테이트리스 함수 호출

클라이언트 측에서 대화 기록을 관리하고 store=false를 설정하여 상태 비저장 모드에서 함수 호출을 사용할 수도 있습니다.

스테이트리스(Stateless) 모드에서는 각 후속 요청의 input 필드에 대화의 전체 기록을 전달해야 합니다. 이 기록에는 다음이 포함되어야 합니다. 1. 초기 user_input 단계입니다. 2. 턴 1에서 반환된 모든 모델 생성 단계 (thoughtfunction_call 단계 포함)가 수신된 그대로입니다. 3. 실행된 함수의 출력이 포함된 function_result 단계

Python

# This will only work for SDK newer than 2.0.0
from google import genai
import json

client = genai.Client()

# Initialize history with Turn 1 input
history = [
    {
        "type": "user_input",
        "content": [{"type": "text", "text": "Turn the lights down to a romantic level"}]
    }
]

# Turn 1: Call model with tools and store=False
interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    store=False,
    input=history,
    tools=[set_light_values_declaration],
)

# Append all model-generated steps (including thoughts and function_calls)
for step in interaction.steps:
    history.append(step.model_dump())

# Find the function call step to execute it
fc_step = next(s for s in interaction.steps if s.type == "function_call")
if fc_step.name == "set_light_values":
    result = set_light_values(**fc_step.arguments)

# Append the function result as a step
history.append({
    "type": "function_result",
    "name": fc_step.name,
    "call_id": fc_step.id,
    "result": [{"type": "text", "text": json.dumps(result)}],
})

# Turn 2: Send the full history to get the final response
final_interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    store=False,
    input=history,
    tools=[set_light_values_declaration],
)

print(final_interaction.steps[-1].content[0].text)

자바스크립트

// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

async function main() {
  // Initialize history with Turn 1 input
  const history = [
    {
      type: "user_input",
      content: [{ type: "text", text: "Turn the lights down to a romantic level" }]
    }
  ];

  // Turn 1: Call model with tools and store: false
  const interaction = await client.interactions.create({
    model: "gemini-3-flash-preview",
    store: false,
    input: history,
    tools: [setLightValuesTool],
  });

  // Append all model-generated steps
  history.push(...interaction.steps);

  // Find and execute function
  const fcStep = interaction.steps.find(s => s.type === 'function_call');
  let result;
  if (fcStep.name === 'set_light_values') {
    result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp);
  }

  // Append function result step
  history.push({
    type: 'function_result',
    name: fcStep.name,
    call_id: fcStep.id,
    result: [{ type: 'text', text: JSON.stringify(result) }]
  });

  // Turn 2: Send full history
  const finalInteraction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    store: false,
    input: history,
    tools: [setLightValuesTool],
  });

  console.log(finalInteraction.steps.at(-1).content[0].text);
}

await main();

REST

# Turn 1: Send request with tools and store: false
# Specifies the API revision to avoid breaking changes when they become default
RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-3-flash-preview",
    "store": false,
    "input": [
      {
        "type": "user_input",
        "content": [{"type": "text", "text": "Turn the lights down to a romantic level"}]
      }
    ],
    "tools": [{
      "type": "function",
      "name": "set_light_values",
      "description": "Sets the brightness and color temperature of a light.",
      "parameters": {
        "type": "object",
        "properties": {
          "brightness": {"type": "integer", "description": "Light level from 0 to 100"},
          "color_temp": {"type": "string", "enum": ["daylight", "cool", "warm"]}
        },
        "required": ["brightness", "color_temp"]
      }
    }]
  }')

# Extract model steps (thought, function_call)
MODEL_STEPS=$(echo "$RESPONSE1" | jq '.steps')

# Extract function call details to execute
FC_NAME=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .name')
FC_ID=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .id')

# Assume local execution returns: {"brightness": 25, "colorTemperature": "warm"}
RESULT="{\"brightness\": 25, \"colorTemperature\": \"warm\"}"

# Reconstruct history for Turn 2
HISTORY=$(jq -n \
  --argjson first_input '[{"type": "user_input", "content": [{"type": "text", "text": "Turn the lights down to a romantic level"}]}]' \
  --argjson model_steps "$MODEL_STEPS" \
  --arg fc_name "$FC_NAME" \
  --arg fc_id "$FC_ID" \
  --arg result "$RESULT" \
  '$first_input + $model_steps + [{"type": "function_result", "name": $fc_name, "call_id": $fc_id, "result": [{"type": "text", "text": $result}]}]')

# Turn 2: Send the full history
# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Api-Revision: 2026-05-20" \
  -d "{
    \"model\": \"gemini-3-flash-preview\",
    \"store\": false,
    \"input\": $HISTORY,
    \"tools\": [{
      \"type\": \"function\",
      \"name\": \"set_light_values\",
      \"description\": \"Sets the brightness and color temperature of a light.\",
      \"parameters\": {
        \"type\": \"object\",
        \"properties\": {
          \"brightness\": {\"type\": \"integer\"},
          \"color_temp\": {\"type\": \"string\"}
        },
        \"required\": [\"brightness\", \"color_temp\"]
      }
    }]
  }"

함수 선언

함수 선언은 도구로 전달되며 다음을 포함합니다.

  • type (문자열): 맞춤 함수의 경우 "function"여야 합니다.
  • name (문자열): 고유한 함수 이름 (밑줄 또는 카멜 표기법 사용)
  • description (문자열): 함수의 목적에 관한 명확한 설명입니다.
  • parameters (객체): 함수가 예상하는 입력 매개변수입니다.
    • type (문자열): object과 같은 전체 데이터 유형입니다.
    • properties (객체): 유형과 설명이 있는 개별 매개변수입니다.
    • required (배열): 필수 매개변수 이름입니다.

사고 모델을 사용한 함수 호출

Gemini 3 및 2.5 시리즈 모델은 함수 호출을 개선하는 내부 '사고' 프로세스를 사용합니다. SDK는 생각 서명을 자동으로 처리합니다.

병렬 함수 호출

독립적인 경우 한 번에 여러 함수 호출:

Python

# This will only work for SDK newer than 2.0.0
power_disco_ball = {"type": "function", "name": "power_disco_ball", "description": "Powers the disco ball.",
    "parameters": {"type": "object", "properties": {"power": {"type": "boolean"}}, "required": ["power"]}}
start_music = {"type": "function", "name": "start_music", "description": "Play music.",
    "parameters": {"type": "object", "properties": {"energetic": {"type": "boolean"}, "loud": {"type": "boolean"}}, "required": ["energetic", "loud"]}}
dim_lights = {"type": "function", "name": "dim_lights", "description": "Dim the lights.",
    "parameters": {"type": "object", "properties": {"brightness": {"type": "number"}}, "required": ["brightness"]}}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Turn this place into a party!",
    tools=[power_disco_ball, start_music, dim_lights],
    generation_config={"tool_choice": "any"},
)

for step in interaction.steps:
    if step.type == "function_call":
        args = ", ".join(f"{key}={val}" for key, val in step.arguments.items())
        print(f"{step.name}({args})")

자바스크립트

// This will only work for SDK newer than 2.0.0
const powerDiscoBall = { type: 'function', name: 'power_disco_ball', description: 'Powers the disco ball.',
  parameters: { type: 'object', properties: { power: { type: 'boolean' } }, required: ['power'] } };
const startMusic = { type: 'function', name: 'start_music', description: 'Play music.',
  parameters: { type: 'object', properties: { energetic: { type: 'boolean' }, loud: { type: 'boolean' } }, required: ['energetic', 'loud'] } };
const dimLights = { type: 'function', name: 'dim_lights', description: 'Dim the lights.',
  parameters: { type: 'object', properties: { brightness: { type: 'number' } }, required: ['brightness'] } };

const interaction = await client.interactions.create({
  model: 'gemini-3-flash-preview',
  input: 'Turn this place into a party!',
  tools: [powerDiscoBall, startMusic, dimLights],
  generation_config: { tool_choice: 'any' },
});

for (const step of interaction.steps) {
  if (step.type === 'function_call') {
    console.log(`${step.name}(${JSON.stringify(step.arguments)})`);
  }
}

구성 함수 호출

복잡한 요청을 위해 여러 함수 호출을 함께 연결합니다 (예: 먼저 위치를 가져온 다음 해당 위치의 날씨를 가져옴).

Python

# This will only work for SDK newer than 2.0.0
get_weather_forecast_declaration = {
    "type": "function",
    "name": "get_weather_forecast",
    "description": "Gets the current weather temperature for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "The location"},
        },
        "required": ["location"],
    },
}

set_thermostat_temperature_declaration = {
    "type": "function",
    "name": "set_thermostat_temperature",
    "description": "Sets the thermostat to a desired temperature.",
    "parameters": {
        "type": "object",
        "properties": {
            "temperature": {
                "type": "integer",
                "description": "The temperature in Celsius",
            },
        },
        "required": ["temperature"],
    },
}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.",
    tools=[
        get_weather_forecast_declaration,
        set_thermostat_temperature_declaration,
    ],
)

for step in interaction.steps:
    if step.type == "function_call":
        print(f"Function to call: {step.name}")
        print(f"Arguments: {step.arguments}")
    elif hasattr(step, "content") and step.content:
         for part in step.content:
             if hasattr(part, "text"):
                 print(part.text)

함수 호출 모드

generation_config에서 tool_choice를 사용하여 모델이 도구를 사용하는 방식 제어:

  • auto (기본값): 모델이 함수를 호출할지 아니면 직접 응답할지 결정합니다.
  • any: 모델이 항상 함수 호출을 예측하도록 제한됩니다.
  • none: 모델이 함수 호출을 실행하는 것이 금지됩니다.
  • validated (미리보기): 모델이 함수 스키마 준수를 보장합니다.

Python

# This will only work for SDK newer than 2.0.0
generation_config = {
    "tool_choice": {
        "allowed_tools": {
            "mode": "any",
            "tools": ["get_current_temperature"]
        }
    }
}

자바스크립트

// This will only work for SDK newer than 2.0.0
const generation_config = {
  tool_choice: {
    allowed_tools: {
      mode: 'any',
      tools: ['get_current_temperature']
    }
  }
};

REST

# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "What is the temperature in Boston?",
    "tools": [{
      "type": "function",
      "name": "get_current_temperature",
      "description": "Gets the current temperature for a given location.",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {"type": "string"}
        },
        "required": ["location"]
      }
    }],
    "generation_config": {
      "tool_choice": {
        "allowed_tools": {
          "mode": "any",
          "tools": ["get_current_temperature"]
        }
      }
    }
  }'

멀티 도구 사용

동일한 요청에서 기본 제공 도구와 함수 호출을 결합하여 여러 도구를 사용 설정할 수 있습니다. Gemini 3 모델은 상호작용에서 기본 제공 도구와 함수 호출을 즉시 결합할 수 있습니다. previous_interaction_id를 전달하면 기본 제공 도구 컨텍스트가 자동으로 순환됩니다.

Python

# This will only work for SDK newer than 2.0.0
from google import genai
import json

client = genai.Client()

get_weather = {
    "type": "function",
    "name": "get_weather",
    "description": "Gets the weather for a requested city.",
    "parameters": {
        "type": "object",
        "properties": {
            "city": {
                "type": "string",
                "description": "The city and state, e.g. Utqiaġvik, Alaska",
            },
        },
        "required": ["city"],
    },
}

tools = [
    {"type": "google_search"},  # Built-in tool
    get_weather                 # Custom tool
]

# Turn 1: Initial request with both tools enabled
interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="What is the northernmost city in the United States? What's the weather like there today?",
    tools=tools
)

for step in interaction.steps:
    if step.type == "function_call":
        print(f"Function call: {step.name} (ID: {step.id})")
        # Execute your custom function locally
        result = {"response": "Very cold. 22 degrees Fahrenheit."}
        # Turn 2: Provide the function result back to the model.
        # Passing `previous_interaction_id` automatically circulates the
        # built-in Google Search context from Turn 1
        interaction_2 = client.interactions.create(
            model="gemini-3-flash-preview",
            previous_interaction_id=interaction.id,
            tools=tools,
            input=[{
                "type": "function_result",
                "name": step.name,
                "call_id": step.id,
                "result": [{"type": "text", "text": json.dumps(result)}]
            }]
        )

        print(interaction_2.steps[-1].content[0].text)

자바스크립트

// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const weatherTool = {
    type: 'function',
    name: 'get_weather',
    description: 'Gets the weather for a given location.',
    parameters: {
        type: 'object',
        properties: {
            location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA' }
        },
        required: ['location']
    }
};

const tools = [
    {type: 'google_search'}, // Built-in tool
    weatherTool              // Custom tool
];

// Turn 1: Initial request with both tools enabled
let interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: "What is the northernmost city in the United States? What's the weather like there today?",
    tools: tools
});

for (const step of interaction.steps) {
    if (step.type === 'function_call') {
        console.log(`Function call: ${step.name} (ID: ${step.id})`);
        // Execute your custom function locally
        const result = {response: "Very cold. 22 degrees Fahrenheit."};
        // Turn 2: Provide the function result back to the model.
        const interaction_2 = await client.interactions.create({
            model: 'gemini-3-flash-preview',
            previous_interaction_id: interaction.id,
            tools: tools,
            input: [{
                type: 'function_result',
                name: step.name,
                call_id: step.id,
                result: [{ type: 'text', text: JSON.stringify(result) }]
            }]
        });

        console.log(interaction_2.steps.at(-1).content[0].text);
    }
}

멀티모달 함수 응답

Gemini 3 시리즈 모델의 경우 모델에 전송하는 함수 응답 부분에 멀티모달 콘텐츠를 포함할 수 있습니다. 모델은 다음 차례에 이 멀티모달 콘텐츠를 처리하여 더 많은 정보를 바탕으로 응답을 생성할 수 있습니다.

함수 응답에 멀티모달 데이터를 포함하려면 function_result 단계의 result 필드에 하나 이상의 콘텐츠 블록으로 포함하세요. 각 콘텐츠 블록은 type (예: "text", "image")를 지정해야 합니다.

다음 예시는 상호작용에서 이미지 데이터가 포함된 함수 응답을 모델에 다시 전송하는 방법을 보여줍니다.

Python

# This will only work for SDK newer than 2.0.0
import base64
from google import genai
import requests

client = genai.Client()

# Find the function call step
tool_call = next(s for s in interaction.steps if s.type == "function_call")

# Execute your tool to get image bytes
image_path = "https://goo.gle/instrument-img"
image_bytes = requests.get(image_path).content

base64_image_data = base64.b64encode(image_bytes).decode("utf-8")

final_interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    previous_interaction_id=interaction.id,
    input=[
        {
            "type": "function_result",
            "name": tool_call.name,
            "call_id": tool_call.id,
            "result": [
                {"type": "text", "text": "instrument.jpg"},
                {
                    "type": "image",
                    "mime_type": "image/jpeg",
                    "data": base64_image_data,
                },
            ],
        }
    ],
)

print(final_interaction.steps[-1].content[0].text)

자바스크립트

// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

// Find the function call step
const toolCall = interaction.steps.find(s => s.type === 'function_call');

// Execute your tool to get image bytes and convert to base64
// (Implementation depends on your environment)
const base64ImageData = "BASE64_IMAGE_DATA";

const finalInteraction = await ai.interactions.create({
    model: 'gemini-3-flash-preview',
    previous_interaction_id: interaction.id,
    input: [{
        type: 'function_result',
        name: toolCall.name,
        call_id: toolCall.id,
        result: [
            { type: 'text', text: 'instrument.jpg' },
            {
                type: 'image',
                mime_type: 'image/jpeg',
                data: base64ImageData,
            }
        ]
    }]
});

console.log(finalInteraction.steps.at(-1).content[0].text);

REST

# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-3-flash-preview",
    "previous_interaction_id": "INTERACTION_ID",
    "input": [
      {
        "type": "function_result",
        "name": "get_image",
        "call_id": "call_123",
        "result": [
          {"type": "text", "text": "instrument.jpg"},
          {
            "type": "image",
            "mime_type": "image/jpeg",
            "data": "BASE64_IMAGE_DATA"
          }
        ]
      }
    ]
  }'

구조화된 출력을 사용한 함수 호출

Gemini 3 시리즈 모델의 경우 함수 호출을 구조화된 출력과 결합하여 일관된 형식의 응답을 얻으세요.

원격 MCP (모델 컨텍스트 프로토콜)

Interactions API는 원격 MCP 서버에 연결하여 모델이 외부 도구 및 서비스에 액세스할 수 있도록 지원합니다. 도구 구성에서 서버 nameurl을 제공합니다.

원격 MCP를 사용할 때는 다음 제약 조건에 유의하세요.

  • 서버 유형: 원격 MCP는 스트리밍 가능 HTTP 서버에서만 작동합니다. SSE (서버 전송 이벤트) 서버는 지원되지 않습니다.
  • 모델 지원: 현재 원격 MCP는 Gemini 3 모델과 호환되지 않습니다. Gemini 3 지원이 곧 제공될 예정입니다.
  • 이름 지정: MCP 서버 이름에 - 문자가 포함되어서는 안 됩니다. 대신 snake_case 서버 이름을 사용하세요.
필드 유형 필수 설명
type string "mcp_server"이어야 합니다.
name string 아니요 MCP 서버의 표시 이름입니다.
url string 아니요 MCP 서버 엔드포인트의 전체 URL입니다.
headers object 아니요 서버에 대한 모든 요청과 함께 HTTP 헤더로 전송되는 키-값 쌍 (예: 인증 토큰)입니다.
allowed_tools array 아니요 에이전트가 호출할 수 있는 서버의 도구를 제한합니다.

Python

# This will only work for SDK newer than 2.0.0
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-2.5-flash",
    input="Check the status of my last server deployment.",
    tools=[
        {
            "type": "mcp_server",
            "name": "Deployment Tracker",
            "url": "https://mcp.example.com/mcp",
            "headers": {"Authorization": "Bearer my-token"},
        }
    ]
)

자바스크립트

// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-2.5-flash',
    input: 'Check the status of my last server deployment.',
    tools: [
        {
            type: 'mcp_server',
            name: 'Deployment Tracker',
            url: 'https://mcp.example.com/mcp',
            headers: { Authorization: 'Bearer my-token' }
        }
    ]
});

REST

# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20" \
-d '{
    "model": "gemini-2.5-flash",
    "input": "Check the status of my last server deployment.",
    "tools": [
        {
            "type": "mcp_server",
            "name": "Deployment Tracker",
            "url": "https://mcp.example.com/mcp",
            "headers": {"Authorization": "Bearer my-token"}
        }
    ]
}'

도구 호출 스트리밍

스트리밍과 함께 도구를 사용하면 모델은 스트림에서 step.delta 이벤트 시퀀스로 함수 호출을 생성합니다. arguments을 사용하여 도구 인수를 부분 인수로 스트리밍할 수 있습니다. 이러한 델타를 집계하여 실행하기 전에 전체 도구 호출을 재구성해야 합니다.

Python

# This will only work for SDK newer than 2.0.0
import json
from google import genai

client = genai.Client()

weather_tool = {
    "type": "function",
    "name": "get_weather",
    "description": "Gets the weather for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "The city and state"}
        },
        "required": ["location"]
    }
}

stream = client.interactions.create(
    model="gemini-3-flash-preview",
    input="What is the weather in Paris?",
    tools=[weather_tool],
    stream=True
)

current_calls = {}
tool_calls = []

for event in stream:
    if event.event_type == "step.start":
        if event.step.type == "function_call":
            current_calls[event.index] = {
                "id": event.step.id,
                "name": event.step.name,
                "arguments": ""
            }
            # Handle arguments provided in step.start
            if hasattr(event.step, "arguments") and event.step.arguments:
                if isinstance(event.step.arguments, dict):
                    current_calls[event.index]["arguments"] = json.dumps(event.step.arguments)
                else:
                    current_calls[event.index]["arguments"] = event.step.arguments
    elif event.event_type == "step.delta":
        if event.delta.type == "arguments":
            if event.index in current_calls:
                current_calls[event.index]["arguments"] += event.delta.partial_arguments
        elif event.delta.type == "text":
            print(event.delta.text, end="", flush=True)

    elif event.event_type == "interaction.completed":
        for index, call in current_calls.items():
            args = call["arguments"]
            if args:
                args = json.loads(args)
            else:
                args = {}

            tool_calls.append({
                "type": "function_call",
                "id": call["id"],
                "name": call["name"],
                "arguments": args
            })

        print(f"\nFinal tool calls ready to execute:")
        print(json.dumps(tool_calls, indent=2))

자바스크립트

// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const weatherTool = {
    type: 'function',
    name: 'get_weather',
    description: 'Gets the weather for a given location.',
    parameters: {
        type: 'object',
        properties: {
            location: { type: 'string', description: 'The city and state' }
        },
        required: ['location']
    }
};

const stream = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'What is the weather in Paris?',
    tools: [weatherTool],
    stream: true,
});

const currentCalls = new Map();
let toolCalls = [];

for await (const event of stream) {
    const evType = event.event_type;
    if (evType === 'step.start') {
        if (event.step.type === 'function_call') {
            currentCalls.set(event.index, {
                id: event.step.id,
                name: event.step.name,
                arguments: ''
            });
            // Handle arguments provided in step.start
            if (event.step.arguments) {
                if (typeof event.step.arguments === 'object') {
                    currentCalls.get(event.index).arguments = JSON.stringify(event.step.arguments);
                } else {
                    currentCalls.get(event.index).arguments = event.step.arguments;
                }
            }
        }
    } else if (evType === 'step.delta') {
        if (event.delta.type === 'arguments') {
            if (currentCalls.has(event.index)) {
                currentCalls.get(event.index).arguments += event.delta.partial_arguments;
            }
        } else if (event.delta.type === 'text') {
            process.stdout.write(event.delta.text);
        }
    } else if (evType === 'interaction.completed' || evType === 'interaction.complete') {
        toolCalls = Array.from(currentCalls.values()).map(call => ({
            type: 'function_call',
            id: call.id,
            name: call.name,
            arguments: call.arguments ? JSON.parse(call.arguments) : {}
        }));
        console.log('\nFinal tool calls ready to execute:');
        console.log(JSON.stringify(toolCalls, null, 2));
    }
}

REST

# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "What is the weather in Paris?",
    "tools": [{
        "type": "function",
        "name": "get_weather",
        "description": "Gets the weather for a given location.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "The city and state"}
            },
            "required": ["location"]
        }
    }],
    "stream": true
}'

권장사항

  • 함수 및 파라미터 설명: 명확하고 구체적으로 작성하세요.
  • 이름 지정: 공백이나 특수문자가 없는 설명적인 이름을 사용합니다.
  • 강한 타이핑: 구체적인 유형 (정수, 문자열, enum)을 사용합니다.
  • 도구 선택: 활성 도구 세트를 최대 10~20개로 유지합니다.
  • 프롬프트 엔지니어링: 컨텍스트와 요청 사항을 제공합니다.
  • 유효성 검사: 실행 전에 함수 호출을 검증합니다.
  • 오류 처리: 오류를 효과적으로 처리합니다.
  • 보안: 외부 API에 적절한 인증을 사용합니다.

참고사항 및 제한사항

  • OpenAPI 스키마의 하위 집합만 지원됩니다.
  • any 모드의 경우 API가 매우 크거나 깊이 중첩된 스키마를 거부할 수 있습니다.
  • Python에서 지원되는 매개변수 유형은 제한적입니다.