Vertex AI

Vertex AI (Gemini) 연동

Google Cloud를 쓰는 팀이 Gemini 모델을 LiteLLM에서 부르려면 Vertex AI를 연결해야 해요. Google은 Gemini를 두 가지 경로로 서빙해요. 하나는 간단한 API 키만 필요한 Google AI Studio(Gemini API), 다른 하나는 GCP 자격 증명이 필요한 Vertex AI입니다. LiteLLM에서 둘을 어떻게 구분해 쓰는지 정리해 드릴게요.

출처: 공식문서 - VertexAI [Gemini]

Vertex AI 프로바이더 한눈에

속성
설명 Vertex AI는 생성형 AI를 만들고 쓰기 위한 완전 관리형 개발 플랫폼
LiteLLM 라우트 vertex_ai/
Base URL 리전 엔드포인트 https://{vertex_location}-aiplatform.googleapis.com/ 또는 글로벌 엔드포인트 https://aiplatform.googleapis.com/
지원 동작 /chat/completions, /completions, /embeddings, /audio/speech, /fine_tuning, /batches, /files, /images, /rerank

Vertex AI vs Gemini API — 어떤 프리픽스를 쓸까

같은 Gemini 모델도 어느 경로로 부르느냐에 따라 인증 방식이 달라져요.

모델 형식 프로바이더 필요한 인증
vertex_ai/gemini-2.0-flash Vertex AI GCP 자격 증명 + 프로젝트
gemini-2.0-flash (프리픽스 없음) Vertex AI GCP 자격 증명 + 프로젝트
gemini/gemini-2.0-flash Gemini API GEMINI_API_KEY (간단한 API 키)

핵심 포인트예요. API 키만으로 간단하게 쓰고 싶다면 gemini/ 프리픽스를 쓰세요. 반대로 프리픽스가 없는 모델은 기본적으로 Vertex AI로 처리되기 때문에 GCP 인증이 필요합니다. 우리 회사가 Google Cloud 인프라를 쓰고 있고 IAM/서비스 계정이 정리되어 있다면 vertex_ai/가 자연스럽고, 그냥 키 하나로 빠르게 돌려보고 싶다면 gemini/를 고르면 돼요.

기본 호출 — 서비스 계정 인증

vertex_ai/ 라우트는 Vertex AI의 REST API를 사용합니다. 먼저 자격 증명을 준비해요.

  • 방법 1: gcloud auth application-default login 을 실행해 환경에 자격 증명을 추가.
  • 방법 2: 서비스 계정 JSON 파일을 로드해 vertex_credentials로 전달.
from litellm import completion
import json

## GET CREDENTIALS
file_path = 'path/to/vertex_ai_service_account.json'

# JSON 파일 로드
with open(file_path, 'r') as file:
    vertex_credentials = json.load(file)

# JSON 문자열로 변환
vertex_credentials_json = json.dumps(vertex_credentials)

## COMPLETION CALL
response = completion(
  model="vertex_ai/gemini-2.5-pro",
  messages=[{ "content": "Hello, how are you?","role": "user"}],
  vertex_credentials=vertex_credentials_json
)

시스템 메시지도 일반적인 형식과 동일하게 넣을 수 있어요.

response = completion(
  model="vertex_ai/gemini-2.5-pro",
  messages=[{"content": "You are a good bot.","role": "system"}, {"content": "Hello, how are you?","role": "user"}],
  vertex_credentials=vertex_credentials_json
)

도구 호출 강제하기

Gemini가 도구를 반드시 호출하도록 하려면 tool_choice="required"를 쓰세요.

from litellm import completion
import json

## GET CREDENTIALS
# gcloud auth application-default login 등으로 준비
file_path = 'path/to/vertex_ai_service_account.json'
with open(file_path, 'r') as file:
    vertex_credentials = json.load(file)
vertex_credentials_json = json.dumps(vertex_credentials)

messages = [
    {"role": "system", "content": "Your name is Litellm Bot, you are a helpful assistant"},
    {"role": "user", "content": "Hello, what is your name and can you tell me the weather?"},
]

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    }
                },
                "required": ["location"],
            },
        },
    }
]

data = {
    "model": "vertex_ai/gemini-1.5-pro-preview-0514",
    "messages": messages,
    "tools": tools,
    "tool_choice": "required",
    "vertex_credentials": vertex_credentials_json
}

print(completion(**data))

tools에 함수 정의를 넣고, tool_choice: "required"로 지정하면 Gemini가 그 도구를 쓰도록 강제됩니다.

응답 스키마 강제 (Response Schema)

v1.40.1+ 부터 LiteLLM은 Vertex AI의 Gemini-1.5-Pro에서 response_schema 파라미터를 지원해요. 그 외 모델(gemini-1.5-flash, claude-3-5-sonnet 등)에서는 사용자가 제어하는 프롬프트에 스키마를 메시지 목록에 추가하는 방식으로 동작합니다.

