如何在 OpenAI 和 Azure OpenAI 终结点之间切换

本文介绍如何切换到新的统一 OpenAI v1 聊天完成终结点。 它介绍使用 OpenAI 和 Azure OpenAI 时的常见更改和差异。

虽然 OpenAI 和 Azure OpenAI 依赖于常见的 Python 客户端库,但需要对代码进行少量更改,以便在终结点之间来回切换。 新的统一 OpenAI v1 聊天完成终结点无需单独的 Azure 特定代码路径。

Authentication

建议使用 Microsoft Entra ID 进行无密钥身份验证。 如果不可能,请使用 API 密钥并将其存储在 Azure Key Vault 中。 可以使用环境变量在 Azure 环境外部进行测试。

API 密钥身份验证

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY")
)

Microsoft Entra 身份验证

Microsoft Entra 身份验证仅受 Azure OpenAI 资源支持。 完成以下步骤:

  1. 安装 Azure 标识客户端库:

    pip install azure-identity
    
  2. 按如下所示配置 OpenAI 客户端对象:

    from azure.identity import DefaultAzureCredential, get_bearer_token_provider
    from openai import OpenAI
    
    credential = DefaultAzureCredential()
    token_provider = get_bearer_token_provider(
        credential,
        "https://cognitiveservices.azure.com/.default"
    )
    
    client = OpenAI(
        base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/", 
        api_key = token_provider,
    )
    

    小窍门

    DefaultAzureCredential 可以针对运行应用的环境进行优化。 有关详细信息,请参阅 如何自定义 DefaultAzureCredential

  3. 分配适当的 Azure 基于角色的访问控制(RBAC)权限。 有关详细信息,请参阅 Azure 基于角色的访问控制(RBAC)。

    在 Azure 上运行时,将角色分配给 Azure 主机资源使用的托管身份。 在本地开发环境中运行时,将角色分配给运行应用的用户。

using OpenAI;
using System;
using System.ClientModel;

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
OpenAIClient client = new(new ApiKeyCredential(apiKey));

Microsoft Entra 身份验证

Microsoft Entra 身份验证仅受 Azure OpenAI 资源支持。 完成以下步骤:

  1. 安装 Azure 标识客户端库:

    dotnet add package Azure.Identity
    
  2. 配置 OpenAIClient 对象如下:

    using Azure.Identity;
    using OpenAI;
    using System;
    using System.ClientModel.Primitives;
    
    // code omitted for brevity
    
    DefaultAzureCredential credential = new();
    BearerTokenPolicy tokenPolicy = new(credential, "https://cognitiveservices.azure.com/.default");
    
    OpenAIClientOptions clientOptions = new()
    {
        Endpoint = new Uri($"{resourceEndpoint}/openai/v1/")
    };
    
    OpenAIClient client = new(tokenPolicy, clientOptions);
    

    小窍门

    DefaultAzureCredential 可以针对运行应用的环境进行优化。 有关详细信息,请参阅 如何自定义 DefaultAzureCredential

  3. 分配适当的 Azure 基于角色的访问控制(RBAC)权限。 有关详细信息,请参阅 Azure 基于角色的访问控制(RBAC)。

    在 Azure 上运行时,将角色分配给 Azure 主机资源使用的托管身份。 在本地开发环境中运行时,将角色分配给运行应用的用户。

import { OpenAI } from "openai";
import "dotenv/config";

const apiKey = process.env["OPENAI_API_KEY"];

if (!endpoint) {
  throw new Error("Please set the OPENAI_API_KEY environment variable.");
}

const client = new OpenAI({ apiKey });

Microsoft Entra 身份验证

Microsoft Entra 身份验证仅受 Azure OpenAI 资源支持。 完成以下步骤:

  1. 安装 Azure 标识客户端库:

    npm install @azure/identity
    
  2. 按如下所示配置 OpenAI 客户端对象:

    import { OpenAI } from "openai";
    import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
    import "dotenv/config";
    
    const endpoint = process.env["AZURE_OPENAI_ENDPOINT"];
    
    if (!endpoint) {
      throw new Error("Please set the AZURE_OPENAI_ENDPOINT environment variable.");
    }
    
    const scope = "https://cognitiveservices.azure.com/.default";
    const azureADTokenProvider = getBearerTokenProvider(new DefaultAzureCredential(), scope);
    const client = new OpenAI({ baseURL: endpoint + "/openai/v1", apiKey: azureADTokenProvider });
    

    小窍门

    DefaultAzureCredential 可以针对运行应用的环境进行优化。 有关详细信息,请参阅 如何自定义 DefaultAzureCredential

  3. 分配适当的 Azure 基于角色的访问控制(RBAC)权限。 有关详细信息,请参阅 Azure 基于角色的访问控制(RBAC)。

    在 Azure 上运行时,将角色分配给 Azure 主机资源使用的托管身份。 在本地开发环境中运行时,将角色分配给运行应用的用户。

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;

public class OpenAISample {

    public static void main(String[] args) {
        OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("OPENAI_API_KEY"))
                .build();
    }
}

