Vertex AI Live API WebSocket 패스스루

Vertex AI Live API WebSocket 패스스루

LiteLLM이 Vertex AI Live API의 WebSocket 패스스루를 지원해요. 이제 Gemini 모델과 실시간 양방향 통신을 할 수 있습니다.

출처: 문서

본문

개요 (Overview)

Vertex AI Live API WebSocket 패스스루를 통해 다음을 할 수 있어요.

  • LiteLLM 프록시를 통해 Vertex AI Live API에 연결
  • 기존 Vertex AI 인증 방식을 그대로 사용
  • 모든 WebSocket 메시지를 양방향으로 그대로 전달
  • 텍스트·오디오·비디오·멀티모달 상호작용 지원
  • 모든 사용 유형에 대해 비용을 자동으로 추적

설정 (Configuration)

환경 변수 (Environment Variables)

Vertex AI 인증을 위해 다음 환경 변수를 설정해요.

# Required
DEFAULT_VERTEXAI_PROJECT=your-project-id
DEFAULT_VERTEXAI_LOCATION=us-central1
# Optional - use one of these for authentication
DEFAULT_GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
# OR run: gcloud auth application-default login

설정 파일 (Configuration File)

기본값을 사용한다면 config.yaml에서도 설정할 수 있어요.

litellm_settings:
  default_vertex_config:
    vertex_project: "your-project-id"
    vertex_location: "us-central1"
    vertex_credentials: "os.environ/GOOGLE_APPLICATION_CREDENTIALS"

사용법 (Usage)

WebSocket 엔드포인트

ws://your-proxy-host/v1/vertex-ai/live
ws://your-proxy-host/vertex-ai/live

쿼리 파라미터

  • vertex_project (선택): Google Cloud 프로젝트 ID (config에 설정 가능)
  • vertex_location (선택): Vertex AI 위치 (config에 설정 가능, 기본: us-central1)
  • model (선택): 모델 이름. 글로벌 모델의 Vertex 지역을 결정하는 데 사용

연결 예시

// If vertex_project and vertex_location are set in config, you can connect without query params
const ws = new WebSocket('ws://localhost:4000/v1/vertex-ai/live');
// Or specify them explicitly
const ws = new WebSocket('ws://localhost:4000/v1/vertex-ai/live?vertex_project=your-project-id&vertex_location=us-central1');

비용 추적 (Cost Tracking)

WebSocket 패스스루는 Vertex AI 가격에 따라 모든 사용 유형의 비용을 자동으로 추적해요.

지원되는 비용 추적

  • 텍스트: 모델에 따라 문자(character) 또는 토큰(token) 기반 가격
  • 오디오: 오디오 입력/출력에 대한 초당(per-second) 가격
  • 비디오: 비디오 입력에 대한 초당(per-second) 가격
  • 이미지: 이미지 입력에 대한 이미지당(per-image) 가격

비용 계산 (Cost Calculation)

비용은 LiteLLM의 다른 Vertex AI 모델과 동일한 방식으로 계산돼요.

  • Gemini 모델에는 cost_per_character 사용
  • 파트너 모델(Claude, Llama 등)에는 cost_per_token 사용
  • 해당되는 경우 오디오·비디오·이미지 비용 포함

비용 로깅 (Cost Logging)

비용은 자동으로 다음에 기록돼요.

  • LiteLLM 프록시 로그
  • 데이터베이스 (설정된 경우)
  • 비용 추적 시스템 (Spend tracking system)
  • 관리자 대시보드

로그 출력 예시:

Vertex AI Live WebSocket session cost: $0.001234 (input: $0.000800, output: $0.000434) tokens: 150, characters: 1200, duration: 45.2s

API 참조 (API Reference)

설정 메시지 (Setup Message)

세션을 초기화하려면 이 메시지를 먼저 보내요.

{
  "setup": {
    "model": "projects/your-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash-live-preview-04-09",
    "generation_config": {
      "response_modalities": ["TEXT"]
    }
  }
}

텍스트 입력 (Text Input)

{
  "client_content": {
    "turns": [
      {
        "role": "user",
        "parts": [{"text": "Hello! How are you?"}]
      }
    ],
    "turn_complete": true
  }
}

오디오 입력 (Audio Input)

