

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Cohere Embed および Cohere Embed v4 モデル
<a name="model-parameters-embed"></a>

[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) を使用してEmbed モデルに推論リクエストを行うには、使用するモデルのモデル ID が必要です。モデル ID を取得するには、「[Amazon Bedrock でサポートされている基盤モデル](models-supported.md)」を参照してください。

**注記**  
Amazon Bedrock は Cohere Embed モデルからのストリーミングレスポンスをサポートしていません。

**Topics**
+ [Cohere Embed v4](model-parameters-embed-v4.md)
+ [Cohere Embed v3](model-parameters-embed-v3.md)

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

Cohere Embed v4 は、テキスト入力と画像入力の両方をサポートするマルチモーダル埋め込みモデルです。インターリーブテキストや画像のコンテンツを処理できるため、ドキュメント理解、視覚的検索、マルチモーダル取得のアプリケーションに最適です。このモデルは、float、int8、uint8、binary、ubinary 形式を含むさまざまな埋め込みタイプをサポートしており、256～1536 の出力ディメンションを設定できます。

Cohere Embed v4 のモデル ID は `cohere.embed-v4` です。

**その他の使用上の注意**  

+ **コンテキスト長:** 最大 128,000 トークンがサポートされています。RAG の場合、チャンクを小さくすると取得とコストが向上することがよくあります。
+ **画像のサイズ設定:** 2,458,624 ピクセルを超える画像はそのサイズにダウンサンプリングされ、3,136 ピクセル未満の画像はアップサンプリングされます。
+ **インターリーブ入力:** テキストコンテキスト (ファイル名、エンティティなど) が画像とともに移動するように、ページのようなマルチモーダルコンテンツには input.content[] を優先します。

