# AI Prompt Decorator

The `ai-prompt-decorator` plugin modifies user input prompts by prefixing and appending pre-engineered prompts to set contexts in content generation. This practice helps the model operate within desired guidelines during interactions.

## Behavior by Request Format[​](#behavior-by-request-format "Direct link to Behavior by Request Format")

The plugin decorates Chat Completions, Responses API, Anthropic Messages, and Bedrock Converse requests using each protocol's native prompt structure.

The gateway identifies each request by checking URI-specific rules before body-only rules:

* Bedrock Converse requires a URI ending in `/converse` and a `messages` array.
* Anthropic Messages requires a URI ending in `/v1/messages`.
* Responses API requires a URI ending in `/v1/responses` and an `input` field.
* Chat Completions uses a `messages` array.
* Embeddings uses `input` after the earlier rules do not match.
* Other non-empty JSON objects use passthrough after none of the earlier rules match.

| Request format           | Prompt decoration                                                                |
| ------------------------ | -------------------------------------------------------------------------------- |
| Bedrock Converse         | Adds system-role content to `system` and other configured content to `messages`. |
| Anthropic Messages       | Adds configured content to `messages`.                                           |
| Responses API            | Adds `prepend` content to `instructions` and `append` content to `input`.        |
| Chat Completions         | Adds configured messages before or after the existing `messages`.                |
| Embeddings               | Does not modify the request because Embeddings has no prompt roles.              |
| Other JSON (passthrough) | Leaves the request unchanged.                                                    |

## Example[​](#example "Direct link to Example")

The following example uses OpenAI as the upstream service provider. Before proceeding, create an [OpenAI account](https://openai.com) and an [API key](https://openai.com/blog/openai-api). Export the key before using the Admin API or ADC example:

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

For the Ingress Controller example, replace the `<openai-api-key>` placeholder in the manifest before applying it.

If you are working with other LLM providers, please refer to the provider's documentation to obtain an API key.

### Prepend and Append Messages[​](#prepend-and-append-messages "Direct link to Prepend and Append Messages")

The following example demonstrates how to configure the `ai-prompt-decorator` plugin to prepend a system message and append a user message to the user input message.

* Admin API
* ADC
* Ingress Controller

Create a route to the chat completion endpoint with pre-configured prompt templates as such:

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

Create a route with the `ai-proxy` and `ai-prompt-decorator` plugins configured as such:

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

Preview the changes for this example and confirm that the diff contains no unintended updates or deletions:

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

Synchronize the reviewed service configuration:

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

* Gateway API
* APISIX CRD

Create a route with the `ai-proxy` and `ai-prompt-decorator` plugins configured as such:

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

Apply the configuration to your cluster:

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

Create a route with the `ai-proxy` and `ai-prompt-decorator` plugins configured as such:

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."
```

Apply the configuration to your cluster:

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

❶ Configure the OpenAI API key in the [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md) plugin. Alternatively, you can choose to attach the API key in every client request if you do not wish to configure the key in APISIX.

❷ Prepend a system message to set the behavior of the assistant.

❸ Append additional user message to the user-defined prompt.

The ADC and Gateway API tabs include a conventional backend. In these examples, `ai-prompt-decorator` modifies the request and `ai-proxy` sends it to the LLM before that backend is contacted. Verify the decorated response below; a backend response alone does not confirm that the plugins ran.

Send a POST request to the route specifying the model and a sample message in the request body:

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

  }'
```

You should receive a response similar to the following:

```
{

  "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

  }

}
```
