Reranking search results by a field using Cohere Rerank
출처: 문서
본문
Cohere Rerank를 사용해 필드 기준으로 검색 결과 재순위화하기
검색 결과를 필드 기준으로 재순위화할 수 있어요. 이 기능은 문서에 특히 중요한 필드가 포함되어 있거나 외부에서 호스팅되는 모델의 결과를 재순위화하고 싶을 때 유용해요. 자세한 내용은 필드 기준 검색 결과 재순위화를 참고하세요.
이 튜토리얼에서는 Cohere Rerank 모델을 사용해 self-managed OpenSearch와 Amazon OpenSearch Service에서 필드 기준으로 검색 결과를 재순위화하는 방법을 설명해요.
your_ 접두사로 시작하는 플레이스홀더는 여러분의 값으로 바꾸세요.
{: .note}
1단계(self-managed OpenSearch): 커넥터 생성
커넥터를 생성하려면 다음 요청을 보내세요:
POST /_plugins/_ml/connectors/_create
{
"name": "cohere-rerank",
"description": "The connector to Cohere reanker model",
"version": "1",
"protocol": "http",
"credential": {
"cohere_key": "your_cohere_api_key"
},
"parameters": {
"model": "rerank-english-v3.0",
"return_documents": true
},
"actions": [
{
"action_type": "predict",
"method": "POST",
"url": "https://api.cohere.ai/v1/rerank",
"headers": {
"Authorization": "Bearer ${credential.cohere_key}"
},
"request_body": "{ \"documents\": ${parameters.documents}, \"query\": \"${parameters.query}\", \"model\": \"${parameters.model}\", \"top_n\": ${parameters.top_n}, \"return_documents\": ${parameters.return_documents} }"
}
]
}
{% include copy-curl.html %}
응답에는 커넥터 ID가 포함되어 있어요:
{"connector_id":"qp2QP40BWbTmLN9Fpo40"}
커넥터 ID를 기록해 두세요. 이후 단계에서 사용하게 돼요. 그런 다음 2단계로 이동하세요.
1단계(Amazon OpenSearch Service): 커넥터 생성
다음 단계에 따라 Amazon OpenSearch Service로 커넥터를 생성하세요.
사전 준비: OpenSearch 클러스터 생성
Amazon OpenSearch Service 콘솔로 이동해 OpenSearch 도메인을 생성하세요.
도메인의 Amazon Resource Name(ARN)과 URL을 기록해 두세요. 이후 단계에서 사용하게 돼요.
1.1단계: AWS Secrets Manager에 API 키 저장
Cohere API 키를 AWS Secrets Manager에 저장하세요:
- AWS Secrets Manager를 여세요.
- Store a new secret를 선택하세요.
- Other type of secret를 선택하세요.
- my_cohere_key를 키로, 여러분의 Cohere API 키를 값으로 하는 키-값 쌍을 만드세요.
- 시크릿 이름을
my_test_cohere_secret으로 지정하세요.
시크릿 ARN을 기록해 두세요. 이후 단계에서 사용하게 돼요.
1.2단계: IAM 역할 생성
1단계에서 생성한 시크릿을 사용하려면 이 시크릿에 대한 읽기 권한을 가진 AWS Identity and Access Management(IAM) 역할을 만들어야 해요. 이 IAM 역할은 커넥터에 구성되어 커넥터가 시크릿을 읽을 수 있도록 해줘요.
IAM 콘솔로 이동해 my_cohere_secret_role이라는 새 IAM 역할을 만들고 다음 신뢰 정책과 권한을 추가하세요:
- 사용자 지정 신뢰 정책:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "es.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
{% include copy.html %}
- 권한:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"secretsmanager:GetSecretValue",
"secretsmanager:DescribeSecret"
],
"Effect": "Allow",
"Resource": "your_secret_arn_created_in_step1"
}
]
}
{% include copy.html %}
역할 ARN을 기록해 두세요. 이후 단계에서 사용하게 돼요.
1.3단계: Amazon OpenSearch Service에서 IAM 역할 구성
다음 단계에 따라 Amazon OpenSearch Service에서 IAM 역할을 구성하세요.
1.3.1단계: 커넥터 요청 서명용 IAM 역할 생성
Create Connector API 요청에 서명하기 위한 새 IAM 역할을 생성하세요.
다음 신뢰 정책과 권한으로 my_create_cohere_connector_role이라는 IAM 역할을 만드세요:
- 사용자 지정 신뢰 정책:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "your_iam_user_arn"
},
"Action": "sts:AssumeRole"
}
]
}
{% include copy.html %}
4.1단계에서 your_iam_user_arn IAM 사용자로 이 역할을 수임하게 돼요.
- 권한:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "your_iam_role_arn_created_in_step2"
},
{
"Effect": "Allow",
"Action": "es:ESHttpPost",
"Resource": "your_opensearch_domain_arn_created_in_step0"
}
]
}
{% include copy.html %}
이 역할 ARN을 기록해 두세요. 이후 단계에서 사용하게 돼요.
1.3.2단계: 백엔드 역할 매핑
다음 단계에 따라 백엔드 역할을 매핑하세요:
- OpenSearch Dashboards에 로그인하고 상단 메뉴에서 Security를 선택하세요.
- Roles를 선택한 다음 ml_full_access 역할을 선택하세요.
- ml_full_access 역할 세부 정보 페이지에서 Mapped users를 선택한 다음 Manage mapping을 선택하세요.
- 다음 이미지와 같이 Backend roles 필드에 3.1단계에서 생성한 IAM 역할 ARN을 입력하세요.

