Google 생성형 AI SDK를 사용하여 Gemini Live API 시작하기

이 튜토리얼에서는 Python용 Google 생성형 AI SDK를 사용하여 Gemini Live API에 연결하는 방법을 보여줍니다. 이 튜토리얼에서는 API 연결을 처리하는 강력한 Python 백엔드를 사용하여 실시간 멀티모달 애플리케이션을 빌드합니다.

시작하기 전에

다음 단계에 따라 환경 설정을 완료합니다.

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. Google Cloud CLI를 설치합니다.

  6. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  7. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  11. Google Cloud CLI를 설치합니다.

  12. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  13. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  14. Git를 설치합니다.
  15. Python 3을 설치합니다.

데모 앱 클론

데모 앱 저장소를 클론하고 해당 디렉터리로 이동합니다.

git clone https://github.com/GoogleCloudPlatform/generative-ai.git &&
cd generative-ai/gemini/multimodal-live-api/native-audio-websocket-demo-apps/plain-js-python-sdk-demo-app

프로젝트 구조

애플리케이션에는 다음 파일이 포함됩니다.

/
├── main.py                 # FastAPI server and WebSocket endpoint
├── gemini_live.py          # Gemini Live API wrapper using Gen AI SDK
├── requirements.txt        # Python dependencies
└── frontend/
    ├── index.html          # User Interface
    ├── main.js             # Application logic
    ├── gemini-client.js    # WebSocket client for backend communication
    ├── media-handler.js    # Audio/Video capture and playback
    └── pcm-processor.js    # AudioWorklet for PCM processing

환경 변수 구성

이 데모를 위해 구성해야 하는 유일한 환경 변수는 Google Cloud 프로젝트의 ID를 정의하는 변수입니다. 다음 명령어는 환경 변수 PROJECT_ID를 설정하는 .env 파일을 만듭니다. PROJECT_ID를 프로젝트의 Google Cloud 프로젝트 ID로 바꿉니다.

echo "PROJECT_ID=PROJECT_ID" > .env

백엔드 서버 실행

백엔드(main.py)는 클라이언트와 Gemini Live API 간의 연결을 처리합니다. 진입점은 WebSocket 엔드포인트를 노출하는 FastAPI 서버입니다. 프런트엔드에서 오디오 및 동영상 청크를 수락하고 GeminiLive 세션으로 전달합니다. gemini_live.pyGeminiLive 클래스는 세션을 관리하기 위해 genai.Client를 래핑합니다.

# Connects using the SDK
async with self.client.aio.live.connect(model=self.model, config=config) as session:
    # Manages input/output queues
    await asyncio.gather(
        send_audio(),
        send_video(),
        receive_responses()
    )

백엔드 서버를 실행하기 위해 다음 명령어를 실행합니다.

  1. 종속 항목을 설치합니다.

    pip3 install -r requirements.txt
    
  2. Google Cloud로 인증:

    gcloud auth application-default login
    
  3. 서버를 시작합니다.

    python3 main.py
    

프런트엔드 UI를 열고 Gemini에 연결

프런트엔드는 오디오 및 동영상 캡처와 재생을 관리합니다. gemini-client.js 파일은 백엔드에 대한 WebSocket 연결을 처리합니다. base64 인코딩된 미디어 청크를 백엔드로 전송하고 Gemini Live API로부터 오디오 응답을 수신한 후 사용자에게 재생합니다.

프런트엔드 UI를 열고 Gemini에 연결하려면 다음을 수행하세요.

  1. 브라우저를 열고 http://localhost:8000으로 이동합니다.
  2. 연결을 클릭합니다.

Gemini와 상호작용하기

다음을 시도해 보세요.

  • 텍스트 입력: 메시지 필드에 메시지를 입력하고 보내기를 클릭하여 Gemini에게 문자 메시지를 작성할 수 있습니다. Gemini는 오디오를 사용하여 메시지에 응답합니다.
  • 음성 입력: Gemini에게 말하려면 마이크 시작을 클릭합니다. Gemini가 오디오를 사용하여 프롬프트에 응답합니다.
  • 동영상 입력: Gemini가 카메라를 통해 볼 수 있게 하려면 카메라 시작을 클릭합니다. 카메라를 통해 보이는 내용에 관해 Gemini와 대화할 수 있습니다.

다음 단계