Python v1 示例。
API 密钥身份验证:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
)
response = client.responses.create(
model="gpt-4.1-nano", # Replace with your deployment name
input="This is a test.",
)
print(response.model_dump_json(indent=2))
请注意前面的代码的以下详细信息:
- 使用
OpenAI()客户端而不是已弃用的AzureOpenAI()客户端。
- 将附加
/openai/v1/ 的 Azure OpenAI 终结点作为 base_url 传递。
- 无需向 v1 GA API 提供
api-version 参数。
- 将
model 参数设置为部署模型时选择的基础 部署名称 。 此名称与部署的模型的名称不同。
要使用为 OPENAI_BASE_URL 和 OPENAI_API_KEY 设置了环境变量的 API 密钥:
client = OpenAI()
Microsoft Entra 身份验证:
Microsoft Entra 身份验证仅支持 Azure OpenAI 资源。 完成以下步骤:
安装 Azure 标识客户端库:
pip install azure-identity
使用以下代码配置 OpenAI 客户端对象、指定部署并生成响应。
import os
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key = token_provider
)
response = client.responses.create(
model ="gpt-4.1-nano", # Replace with your deployment name
input = "This is a test"
)
print(response.model_dump_json(indent=2))
请注意前面的代码的以下详细信息:
- 使用
OpenAI()客户端而不是已弃用的AzureOpenAI()客户端。
- 将附加
/openai/v1/ 的 Azure OpenAI 终结点作为 base_url 传递。
- 将
api_key 参数设置为 token_provider. 此设置支持自动检索和刷新身份验证令牌,而不是使用静态 API 密钥。
- 无需向 v1 GA API 提供
api-version 参数。
- 将
model 参数设置为部署模型时选择的基础 部署名称 。 此名称与部署的模型的名称不同。
C# v1 示例
API 密钥身份验证:
using OpenAI;
using OpenAI.Responses;
using System.ClientModel;
#pragma warning disable OPENAI001
string deploymentName = "my-gpt-4.1-nano-deployment"; // Your model deployment name
OpenAIResponseClient client = new(
model: deploymentName,
credential: new ApiKeyCredential("{your-api-key}"),
options: new OpenAIClientOptions()
{
Endpoint = new("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"),
});
OpenAIResponse response = client.CreateResponse(
[
ResponseItem.CreateUserMessageItem("What's the weather like today for my current location?")
]);
Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");
Microsoft Entra 身份验证:
Microsoft Entra 身份验证仅支持 Azure OpenAI 资源。 完成以下步骤:
安装 Azure 标识客户端库:
dotnet add package Azure.Identity
使用以下代码配置 OpenAI 客户端对象、指定部署并生成响应。
using Azure.Identity;
using OpenAI;
using OpenAI.Responses;
using System.ClientModel.Primitives;
#pragma warning disable OPENAI001
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default");
string deploymentName = "my-gpt-4.1-nano-deployment"; // Your model deployment name
OpenAIResponseClient client = new(
model: deploymentName,
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions()
{
Endpoint = new("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"),
});
OpenAIResponse response = client.CreateResponse(
[
ResponseItem.CreateUserMessageItem("What's the weather like today for my current location?")
]);
Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");
JavaScript v1 示例
API 密钥身份验证:
import { OpenAI } from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: "{your-api-key}"
});
// Make the API request with top-level await
const result = await client.responses
.stream({
model: 'gpt-4.1-nano', // Your model deployment name
input: 'solve 8x + 31 = 2',
}).finalResponse()
// Print the full response
console.log('Full response:', result);
// Print just the message content from the response
console.log('Response content:', result.choices[0].message.content);
若要使用为 OPENAI_BASE_URL 和 OPENAI_API_KEY 设置了环境变量的 API 密钥,请通过以下方式创建客户端来修改前面的代码:
import { OpenAI } from "openai";
const client = new OpenAI();
Microsoft Entra 身份验证:
首先安装 Azure 标识客户端库,然后才能使用 DefaultAzureCredential:
npm install @azure/identity
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import { OpenAI } from "openai";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
'https://cognitiveservices.azure.com/.default');
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: tokenProvider
});
// Make the API request with top-level await
const result = await client.responses
.stream({
model: 'gpt-4.1-nano', // Your model deployment name
input: 'solve 8x + 31 = 2',
}).finalResponse()
// Print the full response
console.log('Full response:', result);
// Print just the message content from the response
console.log('Response content:', result.choices[0].message.content);
Go v1 示例
API 密钥身份验证:
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
client := openai.NewClient(
option.WithBaseURL("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"),
option.WithAPIKey("{your-api-key}")
)
// Make a completion request
question := "Write me a haiku about computers"
resp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(question)},
Model: "gpt-4.1-nano", // Use your deployed model name on Azure
})
if err != nil {
panic(err.Error())
}
println(resp.OutputText())
要使用为 OPENAI_BASE_URL 和 OPENAI_API_KEY 设置了环境变量的 API 密钥:
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
client := openai.NewClient()
Microsoft Entra 身份验证:
首先安装 Azure 标识模块:
go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/azure"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
tokenCredential, err := azidentity.NewDefaultAzureCredential(nil)
client := openai.NewClient(
option.WithBaseURL("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"),
azure.WithTokenCredential(tokenCredential)
)
// Make a completion request
question := "Write me a haiku about computers"
resp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(question)},
Model: "gpt-4.1-nano", // Use your deployed model name on Azure
})
if err != nil {
panic(err.Error())
}
println(resp.OutputText())
Java v1 示例
API 密钥身份验证:
package com.example;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/")
.apiKey(apiKey)
.build();
要使用为 OPENAI_BASE_URL 和 OPENAI_API_KEY 设置了环境变量的 API 密钥:
package com.example;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
OpenAIClient client = OpenAIOkHttpClient.builder()
.fromEnv()
.build();
生成响应:
package com.example;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.responses.ResponseCreateParams;
public class OpenAITest {
public static void main(String[] args) {
// Get API key from environment variable for security
String apiKey = System.getenv("OPENAI_API_KEY");
String resourceName = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
String modelDeploymentName = "gpt-4.1-nano"; //replace with you model deployment name
try {
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl(resourceName)
.apiKey(apiKey)
.build();
ResponseCreateParams.Builder paramsBuilder = ResponseCreateParams.builder()
.model(modelDeploymentName)
.input("What's the capital/major city of France?");
ResponseCreateParams createParams = paramsBuilder.build();
client.responses().create(createParams).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(outputText -> System.out.println(outputText.text()));
}
}
}
Microsoft Entra 身份验证:
使用 Microsoft Entra ID 进行身份验证需要一些初始设置。 首先安装 Azure 标识客户端库。 有关如何安装此库的更多选项,请参阅 适用于 Java 的 Azure 标识客户端库。
添加 Azure 标识客户端库:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.18.0</version>
</dependency>
设置后,可以从 azure.identity 中选择要使用的凭据类型。 例如, DefaultAzureCredential 可用于对客户端进行身份验证。
身份验证是最简单的使用 DefaultAzureCredential。 它会在其运行环境中查找要使用的最佳凭据。
package com.example;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.responses.ResponseCreateParams;
public class OpenAITest {
public static void main(String[] args) {
String resourceName = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
String modelDeploymentName = "gpt-4.1-nano"; //replace with you model deployment name
try {
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl(resourceName)
// Set the Azure Entra ID
.credential(BearerTokenCredential.create(AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(), "https://cognitiveservices.azure.com/.default")))
.build();
ResponseCreateParams.Builder paramsBuilder = ResponseCreateParams.builder()
.model(modelDeploymentName)
.input("What's the capital/major city of France?");
ResponseCreateParams createParams = paramsBuilder.build();
client.responses().create(createParams).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(outputText -> System.out.println(outputText.text()));
}
}
}
API 密钥身份验证:
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "gpt-4.1-nano",
"input": "This is a test"
}'
Microsoft Entra 身份验证:
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN" \
-d '{
"model": "gpt-4o",
"input": "This is a test"
}'
API 密钥身份验证:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
)
completion = client.chat.completions.create(
model="grok-3-mini", # Replace with your model deployment name.
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "When was Microsoft founded?"}
]
)
#print(completion.choices[0].message)
print(completion.model_dump_json(indent=2))
Microsoft Entra 身份验证:
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider,
)
completion = client.chat.completions.create(
model="grok-3-mini", # Replace with your model deployment name.
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Tell me about the attention is all you need paper"}
]
)
#print(completion.choices[0].message)
print(completion.model_dump_json(indent=2))
API 密钥身份验证:
using OpenAI;
using OpenAI.Chat;
using System.ClientModel;
string keyFromEnvironment = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY");
ChatClient client = new(
model: "grok-3-mini", // Replace with your model deployment name.
credential: new ApiKeyCredential(keyFromEnvironment),
options: new OpenAIClientOptions() {
Endpoint = new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/")
}
);
ChatCompletion completion = client.CompleteChat("Tell me about the bitter lesson.'");
Console.WriteLine($"[ASSISTANT]: {completion.Content[0].Text}");
Microsoft Entra 身份验证:
安全的无密钥身份验证方法是通过 Azure 标识库使用 Microsoft Entra ID。 若要使用该库,请使用以下代码:
dotnet add package Azure.Identity
使用库中的所需凭据类型。 例如,DefaultAzureCredential:
using Azure.Identity;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;
#pragma warning disable OPENAI001
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default");
ChatClient client = new(
model: "grok-3-mini", // Replace with your model deployment name.
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions() {
Endpoint = new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1")
}
);
ChatCompletion completion = client.CompleteChat("Tell me about the attention is all you need paper");
Console.WriteLine($"[ASSISTANT]: {completion.Content[0].Text}");
API 密钥身份验证:
不建议在生产环境中使用 API 密钥,因为其安全性低于其他身份验证方法。
import { OpenAI } from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env['OPENAI_API_KEY'] //Your Azure OpenAI API key
});
const messages = [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Tell me about the attention is all you need paper' }
];
// Make the API request with top-level await
const result = await client.chat.completions.create({
messages,
model: 'grok-3-mini', // Your model deployment name
max_tokens: 100
});
// Print the full response
console.log('Full response:', result);
// Print just the message content from the response
console.log('Response content:', result.choices[0].message.content);
Microsoft Entra 身份验证:
首先安装 Azure 标识客户端库,然后才能使用 DefaultAzureCredential:
npm install @azure/identity
若要对客户端进行身份验证 OpenAI ,请使用 getBearerTokenProvider 包中的 @azure/identity 函数。 该函数创建一个令牌提供程序,OpenAI 内部使用该提供程序为每个请求获取令牌。 按如下所示创建令牌提供程序:
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import { OpenAI } from "openai";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
'https://cognitiveservices.azure.com/.default');
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: tokenProvider
});
const messages = [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Tell me about the attention is all you need paper' }
];
// Make the API request with top-level await
const result = await client.chat.completions.create({
messages,
model: 'grok-3-mini', // Your model deployment name
max_tokens: 100
});
// Print the full response
console.log('Full response:', result);
// Print just the message content from the response
console.log('Response content:', result.choices[0].message.content);
API 密钥身份验证:
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/option"
)
func main() {
// Create a client with Azure OpenAI endpoint and API key
client := openai.NewClient(
option.WithBaseURL("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"),
option.WithAPIKey("API-KEY-HERE"),
)
// Make a completion request
chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
Messages: []openai.ChatCompletionMessageParamUnion{
openai.UserMessage("Tell me about the bitter lesson"),
},
Model: "grok-3-mini", // Use your deployed model name on Azure
})
if err != nil {
panic(err.Error())
}
fmt.Println(chatCompletion.Choices[0].Message.Content)
}
Microsoft Entra 身份验证:
使用 azidentity 模块与 Azure OpenAI 一起进行 Microsoft Entra ID 身份验证。
安装 Azure 标识模块:
go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/azure"
"github.com/openai/openai-go/v2/option"
)
func main() {
// Create an Azure credential
tokenCredential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
panic(fmt.Sprintf("Failed to create credential: %v", err))
}
// Create a client with Azure OpenAI endpoint and token credential
client := openai.NewClient(
option.WithBaseURL("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"),
azure.WithTokenCredential(tokenCredential),
)
// Make a completion request
chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
Messages: []openai.ChatCompletionMessageParamUnion{
openai.UserMessage("Explain what the bitter lesson is?"),
},
Model: "grok-3-mini", // Use your deployed model name on Azure
})
if err != nil {
panic(err.Error())
}
fmt.Println(chatCompletion.Choices[0].Message.Content)
}
API 密钥身份验证:
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/")
.apiKey(apiKey)
.build();
Microsoft Entra 身份验证:
使用 Microsoft Entra ID 进行身份验证需要一些初始设置:
添加 Azure 标识包:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.18.0</version>
</dependency>
设置后,可以从 azure.identity 中选择要使用的凭据类型。 例如, DefaultAzureCredential 可用于对客户端进行身份验证。
身份验证是最简单的使用 DefaultAzureCredential。 它会在其运行环境中查找要使用的最佳凭据。
Credential tokenCredential = BearerTokenCredential.create(
AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(),
"https://cognitiveservices.azure.com/.default"));
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/")
.credential(tokenCredential)
.build();
有关 Azure OpenAI 无密钥身份验证的详细信息,请参阅 不使用密钥的 Azure OpenAI。
聊天完成:
package com.example;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
public class OpenAITest {
public static void main(String[] args) {
// Get API key from environment variable for security
String apiKey = System.getenv("OPENAI_API_KEY");
String resourceName = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
String modelDeploymentName = "grok-3-mini"; //replace with you model deployment name
try {
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl(resourceName)
.apiKey(apiKey)
.build();
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.addUserMessage("Explain what the bitter lesson is?")
.model(modelDeploymentName)
.build();
ChatCompletion chatCompletion = client.chat().completions().create(params);
}
}
}
API 密钥身份验证:
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "grok-3-mini",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Explain what the bitter lesson is?"
}
]
}'
Microsoft Entra 身份验证:
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN" \
-d '{
"model": "grok-3-mini",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Explain what the bitter lesson is?"
}
]
}'