Gemini API를 사용한 함수 호출

함수 호출을 사용하면 모델을 외부 도구 및 API에 연결할 수 있습니다. 모델은 텍스트 응답을 생성하는 대신 특정 함수를 호출할 시기를 파악하고 실제 작업을 실행하는 데 필요한 매개변수를 제공합니다. 이를 통해 모델이 자연어와 실제 작업 및 데이터 간의 가교 역할을 할 수 있습니다. 함수 호출에는 다음과 같은 세 가지 기본 사용 사례가 있습니다.

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

함수 호출의 작동 방식

함수 호출 개요

함수 호출에는 애플리케이션, 모델, 외부 함수 간의 구조화된 상호작용이 포함됩니다. 이 과정은 다음과 같이 세분화할 수 있습니다.

  1. 함수 선언 정의: 애플리케이션 코드에서 함수 선언을 정의합니다. 함수 선언은 모델에 함수의 이름, 매개변수, 목적을 설명합니다.
  2. 함수 선언으로 LLM 호출: 함수 선언과 함께 사용자 프롬프트를 모델에 전송합니다. 요청을 분석하고 함수 호출이 유용할지 결정합니다. 그렇다면 구조화된 JSON 객체로 응답합니다.
  3. 함수 코드 실행 (개발자 책임): 모델은 함수 자체를 실행하지 않습니다. 응답을 처리하고 함수 호출을 확인하는 것은 애플리케이션의 책임입니다.
    • : 함수의 이름과 args를 추출하고 애플리케이션에서 상응하는 함수를 실행합니다.
    • 아니요: 모델이 프롬프트에 직접적인 텍스트 응답을 제공했습니다. 이 흐름은 예시에서 강조되지는 않지만 가능한 결과입니다.
  4. 사용자 친화적인 응답 생성: 함수가 실행된 경우 결과를 캡처하고 대화의 후속 턴에서 모델로 다시 전송합니다. 이 결과를 사용하여 함수 호출의 정보를 통합한 최종 사용자 친화적인 응답을 생성합니다.

이 프로세스는 여러 차례 반복하여 복잡한 상호작용과 워크플로를 허용할 수 있습니다. 이 모델은 단일 차례 (병렬 함수 호출)와 순차적으로 (구성 함수 호출) 여러 함수를 호출하는 것도 지원합니다.

1단계: 함수 선언 정의

사용자가 조명 값을 설정하고 API를 요청할 수 있는 함수와 선언을 애플리케이션 코드 내에 정의합니다. 이 함수는 외부 서비스 또는 API를 호출할 수 있습니다.

from google.genai import types

# Define a function that the model can call to control smart lights
set_light_values_declaration = {
    "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. Zero is off and 100 is full brightness",
            },
            "color_temp": {
                "type": "string",
                "enum": ["daylight", "cool", "warm"],
                "description": "Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.",
            },
        },
        "required": ["brightness", "color_temp"],
    },
}

# This is the actual function that would be called based on the model's suggestion
def set_light_values(brightness: int, color_temp: str) -> dict[str, int | str]:
    """Set the brightness and color temperature of a room light. (mock API).

    Args:
        brightness: Light level from 0 to 100. Zero is off and 100 is full brightness
        color_temp: Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.

    Returns:
        A dictionary containing the set brightness and color temperature.
    """
    return {"brightness": brightness, "colorTemperature": color_temp}

import { Type } from '@google/genai';

// Define a function that the model can call to control smart lights
const setLightValuesFunctionDeclaration = {
  name: 'set_light_values',
  description: 'Sets the brightness and color temperature of a light.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      brightness: {
        type: Type.NUMBER,
        description: 'Light level from 0 to 100. Zero is off and 100 is full brightness',
      },
      color_temp: {
        type: Type.STRING,
        enum: ['daylight', 'cool', 'warm'],
        description: 'Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.',
      },
    },
    required: ['brightness', 'color_temp'],
  },
};

/**
* Set the brightness and color temperature of a room light. (mock API)
* @param {number} brightness - Light level from 0 to 100. Zero is off and 100 is full brightness
* @param {string} color_temp - Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
* @return {Object} A dictionary containing the set brightness and color temperature.
*/
function setLightValues(brightness, color_temp) {
  return {
    brightness: brightness,
    colorTemperature: color_temp
  };
}

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

