/generateContent 엔드포인트

/generateContent 엔드포인트

LiteLLM으로 Google AI의 generateContent 엔드포인트를 호출해 텍스트 생성, 멀티모달 상호작용, 스트리밍 응답을 사용하는 방법을 알려드릴게요.

출처: 문서

본문

개요 (Overview)

기능 지원 비고
비용 추적 (Cost Tracking)
로깅 (Logging) 모든 통합에서 작동
엔드유저 추적
스트리밍
폴백 (Fallbacks) 지원 모델 간
로드밸런싱 지원 모델 간
메타데이터 추적 trace ID, metadata를 옵저버빌리티 콜백(예: S3, Langfuse)에 전달

사용법 (Usage)

LiteLLM Python SDK

비스트리밍 예시 (Non-streaming)

from litellm.google_genai import agenerate_content

from litellm.google_genai import agenerate_content
from google.genai.types import ContentDict, PartDict
import os

# Set API key
os.environ["GEMINI_API_KEY"] = "your-gemini-api-key"

contents = ContentDict(
    parts=[
        PartDict(text="Hello, can you tell me a short joke?")
    ],
    role="user",
)

response = await agenerate_content(
    contents=contents,
    model="gemini/gemini-3.8-flash",
    max_tokens=100,
)
print(response)
스트리밍 예시

from litellm.google_genai import agenerate_content_stream

from litellm.google_genai import agenerate_content_stream
from google.genai.types import ContentDict, PartDict
import os

# Set API key
os.environ["GEMINI_API_KEY"] = "your-gemini-api-key"

contents = ContentDict(
    parts=[
        PartDict(text="Write a long story about space exploration")
    ],
    role="user",
)

response = await agenerate_content_stream(
    contents=contents,
    model="gemini/gemini-3.8-flash",
    max_tokens=500,
)

async for chunk in response:
    print(chunk)
동기 비스트리밍 예시

from litellm.google_genai import generate_content

from litellm.google_genai import generate_content
from google.genai.types import ContentDict, PartDict
import os

# Set API key
os.environ["GEMINI_API_KEY"] = "your-gemini-api-key"

contents = ContentDict(
    parts=[
        PartDict(text="Hello, can you tell me a short joke?")
    ],
    role="user",
)

response = generate_content(
    contents=contents,
    model="gemini/gemini-3.8-flash",
    max_tokens=100,
)
print(response)
동기 스트리밍 예시

from litellm.google_genai import generate_content_stream

from litellm.google_genai import generate_content_stream
from google.genai.types import ContentDict, PartDict
import os

# Set API key
os.environ["GEMINI_API_KEY"] = "your-gemini-api-key"

contents = ContentDict(
    parts=[
        PartDict(text="Write a long story about space exploration")
    ],
    role="user",
)

response = generate_content_stream(
    contents=contents,
    model="gemini/gemini-3.8-flash",
    max_tokens=500,
)
for chunk in response:
    print(chunk)

LiteLLM Proxy Server

  • config.yaml 설정
model_list:
    - model_name: gemini-flash
      litellm_params:
        model: gemini/gemini-3.8-flash
        api_key: os.environ/GEMINI_API_KEY
  • 프록시 시작
litellm --config /path/to/config.yaml
  • 테스트하기! — Google GenAI SDK(프록시 사용) 또는 curl로 테스트할 수 있어요.

Google GenAI SDK with LiteLLM Proxy:

from google.genai import Client
import os

# Configure Google GenAI SDK to use LiteLLM proxy
os.environ["GOOGLE_GEMINI_BASE_URL"] = "http://localhost:4000"
os.environ["GEMINI_API_KEY"] = "sk-<your-litellm-api-key>"

client = Client()

response = client.models.generate_content(
    model="gemini-flash",
    contents=[
        {
            "parts": [{"text": "Write a short story about AI"}],
            "role": "user"
        }
    ],
    config={"max_output_tokens": 100}
)

generateContent via LiteLLM Proxy (curl):

curl -L -X POST 'http://localhost:4000/v1beta/models/gemini-flash:generateContent' \
-H 'content-type: application/json' \
-H "authorization: Bearer ***" \
-d '{
  "contents": [
    {
      "parts": [
        {
          "text": "Write a short story about AI"
        }
      ],
      "role": "user"
    }
  ],
  "generationConfig": {
    "maxOutputTokens": 100
  }
}'

streamGenerateContent via LiteLLM Proxy (curl):

curl -L -X POST 'http://localhost:4000/v1beta/models/gemini-flash:streamGenerateContent' \
-H 'content-type: application/json' \
-H "authorization: Bearer ***" \
-d '{
  "contents": [
    {
      "parts": [
        {
          "text": "Write a long story about space exploration"
        }
      ],
      "role": "user"
    }
  ],
  "generationConfig": {
    "maxOutputTokens": 500
  }
}'

네이티브 요청 필드 (Native request fields)

generateContent 엔드포인트는 Google의 Generative Language REST API의 drop-in이에요. 그래서 Google GenerateContentRequestgenerationConfig의 형제(sibling)로 싣는 최상위 필드는 Google에 그대로(verbatim) 전달돼요. 여기에는 safetySettings, toolConfig, cachedContent, labels가 포함돼요. 이 필드들은 Google을 직접 호출할 때처럼 요청 body의 최상위 레벨에 보내면 돼요. extra_body로 감쌀 필요가 없어요. 만약 extra_body를 전달하면, 충돌 시 그 안의 명시적 값이 우선해요.

네이티브 최상위 필드 (curl):

curl -L -X POST 'http://localhost:4000/v1beta/models/gemini-flash:generateContent' \
-H 'content-type: application/json' \
-H "authorization: Bearer ***" \
-d '{
  "contents": [
    {
      "parts": [{"text": "Say hi"}],
      "role": "user"
    }
  ],
  "generationConfig": {
    "maxOutputTokens": 100
  },
  "safetySettings": [
    {
      "category": "HARM_CATEGORY_HATE_SPEECH",
      "threshold": "BLOCK_NONE"
    }
  ],
  "toolConfig": {
    "functionCallingConfig": {"mode": "AUTO"}
  }
}'

네이티브 최상위 필드 (LiteLLM Python SDK):

from litellm.google_genai import generate_content
import os

# Set API key
os.environ["GEMINI_API_KEY"] = "your-gemini-api-key"

response = generate_content(
    model="gemini/gemini-3.8-flash",
    contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
    safetySettings=[
        {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}
    ],
    toolConfig={"functionCallingConfig": {"mode": "AUTO"}},
)
print(response)

더 알아보기 (Learn more)