Gemini 기능 구성

이 문서에서는 Gemini Live API 사용 시 Gemini 모델의 다양한 기능을 구성하는 방법을 보여줍니다. 함수 호출 및 그라운딩과 같은 도구 사용과 공감형 대화 및 능동적 오디오와 같은 라이브 오디오 기능을 구성할 수 있습니다.

도구 사용 구성

다음을 포함하여 다양한 버전의 Gemini Live API 지원 모델과 호환되는 여러 도구가 있습니다.

반환된 응답에서 특정 도구를 사용 설정하려면 모델을 초기화할 때 tools 목록에 도구의 이름을 포함합니다. 다음 섹션에서는 코드에서 각 기본 제공 도구를 사용하는 방법을 보여주는 예시를 제공합니다.

중요: Gemini API는 동일한 설정 요청에서 검색 도구(googleSearch 등)와 검색 이외의 도구 (함수 호출 또는 Gemini Enterprise Agent Platform RAG 엔진 retrieval 도구 등)를 결합하는 것을 지원하지 않습니다. 여러 도구는 모두 검색 도구인 경우에만 지원됩니다.

함수 호출

모델이 사용자가 관리하는 외부 시스템 또는 API와 상호작용하도록 하려면 함수 호출을 사용합니다. 데이터베이스 확인, 이메일 전송, 커스텀 API와의 상호작용과 같은 작업에 사용합니다. Gemini Live API는 비동기 함수 호출을 지원합니다. 자세한 내용은 Gemini Live API를 사용한 비동기 함수 호출을 참고하세요.

모델이 함수 호출을 생성하고 애플리케이션이 코드를 실행하여 결과를 모델에 다시 전송합니다.

모든 함수는 LiveConnectConfig 메시지의 일부로 도구 정의를 전송하여 세션 시작 시 선언되어야 합니다.

함수 호출을 사용 설정하려면 설정 메시지의 tools 목록에 function_declarations를 포함하세요.

Python

import asyncio

from google import genai
from google.genai.types import (
    Content,
    LiveConnectConfig,
    Part,
)

# Initialize the client.
client = genai.Client(
    enterprise=True,
    project="GOOGLE_CLOUD_PROJECT",  # Replace with your project ID
    location="LOCATION",  # Replace with your location
)

MODEL_ID = "gemini-3.8-live"


def get_current_weather(location: str) -> str:
    """Example method. Returns the current weather.

    Args:
        location: The city and state, e.g. San Francisco, CA
    """
    weather_map: dict[str, str] = {
        "Boston, MA": "snowing",
        "San Francisco, CA": "foggy",
        "Seattle, WA": "raining",
        "Austin, TX": "hot",
        "Chicago, IL": "windy",
    }
    return weather_map.get(location, "unknown")


async def main():
    config = LiveConnectConfig(
        response_modalities=["AUDIO"],
        tools=[get_current_weather],
    )

    async with client.aio.live.connect(
        model=MODEL_ID,
        config=config,
    ) as session:
        text_input = "Get the current weather in Boston."
        print(f"Input: {text_input}")

        await session.send_realtime_input(text=text_input)
        )

        async for message in session.receive():
            if message.tool_call:
                function_responses = []
                for function_call in message.tool_call.function_calls:
                    print(f"FunctionCall > {function_call}")
                    # Execute the tool and send the response back to the model.
                    result = get_current_weather(**function_call.args)
                    function_responses.append(
                        {
                            "name": function_call.name,
                            "response": {"result": result},
                            "id": function_call.id,
                        }
                    )
                if function_responses:
                    await session.send_tool_response(function_responses=function_responses)


if __name__ == "__main__":
    asyncio.run(main())
  

시스템 안내에서 함수 호출을 사용하는 예는 권장사항 예를 참고하세요.

모델 컨텍스트 프로토콜 (MCP) 도구

Google 생성형 AI SDK는 Gemini Live API 세션에서 모델 컨텍스트 프로토콜(MCP) 도구 호출을 자동으로 실행하지 않습니다. Gemini Live API 세션에서 MCP 도구를 사용하려면 다음 방법 중 하나를 사용하면 됩니다.

  • MCP 도구 호출 직접 관리: Google 생성형 AI SDK 를 직접 사용하는 경우 애플리케이션이 MCP 클라이언트 세션을 관리하고, 모델에서 요청할 때 도구 호출을 실행하고, send_tool_response를 사용하여 결과를 반환해야 합니다.
  • **에이전트 개발 키트 (ADK) 사용**: Gemini Live API에 기본 제공 MCP 통합을 제공하는 ADK의 McpToolset 클래스를 사용합니다. ADK는 MCP 서버에서 도구를 자동으로 검색하고, 스키마를 함수 선언으로 변환하고, 양방향 스트림 중에 MCP 도구 호출을 실행하고, 도구 응답을 모델에 다시 전송합니다.

