본문 바로가기
WIKI 기술 지식 베이스

RAG chatbot with a conversational flow agent

원문 보기 위키 갱신

출처: 문서

본문

대화형 플로우 에이전트를 사용한 RAG 챗봇

이 튜토리얼에서는 대화형 플로우 에이전트를 사용하여 OpenSearch 데이터를 지식 베이스로 활용하는 검색 증강 생성(RAG) 애플리케이션을 구축하는 방법을 설명해요.

your_ 접두사로 시작하는 플레이스홀더를 자신의 값으로 바꾸세요. {: .note}

RAG 대화형 검색을 구축하는 다른 방법은 RAG 파이프라인을 사용하는 거예요. 자세한 내용은 Cohere Command 모델을 사용한 대화형 검색을 참조하세요.

사전 조건

이 튜토리얼에서는 OpenSearch 벡터 인덱스를 대규모 언어 모델(LLM)의 지식 베이스로 제공하는 RAG 애플리케이션을 구축할 거예요. 데이터 검색을 위해 시맨틱 검색을 사용할 거예요. 포괄적인 시맨틱 검색 설정은 이 튜토리얼을 참조하세요.

먼저 클러스터 설정을 업데이트해야 해요. 전용 머신러닝(ML) 노드가 없는 경우 "plugins.ml_commons.only_run_on_ml_node": false로 설정하세요. 네이티브 메모리 서킷 브레이커가 트리거되는 것을 방지하려면 "plugins.ml_commons.native_memory_threshold"를 100%로 설정하세요:

PUT _cluster/settings
{
    "persistent": {
        "plugins.ml_commons.only_run_on_ml_node": false,
        "plugins.ml_commons.native_memory_threshold": 100,
        "plugins.ml_commons.agent_framework_enabled": true
    }
}

{% include copy-curl.html %}

1단계: 지식 베이스 준비

다음 단계를 사용하여 LLM 지식을 보완할 지식 베이스를 준비하세요.

1.1단계: 텍스트 임베딩 모델 등록

텍스트를 벡터 임베딩으로 변환할 텍스트 임베딩 모델을 등록하세요:

POST /_plugins/_ml/models/_register
{
  "name": "huggingface/sentence-transformers/all-MiniLM-L12-v2",
  "version": "1.0.2",
  "model_format": "TORCH_SCRIPT"
}

{% include copy-curl.html %}

텍스트 임베딩 모델 ID를 기록해 두세요. 다음 단계에서 사용할 거예요.

또는 Get Task API를 호출하여 모델 ID를 가져올 수 있어요:

GET /_plugins/_ml/tasks/your_task_id

{% include copy-curl.html %}

모델을 배포하세요:

POST /_plugins/_ml/models/your_text_embedding_model_id/_deploy

{% include copy-curl.html %}

모델을 테스트하세요:

POST /_plugins/_ml/models/your_text_embedding_model_id/_predict
{
  "text_docs":[ "today is sunny"],
  "return_number": true,
  "target_response": ["sentence_embedding"]
}

{% include copy-curl.html %}

OpenSearch 클러스터 내에서 모델을 사용하는 방법에 대한 자세한 내용은 사전 훈련된 모델을 참조하세요.

1.2단계: 수집 파이프라인 생성

텍스트 임베딩 프로세서를 사용하여 수집 파이프라인을 생성하세요. 이 프로세서는 이전 단계에서 생성한 모델을 호출하여 텍스트 필드에서 임베딩을 생성할 수 있어요:

PUT /_ingest/pipeline/test_population_data_pipeline
{
    "description": "text embedding pipeline",
    "processors": [
        {
            "text_embedding": {
                "model_id": "your_text_embedding_model_id",
                "field_map": {
                    "population_description": "population_description_embedding"
                }
            }
        }
    ]
}

{% include copy-curl.html %}

수집 파이프라인에 대한 자세한 내용은 수집 파이프라인을 참조하세요.

1.3단계: 벡터 인덱스 생성

수집 파이프라인을 기본 파이프라인으로 지정하여 벡터 인덱스를 생성하세요:

