# 使用 AI 重写转换 API 请求

API7 网关的 `ai-request-rewrite` 插件会将每个传入的请求体发送给专用大语言模型，然后在转发到上游前，用模型输出替换完整请求体。当输入含义模糊、格式自由、包含多种语言或语义复杂，静态正则表达式或模板重写不足以处理时，可以使用此方式进行规范化。

常见用例包括：

* **格式规范化**：把自由文本用户输入转换为结构化 JSON。
* **语言翻译**：把多语言输入转换为上游系统要求的统一目标语言。
* **数据增强**：提取并标准化意图、实体或类别等字段。
* **旧版 API 适配**：把现代客户端载荷转换为旧版上游 API 要求的 Schema。

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

* 安装 [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
  ```

## 工作原理[​](#工作原理 "工作原理的直接链接")

转换流程如下：

1. **客户端请求进入网关**。
2. **网关使用 `ai-request-rewrite` 调用转换模型**，并传入你的提示词指令。
3. **网关接收转换后的内容**，并用它替换完整请求体。
4. **修改后的请求被转发到上游 API**。

转换模型调用是一项独立的中间件行为，**不会**取代主要上游服务。插件仅处理请求，不会转换上游响应。

重写模型的输出会成为发送给上游的整个请求体。请编写提示词，使输出符合上游要求的请求体格式。如果上游使用 JSON API，应要求模型返回完整、有效的 JSON，而非片段或解释性文字。

## 配置 AI 请求重写[​](#配置-ai-请求重写 "配置 AI 请求重写的直接链接")

以下路由使用 `ai-request-rewrite`，并将 OpenAI 作为转换服务提供方。

* Admin API
* ADC

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

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

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

  --data-binary @- <<EOF

  {

    "name": "ai-request-transformation",

    "service_id": "$SERVICE_ID",

    "paths": ["/api/intake"],

    "plugins": {

      "ai-request-rewrite": {

        "provider": "openai",

        "auth": {

          "header": {

            "Authorization": "Bearer $OPENAI_API_KEY"

          }

        },

        "options": {

          "model": "gpt-4o"

        },

        "prompt": "transformation instructions here"

      },

      "proxy-rewrite": {

        "headers": {

          "set": {

            "Content-Type": "application/json"

          }

        }

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "intake-api.internal:8080": 1

      }

    }

  }

EOF
```

❶ `provider` 选择转换所用的大语言模型后端，此处为 OpenAI。

❷ `auth.header.Authorization` 设置调用转换模型所需的凭证。

❸ `options.model` 设置重写所使用的转换模型。

❹ `prompt` 包含明确的转换指令。应保持简洁、确定，并以 Schema 为导向。

❺ `proxy-rewrite` 在 rewrite 阶段设置发往上游的 `Content-Type`。随后 `ai-request-rewrite` 在 access 阶段替换请求体；转发请求时，该请求头仍为 `application/json`。处于不同阶段的插件不会按数值优先级决定执行顺序。

adc.yaml

```
services:

  - name: AI Request Transformation Service

    routes:

      - name: ai-request-transformation

        uris:

          - /api/intake

        plugins:

          ai-request-rewrite:

            provider: openai

            auth:

              header:

                Authorization: "Bearer ${OPENAI_API_KEY}"

            options:

              model: gpt-4o

            prompt: "transformation instructions here"

          proxy-rewrite:

            headers:

              set:

                Content-Type: application/json

    upstream:

      type: roundrobin

      nodes:

        - host: intake-api.internal

          port: 8080

          weight: 1

    labels:

      docs-example: ai-request-transformation-service
```

❶ `provider` 选择转换所用的大语言模型后端，此处为 OpenAI。

❷ `auth.header.Authorization` 设置调用转换模型所需的凭证。

❸ `options.model` 设置重写所使用的转换模型。

❹ `prompt` 包含明确的转换指令。应保持简洁、确定，并以 Schema 为导向。

❺ `proxy-rewrite` 在 rewrite 阶段设置发往上游的 `Content-Type`。随后 `ai-request-rewrite` 在 access 阶段替换请求体；转发请求时，该请求头仍为 `application/json`。处于不同阶段的插件不会按数值优先级决定执行顺序。

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

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-request-transformation-service
```

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-request-transformation-service
```

使用 `provider: "openai-compatible"` 时，Schema 校验要求必须提供 `override.endpoint`。

```
{

  "provider": "openai-compatible",

  "override": {

    "endpoint": "https://your-llm-endpoint.example/v1/chat/completions"

  },

  "auth": {

    "header": {

      "Authorization": "Bearer sk-xxxxxxxx"

    }

  },

  "options": {

    "model": "custom-model"

  },

  "prompt": "transformation instructions here"

}
```

## 示例：规范化自由文本输入[​](#示例规范化自由文本输入 "示例：规范化自由文本输入的直接链接")

场景：客户端发送非结构化文本，但上游要求严格的 JSON 字段。

```
curl "http://127.0.0.1:9080/api/intake" \

  -X POST \

  -H "Content-Type: text/plain" \

  --data-raw "Hi, I am Jane Doe, my email is jane@example.com and I cannot log in. Please help me reset my password."
```

使用如下转换提示词：

```
Read the raw request body as unstructured text. Return a complete valid JSON object with the keys `name`, `email`, and `intent`. If a field is missing, set its value to null. Return JSON only.
```

转发到上游的预期载荷：

```
{

  "name": "Jane Doe",

  "email": "jane@example.com",

  "intent": "password_reset"

}
```

## 示例：转换请求语言[​](#示例转换请求语言 "示例：转换请求语言的直接链接")

场景：客户端发送多语言内容，但上游只接受英文载荷。

```
curl "http://127.0.0.1:9080/api/intake" -X POST \

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

  -d '{

    "message": "Veuillez annuler mon rendez-vous de mercredi prochain et le reporter à vendredi matin."

  }'
```

使用如下转换提示词：

```
Return the complete request as a valid JSON object. Preserve every top-level field and translate only the `message` value to English while retaining its meaning and time references. Return JSON only.
```

转换后的请求载荷示例：

```
{

  "message": "Please cancel my appointment for next Wednesday and reschedule it to Friday morning."

}
```

## 性能注意事项[​](#性能注意事项 "性能注意事项的直接链接")

AI 转换会在请求路径中增加一次大语言模型往返调用，因此需要考虑：

* **延迟**：每次转换都会增加模型推理时间，只应在需要语义转换时使用。
* **成本**：转换提示词和输出会在转换服务提供方处消耗额外 Token。
* **范围控制**：仅在需要重写的路由上应用该插件，不要全局启用。
* **提示词规范**：提示词应明确并限制输出格式，以减少重试和结果漂移。
* **缓存机会**：如果输入重复，可以缓存转换结果，同时降低延迟和 Token 开销。

仅当传统的确定性转换（映射、正则表达式、固定模板）不足以满足要求时，才使用 AI 请求转换。

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

* [提示词工程和模板](https://docs.apiseven.com/api7-gateway/ai-gateway/use-cases/prompt-engineering-and-templating.md) — 将路由级提示词治理与转换工作流组合使用。
* [内容安全和安全护栏](https://docs.apiseven.com/api7-gateway/ai-gateway/use-cases/content-safety-and-guardrails.md) — 按文档所述的运行顺序应用提示词过滤和请求审核。
* [基于 Token 的限流和配额管理](https://docs.apiseven.com/api7-gateway/ai-gateway/use-cases/token-rate-limiting-and-quota-management.md) — 控制转换产生的 Token 开销。
* 完整配置说明请参阅 [`ai-request-rewrite`](https://docs.apiseven.com/hub/ai-request-rewrite.md)。
