你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
从 2024 年 6 月开始,我们建议迁移到 OpenAI JavaScript API 库 4.x,这是官方 OpenAI JavaScript 客户端库的最新版本,该库支持 Azure AI Foundry 模型 API 版本及更高版本中 2022-12-01 的 Azure OpenAI。 本文可帮助你快速了解特定于 Azure OpenAI 的更改。
对客户端进行身份验证
可通过若干方式对针对 Azure OpenAI 的 API 请求进行身份验证。 强烈建议使用 Microsoft Entra ID 令牌。 有关详细信息,请参阅 Azure 标识文档。
Microsoft Entra ID
可通过多种方式使用 Microsoft Entra ID 令牌通过 Azure OpenAI 进行身份验证。 默认方法是使用 @azure/identity 包中的 DefaultAzureCredential 类,但应用程序可能使用其他凭据类。 在本指南中,我们假设你使用的是 DefaultAzureCredential 类。 可以按如下所示创建凭据:
import { DefaultAzureCredential } from "@azure/identity";
const credential = new DefaultAzureCredential();
然后,该对象会传递给 OpenAIClient 和 AssistantsClient 客户端构造函数的第二个参数。
但是,为了对 AzureOpenAI 客户端进行身份验证,我们需要使用 @azure/identity 包中的 getBearerTokenProvider 函数。 该函数创建一个令牌提供程序,AzureOpenAI 内部使用该提供程序为每个请求获取令牌。 令牌提供程序的创建方式如下:
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
const credential = new DefaultAzureCredential();
const scope = "https://cognitiveservices.azure.com/.default";
const azureADTokenProvider = getBearerTokenProvider(credential, scope);
创建 AzureOpenAI 客户端时,azureADTokenProvider 会传递给 options 对象。
(极不推荐)API 密钥
不建议在生产环境中使用 API 密钥,因为其安全性低于其他身份验证方法。 之前,按如下所示创建了 AzureKeyCredential 对象,以对 OpenAIClient 或 AssistantsClient 进行身份验证:
import { AzureKeyCredential } from "@azure/openai";
const apiKey = new AzureKeyCredential("your API key");
另一方面,通过设置 AZURE_OPENAI_API_KEY 环境变量或在创建 AzureOpenAI 客户端时设置 options 对象中的 apiKey 字符串属性,可通过 API 密钥对 AzureOpenAI 进行身份验证。
重要
请谨慎使用 API 密钥。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。 如果使用 API 密钥,请将其安全地存储在 Azure Key Vault 中。 若要详细了解如何在应用中安全地使用 API 密钥,请参阅 API 密钥与 Azure 密钥保管库。
有关 AI 服务安全性的详细信息,请参阅 对 Azure AI 服务的请求进行身份验证。
构造客户端
import { AzureOpenAI } from "openai";
const deployment = "Your Azure OpenAI deployment";
const apiVersion = "2024-04-01-preview";
const options = { azureADTokenProvider, deployment, apiVersion }
const client = new AzureOpenAI(options);
Azure OpenAI 资源的终结点可以通过设置 endpoint 选项指定,但也可以通过环境变量 AZURE_OPENAI_ENDPOINT 由客户端加载。 这是设置终结点的推荐方法,因为它允许客户端在不同环境中使用,而无需更改代码,同时还能防止终结点在代码中公开。
需要指定 API 版本,这是确保现有代码在预览 API 版本之间不会中断所必需的。 请参阅 API 版本控制文档,了解有关 Azure OpenAI API 版本的更多信息。 此外,不需要 deployment 属性,但建议进行设置。 设置 deployment 后,它将用作所有需要它的操作的默认部署。 如果客户端不是用 deployment 选项创建的,则应使用部署名称设置 options 对象中的 model 属性。 不过,audio.transcriptions.create 等音频操作要求在创建客户端时将 deployment 选项设置为部署名称。
API 差异
OpenAIClient 和 AssistantsClient 客户端与 AzureOpenAI 客户端之间存在主要区别:
- 操作以
OpenAIClient和AssistantsClient中方法的平面列表形式表示,例如client.getChatCompletions。 在AzureOpenAI中,操作被分组为嵌套组,例如client.chat.completions.create。 OpenAIClient并AssistantsClient重命名 Azure OpenAI API 中使用的许多名称。 例如,在 API 中使用蛇形命名法,但在客户端中使用驼峰命名法。 在AzureOpenAI中,名称与 Azure OpenAI API 中保持相同。
迁移示例
以下部分提供了如何从 OpenAIClient 和 AssistantsClient 迁移到 AzureOpenAI 的示例。
聊天补全
const result = await client.chat.completions.create({ messages, model: '', max_tokens: 100 });
注意以下事项:
getChatCompletions方法已替换为chat.completions.create方法。messages参数现在通过 options 对象中的messages属性传递。maxTokens属性已重命名为max_tokens,deploymentName参数已删除。 通常,options对象中属性的名称与 Azure OpenAI API 中的名称相同,遵循蛇形大小写约定,而不是AssistantsClient中使用的骆驼大小写约定。 这适用于AzureOpenAI客户端中所有请求和响应的所有属性。- 如果使用
deployment选项创建客户端,则不需要deploymentName参数。 如果客户端不是用deployment选项创建的,则应使用部署名称设置 option 对象中的model属性。
流式处理聊天补全
const stream = await client.chat.completions.create({ model: '', messages, max_tokens: 100, stream: true });
基于自有数据的 Azure
import "@azure/openai/types";
const azureSearchEndpoint = "Your Azure Search resource endpoint";
const azureSearchIndexName = "Your Azure Search index name";
const result = await client.chat.completions.create({ model: '', messages, data_sources: [{
type: "azure_search",
parameters: {
endpoint: azureSearchEndpoint,
index_name: azureSearchIndexName,
authentication: {
type: "system_assigned_managed_identity",
}
}
}]
});
- 导入
"@azure/openai/types"后,客户端类型将添加特定于 Azure 的定义(例如data_sources)。 azureExtensionOptions属性已替换为内data_sources属性。- 已添加该
parameters属性以包装扩展的参数,该扩展反映了 Azure OpenAI API 的架构。 - 驼峰命名法的属性已替换为蛇形命名法的属性。
音频听录
import { createReadStream } from "fs";
const result = await client.audio.transcriptions.create({
model: '',
file: createReadStream(audioFilePath),
});
getAudioTranscription方法已替换为audio.transcriptions.create方法。- 要使用
audio.transcriptions.create等音频操作,必须在构建AzureOpenAI时将deployment选项设置为部署名称。 - options 对象中需要设置
model属性,但其值不会在操作中使用,因此可以将其设置为任何值。 file属性可接受多种类型,包括Buffer、fs.ReadaStream和Blob,但在本例中,使用fs.createReadStream从磁盘流式传输文件。
音频翻译
import { createReadStream } from "fs";
const result = await client.audio.translations.create({
model: '',
file: createReadStream(audioFilePath),
});
getAudioTranslation方法已替换为audio.translations.create方法。- 所有其他更改均与音频听录示例中的相同。
助手
以下示例演示如何迁移某些 AssistantsClient 方法。
助手创建
const options = ...;
const assistantResponse = await assistantsClient.beta.assistants.create(
options
);
createAssistant方法已替换为beta.assistants.create方法
线程创建
以下示例演示如何迁移 createThread 方法调用。
const assistantThread = await assistantsClient.beta.threads.create();
createThread方法已替换为beta.threads.create方法
消息创建
以下示例演示如何迁移 createMessage 方法调用。
const threadResponse = await assistantsClient.beta.threads.messages.create(
assistantThread.id,
{
role,
content: message,
}
);
createMessage方法已替换为beta.threads.messages.create方法。- 消息规范已从参数列表移动到对象。
运行次数
要在线程上运行助手,需要使用 createRun 方法创建运行,然后使用循环轮询运行状态,直到其处于终止状态。 以下示例演示如何迁移运行创建和轮询。
使用 createAndPoll 方法可以迁移和简化该代码,该方法会创建一个运行并轮询它,直到它处于终止状态。
const runResponse = await assistantsClient.beta.threads.runs.createAndPoll(
assistantThread.id,
{
assistant_id: assistantResponse.id,
},
{ pollIntervalMs: 500 }
);
createRun方法已替换为beta.threads.runs.create和createAndPoll方法。createAndPoll方法用于创建一个运行并轮询它,直到它处于终止状态。
处理运行结果
可以使用 for await 循环遍历页面。
for await (const runMessageDatum of runMessages) {
for (const item of runMessageDatum.content) {
...
}
}
嵌入
以下示例演示如何迁移 getEmbeddings 方法调用。
const embeddings = await client.embeddings.create({ input, model: '' });
getEmbeddings方法已替换为embeddings.create方法。input参数现在通过 options 对象中的input属性传递。- 已删除
deploymentName参数。 如果使用deployment选项创建客户端,则不需要deploymentName参数。 如果客户端不是用deployment选项创建的,则应使用部署名称设置 option 对象中的model属性。
图像生成
以下示例演示如何迁移 getImages 方法调用。
const results = await client.images.generate({ prompt, model: '', n, size });
getImages方法已替换为images.generate方法。prompt参数现在通过 options 对象中的prompt属性传递。- 已删除
deploymentName参数。 如果使用deployment选项创建客户端,则不需要deploymentName参数。 如果客户端不是用deployment选项创建的,则应使用部署名称设置 option 对象中的model属性。
内容筛选器
内容筛选器结果是 OpenAIClient 中聊天补全响应类型的一部分。 但是,AzureOpenAI 没有与 ChatCompletion.Choice 接口中的 contentFilterResults 属性直接等效的属性。 可以通过导入 "@azure/openai/types" 和访问 content_filter_results 属性来访问内容筛选器结果。 以下示例演示如何访问内容筛选器结果。
import "@azure/openai/types";
const result = await client.chat.completions.create({ model: '', messages });
for (const choice of results.choices) {
const filterResults = choice.content_filter_results;
if (!filterResults) {
console.log("No content filter is found");
return;
}
if (filterResults.error) {
console.log(
`Content filter ran into the error ${filterResults.error.code}: ${filterResults.error.message}`);
}
const { hate, sexual, self_harm, violence } = filterResults;
...
}
- 驼峰命名法的属性已替换为蛇形命名法的属性。
- 导入
"@azure/openai/types"后,会在客户端类型中添加特定于 Azure 的定义(例如 content_filter_results),有关详细信息,请参见 Azure 类型部分。
比较类型
下表探讨了 @azure/openai 中的多个类型名称,并显示其最近的 openai 等效名称。 名称差异说明了上述几种更改。 此表为概述,更多详细信息和代码示例将在以下部分中提供。
| 旧类型名称 | 最近的新类型 | 符号类型 | 更改描述 |
|---|---|---|---|
OpenAIClient |
AzureOpenAI |
班级 | 此类替代了以前的类,与以前的类没有共同的方法。 请参阅下面的 AzureOpenAI 部分。 |
AudioResult |
Transcription/Transcription |
接口 | 根据调用操作,这两个接口替代了以前的单个接口 |
AudioResultFormat |
response_format 属性的内联联合类型 |
别名 | 它不存在 |
AudioResultSimpleJson |
Transcription/Transcription |
接口 | 根据调用操作,这两个接口替代了以前的单个接口 |
AudioResultVerboseJson |
无 | 接口 | |
AudioSegment |
无 | 接口 | |
AudioTranscriptionTask |
无 | 别名 | |
AzureChatEnhancementConfiguration、AzureChatEnhancements、AzureChatExtensionConfiguration、AzureChatExtensionConfigurationUnion、AzureChatExtensionDataSourceResponseCitation、AzureChatExtensionsMessageContext、AzureChatExtensionType、AzureChatGroundingEnhancementConfiguration、AzureChatOCREnhancementConfiguration、AzureCosmosDBChatExtensionConfiguration、AzureCosmosDBFieldMappingOptions、AzureExtensionsOptions、AzureGroundingEnhancement、AzureGroundingEnhancementCoordinatePoint、AzureGroundingEnhancementLine、AzureGroundingEnhancementLineSpan、AzureMachineLearningIndexChatExtensionConfiguration、AzureSearchChatExtensionConfiguration、AzureSearchIndexFieldMappingOptions、AzureSearchQueryType、ContentFilterBlocklistIdResult、ContentFilterCitedDetectionResult、ContentFilterDetectionResult、ContentFilterErrorResults、ContentFilterResult、ContentFilterResultDetailsForPrompt、ContentFilterResultsForChoice、ContentFilterSeverity、ContentFilterResultsForPrompt、ContentFilterSuccessResultDetailsForPrompt、ContentFilterSuccessResultsForChoice、ElasticsearchChatExtensionConfiguration、ElasticsearchIndexFieldMappingOptions、ElasticsearchQueryType、ImageGenerationContentFilterResults、ImageGenerationPromptFilterResults、OnYourDataAccessTokenAuthenticationOptions、OnYourDataApiKeyAuthenticationOptions、OnYourDataAuthenticationOptions、OnYourDataAuthenticationOptionsUnion、OnYourDataConnectionStringAuthenticationOptions、OnYourDataDeploymentNameVectorizationSource、OnYourDataEncodedApiKeyAuthenticationOptions、OnYourDataEndpointVectorizationSource、OnYourDataKeyAndKeyIdAuthenticationOptions、OnYourDataModelIdVectorizationSource、OnYourDataSystemAssignedManagedIdentityAuthenticationOptions、OnYourDataUserAssignedManagedIdentityAuthenticationOptions、OnYourDataVectorizationSource、OnYourDataVectorizationSourceType、OnYourDataVectorizationSourceUnion、PineconeChatExtensionConfiguration、PineconeFieldMappingOptions |
无 | 接口和别名 | 请参阅下面的“Azure 类型”部分 |
AzureKeyCredential |
无 | 班级 | API 密钥可以作为字符串值提供 |
ChatChoice |
ChatCompletion.Choice |
接口 | |
ChatChoiceLogProbabilityInfo |
Logprobs |
接口 | |
ChatCompletions |
ChatCompletion 和 ChatCompletionChunk |
接口 | |
ChatCompletionsFunctionToolCall |
ChatCompletionMessageToolCall |
接口 | |
ChatRequestFunctionMessage |
ChatCompletionFunctionMessageParam |
接口 | |
ChatRequestMessage |
ChatCompletionMessageParam |
接口 | |
ChatRequestMessageUnion |
ChatCompletionMessageParam |
||
ChatRequestSystemMessage |
ChatCompletionSystemMessageParam |
接口 | |
ChatRequestToolMessage |
ChatCompletionToolMessageParam |
接口 | |
ChatRequestUserMessage |
ChatCompletionUserMessageParam |
接口 | |
ChatResponseMessage |
Delta / ChatCompletionMessage |
接口 | |
ChatRole |
无 | 别名 | |
ChatTokenLogProbabilityInfo |
TopLogprob |
接口 | |
ChatTokenLogProbabilityResult |
ChatCompletionTokenLogprob |
接口 | |
Choice |
Choice |
接口 | |
Completions |
Completion |
接口 | |
CompletionsFinishReason |
无 | 别名 | |
CompletionsLogProbabilityModel |
Logprobs |
接口 | |
CompletionsUsage |
CompletionUsage |
接口 | |
EmbeddingItem |
Embedding |
接口 | |
Embeddings |
CreateEmbeddingResponse |
接口 | |
EmbeddingsUsage |
CreateEmbeddingResponse.Usage |
接口 | |
EventStream |
Stream |
接口 | |
FunctionCall |
FunctionCall |
接口 | |
FunctionCallPreset |
无 | 别名 | |
FunctionDefinition |
Function |
接口 | |
FunctionName |
无 | 别名 | |
GetAudioTranscriptionOptions |
TranscriptionCreateParams |
接口 | |
GetAudioTranslationOptions |
TranslationCreateParams |
接口 | |
GetChatCompletionsOptions |
ChatCompletionCreateParamsNonStreaming 和 ChatCompletionCreateParamsStreaming |
接口 | |
GetCompletionsOptions |
CompletionCreateParams |
接口 | |
GetEmbeddingsOptions |
EmbeddingCreateParams |
接口 | |
GetImagesOptions |
ImageGenerateParams |
接口 | |
ImageGenerationData |
Image |
接口 | |
ImageGenerationQuality |
无 | 别名 | |
ImageGenerationResponseFormat |
无 | 别名 | |
ImageGenerations |
ImagesResponse |
接口 | |
ImageGenerationStyle |
无 | 别名 | |
ImageSize |
无 | 别名 | |
MaxTokensFinishDetails |
无 | 接口 | |
OpenAIClientOptions |
AzureClientOptions |
接口 | |
OpenAIError |
OpenAIError |
接口 | |
OpenAIKeyCredential |
无 | 班级 | |
StopFinishDetails |
无 | 接口 |
Azure 类型
AzureOpenAI 连接到 Azure OpenAI,并且可以调用服务中所有可用的操作。 但是,请求和响应的类型是从 OpenAI 继承,尚未更新以反映 Azure OpenAI 服务独家支持的附加功能。 TypeScript 用户需要从 @azure/openai@2.0.0-beta.1 导入 "@azure/openai/types",这会将特定于 Azure 的定义合并到现有类型中。 迁移示例 部分中的示例演示了如何执行此操作。