Gemini Live API 권장사항

Gemini Live API에서 더 나은 결과를 얻으려면 다음 권장사항에 집중하세요.

명확한 시스템 요청 사항 설계

Gemini Live API를 최대한 활용하려면 에이전트 페르소나, 대화 규칙, 가드레일을 이 순서대로 정의하는 명확하게 정의된 시스템 요청 사항 집합(SIs)이 있어야 합니다.

최상의 결과를 얻으려면 각 에이전트를 별도의 SI로 분리하세요.

  1. 에이전트 페르소나 지정: 에이전트의 이름, 역할, 선호하는 특징에 관한 세부정보를 제공합니다. 억양을 지정하려면 선호하는 출력 언어(예: 영어 화자의 경우 영국 억양)도 지정해야 합니다.

  2. 대화 규칙 지정: 모델이 따라야 하는 순서대로 이러한 규칙을 입력합니다. 대화의 일회성 요소와 대화형 루프를 구분합니다. 예를 들면 다음과 같습니다.

    • 일회성 요소: 고객의 세부정보(예: 이름, 위치, 포인트 카드 번호)를 한 번 수집합니다.
    • 대화형 루프: 사용자는 추천, 가격, 반품, 배송에 대해 논의할 수 있으며 주제를 전환하고 싶어 할 수 있습니다. 사용자가 원하는 한 이 대화형 루프에 참여해도 된다고 모델에게 알립니다.
  3. 흐름 내에서 도구 호출을 별도의 문장으로 지정: 예를 들어 고객 세부정보를 수집하는 일회성 단계에서 get_user_info 함수를 호출해야 하는 경우 다음과 같이 말할 수 있습니다. 첫 번째 단계는 사용자 정보를 수집하는 것입니다. 먼저 사용자에게 이름, 위치, 포인트 카드 번호를 제공해 달라고 요청합니다. 그런 다음 이러한 세부정보를 사용하여 get_user_info를 호출합니다.

  4. 필요한 가드레일 추가: 모델이 수행하지 않기를 바라는 일반적인 대화형 가드레일을 제공합니다. x 가 발생하면 모델이 y 를 수행하기를 바라는 구체적인 예시를 제공해도 됩니다. 여전히 원하는 수준의 정밀도를 얻지 못한다면 분명하게라는 단어를 사용하여 모델이 정확하도록 안내합니다.

도구 정확하게 정의

Gemini Live API에서 도구를 사용할 때는 도구 정의를 구체적으로 작성하세요. 어떤 조건에서 도구 호출이 실행되어야 하는지 Gemini에게 명확하게 전달해야 합니다. 자세한 내용은 도구 정의를 참조하세요.

효과적인 프롬프트 작성

  • 명확한 프롬프트 사용: 프롬프트에서 모델이 해야 하는 일과 하지 말아야 하는 일의 예시를 제공하고, 한 번에 페르소나 또는 역할당 하나의 프롬프트로 제한합니다. 길고 여러 페이지로 구성된 프롬프트 대신 프롬프트 체이닝을 사용하는 것이 좋습니다. 모델은 단일 함수 호출이 있는 태스크에서 가장 우수한 성능을 발휘합니다.

    # Prompt chaining example.
    chainable_long_prompt = """
    You need to perform a sequence of tasks.
    First, you should do task1; after that, task2; later, task3; and finally, task4.
    """
    
    # New initial prompt
    """
    You need to perform a sequence of tasks. Once you finish the current task, call
    the `get_next_prompt` function to get instructions for the next task.
    """
    
    PROMPT_LIST = ["Now, do task1", "Now, do task2", "Now, do task3", "Now, do task 4", "all tasks done"]
    def get_next_prompt():
      # Provide this function as a tool to the model. 
      for prompt in PROMPT_LIST:
        yield prompt
    
    # Catch and execute tool call `get_next_prompt` and send the new prompt back to the model. 
    
  • 시작 명령어와 정보 제공: Gemini Live API는 응답하기 전에 사용자 입력을 기다립니다. Gemini Live API가 대화를 시작하도록 하려면 사용자에게 인사하거나 대화를 시작하라는 프롬프트를 포함합니다. Gemini Live API가 인사말을 맞춤설정할 수 있도록 사용자에 관한 정보를 포함합니다.

세션 재개

  1. 투명한 세션 재개 사용: SessionResumptionConfig(transparent=True)에서 genai.types.LiveConnectConfig로 연결을 구성합니다. 이렇게 하면 클라이언트가 세션 재개를 원활하게 처리하여 다시 연결 시 사용되지 않은 메시지 재생과 같은 기능을 사용할 수 있음을 알립니다.
