# AI RAG

`ai-rag` 插件实现检索增强生成（RAG）请求流程中的检索步骤。它根据请求生成嵌入向量并执行向量搜索，然后将检索到的内容添加到协议对应的 LLM 输入中，移除 `ai_rag` 对象后再代理请求。

当前实现使用 [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service) 生成嵌入向量，并使用 [Azure AI Search](https://azure.microsoft.com/en-us/products/ai-services/ai-search) 执行向量搜索。请在同一请求流程中使用 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件，将增强后的请求代理到 LLM 服务提供方。该插件不会创建或填充搜索索引；通过 APISIX 发送请求之前，请先准备好索引及其内容。

<!-- -->

## 按请求格式处理[​](#按请求格式处理 "按请求格式处理的直接链接")

该插件使用各协议的原生提示词结构丰富 Chat Completions、Responses API、Anthropic Messages 和 Bedrock Converse 请求。

网关会先检查 URI 特定规则，再检查仅基于请求体的规则，以识别请求格式：

* Bedrock Converse 要求 URI 以 `/converse` 结尾且包含 `messages` 数组。
* Anthropic Messages 要求 URI 以 `/v1/messages` 结尾。
* Responses API 要求 URI 以 `/v1/responses` 结尾且包含 `input` 字段。
* Chat Completions 使用 `messages` 数组。
* 当前面的规则均不匹配时，Embeddings 使用 `input`。
* 当前面的规则均不匹配时，其他非空 JSON 对象使用透传格式。

| 请求格式           | 上下文增强方式                                                                        |
| ------------------ | ------------------------------------------------------------------------------------- |
| Bedrock Converse   | 将检索到的上下文作为用户消息追加到 `messages`。                                       |
| Anthropic Messages | 将检索到的上下文作为用户消息追加到 `messages`。                                       |
| Responses API      | 将检索到的上下文追加到 `input`。                                                      |
| Chat Completions   | 将检索到的上下文作为用户消息追加到 `messages`。                                       |
| Embeddings         | 不增强请求。嵌套的 `ai_rag.embeddings` 对象用于配置内部检索时生成嵌入向量所需的输入。 |
| 其他 JSON（透传）  | 不增强请求。                                                                          |

## 示例[​](#示例 "示例的直接链接")

要运行示例，请创建 [Azure 账户](https://portal.azure.com) 并完成以下准备工作：

* 在 [Microsoft Foundry](https://ai.azure.com/) 中创建或打开 Azure OpenAI 资源，并部署聊天模型和嵌入模型。记录资源名称、API Key 和两个部署的名称。
* 按 Microsoft 的 [基本向量搜索流程](https://github.com/Azure/azure-search-vector-samples/blob/ea17a7604d6f4d67fba50c68b3e0a149aa9c05c0/demo-python/code/basic-vector-workflow/azure-search-vector-python-sample.ipynb) 创建 `vectest` 索引并载入 [示例数据](https://github.com/Azure/azure-search-vector-samples/blob/ea17a7604d6f4d67fba50c68b3e0a149aa9c05c0/data/text-sample.json)。该流程默认创建 1,024 维的 `contentVector` 字段，与本示例一致。如果使用其他索引，请在整个流程中替换索引、字段和维度。
* [获取 Azure AI Search API Key 和服务端点](https://learn.microsoft.com/en-us/azure/search/search-get-started-vector?tabs=api-key#retrieve-resource-information)。

将 API Key 和端点保存到环境变量中：

```
# 替换为你的配置值



export AZ_OPENAI_DOMAIN=https://your-openai-resource.openai.azure.com

export AZ_OPENAI_API_KEY=replace-with-azure-openai-api-key

export AZ_CHAT_DEPLOYMENT=replace-with-chat-deployment-name

export AZ_EMBEDDING_DEPLOYMENT=replace-with-embedding-deployment-name

export AZ_CHAT_ENDPOINT=${AZ_OPENAI_DOMAIN}/openai/v1/chat/completions

export AZ_EMBEDDINGS_ENDPOINT=${AZ_OPENAI_DOMAIN}/openai/v1/embeddings



export AZ_AI_SEARCH_SVC_DOMAIN=https://your-search-service.search.windows.net

export AZ_AI_SEARCH_KEY=replace-with-azure-ai-search-api-key

export AZ_AI_SEARCH_INDEX=vectest

export AZ_AI_SEARCH_ENDPOINT=${AZ_AI_SEARCH_SVC_DOMAIN}/indexes/${AZ_AI_SEARCH_INDEX}/docs/search?api-version=2024-07-01
```

### 增强 Azure OpenAI 响应[​](#增强-azure-openai-响应 "增强 Azure OpenAI 响应的直接链接")

本示例使用 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 将增强后的请求发送给 Azure OpenAI。转发前，`ai-rag` 生成嵌入向量并从 Azure AI Search 检索上下文。

* Admin API
* ADC
* Ingress Controller

创建包含 `ai-rag` 和 `ai-proxy` 的路由：

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d @- <<EOF

  {

    "id": "ai-rag-route",

    "uri": "/rag",

    "plugins": {

      "ai-rag": {

        "embeddings_provider": {

          "azure_openai": {

            "endpoint": "$AZ_EMBEDDINGS_ENDPOINT",

            "api_key": "$AZ_OPENAI_API_KEY"

          }

        },

        "vector_search_provider": {

          "azure_ai_search": {

            "endpoint": "$AZ_AI_SEARCH_ENDPOINT",

            "api_key": "$AZ_AI_SEARCH_KEY"

          }

        }

      },

      "ai-proxy": {

        "provider": "openai-compatible",

        "auth": {

          "header": {

            "api-key": "$AZ_OPENAI_API_KEY"

          }

        },

        "options": {

          "model": "$AZ_CHAT_DEPLOYMENT"

        },

        "override": {

          "endpoint": "$AZ_CHAT_ENDPOINT"

        }

      }

    }

  }

EOF
```

创建一个配置了 `ai-rag` 和 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件的路由，如下所示：

adc.yaml

```
services:

  - name: ai-rag-service

    labels:

      docs-example: ai-rag

    routes:

      - name: ai-rag-route

        uris:

          - /rag

        methods:

          - POST

        plugins:

          ai-rag:

            embeddings_provider:

              azure_openai:

                endpoint: ${AZ_EMBEDDINGS_ENDPOINT}

                api_key: ${AZ_OPENAI_API_KEY}

            vector_search_provider:

              azure_ai_search:

                endpoint: ${AZ_AI_SEARCH_ENDPOINT}

                api_key: ${AZ_AI_SEARCH_KEY}

          ai-proxy:

            provider: openai-compatible

            auth:

              header:

                api-key: ${AZ_OPENAI_API_KEY}

            options:

              model: ${AZ_CHAT_DEPLOYMENT}

            override:

              endpoint: ${AZ_CHAT_ENDPOINT}

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

ADC 的服务配置要求包含常规上游。成功的请求在访问该上游之前，就由 `ai-rag` 和 `ai-proxy` 处理。

预览此示例管理的资源变更，确认差异不包含意外的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-rag
```

同步已核对的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-rag
```

* Gateway API
* APISIX CRD

创建一个配置了 `ai-rag` 和 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件的路由，如下所示：

ai-rag-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  name: httpbin-external-domain

  namespace: aic

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      protocol: TCP

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: ai-rag-plugin-config

spec:

  plugins:

    - name: ai-rag

      config:

        embeddings_provider:

          azure_openai:

            endpoint: https://your-openai-resource.openai.azure.com/openai/v1/embeddings

            api_key: replace-with-azure-openai-api-key

        vector_search_provider:

          azure_ai_search:

            endpoint: https://your-search-service.search.windows.net/indexes/vectest/docs/search?api-version=2024-07-01

            api_key: replace-with-azure-ai-search-api-key

    - name: ai-proxy

      config:

        provider: openai-compatible

        auth:

          header:

            api-key: replace-with-azure-openai-api-key

        options:

          model: replace-with-chat-deployment-name

        override:

          endpoint: https://your-openai-resource.openai.azure.com/openai/v1/chat/completions

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: ai-rag-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /rag

          method: POST

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: ai-rag-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

HTTPRoute 包含常规后端引用。成功的请求在访问该后端之前，就由 `ai-rag` 和 `ai-proxy` 处理。

将配置应用到集群：

```
kubectl apply -f ai-rag-ic.yaml
```

创建一个配置了 `ai-rag` 和 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件的路由，如下所示：

ai-rag-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: ai-rag-route

spec:

  ingressClassName: apisix

  http:

    - name: ai-rag-route

      match:

        paths:

          - /rag

        methods:

          - POST

      plugins:

        - name: ai-rag

          enable: true

          config:

            embeddings_provider:

              azure_openai:

                endpoint: "https://your-openai-resource.openai.azure.com/openai/v1/embeddings"

                api_key: "replace-with-azure-openai-api-key"

            vector_search_provider:

              azure_ai_search:

                endpoint: "https://your-search-service.search.windows.net/indexes/vectest/docs/search?api-version=2024-07-01"

                api_key: "replace-with-azure-ai-search-api-key"

        - name: ai-proxy

          enable: true

          config:

            provider: openai-compatible

            auth:

              header:

                api-key: "replace-with-azure-openai-api-key"

            options:

              model: replace-with-chat-deployment-name

            override:

              endpoint: "https://your-openai-resource.openai.azure.com/openai/v1/chat/completions"
```

将配置应用到集群：

```
kubectl apply -f ai-rag-ic.yaml
```

发送一个聊天请求，在 `ai_rag` 中指定嵌入模型部署、向量字段和检索输入：

```
curl "http://127.0.0.1:9080/rag" -X POST \

  -H "Content-Type: application/json" \

  -d @- <<EOF

{

  "messages": [

    {

      "role": "user",

      "content": "Which Azure services are good for DevOps?"

    }

  ],

  "ai_rag": {

    "vector_search": {

      "fields": "contentVector"

    },

    "embeddings": {

      "model": "$AZ_EMBEDDING_DEPLOYMENT",

      "input": "Which Azure services are good for DevOps?",

      "dimensions": 1024

    }

  }

}

EOF
```

你应收到 `HTTP/1.1 200 OK` 响应，其中的回答使用从已配置索引中检索到的内容。响应包含类似以下的字段：

```
{

  "choices": [

    {

      "finish_reason": "stop",

      "index": 0,

      "message": {

        "content": "Azure DevOps and related services support source control, build pipelines, testing, and deployment workflows...",

        "role": "assistant"

      }

    }

  ],

  "object": "chat.completion"

}
```
