

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 亚马逊的 ML 推理管道 OpenSearch 无服务器

这个 `ml_inference` 亚马逊的处理器 OpenSearch Serverless 是一种通用处理器，它调用已配置的机器学习模型，并将该模型的输入和输出映射到文档或查询字段。你可以用控制映射 `input_map` 和 `output_map` 参数，用于指定提供模型输入的文档或查询字段以及接收模型输出的字段。

与专门制造的机器学习处理器不同，例如 `text_embedding`， `text_image_embedding`，以及 `sparse_encoding`，每个都支持一个模型类型， `ml_inference` 处理器适用于任何配置的型号。它还可以在采集管道和搜索管道中运行，因此您可以在索引期间、查询运行之前或返回结果之后应用模型推理。使用 `ml_inference` 当您需要专用处理器不提供的模型或输入和输出映射时，需要处理器。有关完整的概念文档，请参见 [机器学习推理处理器](https://docs.opensearch.org/latest/ingest-pipelines/processors/ml-inference/) 在 *OpenSearch 文档* 网站。

你可以使用 `ml_inference` 处理器以支持如下工作流程：
+ 语义搜索
+ Retrieval-augmented 世代 (RAG)
+ 多模态搜索
+ 结果汇总
+ 丰富查询

**Topics**
+ [先决条件](#serverless-ml-inference-prerequisites)
+ [示例：设置亚马逊 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 无服务器支持 `ml_inference` 矢量搜索集合上的处理器（类型 `VECTORSEARCH`) 在 NextGen 收集组。 OpenSearch Serverless 仅接受带有 `function_name` 的 `remote`。要创建集合组，请参阅 [创建收藏组](serverless-collection-groups-procedures.md#collection-groups-create)。要创建收藏集，请参阅 [使用向量搜索集合](serverless-vector-search.md)。在集合组和集合上启用备用副本。

  以下 Amazon 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 嵌入模型的示例，请参阅 [示例：设置亚马逊 Titan 嵌入模型](#serverless-ml-inference-model-setup)。有关更多信息，请参阅 [在 Amazon OpenSearch 无服务器上配置 Machine Learning](serverless-configure-machine-learning.md)。
+ **签署您的请求。**使用以下命令对所有发送到收集端点的请求进行签名 Amazon 使用服务名称对版本 4 进行签名 `aoss`。有关更多信息，请参阅 [与其他客户端签署 HTTP 请求](serverless-clients.md#serverless-signing)。

## 示例：设置亚马逊 Titan 嵌入模型
<a name="serverless-ml-inference-model-setup"></a>

本主题中的示例使用亚马逊 Bedrock 中的亚马逊 Titan 文本嵌入 V2 模型。以下步骤在您的集合中创建连接器和模型。

1. 创建一个 IAM 角色 OpenSearch Serverless 假设调用亚马逊 Bedrock。该角色的信任策略必须允许 `ml.opensearchservice.amazonaws.com` 服务主体，角色的权限策略必须允许 `bedrock:InvokeModel` 在模型上。创建连接器的主体还需要 `iam:PassRole` 在这个角色上。

1. 创建 连接器。替换 {{region}} 和 Amazon Web Services 区域 亚马逊 Bedrock 模型中， {{account-id}} 和你的 Amazon 账户 ID，以及 {{bedrock-role}} 使用上一步中的角色名称。

   ```json
   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。

   ```json
   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。

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

1. 使用预测 API 测试模型，如所示 [将处理器与您的型号相匹配](#serverless-ml-inference-match-model)。

这些步骤需要以下权限 `model` 资源类型: `aoss:CreateMLResource` 创建连接器并注册模型， `aoss:UpdateMLResource` 对其进行部署，以及 `aoss:ExecuteMLResource` 调用预测 API。有关授予这些权限的数据访问策略示例，请参阅 [配置机器学习的权限](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 测试模型，然后将参数名称和输出路径复制到您的管道中。

下表显示了映射的每个部分的来源。


| Mapping | 它必须匹配什么 | 
| --- | --- | 
| 键入 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。

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

该模型返回如下所示的响应。这个 `data` 为了便于阅读，对数组进行了缩短。

```json
{
  "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`。

**注意**  
当亚马逊 Titan 嵌入式连接器设置时，此响应形状适用 `post_process_function` 到 `connector.post_process.bedrock.embedding`。如果没有后处理函数，矢量位于 `$.inference_results[0].output[0].dataAsMap.embedding` 取而代之。有关连接器设置，请参见 [在 Amazon OpenSearch 无服务器上配置 Machine Learning](serverless-configure-machine-learning.md)。

**重要**  
请求参数和响应形状取决于模型及其连接器。当你使用不同的模型时，不要重复使用本主题中示例中的路径。为您的模型运行预测 API 并从其响应中读取路径。

例如，返回原始响应的大型语言模型具有不同的形状。文本嵌套在 `dataAsMap` 对象，并且您发送的参数以连接器占位符命名，而不是 `inputText`。

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

```json
{
  "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. 更新 `model_id`， `input_map`，以及 `output_map` 在管道中。

1. 运行 `_simulate` 对示例文档进行 API，以确认输出字段的值是否符合您的期望。

**注意**  
预测 API 需要 `aoss:ExecuteMLResource` 模型资源的权限。有关更多信息，请参阅 [在 Amazon OpenSearch 无服务器上配置 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。

```json
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"
          }
        ]
      }
    }
  ]
}
```

该请求返回以下响应：

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

这个 `output_map` 路径的根源是 `inference_results` 因为 `full_response_path` 设置为 `true`。此设置根据完整模型响应评估输出路径。有关更多信息，请参阅 [机器学习推理处理器](https://docs.opensearch.org/latest/ingest-pipelines/processors/ml-inference/) 在 *OpenSearch 文档* 网站。

在将管道应用于实时流量之前，您可以使用 `_simulate` 终点。要对索引到索引的每个文档自动运行模型推断，请设置 `index.default_pipeline` 创建索引时设置。或者，使用单个索引请求指定管道 `pipeline` 查询参数。有关创建、模拟和应用采集管道的更多信息，请参阅 [在亚马逊收录管道 OpenSearch 无服务器](serverless-ingest-pipelines.md)。

以下示例为文档编制索引并运行管道。替换 {{my-index}} 用你的索引名称和 {{my-pipeline}} 并附上您的管道名称。

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

答复证实该文件已编入索引：

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

**注意**  
必须为矢量搜索配置目标索引。启用 `index.knn` 并映射输出字段（例如， `embedding`) 作为 `knn_vector` 字段的维度与您的模型相匹配。

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

在搜索管道中， `ml_inference` 处理器将模型推断作为查询的一部分运行。搜索请求处理器会在查询运行之前对其进行转换或重写。搜索响应处理器会在您收到结果之前对其进行丰富。要运行搜索管道，请使用以下命令发送请求 `search_pipeline` 查询参数。替换 {{my-index}} 用你的索引名称和 {{my-pipeline}} 并附上您的管道名称。

```json
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 无服务器运行它。以下示例采用的文本 `match` 查询，使用已配置的模型从中生成向量，然后使用以下命令将请求重写为 k-nn 查询 `query_template` 参数。 OpenSearch 无服务器取代了 `${query_vec}` 模板中的占位符，其模型输出为 `output_map` 捕获。替换 {{my-model-id}} 使用您部署的模型的 ID。

```json
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 响应中读取的相同输出路径。

设置 `ignore_missing` 到 `true` 当源字段可能缺失时。不包含映射字段的查询，例如 `match_all` 查询，然后不变地传递而不是失败。处理器仍会重写包含该字段的查询。

### 搜索响应处理器
<a name="serverless-ml-inference-search-response"></a>

搜索响应处理器会在查询返回后运行，因此您可以丰富或汇总每次命中。以下示例发送了 `text` 将每次点击的字段写入配置的模型，并将模型输出写入 `text_vec` 领域。设置 `one_to_one` 到 `true` 这样处理器每次搜索命中都会运行一次模型。默认值是 `false`，它会在单个请求中将所有命中发送到模型，而期望单个输入值的模型则拒绝该请求。替换 {{my-model-id}} 使用您部署的模型的 ID。

```json
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。

```json
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 您的收藏的计算单位 (OCU)。在搜索管道中，其处理计入搜索 OCU，就像其他索引和搜索活动一样。具有更多处理器或计算密集型处理器的管道比简单的管道消耗更多的容量。有关容量如何扩展和计费的更多信息，请参阅 [管理亚马逊的容量限制 OpenSearch 无服务器](serverless-scaling.md) 和 [亚马逊 OpenSearch 服务定价](https://www.amazonaws.cn/opensearch-service/pricing/)。

处理器还调用您配置的远程模型，模型提供者单独开具模型推理账单。

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

管理包含以下内容的搜索和采集管道 `ml_inference` 处理器映射到以下内容 OpenSearch 无服务器数据访问策略权限。权限适用于 `collection` 资源类型。
+ `aoss:CreateCollectionItems` — 创建或更新管道。
+ `aoss:DescribeCollectionItems` — 获取、列出和模拟管道。
+ `aoss:DeleteCollectionItems` — 删除管道。

处理器还会调用您配置的模型。有关委托人创建和运行模型所需的数据访问策略权限，请参阅 [在 Amazon OpenSearch 无服务器上配置 Machine Learning](serverless-configure-machine-learning.md)。

**重要**  
通过管道发送请求的委托人需要 `aoss:ExecuteMLResource` 对模型的许可。这适用于索引文档，运行 `_simulate`，然后搜索。如果没有此权限，这些请求将失败 `Forbidden` 错误，没有命名缺失的权限。

以下示例数据访问策略向委托人授予管理集合中的管道和运行该集合中的模型的权限。替换 {{collection-name}} 上面写上你收藏的名字， {{account-id}} 和你的 Amazon 账户 ID，以及 {{role-name}} 使用管理和使用管道的 IAM 角色的名称。

```json
[
    {
        "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 无服务器权限，请参阅 [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` 处理器，请参见以下内容：
+ 有关采集流水线处理器的参考信息，请参见 [机器学习推理处理器](https://docs.opensearch.org/latest/ingest-pipelines/processors/ml-inference/) 在 *OpenSearch 文档* 网站。
+ 有关搜索请求处理器参考信息，请参阅 [机器学习推理搜索请求处理器](https://docs.opensearch.org/latest/search-plugins/search-pipelines/ml-inference-search-request/) 在 *OpenSearch 文档* 网站。
+ 有关搜索响应处理器的参考信息，请参见 [机器学习推理搜索响应处理器](https://docs.opensearch.org/latest/search-plugins/search-pipelines/ml-inference-search-response/) 在 *OpenSearch 文档* 网站。
+ 有关评论摘要和语义搜索的有效示例，请参阅 [《机器学习推理处理器简介》 OpenSearch: 评论摘要和语义搜索](https://opensearch.org/blog/introduction-to-ml-inference-processors-in-opensearch-review-summarization-and-semantic-search/) 在 *OpenSearch* 博客。