Bedrock Embedding
Bedrock Embedding
Amazon Titan, Amazon Nova, Cohere, TwelveLabs 임베딩 모델을 LiteLLM의 bedrock/ 라우트로 호출해요.
출처: 문서
본문
지원 임베딩 모델 (Supported Embedding Models)
| 제공자 | LiteLLM 라우트 | AWS 문서 | 비용 추적 |
|---|---|---|---|
| Amazon Titan | bedrock/amazon.titan-* |
Amazon Titan Embeddings | ✅ |
| Amazon Nova | bedrock/amazon.nova-* |
Amazon Nova Embeddings | ✅ |
| Cohere | bedrock/cohere.* |
Cohere Embeddings | ✅ |
| TwelveLabs | bedrock/twelvelabs.*, bedrock/us.twelvelabs.*, bedrock/eu.twelvelabs.* |
TwelveLabs, Marengo Embed 3.0 | ✅ |
비동기 Invoke 지원 (Async Invoke Support)
LiteLLM은 비동기 처리가 필요한 임베딩 모델을 위한 AWS Bedrock의 async-invoke 기능을 지원해요. 특히 대용량 미디어 파일(비디오, 오디오)이나 백그라운드에서 임베딩을 처리해야 할 때 유용해요.
지원 모델
| 제공자 | Async Invoke 라우트 | 사용 사례 |
|---|---|---|
| Amazon Nova | bedrock/async_invoke/amazon.nova-2-multimodal-embeddings-v1:0 |
긴 텍스트, 비디오, 오디오를 위한 segmentation 포함 멀티모달 임베딩 |
| TwelveLabs Marengo Embed 2.7 | bedrock/async_invoke/twelvelabs.marengo-embed-2-7-v1:0 |
비디오, 오디오, 이미지, 텍스트 임베딩 |
| TwelveLabs Marengo Embed 3.0 | bedrock/async_invoke/twelvelabs.marengo-embed-3-0-v1:0 |
비디오와 오디오 임베딩 (텍스트·이미지는 동기 실행) |
필수 파라미터
Bedrock의 async invoke는 base model id만 받아요. 여기서
us.또는eu.inference profile 대신twelvelabs.marengo-embed-2-7-v1:0또는twelvelabs.marengo-embed-3-0-v1:0을 사용하세요. inference profile은 Bedrock이 "The provided model doesn't support async inference"로 거부해요.
async-invoke를 쓸 때는 다음을 제공해야 해요:
| 파라미터 | 설명 | 필수 |
|---|---|---|
| output_s3_uri | 임베딩 결과가 저장될 S3 URI | ✅ |
| input_type | 입력 유형: "text", "image", "video", "audio" (Marengo Embed 3.0은 "text_image"와 "multi_input"도 받음) | ✅ |
| aws_region_name | 요청용 AWS 지역 | ✅ |
기본 Async Invoke
from litellm import embedding
# Text embedding with async-invoke
response = embedding(
model="bedrock/async_invoke/twelvelabs.marengo-embed-2-7-v1:0",
input=["Hello world from LiteLLM async invoke!"],
aws_region_name="us-east-1",
input_type="text",
output_s3_uri="s3://your-bucket/async-invoke-output/",
)
print(f"Job submitted! Invocation ARN: {response._hidden_params._invocation_arn}")
비디오/오디오 임베딩
# Video embedding (requires async-invoke)
response = embedding(
model="bedrock/async_invoke/twelvelabs.marengo-embed-2-7-v1:0",
input=["s3://your-bucket/video.mp4"], # S3 URL for video
aws_region_name="us-east-1",
input_type="video",
output_s3_uri="s3://your-bucket/async-invoke-output/",
)
print(f"Video embedding job submitted! ARN: {response._hidden_params._invocation_arn}")
Base64 이미지 임베딩
import base64
# Load and encode image
with open("image.jpg", "rb") as img_file:
img_data = base64.b64encode(img_file.read()).decode('utf-8')
img_base64 = f"data:image/jpeg;base64,{img_data}"
response = embedding(
model="bedrock/async_invoke/twelvelabs.marengo-embed-2-7-v1:0",
input=[img_base64],
aws_region_name="us-east-1",
input_type="image",
output_s3_uri="s3://your-bucket/async-invoke-output/",
)
작업 ID와 Invocation ARN 가져오기
async-invoke 응답은 hidden parameters에 invocation ARN을 포함해요.
response = embedding(
model="bedrock/async_invoke/twelvelabs.marengo-embed-2-7-v1:0",
input=["Hello world"],
aws_region_name="us-east-1",
input_type="text",
output_s3_uri="s3://your-bucket/async-invoke-output/",
)
# Access invocation ARN
invocation_arn = response._hidden_params._invocation_arn
print(f"Invocation ARN: {invocation_arn}")
# Extract job ID from ARN (last part after the last slash)
job_id = invocation_arn.split("/")[-1]
print(f"Job ID: {job_id}")
작업 상태 확인
LiteLLM의 retrieve_batch 함수로 작업이 처리 중인지 확인할 수 있어요.
from litellm import retrieve_batch
def check_async_job_status(invocation_arn, aws_region_name="us-east-1"):
"""Check the status of an async invoke job using LiteLLM batch API"""
try:
response = retrieve_batch(
batch_id=invocation_arn, # Pass the invocation ARN here
custom_llm_provider="bedrock",
aws_region_name=aws_region_name,
)
return response
except Exception as e:
print(f"Error checking job status: {e}")
return None
# Check status
status = check_async_job_status(invocation_arn, "us-east-1")
if status:
print(f"Job Status: {status.status}") # "in_progress", "completed", or "failed"
print(f"Output Location: {status.metadata['output_file_id']}") # S3 URI where results are stored
완료까지 폴링
def wait_for_async_job(invocation_arn, aws_region_name="us-east-1", max_wait=3600):
"""Poll job status until completion"""
start_time = time.time()
while True:
status = retrieve_batch(
batch_id=invocation_arn,
custom_llm_provider="bedrock",
aws_region_name=aws_region_name,
)
if status.status == "completed":
print("✅ Job completed!")
return status
elif status.status == "failed":
error_msg = status.metadata.get('failure_message', 'Unknown error')
raise Exception(f"❌ Job failed: {error_msg}")
else:
elapsed = time.time() - start_time
if elapsed > max_wait:
raise TimeoutError(f"Job timed out after {max_wait} seconds")
print(f"⏳ Job still processing... (elapsed: {elapsed:.0f}s)")
time.sleep(10) # Wait 10 seconds before checking again
# Wait for completion
completed_status = wait_for_async_job(invocation_arn)
output_s3_uri = completed_status.metadata['output_file_id']
print(f"Results available at: {output_s3_uri}")
참고: 실제 임베딩 결과는 S3에 저장돼요. 작업이 완료되면
status.metadata['output_file_id']에 지정된 S3 위치에서 결과를 다운로드해요. 결과는 임베딩 벡터가 포함된 JSON/JSONL 형식이에요.
TwelveLabs Marengo Embed 3.0
Marengo Embed 3.0(twelvelabs.marengo-embed-3-0-v1:0, us-east-1과 eu-west-1용 us.·eu. inference profile 포함)은 512차원 벡터를 반환하고 최대 500 토큰의 텍스트를 받아요. 텍스트, 이미지, 텍스트+이미지, 다중 이미지 입력은 bedrock/<model id>로 동기 실행되고, 비디오와 오디오는 output_s3_uri와 함께 bedrock/async_invoke/twelvelabs.marengo-embed-3-0-v1:0으로 가며, Bedrock의 async invoke가 inference profile을 거부하므로 base model id를 사용해요. 3.0은 2.7과 다른 요청 본문을 Bedrock에 보내며, LiteLLM은 같은 input_type 파라미터로 그 본문을 구성하므로 2.7(2026-11-30 폐기 예정)에서 이동하는 것은 모델 id 변경일 뿐이에요.
입력 유형
| input_type | input | 추가 파라미터 |
|---|---|---|
| text (기본값) | 임베딩할 텍스트 | |
| image | base64 이미지 또는 s3:// URI | |
| text_image | 텍스트 | media_source: base64 이미지 또는 s3:// URI |
| multi_input | 텍스트, 각 이미지를 <@name>으로 참조 |
media_sources: 이름 → base64 이미지 또는 s3:// URI 매핑 |
| video, audio | s3:// URI 또는 base64 미디어, async invoke 전용 | startSec, endSec, segmentation, embeddingOption, embeddingType, embeddingScope (AWS 문서대로) |
inferenceId와 bucketOwner(다른 계정이 소유한 s3:// URI용)는 모든 입력 유형에 걸쳐 패스스루돼요. media_source 없는 text_image 요청이나 media_sources 없는 multi_input 요청은 누락된 파라미터를 명명하는 400으로 거부돼요. Marengo 2.7의 textTruncate, lengthSec, useFixedLengthSec, minClipSec과 다른 입력 유형의 비디오·오디오 옵션은 drop_params가 설정되지 않으면 3.0에서 400으로 거부되며, 설정하면 대신 버려져요.
Proxy config
model_list:
- model_name: marengo-3
litellm_params:
model: bedrock/us.twelvelabs.marengo-embed-3-0-v1:0
aws_region_name: us-east-1
- model_name: marengo-3-async
litellm_params:
model: bedrock/async_invoke/twelvelabs.marengo-embed-3-0-v1:0
aws_region_name: us-east-1
텍스트:
curl http://0.0.0.0:4000/v1/embeddings \
-H "Authorization: Bearer ***" -H "Content-Type: application/json" \
-d '{"model": "marengo-3", "input": "a dog running on the beach", "input_type": "text"}'
이미지:
curl http://0.0.0.0:4000/v1/embeddings \
-H "Authorization: Bearer ***" -H "Content-Type: application/json" \
-d '{"model": "marengo-3", "input": "<base64 image>", "input_type": "image"}'
텍스트 + 이미지:
curl http://0.0.0.0:4000/v1/embeddings \
-H "Authorization: Bearer ***" -H "Content-Type: application/json" \
-d '{"model": "marengo-3", "input": "a duck", "input_type": "text_image", "media_source": "s3://your-bucket/duck.png"}'
다중 이미지:
curl http://0.0.0.0:4000/v1/embeddings \
-H "Authorization: Bearer ***" -H "Content-Type: application/json" \
-d '{"model": "marengo-3", "input": "a photo of <@bird> on water", "input_type": "multi_input", "media_sources": {"bird": "<base64 image>"}}'
async invoke로 비디오:
from litellm import embedding
response = embedding(
model="bedrock/async_invoke/twelvelabs.marengo-embed-3-0-v1:0",
input=["s3://your-bucket/video.mp4"],
aws_region_name="us-east-1",
input_type="video",
embeddingOption=["visual", "audio"],
segmentation={"method": "fixed", "fixed": {"durationSec": 10}},
output_s3_uri="s3://your-bucket/async-invoke-output/",
)
print(response._hidden_params._invocation_arn)
Amazon Nova Multimodal Embeddings
Amazon Nova는 텍스트, 이미지, 비디오, 오디오용 멀티모달 임베딩을 지원해요. 다양한 용도에 최적화된 유연한 임베딩 차원과 purpose를 제공해요.
지원 기능
- 모달리티: 텍스트, 이미지, 비디오, 오디오
- 차원: 256, 384, 1024, 3072 (기본: 3072)
- 임베딩 Purpose:
GENERIC_INDEX(기본값)GENERIC_RETRIEVALTEXT_RETRIEVALIMAGE_RETRIEVALVIDEO_RETRIEVALAUDIO_RETRIEVALCLASSIFICATIONCLUSTERING
텍스트 임베딩
from litellm import embedding
response = embedding(
model="bedrock/amazon.nova-2-multimodal-embeddings-v1:0",
input=["Hello, world!"],
aws_region_name="us-east-1",
dimensions=1024, # Optional: 256, 384, 1024, or 3072
)
print(response.data[0].embedding)
Base64 이미지 임베딩
Amazon Nova는 표준 data URL 형식으로 base64 이미지를 받아요. 지원 이미지 형식: data:image/jpeg;base64,..., data:image/png;base64,..., data:image/gif;base64,..., data:image/webp;base64,....
import base64
from litellm import embedding
# Method 1: Load image from file
with open("image.jpg", "rb") as image_file:
image_data = base64.b64encode(image_file.read()).decode('utf-8')
# Create data URL with proper format
image_base64 = f"data:image/jpeg;base64,{image_data}"
response = embedding(
model="bedrock/amazon.nova-2-multimodal-embeddings-v1:0",
input=[image_base64],
aws_region_name="us-east-1",
dimensions=1024,
)
print(f"Image embedding: {response.data[0].embedding[:10]}...") # First 10 dimensions
에러 처리가 포함된 완전한 예시
import base64
from litellm import embedding
def get_image_embedding(image_path, dimensions=1024):
"""
Get embedding for an image file.
Args:
image_path: Path to the image file
dimensions: Embedding dimension (256, 384, 1024, or 3072)
Returns:
List of embedding values
"""
try:
# Determine image format from file extension
if image_path.lower().endswith('.png'):
mime_type = "image/png"
elif image_path.lower().endswith(('.jpg', '.jpeg')):
mime_type = "image/jpeg"
elif image_path.lower().endswith('.gif'):
mime_type = "image/gif"
elif image_path.lower().endswith('.webp'):
mime_type = "image/webp"
else:
raise ValueError(f"Unsupported image format: {image_path}")
# Read and encode image
with open(image_path, "rb") as image_file:
image_data = base64.b64encode(image_file.read()).decode('utf-8')
image_base64 = f"data:{mime_type};base64,{image_data}"
# Get embedding
response = embedding(
model="bedrock/amazon.nova-2-multimodal-embeddings-v1:0",
input=[image_base64],
aws_region_name="us-east-1",
dimensions=dimensions,
)
return response.data[0].embedding
except Exception as e:
print(f"Error getting image embedding: {e}")
raise
# Example usage
image_embedding = get_image_embedding("photo.jpg", dimensions=1024)
print(f"Got embedding with {len(image_embedding)} dimensions")
에러 처리 (Error Handling)
일반적인 에러:
| 에러 | 원인 | 해결 |
|---|---|---|
| ValueError: output_s3_uri cannot be empty | S3 출력 URI 누락 | 유효한 S3 URI 제공 |
| ValueError: Input type 'video' requires async_invoke route | async-invoke 없이 비디오/오디오 사용 | bedrock/async_invoke/ 모델 접두사 사용 |
| ValueError: input_type is required | input type 파라미터 누락 | input_type 파라미터 지정 |
try:
response = embedding(
model="bedrock/async_invoke/twelvelabs.marengo-embed-2-7-v1:0",
input=["Hello world"],
aws_region_name="us-east-1",
input_type="text",
output_s3_uri="s3://your-bucket/output/" # Required for async-invoke
)
print("Job submitted successfully!")
except ValueError as e:
if "output_s3_uri cannot be empty" in str(e):
print("Error: Please provide a valid S3 output URI")
elif "requires async_invoke route" in str(e):
print("Error: Use async_invoke model for video/audio inputs")
else:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
모범 사례 (Best Practices)
- 대용량 파일에는 async-invoke 사용: 비디오와 오디오 파일은 비동기 처리가 더 좋아요
- LiteLLM batch API 사용: 상태 확인에 직접 Bedrock API 대신
retrieve_batch()사용 - 작업 상태 주기적 모니터링: batch API로 결과 준비 시점 확인
- 에러를 우아하게 처리: 네트워크 문제와 작업 실패에 대한 적절한 오류 처리 구현
- 적절한 타임아웃 설정: 대용량 파일의 처리 시간을 고려
- 대용량 입력에 S3 사용: 비디오/오디오는 base64 인코딩 대신 S3 URL 사용
제한 사항 (Limitations)
- async-invoke는 TwelveLabs Marengo와 Amazon Nova 모델에 지원
- 결과는 S3에 저장되며 output file ID로 별도로 검색해야 함
- 작업 상태 확인은 LiteLLM의
retrieve_batch()함수 필요 - LiteLLM에 내장 폴링 메커니즘 없음 (자체 상태 확인 루프 구현 필요)
API 키와 기본 사용법
API 키는 환경 변수로 설정하거나 litellm.embedding() 파라미터로 전달할 수 있어요.
import os
os.environ["AWS_ACCESS_KEY_ID"] = "" # Access key
os.environ["AWS_SECRET_ACCESS_KEY"] = "" # Secret access key
os.environ["AWS_REGION_NAME"] = "" # us-east-1, us-east-2, us-west-1, us-west-2
LiteLLM Python SDK:
from litellm import embedding
response = embedding(
model="bedrock/amazon.titan-embed-text-v1",
input=["good morning from litellm"],
)
print(response)
LiteLLM Proxy Server
1. config.yaml 설정:
model_list:
- model_name: titan-embed-v1
litellm_params:
model: bedrock/amazon.titan-embed-text-v1
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-1
- model_name: titan-embed-v2
litellm_params:
model: bedrock/amazon.titan-embed-text-v2:0
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-1
2. Proxy 시작:
litellm --config /path/to/config.yaml
3. OpenAI Python SDK 사용:
import openai
client = openai.OpenAI(
api_key="anything",
base_url="http://0.0.0.0:4000"
)
response = client.embeddings.create(
input=["good morning from litellm"],
model="titan-embed-v1",
)
print(response)
4. LiteLLM Python SDK 사용:
import litellm
response = litellm.embedding(
model="titan-embed-v1", # model alias from config.yaml
input=["good morning from litellm"],
api_base="http://0.0.0.0:4000",
api_key="anything",
)
print(response)
지원되는 AWS Bedrock 임베딩 모델
| 모델 이름 | 사용법 | 지원 추가 OpenAI 파라미터 |
|---|---|---|
| Amazon Nova Multimodal Embeddings | embedding(model="bedrock/amazon.nova-2-multimodal-embeddings-v1:0", input=input) |
멀티모달 입력(텍스트, 이미지, 비디오, 오디오), 여러 purpose, 차원(256, 384, 1024, 3072) |
| Titan Embeddings V2 | embedding(model="bedrock/amazon.titan-embed-text-v2:0", input=input) |
여기 참고 |
| Titan Embeddings - V1 | embedding(model="bedrock/amazon.titan-embed-text-v1", input=input) |
여기 참고 |
| Titan Multimodal Embeddings | embedding(model="bedrock/amazon.titan-embed-image-v1", input=input) |
여기 참고 |
| TwelveLabs Marengo Embed 2.7 | embedding(model="bedrock/us.twelvelabs.marengo-embed-2-7-v1:0", input=input) |
멀티모달 입력(텍스트, 비디오, 오디오, 이미지) |
| TwelveLabs Marengo Embed 3.0 | embedding(model="bedrock/us.twelvelabs.marengo-embed-3-0-v1:0", input=input) |
텍스트, 이미지, text_image, multi_input은 동기, 비디오·오디오는 async invoke, 512차원 |
| Cohere Embeddings - English | embedding(model="bedrock/cohere.embed-english-v3", input=input) |
여기 참고 |
| Cohere Embeddings - Multilingual | embedding(model="bedrock/cohere.embed-multilingual-v3", input=input) |
여기 참고 |
| Cohere Embed v4 | embedding(model="bedrock/cohere.embed-v4:0", input=input) |
텍스트·이미지 입력, 설정 가능한 차원(256, 512, 1024, 1536), 128k 컨텍스트 길이 |