使用 AI 改写和转换接口请求
本文介绍如何使用 ai-request-rewrite 插件在网关层进行 AI 驱动的请求转换。与静态正则或模板改写不同,AI 改写可以理解非结构化、多语言或语义复杂的输入,并转换为上游接口需要的格式。
适用场景
- 格式归一化:将自由文本转换为结构化 JSON。
- 语言转换:把多语言输入转换成上游系统要求的目标语言。
- 数据增强:提取意图、实体、分类等字段并补全请求。
- 旧系统适配:将现代客户端请求转换为旧系统要求的字段结构。
工作流程
- 客户端请求进入 API7 AI 网关。
- 网关通过
ai-request-rewrite调用转换模型,并传入改写指令。 - 网关获得转换后的内容并注入请求。
- 修改后的请求被转发到上游接口。
该插件也可以用于响应侧转换,在数据返回客户端前进行格式化或脱敏。
配置请求改写
以下示例使用 OpenAI 作为转换模型,将自然语言输入改写为上游系统需要的 JSON。
- Admin API
- ADC
curl "http://127.0.0.1:7080/apisix/admin/routes?gateway_group_id=default" -X PUT \
-H "X-API-KEY: $ADMIN_API_KEY" \
-d '{
"id": "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-mini"
},
"prompt": "Extract intent and entities from the request body, then return compact JSON for the upstream API."
}
}
}'
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-mini
prompt: Extract intent and entities from the request body, then return compact JSON for the upstream API.
设计建议
- 明确转换模型的输入、输出格式和失败处理策略。
- 对转换结果做结构校验,避免无效 JSON 进入上游系统。
- 设置令牌限流和超时,防止转换链路影响主业务稳定性。
- 对涉及敏感信息的请求,先脱敏再调用转换模型。