Microsoft Entra 身份验证

Microsoft Entra 身份验证仅受 Azure OpenAI 资源支持。 完成以下步骤:

  1. 在项目中包括 azure-identity 依赖项。

  2. 配置 OpenAIClient 对象如下:

    import com.azure.identity.AuthenticationUtil;
    import com.azure.identity.DefaultAzureCredential;
    import com.azure.identity.DefaultAzureCredentialBuilder;
    import com.openai.client.OpenAIClient;
    import com.openai.client.okhttp.OpenAIOkHttpClient;
    import com.openai.credential.BearerTokenCredential;
    
    import java.util.function.Supplier;
    
    public class AzureOpenAISample {
    
        public static void main(String[] args) {
            DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
            Supplier<String> bearerTokenSupplier = AuthenticationUtil.getBearerTokenSupplier(
                    tokenCredential, "https://cognitiveservices.azure.com/.default");
            OpenAIClient azureOpenAIClient = OpenAIOkHttpClient.builder()
                    .fromEnv()
                    // Set the Azure Entra ID
                    .credential(BearerTokenCredential.create(bearerTokenSupplier))
                    .build();
        }
    }
    

    小窍门

    DefaultAzureCredential 可以针对运行应用的环境进行优化。 有关详细信息,请参阅 如何自定义 DefaultAzureCredential

  3. 分配适当的 Azure 基于角色的访问控制(RBAC)权限。 有关详细信息,请参阅 Azure 基于角色的访问控制(RBAC)。

    在 Azure 上运行时,将角色分配给 Azure 主机资源使用的托管身份。 在本地开发环境中运行时,将角色分配给运行应用的用户。

// import (
//    "github.com/openai/openai-go/v3"
//    "github.com/openai/openai-go/v3/option"
// )

client := openai.NewClient(
    option.WithAPIKey(os.Getenv("OPENAI_API_KEY")),
)

Microsoft Entra 身份验证

Microsoft Entra 身份验证仅受 Azure OpenAI 资源支持。 完成以下步骤:

  1. 在项目中包括 azure-identity 依赖项。

  2. 配置 OpenAIClient 对象如下:

    // import (
    //    "github.com/openai/openai-go/v3"
    //    "github.com/openai/openai-go/v3/azure"
    //    "github.com/openai/openai-go/v3/option"
    // )
    
    client := openai.NewClient(
        option.WithBaseURL("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"),
        azure.WithTokenCredential(cred),
    )
    

    小窍门

    DefaultAzureCredential 可以针对运行应用的环境进行优化。 有关详细信息,请参阅 如何自定义 DefaultAzureCredential

  3. 分配适当的 Azure 基于角色的访问控制(RBAC)权限。 有关详细信息,请参阅 Azure 基于角色的访问控制(RBAC)。

    在 Azure 上运行时,将角色分配给 Azure 主机资源使用的托管身份。 在本地开发环境中运行时,将角色分配给运行应用的用户。

指定模型

OpenAI 使用 model 关键字参数指定要使用的模型。 Azure OpenAI 具有唯一模型 部署的概念。 使用 Azure OpenAI 时, model 应引用部署模型时选择的基础部署名称。

重要

Azure OpenAI 和 OpenAI 在 API 调用中以不同的方式处理模型名称。 OpenAI 只需要模型名称。 即使使用模型参数,Azure OpenAI 也始终需要部署名称。 调用 Azure OpenAI API 时,必须使用部署名称而不是模型名称。 我们的文档通常显示与模型名称匹配的部署名称,以显示哪个模型适用于每个 API 终结点。 选择任何最适合你的部署名称的命名约定。

response = client.responses.create(   
    model="gpt-4.1-nano", 
    input="This is a test."
)

chat_completion = client.chat.completions.create(
    model="gpt-4o", 
    messages="<messages>"
)

embedding = client.embeddings.create(
    model="text-embedding-3-large", 
    input="<input>"
)

OpenAI 使用 model 参数来指定要使用的模型。 Azure OpenAI 具有唯一模型 部署的概念。 使用 Azure OpenAI 时, model 应引用部署模型时选择的基础部署名称。

重要

Azure OpenAI 和 OpenAI 在 API 调用中以不同的方式处理模型名称。 OpenAI 只需要模型名称。 即使使用模型参数,Azure OpenAI 也始终需要部署名称。 调用 Azure OpenAI API 时,必须使用部署名称而不是模型名称。 我们的文档通常显示与模型名称匹配的部署名称,以显示哪个模型适用于每个 API 终结点。 选择任何最适合你的部署名称的命名约定。

string modelName = "gpt-4.1-nano";
OpenAIResponseClient response = client.GetOpenAIResponseClient(modelName);

modelName = "gpt-4o";
ChatClient chatCompletion = client.GetChatClient(modelName);

modelName = "text-embedding-3-large";
EmbeddingClient embedding = client.GetEmbeddingClient(modelName);

