Cohere Embed v4 - Amazon Bedrock

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Cohere Embed v4

Cohere Embed v4 è un modello di embedding multimodale che supporta input di testo e immagini. È in grado di elaborare contenuti interlacciati di testo e immagini ed è quindi ideale per le applicazioni di comprensione di documenti, di ricerca visiva e di recupero multimodale. Il modello supporta vari tipi di embedding, tra cui i formati float, int8, uint8, binary e ubinary, con dimensioni di output configurabili da 256 a 1536.

L’ID modello per Cohere Embed v4 è cohere.embed-v4.

Note per l’utilizzo aggiuntive

  • Lunghezza del contesto: sono supportati fino a ~128.000 token; in caso di RAG, blocchi più piccoli spesso migliorano il recupero e i costi.

  • Dimensionamento delle immagini: le immagini con più di 2.458.624 pixel vengono sottocampionate fino a quelle dimensioni; le immagini con meno di 3.136 pixel vengono sovracampionate.

  • Input interlacciati: si preferisce il formato inputs.content[] per contenuti multimodali simili a pagine in modo che il contesto del testo, ad esempio nome file o entità, sia gestito con l’immagine.

Richiesta e risposta

Request

Tipo di contenuto: 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" }
Parametri

  • input_type (necessario): aggiunge token speciali per distinguere i casi d’uso. Valori consentiti: search_document, search_query, classification, clustering. Per ricerca/RAG, integra il corpus con search_document e le query con search_query.

  • texts (facoltativo): array di stringhe da incorporare. Il numero massimo per chiamata è 96. Se utilizzi texts, non inviare images nella stessa chiamata.

  • images (facoltativo): array di immagini con URI dati base64 da incorporare. Il numero massimo per chiamata è 96. Non inviare texts e images insieme. Usa inputs per l’interlacciamento.

  • inputs (facoltativo, modalità mista/fusa): elenco in cui ogni elemento ha un elenco di parti del contenuto. Ogni parte è { "type": "text", "text": ... } o { "type": "image_url", "image_url": "data:<mime>;base64,..." }. Invia qui contenuti interlacciati simili a pagine (ad esempio l’immagine della pagina PDF più didascalia/metadati). Il numero massimo di elementi è 96.

  • embedding_types (facoltativo): uno o più dei valori float, int8, uint8, binary, ubinary. Se omesso, restituisce embedding di tipo float.

  • output_dimension (facoltativo): determina la lunghezza del vettore. Valori consentiti: 256, 512, 1024, 1536 (se non specificato, il valore predefinito è 1536).

  • max_tokens (facoltativo): budget per il troncamento per oggetto di input. Il modello supporta fino a ~128.000 token; blocchi più piccoli per RAG, se appropriato.

  • truncate (facoltativo): consente di gestire gli input di lunghezza eccessiva. I valori consentiti sono: LEFT (elimina i token a partire dall’inizio), RIGHT (elimina i token a partire dalla fine), NONE (restituisce un errore se l’input supera il limite).

Limiti e dimensionamento

  • Elementi per richiesta: fino a 96 immagini. Il tipo di file di immagine originale deve essere png, jpeg, webp o gif e può avere una dimensione massima di 5 MB.

  • Dimensione massima della richiesta: ~20 MB di payload totale.

  • Numero massimo di token di input: 128.000 token. I file di immagine vengono convertiti in token, il cui totale deve essere inferiore a 128.000.

  • Immagini: massimo 2.458.624 pixel prima del sottocampionamento; le immagini di dimensioni inferiori a 3.136 pixel vengono sovracampionate. Le immagini devono essere fornite come data:<mime>;base64,....

  • Conteggio dei token (per elemento inputs): token provenienti da un input di immagine ≈ (pixel dell’immagine ÷ 784) x 4 token da un input di testo e immagine interlacciati = (pixel dell’immagine ÷ 784) x 4 + (token di testo)

Suggerimento: per i file PDF, converti ogni pagina in un’immagine e inviala tramite inputs con i metadati della pagina (ad esempio nome file, entità) in parti di testo adiacenti.

Response

Tipo di contenuto: application/json

Se è stato richiesto un solo tipo di embedding, ad esempio solo float:

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

Se sono stati richiesti più tipi di embedding, ad esempio ["float","int8"]:

{ "id": "string", "embeddings": { "float": [[ ... ]], "int8": [[ ... ]] }, "response_type": "embeddings_by_type", "texts": ["..."], // when text used "inputs": [ { "content": [ ... ] } ] // when 'inputs' used }
  • Il numero di vettori restituiti corrisponde alla lunghezza dell’array textso al numero di elementi inputs.

  • La lunghezza di ogni vettore è uguale a output_dimension (valore predefinito 1536).

Richiesta e risposta per diversi elementi input_types

A) Pagina interlacciata (immagine + didascalia) con vettori int8 compatti

Richiesta

{ "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 }
Risposta (troncata)

{ "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) Indicizzazione del corpus in solo testo (valori predefiniti: float, dimensioni 1536)

Richiesta

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

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

Codici di esempio

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