**Topics**
+ [リクエストとレスポンス](#model-parameters-embed-v4-request-response)
+ [さまざまな input\$1types のリクエストとレスポンス](#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\$1type** (必須) – ユースケースを区別するための特殊なトークンを追加します。`search_document`、`search_query`、`classification`、`clustering` が使用可能です。検索/RAG の場合は、コーパスを `search_document` で埋め込み、クエリを `search_query` で埋め込みます。
+ **texts** (オプション) – 埋め込む文字列の配列。呼び出し 1 件あたり最大 96 です。`texts` を使用する場合は、同じ呼び出しで `images` を送信しないでください。
+ **images** (オプション) – 埋め込む data-URI base64 画像の配列。呼び出し 1 件あたり最大 96 です。`texts` と `images` を一緒に送信しないでください。(インターリーブには `inputs` を使用します。)
+ **inputs** (オプション、混合/融合モダリティ) – 各項目にパートのコンテンツリストが含まれているリスト。各パートは `{ "type": "text", "text": ... }` または `{ "type": "image_url", "image_url": {"url": "data:<mime>;base64,..."} }` です。ページのようなインターリーブコンテンツ (PDF ページの画像とキャプション/メタデータなど) をここで送信します。最大 96 項目です。
+ **embedding\$1types** (オプション) – `float`、`int8`、`uint8`、`binary`、`ubinary` のうち 1 つ以上。省略した場合、float の埋め込みが返されます。
+ **output\$1dimension** (オプション) – ベクトル長を選択します。`256`、`512`、`1024`、`1536` を指定できます (指定しない場合のデフォルトは `1536` です)。
+ **max\$1tokens** (オプション) – 入力オブジェクト 1 つあたりの切り捨て予算。このモデルは最大 128,000 トークンをサポートします。RAG の場合は、適宜チャンクを小さくしてください。
+ **truncate** (オプション) – 長すぎる入力の処理方法: `LEFT` の場合、トークンを先頭からドロップします。`RIGHT` の場合、末尾からドロップします。`NONE` の場合、入力が制限を超えるとエラーを返します。

**制限とサイズ設定**  

+ 1 リクエストあたりの項目: 最大 96 個の画像。元の画像ファイルタイプは png、jpeg、webp、gif のいずれかの形式である必要があり、サイズは最大 5 MB です。
+ リクエストサイズの上限: 合計ペイロードで最大 20 MB。
+ 最大入力トークン: 最大 128,000 トークン。画像ファイルはトークンに変換され、トークンの合計数が 128,000 未満である必要があります。
+ 画像: 2,458,624 ピクセルを超えるとダウンサンプリングされます。3,136 ピクセル未満の画像はアップサンプリングされます。画像は `data:<mime>;base64,....` として指定します
+ トークンアカウンティング (`inputs` 項目 1 つあたり): 画像入力のトークン数 ≈ (画像のピクセル数 ÷ 784) x インターリーブテキストと画像入力からの 4 トークン = (画像のピクセル数 ÷ 784) x 4 \$1 (テキストトークン数)

**ヒント:** PDF の場合、各ページを画像に変換し、隣接するテキスト部分のページメタデータ (file\$1name、エンティティなど) とともに `inputs` 経由で送信します。

------
#### [ Response ]

コンテンツタイプ: application/json

1 つの埋め込みタイプ (例: `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\$1types のリクエストとレスポンス
<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) テキストのみのコーパスインデックス作成 (デフォルトの float、1536 ディメンション)**

**リクエスト**  


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

------

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

**Topics**
+ [リクエストとレスポンス](#model-parameters-embed-v3-request-response)
+ [コード例](#api-inference-examples-cohere-embed-v3)

## リクエストとレスポンス
<a name="model-parameters-embed-v3-request-response"></a>

------
#### [ Request ]

Cohere Embed モデルには次の推論パラメータがあります。

```
{
    "input_type": "search_document|search_query|classification|clustering|image",
    "texts":[string],
    "images":[image_base64_image_uri]
    "truncate": "NONE|START|END",
    "embedding_types": embedding_types
}
```

必須パラメータを以下に示します。
+ **texts** – 埋め込むモデルの文字列の配列。最適なパフォーマンスを得るには、各テキストの長さを 512 トークン未満に減らすことをお勧めします。1 トークンは約 4 文字です。

  以下は、呼び出しおよび文字あたりのテキスト数の制限です。

**呼び出しあたりのテキスト**  
    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-embed-v3.html)

**文字**  
    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-embed-v3.html)
+ **input\$1type** – 特殊なトークンを先頭に付加して、タイプ同士を区別します。検索と取得の間でタイプを混在させる場合を除いて、異なるタイプを混在させないでください。そのような場合、`search_document` タイプにはコーパスを、`search_query` タイプには埋め込みクエリを埋め込みます。
  + `search_document` - 検索のユースケースで、ベクトルデータベースに保存する埋め込み用のドキュメントをエンコードするときに、`search_document` を使用します。
  + `search_query` - ベクトル DB にクエリを実行して関連ドキュメントを検索する場合に `search_query` を使用します。
  + `classification` - 埋め込みをテキスト分類子への入力として使用する場合に `classification` を使用します。
  + `clustering` - 埋め込みをクラスター化する場合に `clustering` を使用します。
  + `images` – これは画像の配列です。
    + 埋め込むモデルの画像データ URI の配列。呼び出し 1 件あたりの画像の最大数は 1 です (つまり、モデルは 1 つの画像入力のみをサポートします)。
    + 画像は有効なデータ URI である必要があります。画像は、image/jpeg 形式または image/png 形式である必要があり、最大サイズは 5MB です。
    + "images" と "texts" のいずれか一方のみを指定する必要があります。

オプションのパラメータを以下に示します。
+  **truncate** – トークンの最大長を超える入力を API がどのように処理するかを指定します。以下のいずれかを使用します。
  + `NONE` - (デフォルト) 入力が入力トークンの最大長を超えるとエラーを返します。
  + `START` - 入力の先頭部分を切り捨てます。
  + `END` - 入力の末尾部分を切り捨てます。

  `START` または `END` を指定すると、入力の長さがモデルの入力トークンの最大長とまったく同じになるまで、モデルが入力内容を切り捨てます。
+  **embedding\$1types** — 返したい埋め込みのタイプを指定します。オプションとデフォルトは、`None` で、`Embed Floats` レスポンスタイプを返します。タイプは次のいずれかになります。
  + `float` – この値を使用して、デフォルトのフロート埋め込みを返します。
  + `int8` – この値を使用して、署名付き int8 埋め込みを返します。
  + `uint8` – この値を使用して、署名なし int8 埋め込みを返します。
  + `binary` – この値を使用して、署名付きバイナリ埋め込みを返します。
  + `ubinary` – この値を使用して、署名なしバイナリ埋め込みを返します。

詳細については、「Cohere ドキュメント」の [https://docs.cohere.com/reference/embed](https://docs.cohere.com/reference/embed) を参照してください。

------
#### [ Response ]

`InvokeModel` を呼び出した場合の `body` レスポンスを以下に示します。

```
{
    "embeddings": [
        [ array of 1024 floats. ]
    ],
    "id": string,
    "response_type" : "embeddings_floats,
    "texts": [string],
    "images": [image_description]
}
```

`body` レスポンスに指定できるフィールドについて説明します。
+ **id** - レスポンスの識別子。
+ **response\$1type** – レスポンスタイプ。この値は常に `embeddings_floats` です。
+ **embeddings** - 埋め込みの配列。各埋め込みは 1,024 個の要素から成る、浮動小数点数の配列です。`embeddings` 配列の長さは 元の `texts` 配列の長さと同じになります。
+ **texts** - 埋め込みが返されたテキストエントリから成る配列。
+ **images** – 各画像入力の説明の配列。

  `image_description`image\$1description は、次の形式を取ります。

  ```
  {
      "width": long,
      "height": long,
      "format": string,
      "bit_depth": long
  }
  ```

  画像を入力として使用した場合、`“texts”` レスポンスフィールドは空の配列になります。これは逆のケースには当てはまりません (つまり、texts が使用されている場合、`“images”` はレスポンスに含まれません)

詳細については、[https://docs.cohere.com/reference/embed](https://docs.cohere.com/reference/embed) を参照してください。

------

## コード例
<a name="api-inference-examples-cohere-embed-v3"></a>

この例は、*Cohere Embed English* モデルを呼び出す方法を示しています。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate text embeddings using the Cohere Embed English 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-english-v3'
    text1 = "hello world"
    text2 = "this is a test"
    input_type = "search_document"
    embedding_types = ["int8", "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()
```

**画像入力**

```
# 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 English 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_image_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"

    model_id = 'cohere.embed-english-v3'
    input_type = "image"
    images = [get_base64_image_uri(image_file_path, image_mime_type)]
    embedding_types = ["int8", "float"]

    try:
        body = json.dumps({
            "images": images,
            "input_type": input_type,
            "embedding_types": embedding_types
        })
        
        response = generate_image_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()
```