from google.genai import types

session_handle: str | None = None

live_config = types.LiveConnectConfig(
  session_resumption=types.SessionResumptionConfig(
      handle=session_handle,
      transparent=True,
  ),
)
  1. 세션 핸들 유지관리 및 업데이트: 서버에서 session_resumption_update 메시지를 수신 대기합니다. resumable이 true이고 new_handle이 제공되면 이 핸들을 저장합니다. 이 핸들은 연결이 끊어질 경우 동일한 세션 상태에 다시 연결하는 데 필수적입니다.

  2. 전송된 메시지 버퍼링 및 확인된 메시지 삭제: 연결이 끊어지는 동안 클라이언트 메시지가 손실되지 않도록 Gemini Live API로 전송된 메시지의 버퍼를 유지관리합니다. 투명한 세션 재개가 사용 설정되면 session_resumption_update 메시지에 서버에서 처리한 마지막 메시지를 나타내는 last_consumed_client_message_index가 포함됩니다. 이 색인을 사용하여 확인된 메시지를 버퍼에서 삭제합니다. 메시지를 올바르게 추적하려면 사용자 관리 색인이 1부터 시작해야 합니다. 색인 0은 the session is not resumable을 나타내기 때문입니다. 모델로 전송되는 각 후속 메시지는 이 색인을 1씩 증가시켜야 합니다. 각 세션 재개 시 새 연결을 사용하여 전송된 초기 메시지의 색인이 1로 재설정되는지 확인합니다.

  3. 연결 끊김을 원활하게 처리:

    • GoAway 신호: 서버는 예상되는 연결 끊김 (예: 시간 제한) 전에 go_away 메시지를 전송합니다. 관리자는 이 메시지를 수신 대기한 후 최신 핸들을 사용하여 사전에 다시 연결해야 합니다.
    • API 오류: 네트워크 문제로 인해 genai_errors.APIError (예: WebSocket 오류의 경우 코드 1000 또는 1006)가 발생할 수 있습니다. 관리자는 전송 및 수신 루프 모두에서 이러한 오류를 포착하고 세션 업데이트 또는 다시 연결 프로세스를 트리거해야 합니다.
  4. 메시지 재생으로 다시 연결 구현: 연결이 끊어지면 최신 세션 핸들로 client.aio.live.connect를 사용하여 새 세션을 만듭니다. 새 연결을 설정한 후 연결이 끊어지기 전에 서버에서 확인하지 않은 버퍼의 메시지를 다시 전송합니다. 버퍼에서 전송된 첫 번째 메시지는 새 연결의 색인 1로 표시되어야 합니다.

컨텍스트 윈도우 압축 사용 설정

기본 오디오 토큰이 빠르게 누적되므로 (오디오 초당 약 25개 토큰) 긴 세션의 경우 ContextWindowCompressionConfig를 사용하여 세션의 컨텍스트 윈도우를 구성합니다 .

경고: 컨텍스트 압축으로 인해 대화 기록이 손실됩니다.

from google.genai import types

live_config = types.LiveConnectConfig(
  context_window_compression=types.ContextWindowCompressionConfig(
    trigger_tokens=100_000, # For better clarity
    sliding_window=types.SlidingWindow(target_tokens=4_000),
  ),
)

토큰 사용량 계산

Gemini Live API 청구 구조는 가격 책정 페이지에 자세히 설명되어 있습니다. 각 턴 동안 API는 대화 기록과 사용자가 제공한 시스템 요청 사항을 모두 포함하는 모든 컨텍스트 토큰에 대해 청구합니다. 개발자는 모델의 응답에 제공된 usage_metadata 필드를 추출하여 이러한 요금을 모니터링하고 계산할 수 있습니다.

# Example code to get token usage
from google.genai import live

session: live.AsyncSession
async for response in session.receive():
  if response.usage_metadata is not None:
    print("Token usage:", response.usage_metadata)

음성 활동 감지 (VAD)

기본적으로 Gemini Live API는 Gemini에서 제공하는 VAD를 사용합니다.

Gemini Live API VAD를 사용하는 동안 모델이 VAD 이벤트를 명시적으로 반환하도록 구성할 수 있습니다. 구성에서 explicit_vad_signal을 사용 설정하면 모델의 응답에서 이러한 이벤트를 직접 모니터링하고 캡처할 수 있습니다.

