CohereEmbed모델 - Amazon Bedrock

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

CohereEmbed모델

사용하려는 Embed 모델의 모델 ID가 필요함을 사용하여 모델에 추론 요청을 합니다. InvokeModel 모델 ID를 가져오려면 을 참조하십시오아마존 베드락 모델 ID.

참고

Amazon Bedrock은 모델로부터의 Cohere Embed 스트리밍 응답을 지원하지 않습니다.

요청 및 응답

Request

CohereEmbed모델에는 다음과 같은 추론 파라미터가 있습니다.

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

다음은 필수 파라미터입니다.

  • text — 모델에 포함할 문자열 배열입니다. 최적의 성능을 위해 각 텍스트의 길이를 토큰 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을 사용합니다.

다음은 선택적 매개변수입니다.

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

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

    • START— 입력의 시작 부분을 무시합니다.

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

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

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

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

    • int8— 이 값을 사용하여 부호있는 int8 임베딩을 반환할 수 있습니다.

    • uint8— 이 값을 사용하여 부호 없는 int8 임베딩을 반환할 수 있습니다.

    • binary— 이 값을 사용하여 부호 있는 이진 임베딩을 반환할 수 있습니다.

    • ubinary— 이 값을 사용하여 부호 없는 이진 임베딩을 반환할 수 있습니다.

자세한 내용은 설명서의 https://docs.cohere.com/reference/embed 을 Cohere 참조하십시오.

Response

InvokeModel에 대한 직접 호출의 body 응답은 다음과 같습니다.

{ "embeddings": [ [ <array of 1024 floats> ] ], "id": string, "response_type" : "embeddings_floats, "texts": [string] }

body 응답에는 다음과 같은 필드가 포함됩니다.

  • id - 응답의 식별자입니다.

  • 응답_유형 — 응답 유형입니다. 이 값은 항상 embeddings_floats입니다.

  • embeddings - 임베딩 배열입니다. 각 임베딩은 1024개 요소로 구성된 부동 소수 배열입니다. embeddings 배열의 길이는 원본 texts 배열의 길이와 같습니다.

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

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

코드 예제

이 예제는 모델을 호출하는 방법을 보여줍니다. CohereEmbed 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): """ 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. Returns: dict: The response from the model. """ logger.info( "Generating text emdeddings with the Cohere Embed model %s", model_id) accept = '*/*' content_type = 'application/json' bedrock = boto3.client(service_name='bedrock-runtime') response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) logger.info("Successfully generated text 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") 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) 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") for i, embedding in enumerate(response_body.get('embeddings')): print(f"\tEmbedding {i}") print(*embedding) 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()