キーレス認証方法
JavaScript 用の OpenAI をAzureするキーレス認証では、API キーをハードコーディングする代わりに、マネージド ID (Azure ホステッド コード用) または開発者Microsoft Entra ID ID (ローカル開発用) を使用して認証します。 これは、DefaultAzureCredential ライブラリの ManagedIdentityCredential クラスまたは @azure/identity クラスを使用して行われます。これにより、Azure サービスへの認証に必要なベアラー トークンを安全に取得できます。 実際の動作を次に示します。
- Azure環境を設定します。 Azure OpenAI リソースが作成され、開発者 ID (ローカル開発用) またはマネージド ID (Azure ホスト型コードの場合) に、リソースに対する Azure OpenAI RBAC ロール (たとえば、Cognitive Services OpenAI ユーザー) が付与されていることを確認します。
- 資格情報を初期化する。 トークンを自動的に取得するには、
DefaultAzureCredentialクラスまたはManagedIdentityCredentialから@azure/identityクラスを使用します。 - クライアント インスタンスを作成します。
AzureOpenAI、openai、endpoint、およびdeploymentによって返されるトークン プロバイダーを使用して、apiVersionパッケージからgetBearerTokenProviderをインスタンス化します。 - API 呼び出しを行います。 クライアント (
client.chat.completions.createなど) を使用して、コード内のシークレットを処理せずに、Azure OpenAI と安全に対話します。
次の例では、4 つの手順すべてを一緒に示します。
import { AzureOpenAI } from 'openai';
import { getBearerTokenProvider, DefaultAzureCredential } from '@azure/identity';
// Set AZURE_OPENAI_ENDPOINT to the endpoint of your Azure OpenAI resource,
// for example: https://YOUR-RESOURCE-NAME.openai.azure.com/
const endpoint = process.env.AZURE_OPENAI_ENDPOINT;
if (!endpoint) {
throw new Error("Set the AZURE_OPENAI_ENDPOINT environment variable to your Azure OpenAI resource endpoint.");
}
const deployment = '<your Azure OpenAI deployment name>';
const apiVersion = '2024-10-21';
const credential = new DefaultAzureCredential();
const scope = 'https://cognitiveservices.azure.com/.default';
const azureADTokenProvider = getBearerTokenProvider(credential, scope);
// Create an Azure OpenAI client.
const client = new AzureOpenAI({ azureADTokenProvider, endpoint, deployment, apiVersion });
// Call the chat completions API. In the Azure OpenAI client, `model` is the
// name of the deployment, not the underlying model name.
const result = await client.chat.completions.create({
model: deployment,
messages: [{ role: 'user', content: 'Say hello!' }],
});
console.log(result.choices[0].message?.content);
ローカル開発とAzureホスト実行
DefaultAzureCredential は、ローカル開発とAzureホスト環境の両方で動作するように設計されています。 この資格情報は、いずれかが成功するまで、一連の資格情報の種類を順に試します。
-
ローカル開発:
AzureCliCredential(az loginの後)、AzurePowerShellCredential、およびサポートされている IDE の資格情報などの資格情報を通じて、サインイン中の開発者 ID を取得します。 開発者 ID には、ターゲット リソースに対する Azure OpenAI RBAC ロールが付与されている必要があります。 -
Azure ホスト環境: Azure App Service、Azure Functions、Azure Container Apps、Azure 仮想マシンなどのリソースで同じコードが実行される場合、
DefaultAzureCredentialは、ManagedIdentityCredentialを使用して、そのリソースに割り当てられているマネージド ID のトークンを取得します。 マネージド ID には、ターゲット リソースに対する Azure OpenAI RBAC ロールが付与されている必要があります。
ユーザー割り当てマネージド ID の場合は、 AZURE_CLIENT_ID 環境変数 (または資格情報オプションで managedIdentityClientId を渡す) を、そのユーザー割り当て ID のクライアント ID に設定します。 システム割り当てマネージド ID には、クライアント ID は必要ありません。Azureホストされているリソースでは、パラメーターなしの new DefaultAzureCredential() で十分です。