Cohere Embed v4 - Amazon Bedrock

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Cohere Embed v4

O Cohere Embed v4 é um modelo de incorporação multimodal que comporta entradas de texto e imagem. Ele pode processar conteúdo intercalado de texto e imagem, o que o torna ideal para aplicações de compreensão de documentos, pesquisa visual e recuperação multimodal. O modelo comporta vários tipos de incorporação, como formatos float, int8, uint8, binário e ubinário, com dimensões de saída configuráveis de 256 a 1.536.

O ID de modelo do Cohere Embed v4 é cohere.embed-v4.

Observações adicionais sobre o uso

  • Tamanho do contexto: são aceitos aproximadamente 128 mil tokens; para RAG, fragmentos menores geralmente melhoram a recuperação e o custo.

  • Dimensionamento da imagem: imagens > 2.458.624 pixels têm resolução reduzida para esse tamanho; imagens com menos de 3.136 pixels são ampliadas.

  • Entradas intercaladas: prefira inputs.content[] para conteúdo multimodal semelhante a uma página, para que o contexto textual (p. ex., nome do arquivo, entidades) seja correlacionado à imagem.

Solicitação e reposta

Request

Tipo de conteúdo: 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" }
Parâmetros

  • input_type: (obrigatório) adiciona tokens especiais para distinguir casos de uso. Permitidos: search_document, search_query, classification e clustering. Para pesquisa/RAG, incorpore o corpo com search_document e as consultas com search_query.

  • texts: (opcional) matriz de strings a serem incorporadas. No máximo 96 por chamada. Se você usar texts, não envie images na mesma chamada.

  • images: (opcional) matriz de imagens data-URI em base64 para incorporar. No máximo 96 por chamada. Não envie texts e images juntos. (Use inputs para intercalação.)

  • inputs: (opcional; modalidade mista/fundida) uma lista em que cada item tem uma lista de partes do conteúdo. Cada parte é { "type": "text", "text": ... } ou { "type": "image_url", "image_url": "data:<mime>;base64,..." }. Envie conteúdo intercalado semelhante a uma página aqui (p. ex., imagem da página em PDF + legenda/metadados). Máximo de 96 itens.

  • embedding_types: (opcional) um ou mais float, int8, uint8, binary e ubinary. Se omitido, exibe incorporações de número flutuante.

  • output_dimension: (opcional) selecione o tamanho do vetor. Permitido: 256, 512, 1024 e 1536 (o padrão é 1536, se especificado).

  • max_tokens: (opcional) limite para truncamento por objeto de entrada. O modelo comporta em torno de 128 mil tokens, no máximo, e um fragmento menor para RAG, conforme apropriado.

  • truncate: (opcional) como lidar com entradas de tamanho exagerado: LEFT descarta tokens do início; RIGHT descarta do final; NONE exibe um erro se a entrada ultrapassar o limite.

Limites e tamanhos

  • Itens por solicitação: até 96 imagens. O tipo de arquivo de imagem original deve estar no formato png, jpeg, webp ou gif e pode ter até 5 MB.

  • Limite de tamanho da solicitação: ~20 MB de carga útil total.

  • Máximo de tokens de entrada: 128 mil. Os arquivos de imagem são convertidos em tokens, e o total de tokens deve ser inferior a 128 mil.

  • Imagens: no máximo 2.458.624 pixels antes da redução da amostragem; imagens com menos de 3.136 pixels sobreamostradas. Forneça imagens como data:<mime>;base64,....

  • Contagem de tokens (por item de inputs): tokens de uma entrada de imagem ≈ (pixels da imagem ÷ 784) x 4 tokens de uma entrada intercalada de texto e imagem = (pixels da imagem ÷ 784) x 4 + (tokens de texto).

Dica: para PDFs, converta cada página em uma imagem e a envie por meio de inputs com os metadados da página (p. ex., file_name, entidades) em partes de texto adjacentes.

Response

Tipo de conteúdo: application/json

Se você solicitou um único tipo de incorporação (p. ex., somente 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 você solicitou vários tipos de incorporação (por exemplo, ["float","int8"]):

{ "id": "string", "embeddings": { "float": [[ ... ]], "int8": [[ ... ]] }, "response_type": "embeddings_by_type", "texts": ["..."], // when text used "inputs": [ { "content": [ ... ] } ] // when 'inputs' used }
  • O número de vetores exibidos corresponde ao tamanho da matriz texts ou ao número de itens de inputs.

  • O tamanho de cada vetor é igual a output_dimension (o padrão é 1536).

Solicitação e resposta para diferentes input_types

A) Página intercalada (imagem + legenda) com vetores int8 compactos

Solicitação

{ "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 }
Resposta (truncada)

{ "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) Indexação de corpo somente de texto (número flutuante padrão: 1.536 dim)

Solicitação

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

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

Exemplos de código

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