함수 선언을 정의한 후에는 모델에 함수를 사용하도록 프롬프트할 수 있습니다. 프롬프트와 함수 선언을 분석하고 직접 응답할지 아니면 함수를 호출할지 결정합니다. 함수가 호출되면 응답 객체에 함수 호출 제안이 포함됩니다.

from google import genai

# Generation Config with Function Declaration
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])

# Configure the client
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))

# Define user prompt
contents = [
    types.Content(
        role="user", parts=[types.Part(text="Turn the lights down to a romantic level")]
    )
]

# Send request with function declarations
response = client.models.generate_content(
    model="gemini-2.0-flash", config=config, contents=contents
)

print(response.candidates[0].content.parts[0].function_call)
import { GoogleGenAI } from '@google/genai';

// Generation Config with Function Declaration
const config = {
  tools: [{
    functionDeclarations: [setLightValuesFunctionDeclaration]
  }]
};

// Configure the client
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// Define user prompt
const contents = [
  {
    role: 'user',
    parts: [{ text: 'Turn the lights down to a romantic level' }]
  }
];

// Send request with function declarations
const response = await ai.models.generateContent({
  model: 'gemini-2.0-flash',
  contents: contents,
  config: config
});

console.log(response.functionCalls[0]); 

그러면 모델은 사용자의 질문에 응답하기 위해 선언된 함수 중 하나 이상을 호출하는 방법을 지정하는 OpenAPI 호환 스키마의 functionCall 객체를 반환합니다.

id=None args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'
{
  name: 'set_light_values',
  args: { brightness: 25, color_temp: 'warm' }
}

3단계: set_light_values 함수 코드 실행

모델의 응답에서 함수 호출 세부정보를 추출하고 인수를 파싱한 다음 코드에서 set_light_values 함수를 실행합니다.

# Extract tool call details
tool_call = response.candidates[0].content.parts[0].function_call

if tool_call.name == "set_light_values":
    result = set_light_values(**tool_call.args)
    print(f"Function execution result: {result}")
// Extract tool call details
const tool_call = response.functionCalls[0]

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

4단계: 함수 결과로 사용자 친화적인 응답을 만들고 모델을 다시 호출합니다.

마지막으로 함수 실행 결과를 모델에 다시 전송하여 모델이 이 정보를 사용자에게 보내는 최종 응답에 통합할 수 있도록 합니다.

# Create a function response part
function_response_part = types.Part.from_function_response(
    name=tool_call.name,
    response={"result": result},
)

# Append function call and result of the function execution to contents
contents.append(types.Content(role="model", parts=[types.Part(function_call=tool_call)])) # Append the model's function call message
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response

final_response = client.models.generate_content(
    model="gemini-2.0-flash",
    config=config,
    contents=contents,
)

print(final_response.text)
// Create a function response part
const function_response_part = {
  name: tool_call.name,
  response: { result }
}

// Append function call and result of the function execution to contents
contents.push({ role: 'model', parts: [{ functionCall: tool_call }] });
contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] });

// Get the final response from the model
const final_response = await ai.models.generateContent({
  model: 'gemini-2.0-flash',
  contents: contents,
  config: config
});

console.log(final_response.text);

이렇게 하면 함수 호출 흐름이 완료됩니다. 모델이 set_light_values 함수를 사용하여 사용자의 요청 작업을 실행했습니다.

함수 선언

