기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
Cohere 임베드 v4
Cohere Embed v4는 텍스트 및 이미지 입력을 모두 지원하는 멀티모달 임베딩 모델입니다. 인터리브 텍스트 및 이미지 콘텐츠를 처리할 수 있으므로 문서 이해, 시각적 검색 및 멀티모달 검색 애플리케이션에 적합합니다. 모델은 float, int8, uint8, 바이너리 및 ubinary 형식을 비롯한 다양한 임베딩 유형을 지원하며, 구성 가능한 출력 차원은 256~1536입니다.
의 모델 ID는 Cohere Embed v4입니다cohere.embed-v4.
추가 사용 정보
-
컨텍스트 길이: 최대 ~128,000개의 토큰이 지원됩니다. RAG의 경우 작은 청크는 검색 및 비용을 개선하는 경우가 많습니다.
-
이미지 크기 조정: 이미지 > 2,458,624픽셀은 해당 크기로 다운샘플링되고 이미지 < 3,136픽셀은 업샘플링됩니다.
-
인터리브 입력: 텍스트 컨텍스트(예: 파일 이름, 개체)가 이미지와 함께 이동하도록 페이지와 같은 멀티모달 콘텐츠의 경우 input.content[]를 선호합니다.
요청 및 응답
- Request
-
콘텐츠 유형: application/json
{
"input_type": "search_document | search_query | classification | clustering",
"texts": ["..."], // optional; text-only
"images": ["data:<mime>;base64,..."], // optional; image-only
"inputs": [
{ "content": [
{ "type": "text", "text": "..." },
{ "type": "image_url", "image_url": "data:<mime>;base64,..." }
]
}
], // optional; mixed (interleaved) text+image
"embedding_types": ["float" | "int8" | "uint8" | "binary" | "ubinary"],
"output_dimension": 256 | 512 | 1024 | 1536,
"max_tokens": 128000,
"truncate": "NONE | LEFT | RIGHT"
}
파라미터
-
input_type(필수) - 특수 토큰을 추가하여 사용 사례를 구분합니다. 허용: search_document, search_query, classification, clustering. search/RAG의 경우에 코퍼스를 포함하고 search_document에 쿼리를 포함합니다search_query.
-
texts(선택 사항) - 포함할 문자열 배열입니다. 호출당 최대 96개. 를 사용하는 경우 동일한 호출images로 전송하지 texts마십시오.
-
이미지(선택 사항) - 포함할 data-URI base64 이미지의 배열입니다. 호출당 최대 96개. texts 및를 images 함께 보내지 마십시오. ( 인터리브inputs에 사용)
-
입력(선택 사항, 혼합/혼합 양식) - 각 항목에 부분 콘텐츠 목록이 있는 목록입니다. 각 부분은 { "type": "text", "text": ... } 또는 입니다{ "type": "image_url", "image_url": "data:<mime>;base64,..." }. 인터리브 페이지와 유사한 콘텐츠를 여기에서 전송합니다(예: PDF 페이지 이미지 + 캡션/메타데이터). 최대 96개 항목.
-
embedding_types(선택 사항) - float, , int8, uint8binary, 중 하나 이상입니다ubinary. 생략하면 부동 소수점 임베딩을 반환합니다.
-
output_dimension(선택 사항) - 벡터 길이를 선택합니다. 허용됨: 256, 512, 1024, 1536 (지정되지 않은 1536 경우 기본값).
-
max_tokens(선택 사항) - 입력 객체당 자르기 예산입니다. 모델은 최대 128,000개의 토큰을 지원하며, RAG의 경우 청크 크기가 더 작습니다.
-
잘라내기(선택 사항) - 길이가 긴 입력을 처리하는 방법: 시작에서 토큰을 LEFT 삭제하고, 끝에서 토큰을 RIGHT 삭제하고, 입력이 제한을 초과하면 오류를 NONE 반환합니다.
제한 및 크기 조정
-
요청당 항목: 최대 96개의 이미지. 원본 이미지 파일 형식은 png, jpeg, webp 또는 gif 형식이어야 하며 최대 5MB까지 가능합니다.
-
요청 크기 한도: 최대 20MB의 총 페이로드.
-
최대 입력 토큰: 최대 128,000개의 토큰 이미지 파일은 토큰으로 변환되며 총 토큰은 128k 미만이어야 합니다.
-
이미지: 다운샘플링 전 최대 2,458,624픽셀, 3,136픽셀 미만의 이미지는 업샘플링됩니다. 이미지를 로 제공 data:<mime>;base64,....
-
토큰 회계(inputs항목당): 이미지 입력의 토큰 "(이미지 픽셀 ÷ 784) x 4 인터리브 텍스트 및 이미지 입력의 토큰 = (이미지 픽셀 ÷ 784) x 4 + (텍스트 토큰)
팁: PDFs 경우 각 페이지를 이미지로 변환하고 페이지 메타데이터(예: file_name, 엔터티)와 inputs 함께 인접한 텍스트 부분으로를 통해 전송합니다.
- Response
-
콘텐츠 유형: application/json
단일 임베딩 유형을 요청한 경우(예: 만 해당float):
{
"id": "string",
"embeddings": [[ /* length = output_dimension */ ]],
"response_type": "embeddings_floats",
"texts": ["..."], // present if text was provided
"inputs": [ { "content": [ ... ] } ] // present if 'inputs' was used
}
여러 임베딩 유형(예: ["float","int8"])을 요청한 경우:
{
"id": "string",
"embeddings": {
"float": [[ ... ]],
"int8": [[ ... ]]
},
"response_type": "embeddings_by_type",
"texts": ["..."], // when text used
"inputs": [ { "content": [ ... ] } ] // when 'inputs' used
}
다양한 input_types에 대한 요청 및 응답
A) 압축 int8 벡터가 있는 인터리브 페이지(이미지 + 캡션)
요청
{
"input_type": "search_document",
"inputs": [
{
"content": [
{ "type": "text", "text": "Quarterly ARR growth chart; outlier in Q3." },
{ "type": "image_url", "image_url": "data:image/png;base64,{{BASE64_PAGE_IMG}}" }
]
}
],
"embedding_types": ["int8"],
"output_dimension": 512,
"truncate": "RIGHT",
"max_tokens": 128000
}
응답(잘림)
{
"id": "836a33cc-61ec-4e65-afaf-c4628171a315",
"embeddings": { "int8": [[ 7, -3, ... ]] },
"response_type": "embeddings_by_type",
"inputs": [
{ "content": [
{ "type": "text", "text": "Quarterly ARR growth chart; outlier in Q3." },
{ "type": "image_url", "image_url": "data:image/png;base64,{{...}}" }
] }
]
}
B) 텍스트 전용 코퍼스 인덱싱(기본 부동 소수점, 1536-dim)
요청
{
"input_type": "search_document",
"texts": [
"RAG system design patterns for insurance claims",
"Actuarial loss triangles and reserving primer"
]
}
응답(샘플)
{
"response_type": "embeddings_floats",
"embeddings": [
[0.0135, -0.0272, ...], // length 1536
[0.0047, 0.0189, ...]
]
}
코드 예제
- Text input
-
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate embeddings using the Cohere Embed v4 model.
"""
import json
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def generate_text_embeddings(model_id, body, region_name):
"""
Generate text embedding by using the Cohere Embed model.
Args:
model_id (str): The model ID to use.
body (str) : The reqest body to use.
region_name (str): The AWS region to invoke the model on
Returns:
dict: The response from the model.
"""
logger.info("Generating text embeddings with the Cohere Embed model %s", model_id)
accept = '*/*'
content_type = 'application/json'
bedrock = boto3.client(service_name='bedrock-runtime', region_name=region_name)
response = bedrock.invoke_model(
body=body,
modelId=model_id,
accept=accept,
contentType=content_type
)
logger.info("Successfully generated embeddings with Cohere model %s", model_id)
return response
def main():
"""
Entrypoint for Cohere Embed example.
"""
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
region_name = 'us-east-1'
model_id = 'cohere.embed-v4:0'
text1 = "hello world"
text2 = "this is a test"
input_type = "search_document"
embedding_types = ["float"]
try:
body = json.dumps({
"texts": [
text1,
text2],
"input_type": input_type,
"embedding_types": embedding_types
})
response = generate_text_embeddings(model_id=model_id, body=body, region_name=region_name)
response_body = json.loads(response.get('body').read())
print(f"ID: {response_body.get('id')}")
print(f"Response type: {response_body.get('response_type')}")
print("Embeddings")
embeddings = response_body.get('embeddings')
for i, embedding_type in enumerate(embeddings):
print(f"\t{embedding_type} Embeddings:")
print(f"\t{embeddings[embedding_type]}")
print("Texts")
for i, text in enumerate(response_body.get('texts')):
print(f"\tText {i}: {text}")
except ClientError as err:
message = err.response["Error"]["Message"]
logger.error("A client error occurred: %s", message)
print("A client error occured: " +
format(message))
else:
print(
f"Finished generating text embeddings with Cohere model {model_id}.")
if __name__ == "__main__":
main()
- Mixed modalities
-
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate image embeddings using the Cohere Embed v4 model.
"""
import json
import logging
import boto3
import base64
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def get_base64_image_uri(image_file_path: str, image_mime_type: str):
with open(image_file_path, "rb") as image_file:
image_bytes = image_file.read()
base64_image = base64.b64encode(image_bytes).decode("utf-8")
return f"data:{image_mime_type};base64,{base64_image}"
def generate_embeddings(model_id, body, region_name):
"""
Generate image embedding by using the Cohere Embed model.
Args:
model_id (str): The model ID to use.
body (str) : The reqest body to use.
region_name (str): The AWS region to invoke the model on
Returns:
dict: The response from the model.
"""
logger.info("Generating image embeddings with the Cohere Embed model %s", model_id)
accept = '*/*'
content_type = 'application/json'
bedrock = boto3.client(service_name='bedrock-runtime', region_name=region_name)
response = bedrock.invoke_model(
body=body,
modelId=model_id,
accept=accept,
contentType=content_type
)
logger.info("Successfully generated embeddings with Cohere model %s", model_id)
return response
def main():
"""
Entrypoint for Cohere Embed example.
"""
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
region_name = 'us-east-1'
image_file_path = "image.jpg"
image_mime_type = "image/jpg"
text = "hello world"
model_id = 'cohere.embed-v4:0'
input_type = "search_document"
image_base64_uri = get_base64_image_uri(image_file_path, image_mime_type)
embedding_types = ["int8","float"]
try:
body = json.dumps({
"inputs": [
{
"content": [
{ "type": "text", "text": text },
{ "type": "image_url", "image_url": "data:image/png;base64,{{image_base64_uri}}" }
]
}
],
"input_type": input_type,
"embedding_types": embedding_types
})
response = generate_embeddings(model_id=model_id, body=body, region_name=region_name)
response_body = json.loads(response.get('body').read())
print(f"ID: {response_body.get('id')}")
print(f"Response type: {response_body.get('response_type')}")
print("Embeddings")
embeddings = response_body.get('embeddings')
for i, embedding_type in enumerate(embeddings):
print(f"\t{embedding_type} Embeddings:")
print(f"\t{embeddings[embedding_type]}")
print("inputs")
for i, input in enumerate(response_body.get('inputs')):
print(f"\tinput {i}: {input}")
except ClientError as err:
message = err.response["Error"]["Message"]
logger.error("A client error occurred: %s", message)
print("A client error occured: " +
format(message))
else:
print(
f"Finished generating embeddings with Cohere model {model_id}.")
if __name__ == "__main__":
main()