Agents and tools tutorial
출처: 문서
본문
에이전트와 툴 튜토리얼
2.13에 도입 {: .label .label-purple }
다음 튜토리얼에서는 검색 증강 생성(RAG)을 위한 플로우 에이전트를 만드는 방법을 살펴봐요. 플로우 에이전트는 설정된 툴을 지정된 순서대로 차례차례 실행해요. 이 예제에서는 두 개의 툴을 갖춘 에이전트를 만들 거예요:
VectorDBTool: 에이전트는 이 툴을 사용해 사용자 질문과 관련된 OpenSearch 문서를 검색해요. 보충 정보를 OpenSearch 인덱스에 적재하게 되는데, 벡터 검색을 원활하게 하기 위해 텍스트를 벡터 임베딩으로 변환하는 텍스트 임베딩 모델을 배포해야 해요. OpenSearch는 적재된 문서를 임베딩으로 변환해서 인덱스에 저장해요. 에이전트에 사용자 질문을 제공하면, 에이전트는 그 질문으로 쿼리를 만들어 OpenSearch 인덱스에서 벡터 검색을 수행하고, 검색된 관련 문서를MLModelTool에 전달해요.MLModelTool: 에이전트는 이 툴을 실행해 대규모 언어 모델(LLM)에 연결하고, OpenSearch 문서로 보강된 사용자 쿼리를 모델에 보내요. 이 예제에서는 Amazon Bedrock에서 호스팅되는 Anthropic Claude 모델을 사용해요. 그러면 LLM이 자신의 지식과 제공된 문서를 바탕으로 질문에 답변해요.
사전 준비 사항
메모리 기능을 사용하려면 먼저 다음 클러스터 설정을 구성해야 해요. 이 튜토리얼에서는 전용 머신 러닝(ML) 노드가 없다고 가정해요:
PUT _cluster/settings
{
"persistent": {
"plugins.ml_commons.only_run_on_ml_node": "false",
"plugins.ml_commons.memory_feature_enabled": "true"
}
}
{% include copy-curl.html %}
자세한 내용은 ML Commons 클러스터 설정을 참조하세요.
1단계: 텍스트 임베딩 모델 등록 및 배포
벡터 검색을 위해서는 텍스트 임베딩 모델이 필요해요. 이 튜토리얼에서는 OpenSearch에서 제공하는 사전 학습된 모델 중 하나를 사용할 거예요. 모델을 선택할 때는 차원 수를 잘 확인하세요. 인덱스를 생성할 때 이 차원 수를 지정해야 하거든요.
이 튜토리얼에서는 384차원의 dense 벡터 임베딩을 생성하는 huggingface/sentence-transformers/all-MiniLM-L12-v2 모델을 사용해요. 모델을 등록하고 배포하려면 다음 요청을 보내세요:
POST /_plugins/_ml/models/_register?deploy=true
{
"name": "huggingface/sentence-transformers/all-MiniLM-L12-v2",
"version": "1.0.2",
"model_format": "TORCH_SCRIPT"
}
{% include copy-curl.html %}
모델 등록은 비동기 작업이에요. OpenSearch는 이 작업에 대한 태스크 ID를 반환해요:
{
"task_id": "aFeif4oB5Vm0Tdw8yoN7",
"status": "CREATED"
}
Get ML Task API를 호출하면 작업 상태를 확인할 수 있어요:
GET /_plugins/_ml/tasks/aFeif4oB5Vm0Tdw8yoN7
{% include copy-curl.html %}
작업이 완료되면 태스크 상태가 COMPLETED로 바뀌고, ML Tasks API 응답에 배포된 모델의 모델 ID가 포함돼요:
{
"model_id": "aVeif4oB5Vm0Tdw8zYO2",
"task_type": "REGISTER_MODEL",
"function_name": "TEXT_EMBEDDING",
"state": "COMPLETED",
"worker_node": [
"4p6FVOmJRtu3wehDD74hzQ"
],
"create_time": 1694358489722,
"last_update_time": 1694358499139,
"is_async": true
}
2단계: 인제스트 파이프라인 생성
텍스트를 벡터 임베딩으로 변환하기 위해 인제스트 파이프라인을 설정할 거예요. 이 파이프라인은 text 필드를 변환하고, 그 결과로 나온 벡터 임베딩을 embedding 필드에 기록해요. 다음 요청에서 이전 단계의 model_id를 지정해서 파이프라인을 생성하세요:
PUT /_ingest/pipeline/test-pipeline-local-model
{
"description": "text embedding pipeline",
"processors": [
{
"text_embedding": {
"model_id": "aVeif4oB5Vm0Tdw8zYO2",
"field_map": {
"text": "embedding"
}
}
}
]
}
{% include copy-curl.html %}
3단계: 벡터 인덱스 생성 및 데이터 적재
이제 보충 데이터를 OpenSearch 인덱스에 적재할 거예요. OpenSearch에서 벡터는 벡터 인덱스에 저장돼요. 다음 요청을 보내 벡터 인덱스를 만들 수 있어요:
PUT my_test_data
{
"mappings": {
"properties": {
"text": {
"type": "text"
},
"embedding": {
"type": "knn_vector",
"dimension": 384
}
}
},
"settings": {
"index": {
"knn.space_type": "cosinesimil",
"default_pipeline": "test-pipeline-local-model",
"knn": "true"
}
}
}
{% include copy-curl.html %}
그다음 벌크 요청을 사용해 인덱스에 데이터를 적재해요:
POST _bulk
{"index": {"_index": "my_test_data", "_id": "1"}}
{"text": "Chart and table of population level and growth rate for the Ogden-Layton metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\nThe current metro area population of Ogden-Layton in 2023 is 750,000, a 1.63% increase from 2022.\nThe metro area population of Ogden-Layton in 2022 was 738,000, a 1.79% increase from 2021.\nThe metro area population of Ogden-Layton in 2021 was 725,000, a 1.97% increase from 2020.\nThe metro area population of Ogden-Layton in 2020 was 711,000, a 2.16% increase from 2019."}
{"index": {"_index": "my_test_data", "_id": "2"}}
{"text": "Chart and table of population level and growth rate for the New York City metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\\nThe current metro area population of New York City in 2023 is 18,937,000, a 0.37% increase from 2022.\\nThe metro area population of New York City in 2022 was 18,867,000, a 0.23% increase from 2021.\\nThe metro area population of New York City in 2021 was 18,823,000, a 0.1% increase from 2020.\\nThe metro area population of New York City in 2020 was 18,804,000, a 0.01% decline from 2019."}
{"index": {"_index": "my_test_data", "_id": "3"}}
{"text": "Chart and table of population level and growth rate for the Chicago metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\\nThe current metro area population of Chicago in 2023 is 8,937,000, a 0.4% increase from 2022.\\nThe metro area population of Chicago in 2022 was 8,901,000, a 0.27% increase from 2021.\\nThe metro area population of Chicago in 2021 was 8,877,000, a 0.14% increase from 2020.\\nThe metro area population of Chicago in 2020 was 8,865,000, a 0.03% increase from 2019."}
{"index": {"_index": "my_test_data", "_id": "4"}}
{"text": "Chart and table of population level and growth rate for the Miami metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\\nThe current metro area population of Miami in 2023 is 6,265,000, a 0.8% increase from 2022.\\nThe metro area population of Miami in 2022 was 6,215,000, a 0.78% increase from 2021.\\nThe metro area population of Miami in 2021 was 6,167,000, a 0.74% increase from 2020.\\nThe metro area population of Miami in 2020 was 6,122,000, a 0.71% increase from 2019."}
{"index": {"_index": "my_test_data", "_id": "5"}}
{"text": "Chart and table of population level and growth rate for the Austin metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\\nThe current metro area population of Austin in 2023 is 2,228,000, a 2.39% increase from 2022.\\nThe metro area population of Austin in 2022 was 2,176,000, a 2.79% increase from 2021.\\nThe metro area population of Austin in 2021 was 2,117,000, a 3.12% increase from 2020.\\nThe metro area population of Austin in 2020 was 2,053,000, a 3.43% increase from 2019."}
{"index": {"_index": "my_test_data", "_id": "6"}}
{"text": "Chart and table of population level and growth rate for the Seattle metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\\nThe current metro area population of Seattle in 2023 is 3,519,000, a 0.86% increase from 2022.\\nThe metro area population of Seattle in 2022 was 3,489,000, a 0.81% increase from 2021.\\nThe metro area population of Seattle in 2021 was 3,461,000, a 0.82% increase from 2020.\\nThe metro area population of Seattle in 2020 was 3,433,000, a 0.79% increase from 2019."}
{% include copy-curl.html %}
4단계: 외부 호스팅 모델에 대한 커넥터 생성
사용자 질문에 대한 응답을 생성하려면 LLM이 필요해요. LLM은 OpenSearch 클러스터에서 처리하기엔 너무 크기 때문에, 외부에서 호스팅되는 LLM에 대한 연결을 만들 거예요. 이 예제에서는 Amazon Bedrock에서 호스팅되는 Anthropic Claude 모델에 대한 커넥터를 만들어요:
POST /_plugins/_ml/connectors/_create
{
"name": "BedRock test claude Connector",
"description": "The connector to BedRock service for claude model",
"version": 1,
"protocol": "aws_sigv4",
"parameters": {
"region": "us-east-1",
"service_name": "bedrock",
"anthropic_version": "bedrock-2023-05-31",
"endpoint": "bedrock.us-east-1.amazonaws.com",
"auth": "Sig_V4",
"content_type": "application/json",
"max_tokens_to_sample": 8000,
"temperature": 0.0001,
"response_filter": "$.completion"
},
"credential": {
"access_key": "<bedrock_access_key>",
"secret_key": "<bedrock_secret_key>",
"session_token": "<bedrock_session_token>"
},
"actions": [
{
"action_type": "predict",
"method": "POST",
"url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-v2/invoke",
"headers": {
"content-type": "application/json",
"x-amz-content-sha256": "required"
},
"request_body": "{\"prompt\":\"${parameters.prompt}\", \"max_tokens_to_sample\":${parameters.max_tokens_to_sample}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }"
}
]
}
{% include copy-curl.html %}
응답에는 새로 생성된 커넥터의 커넥터 ID가 포함되어 있어요:
{
"connector_id": "a1eMb4kBJ1eYAeTMAljY"
}
5단계: 외부 호스팅 모델 등록 및 배포
텍스트 임베딩 모델과 마찬가지로 LLM도 OpenSearch에 등록하고 배포해야 해요. 외부 호스팅 모델을 설정하려면 먼저 이 모델을 위한 모델 그룹을 생성하세요:
POST /_plugins/_ml/model_groups/_register
{
"name": "test_model_group_bedrock",
"description": "This is a public model group"
}
{% include copy-curl.html %}
응답에는 이 모델 그룹에 모델을 등록할 때 사용할 모델 그룹 ID가 포함되어 있어요:
{
"model_group_id": "wlcnb4kBJ1eYAeTMHlV6",
"status": "CREATED"
}
다음으로 외부 호스팅 Claude 모델을 등록하고 배포해요:
POST /_plugins/_ml/models/_register?deploy=true
{
"name": "Bedrock Claude V2 model",
"function_name": "remote",
"model_group_id": "wlcnb4kBJ1eYAeTMHlV6",
"description": "test model",
"connector_id": "a1eMb4kBJ1eYAeTMAljY"
}
{% include copy-curl.html %}
1단계와 마찬가지로, 응답에는 배포 상태를 확인하는 데 사용할 수 있는 태스크 ID가 포함되어 있어요. 모델이 배포되면 상태가 COMPLETED로 바뀌고, 응답에 Claude 모델의 모델 ID가 포함돼요:
{
"model_id": "NWR9YIsBUysqmzBdifVJ",
"task_type": "REGISTER_MODEL",
"function_name": "remote",
"state": "COMPLETED",
"worker_node": [
"4p6FVOmJRtu3wehDD74hzQ"
],
"create_time": 1694358489722,
"last_update_time": 1694358499139,
"is_async": true
}
LLM을 테스트하려면 다음 predict 요청을 보내세요:
POST /_plugins/_ml/models/NWR9YIsBUysqmzBdifVJ/_predict
{
"parameters": {
"prompt": "\n\nHuman:hello\n\nAssistant:"
}
}
{% include copy-curl.html %}
6단계: 에이전트 등록 및 실행
마지막으로 1단계에서 만든 텍스트 임베딩 모델과 5단계에서 만든 Claude 모델을 사용해 플로우 에이전트를 만들 거예요. 이 플로우 에이전트는 VectorDBTool을 실행한 뒤 MLModelTool을 실행해요. VectorDBTool은 벡터 검색을 위해 1단계에서 만든 텍스트 임베딩 모델의 모델 ID로 구성돼요. MLModelTool은 5단계에서 만든 Claude 모델로 구성돼요:
POST /_plugins/_ml/agents/_register
{
"name": "Test_Agent_For_RAG",
"type": "flow",
"description": "this is a test agent",
"tools": [
{
"type": "VectorDBTool",
"parameters": {
"model_id": "aVeif4oB5Vm0Tdw8zYO2",
"index": "my_test_data",
"embedding_field": "embedding",
"source_field": ["text"],
"input": "${parameters.question}"
}
},
{
"type": "MLModelTool",
"description": "A general tool to answer any question",
"parameters": {
"model_id": "NWR9YIsBUysqmzBdifVJ",
"prompt": "\n\nHuman:You are a professional data analyst. You will always answer a question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say you don't know. \n\n Context:\n${parameters.VectorDBTool.output}\n\nHuman:${parameters.question}\n\nAssistant:"
}
}
]
}
{% include copy-curl.html %}
OpenSearch는 새로 생성된 에이전트의 에이전트 ID를 반환해요:
{
"agent_id": "879v9YwBjWKCe6Kg12Tx"
}
agents 엔드포인트에 에이전트 ID와 함께 요청을 보내면 에이전트를 조회할 수 있어요:
GET /_plugins/_ml/agents/879v9YwBjWKCe6Kg12Tx
{% include copy-curl.html %}
에이전트를 실행하려면 다음 요청을 보내세요. 에이전트를 등록할 때 parameters.question을 입력받도록 설정했기 때문에, 요청에서 이 파라미터를 제공해야 해요. 이 파라미터는 사용자가 직접 입력한 질문을 나타내요:
POST /_plugins/_ml/agents/879v9YwBjWKCe6Kg12Tx/_execute
{
"parameters": {
"question": "what's the population increase of Seattle from 2021 to 2023"
}
}
{% include copy-curl.html %}
LLM의 지식 기반에는 최신 정보가 없기 때문에, 적재된 데이터를 바탕으로 질문에 대한 응답을 추론해요. 이것이 바로 RAG를 보여주는 부분이에요:
{
"inference_results": [
{
"output": [
{
"result": """ Based on the given context, the key information is:
The metro area population of Seattle in 2021 was 3,461,000.
The metro area population of Seattle in 2023 is 3,519,000.
To calculate the population increase from 2021 to 2023:
Population in 2023 (3,519,000) - Population in 2021 (3,461,000) = 58,000
Therefore, the population increase of Seattle from 2021 to 2023 is 58,000."""
}
]
}
]
}