# OpenAI

[OpenAI](https://platform.openai.com/docs/) provides hosted GPT models through its API. Applications call them through stable AISIX aliases while the gateway keeps the OpenAI credential out of client code.

This guide covers both GPT chat traffic and Sora video tasks through a single OpenAI provider key.

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

Before starting, prepare the following:

* One AISIX setup:

  <!-- -->

  * For AISIX Enterprise or AISIX Cloud, an environment with an attached gateway and a write-scoped admin token. For AISIX Enterprise, follow the [AISIX Enterprise getting-started guide](https://docs.api7.ai/ai-gateway/getting-started/aisix-cloud-quickstart.md). To request AISIX Cloud access, [contact API7](https://api7.ai/contact).
  * For the open-source AISIX gateway, prepare either a local AISIX installation or the Docker setup from the [AISIX OSS getting-started guide](https://docs.api7.ai/ai-gateway/getting-started/gateway-quickstart.md). Configure the gateway to load a declarative resources file.

* An OpenAI API key from the [OpenAI platform](https://platform.openai.com/api-keys).

* `curl` and `jq`.

## Configure with AISIX Enterprise or AISIX Cloud[​](#configure-with-aisix-enterprise-or-aisix-cloud "Direct link to Configure with AISIX Enterprise or AISIX Cloud")

Export the control-plane connection details:

```
# AISIX_CP is the Admin API base URL; include /api and omit a trailing slash

# The local AISIX Enterprise quickstart uses http://localhost:8080/api

export AISIX_CP="YOUR_AISIX_CONTROL_PLANE_API_URL"

export AISIX_TOKEN="YOUR_ADMIN_TOKEN"

export ENV_ID="YOUR_ENVIRONMENT_ID"
```

Create a provider key, model alias, and caller API key for the OpenAI-backed route.

OpenAI is the gateway's native OpenAI-compatible upstream, and the integration uses the `openai` adapter. You can leave `api_base` unset for OpenAI's canonical endpoint or set it to target an OpenAI-compatible proxy that preserves bearer authentication and the OpenAI route shape.

### Create a Provider Key[​](#create-a-provider-key "Direct link to Create a Provider Key")

Create the provider key that stores the OpenAI credential:

```
# Replace with your values

export OPENAI_API_KEY="YOUR_PROVIDER_API_KEY"



PROVIDER_KEY_ID=$(curl -sS -X POST "$AISIX_CP/provider_keys" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

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

  -d '{

    "display_name": "openai-prod",

    "provider": "openai",

    "api_key": "'"${OPENAI_API_KEY}"'",

    "allowed_environments": ["'"${ENV_ID}"'"]

  }' | jq -r '.provider_key.id')
```

❶ `provider` is `openai`. This is the only provider value that lets AISIX fall back to the default base URL `https://api.openai.com/v1`.

❷ `api_key` stores the OpenAI API key. The value is encrypted before it is stored and is never returned by read endpoints. It follows the credential-handling behavior in [Provider Keys](https://docs.api7.ai/ai-gateway/models/provider-keys.md#credential-handling).

❸ `allowed_environments` lists the environments that may reference this provider key when creating models.

The AISIX Cloud Admin API derives the adapter from the catalog provider; the `adapter` field is only accepted on BYO provider keys.

You can omit `api_base` for OpenAI. To target a compatible bearer-authenticated proxy or regional gateway, set `api_base` explicitly. Use the dedicated [Azure OpenAI](https://docs.api7.ai/ai-gateway/providers/azure-openai.md) integration for the Azure OpenAI service itself. The command captures the returned provider key ID in `PROVIDER_KEY_ID`.

### Create a Model[​](#create-a-model "Direct link to Create a Model")

Create the model alias callers will send in requests:

```
MODEL_ID=$(curl -sS -X POST "$AISIX_CP/environments/$ENV_ID/models" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

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

  -d '{

    "display_name": "gpt-5.6-sol-prod",

    "model_name": "gpt-5.6-sol",

    "provider_key_id": "'"${PROVIDER_KEY_ID}"'"

  }' | jq -r '.model.id')
```

❶ `display_name` is the alias callers send in `model`.

❷ `model_name` is the OpenAI model ID. This guide uses `gpt-5.6-sol`, the current flagship model in the [OpenAI model catalog](https://developers.openai.com/api/docs/models). Choose a different current model when its cost, latency, or modality better matches the workload.

❸ `provider_key_id` attaches the alias to the OpenAI provider key.

### Create a Caller API Key[​](#create-a-caller-api-key "Direct link to Create a Caller API Key")

Create the caller API key resource that can access the model alias. The control plane generates the key value and returns the plaintext once in the create response:

```
AISIX_API_KEY=$(curl -sS -X POST "$AISIX_CP/environments/$ENV_ID/api_keys" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

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

  -d '{

    "display_name": "openai-caller",

    "allowed_models": ["'"${MODEL_ID}"'"]

  }' | jq -r '.plaintext')
```

The `allowed_models` value references the model ID captured in the previous step.

Store the plaintext key securely. The control plane stores only a hash; the plaintext is not retrievable after this response.

After each write, the configuration projects to the attached gateways automatically.

## Configure with AISIX OSS[​](#configure-with-aisix-oss "Direct link to Configure with AISIX OSS")

Export the upstream credential and choose the caller API key that applications will send to the gateway:

```
export OPENAI_API_KEY="YOUR_PROVIDER_API_KEY"

export CALLER_API_KEY="YOUR_CALLER_API_KEY"

export CALLER_API_KEY_SHA256="$(printf '%s' "$CALLER_API_KEY" | sha256sum | cut -d ' ' -f 1)"
```

For a new gateway, use this complete resources file. For an existing gateway, merge the entries into its [current file](https://docs.api7.ai/ai-gateway/reference/resources-file.md#apply-resource-examples-safely), preserving its other resources:

resources.yaml

```
_format_version: "2"



provider_keys:

  - id: 83eba07c-0ad3-4b81-b760-247f2d978e95

    display_name: "openai-prod"

    provider: "openai"

    adapter: "openai"

    api_key: ${OPENAI_API_KEY}



models:

  - id: d686bf52-9e52-4bad-a082-780cc271f968

    display_name: "gpt-5.6-sol-prod"

    provider: "openai"

    model_name: "gpt-5.6-sol"

    provider_key_id: 83eba07c-0ad3-4b81-b760-247f2d978e95



api_keys:

  - id: bd7463c0-f0da-4276-ac7c-9fc73e2983e5

    display_name: "openai-caller"

    key_hash: ${CALLER_API_KEY_SHA256}

    allowed_models:

      - "gpt-5.6-sol-prod"
```

If AISIX is installed locally, validate the file before loading it:

```
aisix validate --resources resources.yaml
```

After validation, start the gateway with the referenced environment variables in its process environment. Reload an existing gateway only if those variables are already available to the process; otherwise, restart it with the updated environment.

If you use Docker, adapt the validation and startup commands in the [AISIX OSS getting-started guide](https://docs.api7.ai/ai-gateway/getting-started/gateway-quickstart.md). Mount this `resources.yaml` file and pass every environment variable it references with `-e` in both commands. After the resources load, prepare the shared verification request below:

```
export AISIX_API_KEY="$CALLER_API_KEY"
```

## Verify the Provider Connection[​](#verify-the-provider-connection "Direct link to Verify the Provider Connection")

Export the AISIX gateway origin:

```
# AISIX_PROXY has no trailing slash or endpoint path

# The local quickstarts use http://127.0.0.1:3000

export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"
```

Send a chat-completions request through the AISIX proxy:

```
curl -sS -X POST "$AISIX_PROXY/v1/chat/completions" \

  -H "Authorization: Bearer ${AISIX_API_KEY}" \

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

  -d '{

    "model": "gpt-5.6-sol-prod",

    "messages": [

      {

        "role": "user",

        "content": "Say hello from OpenAI."

      }

    ]

  }'
```

The gateway returns an OpenAI-compatible response that echoes the caller-facing alias `gpt-5.6-sol-prod`. Confirm the request on the [OpenAI usage dashboard](https://platform.openai.com/usage). If the request fails with an upstream authentication error, check the provider key `api_key`.

For reasoning, tool-calling, and multi-turn workflows, OpenAI recommends the Responses API. Send a native Responses request through the same alias:

```
curl -sS -X POST "$AISIX_PROXY/v1/responses" \

  -H "Authorization: Bearer ${AISIX_API_KEY}" \

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

  -d '{

    "model": "gpt-5.6-sol-prod",

    "input": "Say hello from the OpenAI Responses API."

  }'
```

Because the model's configured provider is `openai`, AISIX rewrites the model alias and forwards this request to OpenAI's native Responses endpoint. It does not use the cross-provider Responses bridge.

## Reasoning Model Token Cap[​](#reasoning-model-token-cap "Direct link to Reasoning Model Token Cap")

OpenAI's o-series and GPT-5 models reject `max_tokens` on Chat Completions and take the output cap as `max_completion_tokens`. For a provider key whose `provider` is `openai`, and for a provider key on the `azure-openai` adapter, AISIX renames a caller's `max_tokens` to `max_completion_tokens` when the upstream model is a reasoning model, so a client that sends `max_tokens` still succeeds. When the request carries both fields, `max_completion_tokens` wins and `max_tokens` is dropped. Every other parameter, including `temperature`, is forwarded as sent.

AISIX classifies the model by the last `/`-separated segment of its upstream model name, which is the deployment name on Azure OpenAI. The match is literal and case-sensitive:

| Adapter        | The model is a reasoning model when its name                                                                                                              |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `openai`       | Starts with `o` followed by a digit, such as `o3-mini`, or contains `gpt-5` or `gpt-6` and does not start with `gpt-5-chat`.                              |
| `azure-openai` | Contains `o1`, `o3`, `o4`, `gpt-5`, or `gpt-6`. Deployments of `gpt-5-chat` match as well, because Azure OpenAI rejects `max_tokens` for that family too. |

The rule follows OpenAI's own API contract, so it applies only to OpenAI and Azure OpenAI. Another vendor on the `openai` adapter receives `max_tokens` as sent, even when its upstream model name matches, such as `openai/o3-mini` on OpenRouter, which documents only `max_tokens`. It covers every upstream Chat Completions call these adapters make, streamed or not: `/v1/chat/completions`, `/v1/messages` translated to Chat Completions, and `/v1/responses` bridged to Chat Completions. On the bridged path, `max_output_tokens` becomes the chat cap and is renamed the same way. Native `/v1/responses` requests, `/v1/completions`, and the request lines of Batch input files are not changed.

The rename runs before the provider key's [`request.param_renames`](https://docs.api7.ai/ai-gateway/models/provider-keys.md#configure-provider-specific-overrides), so an explicit rename on the key has the last word. A `max_tokens` that the key's `request.default_body_fields` adds, because the caller sent no cap, is converted the same way. The control-plane [playground](https://docs.api7.ai/ai-gateway/cloud/playground.md) applies the rule to its test requests by adapter rather than by provider, so it also renames the field for other vendors on the `openai` adapter.

## Generate Videos with Sora[​](#generate-videos-with-sora "Direct link to Generate Videos with Sora")

caution

OpenAI [deprecated the Videos API and the Sora 2 models](https://developers.openai.com/api/docs/deprecations) on March 24, 2026 and will remove them from the API on September 24, 2026. Aliases backed by `sora-2` or `sora-2-pro` stop working on that date, and OpenAI lists no replacement model on this API.

The same provider key drives the gateway's modeled [video routes](https://docs.api7.ai/ai-gateway/endpoints/video-generation.md). Create a second alias that points at a Sora model — `sora-2` or `sora-2-pro`:

In AISIX Enterprise and AISIX Cloud, create the video alias and a caller key scoped to it:

```
VIDEO_MODEL_ID=$(curl -sS -X POST "$AISIX_CP/environments/$ENV_ID/models" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

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

  -d '{

    "display_name": "sora-video-prod",

    "model_name": "sora-2",

    "provider_key_id": "'"${PROVIDER_KEY_ID}"'"

  }' | jq -r '.model.id')



echo "$VIDEO_MODEL_ID"



VIDEO_API_KEY=$(curl -sS -X POST "$AISIX_CP/environments/$ENV_ID/api_keys" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

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

  -d '{

    "display_name": "openai-video-caller",

    "allowed_models": ["'"${VIDEO_MODEL_ID}"'"]

  }' | jq -r '.plaintext')
```

For the open-source AISIX gateway, add `sora-video-prod` to the existing `models` collection. Replace the existing `openai-caller` entry with the updated entry below so it allows both model aliases. Preserve unrelated entries and collections:

resources.yaml (video model access)

```
models:

  - id: 2a0211f4-4847-4842-aa4d-65900bb5c88b

    display_name: "sora-video-prod"

    provider: "openai"

    model_name: "sora-2"

    provider_key_id: 83eba07c-0ad3-4b81-b760-247f2d978e95



api_keys:

  - id: bd7463c0-f0da-4276-ac7c-9fc73e2983e5

    display_name: "openai-caller"

    key_hash: ${CALLER_API_KEY_SHA256}

    allowed_models:

      - "gpt-5.6-sol-prod"

      - "sora-video-prod"
```

Validate and reload or restart the declarative resources file as described above, then use the existing caller key for the video request:

```
export VIDEO_API_KEY="$CALLER_API_KEY"
```

Submit a task:

```
curl -sS -X POST "$AISIX_PROXY/v1/videos" \

  -H "Authorization: Bearer ${VIDEO_API_KEY}" \

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

  -d '{

    "model": "sora-video-prod",

    "prompt": "A paper boat drifts down a rain-soaked street at dusk.",

    "seconds": 4,

    "size": "1280x720"

  }'
```

Five provider-specific behaviors are worth knowing before you script around this route:

* **OpenAI is the only video provider with a default base URL.** An OpenAI-backed video alias works with `api_base` unset, exactly like the chat alias on this page. Every other video provider requires `api_base` on the provider key.
* **Sora validates `seconds` and `size` itself.** OpenAI's create-video schema accepts `4`, `8`, or `12` for `seconds` and lists `720x1280`, `1280x720`, `1024x1792`, and `1792x1024` for `size`, but the per-model pages publish narrower resolution sets — check the page for the model your alias names. AISIX forwards `seconds` as a string and checks that `size` has the `WIDTHxHEIGHT` shape before forwarding it verbatim, so a well-formed value the model does not accept is rejected by the provider, not by the gateway.
* **Finished videos stream through the gateway.** Sora serves the finished file from an authenticated content endpoint rather than a signed URL, so `GET /v1/videos/{id}/content` returns `200` with the MP4 bytes instead of a `302`. AISIX fetches the file with the provider credential and relays it chunk by chunk, so the credential never reaches the caller and a large file does not grow the gateway's memory use. Size the gateway's egress for this traffic: those bytes transit the gateway and do not count against the model's rate limits.
* **`progress` is a real percentage.** Sora reports task progress, so poll responses carry the provider's own completion percentage. Providers that report none stay at `0` until the task completes.
* **Image-to-video requires a passthrough route.** The normalized request models only `prompt`, `seconds`, and `size`; extra fields, including `input_reference`, are ignored rather than rejected, so a remix or image-guided request would silently generate from the prompt alone. Call `/passthrough/openai/v1/videos` with the native multipart body for those, and use the native remix route the same way. An OpenAI SDK client reaches this path too, but it needs its own client: point its base URL at `${AISIX_PROXY}/passthrough/openai/v1` rather than the `${AISIX_PROXY}/v1` client used elsewhere on this page, and grant the route name in the caller key's `allowed_routes`. The video create helper always sends `multipart/form-data`, which the modeled route does not accept. Passthrough does not return the unified AISIX video object or gateway-encoded task ID.

For the full submit, poll, and download workflow, including status semantics and rate-limit behavior on polling, see [Video Generation](https://docs.api7.ai/ai-gateway/endpoints/video-generation.md).

## Endpoint Coverage[​](#endpoint-coverage "Direct link to Endpoint Coverage")

OpenAI exposes several API families that use different model types. Configure a separate AISIX model alias for each upstream model an application needs.

| Route                                              | Behavior with an OpenAI-backed alias                                                                                                                                                                                                                                                                |
| -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/v1/chat/completions`                             | Supported with the OpenAI request and response shape. Model-specific feature and parameter limits still apply.                                                                                                                                                                                      |
| `/v1/responses`                                    | Forwarded to OpenAI's native Responses endpoint after model-alias rewriting. Stateful fields, hosted tools, reasoning controls, and upstream SSE remain on the native path.                                                                                                                         |
| `/v1/completions`                                  | Forwarded to OpenAI, but this is a legacy endpoint and the selected model must support it.                                                                                                                                                                                                          |
| `/v1/embeddings`                                   | Supported with an alias for an OpenAI embedding model, such as `text-embedding-3-large`.                                                                                                                                                                                                            |
| `/v1/images/generations`                           | Supported with an alias for a current OpenAI image model.                                                                                                                                                                                                                                           |
| `/v1/images/edits`                                 | Supported with an alias for an OpenAI image-editing model such as `gpt-image-2`. Requests are `multipart/form-data`; see [Image Editing](https://docs.api7.ai/ai-gateway/endpoints/image-editing.md).                                                                                               |
| `/v1/videos` and its status and content routes     | Supported with an alias for a Sora model, `sora-2` or `sora-2-pro`. The content route streams the MP4 through the gateway instead of redirecting, because OpenAI serves finished files from an authenticated endpoint. See [Generate Videos with Sora](#generate-videos-with-sora).                 |
| `/v1/audio/*`                                      | Supported with an appropriate speech, transcription, or translation model alias.                                                                                                                                                                                                                    |
| `/v1/realtime`                                     | Supported as a WebSocket relay with a direct Realtime model alias. See [Realtime API](https://docs.api7.ai/ai-gateway/endpoints/realtime.md).                                                                                                                                                       |
| `/v1/files`, `/v1/batches`, `/v1/fine_tuning/jobs` | Supported through the OpenAI adapter. These job-style routes select credentials differently from ordinary inference calls; see [Files, Batch, and Fine-tuning](https://docs.api7.ai/ai-gateway/endpoints/batch-files-fine-tuning.md).                                                               |
| `/v1/messages`                                     | Translated through OpenAI chat; OpenAI does not expose a native Anthropic Messages endpoint.                                                                                                                                                                                                        |
| `/v1/messages/count_tokens`                        | Rejected because token counting on this route requires an Anthropic-backed model.                                                                                                                                                                                                                   |
| `/v1/models`                                       | Returns caller-accessible AISIX model aliases, not the OpenAI account's model inventory. Use `/passthrough/openai/v1/models` when the native list is required.                                                                                                                                      |
| `/v1/rerank`                                       | AISIX accepts the `openai` provider value, but the public OpenAI API does not expose `/v1/rerank`, so the upstream rejects the call.                                                                                                                                                                |
| `/v1/decisions` and `/v1/systemone`                | Supported with an alias whose upstream model is `gpt-6-luna`, currently the only model supported by OpenAI's Decisions API. `/v1/decisions` is forwarded natively, and `/v1/systemone` requests are converted. See [Decision Models](https://docs.api7.ai/ai-gateway/endpoints/decision-models.md). |

Use a [passthrough route](https://docs.api7.ai/ai-gateway/endpoints/provider-passthrough.md) for an OpenAI route that AISIX does not model, such as moderation or image variations. The `/passthrough/openai` paths on this page assume a route claiming that prefix with OpenAI's API root as its `target_url`; grant the route on the caller key's `allowed_routes`. Passthrough uses OpenAI model IDs rather than AISIX aliases and has different streaming and usage-accounting behavior.

## Use an OpenAI SDK[​](#use-an-openai-sdk "Direct link to Use an OpenAI SDK")

Set `AISIX_BASE_URL` to `${AISIX_PROXY}/v1` and use the caller key as the API key. See the [OpenAI SDK](https://docs.api7.ai/ai-gateway/getting-started/openai-sdk.md) guide.

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

You have now connected AISIX to OpenAI and verified the model alias. Continue with these guides:

* [Model Aliases](https://docs.api7.ai/ai-gateway/models/model-aliases.md): configure routing, retry behavior, or cost metadata for this alias.
* [Audio Input and Output with Chat Completions](https://docs.api7.ai/ai-gateway/endpoints/chat-audio.md): send recorded audio to a compatible chat model or save its generated audio response.
* [Azure OpenAI](https://docs.api7.ai/ai-gateway/providers/azure-openai.md): configure an Azure-hosted OpenAI deployment instead.
* [Provider Compatibility](https://docs.api7.ai/ai-gateway/providers/compatibility.md): review supported proxy endpoints and provider-specific boundaries.
