Cohere 임베드 v3 - Amazon Bedrock

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Cohere 임베드 v3

요청 및 응답

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자입니다.

    다음은 직접 호출당 텍스트 및 글자 수 제한입니다.

    직접 호출당 텍스트

    최소 Maximum

    0개 텍스트

    96개 텍스트

    글자 수

    최소 Maximum

    0자

    2048자

  • input_type - 특수 토큰을 앞에 추가하여 각 유형을 구분합니다. 검색을 위해 유형을 혼합하는 경우를 제외하고는 서로 다른 유형을 혼합해서는 안 됩니다. 이 경우 코퍼스를 search_document 유형과 함께 임베드하고, 임베디드 쿼리에는 search_query 유형을 포함합니다.

    • search_document - 검색 사용 사례의 경우, 벡터 데이터베이스에 저장하는 임베딩을 위해 문서를 인코딩할 때 search_document를 사용합니다.

    • search_query - 벡터 DB를 쿼리하여 관련 문서를 찾을 때 search_query를 사용합니다.

    • classification - 임베딩을 텍스트 분류자에 대한 입력으로 사용할 때 classification을 사용합니다.

    • clustering - 임베딩을 클러스터링하는 데 clustering을 사용합니다.

    • images - 이미지 배열입니다.

      • 포함할 모델의 이미지 데이터 URIs. 호출당 최대 이미지 수는 1개입니다(즉, 모델은 하나의 이미지 입력만 지원함).

      • 이미지는 유효한 데이터 URI여야 합니다. 이미지는 image/jpeg 또는 image/png 형식이어야 하며 최대 크기는 5MB입니다.

      • “이미지” 또는 “텍스트” 중 하나만 제공해야 합니다.

다음 파라미터는 선택 사항입니다.

  • truncate - API가 최대 토큰 길이보다 긴 입력을 처리하는 방법을 지정합니다. 다음 중 하나를 사용하세요.

    • NONE - (기본값) 입력이 최대 입력 토큰 길이를 초과하면 오류가 반환됩니다.

    • START - 입력의 시작을 취소합니다.

    • END - 입력의 종료를 취소합니다.

    START 또는 END 를 지정할 경우, 모델은 나머지 입력값이 모델의 최대 입력 토큰 길이와 정확히 일치할 때까지 입력값을 취소합니다.

  • embedding_types - 반환하려는 임베딩 유형을 지정합니다. 선택 사항이며 기본값은 Embed Floats 응답 유형을 반환하는 None입니다. 다음 유형 중 하나 이상에 해당할 수 있습니다.

    • float - 이 값을 사용하여 기본 플로트 임베딩을 반환합니다.

    • int8 - 이 값을 사용하여 서명된 int8 임베딩을 반환합니다.

    • uint8 - 이 값을 사용하여 서명되지 않은 int8 임베딩을 반환합니다.

    • binary - 이 값을 사용하여 서명된 바이너리 임베딩을 반환합니다.

    • ubinary - 이 값을 사용하여 서명되지 않은 바이너리 임베딩을 반환합니다.

자세한 내용은 Cohere 설명서의 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 배열의 길이와 같습니다.

  • text - 임베딩이 반환된 텍스트 항목이 포함된 배열입니다.

  • 이미지 - 각 이미지 입력에 대한 설명의 배열입니다.

    image_descriptionimage_description은 다음과 같은 형식입니다.

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

    이미지가 입력으로 사용된 경우 “texts” 응답 필드는 빈 배열이 됩니다. 반대의 경우도 마찬가지입니다(즉, 텍스트가 사용될 때 응답에 포함되지 “images” 않음).

자세한 내용은 https://docs.cohere.com/reference/embed를 참조하세요.

코드 예제

이 예제는 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()