from google.genai import types
from google.genai import live

live_config = types.LiveConnectConfig(
  explicit_vad_signal=True
)

session: live.AsyncSession
# In receive loop
async for response in session.receive():
  if response.voice_activity is not None:
    print("Get VAD event", response.voice_activity)

맞춤 활동 감지 시스템을 사용하려면 기본 음성 활동 감지 (VAD) 를 비활성화하고 사용자 턴을 Gemini 모델에 수동으로 알리세요. 이는 ActivityStart 또는 ActivityEnd 이벤트를 전송하여 상호작용 경계를 정의함으로써 이루어집니다.

from google.genai import live
from google.genai import types

# Disable VAD in config
live_config = types.LiveConnectConfig(
  realtime_input_config=types.RealtimeInputConfig(
    automatic_activity_detection=types.AutomaticActivityDetection(
        disabled=True
    ),
  ),
)

session: live.AsyncSession
await session.send_realtime_input( # Send activity start
    activity_start=types.ActivityStart()
)
for audio_bytes in bytes_to_send_queue: # Send user data
    await session.send_realtime_input(
        audio=types.Blob(
            data=audio_bytes,
            mime_type=f"audio/pcm;rate=16000",
        )
    )
await session.send_realtime_input(activity_end=types.ActivityEnd()) # Send activity end

오디오 언어 코드 설정

일관성을 유지하려면 구성에서 언어 및 음성 코드를 명시적으로 설정하는 것이 좋습니다. 이 정의가 없으면 Gemini가 제공된 컨텍스트에 따라 대화 언어를 변경할 수 있습니다.

from google.genai import types

config = types.LiveConnectConfig(
  speech_config=types.SpeechConfig(
    language_code="en-US",
  ),
)

시스템 요청 사항에서 다음도 언급하세요.

RESPOND IN {OUTPUT_LANGUAGE}. YOU MUST RESPOND UNMISTAKABLY IN {OUTPUT_LANGUAGE}.

gemini-live-2.5-flash-native-audio와 같은 네이티브 오디오 모델의 경우 세션 구성에서 언어 힌트를 제공하여 다국어 자동 음성 인식(ASR)의 스크립트 작성 품질을 개선할 수 있습니다. 자세한 내용은 세션의 오디오 스크립트 작성 사용 설정을 참조하세요.

스크립트 작성 언어 코드 설정

BCP-47 언어 코드 형식을 사용하여 스크립트 작성 정확도를 높이려면 스크립트 작성 언어 코드를 지정하세요.

참고: 스크립트 작성을 사용 설정하면 토큰이 더 많이 도입됩니다.

from google.genai import types

config = types.LiveConnectConfig(
  input_audio_transcription=types.AudioTranscriptionConfig(
      language_codes=['en-US']  # This supports multiple language codes.
  ),
  output_audio_transcription=types.AudioTranscriptionConfig(
      language_codes=['en-US']
  ),
)

클라이언트 버퍼링

전송하기 전에 입력 오디오를 크게 (예: 1초) 버퍼링하지 마세요. 지연 시간을 최소화하기 위해 작은 청크 (20ms~40ms)를 전송합니다.

리샘플링

클라이언트 애플리케이션이 전송 전에 마이크 입력 (일반적으로 44.1kHz 또는 48kHz)을 16kHz로 리샘플링하는지 확인합니다.

이 예시에서는 권장사항과 시스템 요청 사항 설계 가이드라인을 결합하여 모델이 커리어 코치로서의 역할을 수행하도록 안내합니다.

**Persona:**
You are Laura, a career coach from Brooklyn, NY. You specialize in providing
data-driven advice to give your clients a fresh perspective on the career
questions they're navigating. Your special sauce is providing quantitative,
data-driven insights to help clients think about their issues in a different
way. You leverage statistics, research, and psychology as much as possible.
You only speak to your clients in English, no matter what language they speak
to you in.

**Conversational Rules:**

1. **Introduce yourself:** Warmly greet the client.

2. **Intake:** Ask for your client's full name, date of birth, and state they're
calling in from. Call `create_client_profile` to create a new patient profile.

3. **Discuss the client's issue:** Get a sense of what the client wants to
cover in the session. DO NOT repeat what the client is saying back to them in
your response. Don't ask more than a few questions here.

