# Transform API Requests with AI-Powered Rewriting

API7 Gateway's `ai-request-rewrite` plugin sends each incoming request body to a dedicated LLM, then replaces the complete body with the model output before forwarding it upstream. This approach can normalize ambiguous, free-form, multilingual, or semantically complex input when static regex or template rewrites are insufficient.

Common use cases include:

* **Format normalization**: Convert free-text user input into structured JSON.
* **Language translation**: Convert multilingual input into a single target language expected by upstream systems.
* **Data enrichment**: Extract and standardize fields such as intent, entities, or categories.
* **Legacy API adaptation**: Transform modern client payloads into schemas required by legacy upstream APIs.

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

## How It Works[​](#how-it-works "Direct link to How It Works")

The transformation flow:

1. **Client request enters the gateway**.
2. **Gateway calls a transformation LLM** using `ai-request-rewrite` and your prompt instructions.
3. **Gateway receives transformed content** and replaces the complete request body with it.
4. **Modified request is forwarded to the upstream API**.

The transformation LLM call is separate middleware behavior. It does **not** replace your primary upstream service. The plugin runs only on the request and does not transform the upstream response.

The rewrite-model output becomes the entire upstream request body. Write the prompt so the output matches the upstream's required body format. For a JSON API, require complete valid JSON rather than a fragment or explanatory text.

## Configure AI Request Rewriting[​](#configure-ai-request-rewriting "Direct link to Configure AI Request Rewriting")

The following route uses `ai-request-rewrite` with OpenAI as the transformation provider.

* 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` selects the transformation LLM backend. Here it is OpenAI.

❷ `auth.header.Authorization` sets credentials for the transformation LLM call.

❸ `options.model` sets the transformation model used for rewriting.

❹ `prompt` contains explicit transformation instructions. Keep this concise, deterministic, and schema-oriented.

❺ `proxy-rewrite` sets the upstream `Content-Type` during the rewrite phase. `ai-request-rewrite` later replaces the body during the access phase, and the header remains `application/json` when the request is forwarded. Numeric priority does not order plugins across different phases.

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` selects the transformation LLM backend. Here it is OpenAI.

❷ `auth.header.Authorization` sets credentials for the transformation LLM call.

❸ `options.model` sets the transformation model used for rewriting.

❹ `prompt` contains explicit transformation instructions. Keep this concise, deterministic, and schema-oriented.

❺ `proxy-rewrite` sets the upstream `Content-Type` during the rewrite phase. `ai-request-rewrite` later replaces the body during the access phase, and the header remains `application/json` when the request is forwarded. Numeric priority does not order plugins across different phases.

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-request-transformation-service
```

Synchronize the reviewed configuration:

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

When using `provider: "openai-compatible"`, `override.endpoint` is **required** by schema validation.

```
{

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

}
```

## Example: Normalize Free-Text Input[​](#example-normalize-free-text-input "Direct link to Example: Normalize Free-Text Input")

Scenario: clients send unstructured text, but the upstream expects strict JSON fields.

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

Use a transformation prompt such as:

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

Expected transformed payload forwarded upstream:

```
{

  "name": "Jane Doe",

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

  "intent": "password_reset"

}
```

## Example: Translate Request Language[​](#example-translate-request-language "Direct link to Example: Translate Request Language")

Scenario: clients send multilingual content, but the upstream only accepts English payloads.

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

  }'
```

Use a transformation prompt such as:

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

Example transformed request payload:

```
{

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

}
```

## Performance Considerations[​](#performance-considerations "Direct link to Performance Considerations")

AI transformation introduces an additional LLM round-trip in the request path, so plan for:

* **Latency**: Every transformation adds model inference time. Use this only where semantic transformation is required.
* **Cost**: Transformation prompts and outputs consume extra tokens on the transformation provider.
* **Scope control**: Apply rewriting only on routes that need it, not globally.
* **Prompt discipline**: Keep prompts explicit and output-constrained to reduce retries and drift.
* **Caching opportunities**: If inputs are repetitive, cache transformed outputs to reduce both latency and token spend.

Use AI request transformation when traditional deterministic transforms (mapping, regex, fixed templates) are insufficient.

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

* [Prompt Engineering and Templating](https://docs.api7.ai/api7-gateway/ai-gateway/use-cases/prompt-engineering-and-templating.md) — Combine route-level prompt governance with transformation workflows.
* [Content Safety and Guardrails](https://docs.api7.ai/api7-gateway/ai-gateway/use-cases/content-safety-and-guardrails.md) — Apply prompt filtering and request moderation with the documented runtime ordering.
* [Token-Based Rate Limiting and Quota Management](https://docs.api7.ai/api7-gateway/ai-gateway/use-cases/token-rate-limiting-and-quota-management.md) — Control transformation token spend.
* For the full configuration reference, see [`ai-request-rewrite`](https://docs.api7.ai/hub/ai-request-rewrite.md).
