# 实现提示词模板和装饰器

本指南介绍如何在网关层使用 [`ai-prompt-decorator`](https://docs.apiseven.com/hub/ai-prompt-decorator.md) 和 [`ai-prompt-template`](https://docs.apiseven.com/hub/ai-prompt-template.md) 规范提示词行为。你将配置可复用提示词模板、强制执行系统指令，并将这两个插件与 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 组合使用。

## 概览[​](#概览 "概览的直接链接")

网关层提示词工程可以将提示词策略从应用代码中分离。平台团队可以跨服务强制实施一致行为、集中更新指令，并减少团队之间的策略漂移。

API7 AI 网关提供两种互补模式：

* 使用 [`ai-prompt-decorator`](https://docs.apiseven.com/hub/ai-prompt-decorator.md) 进行**提示词装饰**：在每个请求的消息前面或后面添加内容。
* 使用 [`ai-prompt-template`](https://docs.apiseven.com/hub/ai-prompt-template.md) 进行**提示词模板化**：定义支持 `{{variable}}` 替换的命名模板。

## 前置条件[​](#前置条件 "前置条件的直接链接")

* 安装 [Docker](https://docs.docker.com/get-docker/)。

* 安装 [cURL](https://curl.se/)，用于发送请求并验证服务。

* 拥有一个正在运行的 API7 网关实例。

* [从控制台获取 Token](https://docs.apiseven.com/api7-gateway/reference/obtain-dashboard-token.md)，并保存到环境变量：

  ```
  export API_KEY=your-dashboard-token   # 请替换为你的控制台 Token
  ```

* 将 `{gateway_group_id}` 替换为网关组 ID。如果正在按照快速入门操作，请使用 `default`。

* 如果使用 Admin API 示例，请创建或复用一个服务。如果尚无服务，请按照[创建或复用服务](https://docs.apiseven.com/api7-gateway/ai-gateway/get-started.md#create-or-reuse-a-service)操作，然后保存其 ID：

  ```
  export SERVICE_ID=your-service-id         # 请替换为你的服务 ID
  ```

## 提示词装饰[​](#提示词装饰 "提示词装饰的直接链接")

使用 `ai-prompt-decorator` 在用户消息前后注入全局指令。

* 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` 在对话开头插入消息，通常用于强制系统指令。

❷ `append` 在对话末尾插入消息，适合添加额外的策略提醒。

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` 在对话开头插入消息，通常用于强制系统指令。

❷ `append` 在对话末尾插入消息，适合添加额外的策略提醒。

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

完整配置说明请参阅 [`ai-prompt-decorator`](https://docs.apiseven.com/hub/ai-prompt-decorator.md)。

## 提示词模板化[​](#提示词模板化 "提示词模板化的直接链接")

使用 `ai-prompt-template` 暴露命名提示词契约。调用方只需提供变量，完整提示词结构由网关管理。此插件在内部使用 `body-transformer`。

* 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` 定义可复用的命名提示词模板。客户端通过请求体中的 `template_name` 选择模板。

❷ `template` 包含完整的请求体结构，包括 `model`，以及带 `{{issue_summary}}` 等变量占位符的 `messages`。

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` 定义可复用的命名提示词模板。客户端通过请求体中的 `template_name` 选择模板。

❷ `template` 包含完整的请求体结构，包括 `model`，以及带 `{{issue_summary}}` 等变量占位符的 `messages`。

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
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-prompt-template`](https://docs.apiseven.com/hub/ai-prompt-template.md)。

## 组合装饰器和模板[​](#组合装饰器和模板 "组合装饰器和模板的直接链接")

可以在同一个路由上组合这两个插件。常见模式如下：

1. `ai-prompt-template` 定义特定任务的提示词契约。
2. `ai-prompt-decorator` 注入组织级系统策略。

* 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` 定义由 `template_name` 选择的可复用任务模板。

❷ `ai-prompt-decorator` 对所有使用该模板的请求强制实施共享系统行为。

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` 定义由 `template_name` 选择的可复用任务模板。

❷ `ai-prompt-decorator` 对所有使用该模板的请求强制实施共享系统行为。

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

## 验证[​](#验证 "验证的直接链接")

向装饰后的路由发送请求：

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

    ]

  }'
```

预期结果：响应遵循注入的策略，例如在执行账户操作前询问工单 ID。

使用命名模板发送请求：

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

  }'
```

预期结果：网关将 `{{issue_summary}}` 展开到模板中，并返回生成的回答。

向组合路由发送请求：

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

  }'
```

预期结果：输出同时遵循模板意图和装饰器强制的风格，即 SRE 语气和 `Next Steps` 部分。

## 后续步骤[​](#后续步骤 "后续步骤的直接链接")

* [内容安全和安全护栏](https://docs.apiseven.com/api7-gateway/ai-gateway/use-cases/content-safety-and-guardrails.md) — 添加提示词过滤和内容审核控制。
* [AI 网关概览](https://docs.apiseven.com/api7-gateway/ai-gateway/overview.md) — 查看架构和能力映射。
* 插件参考：[`ai-prompt-decorator`](https://docs.apiseven.com/hub/ai-prompt-decorator.md)、[`ai-prompt-template`](https://docs.apiseven.com/hub/ai-prompt-template.md)、[`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md)。