from litellm import completion
import json

## SETUP ENVIRONMENT
# !gcloud auth application-default login - run this to add vertex credentials to your env

messages = [{"role": "user", "content": "List 5 popular cookie recipes."}]

response_schema = {
        "type": "array",
        "items": {
            "type": "object",
            "properties": {
                "recipe_name": {
                    "type": "string",
                },
            },
            "required": ["recipe_name"],
        },
    }

completion(
    model="vertex_ai/gemini-1.5-pro",
    messages=messages,
    response_format={"type": "json_object", "response_schema": response_schema} # 핵심 변경
    )

print(json.loads(completion.choices[0].message.content))

스키마 검증을 강제하려면 enforce_validation: true를 넣으세요. 응답이 스키마와 안 맞으면 JSONSchemaValidationError(openai.APIError를 상속)가 발생하고, 원시 응답은 e.raw_response로 접근할 수 있어요.

검색·지면 기반(grounding)과 도구들

Vertex AI는 Google 검색 접지, URL 컨텍스트, 코드 실행, Google 지도 같은 고급 도구를 지원해요. tools에 각각의 객체를 넣으면 됩니다.

  • Google 검색 접지: tools = [{"googleSearch": {}}]. 접지 메타데이터는 response_obj._hidden_params["vertex_ai_grounding_metadata"]에서 확인.
  • URL 컨텍스트: tools = [{"urlContext": {}}]. Gemini가 URL에서 내용을 가져와 응답에 반영. response_obj.model_extra['vertex_ai_url_context_metadata']로 접근.
  • 엔터프라이즈 웹 검색: tools = [{"enterpriseWebSearch": {}}].
  • 코드 실행: tools = [{"codeExecution": {}}].
  • Google 지도: tools = [{"googleMaps": {"enableWidget": "ENABLE_WIDGET", "latitude": 37.7749, "longitude": -122.4194, "languageCode": "en_US"}}].

이 도구들은 "모델이 스스로 외부 정보나 계산을 써야 할 때"를 위한 것들이에요. 예를 들어 googleMaps를 주고 "주변 식당은?"이라고 물으면 응답이 지리 정보에 근거해서 나옵니다.

임베딩

Vertex AI 임베딩 모델(vertex_ai/text-embedding-004)도 지원해요. task_type, title, dimensions, auto_truncate 같은 파라미터를 넘길 수 있습니다.

response = litellm.embedding(
    model="vertex_ai/text-embedding-004",
    input=["good morning from litellm", "gm"],
    task_type="RETRIEVAL_DOCUMENT",
    title="test",
    dimensions=1,
    auto_truncate=True,
)

멀티모달 임베딩(vertex_ai/multimodalembedding@001)은 GCS URL이나 base64 인코딩 이미지/영상을 받아요. 텍스트+이미지, 텍스트+영상, 이미지+영상을 함께 임베딩할 수도 있고, 요청당 이미지/영상 1개 제한 같은 제약이 있습니다.

파인튜닝 (Fine Tuning)

OpenAI Python SDK로 Vertex AI의 파인튜닝 잡(/tuningJobs)을 만들 수 있어요. config.yaml에 finetune_settings를 지정하고:

model_list:
  - model_name: gpt-4
    litellm_params:
      model: openai/fake
      api_key: fake-key
      api_base: https://exampleopenaiendpoint-production.up.railway.app/

# 핵심 변경: /fine_tuning/jobs 엔드포인트용
finetune_settings:
  - custom_llm_provider: "vertex_ai"
    vertex_project: "adroit-crow-413218"
    vertex_location: "us-central1"
    vertex_credentials: "/Users/ishaanjaffer/Downloads/adroit-crow-413218-a956eef1a2a8.json"

custom-llm-provider: vertex_ai 헤더를 달아 파인튜닝 잡을 생성합니다.

ft_job = await client.fine_tuning.jobs.create(
    model="gemini-1.0-pro-002",                  # 파인튜닝할 Vertex 모델
    training_file="gs://cloud-samples-data/ai-platform/generative_ai/sft_train_data.jsonl",
    extra_headers={"custom-llm-provider": "vertex_ai"}, # litellm proxy에 쓸 프로바이더 지시
)

hyperparametersn_epochs, learning_rate_multiplier, adapter_size 같은 Vertex 고유 하이퍼파라미터를 넘길 수도 있어요.

생각 정리

Vertex AI를 쓰는 첫 관문은 인증 방식 결정이에요. gemini/(API 키)냐 vertex_ai/(GCP 자격 증명)냐를 먼저 정하고, 자격 증명은 gcloud auth application-default login이나 서비스 계정 JSON으로 준비하세요. 그 다음 completion(model="vertex_ai/<model-id>", vertex_credentials=...)로 부르면 됩니다. 그 뒤로 도구 호출, 응답 스키마, 접지, 임베딩, 파인튜닝을 필요에 따라 하나씩 붙여 나가면 돼요.

더 알아보기