프롬프트에서 함수 호출을 구현할 때는 하나 이상의 function declarations가 포함된 tools 객체를 만듭니다. JSON을 사용하여 함수를 정의합니다. 특히 OpenAPI 스키마 형식의 일부 하위 집합을 사용합니다. 단일 함수 선언에는 다음 매개변수가 포함될 수 있습니다.

  • name (문자열): 함수의 고유한 이름 (get_weather_forecast, send_email)입니다. 공백이나 특수문자가 없는 설명적인 이름을 사용하세요 (밑줄 또는 케임캐슬 사용).
  • description (문자열): 함수의 목적과 기능을 명확하고 자세하게 설명합니다. 이는 모델이 함수를 사용할 시기를 이해하는 데 중요합니다. 구체적으로 설명하고 도움이 되는 경우 예시를 제공합니다(예: '위치와 현재 극장에서 상영 중인 영화 제목(선택사항)을 기반으로 영화관을 찾습니다.').
  • parameters (객체): 함수가 예상하는 입력 매개변수를 정의합니다.
    • type(문자열): 전체 데이터 유형(예: object)을 지정합니다.
    • properties (객체): 개별 매개변수를 나열하며 각 매개변수에는 다음이 포함됩니다.
      • type(문자열): 매개변수의 데이터 유형입니다(예: string, integer, boolean, array).
      • description (문자열): 매개변수의 목적과 형식에 관한 설명입니다. 예시와 제약 조건을 제공합니다(예: '서울' 또는 우편번호(예: '95616'.").
      • enum (배열, 선택사항): 매개변수 값이 고정된 집합에서 가져온 경우 설명에 값을 설명하는 대신 'enum'을 사용하여 허용되는 값을 나열합니다. 이렇게 하면 정확성이 향상됩니다 ('enum': ['daylight', 'cool', 'warm']).
    • required (배열): 함수가 작동하는 데 필수인 매개변수 이름을 나열하는 문자열 배열입니다.

병렬 함수 호출

단일 턴 함수 호출 외에도 여러 함수를 한 번에 호출할 수도 있습니다. 병렬 함수 호출을 사용하면 여러 함수를 한 번에 실행할 수 있으며, 함수가 서로 종속되지 않을 때 사용됩니다. 이는 여러 독립된 소스에서 데이터를 수집하는 시나리오(예: 여러 데이터베이스에서 고객 세부정보를 검색하거나 여러 창고에서 인벤토리 수준을 확인하거나 아파트를 디스코로 전환하는 등의 여러 작업 실행)에 유용합니다.

power_disco_ball = {
    "name": "power_disco_ball",
    "description": "Powers the spinning disco ball.",
    "parameters": {
        "type": "object",
        "properties": {
            "power": {
                "type": "boolean",
                "description": "Whether to turn the disco ball on or off.",
            }
        },
        "required": ["power"],
    },
}

start_music = {
    "name": "start_music",
    "description": "Play some music matching the specified parameters.",
    "parameters": {
        "type": "object",
        "properties": {
            "energetic": {
                "type": "boolean",
                "description": "Whether the music is energetic or not.",
            },
            "loud": {
                "type": "boolean",
                "description": "Whether the music is loud or not.",
            },
        },
        "required": ["energetic", "loud"],
    },
}

dim_lights = {
    "name": "dim_lights",
    "description": "Dim the lights.",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "number",
                "description": "The brightness of the lights, 0.0 is off, 1.0 is full.",
            }
        },
        "required": ["brightness"],
    },
}
import { Type } from '@google/genai';

const powerDiscoBall = {
  name: 'power_disco_ball',
  description: 'Powers the spinning disco ball.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      power: {
        type: Type.BOOLEAN,
        description: 'Whether to turn the disco ball on or off.'
      }
    },
    required: ['power']
  }
};

const startMusic = {
  name: 'start_music',
  description: 'Play some music matching the specified parameters.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      energetic: {
        type: Type.BOOLEAN,
        description: 'Whether the music is energetic or not.'
      },
      loud: {
        type: Type.BOOLEAN,
        description: 'Whether the music is loud or not.'
      }
    },
    required: ['energetic', 'loud']
  }
};

const dimLights = {
  name: 'dim_lights',
  description: 'Dim the lights.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      brightness: {
        type: Type.NUMBER,
        description: 'The brightness of the lights, 0.0 is off, 1.0 is full.'
      }
    },
    required: ['brightness']
  }
};

지정된 모든 도구를 사용할 수 있는 명령으로 모델을 호출합니다. 이 예에서는 tool_config를 사용합니다. 자세한 내용은 함수 호출 구성을 참고하세요.

from google import genai
from google.genai import types

# Set up function declarations
house_tools = [
    types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]

config = {
    "tools": house_tools,
    "automatic_function_calling": {"disable": True},
    # Force the model to call 'any' function, instead of chatting.
    "tool_config": {"function_calling_config": {"mode": "any"}},
}

# Configure the client
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))

chat = client.chats.create(model="gemini-2.0-flash", config=config)
response = chat.send_message("Turn this place into a party!")