PUT test_population_data
{
  "mappings": {
    "properties": {
      "population_description": {
        "type": "text"
      },
      "population_description_embedding": {
        "type": "knn_vector",
        "dimension": 384
      }
    }
  },
  "settings": {
    "index": {
      "knn.space_type": "cosinesimil",
      "default_pipeline": "test_population_data_pipeline",
      "knn": "true"
    }
  }
}

{% include copy-curl.html %}

벡터 인덱스에 대한 자세한 내용은 벡터 인덱스 생성을 참조하세요.

1.4단계: 데이터 수집

테스트 데이터를 벡터 인덱스에 수집하세요:

POST _bulk
{"index": {"_index": "test_population_data"}}
{"population_description": "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": "test_population_data"}}
{"population_description": "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": "test_population_data"}}
{"population_description": "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": "test_population_data"}}
{"population_description": "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": "test_population_data"}}
{"population_description": "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": "test_population_data"}}
{"population_description": "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 %}

2단계: LLM 준비

이 튜토리얼에서는 대화형 검색을 위해 Amazon Bedrock Claude 모델을 사용해요. 다른 LLM을 사용할 수도 있어요. 외부 호스팅 모델 사용에 대한 자세한 내용은 외부 호스팅 모델에 연결을 참조하세요.

2.1단계: 커넥터 생성

Claude 모델용 커넥터를 생성하세요:

POST /_plugins/_ml/connectors/_create
{
  "name": "Bedrock Claude Sonnet 5",
  "description": "The connector to BedRock service for claude model",
  "version": 1,
  "protocol": "aws_sigv4",
  "parameters": {
    "region": "us-east-1",
    "service_name": "bedrock",
    "model": "us.anthropic.claude-sonnet-5",
    "response_filter": "$.output.message.content[0].text"
  },
  "credential": {
    "access_key": "your_aws_access_key",
    "secret_key": "your_aws_secret_key",
    "session_token": "your_aws_session_token"
  },
  "actions": [{
    "action_type": "predict",
    "method": "POST",
    "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse",
    "headers": { "content-type": "application/json" },
    "request_body": "{\"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.prompt:-}\"}]}${parameters._interactions:-}]${parameters.tool_configs:-}}"
  }]
}

{% include copy-curl.html %}

커넥터 ID를 기록해 두세요. 모델을 등록할 때 사용할 거예요.

2.2단계: 모델 등록

Amazon Bedrock에 호스팅된 Claude 모델을 등록하세요:

POST /_plugins/_ml/models/_register
{
    "name": "Bedrock Claude Instant model",
    "function_name": "remote",
    "description": "Bedrock Claude instant-v1 model",
    "connector_id": "your_LLM_connector_id"
}

{% include copy-curl.html %}

LLM 모델 ID를 기록해 두세요. 다음 단계에서 사용할 거예요.

2.3단계: 모델 배포

Claude 모델을 배포하세요:

POST /_plugins/_ml/models/your_LLM_model_id/_deploy

{% include copy-curl.html %}

2.4단계: 모델 테스트

모델을 테스트하려면 Predict API 요청을 보내세요:

POST /_plugins/_ml/models/your_LLM_model_id/_predict
{
  "parameters": {
    "prompt": "\n\nHuman: how are you? \n\nAssistant:"
  }
}

{% include copy-curl.html %}

3단계: 에이전트 등록

OpenSearch는 flow, conversational_flow, conversational과 같은 에이전트 유형을 제공해요. 에이전트에 대한 자세한 내용은 에이전트를 참조하세요.

이 튜토리얼에서는 conversational_flow 에이전트를 사용할 거예요. 에이전트는 다음으로 구성돼요:

  • 메타 정보: name, type, description.
  • app_type: 애플리케이션 유형을 구분해요.
  • memory: 사용자 질문과 LLM 응답을 대화로 저장하여 에이전트가 메모리에서 대화 기록을 검색하고 동일한 대화를 계속할 수 있게 해요.
  • tools: 사용할 도구 목록을 정의해요. 에이전트는 이 도구들을 순차적으로 실행할 거예요.

에이전트를 등록하려면 다음 요청을 보내세요:

POST /_plugins/_ml/agents/_register
{
    "name": "population data analysis agent",
    "type": "conversational_flow",
    "description": "This is a demo agent for population data analysis",
    "app_type": "rag",
    "memory": {
        "type": "conversation_index"
    },
    "tools": [
        {
            "type": "VectorDBTool",
            "name": "population_knowledge_base",
            "parameters": {
                "model_id": "your_text_embedding_model_id",
                "index": "test_population_data",
                "embedding_field": "population_description_embedding",
                "source_field": [
                    "population_description"
                ],
                "input": "${parameters.question}"
            }
        },
        {
            "type": "MLModelTool",
            "name": "bedrock_claude_model",
            "description": "A general tool to answer any question",
            "parameters": {
                "model_id": "your_LLM_model_id",
                "prompt": "\n\nHuman:You are a professional data analysist. You will always answer 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 don't know. \n\nContext:\n${parameters.population_knowledge_base.output:-}\n\n${parameters.chat_history:-}\n\nHuman:${parameters.question}\n\nAssistant:"
            }
        }
    ]
}

{% include copy-curl.html %}

OpenSearch가 에이전트 ID로 응답해요:

{
  "agent_id": "fQ75lI0BHcHmo_czdqcJ"
}

에이전트 ID를 기록해 두세요. 다음 단계에서 사용할 거예요.

4단계: 에이전트 실행

시애틀 인구 증가를 분석하기 위해 에이전트를 실행할 거예요. 이 에이전트를 실행하면 에이전트가 새 대화를 생성해요. 나중에 다른 질문을 하여 이 대화를 계속할 수 있어요.

4.1단계: 새 대화 시작

먼저 LLM에 질문하여 새 대화를 시작하세요:

POST /_plugins/_ml/agents/your_agent_id/_execute
{
  "parameters": {
    "question": "what's the population increase of Seattle from 2021 to 2023?"
  }
}

{% include copy-curl.html %}

응답에는 LLM이 생성한 답변이 포함돼요:

{
  "inference_results": [
    {
      "output": [
        {
          "name": "memory_id",
          "result": "gQ75lI0BHcHmo_cz2acL" 
        },
        {
          "name": "parent_message_id",
          "result": "gg75lI0BHcHmo_cz2acZ"
        },
        {
          "name": "bedrock_claude_model",
          "result": """ Based on the context given:
- The metro area population of Seattle in 2021 was 3,461,000
- The current metro area population of Seattle in 2023 is 3,519,000
- So the population increase of Seattle from 2021 to 2023 is 3,519,000 - 3,461,000 = 58,000"""
        }
      ]
    }
  ]
}

응답에는 다음 필드가 포함돼요:

  • memory_id는 단일 대화 내의 모든 메시지를 그룹화하는 메모리(대화)의 식별자예요. 이 ID를 기록해 두세요. 다음 단계에서 사용할 거예요.
  • parent_message_id는 사람과 LLM 간의 현재 메시지(하나의 질문/답변)의 식별자예요. 하나의 메모리는 여러 메시지를 포함할 수 있어요.

메모리 세부 정보를 얻으려면 Get Memory API를 호출하세요:

GET /_plugins/_ml/memory/gQ75lI0BHcHmo_cz2acL

{% include copy-curl.html %}

메모리 내의 모든 메시지를 얻으려면 Get Messages API를 호출하세요:

GET /_plugins/_ml/memory/gQ75lI0BHcHmo_cz2acL/messages

{% include copy-curl.html %}

메시지 세부 정보를 얻으려면 Get Message API를 호출하세요:

GET /_plugins/_ml/memory/message/gg75lI0BHcHmo_cz2acZ

{% include copy-curl.html %}

디버깅 목적으로 Get Message Traces API를 호출하여 메시지의 추적 데이터를 얻을 수 있어요:

GET /_plugins/_ml/memory/message/gg75lI0BHcHmo_cz2acZ/traces

{% include copy-curl.html %}

4.2 새 질문으로 대화 계속하기

동일한 대화를 계속하려면 이전 단계의 메모리 ID를 제공하세요.

추가로 다음 매개변수를 제공할 수 있어요:

  • message_history_limit: 에이전트의 새 질문/답변 라운드에 포함할 과거 메시지 수를 지정하세요.
  • prompt: 이 매개변수를 사용하여 LLM 프롬프트를 사용자 지정하세요. 예를 들어 다음 예제는 새로운 지침 always learn useful information from chat history와 새로운 매개변수 next_action을 추가해요:
POST /_plugins/_ml/agents/your_agent_id/_execute
{
  "parameters": {
    "question": "What's the population of New York City in 2023?",
    "next_action": "then compare with Seattle population of 2023",
    "memory_id": "gQ75lI0BHcHmo_cz2acL",
    "message_history_limit": 5,
    "prompt": "\n\nHuman:You are a professional data analysist. You will always answer 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 don't know. \n\nContext:\n${parameters.population_knowledge_base.output:-}\n\n${parameters.chat_history:-}\n\nHuman:always learn useful information from chat history\nHuman:${parameters.question}, ${parameters.next_action}\n\nAssistant:"
  }
}

{% include copy-curl.html %}

응답에는 LLM이 생성한 답변이 포함돼요:

{
  "inference_results": [
    {
      "output": [
        {
          "name": "memory_id",
          "result": "gQ75lI0BHcHmo_cz2acL"
        },
        {
          "name": "parent_message_id",
          "result": "wQ4JlY0BHcHmo_cz8Kc-"
        },
        {
          "name": "bedrock_claude_model",
          "result": """ Based on the context given:
- The current metro area population of New York City in 2023 is 18,937,000
- The current metro area population of Seattle in 2023 is 3,519,000
- So the population of New York City in 2023 (18,937,000) is much higher than the population of Seattle in 2023 (3,519,000)"""
        }
      ]
    }
  ]
}

에이전트가 특정 Predict API 요청을 실행하는 데 사용할 도구를 알고 있다면 에이전트를 실행할 때 도구를 지정할 수 있어요. 예를 들어 이전 답변을 중국어로 번역하려면 지식 베이스에서 데이터를 검색할 필요가 없어요. Claude 모델만 실행하려면 selected_tools 매개변수에 bedrock_claude_model 도구를 지정하세요:

POST /_plugins/_ml/agents/your_agent_id/_execute
{
  "parameters": {
    "question": "Translate last answer into Chinese?",
    "selected_tools": ["bedrock_claude_model"]
  }
}

{% include copy-curl.html %}

에이전트는 selected_tools에 정의된 새 순서대로 도구를 하나씩 실행할 거예요. {: .note}

여러 지식 베이스 구성

에이전트에 대해 여러 지식 베이스를 구성할 수 있어요. 예를 들어 제품 설명과 댓글 데이터가 모두 있는 경우 다음 두 도구로 에이전트를 구성할 수 있어요:

{
    "name": "My product agent",
    "type": "conversational_flow",
    "description": "This is an agent with product description and comments knowledge bases.",
    "memory": {
        "type": "conversation_index"
    },
    "app_type": "rag",
    "tools": [
        {
            "type": "VectorDBTool",
            "name": "product_description_vectordb",
            "parameters": {
                "model_id": "your_embedding_model_id",
                "index": "product_description_data",
                "embedding_field": "product_description_embedding",
                "source_field": [
                    "product_description"
                ],
                "input": "${parameters.question}"
            }
        },
        {
            "type": "VectorDBTool",
            "name": "product_comments_vectordb",
            "parameters": {
                "model_id": "your_embedding_model_id",
                "index": "product_comments_data",
                "embedding_field": "product_comment_embedding",
                "source_field": [
                    "product_comment"
                ],
                "input": "${parameters.question}"
            }
        },
        {
            "type": "MLModelTool",
            "description": "A general tool to answer any question",
            "parameters": {
                "model_id": "{{llm_model_id}}",
                "prompt": "\n\nHuman:You are a professional product recommendation engine. You will always recommend product based on the given context. If you don't have enough context, you will ask Human to provide more information. If you don't see any related product to recommend, just say we don't have such product. \n\n Context:\n${parameters.product_description_vectordb.output}\n\n${parameters.product_comments_vectordb.output}\n\nHuman:${parameters.question}\n\nAssistant:"
            }
        }
    ]
}

{% include copy-curl.html %}

에이전트를 실행하면 에이전트가 제품 설명과 댓글 데이터를 쿼리한 다음 쿼리 결과와 질문을 LLM으로 보내요.

특정 지식 베이스를 쿼리하려면 selected_tools에 지정하세요. 예를 들어 질문이 제품 댓글에만 관련된 경우 product_comments_vectordb에서만 정보를 검색할 수 있어요:

POST /_plugins/_ml/agents/your_agent_id/_execute
{
  "parameters": {
    "question": "What feature people like the most for Amazon Echo Dot",
    "selected_tools": ["product_comments_vectordb", "MLModelTool"]
  }
}

{% include copy-curl.html %}

인덱스에서 쿼리 실행

SearchIndexTool을 사용하여 모든 인덱스에서 OpenSearch 쿼리를 실행하세요.

설정: 에이전트 등록

POST /_plugins/_ml/agents/_register
{
    "name": "Demo agent",
    "type": "conversational_flow",
    "description": "This agent supports running any search query",
    "memory": {
        "type": "conversation_index"
    },
    "app_type": "rag",
    "tools": [
        {
            "type": "SearchIndexTool",
            "parameters": {
                "input": "{\"index\": \"${parameters.index}\", \"query\": ${parameters.query} }"
            }
        },
        {
            "type": "MLModelTool",
            "description": "A general tool to answer any question",
            "parameters": {
                "model_id": "your_llm_model_id",
                "prompt": "\n\nHuman:You are a professional data analysist. You will always answer 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 don't know. \n\n Context:\n${parameters.SearchIndexTool.output:-}\n\nHuman:${parameters.question}\n\nAssistant:"
            }
        }
    ]
}

{% include copy-curl.html %}

BM25 쿼리 실행

POST /_plugins/_ml/agents/your_agent_id/_execute
{
    "parameters": {
        "question": "what's the population increase of Seattle from 2021 to 2023?",
        "index": "test_population_data",
        "query": {
            "query": {
                "match": {
                    "population_description": "${parameters.question}"
                }
            },
            "size": 2,
            "_source": "population_description"
        }
    }
}

{% include copy-curl.html %}

question 매개변수만 노출

question 매개변수만 노출하려면 에이전트를 다음과 같이 정의하세요:

POST /_plugins/_ml/agents/_register
{
  "name": "Demo agent",
  "type": "conversational_flow",
  "description": "This is a test agent support running any search query",
  "memory": {
    "type": "conversation_index"
  },
  "app_type": "rag",
  "tools": [
    {
      "type": "SearchIndexTool",
      "parameters": {
        "input": "{\"index\": \"${parameters.index}\", \"query\": ${parameters.query} }",
        "index": "test_population_data",
        "query": {
          "query": {
            "match": {
              "population_description": "${parameters.question}"
            }
          },
          "size": 2,
          "_source": "population_description"
        }
      }
    },
    {
      "type": "MLModelTool",
      "description": "A general tool to answer any question",
      "parameters": {
        "model_id": "your_llm_model_id",
        "prompt": "\n\nHuman:You are a professional data analyst. You will always answer 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 don't know. \n\n Context:\n${parameters.SearchIndexTool.output:-}\n\nHuman:${parameters.question}\n\nAssistant:"
      }
    }
  ]
}

{% include copy-curl.html %}

이제 question 매개변수만 지정하여 에이전트를 실행할 수 있어요:

POST /_plugins/_ml/agents/your_agent_id/_execute
{
    "parameters": {
        "question": "what's the population increase of Seattle from 2021 to 2023?"
    }
}

{% include copy-curl.html %}

벡터 검색 실행

POST /_plugins/_ml/agents/your_agent_id/_execute
{
    "parameters": {
        "question": "what's the population increase of Seattle from 2021 to 2023??",
        "index": "test_population_data",
        "query": {
            "query": {
                "neural": {
                    "population_description_embedding": {
                        "query_text": "${parameters.question}",
                        "model_id": "your_embedding_model_id",
                        "k": 10
                    }
                }
            },
            "size": 2,
            "_source": ["population_description"]
        }
    }
}

{% include copy-curl.html %}

question 매개변수를 노출하려면 question 매개변수만 노출을 참조하세요.

하이브리드 검색 쿼리 실행

하이브리드 검색은 키워드 검색과 벡터 검색을 결합하여 검색 관련성을 향상시켜요. 자세한 내용은 하이브리드 검색을 참조하세요.

검색 파이프라인을 구성하세요:

PUT /_search/pipeline/nlp-search-pipeline
{
    "description": "Post processor for hybrid search",
    "phase_results_processors": [
      {
        "normalization-processor": {
          "normalization": {
            "technique": "min_max"
          },
          "combination": {
            "technique": "arithmetic_mean",
            "parameters": {
              "weights": [
                0.3,
                0.7
              ]
            }
          }
        }
      }
    ]
  }

{% include copy-curl.html %}

하이브리드 쿼리로 에이전트를 실행하세요:

POST /_plugins/_ml/agents/your_agent_id/_execute
{
    "parameters": {
        "question": "what's the population increase of Seattle from 2021 to 2023??",
        "index": "test_population_data",
        "query": {
            "_source": {
                "exclude": [
                    "population_description_embedding"
                ]
            },
            "size": 2,
            "query": {
                "hybrid": {
                    "queries": [
                        {
                            "match": {
                                "population_description": {
                                    "query": "${parameters.question}"
                                }
                            }
                        },
                        {
                            "neural": {
                                "population_description_embedding": {
                                    "query_text": "${parameters.question}",
                                    "model_id": "your_embedding_model_id",
                                    "k": 10
                                }
                            }
                        }
                    ]
                }
            }
        }
    }
}

{% include copy-curl.html %}

question 매개변수를 노출하려면 question 매개변수만 노출을 참조하세요.

자연어 쿼리

PPLTool은 자연어 쿼리(NLQ)를 Piped Processing Language (PPL)로 변환하고 생성된 PPL 쿼리를 실행할 수 있어요.

설정

시작하기 전에 OpenSearch Dashboards 홈 페이지로 이동하여 Add sample data를 선택한 다음 Sample eCommerce orders를 추가하세요.

1단계: PPLTool로 에이전트 등록

PPLTool에는 다음 매개변수가 있어요:

  • model_type (열거형): CLAUDE, OPENAI, FINETUNE.
  • execute (부울): true이면 생성된 PPL 쿼리를 실행해요.
  • input (문자열): index와 question을 입력으로 제공해야 해요.

이 튜토리얼에서는 Bedrock Claude를 사용하므로 model_type을 CLAUDE로 설정하세요:

POST /_plugins/_ml/agents/_register
{
    "name": "Demo agent for NLQ",
    "type": "conversational_flow",
    "description": "This is a test flow agent for NLQ",
    "memory": {
        "type": "conversation_index"
    },
    "app_type": "rag",
    "tools": [
        {
            "type": "PPLTool",
            "parameters": {
                "model_id": "your_ppl_model_id",
                "model_type": "CLAUDE",
                "execute": true,
                "input": "{\"index\": \"${parameters.index}\", \"question\": ${parameters.question} }"
            }
        },
        {
            "type": "MLModelTool",
            "description": "A general tool to answer any question",
            "parameters": {
                "model_id": "your_llm_model_id",
                "prompt": "\n\nHuman:You are a professional data analysist. You will always answer 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 don't know. \n\n Context:\n${parameters.PPLTool.output:-}\n\nHuman:${parameters.question}\n\nAssistant:"
            }
        }
    ]
}

{% include copy-curl.html %}

2단계: NLQ로 에이전트 실행

에이전트를 실행하세요:

POST /_plugins/_ml/agents/your_agent_id/_execute
{
    "parameters": {
        "question": "How many orders do I have in last week",
        "index": "opensearch_dashboards_sample_data_ecommerce"
    }
}

{% include copy-curl.html %}

응답에는 LLM이 생성한 답변이 포함돼요:

{
    "inference_results": [
        {
            "output": [
                {
                    "name": "memory_id",
                    "result": "sqIioI0BJhBwrVXYeYOM"
                },
                {
                    "name": "parent_message_id",
                    "result": "s6IioI0BJhBwrVXYeYOW"
                },
                {
                    "name": "MLModelTool",
                    "result": " Based on the given context, the number of orders in the last week is 3992. The data shows a query that counts the number of orders where the order date is greater than 1 week ago. The query result shows the count as 3992."
                }
            ]
        }
    ]
}

자세한 내용은 Get Message Traces API를 호출하여 추적 데이터를 얻으세요:

GET _plugins/_ml/memory/message/s6IioI0BJhBwrVXYeYOW/traces

{% include copy-curl.html %}

더 알아보기 (Learn more)