4. **Reframe the client's issue with real data:** NO PLATITUDES. Start providing
data-driven insights for the client, but embed these as general facts within
conversation. This is what they're coming to you for: your unique thinking on
the subjects that are stressing them out. Show them a new way of thinking about
something. Let this step go on for as long as the client wants. As part of this,
if the client mentions wanting to take any actions, update
`add_action_items_to_profile` to remind the client later.

5. **Next appointment:** Call `get_next_appointment` to see if another
appointment has already been scheduled for the client. If so, then share the
date and time with the client and confirm if they'll be able to attend. If
there is no appointment, then call `get_available_appointments` to see openings.
Share the list of openings with the client and ask what they would prefer. Save
their preference with `schedule_appointment`. If the client prefers to schedule
offline, then let them know that's perfectly fine and to use the patient portal.

**General Guidelines:** You're meant to be a witty, snappy conversational
partner. Keep your responses short and progressively disclose more information
if the client requests it. Don't repeat what the client says back to them.
Each of your responses should add to the conversation, not just recap what
the client said. Be relatable by bringing in your own background 
growing up professionally in Brooklyn, NY. If a client tries to get you off
track, gently bring them back to the workflow articulated above.

**Guardrails:** If the client is being hard on themselves, never encourage that.
Remember that your ultimate goal is to create a supportive environment for your
clients to thrive.

도구 정의

이 JSON은 커리어 코치 예시에서 호출되는 관련 함수를 정의합니다. 함수를 정의할 때 최상의 결과를 얻으려면 이름, 설명, 파라미터, 호출 조건을 포함하세요.

[
 {
   "name": "create_client_profile",
   "description": "Creates a new client profile with their personal details. Returns a unique client ID. \n**Invocation Condition:** Invoke this tool *only after* the client has provided their full name, date of birth, AND state. This should only be called once at the beginning of the 'Intake' step.",
   "parameters": {
     "type": "object",
     "properties": {
       "full_name": {
         "type": "string",
         "description": "The client's full name."
       },
       "date_of_birth": {
         "type": "string",
         "description": "The client's date of birth in YYYY-MM-DD format."
       },
       "state": {
         "type": "string",
         "description": "The 2-letter postal abbreviation for the client's state (e.g., 'NY', 'CA')."
       }
     },
     "required": ["full_name", "date_of_birth", "state"]
   }
 },
 {
   "name": "add_action_items_to_profile",
   "description": "Adds a list of actionable next steps to a client's profile using their client ID. \n**Invocation Condition:** Invoke this tool *only after* a list of actionable next steps has been discussed and agreed upon with the client during the 'Actions' step. Requires the `client_id` obtained from the start of the session.",
   "parameters": {
     "type": "object",
     "properties": {
       "client_id": {
         "type": "string",
         "description": "The unique ID of the client, obtained from create_client_profile."
       },
       "action_items": {
         "type": "array",
         "items": {
           "type": "string"
         },
         "description": "A list of action items for the client (e.g., ['Update resume', 'Research three companies'])."
       }
     },
     "required": ["client_id", "action_items"]
   }
 },
 {
   "name": "get_next_appointment",
   "description": "Checks if a client has a future appointment already scheduled using their client ID. Returns the appointment details or null. \n**Invocation Condition:** Invoke this tool at the *start* of the 'Next Appointment' workflow step, immediately after the 'Actions' step is complete. This is used to check if an appointment *already exists*.",
   "parameters": {
     "type": "object",
     "properties": {
       "client_id": {
         "type": "string",
         "description": "The unique ID of the client."
       }
     },
     "required": ["client_id"]
   }
 },
 {
   "name": "get_available_appointments",
   "description": "Fetches a list of the next available appointment slots. \n**Invocation Condition:** Invoke this tool *only if* the `get_next_appointment` tool was called and it returned `null` (or an empty response), indicating no future appointment is scheduled.",
   "parameters": {
     "type": "object",
     "properties": {}
   }
 },
 {
   "name": "schedule_appointment",
   "description": "Books a new appointment for a client at a specific date and time. \n**Invocation Condition:** Invoke this tool *only after* `get_available_appointments` has been called, a list of openings has been presented to the client, and the client has *explicitly confirmed* which specific date and time they want to book.",
   "parameters": {
     "type": "object",
     "properties": {
       "client_id": {
         "type": "string",
         "description": "The unique ID of the client."
       },
       "appointment_datetime": {
         "type": "string",
         "description": "The chosen appointment slot in ISO 8601 format (e.g., '2025-10-30T14:30:00')."
       }
     },
     "required": ["client_id", "appointment_datetime"]
   }
 }
]

추가 정보

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