

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

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

**Topics**
+ [Permintaan dan Tanggapan](#model-parameters-embed-v3-request-response)
+ [Contoh kode](#api-inference-examples-cohere-embed-v3)

## Permintaan dan Tanggapan
<a name="model-parameters-embed-v3-request-response"></a>

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

CohereEmbedModel memiliki parameter inferensi berikut. 

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

Berikut ini adalah parameter yang diperlukan.
+ **text** — Sebuah array string untuk model untuk embed. Untuk kinerja optimal, kami sarankan untuk mengurangi panjang setiap teks menjadi kurang dari 512 token. 1 token adalah sekitar 4 karakter.

  Berikut ini adalah teks per panggilan dan batas karakter.

**Teks per panggilan**  
    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/id_id/bedrock/latest/userguide/model-parameters-embed-v3.html)

**Karakter**  
    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/id_id/bedrock/latest/userguide/model-parameters-embed-v3.html)
+ **input\_type** — Menambahkan token khusus untuk membedakan setiap jenis satu sama lain. Anda tidak boleh mencampur jenis yang berbeda bersama-sama, kecuali saat mencampur jenis untuk pencarian dan pengambilan. Dalam hal ini, sematkan korpus Anda dengan `search_document` tipe dan kueri yang disematkan dengan tipe tipe. `search_query` 
  + `search_document`— Dalam kasus penggunaan pencarian, gunakan `search_document` saat Anda menyandikan dokumen untuk penyematan yang Anda simpan dalam database vektor.
  + `search_query`— Gunakan `search_query` saat menanyakan DB vektor Anda untuk menemukan dokumen yang relevan.
  + `classification`— Gunakan `classification` saat menggunakan embeddings sebagai masukan ke pengklasifikasi teks.
  + `clustering`— Gunakan `clustering` untuk mengelompokkan embeddings.
  + `images`- Ini adalah array gambar.
    + Array data gambar URIs untuk model yang akan disematkan. Jumlah maksimum gambar per panggilan adalah 1 (yaitu, model hanya mendukung satu input gambar).
    + Gambar harus berupa URI data yang valid. Gambar harus dalam salah satu image/jpeg atau image/png format dan memiliki ukuran maksimum 5MB.
    + Hanya satu dari “gambar” atau “teks” yang harus disediakan.

Berikut ini adalah parameter opsional:
+  **truncate** — Menentukan bagaimana API menangani input lebih lama dari panjang token maksimum. Gunakan salah satu langkah berikut:
  + `NONE`— (Default) Mengembalikan kesalahan ketika input melebihi panjang token masukan maksimum. 
  + `START`— Buang awal input. 
  + `END`— Buang akhir input.

  Jika Anda menentukan `START` atau`END`, model membuang input hingga input yang tersisa persis dengan panjang token input maksimum untuk model.
+  **embedding\_types** - Menentukan jenis embeddings Anda ingin telah kembali. Opsional dan default adalah`None`, yang mengembalikan jenis `Embed Floats` respons. Bisa satu atau lebih dari jenis berikut:
  + `float`— Gunakan nilai ini untuk mengembalikan embeddings float default. 
  + `int8`— Gunakan nilai ini untuk mengembalikan penyematan int8 yang ditandatangani. 
  + `uint8`— Gunakan nilai ini untuk mengembalikan embeddings int8 yang tidak ditandatangani. 
  + `binary`— Gunakan nilai ini untuk mengembalikan penyematan biner yang ditandatangani. 
  + `ubinary`— Gunakan nilai ini untuk mengembalikan embeddings biner yang tidak ditandatangani. 

Untuk informasi selengkapnya, lihat [https://docs.cohere.com/reference/menyematkan](https://docs.cohere.com/reference/embed) dalam Cohere dokumentasi.

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

`body`Tanggapan dari panggilan ke `InvokeModel` adalah sebagai berikut:

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

`body`Tanggapan memiliki bidang-bidang berikut:
+ **id** — Pengenal untuk respons. 
+ **response\_type — Jenis** respon. Nilai ini selalu `embeddings_floats`. 
+ **Embeddings** — Sebuah array embeddings, di mana setiap embedding adalah array float dengan 1024 elemen. Panjang `embeddings` array akan sama dengan panjang `texts` array asli. 
+ **text** — Sebuah array yang berisi entri teks yang embeddings dikembalikan. 
+ **gambar** — Sebuah array deskripsi untuk setiap input gambar.

  Sebuah `image_description` image\_description adalah dari bentuk ini:

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

  Jika gambar digunakan sebagai input, bidang `“texts”` respon akan menjadi array kosong. Sebaliknya tidak benar (yaitu, ketika teks digunakan, tidak `“images”` akan ada dalam tanggapan)

Untuk informasi selengkapnya, lihat [https://docs.cohere.com/reference/menyematkan.](https://docs.cohere.com/reference/embed)

------

## Contoh kode
<a name="api-inference-examples-cohere-embed-v3"></a>

Contoh ini menunjukkan cara memanggil *CohereEmbed English*model.

```
# 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()
```

**Input Gambar**

```
# 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()
```