

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Amazon OpenSearch Serverless 中的 ML 推論管道

Amazon OpenSearch Serverless 中的`ml_inference`處理器是一種一般用途處理器，可呼叫設定的機器學習模型，並將模型的輸入和輸出映射至文件或查詢欄位。您可以使用 `input_map`和 `output_map` 參數控制映射，指定提供模型輸入的文件或查詢欄位，以及接收模型輸出的欄位。

與各支援單一模型類型的專用機器學習處理器不同`sparse_encoding`，例如 `text_image_embedding`、 `text_embedding`和 ，`ml_inference`處理器可與任何設定的模型搭配使用。它也可以在擷取管道和搜尋管道中執行，因此您可以在編製索引期間、查詢執行之前或傳回結果之後套用模型推論。當您需要專用`ml_inference`處理器未提供的模型或輸入和輸出映射時，請使用處理器。如需完整的概念文件，請參閱 *OpenSearch 文件*網站上的 [ML 推論處理器](https://docs.opensearch.org/latest/ingest-pipelines/processors/ml-inference/)。

您可以使用`ml_inference`處理器來支援工作流程，例如：
+ 語意搜尋
+ 擷取經調整的產生 (RAG)
+ 多模式搜尋
+ 結果摘要
+ 查詢擴充

**Topics**
+ [先決條件](#serverless-ml-inference-prerequisites)
+ [範例：設定 Amazon Titan 內嵌模型](#serverless-ml-inference-model-setup)
+ [將處理器與您的模型配對](#serverless-ml-inference-match-model)
+ [在擷取管道中使用 ml\_inference](#serverless-ml-inference-ingest)
+ [在搜尋管道中使用 ml\_inference](#serverless-ml-inference-search)
+ [定價](#serverless-ml-inference-pricing)
+ [所需的許可](#serverless-ml-inference-permissions)
+ [疑難排解](#serverless-ml-inference-troubleshooting)
+ [如需詳細資訊](#serverless-ml-inference-more-info)

## 先決條件
<a name="serverless-ml-inference-prerequisites"></a>

使用`ml_inference`處理器之前，請先完成下列操作：
+ **建立向量搜尋集合。**OpenSearch Serverless 支援 NextGen 集合群組中向量搜尋集合 （類型 `VECTORSEARCH`) 上的`ml_inference`處理器。OpenSearch Serverless 僅接受具有 之 `function_name`的模型`remote`。若要建立集合群組，請參閱 [建立集合群組](serverless-collection-groups-procedures.md#collection-groups-create)。若要建立集合，請參閱 [使用向量搜尋集合](serverless-vector-search.md)。在集合群組和集合上啟用待命複本。

  下列 AWS CLI 範例會在其中建立 NextGen 集合群組和向量搜尋集合。將 {{my-collection-group}} 和 {{my-collection}} 取代為您自己的名稱。

  ```
  aws opensearchserverless create-collection-group \
      --name {{my-collection-group}} \
      --generation NEXTGEN \
      --standby-replicas ENABLED \
      --capacity-limits maxIndexingCapacityInOCU={{8}},maxSearchCapacityInOCU={{8}}
  
  aws opensearchserverless create-collection \
      --name {{my-collection}} \
      --type VECTORSEARCH \
      --collection-group-name {{my-collection-group}} \
      --standby-replicas ENABLED
  ```
+ **設定和部署遠端模型。**處理器會呼叫已設定和已部署的遠端模型，您依其模型 ID 參考該模型。如需設定 Amazon Titan 內嵌模型的範例，請參閱 [範例：設定 Amazon Titan 內嵌模型](#serverless-ml-inference-model-setup)。如需詳細資訊，請參閱[在 Amazon OpenSearch Serverless 上設定Machine Learning](serverless-configure-machine-learning.md)。
+ **簽署您的請求。**使用服務名稱 ，使用 AWS Signature 第 4 版將每個請求簽署至集合端點`aoss`。如需詳細資訊，請參閱[使用其他用戶端簽署 HTTP 請求](serverless-clients.md#serverless-signing)。

## 範例：設定 Amazon Titan 內嵌模型
<a name="serverless-ml-inference-model-setup"></a>

本主題中的範例使用 Amazon Bedrock 中的 Amazon Titan Text Embeddings V2 模型。下列步驟會在您的集合中建立連接器和模型。

1. 建立 OpenSearch Serverless 擔任以呼叫 Amazon Bedrock 的 IAM 角色。角色的信任政策必須允許 `ml.opensearchservice.amazonaws.com` 服務主體，而且角色的許可政策必須在模型`bedrock:InvokeModel`上允許 。建立連接器的主體也需要`iam:PassRole`此角色。

1. 建立連接器。將{{區域}}取代為 Amazon Bedrock 模型 AWS 區域 的 、將 {{account-id}} 取代為 AWS 您的帳戶 ID，並將 {{bedrock-role}} 取代為上一個步驟的角色名稱。

   ```
   POST /_plugins/_ml/connectors/_create
   {
     "name": "Amazon Bedrock Titan Text Embeddings V2",
     "description": "Connector for amazon.titan-embed-text-v2:0",
     "version": 1,
     "protocol": "aws_sigv4",
     "parameters": {
       "region": "{{region}}",
       "service_name": "bedrock",
       "model": "amazon.titan-embed-text-v2:0"
     },
     "credential": {
       "roleArn": "arn:aws:iam::{{account-id}}:role/{{bedrock-role}}"
     },
     "actions": [
       {
         "action_type": "predict",
         "method": "POST",
         "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/invoke",
         "headers": {
           "content-type": "application/json",
           "x-amz-content-sha256": "required"
         },
         "request_body": "{ \"inputText\": \"${parameters.inputText}\" }",
         "post_process_function": "connector.post_process.bedrock.embedding"
       }
     ]
   }
   ```

   回應包含連接器 ID。`post_process_function` 設定會傳回內嵌於 `$.inference_results[0].output[0].data`，這是本主題中範例使用的路徑。

1. 向連接器註冊模型。將 {{my-connector-id}} 取代為上一個步驟的連接器 ID。

   ```
   POST /_plugins/_ml/models/_register
   {
     "name": "titan-embed-text-v2",
     "function_name": "remote",
     "description": "Amazon Titan Text Embeddings V2",
     "connector_id": "{{my-connector-id}}"
   }
   ```

   回應包含模型 ID。

1. 部署模型。將 {{my-model-id}} 取代為上一個步驟的模型 ID。

   ```
   POST /_plugins/_ml/models/{{my-model-id}}/_deploy
   ```

1. 使用預測 API 測試模型，如 所示[將處理器與您的模型配對](#serverless-ml-inference-match-model)。

這些步驟需要`model`資源類型的下列許可：`aoss:CreateMLResource`建立連接器並註冊模型、`aoss:UpdateMLResource`部署模型，以及`aoss:ExecuteMLResource`呼叫預測 API。如需授予這些許可的資料存取政策範例，請參閱 [設定Machine Learning的許可](serverless-configure-machine-learning.md#serverless-configure-machine-learning-permissions)。

## 將處理器與您的模型配對
<a name="serverless-ml-inference-match-model"></a>

`ml_inference` 處理器不知道模型的形狀。您可以使用 `input_map`和 來告知它`output_map`。如果這些不符合模型的預測 API，處理器會失敗或寫入錯誤的值。先使用預測 API 測試模型，然後將參數名稱和輸出路徑複製到管道。

下表顯示映射每個部分的來源。


| 映射 | 必須符合的項目 | 
| --- | --- | 
| 中的金鑰 input\_map | 預測請求中的參數名稱，這是連接器 中的${parameters.{{name}}}預留位置request\_body。 | 
| 中的值 input\_map | 提供值的文件欄位或查詢欄位。 | 
| 中的金鑰 output\_map | 接收模型輸出的欄位名稱。 | 
| 中的值 output\_map | 預測回應的 JSON 路徑，例如 $.inference\_results[0].output[0].data。 | 

下列範例會呼叫文字內嵌模型的預測 API。`inputText` 參數是擷取管道範例用作 中金鑰的相同名稱`input_map`。將 {{my-model-id}} 取代為您部署模型的 ID。

```
POST /_plugins/_ml/models/{{my-model-id}}/_predict
{
  "parameters": {
    "inputText": "Example document text"
  }
}
```

模型會傳回如下所示的回應。`data` 陣列縮短可讀性。

```
{
  "inference_results": [
    {
      "output": [
        {
          "name": "sentence_embedding",
          "data_type": "FLOAT32",
          "shape": [1024],
          "data": [0.0123, -0.0456, 0.0789]
        }
      ],
      "status_code": 200
    }
  ]
}
```

內嵌項目位於第一個輸出的`data`陣列中。JSON 路徑會`$.inference_results[0].output[0].data`選取它。這是擷取管道範例在 中使用的路徑`output_map`。

**注意**  
此回應形狀會在 Amazon Titan 內嵌連接器`post_process_function`設定為 時套用`connector.post_process.bedrock.embedding`。如果沒有後製處理函數，則向量會`$.inference_results[0].output[0].dataAsMap.embedding`改為位於 。如需連接器設定，請參閱 [在 Amazon OpenSearch Serverless 上設定Machine Learning](serverless-configure-machine-learning.md)。

**重要**  
請求參數和回應形狀取決於模型及其連接器。當您使用不同的模型時，請勿重複使用本主題中範例的路徑。為您的模型執行預測 API，並從其回應讀取路徑。

例如，傳回其原始回應的大型語言模型具有不同的形狀。文字會巢狀在 `dataAsMap` 物件內，而您傳送的參數是以連接器預留位置命名，而不是以 命名`inputText`。

```
POST /_plugins/_ml/models/{{my-llm-model-id}}/_predict
{
  "parameters": {
    "messages": "[{\"role\":\"user\",\"content\":[{\"text\":\"Summarize: Example text\"}]}]"
  }
}
```

```
{
  "inference_results": [
    {
      "output": [
        {
          "name": "response",
          "dataAsMap": {
            "output": {
              "message": {
                "role": "assistant",
                "content": [
                  {
                    "text": "A short summary of the example text."
                  }
                ]
              }
            },
            "stopReason": "end_turn"
          }
        }
      ],
      "status_code": 200
    }
  ]
}
```

對於此回應，JSON 路徑為 `$.inference_results[0].output[0].dataAsMap.output.message.content[0].text`。下的確切結構`dataAsMap`是模型提供者的回應，因此提供者和模型之間有所不同。

若要將處理器切換到不同的模型，請執行下列動作：

1. 在模型連接器`request_body`的 中尋找參數名稱。每個`${parameters.{{name}}}`預留位置都是您可以在 中用作索引鍵的名稱`input_map`。

1. 使用每個參數的範例值呼叫預測 API。

1. 讀取預測回應，並將 JSON 路徑寫入您要保留的值。

1. 在管道`output_map`中更新 `input_map`、 `model_id`和 。

1. 在範例文件上執行 `_simulate` API，以確認輸出欄位具有您預期的值。

**注意**  
預測 API 需要模型資源的 `aoss:ExecuteMLResource` 許可。如需詳細資訊，請參閱[在 Amazon OpenSearch Serverless 上設定Machine Learning](serverless-configure-machine-learning.md)。

## 在擷取管道中使用 ml\_inference
<a name="serverless-ml-inference-ingest"></a>

在擷取管道中，`ml_inference`處理器會在索引期間執行模型推論。常見的用途是從文字欄位產生向量內嵌，讓您可以對資料執行語意搜尋。會將文件欄位`input_map`映射至模型輸入，並將模型輸出`output_map`寫入新欄位。

下列範例會建立管道，將 `text` 欄位傳送至模型，並將傳回的內嵌寫入 `embedding` 欄位。將 {{my-pipeline}} 取代為您的管道名稱，並將 {{my-model-id}} 取代為您部署模型的 ID。

```
PUT _ingest/pipeline/{{my-pipeline}}
{
  "description": "Generates embeddings with a configured model",
  "processors": [
    {
      "ml_inference": {
        "model_id": "{{my-model-id}}",
        "full_response_path": true,
        "input_map": [
          {
            "inputText": "text"
          }
        ],
        "output_map": [
          {
            "embedding": "$.inference_results[0].output[0].data"
          }
        ]
      }
    }
  ]
}
```

請求會傳回下列回應：

```
{
  "acknowledged": true
}
```

`output_map` 路徑的根目錄為 ，`inference_results`因為 `full_response_path` 設定為 `true`。此設定會根據完整的模型回應評估輸出路徑。如需詳細資訊，請參閱 *OpenSearch 文件*網站上的 [ML 推論處理器](https://docs.opensearch.org/latest/ingest-pipelines/processors/ml-inference/)。

將管道套用到即時流量之前，您可以針對具有`_simulate`端點的範例文件進行模擬。若要在索引為索引的每個文件上自動執行模型推論，請在建立索引時設定 `index.default_pipeline`設定。或者，使用`pipeline`查詢參數在個別索引請求上指定管道。如需建立、模擬和套用擷取管道的詳細資訊，請參閱 [在 Amazon OpenSearch Serverless 中擷取管道](serverless-ingest-pipelines.md)。

下列範例會為文件編製索引並執行管道。將 {{my-index}} 取代為您的索引名稱，將 {{my-pipeline}} 取代為您的管道名稱。

```
POST {{my-index}}/_doc?pipeline={{my-pipeline}}
{
  "text": "Example document text"
}
```

回應會確認文件已編製索引：

```
{
  "_index": "my-index",
  "_id": "93VTg6EBtHTIBjFym5yW",
  "_version": 1,
  "result": "created",
  "_shards": {
    "total": 0,
    "successful": 0,
    "failed": 0
  },
  "_seq_no": 0,
  "_primary_term": 0
}
```

**注意**  
目標索引必須設定為向量搜尋。啟用輸出欄位 （例如，`embedding`) `index.knn`並將其對應為具有符合您模型之維度`knn_vector`的欄位。

## 在搜尋管道中使用 ml\_inference
<a name="serverless-ml-inference-search"></a>

在搜尋管道中，`ml_inference`處理器會在查詢中執行模型推論。搜尋請求處理器會在執行之前轉換或重寫查詢。搜尋回應處理器會先充實結果，再接收結果。若要執行搜尋管道，請使用`search_pipeline`查詢參數傳送請求。將 {{my-index}} 取代為您的索引名稱，將 {{my-pipeline}} 取代為您的管道名稱。

```
POST {{my-index}}/_search?search_pipeline={{my-pipeline}}
```

若要建立或更新搜尋管道，請將管道內文傳送至`_search/pipeline`端點，如下列各節中的範例所示。

**注意**  
即使建立請求傳回 ，新建立的搜尋管道仍可能需要幾分鐘才會生效`"acknowledged": true`。在此之前，參考管道的搜尋請求會失敗並顯示`Pipeline {{my-pipeline}} is not defined`錯誤。在短暫等待後重試請求。

### 搜尋請求處理器
<a name="serverless-ml-inference-search-request"></a>

您可以在 OpenSearch Serverless 執行前，使用搜尋請求處理器來重寫傳入的查詢。下列範例採用`match`查詢的文字、使用設定的模型從中產生向量，並使用 `query_template` 參數將請求重寫至 k-NN 查詢。OpenSearch Serverless 會將範本中的`${query_vec}`預留位置取代為`output_map`擷取的模型輸出。將 {{my-model-id}} 取代為您部署模型的 ID。

```
PUT /_search/pipeline/{{my-pipeline}}
{
  "request_processors": [
    {
      "ml_inference": {
        "model_id": "{{my-model-id}}",
        "full_response_path": true,
        "query_template": "{\"size\":2,\"_source\":[\"text\"],\"query\":{\"knn\":{\"embedding\":{\"vector\":${query_vec},\"k\":2}}}}",
        "input_map": [
          {
            "inputText": "query.match.text.query"
          }
        ],
        "output_map": [
          {
            "query_vec": "$.inference_results[0].output[0].data"
          }
        ],
        "ignore_missing": true
      }
    }
  ]
}
```

`full_response_path` 設定為 ，`true`讓 `output_map` JSON 路徑針對完整模型回應進行解析。這可讓您使用從預測 API 回應讀取的相同輸出路徑。

當來源欄位可能遺失`true`時，`ignore_missing`將 設定為 。不包含映射欄位的查詢，例如`match_all`查詢，然後傳遞不變而不是失敗。處理器仍會重寫包含 欄位的查詢。

### 搜尋回應處理器
<a name="serverless-ml-inference-search-response"></a>

搜尋回應處理器會在查詢傳回後執行，因此您可以豐富或摘要每個命中項目。下列範例會將每個命中項目`text`的欄位傳送至設定的模型，並將模型輸出寫入`text_vec`欄位。將 `one_to_one`設定為 ，`true`讓處理器針對每個搜尋命中執行一次模型。預設值為 `false`，其會在單一請求中將所有命中項目傳送至模型，而預期單一輸入值會拒絕該請求的模型。將 {{my-model-id}} 取代為您部署模型的 ID。

```
PUT /_search/pipeline/{{my-pipeline}}
{
  "response_processors": [
    {
      "ml_inference": {
        "model_id": "{{my-model-id}}",
        "full_response_path": true,
        "input_map": [
          {
            "inputText": "text"
          }
        ],
        "output_map": [
          {
            "text_vec": "$.inference_results[0].output[0].data"
          }
        ],
        "one_to_one": true
      }
    }
  ]
}
```

若要使用大型語言模型摘要結果，請新增包含模型提示的`model_config`物件，並將 `one_to_one`設定為 ，`true`讓處理器分別摘要每個搜尋命中項目。提示可以透過範本參數參考映射的輸入，例如 `${parameters.context}`。此範例中的`output_map`路徑符合傳回其原始回應的模型。如需詳細資訊，請參閱[將處理器與您的模型配對](#serverless-ml-inference-match-model)。將 {{my-model-id}} 取代為您部署模型的 ID。

```
PUT /_search/pipeline/{{my-pipeline}}
{
  "response_processors": [
    {
      "ml_inference": {
        "model_id": "{{my-model-id}}",
        "full_response_path": true,
        "input_map": [
          {
            "context": "text"
          }
        ],
        "output_map": [
          {
            "summary": "$.inference_results[0].output[0].dataAsMap.output.message.content[0].text"
          }
        ],
        "model_config": {
          "messages": "[{\"role\":\"user\",\"content\":[{\"text\":\"Summarize the following text: ${parameters.context}\"}]}]"
        },
        "one_to_one": true
      }
    }
  ]
}
```

## 定價
<a name="serverless-ml-inference-pricing"></a>

`ml_inference` 處理器會在處理集合請求的運算上執行。在擷取管道中，其處理會計入集合的 OpenSearch Compute Units (OCUs) 索引。在搜尋管道中，其處理會計入搜尋 OCUs，就像其他索引和搜尋活動一樣。比起簡單管道，具有更多處理器或運算密集型處理器的管道會耗用更多容量。如需容量如何擴展和計費的詳細資訊，請參閱 [管理 Amazon OpenSearch Serverless 的容量限制](serverless-scaling.md)和 [Amazon OpenSearch Service 定價](https://aws.amazon.com/opensearch-service/pricing/)。

處理器也會叫用您設定的遠端模型，模型提供者會分別向模型推論收費。

## 所需的許可
<a name="serverless-ml-inference-permissions"></a>

管理包含`ml_inference`處理器的搜尋和擷取管道會映射至下列 OpenSearch Serverless 資料存取政策許可。許可適用於 `collection` 資源類型。
+ `aoss:CreateCollectionItems` – 建立或更新管道。
+ `aoss:DescribeCollectionItems` – 取得、列出和模擬管道。
+ `aoss:DeleteCollectionItems` – 刪除管道。

處理器也會呼叫您設定的模型。如需主體建立和執行模型所需的資料存取政策許可，請參閱 [在 Amazon OpenSearch Serverless 上設定Machine Learning](serverless-configure-machine-learning.md)。

**重要**  
透過管道傳送請求的委託人需要模型的 `aoss:ExecuteMLResource` 許可。這適用於編製文件索引、執行 `_simulate`和搜尋。如果沒有此許可，這些請求會失敗，並顯示錯誤，該`Forbidden`錯誤不會將缺少的許可命名為 。

下列範例資料存取政策會授予委託人許可，以管理集合中的管道，以及在該集合中執行模型。將 {{collection-name}} 取代為您的集合名稱、將 {{account-id}} 取代為您的 AWS 帳戶 ID，並將 {{role-name}} 取代為管理和使用管道的 IAM 角色名稱。

```
[
    {
        "Description": "Manage pipelines and run models",
        "Rules": [
            {
                "ResourceType": "collection",
                "Resource": ["collection/{{collection-name}}"],
                "Permission": [
                    "aoss:CreateCollectionItems",
                    "aoss:DescribeCollectionItems",
                    "aoss:DeleteCollectionItems"
                ]
            },
            {
                "ResourceType": "model",
                "Resource": ["model/{{collection-name}}/*"],
                "Permission": [
                    "aoss:ExecuteMLResource"
                ]
            }
        ],
        "Principal": [
            "arn:aws:iam::{{account-id}}:role/{{role-name}}"
        ]
    }
]
```

如需 OpenSearch API 操作與 OpenSearch Serverless 許可的完整映射，請參閱 [Amazon OpenSearch Serverless 中支援的操作和外掛程式](serverless-genref.md)。

## 疑難排解
<a name="serverless-ml-inference-troubleshooting"></a>

如果使用 `ml_inference`管道的請求失敗並發生錯誤`Forbidden`，請檢查下列常見原因：
+ 呼叫主體在模型`aoss:ExecuteMLResource`上沒有 。將`model`規則新增至資料存取政策，如 所示[所需的許可](#serverless-ml-inference-permissions)。
+ 資料存取政策不會授予委託人操作的索引或集合許可，例如撰寫文件、搜尋或建立管道。
+ 使用服務名稱`es`而非 簽署請求`aoss`。
+ 集合的網路政策不允許從請求的來源存取 。

如果搜尋請求在您建立管道後立即失敗並出現`Pipeline {{my-pipeline}} is not defined`錯誤，請等待幾分鐘後重試。如需詳細資訊，請參閱[在搜尋管道中使用 ml\_inference](#serverless-ml-inference-search)。

## 如需詳細資訊
<a name="serverless-ml-inference-more-info"></a>

如需`ml_inference`處理器的詳細資訊，請參閱下列內容：
+ 如需擷取管道處理器參考，請參閱 *OpenSearch 文件*網站上的 [ML 推論處理器](https://docs.opensearch.org/latest/ingest-pipelines/processors/ml-inference/)。
+ 如需搜尋請求處理器參考，請參閱 *OpenSearch 文件*網站上的 [ML 推論搜尋請求處理器](https://docs.opensearch.org/latest/search-plugins/search-pipelines/ml-inference-search-request/)。
+ 如需搜尋回應處理器參考，請參閱 *OpenSearch 文件*網站上的 [ML 推論搜尋回應處理器](https://docs.opensearch.org/latest/search-plugins/search-pipelines/ml-inference-search-response/)。
+ 如需檢閱摘要和語意搜尋的工作範例，請參閱 [ OpenSearch 中的 ML 推論處理器簡介：OpenSearch 部落格上的檢閱摘要和語意搜尋](https://opensearch.org/blog/introduction-to-ml-inference-processors-in-opensearch-review-summarization-and-semantic-search/)。 *OpenSearch* 