Skip to content
AI GatewayAI Gateway Manual

Use the OpenAI SDK with AI Gateway

Keep your OpenAI SDK code as it is and use it through AI Gateway by changing only the base URL and API key.

AI Gateway supports requests and responses in the same format as the OpenAI API. Code written with the official OpenAI SDK therefore works through AI Gateway without other changes. You change only two values:

  • Base URL: https://<gateway-host>/v1 instead of https://api.openai.com/v1.
  • API key: a Gateway Key instead of an OpenAI API key.

Request and response formats, streaming, and tool calling stay the same, so the rest of your code does not change. AI Gateway applies the project’s model permissions, routing policy, and usage limits to every request.

To use the Anthropic SDK instead, see Use the Anthropic SDK.

  • Install the OpenAI SDK: pip install openai for Python, or npm install openai for JavaScript / TypeScript.
  • Issue a Gateway Key from the Gateway Keys menu of the project you want to use. See Issue a Gateway Key for the steps.
  • Check that the model you want appears in the Models menu of the same project. In the row of the model, select the gear icon in the Installation column and check the Gateway base URL and model ID.

Set the Gateway Key as an environment variable where your code runs. The examples on this page read it from AI_GATEWAY_API_KEY.

Terminal window
export AI_GATEWAY_API_KEY='<your Gateway Key>'

A Gateway Key is a secret. Do not put the key value directly in source code, source control, or shared screenshots.

APISDK methodPath
Chat Completionschat.completions.create/v1/chat/completions
Responsesresponses.create/v1/responses
Embeddingsembeddings.create/v1/embeddings
Images (generation)images.generate/v1/images/generations
Models (list)models.list/v1/models

Replace <gateway-host> in the examples with the host of your AI Gateway. The SDK adds the rest of the path itself.

Python:

import os
from openai import OpenAI
client = OpenAI(
base_url="https://<gateway-host>/v1",
api_key=os.environ["AI_GATEWAY_API_KEY"],
)
completion = client.chat.completions.create(
model="<provider-name>/<model-id>",
messages=[{"role": "user", "content": "Hello!"}],
)
print(completion.choices[0].message.content)

JavaScript / TypeScript:

import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://<gateway-host>/v1",
apiKey: process.env.AI_GATEWAY_API_KEY,
});
const completion = await client.chat.completions.create({
model: "<provider-name>/<model-id>",
messages: [{ role: "user", content: "Hello!" }],
});
console.log(completion.choices[0].message.content);

The SDK sends the Gateway Key in the Authorization: Bearer header, as it does with an OpenAI API key.

The Responses API works the same way:

response = client.responses.create(
model="<provider-name>/<model-id>",
input="Write a one-line summary of AI Gateway.",
)
print(response.output_text)

You can call embedding models registered with OpenAI, OpenAI-format Custom, and AWS Bedrock Providers. An administrator must allow Embeddings for a Custom Provider. Use the exact provider-name/model-id allowed in your project and a Gateway Key from the same project.

Python:

embedding = client.embeddings.create(
model="<provider-name>/text-embedding-3-small",
input=["AI Gateway", "Semantic search"],
encoding_format="float",
)
print(embedding.data[0].embedding)
print(embedding.usage.prompt_tokens)

JavaScript / TypeScript:

const embedding = await client.embeddings.create({
model: "<provider-name>/text-embedding-3-small",
input: ["AI Gateway", "Semantic search"],
encoding_format: "float",
});
console.log(embedding.data[0].embedding);
console.log(embedding.usage.prompt_tokens);

Keep the existing client configuration. Embeddings do not support streaming. Set encoding_format: "base64" to request a base64 response, and use dimensions when the model supports it.

Bedrock uses the same client. Titan Text and Nova Embeddings text mode accept a string or a one-element string array. Cohere Embed also accepts batches of strings.

titan = client.embeddings.create(
model="<bedrock-provider-name>/amazon.titan-embed-text-v2:0",
input="AI Gateway",
encoding_format="float",
)
cohere = client.embeddings.create(
model="<bedrock-provider-name>/cohere.embed-english-v3",
input=["AI Gateway", "Semantic search"],
encoding_format="float",
)
nova = client.embeddings.create(
model="<bedrock-provider-name>/amazon.nova-2-multimodal-embeddings-v1:0",
input="Semantic search",
encoding_format="base64",
)

