# AI Prompt Template

`ai-prompt-template` 插件支持以“填空”的方式预配置提示词模板，只接受用户在指定模板变量中输入的内容。

## 替换请求体[​](#替换请求体 "替换请��求体的直接链接")

`ai-prompt-template` 插件会使用选定的 JSON 模板替换传入的请求体。模板可以使用下游插件支持的任意请求结构。以下示例配置了包含 `messages` 数组的 Chat Completions 请求体。有关 Responses API Web 搜索模板，请参阅[预定义提示词模板](https://docs.apiseven.com/apisix/how-to-guide/ai-gateway/pre-define-prompt-templates.md#%E9%85%8D%E7%BD%AE-responses-api-web-%E6%90%9C%E7%B4%A2%E6%A8%A1%E6%9D%BF)。

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

以下示例将使用 OpenAI 作为上游模型服务提供方。在开始之前，请创建一个 [OpenAI 账号](https://openai.com) 并获取 [API Key](https://openai.com/blog/openai-api)。你可以选择将密钥保存到环境变量中，如下所示：

```
export OPENAI_API_KEY=YOUR_LLM_API_KEY   # 替换为你的 API Key
```

如果你使用其他模型服务提供方，请参考该提供方的文档获取 API Key。

### 配置自定义复杂度的开放式问题模板[​](#配置自定义复杂度的开放式问题模板 "配置自定义复杂度的开放式问题模板的直接链接")

以下示例演示了如何使用 `ai-prompt-template` 插件配置一个模板，该模板可用于回答开放式问题并接受用户指定的回答复杂度。

* Admin API
* ADC
* Ingress Controller

创建一个带有预配置提示词模板的聊天完成端点路由：

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

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

  --data-binary @- <<EOF

  {

    "id": "ai-prompt-template-route",

    "uri": "/openai-chat",

    "methods": ["POST"],

    "plugins": {

      "ai-proxy": {

        "provider": "openai",

        "auth": {

          "header": {

            "Authorization": "Bearer $OPENAI_API_KEY"

          }

        },

        "options": {

          "model": "gpt-4"

        }

      },

      "ai-prompt-template": {

        "templates": [

          {

            "name": "QnA with complexity",

            "template": {

              "model": "gpt-4",

              "messages": [

                {

                  "role": "system",

                  "content": "Answer in {{complexity}}."

                },

                {

                  "role": "user",

                  "content": "Explain {{prompt}}."

                }

              ]

            }

          }

        ]

      }

    }

  }

EOF
```

❶ 在 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件中配置 OpenAI API Key。

❷ 命名模板。请求该路由时，请求应包含模板名称。

❸ 指定模型标识符。

❹ 配置一个提示词，从请求体键 `complexity` 中获取用户定义的回答复杂度。

❺ 配置一个提示词，从请求体键 `prompt` 中获取用户定义的问题。

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

adc.yaml

```
services:

  - name: prompt-template-service

    routes:

      - name: prompt-template-route

        uris:

          - /openai-chat

        methods:

          - POST

        plugins:

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: Bearer ${OPENAI_API_KEY}

            options:

              model: gpt-4

          ai-prompt-template:

            templates:

              - name: QnA with complexity

                template:

                  model: gpt-4

                  messages:

                    - role: system

                      content: Answer in {{complexity}}.

                    - role: user

                      content: Explain {{prompt}}.

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更并确认仅影响本指南的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-prompt-template
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-prompt-template
```

❶ 在 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件中配置 OpenAI API Key。

❷ 命名模板。请求该路由时，请求应包含模板名称。

❸ 指定模型标识符。

❹ 配置一个提示词，从请求体键 `complexity` 中获取用户定义的回答复杂度。

❺ 配置一个提示词，从请求体键 `prompt` 中获取用户定义的问题。

* Gateway API
* APISIX CRD

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

ai-prompt-template-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-prompt-template-plugin-config

spec:

  plugins:

    - name: ai-prompt-template

      config:

        templates:

          - name: QnA with complexity

            template:

              model: gpt-4

              messages:

                - role: system

                  content: Answer in {{complexity}}.

                - role: user

                  content: Explain {{prompt}}.

    - name: ai-proxy

      config:

        provider: openai

        auth:

          header:

            Authorization: Bearer YOUR_LLM_API_KEY

        options:

          model: gpt-4

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: prompt-template-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /openai-chat

          method: POST

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: ai-prompt-template-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f ai-prompt-template-ic.yaml
```

❶ 为模板命名。请求该路由时，请求中应包含模板名称。

❷ 指定模型标识符。

❸ 配置提示词，从请求体的 `complexity` 字段获取用户定义的回答复杂度。

❹ 配置提示词，从请求体的 `prompt` 字段获取用户定义的问题。

❺ 在 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件中配置 OpenAI API Key。

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

ai-prompt-template-ic.yaml

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

kind: ApisixRoute

metadata:

  namespace: aic

  name: prompt-template-route

spec:

  ingressClassName: apisix

  http:

    - name: prompt-template-route

      match:

        paths:

          - /openai-chat

        methods:

          - POST

      plugins:

        - name: ai-prompt-template

          enable: true

          config:

            templates:

              - name: "QnA with complexity"

                template:

                  model: gpt-4

                  messages:

                    - role: system

                      content: "Answer in {{complexity}}."

                    - role: user

                      content: "Explain {{prompt}}."

        - name: ai-proxy

          enable: true

          config:

            provider: openai

            auth:

              header:

                Authorization: "Bearer YOUR_LLM_API_KEY"

            options:

              model: gpt-4
```

将配置应用到集群：

```
kubectl apply -f ai-prompt-template-ic.yaml
```

❶ 为模板命名。请求该路由时，请求中应包含模板名称。

❷ 指定模型标识符。

❸ 配置提示词，从请求体的 `complexity` 字段获取用户定义的回答复杂度。

❹ 配置提示词，从请求体的 `prompt` 字段获取用户定义的问题。

❺ 在 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件中配置 OpenAI API Key。

现在，该路由可以被重复使用，以响应不同用户指定复杂度的各种问题。

ADC 和 Gateway API 标签页包含常规后端。在这些示例中，`ai-prompt-template` 会转换请求，随后 `ai-proxy` 会在联系该后端之前将请求发送给 LLM。请验证下方转换后的响应；仅收到后端响应并不能证明模板已运行。

向该路由发送一个 POST 请求，请求体中包含示例问题和期望的回答复杂度：

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

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

  -d '{

    "template_name": "QnA with complexity",

    "complexity": "brief",

    "prompt": "quick sort"

  }'
```

你应该会收到类似以下的响应：

```
{

  "choices": [

    {

      "finish_reason": "stop",

      "index": 0,

      "message": {

        "content": "Quick sort is a highly efficient sorting algorithm that uses a divide-and-conquer approach to arrange elements in a list or array in order. Here’s a brief explanation:\n\n1. **Choose a Pivot**: Select an element from the list as a 'pivot'. Common methods include choosing the first element, the last element, the middle element, or a random element.\n\n2. **Partitioning**: Rearrange the elements in the list such that all elements less than the pivot are moved before it, and all elements greater than the pivot are moved after it. The pivot is now in its final position.\n\n3. **Recursively Apply**: Recursively apply the same process to the sub-lists of elements to the left and right of the pivot.\n\nThe base case of the recursion is lists of size zero or one, which are already sorted.\n\nQuick sort has an average-case time complexity of O(n log n), making it suitable for large datasets. However, its worst-case time complexity is O(n^2), which occurs when the smallest or largest element is always chosen as the pivot. This can be mitigated by using good pivot selection strategies or randomization.",

        "role": "assistant"

      }

    }

  ],

  "created": 1723194057,

  "id": "chatcmpl-9uFmTYN4tfwaXZjyOQwcp0t5law4x",

  "model": "gpt-4o-2024-05-13",

  "object": "chat.completion",

  "system_fingerprint": "fp_abc28019ad",

  "usage": {

    "completion_tokens": 234,

    "prompt_tokens": 18,

    "total_tokens": 252

  }

}
```

### 配置多个模板[​](#配置多个模板 "配置多个模板的直接链接")

以下示例演示了如何在同一路由上配置多个模板。请求该路由时，用户可以通过指定模板名称向不同的模板传递自定义输入。

该示例接续[上一个示例](#%E9%85%8D%E7%BD%AE%E8%87%AA%E5%AE%9A%E4%B9%89%E5%A4%8D%E6%9D%82%E5%BA%A6%E7%9A%84%E5%BC%80%E6%94%BE%E5%BC%8F%E9%97%AE%E9%A2%98%E6%A8%A1%E6%9D%BF)。更新插件配置添加另一个模板：

* Admin API
* ADC
* Ingress Controller

更新路由以添加另一个模板：

```
curl "http://127.0.0.1:9180/apisix/admin/routes/ai-prompt-template-route" -X PATCH \

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

  -d '{

    "plugins": {

      "ai-prompt-template": {

        "templates": [

          {

            "name": "QnA with complexity",

            "template": {

              "model": "gpt-4",

              "messages": [

                {

                  "role": "system",

                  "content": "Answer in {{complexity}}."

                },

                {

                  "role": "user",

                  "content": "Explain {{prompt}}."

                }

              ]

            }

          },

          {

            "name": "echo",

            "template": {

              "model": "gpt-4",

              "messages": [

                {

                  "role": "user",

                  "content": "Echo {{prompt}}."

                }

              ]

            }

          }

        ]

      }

    }

  }'
```

更新路由配置以添加另一个模板：

adc.yaml

```
services:

  - name: prompt-template-service

    routes:

      - name: prompt-template-route

        uris:

          - /openai-chat

        methods:

          - POST

        plugins:

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: Bearer ${OPENAI_API_KEY}

            options:

              model: gpt-4

          ai-prompt-template:

            templates:

              - name: QnA with complexity

                template:

                  model: gpt-4

                  messages:

                    - role: system

                      content: Answer in {{complexity}}.

                    - role: user

                      content: Explain {{prompt}}.

              - name: echo

                template:

                  model: gpt-4

                  messages:

                    - role: user

                      content: Echo {{prompt}}.

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更并确认仅影响本指南的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-prompt-template
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-prompt-template
```

* Gateway API
* APISIX CRD

更新 `PluginConfig` 以添加另一个模板：

ai-prompt-template-multi-ic.yaml

```
# 其他配置

# ---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: ai-prompt-template-plugin-config

spec:

  plugins:

    - name: ai-prompt-template

      config:

        templates:

          - name: "QnA with complexity"

            template:

              model: gpt-4

              messages:

                - role: system

                  content: "Answer in {{complexity}}."

                - role: user

                  content: "Explain {{prompt}}."

          - name: "echo"

            template:

              model: gpt-4

              messages:

                - role: user

                  content: "Echo {{prompt}}."

    - name: ai-proxy

      config:

        provider: openai

        auth:

          header:

            Authorization: "Bearer YOUR_LLM_API_KEY"

        options:

          model: gpt-4
```

将更新后的配置应用到集群：

```
kubectl apply -f ai-prompt-template-multi-ic.yaml
```

更新 `ApisixRoute` 以添加另一个模板：

ai-prompt-template-multi-ic.yaml

```
# 其他配置

# ---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: prompt-template-route

spec:

  ingressClassName: apisix

  http:

    - name: prompt-template-route

      match:

        paths:

          - /openai-chat

        methods:

          - POST

      plugins:

        - name: ai-prompt-template

          enable: true

          config:

            templates:

              - name: "QnA with complexity"

                template:

                  model: gpt-4

                  messages:

                    - role: system

                      content: "Answer in {{complexity}}."

                    - role: user

                      content: "Explain {{prompt}}."

              - name: "echo"

                template:

                  model: gpt-4

                  messages:

                    - role: user

                      content: "Echo {{prompt}}."

        - name: ai-proxy

          enable: true

          config:

            provider: openai

            auth:

              header:

                Authorization: "Bearer YOUR_LLM_API_KEY"

            options:

              model: gpt-4
```

将更新后的配置应用到集群：

```
kubectl apply -f ai-prompt-template-multi-ic.yaml
```

现在你应该可以通过同一路由使用这两个模板。

向该路由发送一个 POST 请求并使用第一个模板：

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

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

  -d '{

    "template_name": "QnA with complexity",

    "complexity": "brief",

    "prompt": "quick sort"

  }'
```

你应该会收到类似以下的响应：

```
{

  "choices": [

    {

      "finish_reason": "stop",

      "index": 0,

      "message": {

        "content": "Quick sort is a highly efficient sorting algorithm that uses a divide-and-conquer approach to arrange elements in a list or array in order. Here’s a brief explanation:\n\n1. **Choose a Pivot**: Select an element from the list as a 'pivot'. Common methods include choosing the first element, the last element, the middle element, or a random element.\n\n2. **Partitioning**: Rearrange the elements in the list such that all elements less than the pivot are moved before it, and all elements greater than the pivot are moved after it. The pivot is now in its final position.\n\n3. **Recursively Apply**: Recursively apply the same process to the sub-lists of elements to the left and right of the pivot.\n\nThe base case of the recursion is lists of size zero or one, which are already sorted.\n\nQuick sort has an average-case time complexity of O(n log n), making it suitable for large datasets. However, its worst-case time complexity is O(n^2), which occurs when the smallest or largest element is always chosen as the pivot. This can be mitigated by using good pivot selection strategies or randomization.",

        "role": "assistant"

      }

    }

  ],

  ...

}
```

向该路由发送一个 POST 请求并使用第二个模板：

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

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

  -d '{

    "template_name": "echo",

    "prompt": "hello APISIX"

  }'
```

你应该会收到类似以下的响应：

```
{

  "choices": [

    {

      "finish_reason": "stop",

      "index": 0,

      "message": {

        "content": "hello APISIX",

        "role": "assistant"

      }

    }

  ],

  ...

}
```
