Google GenAI SDK와 LiteLLM
Google GenAI SDK와 LiteLLM
Google의 공식 GenAI SDK(JavaScript/TypeScript 및 Python)를 LiteLLM Proxy를 통해 모든 LLM 제공자와 함께 사용해 봐요.
Google GenAI SDK(@google/genai for JS, google-genai for Python)는 Gemini 모델을 호출하기 위한 네이티브 인터페이스를 제공합니다. 이를 LiteLLM에 연결하면 네이티브 Gemini 요청/응답 형식을 유지하면서 OpenAI, Anthropic, Bedrock, Azure, Vertex AI 등 어떤 제공자든 같은 SDK로 사용할 수 있어요.
출처: 문서
본문
Google GenAI SDK와 함께 LiteLLM을 쓰는 이유
개발자 이점:
- 범용 모델 접근: Google GenAI SDK 인터페이스를 통해 LiteLLM이 지원하는 모든 모델(Anthropic, OpenAI, Vertex AI, Bedrock 등)을 사용할 수 있어요.
- 더 높은 Rate Limit과 신뢰성: 여러 모델과 제공자에 걸쳐 로드 밸런싱하여 개별 제공자 한도에 부딪히지 않게 하고, 한 제공자가 실패해도 응답을 받도록 fallback을 보장해요.
Proxy 관리자 이점:
- 중앙 집중식 관리: 각 제공자에 개발자에게 API 키를 주지 않고 단일 LiteLLM proxy 인스턴스를 통해 모든 모델 접근을 통제할 수 있어요.
- 예산 컨트롤: 모든 SDK 사용량에 걸쳐 비용 상한을 설정하고 비용을 추적할 수 있어요.
- 로깅 및 관찰 가능성: 비용 추적, 로깅, 분석으로 모든 요청을 추적할 수 있어요.
| Feature | Supported | Notes |
| Cost Tracking | ✅ | All models on /generateContent endpoint |
| Logging | ✅ | Works across all integrations |
| Streaming | ✅ | streamGenerateContent supported |
| Virtual Keys | ✅ | Use LiteLLM keys instead of Google keys |
| Load Balancing | ✅ | Via native router endpoints |
| Fallbacks | ✅ | Via native router endpoints |
빠른 시작
1. SDK 설치
- JavaScript/TypeScript
- Python
npm install @google/genai
uv add google-genai
2. LiteLLM Proxy 시작
config.yaml
model_list:
- model_name: gemini-3.8-flash
litellm_params:
model: gemini/gemini-3.8-flash
api_key: os.environ/GEMINI_API_KEY
litellm --config config.yaml
3. LiteLLM을 통해 SDK 호출
- JavaScript/TypeScript
- Python
- curl
index.js
const { GoogleGenAI } = require("@google/genai");const ai = new GoogleGenAI({
apiKey: *** // LiteLLM virtual key (not a Google key)
httpOptions: {
baseUrl: "http://localhost:4000/gemini", // LiteLLM proxy URL
},
});async function main() {
const response = await ai.models.generateContent({
model: "gemini-3.8-flash",
contents: "Explain how AI works",
});
console.log(response.text);
}main();
main.py
from google import genaiclient = genai.Client(
api_key="sk-", # LiteLLM virtual key (not a Google key)
http_options={"base_url": "http://localhost:4000/gemini"}, # LiteLLM proxy URL)response = client.models.generate_content(
model="gemini-3.8-flash",
contents="Explain how AI works",)print(response.text)
curl "http://localhost:4000/gemini/v1beta/models/gemini-3.8-flash:generateContent?key=sk-" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts": [{"text": "Explain how AI works"}]
}]
}'
스트리밍
- JavaScript/TypeScript
- Python
streaming.js
const { GoogleGenAI } = require("@google/genai");const ai = new GoogleGenAI({
apiKey: ***
httpOptions: {
baseUrl: "http://localhost:4000/gemini",
},
});async function main() {
const response = await ai.models.generateContentStream({
model: "gemini-3.8-flash",
contents: "Write a short poem about the ocean",
});
for await (const chunk of response) {
process.stdout.write(chunk.text);
}
}main();
streaming.py
from google import genaiclient = genai.Client(
api_key="sk-",
http_options={"base_url": "http://localhost:4000/gemini"},)response = client.models.generate_content_stream(
model="gemini-3.8-flash",
contents: "Write a short poem about the ocean",
)for chunk in response: print(chunk.text, end="")
다중 턴 채팅
- JavaScript/TypeScript
- Python
chat.js
const { GoogleGenAI } = require("@google/genai");const ai = new GoogleGenAI({
apiKey: ***
httpOptions: {
baseUrl: "http://localhost:4000/gemini",
},
});async function main() {
const chat = ai.chats.create({
model: "gemini-3.8-flash",
});
const response1 = await chat.sendMessage({ message: "I have 2 dogs and 3 cats." });
console.log(response1.text);
const response2 = await chat.sendMessage({ message: "How many pets is that in total?" });
console.log(response2.text);
}main();
chat.py
from google import genaiclient = genai.Client(
api_key="sk-",
http_options={"base_url": "http://localhost:4000/gemini"},)chat = client.chats.create(model="gemini-3.8-flash")response1 = chat.send_message("I have 2 dogs and 3 cats.")print(response1.text)response2 = chat.send_message("How many pets is that in total?")print(response2.text)
고급: GenAI SDK로 어떤 모델이든 사용
기본적으로 GenAI SDK는 Gemini 모델과 통신합니다. 그러나 LiteLLM의 router를 사용하면 GenAI SDK 요청을 어떤 제공자로든(Anthropic, OpenAI, Bedrock 등) 라우팅할 수 있어요.
이는 model_group_alias를 사용해 Gemini 모델 이름을 원하는 제공자 모델에 매핑하는 방식으로 동작합니다. LiteLLM이 내부적으로 형식 변환을 처리해요.
info
이것이 동작하려면 SDK baseUrl을 http://localhost:4000처럼 /gemini 없이 지정하세요. 이렇게 하면 LiteLLM의 네이티브 Google 엔드포인트로 요청이 라우팅되며, router를 거치고 모델 별칭을 지원해요.
- Anthropic
- OpenAI
- Bedrock
- 다중 제공자 로드 밸런싱
gemini-3.8-flash 요청을 Claude Sonnet으로 라우팅:config.yaml
model_list:
- model_name: claude-sonnet
litellm_params:
model: anthropic/claude-sonnet-5
api_key: os.environ/ANTHROPIC_API_KEYrouter_settings:
model_group_alias: {"gemini-3.8-flash": "claude-sonnet"}
gemini-3.8-flash 요청을 gpt-5.6-terra로 라우팅:config.yaml
model_list:
- model_name: openai-gpt
litellm_params:
model: gpt-5.6-terra
api_key: os.environ/OPENAI_API_KEYrouter_settings:
model_group_alias: {"gemini-3.8-flash": "openai-gpt"}
gemini-3.8-flash 요청을 Bedrock의 Claude로 라우팅:config.yaml
model_list:
- model_name: bedrock-claude
litellm_params:
model: bedrock/us.anthropic.claude-sonnet-5
aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
aws_region_name: us-east-1router_settings:
model_group_alias: {"gemini-3.8-flash": "bedrock-claude"}
Anthropic과 OpenAI 간 로드 밸런싱:config.yaml
model_list:
- model_name: my-model
litellm_params:
model: anthropic/claude-sonnet-5
api_key: os.environ/ANTHROPIC_API_KEY
- model_name: my-model
litellm_params:
model: gpt-5.6-terra
api_key: os.environ/OPENAI_API_KEYrouter_settings:
model_group_alias: {"gemini-3.8-flash": "my-model"}
그다음 /gemini 없는 baseUrl로 SDK를 사용하세요:
- JavaScript/TypeScript
- Python
any_model.js
const { GoogleGenAI } = require("@google/genai");const ai = new GoogleGenAI({
apiKey: ***
httpOptions: {
baseUrl: "http://localhost:4000", // No /gemini — goes through the router
},
});async function main() {
// This calls Claude/gpt-5.6-terra/Bedrock under the hood via model_group_alias
const response = await ai.models.generateContent({
model: "gemini-3.8-flash",
contents: "Hello from any model!",
});
console.log(response.text);
}main();
any_model.py
from google import genaiclient = genai.Client(
api_key="sk-",
http_options={"base_url": "http://localhost:4000"}, # No /gemini)# This calls Claude/gpt-5.6-terra/Bedrock under the hood via model_group_aliasresponse = client.models.generate_content(
model="gemini-3.8-flash",
contents: "Hello from any model!",)print(response.text)
Pass-through vs 네이티브 Router 엔드포인트
LiteLLM은 GenAI SDK 요청을 처리하는 두 가지 방식을 제공해요:
| | Pass-through (/gemini) | Native Router (/) |
| baseUrl | http://localhost:4000/gemini | http://localhost:4000 |
| Models | Gemini only | Any provider via model_group_alias |
| Translation | None — proxies directly to Google | Translates internally |
| Cost Tracking | ✅ | ✅ |
| Virtual Keys | ✅ | ✅ |
| Load Balancing | ❌ | ✅ |
| Fallbacks | ❌ | ✅ |
| Best for | Simple Gemini proxy | Multi-provider routing |
환경 변수 구성
코드 대신 환경 변수로 SDK를 구성할 수도 있어요:
# For JavaScript SDK (@google/genai)export GOOGLE_GEMINI_BASE_URL="http://localhost:4000/gemini"export GEMINI_API_KEY="sk-"# For Python SDK (google-genai)# Note: The Python SDK does not support a base URL env var.# Configure it in code with http_options={"base_url": "..."} instead.export GEMINI_API_KEY="sk-"
이것은 GenAI SDK 위에 구축된 도구(예: Gemini CLI)에 특히 유용합니다.
관련 리소스
- Gemini CLI with LiteLLM
- Google AI Studio Pass-Through
- Google ADK with LiteLLM
- LiteLLM Proxy Quick Start
@google/genainpm packagegoogle-genaiPyPI package