Skip to main content

Adding Models

This section explains the steps to add OpenAI models and configure the required access controls.
1

Select OpenAI as the provider

From the TrueFoundry dashboard, go to AI Gateway > Models, click Add Model and choose To New Provider Account. Select OpenAI from the provider list.
Add Provider Account page listing the supported model providers

Choose a provider in Add Provider Account

2

Configure Account

Give a unique name to your OpenAI account and provide your API Key.
Strongly prefer Workload Identity Federation when you use a TrueFoundry SaaS gateway. It connects without an API key and uses short-lived tokens instead of a long-lived secret.
OpenAI Configure Account form in the provider account setup drawer

Configure Account for OpenAI

3

Select Models

Tick the models you want to enable. Each row shows the model type and its public input and output price per million tokens, which the gateway uses for cost tracking. Click the pencil on a selected model to change its display name or cost.
Models Selection step listing OpenAI models with input and output prices

Models Selection with three OpenAI models picked

If the model you need is not listed, click Add Model Manually in the banner below the list and enter its display name, model ID and model types.
TrueFoundry AI Gateway supports all text and image models in OpenAI. The complete list of models supported by OpenAI can be found here.
For OpenAI Decisions models (for example gpt-6-luna), set Model Types to Decision. These models answer on /v1/decisions and /v1/systemone, not chat completions. See Decision.
4

Save and grant access

Click Test Credentials to check the account against the selected models, or click Save without Testing. To keep the account in Git instead, click Apply using YAML and apply the generated spec with tfy apply.To let other users, teams or virtual accounts use or manage these models, open Manage Accounts, click ⋮ on the account and choose Access Control > Grant Access. See Access control.

Authenticate with Workload Identity Federation

For now, Workload Identity Federation for Anthropic and OpenAI works only on TrueFoundry SaaS gateways (gateway.truefoundry.ai). Support for customer-hosted (hybrid) and self-hosted gateways is planned.
With Workload Identity Federation (WIF), the gateway calls OpenAI with short-lived access tokens instead of an API key. TrueFoundry signs a JWT for your tenant; OpenAI trusts that JWT and returns an access token. You set up the trust once on the OpenAI Platform, then paste two IDs into TrueFoundry: the Identity Provider ID (idp_… or wip_…) and the Service Account ID (user-… or svc_acct_…). Neither is secret.
A federation rule or mapping trusts your whole TrueFoundry tenant, not one provider account: the JWT’s subject is tfy-ai-gateway:tenant:<tenant-name>. Anyone who can manage an Anthropic or OpenAI provider account in your tenant can point it at any rule or mapping that trusts the tenant, and anyone signed in to your tenant can test those IDs by calling the gateway’s test endpoint directly. Give each rule or mapping only the access your whole tenant may use.

What you’ll do

The examples use a tenant named acme.
  1. In TrueFoundry, open a new OpenAI provider account on the Workload Identity Federation tab and copy the Issuer URL, Subject, and Audience.
  2. On the OpenAI Platform, create an identity provider and mapping that use those three values.
  3. Copy the resulting Identity Provider ID and Service Account ID back into TrueFoundry, then test and save.

Copy the values from TrueFoundry

Go to AI Gateway > Models, click Add Model, choose To New Provider Account and select OpenAI. Name the account, turn on Authentication Data and select the Workload Identity Federation tab. Copy the Issuer URL, Subject and Audience, and keep the form open — you’ll paste OpenAI’s IDs into the empty fields below them. Every provider account in your tenant shows the same issuer and subject.
OpenAI account form with the Workload Identity Federation tab selected, showing the issuer URL, subject and audience with Copy buttons, and the Identity Provider ID and Service Account ID fields

The Workload Identity Federation tab of an OpenAI provider account

Set up OpenAI

Do these steps on the OpenAI Platform. Paste the three values you copied from TrueFoundry into the matching fields below.
OpenAI documents arbitrary OIDC issuers, other than the providers in its setup guides, as not supported yet, and asks you to contact OpenAI support if your OIDC provider isn’t listed. The TrueFoundry issuer is such a custom OIDC issuer. If OpenAI rejects the identity provider or every token exchange, contact OpenAI support and mention that the issuer is a custom OIDC issuer.
1

