Cohere Embed v4 - Amazon Bedrock

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Cohere Embed v4

Cohere Embed v4est un modèle d'intégration multimodal qui prend en charge les entrées de texte et d'image. Il peut traiter le contenu de texte et d'image entrelacé, ce qui le rend idéal pour les applications de compréhension de documents, de recherche visuelle et de récupération multimodale. Le modèle prend en charge différents types d'intégration, notamment les formats float, int8, uint8, binaire et ubinary, avec des dimensions de sortie configurables comprises entre 256 et 1536.

L'identifiant du modèle pour Cohere Embed v4 estcohere.embed-v4.

Remarques d'utilisation supplémentaires

  • Longueur du contexte : Jusqu'à 128 000 jetons sont pris en charge ; pour RAG, les petits morceaux améliorent souvent la récupération et les coûts.

  • Dimensionnement de l'image : les images > 2 458 624 pixels sont sous-échantillonnées à cette taille ; les images < 3 136 pixels sont suréchantillonnées.

  • Entrées entrelacées : préférez inputs.content [] pour un contenu multimodal semblable à une page afin que le contexte du texte (par exemple, nom de fichier, entités) voyage avec l'image.

Demande et réponse

Request

Type de contenu : 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" }
Paramètres

  • input_type (obligatoire) — Ajoute des jetons spéciaux pour distinguer les cas d'utilisation. Autorisé :search_document,search_query,classification,clustering. Pour Search/RAG, intégrez votre corpus et vos requêtes avecsearch_document. search_query

  • texts (facultatif) — Tableau de chaînes à intégrer. 96 maximum par appel. Si vous l'utiliseztexts, n'envoyez images pas le même appel.

  • images (facultatif) — Tableau d'images Data-URI base64 à intégrer. 96 maximum par appel. N'envoyez pas texts et images ensemble. (À utiliser inputs pour entrelacé.)

  • entrées (facultatif ; mixed/fused modalité) — Une liste où chaque élément possède une liste de contenu de parties. Chaque partie est { "type": "text", "text": ... } ou{ "type": "image_url", "image_url": "data:<mime>;base64,..." }. Envoyez du contenu entrelacé semblable à une page ici (par exemple, image de page PDF avec sous-titre/métadonnées). 96 articles maximum.

  • embedding_types (facultatif) — Un ou plusieurs des éléments suivants :float,,,,. int8 uint8 binary ubinary En cas d'omission, renvoie des intégrations flottantes.

  • output_dimension (facultatif) — Sélectionnez la longueur du vecteur. Autorisé :256, 5121024, 1536 (par défaut 1536 s'il n'est pas spécifié).

  • max_tokens (facultatif) — Budget de troncature par objet d'entrée. Le modèle prend en charge jusqu'à 128 000 jetons ; un peu plus petit pour RAG, le cas échéant.

  • truncate (facultatif) — Comment gérer les entrées trop longues : LEFT supprime les jetons depuis le début ; RIGHT supprime les jetons depuis la fin ; NONE renvoie une erreur si l'entrée dépasse la limite.

Limites et tailles

  • Articles par demande : jusqu'à 96 images. Le type de fichier image d'origine doit être au format png, jpeg, webp ou gif et sa taille peut atteindre 5 Mo.

  • Limite de taille de demande : ~20 Mo de charge utile totale.

  • Nombre maximum de jetons d'entrée : 128 000 jetons maximum Les fichiers image sont convertis en jetons, et le nombre total de jetons doit être inférieur à 128 000.

  • Images : maximum 2 458 624 pixels avant sous-échantillonnage ; les images inférieures à 3 136 pixels sont suréchantillonnées. Fournissez des images sous forme de data:<mime>;base64,....

  • Comptabilité des jetons (par inputs élément) : jetons provenant d'une entrée d'image ≈ (pixels d'image ÷ 784) x 4 jetons provenant d'une entrée de texte et d'image entrelacés = (pixels d'image ÷ 784) x 4 + (jetons de texte)

Conseil : Pour PDFs, convertissez chaque page en image et envoyez-la inputs avec les métadonnées de la page (par exemple, nom_fichier, entités) dans les parties de texte adjacentes.

Response

Type de contenu : application/json

Si vous avez demandé un seul type d'intégration (par exemple, uniquementfloat) :

{ "id": "string", "embeddings": [[ /* length = output_dimension */ ]], "response_type": "embeddings_floats", "texts": ["..."], // present if text was provided "inputs": [ { "content": [ ... ] } ] // present if 'inputs' was used }

Si vous avez demandé plusieurs types d'intégration (par exemple,["float","int8"]) :

{ "id": "string", "embeddings": { "float": [[ ... ]], "int8": [[ ... ]] }, "response_type": "embeddings_by_type", "texts": ["..."], // when text used "inputs": [ { "content": [ ... ] } ] // when 'inputs' used }
  • Le nombre de vecteurs renvoyés correspond à la longueur de votre texts tableau ou au nombre d'inputséléments.

  • La longueur de chaque vecteur est égale output_dimension (par défaut1536).

Demande et réponse pour différents types d'entrées

A) Page entrelacée (image + légende) avec des vecteurs int8 compacts

Demande

{ "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 }
Réponse (tronquée)

{ "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) Indexation de corpus en texte uniquement (float par défaut, 1536-dim)

Demande

{ "input_type": "search_document", "texts": [ "RAG system design patterns for insurance claims", "Actuarial loss triangles and reserving primer" ] }
Réponse (échantillon)

{ "response_type": "embeddings_floats", "embeddings": [ [0.0135, -0.0272, ...], // length 1536 [0.0047, 0.0189, ...] ] }

Exemples de code

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