Bedrock does not accept token arrays, images, audio, or video on this endpoint. Sending two or more inputs to Titan or Nova returns 400 before an AWS call. Split multiple inputs into calls that the model accepts. Model availability and access depend on the AWS region and account.

The official OpenAI SDK may request base64 by default and decode the response into numeric arrays. Explicitly setting encoding_format="base64" returns encoded strings.

Embedding usage contains input tokens only, and total_tokens equals prompt_tokens. Do not count vector length or input items as token usage. Without valid usage or a price, the corresponding Gateway log value remains unavailable.

OpenAI and Custom received and decompressed request bodies each have a 100 MiB limit. Above 10 MiB, the Gateway checks policy, model, and size while the Provider validates the input and options.

Bedrock received, decompressed, and AWS-format bodies each have a 10 MiB (10,485,760 bytes) limit. Exceeding it returns 413 before AWS dispatch. Reduce the input size or split it into smaller batches that the model supports. Titan and Nova require one input per call.

Both raw and normalized responses have an 8 MiB limit. Provider token and batch limits also apply. See the administrator guide for setup and usage checks.

You can call image models registered with OpenAI, OpenAI-format Custom, and Bedrock Runtime Providers. An administrator must enable Image generation for a Custom Provider. Use your existing client and a model ID allowed in the project.

Python:

image = client.images.generate(
model="<provider-name>/gpt-image-1.5",
prompt="A plain green circle on a white background, no text.",
n=1,
size="1024x1024",
quality="low",
output_format="png",
)
print(len(image.data))
print(image.usage)
# Use image.data[0].b64_json, or url when the target model supports it.

JavaScript / TypeScript:

const image = await client.images.generate({
model: "<provider-name>/gpt-image-1.5",
prompt: "A plain green circle on a white background, no text.",
n: 1,
size: "1024x1024",
quality: "low",
output_format: "png",
});
console.log(image.data?.length);
console.log(image.usage);
// Use image.data?.[0]?.b64_json, or url when the target model supports it.

Image generation supports non-streaming JSON only. stream:true, partial_images, image edits, and variations are unsupported. The Gateway does not automatically download images from returned URLs.

Bedrock Runtime supports Stable Image Core (stability.stable-image-core-v1:1), Stable Image Ultra (stability.stable-image-ultra-v1:1), and Stable Diffusion 3.5 Large (stability.sd3-5-large-v1:0). Use https://bedrock-runtime.us-west-2.amazonaws.com as the Provider’s base URL. The model must be registered in the Provider’s model list, and project policy, AWS invocation permissions, and quotas must allow it. This example calls an allowed Stable Image Core model and uses its returned base64 data. Bedrock Mantle, opaque application profile ARNs, and the retired Titan Image Generator v1/v2, Nova Canvas, Core/Ultra v1:0, and SD3 Large models are unsupported.

image = client.images.generate(
model="bedrock-provider/stability.stable-image-core-v1:1",
prompt="A plain green circle on a white background.",
response_format="b64_json",
)
image_base64 = image.data[0].b64_json

Bedrock returns b64_json even when you request response_format="url"; the Gateway does not create image URLs. Unreported tokens remain unavailable. When an administrator’s saved image price or a built-in price exists, cost is calculated from the actual generated count. Received, decompressed, and converted requests each have a 10 MiB Gateway limit; raw and normalized success responses each have a 64 MiB limit. Model-specific limits also apply.

The current Stability conversion does not send size or quality, so cost cannot be calculated from these conditions. Cost is the confirmed image count multiplied by a fixed per-image rate. A rate the administrator saved on the Provider takes precedence; otherwise the built-in price applies (0.04 USD per image for Stable Image Core, 0.14 USD for Ultra). Stable Diffusion 3.5 Large has no built-in price, so its cost remains unavailable until an administrator saves a rate. Check the AWS model cards for availability and retirement status.

Requests have a maximum size of 10 MiB, including after decompression. Successful response JSON has a maximum size of 64 MiB after decompression. Large requests do not switch to passthrough: oversized requests fail with 413, and oversized responses fail with 502.