OpenAI 使用 model 关键字参数指定要使用的模型。 Azure OpenAI 具有唯一模型 部署的概念。 使用 Azure OpenAI 时, model 应引用部署模型时选择的基础部署名称。

重要

Azure OpenAI 和 OpenAI 在 API 调用中以不同的方式处理模型名称。 OpenAI 只需要模型名称。 即使使用模型参数,Azure OpenAI 也始终需要部署名称。 调用 Azure OpenAI API 时,必须使用部署名称而不是模型名称。 我们的文档通常显示与模型名称匹配的部署名称,以显示哪个模型适用于每个 API 终结点。 选择任何最适合你的部署名称的命名约定。

const response = await client.responses.create({
  model: "gpt-4.1-nano",
  input: "This is a test",
});

const chatCompletions = await client.chat.completions.create({
  model: "gpt-4o",
  messages: ["<messages>"],
});

const embeddings = await client.embeddings.create({
  model: "text-embedding-3-large",
  input: "<input>",
});

OpenAI 使用 model 关键字参数指定要使用的模型。 Azure OpenAI 具有唯一模型 部署的概念。 使用 Azure OpenAI 时, model 应引用部署模型时选择的基础部署名称。

重要

Azure OpenAI 和 OpenAI 在 API 调用中以不同的方式处理模型名称。 OpenAI 只需要模型名称。 即使使用模型参数,Azure OpenAI 也始终需要部署名称。 调用 Azure OpenAI API 时,必须使用部署名称而不是模型名称。 我们的文档通常显示与模型名称匹配的部署名称,以显示哪个模型适用于每个 API 终结点。 选择任何最适合你的部署名称的命名约定。

ResponseCreateParams responseCreateParams = ResponseCreateParams.builder()
        .input("This is a test")
        .model(ChatModel.GPT_4_1_NANO)
        .build();

Response response = client.responses().create(responseCreateParams);

ChatCompletionCreateParams chatCompletionCreateParams = ChatCompletionCreateParams.builder()
        .model(ChatModel.GPT_4O)
        .addUserMessage("<message>")
        .build();

ChatCompletion chatCompletion = client.chat().completions().create(chatCompletionCreateParams);

EmbeddingCreateParams embeddingCreateParams = EmbeddingCreateParams.builder()
        .input("<input>")
        .model(EmbeddingModel.TEXT_EMBEDDING_3_LARGE)
        .build();

CreateEmbeddingResponse createEmbeddingResponse = client.embeddings().create(embeddingCreateParams);

OpenAI 使用 Model 关键字参数指定要使用的模型。 Azure OpenAI 具有唯一模型 部署的概念。 使用 Azure OpenAI 时, Model 应引用部署模型时选择的基础部署名称。

重要

Azure OpenAI 和 OpenAI 在 API 调用中以不同的方式处理模型名称。 OpenAI 只需要模型名称。 即使使用模型参数,Azure OpenAI 也始终需要部署名称。 调用 Azure OpenAI API 时,必须使用部署名称而不是模型名称。 我们的文档通常显示与模型名称匹配的部署名称,以显示哪个模型适用于每个 API 终结点。 选择任何最适合你的部署名称的命名约定。

resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{
    Model: "gpt-4.1-nano", 
    Input: responses.ResponseNewParamsInputUnion{
        OfString: openai.String("This is a test."),
    },
})

resp, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
    Model: "gpt-4o", 
    Messages: []openai.ChatCompletionMessageParamUnion{
        // messages
    },
})

resp, err := client.Embeddings.New(context.TODO(), openai.EmbeddingNewParams{
    Model: "text-embedding-3-large", 
    Input: openai.EmbeddingNewParamsInputUnion{
        OfString: openai.String("<input>"),
    },
})

Azure OpenAI 嵌入多个输入支持

OpenAI 和 Azure OpenAI 目前支持最多 2,048 个输入项的 text-embedding-ada-002输入数组。 两者都需要确保每个 API 请求的输入令牌最大限制保持在 8,191 以下以适应此模型。

inputs = ["A", "B", "C"] 

embedding = client.embeddings.create(
    input=inputs,
    model="text-embedding-3-large"
)
string[] inputs = [ "A", "B", "C" ];

EmbeddingClient embedding = client.GetEmbeddingClient(
    model: "text-embedding-3-large"
).GenerateEmbedding(
    input: inputs
);
const embeddings = await client.embeddings.create({
    model: "text-embedding-3-large",
    inputs: ["A", "B", "C"],
})
EmbeddingCreateParams embeddingCreateParams = EmbeddingCreateParams.builder()
        .inputOfArrayOfStrings(List.of("A", "B", "C"))
        .model(EmbeddingModel.TEXT_EMBEDDING_3_LARGE)
        .build();

CreateEmbeddingResponse createEmbeddingResponse = client.embeddings().create(embeddingCreateParams);
resp, err := client.Embeddings.New(context.TODO(), openai.EmbeddingNewParams{
    Model: "text-embedding-3-large",
    Input: openai.EmbeddingNewParamsInputUnion{
        OfArrayOfStrings: []string{"A", "B", "C"},
    },
})