ADK로 MCP 도구 사용

다음 단계에 따라 ADK를 사용하여 MCP 도구를 Gemini Live API에 연결할 수 있습니다.

  1. mcp 추가 기능으로 google-adk 패키지를 설치합니다.

    pip install "google-adk[mcp]"
    
  2. StreamableHTTPConnectionParams를 사용하여 McpToolset을 MCP 서비스에 연결하고 runner.run_live()를 사용하여 이벤트를 스트리밍하는 live_mcp_example.py라는 스크립트를 만듭니다.

    다음을 바꿉니다.

    • PROJECT_ID: Cloud de Confiance by S3NS 프로젝트 ID입니다.
    • MCP_SERVER_URL: 스트리밍 가능한 HTTP MCP 서버 URL (예: http://127.0.0.1:8765/mcp)입니다.
    import asyncio
    import contextlib
    import os
    
    from google.adk.agents import Agent, LiveRequestQueue, RunConfig
    from google.adk.agents.run_config import StreamingMode
    from google.adk.runners import InMemoryRunner
    from google.adk.tools.mcp_tool import McpToolset, StreamableHTTPConnectionParams
    from google.genai import types
    
    os.environ.setdefault("GOOGLE_GENAI_USE_ENTERPRISE", "TRUE")
    os.environ.setdefault("GOOGLE_CLOUD_PROJECT", "PROJECT_ID")
    os.environ.setdefault("GOOGLE_CLOUD_LOCATION", "us-central1")
    
    async def main() -> None:
      # 1. Connect to the Streamable HTTP MCP service
      mcp_toolset = McpToolset(
          connection_params=StreamableHTTPConnectionParams(
              url="MCP_SERVER_URL",
          )
      )
    
      # 2. Create the ADK Agent with a Gemini Live model and the MCP toolset
      agent = Agent(
          name="mcp_live_agent",
          model="gemini-3.8-live",
          instruction="You are a helpful assistant. Use the provided MCP tools when needed.",
          tools=[mcp_toolset],
      )
    
      runner = InMemoryRunner(agent=agent, app_name="mcp_live_demo")
      session = await runner.session_service.create_session(
          app_name="mcp_live_demo",
          user_id="user_1",
      )
    
      # 3. Configure bidirectional streaming and send a prompt
      live_request_queue = LiveRequestQueue()
      run_config = RunConfig(
          streaming_mode=StreamingMode.BIDI,
          response_modalities=[types.Modality.AUDIO],
          output_audio_transcription=types.AudioTranscriptionConfig(),
      )
    
      live_request_queue.send_content(
          types.Content(
              role="user",
              parts=[types.Part.from_text(text="What is the weather in Paris?")],
          )
      )
    
      # 4. Stream Live events (ADK automatically executes MCP tools)
      awaiting_post_tool_response = False
      saw_function_response = False
      has_model_output = False
    
      try:
        async with contextlib.aclosing(
            runner.run_live(
                user_id="user_1",
                session_id=session.id,
                live_request_queue=live_request_queue,
                run_config=run_config,
            )
        ) as live_events:
          async for event in live_events:
            for call in event.get_function_calls():
              print(f"[MCP Tool Call] {call.name}({call.args})")
              awaiting_post_tool_response = True
              saw_function_response = False
              has_model_output = False
    
            for resp in event.get_function_responses():
              print(f"[MCP Tool Response] {resp.name} -> {resp.response}")
              saw_function_response = True
    
            if event.output_transcription and event.output_transcription.text:
              if not awaiting_post_tool_response or saw_function_response:
                has_model_output = True
                awaiting_post_tool_response = False
              if event.output_transcription.finished:
                print(f"[Transcript] {event.output_transcription.text}")
    
            # Wait for the final response turn after tool execution completes
            if event.turn_complete:
              if awaiting_post_tool_response or not has_model_output:
                continue
              live_request_queue.close()
              break
      finally:
        await mcp_toolset.close()
        await runner.close()
    
    if __name__ == "__main__":
      asyncio.run(main())
    

모델이 검증 가능한 정보 소스에 고정하여 더 정확하고 사실에 기반한 대답을 제공하도록 하려면 Google 검색을 사용한 그라운딩을 사용합니다. 웹 검색과 같은 작업에 사용합니다.

함수 호출과 달리 서버 측 통합은 정보 검색을 자동으로 처리합니다.

Google 검색을 사용한 그라운딩을 사용 설정하려면 설정 메시지의 tools 목록에 google_search를 포함하세요.

Python

import asyncio

from google import genai
from google.genai.types import (
    Content,
    LiveConnectConfig,
    Part,
)

# Initialize the client.
client = genai.Client(
    enterprise=True,
    project="GOOGLE_CLOUD_PROJECT",  # Replace with your project ID
    location="LOCATION",  # Replace with your location
)

MODEL_ID = "gemini-3.8-live"


async def main():
    config = LiveConnectConfig(
        response_modalities=["AUDIO"],
        tools=[{"google_search": {}}],
    )

    async with client.aio.live.connect(
        model=MODEL_ID,
        config=config,
    ) as session:
        text_input = "What is the current weather in Toronto, Canada?"
        print(f"Input: {text_input}")

        await session.send_realtime_input(text=text_input)

        async for message in session.receive():
            # Consume the messages from the model.
            # In native audio, the model response is in audio format.
            pass


if __name__ == "__main__":
    asyncio.run(main())
  

공감형 대화 구성

공감형 대화 구성은 gemini-live-2.5-flash-native-audio에만 필요합니다. 이 섹션은 gemini-3.8-live에는 적용되지 않습니다.

공감형 대화가 사용 설정되면 모델은 사용자의 어조와 감정 표현을 기반으로 이해하고 대답하려고 시도합니다.

공감형 대화를 사용 설정하려면 설정 메시지에서 enable_affective_dialog를 true로 설정하세요.

Python

config = LiveConnectConfig(
    response_modalities=["AUDIO"],
    enable_affective_dialog=True,
)
  

능동적 오디오 구성

능동적 오디오 구성은 gemini-live-2.5-flash-native-audio에만 필요합니다. 능동적 오디오는 gemini-3.8-live에 포함되어 있습니다.

능동적 오디오를 사용하면 모델이 대답하는 시점을 제어할 수 있습니다. 예를 들어 프롬프트가 표시되거나 특정 주제가 논의될 때만 대답하도록 Gemini에 요청할 수 있습니다. 능동적 오디오의 동영상 데모를 보려면 Gemini LiveAPI 네이티브 오디오 미리보기를 참조하세요.

능동적 오디오를 사용 설정하려면 설정 메시지에서 proactivity 필드를 구성하고 proactive_audio를 true로 설정합니다.

Python

config = LiveConnectConfig(
    response_modalities=["AUDIO"],
    proactivity=ProactivityConfig(proactive_audio=True),
)
  

대화 예시

다음은 요리에 관한 Gemini와의 대화 예시입니다.

Prompt: "You are an AI assistant in Italian cooking; only chime in when the topic is about Italian cooking."

Speaker A: "I really love cooking!" (No response from Gemini.)

Speaker B: "Oh yes, me too! My favorite is French cuisine." (No response from
Gemini.)

Speaker A: "I really like Italian food; do you know how to make a pizza?"

(Italian cooking topic triggers response from Gemini.)
Gemini Live API: "I'd be happy to help! Here's a recipe for a pizza."

일반 사용 사례

능동적 오디오를 사용할 때 Gemini는 다음과 같이 작동합니다.

  • 지연 시간을 최소화하여 대답: 사용자가 말을 마친 후 Gemini가 대답하므로 중단이 줄어들고 중단이 발생하더라도 Gemini가 맥락을 잃지 않습니다.
  • 중단 방지: 능동적 오디오는 Gemini가 배경 소음이나 외부 메시지로 인해 중단되지 않게 하고, 대화 중에 외부 메시지가 유입되어도 Gemini가 대답하지 않도록 지원합니다.
  • 중단 처리: Gemini의 대답 중에 중단해야 하는 경우, 사용자가 음 또는 어와 같은 추임새를 사용하는 것보다 능동적 오디오를 사용하면 Gemini가 적절하게 백채널링(즉, 적절한 중단 처리)하기가 더 용이해집니다.
  • 오디오 공동 청취: Gemini는 화자의 음성이 아닌 오디오 파일을 공동 청취한 후 대화 후반부에 해당 오디오 파일에 관한 질문에 답변할 수 있습니다.

결제

Gemini가 대화를 듣는 동안 입력 오디오 토큰에 요금이 청구됩니다.

출력 오디오 토큰의 경우 Gemini가 대답할 때만 요금이 청구됩니다. Gemini가 대답하지 않거나 무음 상태이면 출력 오디오 토큰에 요금이 청구되지 않습니다.

자세한 내용은 Agent Platform 가격 책정을 참고하세요.

다음 단계

Gemini Live API 사용에 관한 자세한 내용은 다음을 참조하세요.