The image count comes from the actual response. Unreported token usage remains unavailable in logs; neither n nor base64 length substitutes for tokens. Conditional per-image pricing requires a confirmed count, size, and quality. Fixed per-image pricing requires only a confirmed count. Both modes can calculate cost when token usage is unavailable.

Use gemini-3.1-flash-image or gemini-3-pro-image on a Gemini Provider. The model must be allowed in the project, and your Google account needs model access and sufficient quota.

image = client.images.generate(
model="gemini-provider/gemini-3.1-flash-image",
prompt="A plain green circle on a white background, no text.",
response_format="b64_json",
)
image_base64 = image.data[0].b64_json
const image = await client.images.generate({
model: "gemini-provider/gemini-3-pro-image",
prompt: "A plain green circle on a white background, no text.",
response_format: "b64_json",
});
const imageBase64 = image.data?.[0]?.b64_json;

Replace gemini-provider with your Provider’s name. The Gateway calls generateContent once. It omits n and does not repeat the call to fill the requested count. Even with response_format="url", the response contains base64 data.

Generated text is not returned, but reported text and thinking usage is settled. SDK output tokens may show only candidate output; total output in Model Logs includes thinking. Reasoning tokens are a subset of that total, so do not add them again. Pricing uses reviewed Standard token rates. Cost remains unavailable if usage or applicable rates cannot be established.

Only non-streaming requests that generate new images from text prompts are supported. Image input, editing, multi-turn requests, Imagen predict, Interactions, Vertex AI, and Custom Gemini are unsupported. Blocked, incomplete, image-free results and responses containing intermediate thinking images fail with 502. Confirmed usage may still be recorded on failure. Received, decompressed, and converted requests each have a 10 MiB limit; raw and normalized success responses each have a 64 MiB limit. See the administrator guide for setup and accounting rules.

Set stream=True (or stream: true in JavaScript) as you would with OpenAI:

stream = client.chat.completions.create(
model="<provider-name>/<model-id>",
messages=[{"role": "user", "content": "Count from 1 to 5."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")

models.list() returns the models allowed in the project of the Gateway Key. Each ID has the form provider-name/model-id and can be passed to model as is.

for model in client.models.list():
print(model.id)

The model value selects the provider and the model in the form provider-name/model-id. AI Gateway converts the request between formats, so the OpenAI SDK can call a model of any provider allowed in the project, including Claude models:

# Call a model registered under an Anthropic provider
client.chat.completions.create(
model="<anthropic-provider-name>/<claude-model-id>",
messages=[{"role": "user", "content": "Hello!"}],
)

Use the exact model ID shown in the Models menu. When the project has a routing policy, the policy can choose the provider model, and the administrator may tell you a different model value to use.

  • Only the APIs in the Supported APIs table are supported. Image edits and variations, Audio, Files, Batch, and other APIs return an error.
  • Embeddings support OpenAI, OpenAI-format Custom, and supported Bedrock text embedding models. Routing to another format or an unsupported Bedrock model rejects the call.
  • A field or feature works only when the target provider supports it. For example, a request that uses a feature only OpenAI offers may be rejected when it is routed to a model of another provider.
  • Models of a provider that connects ChatGPT accounts (type openai_codex) work only with streaming requests (stream=True) to the Responses API.
  1. 401 error: Check that the API key is a Gateway Key and that the environment variable is set where the code runs. If the key is correct and you still get 401, check that the API you call is in the Supported APIs table. A request to an unsupported API also returns 401, even with a valid Gateway Key.
  2. 404 error or model not found: Check that the base URL ends with /v1. Also check that model is an exact ID in the project’s Models menu.
  3. Model missing from the list: A Gateway Key belongs to the project it was issued in, so another project’s key gives a different list. Check that the model is allowed in that project.
  4. 429 error: The project’s usage limit or the provider’s rate limit was reached. Try again later, or ask the project administrator to check the limits.
  5. If it still fails, ask the AI Gateway administrator to check the request. Share the request ID from the error response, not the key value.

For the full SDK reference, see the OpenAI SDK documentation.