Google GenAI SDK로 Gemini Live API 시작하기

Google GenAI SDK로 Gemini Live API 시작하기

Gemini Live API는 Gemini 모델과의 실시간 양방향 상호작용을 지원하며, 오디오·비디오·텍스트 입력과 네이티브 오디오 출력을 지원해요. 이 가이드는 서버에서 Google GenAI SDK로 API에 통합하는 방법을 설명해요.

출처: 원문

본문

개요

Gemini Live API는 실시간 통신에 WebSockets를 사용해요. google-genai SDK는 이러한 연결을 관리하는 고수준 비동기 인터페이스를 제공해요.

핵심 개념:

  • 세션(Session): 모델에 대한 지속 연결.
  • Config: 양식(오디오/텍스트), 음성, 시스템 지시 설정.
  • 실시간 입력: 오디오·비디오 프레임을 blob으로 전송.

Live API 연결하기

API 키로 Live API 세션을 시작해요.

import asyncio
from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

model = "gemini-3.8-live"
config = {"response_modalities": ["AUDIO"]}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        print("Session started")
        # Send content...

if __name__ == "__main__":
    asyncio.run(main())
import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: 'YOUR_API_KEY' });
const model = 'gemini-3.8-live';
const config = { responseModalities: [Modality.AUDIO] };

async function main() {

  const session = await ai.live.connect({
    model: model,
    callbacks: {
      onopen: function () {
        console.debug('Opened');
      },
      onmessage: function (message) {
        console.debug(message);
      },
      onerror: function (e) {
        console.debug('Error:', e.message);
      },
      onclose: function (e) {
        console.debug('Close:', e.reason);
      },
    },
    config: config,
  });

  console.debug("Session started");
  // Send content...

  session.close();
}

main();

텍스트 보내기

텍스트는 Python에서는 send_realtime_input, JavaScript에서는 sendRealtimeInput로 보낼 수 있어요.

await session.send_realtime_input(text="Hello, how are you?")
session.sendRealtimeInput({
  text: 'Hello, how are you?'
});

오디오 보내기

오디오는 raw PCM 데이터로 보내야 해요(raw 16-bit PCM 오디오, 16kHz, little-endian).

# Assuming 'chunk' is your raw PCM audio bytes
await session.send_realtime_input(
    audio=types.Blob(
        data=chunk,
        mime_type="audio/pcm;rate=16000"
    )
)
// Assuming 'chunk' is a Buffer of raw PCM audio
session.sendRealtimeInput({
  audio: {
    data: chunk.toString('base64'),
    mimeType: 'audio/pcm;rate=16000'
  }
});

클라이언트 기기(예: 브라우저)에서 오디오를 가져오는 예제는 GitHub의 end-to-end 예제를 참고하세요.

비디오 보내기

비디오 프레임은 특정 프레임 레이트(초당 최대 1프레임)로 개별 이미지(예: JPEG 또는 PNG)로 전송돼요.

# Assuming 'frame' is your JPEG-encoded image bytes
await session.send_realtime_input(
    video=types.Blob(
        data=frame,
        mime_type="image/jpeg"
    )
)
// Assuming 'frame' is a Buffer of JPEG-encoded image data
session.sendRealtimeInput({
  video: {
    data: frame.toString('base64'),
    mimeType: 'image/jpeg'
  }
});

클라이언트 기기(예: 브라우저)에서 비디오를 가져오는 예제는 GitHub의 end-to-end 예제를 참고하세요.

오디오 받기

모델의 오디오 응답은 데이터 청크로 수신돼요.

async for response in session.receive():
    if response.server_content and response.server_content.model_turn:
        for part in response.server_content.model_turn.parts:
            if part.inline_data:
                audio_data = part.inline_data.data
                # Process or play the audio data
// Inside the onmessage callback
const content = response.serverContent;
if (content?.modelTurn?.parts) {
  for (const part of content.modelTurn.parts) {
    if (part.inlineData) {
      const audioData = part.inlineData.data;
      // Process or play audioData (base64 encoded string)
    }
  }
}

GitHub의 예제 앱으로 서버에서 오디오 수신과 브라우저에서 재생 방법을 알아보세요.

텍스트 받기

사용자 입력과 모델 출력 둘 다의 전사(transcription)가 서버 콘텐츠에서 제공돼요.

async for response in session.receive():
    content = response.server_content
    if content:
        if content.input_transcription:
            print(f"User: {content.input_transcription.text}")
        if content.output_transcription:
            print(f"Gemini: {content.output_transcription.text}")
// Inside the onmessage callback
const content = response.serverContent;
if (content?.inputTranscription) {
  console.log('User:', content.inputTranscription.text);
}
if (content?.outputTranscription) {
  console.log('Gemini:', content.outputTranscription.text);
}

도구 호출 처리

API는 도구 호출(함수 호출)을 지원해요. 모델이 도구 호출을 요청하면 함수를 실행하고 응답을 다시 보내야 해요.

async for response in session.receive():
    if response.tool_call:
        function_responses = []
        for fc in response.tool_call.function_calls:
            # 1. Execute the function locally
            result = my_tool_function(**fc.args)

            # 2. Prepare the response
            function_responses.append(types.FunctionResponse(
                name=fc.name,
                id=fc.id,
                response={"result": result}
            ))

        # 3. Send the tool response back to the session
        await session.send_tool_response(function_responses=function_responses)
// Inside the onmessage callback
if (response.toolCall) {
  const functionResponses = [];
  for (const fc of response.toolCall.functionCalls) {
    const result = myToolFunction(fc.args);
    functionResponses.push({
      name: fc.name,
      id: fc.id,
      response: { result }
    });
  }
  session.sendToolResponse({ functionResponses });
}

다음 단계

  • 핵심 기능·구성(Voice Activity Detection과 네이티브 오디오 기능 포함)은 Live API Capabilities 가이드를 읽어보세요.
  • Live API를 도구·함수 호출과 통합하려면 Tool use 가이드를 읽어보세요.
  • 오래 실행되는 대화 관리는 Session management 가이드를 읽어보세요.
  • client-to-server 애플리케이션의 안전한 인증은 Ephemeral tokens 가이드를 읽어보세요.
  • 기본 WebSockets API에 대한 자세한 내용은 WebSockets API reference를 참고하세요.

더 알아보기 (Learn more)