僅適用於:Foundry(經典)入口。 本文尚未在新的 Foundry 入口網站提供。
了解更多關於新入口網站的資訊。
備註
本文中的連結可能會開啟新版 Microsoft Foundry 文件的內容,而非您目前正在瀏覽的 Foundry(經典版)文件。
這很重要
最新的 API 範例請參考 API 生命週期文章。
驗證用戶端
有幾種方法可以驗證 Azure OpenAI 的 API 請求。 我們強烈建議使用 Microsoft Entra ID 代幣。 更多資訊請參閱 Azure身份文件。
Microsoft Entra ID
使用 Microsoft Entra ID 憑證與 Azure OpenAI 進行驗證的方法有多種。 預設方法是使用 DefaultAzureCredential 套件中的 @azure/identity 類別,但你的應用程式可能使用了不同的憑證類別。 為了進行本指南,我們假設您使用的是 DefaultAzureCredential 類別。 您可以建立認證,如下所示:
import { DefaultAzureCredential } from "@azure/identity";
const credential = new DefaultAzureCredential();
將此物件傳遞給建構子的 OpenAIClient 第二個參數。
然而,為了驗證 AzureOpenAI 用戶端,我們需要使用 getBearerTokenProvider 套件中的 @azure/identity 函式。 此函式會建立權杖提供者,AzureOpenAI 會在內部使用此提供者來為每個要求取得權杖。 權杖提供者便會建立,如下所示:
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
const credential = new DefaultAzureCredential();
const scope = "https://ai.azure.com/.default";
const azureADTokenProvider = getBearerTokenProvider(credential, scope);
azureADTokenProvider 會在建立 AzureOpenAI 用戶端時傳遞至 options 物件。
(非常不建議) API 金鑰
不要在生產環境中使用 API 金鑰,因為它們比其他認證方式安全性較低。 先前,您建立 AzureKeyCredential 物件以驗證 OpenAIClient 的方式如下:
import { AzureKeyCredential } from "@azure/openai";
const apiKey = new AzureKeyCredential("your API key");
另一方面,您可以藉由設定 AzureOpenAI 環境變數,或在建立 AZURE_OPENAI_API_KEY 用戶端時在選項物件中設定 apiKey 字串屬性,透過 API 金鑰驗證 AzureOpenAI。
這很重要
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果你使用 API 金鑰,請將其安全地存放在 Azure Key Vault。 欲了解更多如何在應用程式中安全使用 API 金鑰的資訊,請參見 API 金鑰搭配 Azure Key Vault。
欲了解更多關於 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 版本說明文件 以了解 OpenAI Azure API 版本。 此外,deployment 並非必要屬性,但建議您進行設定。 設定 deployment 之後,其便會作為所有需要此屬性之作業的預設部署。 如果不是使用 deployment 選項建立用戶端的,則在設定 options 物件中的 model 屬性時應該加上部署名稱。 不過,audio.transcriptions.create 之類的音訊作業需要建立用戶端並將 deployment 選項設定為部署名稱。
API 差異
OpenAIClient 和 AzureOpenAI 用戶端有幾項關鍵差異:
-
OpenAIClient將操作呈現為一串方法的平面列表,例如client.getChatCompletions。AzureOpenAI會將作業分組到巢狀群組中,例如client.chat.completions.create。 -
OpenAIClient使用與 Azure OpenAI API 不同的名稱。 例如,API 使用蛇形箱,但用戶端使用駱駝殼。AzureOpenAI使用與 Azure OpenAI API 相同的名稱。
移轉範例
以下章節提供如何從 OpenAIClient 遷移到 AzureOpenAI的範例。
聊天完成
const result = await client.chat.completions.create({ messages, model: '', max_tokens: 100 });
請注意下列事項:
-
getChatCompletions方法已取代為chat.completions.create方法。 -
messages參數現在會在具有messages屬性的 options 物件中傳遞。 - 將屬性重新命名
maxTokens為 並max_tokens移除參數deploymentName。 一般來說,物件中options屬性的名稱與 Azure OpenAI API 相同。 API 使用蛇形命名法,而不是使用於OpenAIClient的駝峰式命名法。 此命名規則適用於用戶端中所有請求與回應AzureOpenAI的所有屬性。 - 如果使用了
deploymentName選項建立用戶端,則不需要deployment參數。 如果不是使用deployment選項建立用戶端的,則在設定 options 物件中的model屬性時應該加上部署名稱。
串流聊天完成
const stream = await client.chat.completions.create({ model: '', messages, max_tokens: 100, stream: true });
Azure On Your Data
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方法。 - 在建構
AzureOpenAI時必須將deployment選項設定為部署名稱,才能使用audio.transcriptions.create之類的音訊作業。 -
model屬性必須設定在 options 物件中,但其值不會用於作業中,因此您可以隨意將其設定為任何值。 -
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方法。 - 所有其他變更都與音訊謄寫範例相同。
嵌入技術
下列範例示範如何移轉 getEmbeddings 方法呼叫。
const embeddings = await client.embeddings.create({ input, model: '' });
-
getEmbeddings方法已取代為embeddings.create方法。 -
input參數現在會在具有input屬性的 options 物件中傳遞。 - 已移除
deploymentName參數。 如果使用了deploymentName選項建立用戶端,則不需要deployment參數。 如果不是使用deployment選項建立用戶端的,則在設定 options 物件中的model屬性時應該加上部署名稱。
映射產生
下列範例示範如何移轉 getImages 方法呼叫。
const results = await client.images.generate({ prompt, model: '', n, size });
-
getImages方法已取代為images.generate方法。 -
prompt參數現在會在具有prompt屬性的 options 物件中傳遞。 - 已移除
deploymentName參數。 如果使用了deploymentName選項建立用戶端,則不需要deployment參數。 如果不是使用deployment選項建立用戶端的,則在設定 options 物件中的model屬性時應該加上部署名稱。
內容過濾器
內容篩選結果是 OpenAIClient 中聊天完成回應類型的一部分。 不過,AzureOpenAI 未直接對等於 contentFilterResults 介面中的 ChatCompletion.Choice 屬性。 內容過濾結果可透過匯入 "@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 types 章節。
比較類型
下表探討 @azure/openai 的幾個類型名稱,並顯示它們最近的 openai 對應物。 名稱差異說明了上述的數個變更。 下表提供的是概觀,下列各節會提供更多詳細資料和程式碼範例。
| 舊類型名稱 | 最接近的新類型 | 符號類型 | 變更描述 |
|---|---|---|---|
OpenAIClient |
AzureOpenAI |
Class | 這個類別會取代以前的類別,而且沒有與它一樣的方法。 請參閱以下 AzureOpenAI 上的區段。 |
AudioResult |
Transcription/Transcription |
介面 | 根據呼叫作業而定,這兩個介面會取代以前那個介面 |
AudioResultFormat |
response_format 屬性的內嵌聯集類型 |
Alias | 不存在 |
AudioResultSimpleJson |
Transcription/Transcription |
介面 | 根據呼叫作業而定,這兩個介面會取代以前那個介面 |
AudioResultVerboseJson |
不適用 | 介面 | |
AudioSegment |
不適用 | 介面 | |
AudioTranscriptionTask |
不適用 | Alias | |
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 |
不適用 | Class | 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 |
不適用 | Alias | |
ChatTokenLogProbabilityInfo |
TopLogprob |
介面 | |
ChatTokenLogProbabilityResult |
ChatCompletionTokenLogprob |
介面 | |
Choice |
Choice |
介面 | |
Completions |
Completion |
介面 | |
CompletionsFinishReason |
不適用 | Alias | |
CompletionsLogProbabilityModel |
Logprobs |
介面 | |
CompletionsUsage |
CompletionUsage |
介面 | |
EmbeddingItem |
Embedding |
介面 | |
Embeddings |
CreateEmbeddingResponse |
介面 | |
EmbeddingsUsage |
CreateEmbeddingResponse.Usage |
介面 | |
EventStream |
Stream |
介面 | |
FunctionCall |
FunctionCall |
介面 | |
FunctionCallPreset |
不適用 | Alias | |
FunctionDefinition |
Function |
介面 | |
FunctionName |
不適用 | Alias | |
GetAudioTranscriptionOptions |
TranscriptionCreateParams |
介面 | |
GetAudioTranslationOptions |
TranslationCreateParams |
介面 | |
GetChatCompletionsOptions |
ChatCompletionCreateParamsNonStreaming 和 ChatCompletionCreateParamsStreaming |
介面 | |
GetCompletionsOptions |
CompletionCreateParams |
介面 | |
GetEmbeddingsOptions |
EmbeddingCreateParams |
介面 | |
GetImagesOptions |
ImageGenerateParams |
介面 | |
ImageGenerationData |
Image |
介面 | |
ImageGenerationQuality |
不適用 | Alias | |
ImageGenerationResponseFormat |
不適用 | Alias | |
ImageGenerations |
ImagesResponse |
介面 | |
ImageGenerationStyle |
不適用 | Alias | |
ImageSize |
不適用 | Alias | |
MaxTokensFinishDetails |
不適用 | 介面 | |
OpenAIClientOptions |
AzureClientOptions |
介面 | |
OpenAIError |
OpenAIError |
介面 | |
OpenAIKeyCredential |
不適用 | Class | |
StopFinishDetails |
不適用 | 介面 |
Azure 類型
AzureOpenAI 連接 OpenAI Azure,並能呼叫服務中所有可用的操作。 然而,請求與回應的類型繼承自 OpenAI,尚未更新以反映 Azure OpenAI 服務獨享的額外功能。 TypeScript 使用者需從 "@azure/openai/types" 匯入 @azure/openai@2.0.0-beta.1,這將將Azure專屬定義合併到現有型別中。
遷移範例章節中的例子說明了如何這樣做。