# Implement Prompt Templates and Decorators

This guide shows how to standardize prompt behavior at the gateway layer using [`ai-prompt-decorator`](https://docs.api7.ai/hub/ai-prompt-decorator.md) and [`ai-prompt-template`](https://docs.api7.ai/hub/ai-prompt-template.md). You will configure reusable prompt templates, enforce system instructions, and combine both plugins with [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md).

## Overview[​](#overview "Direct link to Overview")

Gateway-level prompt engineering keeps prompt policy out of application code. Platform teams can enforce consistent behavior across services, update instructions centrally, and reduce drift between teams.

API7 AI Gateway provides two complementary patterns:

* **Prompt decoration** with [`ai-prompt-decorator`](https://docs.api7.ai/hub/ai-prompt-decorator.md): prepend or append messages to each request.
* **Prompt templating** with [`ai-prompt-template`](https://docs.api7.ai/hub/ai-prompt-template.md): define named templates with `{{variable}}` substitution.

## Prerequisites[​](#prerequisites "Direct link to Prerequisites")

* Install [Docker](https://docs.docker.com/get-docker/).

* Install [cURL](https://curl.se/) to send requests to the services for validation.

* Have a running API7 Gateway instance.

* Create a [token from the Dashboard](https://docs.api7.ai/api7-gateway/reference/obtain-dashboard-token.md) and save it to an environment variable:

  ```
  export API_KEY=your-dashboard-token   # replace with your Dashboard token
  ```

* Replace `{gateway_group_id}` with your gateway group ID. Use `default` if you are following the quickstart.

* If you are following the Admin API examples, create or reuse a service in API7 Gateway. If you do not have one yet, follow [Create or Reuse a Service](https://docs.api7.ai/api7-gateway/ai-gateway/get-started.md#create-or-reuse-a-service), then save its ID to an environment variable:

  ```
  export SERVICE_ID=your-service-id         # replace with your service ID
  ```

## Prompt Decoration[​](#prompt-decoration "Direct link to Prompt Decoration")

Use `ai-prompt-decorator` to inject global instructions before and after user messages.

* Admin API
* ADC

```
curl -k "https://localhost:7443/apisix/admin/routes/ai-prompt-decoration?gateway_group_id={gateway_group_id}" -X PUT \

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

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

  --data-binary @- <<EOF

  {

    "name": "ai-prompt-decoration",

    "service_id": "$SERVICE_ID",

    "paths": ["/ai/decorated"],

    "plugins": {

      "ai-proxy": {

        "provider": "openai",

        "auth": { "header": { "Authorization": "Bearer $OPENAI_API_KEY" } },

        "options": { "model": "gpt-4o" }

      },

      "ai-prompt-decorator": {

        "prepend": [

          {

            "role": "system",

            "content": "You are a customer support assistant for Acme Corp. Reply with concise, policy-compliant answers."

          }

        ],

        "append": [

          {

            "role": "system",

            "content": "If the user asks for account actions, ask for ticket ID before proceeding."

          }

        ]

      }

    }

  }

EOF
```

❶ `prepend` inserts messages at the beginning of the conversation, typically for mandatory system instructions.

❷ `append` inserts messages at the end of the conversation, useful for additional policy reminders.

adc.yaml

```
services:

  - name: AI Prompt Decoration

    routes:

      - uris:

          - /ai/decorated

        name: ai-prompt-decoration

        plugins:

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: "Bearer ${OPENAI_API_KEY}"

            options:

              model: gpt-4o

          ai-prompt-decorator:

            prepend:

              - role: system

                content: You are a customer support assistant for Acme Corp. Reply with concise, policy-compliant answers.

            append:

              - role: system

                content: If the user asks for account actions, ask for ticket ID before proceeding.

    labels:

      docs-example: ai-prompt-decoration
```

❶ `prepend` inserts messages at the beginning of the conversation, typically for mandatory system instructions.

❷ `append` inserts messages at the end of the conversation, useful for additional policy reminders.

Preview the changes owned by 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-decoration
```

Synchronize the reviewed configuration:

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

For the full configuration reference, see [`ai-prompt-decorator`](https://docs.api7.ai/hub/ai-prompt-decorator.md).

## Prompt Templating[​](#prompt-templating "Direct link to Prompt Templating")

Use `ai-prompt-template` to expose named prompt contracts. Callers provide variables while the gateway manages full prompt structure. This plugin uses `body-transformer` internally.

* Admin API
* ADC

```
curl -k "https://localhost:7443/apisix/admin/routes/ai-prompt-template?gateway_group_id={gateway_group_id}" -X PUT \

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

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

  --data-binary @- <<EOF

  {

    "service_id": "$SERVICE_ID",

    "name": "ai-prompt-template",

    "paths": ["/ai/template"],

    "plugins": {

      "ai-proxy": {

        "provider": "openai",

        "auth": { "header": { "Authorization": "Bearer $OPENAI_API_KEY" } },

        "options": { "model": "gpt-4o" }

      },

      "ai-prompt-template": {

        "templates": [

          {

            "name": "support-reply",

            "template": {

              "model": "gpt-4o",

              "messages": [

                {

                  "role": "system",

                  "content": "You are a support assistant. Keep answers under 120 words."

                },

                {

                  "role": "user",

                  "content": "User issue: {{issue_summary}}"

                }

              ]

            }

          }

        ]

      }

    }

  }

EOF
```

❶ `templates` defines reusable named prompt templates. Clients select one using `template_name` in the request body.

❷ `template` contains the full request body shape, including `model` and `messages` with variable placeholders such as `{{issue_summary}}`.

adc.yaml

```
services:

  - name: AI Prompt Template

    routes:

      - uris:

          - /ai/template

        name: ai-prompt-template

        plugins:

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: "Bearer ${OPENAI_API_KEY}"

            options:

              model: gpt-4o

          ai-prompt-template:

            templates:

              - name: support-reply

                template:

                  model: gpt-4o

                  messages:

                    - role: system

                      content: You are a support assistant. Keep answers under 120 words.

                    - role: user

                      content: "User issue: {{issue_summary}}"

    labels:

      docs-example: ai-prompt-template
```

❶ `templates` defines reusable named prompt templates. Clients select one using `template_name` in the request body.

❷ `template` contains the full request body shape, including `model` and `messages` with variable placeholders such as `{{issue_summary}}`.

Preview the changes owned by 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-template
```

Synchronize the reviewed configuration:

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

For the full configuration reference, see [`ai-prompt-template`](https://docs.api7.ai/hub/ai-prompt-template.md).

## Combining Decorators and Templates[​](#combining-decorators-and-templates "Direct link to Combining Decorators and Templates")

You can combine both plugins on the same route. A common pattern is:

1. `ai-prompt-template` defines the task-specific prompt contract.
2. `ai-prompt-decorator` injects organization-wide system policies.

* Admin API
* ADC

```
curl -k "https://localhost:7443/apisix/admin/routes/ai-template-and-decorator?gateway_group_id={gateway_group_id}" -X PUT \

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

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

  --data-binary @- <<EOF

  {

    "service_id": "$SERVICE_ID",

    "name": "ai-template-and-decorator",

    "paths": ["/ai/templated-decorated"],

    "plugins": {

      "ai-proxy": {

        "provider": "openai",

        "auth": { "header": { "Authorization": "Bearer $OPENAI_API_KEY" } },

        "options": { "model": "gpt-4o" }

      },

      "ai-prompt-template": {

        "templates": [

          {

            "name": "incident-summary",

            "template": {

              "model": "gpt-4o",

              "messages": [

                {

                  "role": "user",

                  "content": "Summarize this incident for an operations report: {{incident_text}}"

                }

              ]

            }

          }

        ]

      },

      "ai-prompt-decorator": {

        "prepend": [

          {

            "role": "system",

            "content": "You are an SRE assistant. Use factual, neutral language and include concrete action items."

          }

        ],

        "append": [

          {

            "role": "system",

            "content": "End with a section named Next Steps."

          }

        ]

      }

    }

  }

EOF
```

❶ `ai-prompt-template` defines the reusable task template selected by `template_name`.

❷ `ai-prompt-decorator` enforces shared system behavior across all requests using that template.

adc.yaml

```
services:

  - name: AI Template and Decorator

    routes:

      - uris:

          - /ai/templated-decorated

        name: ai-template-and-decorator

        plugins:

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: "Bearer ${OPENAI_API_KEY}"

            options:

              model: gpt-4o

          ai-prompt-template:

            templates:

              - name: incident-summary

                template:

                  model: gpt-4o

                  messages:

                    - role: user

                      content: "Summarize this incident for an operations report: {{incident_text}}"

          ai-prompt-decorator:

            prepend:

              - role: system

                content: You are an SRE assistant. Use factual, neutral language and include concrete action items.

            append:

              - role: system

                content: End with a section named Next Steps.

    labels:

      docs-example: ai-template-and-decorator
```

❶ `ai-prompt-template` defines the reusable task template selected by `template_name`.

❷ `ai-prompt-decorator` enforces shared system behavior across all requests using that template.

Preview the changes owned by 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-template-and-decorator
```

Synchronize the reviewed configuration:

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-template-and-decorator
```

## Verify[​](#verify "Direct link to Verify")

Send a request to the decorated route:

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

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

  -d '{

    "model": "gpt-4o-mini",

    "messages": [

      { "role": "user", "content": "Can you reset my account password?" }

    ]

  }'
```

Expected result: the response follows the injected policy (for example, asking for ticket ID before account actions).

Send a request using a named template:

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

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

  -d '{

    "model": "gpt-4o-mini",

    "template_name": "support-reply",

    "issue_summary": "Order #4721 has not arrived after 10 days"

  }'
```

Expected result: the gateway expands `{{issue_summary}}` into the template and returns a generated answer.

Send a request to the combined route:

```
curl "http://127.0.0.1:9080/ai/templated-decorated" -X POST \

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

  -d '{

    "model": "gpt-4o-mini",

    "template_name": "incident-summary",

    "incident_text": "Database CPU reached 95% for 18 minutes, causing elevated p99 latency in checkout." 

  }'
```

Expected result: the output follows both the template intent and decorator-enforced style (SRE tone and a `Next Steps` section).

## Next Steps[​](#next-steps "Direct link to Next Steps")

* [Content Safety and Guardrails](https://docs.api7.ai/api7-gateway/ai-gateway/use-cases/content-safety-and-guardrails.md) — Add prompt filtering and moderation controls.
* [AI Gateway Overview](https://docs.api7.ai/api7-gateway/ai-gateway/overview.md) — Review architecture and capability mapping.
* Plugin references: [`ai-prompt-decorator`](https://docs.api7.ai/hub/ai-prompt-decorator.md), [`ai-prompt-template`](https://docs.api7.ai/hub/ai-prompt-template.md), [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md).
