

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Cohere Embed v4
<a name="model-parameters-embed-v4"></a>

Cohere Embed v4는 텍스트 및 이미지 입력을 모두 지원하는 멀티모달 임베딩 모델입니다. 인터리브 텍스트 및 이미지 콘텐츠를 처리할 수 있으므로 문서 이해, 시각적 검색 및 멀티모달 검색 애플리케이션에 이상적입니다. 모델은 float, int8, uint8, 바이너리 및 ubinary 형식을 비롯한 다양한 임베딩 유형을 지원하며, 구성 가능한 출력 차원은 256\~1536입니다.

Cohere Embed v4의 모델 ID는 `cohere.embed-v4`입니다.

**추가 사용 정보**  

+ **컨텍스트 길이:** 문서당 최대 128,000개의 토큰. RAG의 경우 청크가 작을수록 검색 및 비용이 향상되는 경우가 많습니다.
+ **Image sizing:** 이미지 > 2,458,624픽셀은 해당 크기로 다운샘플링되고, 이미지 < 3,136픽셀은 업샘플링됩니다.
+ **Interleaved inputs:** 텍스트 컨텍스트(예: 파일 이름, 개체)가 이미지와 함께 이동하도록 페이지와 같은 멀티모달 콘텐츠의 경우 input.content[]를 선호합니다.

**Topics**
+ [요청 및 응답](#model-parameters-embed-v4-request-response)
+ [다양한 input\_types에 대한 요청 및 응답](#api-inference-examples-cohere-embed-v4)
+ [코드 예제](#code-examples-cohere-embed-v4)

## 요청 및 응답
<a name="model-parameters-embed-v4-request-response"></a>

------
#### [ 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": {"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개입니다. `texts`를 사용하는 경우 동일한 직접 호출로 `images`를 보내지 마세요.
+ **images**(선택 사항) - 포함할 data-URI base64 이미지의 배열입니다. 직접 호출당 최대 96개입니다. `texts` 및 `images`를 함께 보내지 마세요. (인터리브에 `inputs` 사용)
+ **inputs**(선택 사항, 혼합/혼합 양식) - 각 항목에 부분 콘텐츠 목록이 있는 목록입니다. 각 파트는 `{ "type": "text", "text": ... }` 또는 `{ "type": "image_url", "image_url": {"url": "data:<mime>;base64,..."} }`입니다. 인터리브 페이지와 유사한 콘텐츠를 여기에서 전송합니다(예: PDF 페이지 이미지 \+ 캡션/메타데이터). 최대 96개입니다.
+ **embedding\_types**(선택 사항) - `float`, `int8`, `uint8`, `binary`, `ubinary` 중 하나 이상입니다. 생략하면 부동 소수점 임베딩을 반환합니다.
+ **output\_dimension**(선택 사항) - 벡터 길이를 선택합니다. `256`, `512`, `1024`, `1536`을 허용합니다(지정되지 않은 경우 기본값 `1536`).
+ **max\_tokens**(선택 사항) - 입력 문서당 자르기 예산입니다. 모델은 문서당 최대 128,000개의 토큰을 지원하며, 필요에 따라 RAG에 대해 더 작은 청크를 지원합니다.
+ **truncate**(선택 사항) - 길이가 긴 입력을 처리하는 방법: 시작에서 `LEFT`에서 토큰을 삭제하고, 끝에서 `RIGHT`에서 토큰을 삭제하고, 입력이 제한을 초과하면 `NONE`에서 오류를 반환합니다.

**제한 및 크기 조정**  

+ 요청당 항목은 최대 96개의 이미지입니다. 원본 이미지 파일 형식은 png, jpeg, webp 또는 gif 형식이어야 하며 최대 5MB까지 가능합니다.
+ 요청 크기 한도는 최대 20MB의 총 페이로드입니다.
+ 최대 입력 토큰은 최대 128,000개의 토큰 이미지 파일은 토큰으로 변환되며 총 토큰은 128,000개 미만이어야 합니다.
+ 이미지: 다운샘플링 전 최대 2,458,624픽셀, 3,136픽셀 미만의 이미지는 업샘플링됩니다. `data:<mime>;base64,....`로 이미지 제공
+ 토큰 회계(`inputs` 항목당): 이미지 입력의 토큰 ≈ (이미지 픽셀 ÷ 784) x 4 텍스트와 이미지가 섞인 입력의 토큰 = (이미지 픽셀 ÷ 784) x 4 \+ (텍스트 토큰)

**팁:** PDF의 경우 각 페이지를 이미지로 변환하고 페이지 메타데이터(예: 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
}
```
+ 반환된 벡터 수는 `texts` 배열의 길이 또는 `inputs` 항목 수와 일치합니다.
+ 각 벡터의 길이는 `output_dimension`과 같습니다(기본값 `1536`).

------

## 다양한 input\_types에 대한 요청 및 응답
<a name="api-inference-examples-cohere-embed-v4"></a>

**A) 압축 int8 벡터가 있는 인터리브 페이지(이미지 \+ 캡션)**

**요청**  


```
{
  "input_type": "search_document",
  "inputs": [
    {
      "content": [
        { "type": "text", "text": "Quarterly ARR growth chart; outlier in Q3." },
        { "type": "image_url", "image_url": {"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": {"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, ...]
  ]
}
```

## 코드 예제
<a name="code-examples-cohere-embed-v4"></a>

------
#### [ 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": {"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()
```

------