# Print out each of the function calls requested from this single call
print("Example 1: Forced function calling")
for fn in response.function_calls:
    args = ", ".join(f"{key}={val}" for key, val in fn.args.items())
    print(f"{fn.name}({args})")
import { GoogleGenAI } from '@google/genai';

// Set up function declarations
const houseFns = [powerDiscoBall, startMusic, dimLights];

const config = {
    tools: [{
        functionDeclarations: houseFns
    }],
    // Force the model to call 'any' function, instead of chatting.
    toolConfig: {
        functionCallingConfig: {
        mode: 'any'
        }
    }
};

// Configure the client
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// Create a chat session
const chat = ai.chats.create({
    model: 'gemini-2.0-flash',
    config: config
});
const response = await chat.sendMessage({message: 'Turn this place into a party!'});

// Print out each of the function calls requested from this single call
console.log("Example 1: Forced function calling");
for (const fn of response.functionCalls) {
    const args = Object.entries(fn.args)
        .map(([key, val]) => `${key}=${val}`)
        .join(', ');
    console.log(`${fn.name}(${args})`);
}

출력된 각 결과는 모델이 요청한 단일 함수 호출을 반영합니다. 결과를 다시 전송하려면 요청된 순서대로 응답을 포함합니다.

Python SDK는 Python 함수를 선언으로 변환하고 함수 호출 실행 및 응답 주기를 자동으로 처리하는 자동 함수 호출이라는 기능을 지원합니다. 다음은 디스코 사용 사례의 예입니다.

Python
from google import genai
from google.genai import types

# Actual implementation functions
def power_disco_ball_impl(power: bool) -> dict:
    """Powers the spinning disco ball.

    Args:
        power: Whether to turn the disco ball on or off.

    Returns:
        A status dictionary indicating the current state.
    """
    return {"status": f"Disco ball powered {'on' if power else 'off'}"}

def start_music_impl(energetic: bool, loud: bool) -> dict:
    """Play some music matching the specified parameters.

    Args:
        energetic: Whether the music is energetic or not.
        loud: Whether the music is loud or not.

    Returns:
        A dictionary containing the music settings.
    """
    music_type = "energetic" if energetic else "chill"
    volume = "loud" if loud else "quiet"
    return {"music_type": music_type, "volume": volume}

def dim_lights_impl(brightness: float) -> dict:
    """Dim the lights.

    Args:
        brightness: The brightness of the lights, 0.0 is off, 1.0 is full.

    Returns:
        A dictionary containing the new brightness setting.
    """
    return {"brightness": brightness}

config = {
    "tools": [power_disco_ball_impl, start_music_impl, dim_lights_impl],
}

chat = client.chats.create(model="gemini-2.0-flash", config=config)
response = chat.send_message("Do everything you need to this place into party!")

print("\nExample 2: Automatic function calling")
print(response.text)
# I've turned on the disco ball, started playing loud and energetic music, and dimmed the lights to 50% brightness. Let's get this party started!

구성 함수 호출

Gemini 2.0은 구성 함수 호출을 지원합니다. 즉, 모델은 여러 함수 호출을 함께 연결할 수 있습니다. 예를 들어 '현재 위치의 온도 가져오기'에 대답하기 위해 Gemini API는 get_current_location() 함수와 위치를 매개변수로 사용하는 get_weather() 함수를 모두 호출할 수 있습니다.

# Light control schemas
turn_on_the_lights_schema = {'name': 'turn_on_the_lights'}
turn_off_the_lights_schema = {'name': 'turn_off_the_lights'}

prompt = """
  Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
  """

tools = [
    {'code_execution': {}},
    {'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]}
]

await run(prompt, tools=tools, modality="AUDIO")
// Light control schemas
const turnOnTheLightsSchema = { name: 'turn_on_the_lights' };
const turnOffTheLightsSchema = { name: 'turn_off_the_lights' };

const prompt = `
  Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
`;

const tools = [
  { codeExecution: {} },
  { functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] }
];

await run(prompt, tools=tools, modality="AUDIO")

함수 호출 모드