{
  "realtime_input": {
    "media_chunks": [
      {
        "data": "base64-encoded-audio-data",
        "mime_type": "audio/pcm"
      }
    ]
  }
}

지원되는 기능 (Supported Features)

응답 형식 (Response Modalities)

  • TEXT: 텍스트 응답
  • AUDIO: 음성 합성(voice synthesis)을 포함한 오디오 응답

도구 (Tools)

  • 함수 호출 (Function Calling): 커스텀 함수 정의 및 사용
  • 코드 실행 (Code Execution): Python 코드 실행
  • Google 검색 (Google Search): 웹 검색
  • 음성 활동 감지 (Voice Activity Detection): 사용자가 말하는 시점 감지

고급 기능 (Advanced Features)

  • 오디오 전사 (Audio Transcription): 입력·출력 오디오 전사
  • 프로액티브 오디오 (Proactive Audio): 관련 있을 때만 모델이 응답
  • 감성 대화 (Affective Dialog): 감정 표현 이해

예시 (Examples)

Python 클라이언트

import asyncio
import json
import websockets

async def chat_with_gemini():
    uri = "ws://localhost:4000/v1/vertex-ai/live?vertex_project=your-project-id"
    
    async with websockets.connect(uri) as websocket:
        # Setup
        setup = {
            "setup": {
                "model": "projects/your-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash-live-preview-04-09",
                "generation_config": {"response_modalities": ["TEXT"]}
            }
        }
        await websocket.send(json.dumps(setup))
        
        # Wait for setup response
        response = await websocket.recv()
        print(f"Setup: {response}")
        
        # Send message
        message = {
            "client_content": {
                "turns": [{"role": "user", "parts": [{"text": "Hello!"}]}],
                "turn_complete": True
            }
        }
        await websocket.send(json.dumps(message))
        
        # Receive response
        async for response in websocket:
            print(f"Response: {response}")
            # Check if turn is complete
            data = json.loads(response)
            if data.get("serverContent", {}).get("turnComplete"):
                break

asyncio.run(chat_with_gemini())

JavaScript 클라이언트

const ws = new WebSocket('ws://localhost:4000/v1/vertex-ai/live?vertex_project=your-project-id');
ws.onopen = function() {
    // Send setup
    const setup = {
        setup: {
            model: "projects/your-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash-live-preview-04-09",
            generation_config: { response_modalities: ["TEXT"] }
        }
    };
    ws.send(JSON.stringify(setup));
};
ws.onmessage = function(event) {
    const data = JSON.parse(event.data);
    console.log('Received:', data);
    
    // Check if setup is complete
    if (data.setupComplete) {
        // Send a message
        const message = {
            client_content: {
                turns: [{ role: "user", parts: [{ text: "Hello!" }] }],
                turn_complete: true
            }
        };
        ws.send(JSON.stringify(message));
    }
};

오류 처리 (Error Handling)

WebSocket 연결은 다음 코드로 종료될 수 있어요.

  • 4001: Vertex AI 자격 증명이 설정되지 않음
  • 4002: 프로젝트 ID가 제공되지 않음
  • 1011: 내부 서버 오류

인증 (Authentication)

WebSocket 패스스루는 다른 LiteLLM 엔드포인트와 동일한 인증을 사용해요.

  • API 키: Authorization: Bearer *** 헤더 전달
  • Vertex AI 자격 증명: 환경 변수 또는 설정 파일로 설정

제약 사항 (Limitations)

  • Vertex AI API가 활성화된 유효한 Google Cloud 프로젝트가 필요해요.
  • WebSocket 연결은 서버 재시작 시에도 유지되지 않아요.
  • Google Cloud 할당량에 따라 속도 제한이 적용돼요.

문제 해결 (Troubleshooting)

흔한 문제 (Common Issues)

  • 인증 오류 (Authentication Error): Vertex AI 자격 증명이 올바르게 설정되었는지 확인해요.
  • 프로젝트를 찾을 수 없음 (Project Not Found): 프로젝트 ID가 존재하고 Vertex AI가 활성화되었는지 확인해요.
  • 연결 거부 (Connection Refused): LiteLLM 프록시 서버가 실행 중인지 확인해요.

디버그 모드 (Debug Mode)

디버그 로깅을 활성화하면 상세한 연결 정보를 볼 수 있어요.

export LITELLM_LOG=DEBUG

더 알아보기 (Learn more)