- Map을 선택하세요.
이제 IAM 역할이 OpenSearch 클러스터에 성공적으로 구성되었어요.
1.4단계: 커넥터 생성
다음 단계에 따라 모델용 커넥터를 생성하세요. 커넥터 생성에 대한 자세한 내용은 커넥터를 참고하세요.
AWS에서 가져온 임시 자격 증명으로 다음 Python 코드를 실행하세요.
import boto3
import requests
from requests_aws4auth import AWS4Auth
host = 'your_amazon_opensearch_domain_endpoint_created_in_step0'
region = 'your_amazon_opensearch_domain_region'
service = 'es'
assume_role_response = boto3.Session().client('sts').assume_role(
RoleArn="your_iam_role_arn_created_in_step1.3.1",
RoleSessionName="your_session_name"
)
credentials = assume_role_response["Credentials"]
awsauth = AWS4Auth(credentials["AccessKeyId"], credentials["SecretAccessKey"], region, service, session_token=credentials["SessionToken"])
path = '/_plugins/_ml/connectors/_create'
url = host + path
payload = {
"name": "cohere-rerank",
"description": "The connector to Cohere reanker model",
"version": "1",
"protocol": "http",
"credential": {
"secretArn": "your_secret_arn_created_in_step1",
"roleArn": "your_iam_role_arn_created_in_step2"
},
"parameters": {
"model": "rerank-english-v3.0",
"return_documents": true
},
"actions": [
{
"action_type": "predict",
"method": "POST",
"url": "https://api.cohere.ai/v1/rerank",
"headers": {
"Authorization": "Bearer ${credential.secretArn.my_cohere_key}"
},
"request_body": "{ \"documents\": ${parameters.documents}, \"query\": \"${parameters.query}\", \"model\": \"${parameters.model}\", \"top_n\": ${parameters.top_n}, \"return_documents\": ${parameters.return_documents} }"
}
]
}
headers = {"Content-Type": "application/json"}
r = requests.post(url, auth=awsauth, json=payload, headers=headers)
print(r.text)
{% include copy.html %}
스크립트는 커넥터 ID를 출력해요:
{"connector_id":"qp2QP40BWbTmLN9Fpo40"}
커넥터 ID를 기록해 두세요. 다음 단계에서 사용하게 돼요.
2단계: Cohere Rerank 모델 등록
self-managed OpenSearch 또는 Amazon OpenSearch Service 방법 중 하나로 커넥터를 성공적으로 생성했다면 이제 Cohere Rerank 모델을 등록할 수 있어요.
1.4단계에서 받은 커넥터 ID를 사용해 모델을 생성하세요:
POST /_plugins/_ml/models/_register?deploy=true
{
"name": "cohere rerank model",
"function_name": "remote",
"description": "test rerank model",
"connector_id": "your_connector_id"
}
{% include copy-curl.html %}
커넥터 ID를 기록해 두세요. 이후 단계에서 사용하게 돼요.
3단계: 모델 테스트
모델을 테스트하려면 다음 요청을 보내세요:
POST /_plugins/_ml/models/your_model_id/_predict
{
"parameters": {
"top_n" : 100,
"query": "What day is it?",
"documents" : ["Monday", "Tuesday", "apples"]
}
}
{% include copy-curl.html %}
응답에는 일치하는 문서들이 포함되어 있어요:
{
"inference_results": [
{
"output": [
{
"name": "response",
"dataAsMap": {
"id": "e15a3922-3d89-4adc-96cf-9b85a619fb66",
"results": [
{
"document": {
"text": "Monday"
},
"index": 0.0,
"relevance_score": 0.21076629
},
{
"document": {
"text": "Tuesday"
},
"index": 1.0,
"relevance_score": 0.13206616
},
{
"document": {
"text": "apples"
},
"index": 2.0,
"relevance_score": 1.0804956E-4
}
],
"meta": {
"api_version": {
"version": "1"
},
"billed_units": {
"search_units": 1.0
}
}
}
}
],
"status_code": 200
}
]
}
각 문서에는 rerank 모델이 점수를 부여해요. 이제 Cohere 모델을 호출하고 관련성 점수를 기준으로 검색 결과 순서를 다시 정렬하는 검색 파이프라인을 만들 거예요.
3단계: 검색 결과 재순위화
다음 단계에 따라 검색 결과를 재순위화하세요.
3.1단계: 인덱스 생성
인덱스를 생성하려면 다음 요청을 보내세요:
POST _bulk
{ "index": { "_index": "nyc_facts", "_id": 1 } }
{ "fact_title": "Population of New York", "fact_description": "New York City has an estimated population of over 8.3 million people as of 2023, making it the most populous city in the United States." }
{ "index": { "_index": "nyc_facts", "_id": 2 } }
{ "fact_title": "Statue of Liberty", "fact_description": "The Statue of Liberty, a symbol of freedom, was gifted to the United States by France in 1886 and stands on Liberty Island in New York Harbor." }
{ "index": { "_index": "nyc_facts", "_id": 3 } }
{ "fact_title": "New York City is a Global Financial Hub", "fact_description": "New York City is home to the New York Stock Exchange (NYSE) and Wall Street, which are central to the global finance industry." }
{ "index": { "_index": "nyc_facts", "_id": 4 } }
{ "fact_title": "Broadway", "fact_description": "Broadway is a major thoroughfare in New York City known for its theaters. It's also considered the birthplace of modern American theater and musicals." }
{ "index": { "_index": "nyc_facts", "_id": 5 } }
{ "fact_title": "Central Park", "fact_description": "Central Park, located in Manhattan, spans 843 acres and is one of the most visited urban parks in the world, offering green spaces, lakes, and recreational areas." }
{ "index": { "_index": "nyc_facts", "_id": 6 } }
{ "fact_title": "Empire State Building", "fact_description": "The Empire State Building, completed in 1931, is an iconic Art Deco skyscraper that was the tallest building in the world until 1970." }
{ "index": { "_index": "nyc_facts", "_id": 7 } }
{ "fact_title": "Times Square", "fact_description": "Times Square, often called 'The Cross-roads of the World,' is known for its bright lights, Broadway theaters, and New Year's Eve ball drop." }
{ "index": { "_index": "nyc_facts", "_id": 8 } }
{ "fact_title": "Brooklyn Bridge", "fact_description": "The Brooklyn Bridge, completed in 1883, connects Manhattan and Brooklyn and was the first suspension bridge to use steel in its construction." }
{ "index": { "_index": "nyc_facts", "_id": 9 } }
{ "fact_title": "New York City Public Library", "fact_description": "The New York Public Library, founded in 1895, has over 50 million items in its collections and serves as a major cultural and educational resource." }
{ "index": { "_index": "nyc_facts", "_id": 10 } }
{ "fact_title": "New York's Chinatown", "fact_description": "New York's Chinatown, one of the largest in the world, is known for its vibrant culture, food, and history. It plays a key role in the city's Chinese community." }
{% include copy-curl.html %}
3.2단계: 재순위화 파이프라인 생성
재순위화 파이프라인을 생성하려면 다음 요청을 보내세요:
PUT /_search/pipeline/cohere_pipeline
{
"response_processors": [
{
"ml_inference": {
"model_id": "your_model_id",
"input_map": {
"documents": "fact_description",
"query": "_request.ext.query_context.query_text",
"top_n": "_request.ext.query_context.top_n"
},
"output_map": {
"relevance_score": "results[*].relevance_score",
"description": "results[*].document.text"
},
"full_response_path": false,
"ignore_missing": false,
"ignore_failure": false,
"one_to_one": false,
"override": false,
"model_config": {}
}
},
{
"rerank": {
"by_field": {
"target_field": "relevance_score",
"remove_target_field": false,
"keep_previous_score": false,
"ignore_failure": false
}
}
}
]
}
{% include copy-curl.html %}
3.3단계: 파이프라인 테스트
파이프라인을 테스트하려면 인덱싱된 문서와 관련된 쿼리를 보내고 top_n을 size 이상의 값으로 설정하세요:
GET nyc_facts/_search?search_pipeline=cohere_pipeline
{
"query": {
"match_all": {}
},
"size": 5,
"ext": {
"rerank": {
"query_context": {
"query_text": "Where do people go to see a show?",
"top_n" : "10"
}
}
}
}
{% include copy-curl.html %}
응답에는 재순위화된 문서들이 포함되어 있어요:
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 10,
"relation": "eq"
},
"max_score": 0.34986588,
"hits": [
{
"_index": "nyc_facts",
"_id": "_7a76b04b5016c71c",
"_score": 0.34986588,
"_source": {
"result_document": "Broadway is a major thoroughfare in New York City known for its theaters. It's also considered the birthplace of modern American theater and musicals.",
"fact_title": "Times Square",
"fact_description": "Times Square, often called 'The Cross-roads of the World,' is known for its bright lights, Broadway theaters, and New Year's Eve ball drop.",
"relevance_score": 0.34986588
}
},
{
"_index": "nyc_facts",
"_id": "_00c26e453971ed68",
"_score": 0.1066906,
"_source": {
"result_document": "Times Square, often called 'The Cross-roads of the World,' is known for its bright lights, Broadway theaters, and New Year's Eve ball drop.",
"fact_title": "New York City Public Library",
"fact_description": "The New York Public Library, founded in 1895, has over 50 million items in its collections and serves as a major cultural and educational resource.",
"relevance_score": 0.1066906
}
},
{
"_index": "nyc_facts",
"_id": "_d03d3610a5a5bd82",
"_score": 0.00019563535,
"_source": {
"result_document": "The New York Public Library, founded in 1895, has over 50 million items in its collections and serves as a major cultural and educational resource.",
"fact_title": "Broadway",
"fact_description": "Broadway is a major thoroughfare in New York City known for its theaters. It's also considered the birthplace of modern American theater and musicals.",
"relevance_score": 0.00019563535
}
},
{
"_index": "nyc_facts",
"_id": "_9284bae64eab7f63",
"_score": 0.000019988918,
"_source": {
"result_document": "The Statue of Liberty, a symbol of freedom, was gifted to the United States by France in 1886 and stands on Liberty Island in New York Harbor.",
"fact_title": "Brooklyn Bridge",
"fact_description": "The Brooklyn Bridge, completed in 1883, connects Manhattan and Brooklyn and was the first suspension bridge to use steel in its construction.",
"relevance_score": 0.000019988918
}
},
{
"_index": "nyc_facts",
"_id": "_7aa6f2934f47911b",
"_score": 0.0000104515475,
"_source": {
"result_document": "The Brooklyn Bridge, completed in 1883, connects Manhattan and Brooklyn and was the first suspension bridge to use steel in its construction.",
"fact_title": "Statue of Liberty",
"fact_description": "The Statue of Liberty, a symbol of freedom, was gifted to the United States by France in 1886 and stands on Liberty Island in New York Harbor.",
"relevance_score": 0.0000104515475
}
}
]
},
"profile": {
"shards": []
}
}
재순위화된 결과를 평가할 때는 result_document 필드와 그에 해당하는 relevance_score에 주목하세요. fact_description 필드는 원본 문서 텍스트를 보여줄 뿐 재순위화 순서를 반영하지 않아요.
{: .note}