# AI Prompt Decorator

`ai-prompt-decorator` 插件通过在用户输入的提示词前后追加预设的提示词来修饰用户输入，从而在内容生成中设定上下文。这种做法有助于模型在交互过程中在预期的准则内运行。

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

该插件使用各协议的原生提示词结构修饰 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   | 将系统角色内容添加到 `system`，并将其他配置内容添加到 `messages`。         |
| Anthropic Messages | 将配置的内容添加到 `messages`。                                            |
| Responses API      | 将 `prepend` 内容添加到 `instructions`，并将 `append` 内容添加到 `input`。 |
| Chat Completions   | 在现有 `messages` 之前或之后添加配置的消息。                               |
| Embeddings         | 不修改请求，因为 Embeddings 没有提示词角色。                               |
| 其他 JSON（透传）  | 保持请求不变。                                                             |

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

以下示例使用 OpenAI 作为上游模型服务提供方。在开始之前，请创建一个 [OpenAI 账号](https://openai.com) 并获取 [API Key](https://openai.com/blog/openai-api)。使用 Admin API 或 ADC 示例前，请先导出密钥：

```
export OPENAI_API_KEY="<your-openai-api-key>"
```

对于 Ingress Controller 示例，请在应用清单前替换其中的 `<openai-api-key>` 占位符。

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

### 前置和后置消息[​](#前置和后置消息 "前置和后置消息的直接链接")

以下示例演示了如何配置 `ai-prompt-decorator` 插件，在用户输入消息前追加系统消息，并在之后追加用户消息。

* 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-decorator-route",

    "uri": "/openai-chat",

    "methods": ["POST"],

    "plugins": {

      "ai-proxy": {

        "provider": "openai",

        "auth": {

          "header": {

            "Authorization": "Bearer $OPENAI_API_KEY"

          }

        }

      },

      "ai-prompt-decorator": {

        "prepend":[

          {

            "role": "system",

            "content": "Answer briefly and conceptually."

          }

        ],

        "append":[

          {

            "role": "user",

            "content": "End the answer with a simple analogy."

          }

        ]

      }

    }

  }

EOF
```

创建一个配置了 `ai-proxy` 和 `ai-prompt-decorator` 插件的路由，如下所示：

adc.yaml

```
services:

  - name: prompt-decorator-service

    labels:

      docs-example: ai-prompt-decorator

    routes:

      - name: prompt-decorator-route

        uris:

          - /openai-chat

        methods:

          - POST

        plugins:

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: Bearer ${OPENAI_API_KEY}

          ai-prompt-decorator:

            prepend:

              - role: system

                content: Answer briefly and conceptually.

            append:

              - role: user

                content: End the answer with a simple analogy.

    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-decorator
```

同步已审查的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

* Gateway API
* APISIX CRD

创建一个配置了 `ai-proxy` 和 `ai-prompt-decorator` 插件的路由，如下所示：

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

spec:

  plugins:

    - name: ai-proxy

      config:

        provider: openai

        auth:

          header:

            Authorization: Bearer <openai-api-key>

    - name: ai-prompt-decorator

      config:

        prepend:

          - role: system

            content: Answer briefly and conceptually.

        append:

          - role: user

            content: End the answer with a simple analogy.

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: prompt-decorator-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-decorator-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

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

创建一个配置了 `ai-proxy` 和 `ai-prompt-decorator` 插件的路由，如下所示：

ai-prompt-decorator-ic.yaml

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

kind: ApisixRoute

metadata:

  namespace: aic

  name: prompt-decorator-route

spec:

  ingressClassName: apisix

  http:

    - name: prompt-decorator-route

      match:

        paths:

          - /openai-chat

        methods:

          - POST

      plugins:

        - name: ai-proxy

          enable: true

          config:

            provider: openai

            auth:

              header:

                Authorization: "Bearer <openai-api-key>"

        - name: ai-prompt-decorator

          enable: true

          config:

            prepend:

              - role: system

                content: "Answer briefly and conceptually."

            append:

              - role: user

                content: "End the answer with a simple analogy."
```

将配置应用到集群：

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

❶ 在 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件中配置 OpenAI API Key。如果不希望在 APISIX 中配置该密钥，也可以选择在每个客户端请求中附带 API Key。

❷ 前置一条系统消息以设定助手的行为。

❸ 在用户定义的提示词后追加额外的用户消息。

ADC 和 Gateway API 标签页包含一个常规后端。在这些示例中，`ai-prompt-decorator` 会修改请求，而 `ai-proxy` 会在访问该后端之前将请求发送给 LLM。请验证下方经过修饰的响应；仅收到后端响应并不能证明这些插件已运行。

向该路由发送一个 POST 请求，在请求体中指定模型和示例消息：

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

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

  -d '{

    "model": "gpt-4",

    "messages": [{ "role": "user", "content": "What is mTLS authentication?" }]

  }'
```

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

```
{

  "choices": [

    {

      "finish_reason": "stop",

      "index": 0,

      "message": {

        "content": "Mutual TLS (mTLS) authentication is a security protocol that ensures both the client and server authenticate each other's identity before establishing a connection. This mutual authentication is achieved through the exchange and verification of digital certificates, which are cryptographically signed credentials proving each party's identity. In contrast to standard TLS, where only the server is authenticated, mTLS adds an additional layer of trust by verifying the client as well, providing enhanced security for sensitive communications.\n\nThink of mTLS as a secret handshake between two friends meeting at a club. Both must know the handshake to get in, ensuring they recognize and trust each other before entering.",

        "role": "assistant"

      }

    }

  ],

  "created": 1723193502,

  "id": "chatcmpl-9uFdWDlwKif6biCt9DpG0xgedEamg",

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

  "object": "chat.completion",

  "system_fingerprint": "fp_abc28019ad",

  "usage": {

    "completion_tokens": 124,

    "prompt_tokens": 31,

    "total_tokens": 155

  }

}
```
