

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 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/zh_cn/bedrock/latest/userguide/model-parameters-embed-v3.html)

**字符数**  
    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-embed-v3.html)
+ **input\_type** – 前缀特殊词元，以区分每种类型。除非混合使用不同类型进行搜索和检索，否则不应将不同的类型混合在一起。在这种情况下，请在语料库中嵌入 `search_document` 类型，并在嵌入式查询中嵌入 `search_query` 类型。
  + `search_document` — 在搜索使用案例中，使用 `search_document` 对存储在向量数据库中的嵌入内容的文档进行编码。
  + `search_query` — 使用 `search_query` 查询向量数据库以查找相关文档。
  + `classification` — 使用 `classification` 将嵌入内容用作文本分类器的输入。
  + `clustering` — 使用 `clustering` 对嵌入内容进行聚类。
  + `images` – 这是一个图像数组。
    + 要嵌入的模型的图像数据 URI 数组。每次调用的最大图像数为 1（即模型仅支持一个图像输入）。
    + 图像必须是有效的数据 URI。图像必须为 image/jpeg 或 image/png 格式，且最大大小为 5 MB。
    + 只能提供“images”或“texts”中的一个。

以下是可选参数：
+  **truncate** – 指定 API 如何处理长度超过最大词元长度的输入。使用以下值之一：
  + `NONE` —（默认）当输入超过最大输入令牌长度时返回错误。
  + `START` – 丢弃输入的开头。
  + `END` — 丢弃输入的结尾。

  如果指定 `START` 或 `END`，则模型会丢弃输入，直到剩余的输入正好达到模型的最大输入令牌长度。
+  **embedding\_types** – 指定您希望模型返回的嵌入类型。可选且默认为 `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\_type** – 响应类型。此值始终为 `embeddings_floats`。
+ **embeddings** — 嵌入内容数组，其中每个嵌入内容是包含 1024 个元素的浮点数数组。`embeddings` 数组的长度将与原 `texts` 数组的长度相同。
+ **texts** – 包含为其返回嵌入内容的文本条目的数组。
+ **images** – 每个图像输入的描述数组。

  `image_description` 采用以下形式：

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

  如果使用图像作为输入，则 `“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()
```