Gemini API를 사용하면 모델이 제공된 도구 (함수 선언)를 사용하는 방식을 제어할 수 있습니다. 구체적으로 function_calling_config 내에서 모드를 설정할 수 있습니다.

  • AUTO (Default): 모델이 프롬프트와 컨텍스트를 기반으로 자연어 응답을 생성할지 또는 함수 호출을 제안할지 결정합니다. 이 모드는 가장 유연하며 대부분의 시나리오에 권장됩니다.
  • ANY: 모델이 항상 함수 호출을 예측하고 함수 스키마 준수를 보장하도록 제한됩니다. allowed_function_names가 지정되지 않으면 모델은 제공된 함수 선언 중에서 선택할 수 있습니다. allowed_function_names가 목록으로 제공되면 모델은 해당 목록의 함수 중에서만 선택할 수 있습니다. 모든 프롬프트에 대한 응답으로 함수 호출이 필요한 경우에 이 모드를 사용합니다 (해당하는 경우).
  • NONE: 모델이 함수를 호출하는 것이 금지됩니다. 이는 함수 선언 없이 요청을 전송하는 것과 같습니다. 이를 사용하여 도구 정의가 삭제되지 않도록 함수 호출을 일시적으로 사용 중지할 수 있습니다.

from google.genai import types

# Configure function calling mode
tool_config = types.ToolConfig(
    function_calling_config=types.FunctionCallingConfig(
        mode="ANY", allowed_function_names=["get_current_temperature"]
    )
)

# Create the generation config
config = types.GenerateContentConfig(
    temperature=0,
    tools=[tools],  # not defined here.
    tool_config=tool_config,
)
import { FunctionCallingConfigMode } from '@google/genai';

// Configure function calling mode
const toolConfig = {
  functionCallingConfig: {
    mode: FunctionCallingConfigMode.ANY,
    allowedFunctionNames: ['get_current_temperature']
  }
};

// Create the generation config
const config = {
  temperature: 0,
  tools: tools, // not defined here.
  toolConfig: toolConfig,
};

자동 함수 호출 (Python만 해당)

Python SDK를 사용하면 Python 함수를 도구로 직접 제공할 수 있습니다. SDK는 Python 함수를 선언으로 자동 변환하고 함수 호출 실행 및 응답 주기를 자동으로 처리합니다. 그러면 Python SDK가 자동으로 다음 작업을 실행합니다.

  1. 모델에서 함수 호출 응답을 감지합니다.
  2. 코드에서 해당 Python 함수를 호출합니다.
  3. 함수 응답을 모델에 다시 보냅니다.
  4. 모델의 최종 텍스트 응답을 반환합니다.

이를 사용하려면 유형 힌트와 문서 문자열로 함수를 정의한 다음 JSON 선언이 아닌 함수 자체를 도구로 전달합니다.

Python
from google import genai
from google.genai import types

# Define the function with type hints and docstring
def get_current_temperature(location: str) -> dict:
    """Gets the current temperature for a given location.

    Args:
        location: The city and state, e.g. San Francisco, CA

    Returns:
        A dictionary containing the temperature and unit.
    """
    # ... (implementation) ...
    return {"temperature": 25, "unit": "Celsius"}

# Configure the client and model
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))  # Replace with your actual API key setup
config = types.GenerateContentConfig(
    tools=[get_current_temperature]
)  # Pass the function itself

# Make the request
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="What's the temperature in London?",
    config=config,
)

print(response.text)  # The SDK handles the function call and returns the final text

다음을 사용하여 자동 함수 호출을 사용 중지할 수 있습니다.

Python
# To disable automatic function calling:
config = types.GenerateContentConfig(
    tools=[get_current_temperature],
    automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)

자동 함수 스키마 선언

Python 함수에서 자동 스키마를 추출하는 것이 모든 경우에 작동하는 것은 아닙니다. 예를 들어 중첩된 사전 객체의 필드를 설명하는 경우는 처리하지 않습니다. 이 API는 다음 유형을 설명할 수 있습니다.

Python
AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType])

유추된 스키마가 어떻게 표시되는지 확인하려면 from_callable를 사용하여 변환하면 됩니다.

Python
def multiply(a: float, b: float):
    """Returns a * b."""
    return a * b

fn_decl = types.FunctionDeclaration.from_callable(callable=multiply, client=client)

# to_json_dict() provides a clean JSON representation.
print(fn_decl.to_json_dict())

여러 도구 사용: 네이티브 도구와 함수 호출 결합

