Azure OpenAI Free code examples in C#, Python, Java and JavaScript
OpenAI models behind Azure auth, networking and regional deployment.
WHAT THIS PAGE COVERS
Entra ID auth instead of an API key — the part that differs from plain OpenAI.
my-gpt-deployment
openai (Azure.AI.OpenAI on .NET)
Model ids change. If a sample returns a 404 on the model, that is the first thing to check against the official docs.
Azure.AI.OpenAI wraps the same OpenAI package you would use directly — GetChatClient hands you the very same ChatClient type, so the OpenAI C# page applies from that line on.
dotnet add package Azure.AI.OpenAI
dotnet add package Azure.Identity
setx AZURE_OPENAI_ENDPOINT "https://your-resource.openai.azure.com"
setx OPENAI_API_VERSION "2024-10-21"
DefaultAzureCredential works from your az login locally and from the managed identity in Azure, so this same code ships unchanged. GetChatClient takes the DEPLOYMENT name.
using Azure.AI.OpenAI;
using Azure.Identity;
using OpenAI.Chat;
AzureOpenAIClient azure = new(
new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!),
new DefaultAzureCredential());
// The argument is your DEPLOYMENT name, not a model id.
ChatClient client = azure.GetChatClient("my-gpt-deployment");
ChatCompletion completion = await client.CompleteChatAsync(
[
new SystemChatMessage("You are a concise technical assistant."),
new UserChatMessage("Explain a database index in two sentences."),
]);
Console.WriteLine(completion.Content[0].Text);
AzureOpenAIClient is thread-safe and holds a connection pool — one singleton, not one per request. DefaultAzureCredential also caches tokens, which a new instance per request throws away.
using Azure.AI.OpenAI;
using Azure.Identity;
using OpenAI.Chat;
builder.Services.AddSingleton(_ => new AzureOpenAIClient(
new Uri(builder.Configuration["AzureOpenAI:Endpoint"]!),
new DefaultAzureCredential()));
builder.Services.AddSingleton(sp => sp
.GetRequiredService<AzureOpenAIClient>()
.GetChatClient(builder.Configuration["AzureOpenAI:Deployment"]!));
// Inject ChatClient anywhere. From here the OpenAI C# page in this
// guide applies verbatim — streaming, tools, ClientResultException.
All three report a cause that is not the cause.
// 1. 404 DeploymentNotFound
// GetChatClient takes your DEPLOYMENT name. Passing a model id
// fails unless the deployment happens to share that name.
// 2. 401 with a valid login
// The identity needs the "Cognitive Services OpenAI User" role on
// the resource. The error says nothing about roles.
// 3. 429 with quota left
// Azure rate limits are per DEPLOYMENT — the tokens-per-minute you
// assigned at creation — not per subscription. Raise the TPM;
// retrying does not help.
// Catch ClientResultException and branch on .Status, exactly as on the
// OpenAI page.
Same package as OpenAI — a different client class inside it. Three environment variables, not one.
pip install openai
export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com"
export AZURE_OPENAI_API_KEY="..."
export OPENAI_API_VERSION="2024-10-21" # check the Azure docs for current
THE thing that catches everyone. `model` is not gpt-5.4-mini here; it is whatever you named the deployment in the Azure portal. A wrong value returns 404 DeploymentNotFound, which reads like the model does not exist.
import os
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
api_key=os.environ["AZURE_OPENAI_API_KEY"],
api_version=os.environ["OPENAI_API_VERSION"],
)
response = client.chat.completions.create(
model="my-gpt-deployment", # deployment name, NOT a model id
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain a database index in two sentences."},
],
)
print(response.choices[0].message.content)
A key in an app setting is a key that gets rotated, leaked, or forgotten. A managed identity has neither problem. DefaultAzureCredential uses your az login locally and the assigned identity in Azure, so the same code works in both.
import os
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import AzureOpenAI
# pip install azure-identity
token_provider = get_bearer_token_provider(
DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default",
)
client = AzureOpenAI(
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
azure_ad_token_provider=token_provider, # no api_key at all
api_version=os.environ["OPENAI_API_VERSION"],
)
response = client.chat.completions.create(
model="my-gpt-deployment",
messages=[{"role": "user", "content": "Explain a database index."}],
)
print(response.choices[0].message.content)
# The identity needs the "Cognitive Services OpenAI User" role on the
# resource. Without it you get a 401 that says nothing about roles.
Every one of these produces an error that points away from the real cause.
# 1. 404 DeploymentNotFound
# The `model` argument is your DEPLOYMENT name, not a model id.
# Passing "gpt-5.4-mini" fails unless that is literally what you
# called the deployment.
# 2. 404 on a valid deployment, or an unknown-parameter error
# Wrong api-version. Each Azure api-version exposes a different set
# of parameters; a feature added after your pinned version simply
# does not exist. Pin it in config so one edit moves everything.
API_VERSION = os.environ["OPENAI_API_VERSION"]
# 3. 429 with plenty of quota left
# Azure rate limits are per DEPLOYMENT (tokens-per-minute assigned
# when you created it), not per subscription. The fix is raising
# that deployment's TPM in the portal, not retrying harder.
# Everything else — streaming, tool calling, typed errors — is the
# OpenAI page in this guide, unchanged.
Azure's own SDK for Java, separate from the OpenAI one. Gradle: implementation("com.azure:azure-ai-openai:1.0.0-beta.16").
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-openai</artifactId>
<version>1.0.0-beta.16</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.15.0</version>
</dependency>
getChatCompletions takes the DEPLOYMENT name as its first argument. That is the single most common Azure mistake in any language.
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.ai.openai.models.ChatCompletions;
import com.azure.ai.openai.models.ChatCompletionsOptions;
import com.azure.ai.openai.models.ChatRequestSystemMessage;
import com.azure.ai.openai.models.ChatRequestUserMessage;
import com.azure.ai.openai.models.ChatRequestMessage;
import com.azure.identity.DefaultAzureCredentialBuilder;
import java.util.List;
OpenAIClient client = new OpenAIClientBuilder()
.endpoint(System.getenv("AZURE_OPENAI_ENDPOINT"))
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
List<ChatRequestMessage> messages = List.of(
new ChatRequestSystemMessage("You are a concise technical assistant."),
new ChatRequestUserMessage("Explain a database index in two sentences."));
ChatCompletions completions = client.getChatCompletions(
"my-gpt-deployment", // DEPLOYMENT name
new ChatCompletionsOptions(messages));
System.out.println(completions.getChoices().get(0).getMessage().getContent());
The streaming call returns an IterableStream. Deltas arrive as choices with a content that may be null — guard before printing.
import com.azure.ai.openai.models.ChatCompletions;
import com.azure.ai.openai.models.ChatCompletionsOptions;
import com.azure.core.util.IterableStream;
IterableStream<ChatCompletions> stream = client.getChatCompletionsStream(
"my-gpt-deployment",
new ChatCompletionsOptions(messages));
stream.forEach(chunk -> chunk.getChoices().forEach(choice -> {
if (choice.getDelta() != null && choice.getDelta().getContent() != null) {
System.out.print(choice.getDelta().getContent());
}
}));
Each reports a cause that is not the cause.
// 1. 404 DeploymentNotFound
// The first argument is your DEPLOYMENT name, not a model id.
String deployment = System.getenv("AZURE_OPENAI_DEPLOYMENT");
// 2. 401 with a valid login
// The identity needs the "Cognitive Services OpenAI User" role on
// the resource. The error message never mentions roles.
// 3. 429 with quota left
// Rate limits are per DEPLOYMENT (its assigned tokens-per-minute),
// not per subscription. Raise the TPM rather than retrying.
// Azure's Java SDK ships its own model classes, so unlike C# this is
// not the OpenAI Java surface — read the azure-ai-openai javadoc for
// tool calling.
Same package as OpenAI, different exported class. Three environment variables.
npm install openai
export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com"
export AZURE_OPENAI_API_KEY="..."
export OPENAI_API_VERSION="2024-10-21" # check the Azure docs for current
Not a model id. A wrong value gives 404 DeploymentNotFound, which reads as though the model is unavailable.
import { AzureOpenAI } from "openai";
const client = new AzureOpenAI({
endpoint: process.env.AZURE_OPENAI_ENDPOINT,
apiKey: process.env.AZURE_OPENAI_API_KEY,
apiVersion: process.env.OPENAI_API_VERSION,
});
const response = await client.chat.completions.create({
model: "my-gpt-deployment", // deployment name, NOT a model id
messages: [
{ role: "system", content: "You are a concise technical assistant." },
{ role: "user", content: "Explain a database index in two sentences." },
],
});
console.log(response.choices[0].message.content);
DefaultAzureCredential uses your az login locally and the assigned managed identity in Azure — the same code in both places, and no secret to rotate.
import { AzureOpenAI } from "openai";
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
// npm install @azure/identity
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default",
);
const client = new AzureOpenAI({
endpoint: process.env.AZURE_OPENAI_ENDPOINT,
azureADTokenProvider: tokenProvider, // no apiKey at all
apiVersion: process.env.OPENAI_API_VERSION,
});
const response = await client.chat.completions.create({
model: "my-gpt-deployment",
messages: [{ role: "user", content: "Explain a database index." }],
});
console.log(response.choices[0].message.content);
Each of these reports a cause that is not the cause.
// 1. 404 DeploymentNotFound — `model` is your DEPLOYMENT name, not a
// model id. "gpt-5.4-mini" fails unless that is what you named it.
// 2. Unknown-parameter errors — wrong api-version. Each version
// exposes a different parameter set, so a newer feature simply is
// not there. Keep it in config.
const API_VERSION = process.env.OPENAI_API_VERSION;
// 3. 429 with quota to spare — Azure rate limits are per DEPLOYMENT
// (the tokens-per-minute you assigned at creation), not per
// subscription. Raise that deployment's TPM; retrying will not help.
// Streaming, tool calling and typed errors are unchanged from the
// OpenAI page in this guide.
QUESTIONS
Which languages are the Azure OpenAI examples in?
C#, Python, Java and JavaScript. Every sample runs as pasted and reads its credentials from an environment variable — no key is ever written into the code.
Which package do I install for Azure OpenAI?
The samples use openai (Azure.AI.OpenAI on .NET). The install step on each language tab gives the exact command.
Which Azure OpenAI model do these examples use?
my-gpt-deployment, checked against the official documentation on 25 September 2026. Model ids change often; if a call returns a model-not-found error, check the current list in the official docs.
Where is the official Azure OpenAI documentation?
https://learn.microsoft.com/azure/ai-services/openai/ — it is linked at the bottom of this page, and it is the authority whenever it disagrees with a sample here.
ALSO IN LANGUAGE MODELS
The authority
Official Azure OpenAI documentation
Model names, pricing and rate limits change faster than any page here can. When this page and the official docs disagree, the official docs are right.
https://learn.microsoft.com/azure/ai-services/openai/