Choose a project

Pick or create a project for gateway traffic, so it gets its own budget and limits. If the project restricts which models it can call, allow the models you plan to add in TrueFoundry.
2

Create the identity provider

Go to Organization settings > Security > Workload Identity Provider > Create identity provider:
  • Name: for example truefoundry-acme.
  • Provider type: OIDC.
  • OIDC Issuer URL: paste the Issuer URL from TrueFoundry, exactly.
  • Audience: paste the Audience from TrueFoundry (https://api.openai.com/v1). The placeholder shows it without /v1. If you enter another value, enter the same value in TrueFoundry too.
  • Advanced: leave both options off and add no attribute transformations.
OpenAI Create workload identity provider dialog with Name, Provider type OIDC, OIDC Issuer URL, Audience, Description and Advanced options

Create workload identity provider

3

Create the mapping

Open the identity provider and click Create mapping:
  • Name: for example tenant-acme.
  • Key and Value: key sub, value the Subject from TrueFoundry, exactly, with no wildcard.
  • Project: the project from step 1.
  • Service account: keep Create a new service account in this project ticked and give it a name. Note the Service Account ID that OpenAI creates (user-… or svc_acct_…) — you’ll paste it into TrueFoundry next.
  • Permissions: Restricted, with Model capabilities set to Request (api.model.request) and everything else set to None. TrueFoundry doesn’t check the scope of the tokens OpenAI issues, so these permissions are the only limit on what they can do.
OpenAI Create mapping dialog with Name, the sub key and its value, Description, Project, and the option to create a new service account

Create mapping: the sub value, project and service account

OpenAI Create mapping permissions with Restricted selected and the Model capabilities row highlighted

Further down the dialog: Restricted permissions. Set Model capabilities to Request and leave everything else at None.

Copy the IDs from OpenAI

Copy these two IDs — they are what you paste into TrueFoundry:
OpenAI Security page, Workload Identity Provider tab, listing an identity provider with its name, a hidden provider ID, type OIDC and the TrueFoundry issuer

The identity provider's ID is in the Provider ID column (hidden here)

Add the account in TrueFoundry

Go back to the form from Copy the values from TrueFoundry.
1

Enter the IDs

Paste the Identity Provider ID and Service Account ID you copied from OpenAI. If the identity provider’s audience isn’t https://api.openai.com/v1, turn on Show advanced fields in the tab and enter it as Audience.Leave Base URL (under Show advanced fields at the bottom of the form) empty, unless your OpenAI project uses data residency: then enter your region’s endpoint, such as https://eu.api.openai.com/v1 (see Regional Endpoints). With Workload Identity Federation, any other host is rejected when you save the account.
2

Select models

Click Continue to Integrations and select models as in Adding Models.
3

Test and save

Click Test Credentials to run a real token exchange with the provider. It works before you save, so you can fix the provider setup first. In the TrueFoundry UI, testing needs the same permission as saving. Then save the account, or click Apply using YAML to keep it in Git and apply it with tfy apply.
OpenAI provider account

Revoke access

Disable the mapping on the OpenAI Platform. New exchanges then fail. Access tokens OpenAI has already issued keep working until they expire, within about 1 hour.

Troubleshooting

OpenAI names the problem in the error response.
The issuer, signature or a claim didn’t verify. Check the identity provider’s OIDC issuer URL, and that its audience matches the account’s Audience (https://api.openai.com/v1 if that’s empty).
The token didn’t match a mapping. Check that the sub row of the mapping is exactly tfy-ai-gateway:tenant:<tenant-name>, and that the mapping is enabled.
OpenAI’s token endpoint returned 500 or 504 because it couldn’t reach the issuer. Usually temporary — retry, and check that the issuer is reachable. If it persists, contact TrueFoundry support.
OpenAI documents custom OIDC issuers as not supported yet, and may not accept one for your organization even when the issuer works and the values match. Contact OpenAI support and mention that the identity provider uses a custom OIDC issuer. See Set up OpenAI.
  • Requests on a customer-hosted (hybrid) or self-hosted gateway fail with Workload identity federation for Anthropic and OpenAI is only supported on TrueFoundry SaaS gateways. — send these requests through a TrueFoundry SaaS gateway, or use an API key provider account on that gateway.
  • Saving the provider account fails with a 400 error: Workload identity federation for Anthropic and OpenAI is only supported on TrueFoundry SaaS. — your control plane isn’t TrueFoundry SaaS. Use an API key provider account there.

Check that the issuer is reachable

Use this when OpenAI can’t verify TrueFoundry’s tokens. OpenAI fetches the signing keys from your issuer URL to check each token, so if that URL doesn’t serve them, every exchange fails. Run these checks before you change the identity provider or mapping. They don’t need any credentials. Fetch your tenant’s discovery document:
Fetch the discovery document
A working issuer returns JSON whose issuer is your issuer URL and whose jwks_uri is <issuer URL>/.well-known/jwks.json. Both documents are public. A 404 means the tenant name in the URL is wrong or the tenant isn’t active. A 503 is temporary, for example while the signing keys load, so retry after a short wait.

How it works

  1. The gateway signs a JWT that names your TrueFoundry tenant, valid for 1 hour, and sends it with the account’s IDs to the provider’s token endpoint.
  2. The provider fetches the public signing keys from your tenant’s issuer URL, verifies the JWT, and checks it against your federation rule (Anthropic) or mapping (OpenAI).
  3. The provider returns an access token valid for about 1 hour, which the gateway uses for model calls. Once half of the token’s life has passed (30 minutes before expiry for a one-hour token), the next request starts a new exchange in the background, and requests keep using the current token meanwhile.
If a refresh fails, for example because the provider or the issuer is briefly unavailable, the gateway keeps using the current token and retries with backoff until 30 seconds before it expires. After that, a failed exchange fails the request with an error that names the provider account. The gateway never falls back to an API key.
The JWT is signed with RS256 and carries exactly these claims, with no user, email or role information. exp is 1 hour after iat, and jti is a new random ID for each JWT. The gateway reuses a signed JWT for up to 5 minutes, so several exchanges can carry the same jti.
Decoded JWT claims
For OpenAI, aud is the account’s Audience, or https://api.openai.com/v1 if it’s empty.

Inference

After adding the models, you can perform inference using an OpenAI-compatible API via the Playground or by integrating with your own application.
TrueFoundry Code Snippet panel showing Base URL, Model ID, API Key and ready-to-use code

Code Snippet panel showing Base URL, Model ID, and API Key

Supported APIs

Once your OpenAI model account is configured, the following API surfaces are available through the AI Gateway. The table below summarizes each endpoint alongside platform feature support (tracing, cost tracking).
Legend:
  • ✅ Supported by provider and TrueFoundry
  • Supported by Provider, but not by TrueFoundry
  • Provider does not support this feature
The chat completions endpoint is the most widely used — it supports streaming, function calling, multimodal input (images, audio, PDF), structured JSON outputs, reasoning models, and prompt caching. Full provider capability matrix: Chat Completions API
Python
Set stream=True to start streaming responses and iterate over delta chunks. You may defensively check that chunk.choices is non-empty and delta.content is not None as some provider chunks (role deltas, finish markers) have no content.
Python
Request parameters like temperature, max_tokens, top_p, frequency_penalty, presence_penalty, and stop fine-tune generation behaviour.
Some models don’t support all parameters — e.g. temperature is not supported on o-series reasoning models.
Python
Advertise a tool, hand the model’s tool_calls back as a tool role message, then request the final response. Use tool_choice to force the model to call a specific tool when you need deterministic behaviour, and defensively unwrap tool_calls since the model may still return content instead of a tool call on some prompts.
Python
Send images as part of a message via the image_url content part. The URL can be a public HTTP URL or an inline data:image/...;base64,... URI.
Python
Send PDF documents as part of a message via the file content type with base64 encoding.
Python
Control the output format with response_format. Two modes:
  • JSON object — {"type": "json_object"} — valid JSON, no schema. Include “respond in JSON” in the prompt.
  • JSON schema — {"type": "json_schema", ...} — strict schema conformance. Set all properties in required.
Python
Reasoning models (o3, o4-mini, etc.) expose a separate pool of reasoning tokens that show up in response.usage. Some request parameters like temperature are not supported on these models.
Python
OpenAI supports automatic prompt caching for gpt-4o and newer models. Pass an optional prompt_cache_key parameter to improve cache hit rates when requests share common prefixes. Cached tokens appear in usage.prompt_tokens_details.cached_tokens.
Python
The embeddings endpoint accepts a single string or a list of strings and returns dense vectors suitable for semantic search, clustering, or RAG. Full docs: Embed API.
Python
Supported models: text-embedding-3-small, text-embedding-3-large, text-embedding-ada-002. See the OpenAI embeddings guide for dimension and pricing details.
OpenAI’s Responses API is a stateful alternative to chat completions that manages conversation state on the server and supports retrieve, delete, and multimodal inputs. Full docs: Responses API.
The Responses API requires the x-tfy-provider-name header. Set it on default_headers when you construct the client — the AI Gateway uses it to route the request to the right OpenAI model account.
Python
Generate images with DALL·E 2/3 or GPT-Image via client.images.generate. The response contains either b64_json or url depending on the model and request parameters — handle both. Full docs: Image Generation.
Python
Supported models: gpt-image-1, dall-e-2, dall-e-3.
Edit an existing image with a text prompt via client.images.edit. Same models as image generation, with size constraints: gpt-image-1 accepts PNG/WebP/JPG up to 50 MB and up to 16 input images, while dall-e-2 requires a single square PNG ≤ 4 MB. Full docs: Image Edit.
Python
Legacy endpoint — dall-e-2 has been deprecated by OpenAI. The create_variation endpoint only supported dall-e-2, which is no longer available. Calls to this endpoint may fail post removal. Use images.edit with gpt-image-1 and a variation-style prompt instead (see below).
Legacy: create_variation (dall-e-2 only — deprecated)The original variation API accepted an image and returned creative variations. It required a square PNG ≤ 4 MB and only worked with dall-e-2. Full docs: Image Variation.
Python
Modern: images.edit with variation prompt (gpt-image-1)The recommended replacement is to use images.edit with a variation-style prompt. This works with current models and produces similar results.
Python
Stream spoken audio from text with OpenAI’s TTS models. Use with_streaming_response.create(...) to stream the response body directly to a file or an AsyncIterator. Full docs: Text-to-Speech.
Python
Supported models: gpt-4o-mini-tts, tts-1, tts-1-hd. Supported voices include alloy, echo, fable, onyx, nova, shimmer. See the OpenAI TTS guide for the full list of voices and audio formats.
Transcribe audio files via client.audio.transcriptions.create. Full docs: Audio Transcription.
Python
Supported models: gpt-transcribe, whisper-1, gpt-4o-transcribe, gpt-4o-mini-transcribe. gpt-live-transcribe is realtime-only; see Realtime API.
Translates audio in any source language to English text via client.audio.translations.create. Same whisper-1 model as transcription; the response is always English. Full docs: Audio Translation.
TrueFoundry gates each model entry by capability. A whisper-1 entry registered with transcription only will refuse audio_translation requests with a 400 (audio_translation is not supported for the model). Re-add whisper-1 on the model account with the translation capability enabled to allow this endpoint.
The example below generates a short French TTS sample inline and translates it back to English so the demo is self-contained — text ↔ translated text round-trip with no external audio file.
Python
Process large volumes of requests asynchronously with lower cost and higher throughput than sync inference. The flow is: upload JSONL → create batch → poll for completion → download results. Full docs: Batch Predictions.
The Batch API requires the x-tfy-provider-name header on the client. Also, the model field inside each JSONL request line must be the bare OpenAI model name (e.g. gpt-4o-mini) — not the TrueFoundry-prefixed one. Routing is handled by the header, not the body.
Python
Upload, list, retrieve, and delete files held by the AI Gateway (used by Batch and Fine-tuning). Full docs: Files API.
The Files API requires the x-tfy-provider-name header on the client.
Python
Identify policy-violating content via client.moderations.create. Routes through the regular client (no x-tfy-provider-name header needed). Full docs: Moderation API.
Python
Supported models: omni-moderation-latest (multi-modal — text + image, recommended) and text-moderation-latest (legacy, text-only).
Submit a fine-tuning job for a chat model. The full lifecycle is: upload a JSONL training file → create job → poll → use the resulting model ID. Full docs: Finetune API.
The Fine-tuning API requires the x-tfy-provider-name header on the client. The model field passed to fine_tuning.jobs.create must be the bare upstream OpenAI model name (e.g. gpt-4o-mini-2024-07-18) — not the AI Gateway-prefixed one.
Python
Fine-tuning takes minutes to hours and incurs real charges on your upstream OpenAI account. For training file format and full lifecycle, see the Fine-tuning docs.
OpenAI’s Realtime API streams full-duplex audio (and text) over a WebSocket, enabling low-latency voice interactions. On TrueFoundry, the realtime endpoint lives at:
Note the two quirks:
  • The host is the bare gateway host — no /api/llm suffix.
  • The OpenAI provider-account name is encoded in the URL path, not in the model name. The model passed to client.realtime.connect(model=...) is the bare upstream OpenAI name (e.g. gpt-4o-realtime-preview).
The recommended client is AsyncOpenAI from openai[realtime], which handles the WebSocket framing and event schema for you. Full docs: Realtime API.For browser WebRTC, mint an ephemeral client secret through the Proxy API and connect the browser directly to OpenAI — see OpenAI Realtime with WebRTC. Live WebRTC media is not proxied through the gateway.
Python
For full-duplex audio (mic input + speaker output), use output_modalities: ["audio"], add an audio.input.turn_detection block, and stream PCM chunks through connection.input_audio_buffer.append. See the OpenAI realtime audio reference for a complete sounddevice-based example — it works against the AI Gateway unchanged, just point websocket_base_url at wss://{host}/live/openai-main.
Realtime transcription: Transcription-only models such as gpt-live-transcribe need a transcription session. Connect with intent=transcription and the model name, then select the model in session.update under audio.input.transcription.model. Without intent=transcription, OpenAI rejects the model with invalid_model.
Python
Convert an audio file to the expected format with ffmpeg -i input.mp3 -f s16le -ar 24000 -ac 1 audio.pcm. gpt-live-transcribe does not support server_vad or semantic_vad, so commit each turn yourself. For file transcription of recorded audio, use gpt-transcribe with the Speech-to-Text API instead.
Local audio hardware is required for mic/speaker I/O. Jupyter kernels running over SSH won’t have access to the host’s audio devices — run the audio example locally.
OpenAI decision models answer typed predicate, choice, and score questions about text or images and return probabilities instead of generated text. Add the model with Model Types set to Decision (for example gpt-6-luna). Decision models bill input tokens only, so set the output cost to 0.Call POST /v1/decisions with OpenAI’s input + questions list, or POST /v1/systemone with a System One body — the AI Gateway translates. Image parts (input_image) work only on this provider and on Microsoft Foundry gpt-6-luna deployments. Full docs: Decisions API.
Python

Regional Endpoints

OpenAI offers data residency controls that let you configure the region where your data is stored and, in some regions, processed. When data residency is enabled on your OpenAI account, you must use a region-specific domain prefix for API requests instead of the default api.openai.com. When adding an OpenAI account in TrueFoundry AI Gateway, set the Base URL to the appropriate regional endpoint for your OpenAI project.
baseURL

Enable Advanced Fields to Set Base URL

Regions marked as (required) must use the regional domain prefix for all requests. Regions marked as (optional) can use the prefix to improve latency, but it is not mandatory.
Non-US regions require approval for Modified Abuse Monitoring or Zero Data Retention on your OpenAI account. For full details on data residency, supported models, and endpoint limitations, refer to the OpenAI data controls documentation.