Gemini 2.0을 사용하면 네이티브 도구와 함수 호출을 동시에 결합하는 여러 도구를 사용 설정할 수 있습니다. 다음은 Live API를 사용하는 요청에서 Google 검색을 통한 기반 구축코드 실행이라는 두 가지 도구를 사용 설정하는 예입니다.

# Multiple tasks example - combining lights, code execution, and search
prompt = """
  Hey, I need you to do three things for me.

    1.  Turn on the lights.
    2.  Then compute the largest prime palindrome under 100000.
    3.  Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.

  Thanks!
  """

tools = [
    {'google_search': {}},
    {'code_execution': {}},
    {'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]} # not defined here.
]

# Execute the prompt with specified tools in audio modality
await run(prompt, tools=tools, modality="AUDIO")
// Multiple tasks example - combining lights, code execution, and search
const prompt = `
  Hey, I need you to do three things for me.

    1.  Turn on the lights.
    2.  Then compute the largest prime palindrome under 100000.
    3.  Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.

  Thanks!
`;

const tools = [
  { googleSearch: {} },
  { codeExecution: {} },
  { functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] } // not defined here.
];

// Execute the prompt with specified tools in audio modality
await run(prompt, {tools: tools, modality: "AUDIO"});

Python 개발자는 실시간 API 도구 사용 노트북에서 이를 사용해 볼 수 있습니다.

지원되는 모델

실험용 모델은 포함되지 않습니다. 모델 개요 페이지에서 기능을 확인할 수 있습니다.

모델 함수 호출 병렬 함수 호출 구성 함수 호출
(실시간 API만 해당)
Gemini 2.0 Flash ✔️ ✔️ ✔️
Gemini 2.0 Flash-Lite X X X
Gemini 1.5 Flash ✔️ ✔️ ✔️
Gemini 1.5 Pro ✔️ ✔️ ✔️

권장사항

  • 함수 및 매개변수 설명: 설명을 매우 명확하고 구체적으로 작성합니다. 모델은 이를 사용하여 올바른 함수를 선택하고 적절한 인수를 제공합니다.
  • 이름 지정: 설명적인 함수 이름을 사용합니다 (공백, 마침표, 대시 없음).
  • 강력한 유형 지정: 매개변수에 특정 유형 (정수, 문자열, enum)을 사용하여 오류를 줄입니다. 매개변수에 유효한 값 집합이 제한된 경우 enum을 사용하세요.
  • 프롬프트 엔지니어링:
    • 컨텍스트 제공: 모델에 역할을 알려줍니다 (예: '유용한 날씨 어시스턴트 역할을 해.')
    • 안내 제공: 함수 사용 방법과 시기를 지정합니다 (예: '날짜를 추측하지 마세요. 예측에는 항상 미래 날짜를 사용하세요.').
    • 명확히 설명하도록 유도: 필요한 경우 명확히 설명하기 위한 질문을 하도록 모델에 지시합니다.
  • 온도: 낮은 온도 (예: 0)을 사용하면 더 결정적이고 안정적인 함수 호출을 실행할 수 있습니다.
  • 유효성 검사: 함수 호출에 중대한 결과가 발생하는 경우 (예: 주문) 이를 실행하기 전에 사용자와 함께 호출 유효성을 검사합니다.
  • 오류 처리: 함수에 강력한 오류 처리를 구현하여 예상치 못한 입력이나 API 실패를 적절하게 처리합니다. 모델이 사용자에게 유용한 응답을 생성하는 데 사용할 수 있는 유용한 오류 메시지를 반환합니다.
  • 보안: 외부 API를 호출할 때 보안에 유의하세요. 적절한 인증 및 승인 메커니즘을 사용합니다. 함수 호출에서 민감한 정보를 노출하지 마세요.
  • 토큰 제한: 함수 설명과 매개변수는 입력 토큰 제한에 포함됩니다. 토큰 한도에 도달한 경우 함수 수 또는 설명 길이를 제한하고 복잡한 태스크를 더 작고 구체적인 함수 세트로 분할하는 것이 좋습니다.

참고사항 및 제한사항

  • OpenAPI 스키마의 하위 집합만 지원됩니다.
  • Python에서 지원되는 매개변수 유형은 제한적입니다.
  • 자동 함수 호출은 Python SDK 전용 기능입니다.