JavaScript 用 Azure OpenAI クライアント ライブラリ - バージョン 1.0.0-beta.12

JavaScript 用 Azure OpenAI クライアント ライブラリは、慣用インターフェイスと Azure SDK エコシステムの残りの部分との豊富な統合を提供する OpenAI の REST API の適応です。 Azure OpenAI リソース または Azure 以外の OpenAI 推論エンドポイントに接続できるため、Azure OpenAI 以外の開発にも適しています。

Azure OpenAI 用のクライアント ライブラリを使用して、次の手順を実行します。

Azure OpenAI は、開発者が Azure リソース上の OpenAI モデルからコンテンツをデプロイ、調整、生成できるようにするマネージド サービスです。

次の例を確認します。

主要リンク:

はじめに

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

const client = new OpenAIClient(
  "https://<resource name>.openai.azure.com/", 
  new AzureKeyCredential("<Azure API key>")
);
const { id, created, choices, usage } = await client.getCompletions("<deployment ID>", ["YOUR PROMPT HERE"]);

現在サポートされている環境

前提条件

Azure OpenAI リソースを使用する場合は、 Azure サブスクリプションAzure OpenAI アクセス権が必要です。 これにより、Azure OpenAI リソースを作成し、接続 URL と API キーの両方を取得できます。 詳細については、「 クイック スタート: Azure OpenAI Service を使用してテキストの生成を開始する」を参照してください。

Azure OpenAI JS クライアント ライブラリを使用して Azure OpenAI 以外に接続する場合は、 の開発者アカウント https://platform.openai.com/から API キーが必要です。

@azure/openai パッケージのインストール

を使用して、JavaScript 用の Azure OpenAI クライアント ライブラリを npmインストールします。

npm install @azure/openai

OpenAIClient を作成して認証する

Azure OpenAI で使用するクライアントを構成するには、Azure OpenAI リソースへの有効なエンドポイント URI と、Azure OpenAI リソースの使用が許可されている対応するキー資格情報、トークン資格情報、または Azure ID 資格情報を指定します。 代わりに、OpenAI のサービスに接続するようにクライアントを構成するには、OpenAI の開発者ポータルから API キーを指定します。

Azure からの API キーの使用

Azure Portal を使用して OpenAI リソースを参照し、API キーを取得するか、次の Azure CLI スニペットを使用します。

メモ: API キーは、"サブスクリプション キー" または "サブスクリプション API キー" と呼ばれる場合があります。

az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>

API キーとエンドポイントを取得したら、 クラスを AzureKeyCredential 使用して、次のようにクライアントを認証できます。

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

const client = new OpenAIClient("<endpoint>", new AzureKeyCredential("<API key>"));

Azure Active Directory 資格情報の使用

クライアント API キー認証はほとんどの例で使用されますが、Azure Id ライブラリを使用して Azure Active Directory で認証することもできます。 下に示した DefaultAzureCredential プロバイダーか、Azure SDK で提供されている他の資格情報プロバイダーを使用するには、@azure/identity パッケージをインストールしてください。

npm install @azure/identity

また、 新しい AAD アプリケーションを登録 し、サービス プリンシパルにロールを "Cognitive Services User" 割り当てることで OpenAI へのアクセス権を付与する必要があります (注: などの "Owner" 他のロールは必要なアクセス許可を付与せず、例とサンプル コードを実行するだけで "Cognitive Services User" 十分です)。

AAD アプリケーションのクライアント ID、テナント ID、およびクライアント シークレットの値を、環境変数 AZURE_CLIENT_IDAZURE_TENANT_ID、、AZURE_CLIENT_SECRET、 として設定します。

const { OpenAIClient } = require("@azure/openai");
const { DefaultAzureCredential } = require("@azure/identity");

const client = new OpenAIClient("<endpoint>", new DefaultAzureCredential());

OpenAI からの API キーの使用

代わりに、OpenAI のサービスに接続するようにクライアントを構成するには、OpenAI の開発者ポータルから API キーを指定します。 API キーを取得したら、 クラスを OpenAIKeyCredential 使用して、次のようにクライアントを認証できます。

const { OpenAIClient, OpenAIKeyCredential } = require("@azure/openai");

const client = new OpenAIClient(new OpenAIKeyCredential("<API key>"));

主要な概念

理解メイン概念は Completions です。 簡単に説明すると、入力候補はテキスト プロンプトの形式で機能を提供します。この機能は、特定の モデルを使用してコンテキストとパターンの照合を試み、出力テキストを提供します。 次のコード スニペットは、大まかな概要を示しています。

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

async function main(){
  const client = new OpenAIClient(
  "https://your-azure-openai-resource.com/",
  new AzureKeyCredential("your-azure-openai-resource-api-key"));

  const { choices } = await client.getCompletions(
    "text-davinci-003", // assumes a matching model deployment or model name
    ["Hello, world!"]);

  for (const choice of choices) {
    console.log(choice.text);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

サンプルを使用して、さまざまな API について理解することができます。

Chatbot 応答を生成する

この例では、DefaultAzureCredential を使用して認証を行い、入力チャットの質問とメッセージに対するチャット応答を生成します。

const { OpenAIClient } = require("@azure/openai");
const { DefaultAzureCredential } = require("@azure/identity");

async function main(){
  const endpoint = "https://myaccount.openai.azure.com/";
  const client = new OpenAIClient(endpoint, new DefaultAzureCredential());

  const deploymentId = "gpt-35-turbo";

  const messages = [
    { role: "system", content: "You are a helpful assistant. You will talk like a pirate." },
    { role: "user", content: "Can you help me?" },
    { role: "assistant", content: "Arrrr! Of course, me hearty! What can I do for ye?" },
    { role: "user", content: "What's the best way to train a parrot?" },
  ];

  console.log(`Messages: ${messages.map((m) => m.content).join("\n")}`);

  const events = await client.streamChatCompletions(deploymentId, messages, { maxTokens: 128 });
  for await (const event of events) {
    for (const choice of event.choices) {
      const delta = choice.delta?.content;
      if (delta !== undefined) {
        console.log(`Chatbot: ${delta}`);
      }
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

サブスクリプション キーを使用して複数の入力候補を生成する

この例では、Azure サブスクリプション キーを使用して入力プロンプトに対するテキスト応答を生成します

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

async function main(){
  // Replace with your Azure OpenAI key
  const key = "YOUR_AZURE_OPENAI_KEY";
  const endpoint = "https://myaccount.openai.azure.com/";
  const client = new OpenAIClient(endpoint, new AzureKeyCredential(key));

  const examplePrompts = [
    "How are you today?",
    "What is Azure OpenAI?",
    "Why do children love dinosaurs?",
    "Generate a proof of Euler's identity",
    "Describe in single words only the good things that come into your mind about your mother.",
  ];

  const deploymentName = "text-davinci-003";

  let promptIndex = 0;
  const { choices } = await client.getCompletions(deploymentName, examplePrompts);
  for (const choice of choices) {
    const completion = choice.text;
    console.log(`Input: ${examplePrompts[promptIndex++]}`);
    console.log(`Chatbot: ${completion}`);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

入力候補を含むテキストの集計

次の使用例は、指定された入力プロンプトの概要を生成します。

const { OpenAIClient } = require("@azure/openai");
const { DefaultAzureCredential } = require("@azure/identity")

async function main(){
  const endpoint = "https://myaccount.openai.azure.com/";
  const client = new OpenAIClient(endpoint, new DefaultAzureCredential());

  const textToSummarize = `
    Two independent experiments reported their results this morning at CERN, Europe's high-energy physics laboratory near Geneva in Switzerland. Both show convincing evidence of a new boson particle weighing around 125 gigaelectronvolts, which so far fits predictions of the Higgs previously made by theoretical physicists.

    ""As a layman I would say: 'I think we have it'. Would you agree?"" Rolf-Dieter Heuer, CERN's director-general, asked the packed auditorium. The physicists assembled there burst into applause.
  :`;

  const summarizationPrompt = [`
    Summarize the following text.

    Text:
    """"""
    ${textToSummarize}
    """"""

    Summary:
  `];

  console.log(`Input: ${summarizationPrompt}`);

  const deploymentName = "text-davinci-003";

  const { choices } = await client.getCompletions(deploymentName, summarizationPrompt, {
    maxTokens: 64
  });
  const completion = choices[0].text;
  console.log(`Summarization: ${completion}`);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

チャット ツールを使用する

ツールは、アシスタントがチャット入力候補要求を満たす過程で定義された関数やその他の機能を呼び出せるようにすることで、チャットの完了を拡張します。 チャット ツールを使用するには、まず関数ツールを定義します。

const getCurrentWeather = {
    name: "get_current_weather",
    description: "Get the current weather in a given location",
    parameters: {
      type: "object",
      properties: {
        location: {
          type: "string",
          description: "The city and state, e.g. San Francisco, CA",
        },
        unit: {
          type: "string",
          enum: ["celsius", "fahrenheit"],
        },
      },
      required: ["location"],
    },
  };

ツールを定義した状態で、チャット入力候補要求のオプションにその新しい定義を含めます。

const deploymentName = "gpt-35-turbo-1106";
const messages = [{ role: "user", content: "What is the weather like in Boston?" }];
const options = {
    tools: [
      {
        type: "function",
        function: getCurrentWeather,
      },
    ],
  };
const events = client.getChatCompletions(deploymentId, messages, options);

アシスタントが 1 つ以上のツールを使用する必要があると判断した場合、応答メッセージには、後続の要求で "ツール メッセージ" を介して解決する必要がある 1 つ以上の "ツール呼び出し" が含まれます。 この新しい要求メッセージへのツール呼び出しの解決は、チャット完了の一種の "コールバック" と考えることができます。

// Purely for convenience and clarity, this function handles tool call responses.
function applyToolCall({ function: call, id }) {
    if (call.name === "get_current_weather") {
      const { location, unit } = JSON.parse(call.arguments);
      // In a real application, this would be a call to a weather API with location and unit parameters
      return {
        role: "tool",
        content: `The weather in ${location} is 72 degrees ${unit} and sunny.`,
        toolCallId: id,
      }
    }
    throw new Error(`Unknown tool call: ${call.name}`);
}

要求の継続を許可するツール呼び出し解決をアシスタントに提供するには、以前のすべての履歴コンテキスト (元のシステムメッセージとユーザー メッセージ、ツール呼び出しを含むアシスタントからの応答、および後続の要求を行うときに各ツールを解決したツール メッセージ) を提供します。

const choice = result.choices[0];
const responseMessage = choice.message;
if (responseMessage?.role === "assistant") {
  const requestedToolCalls = responseMessage?.toolCalls;
  if (requestedToolCalls?.length) {
    const toolCallResolutionMessages = [
      ...messages,
      responseMessage,
      ...requestedToolCalls.map(applyToolCall),
    ];
    const result = await client.getChatCompletions(deploymentName, toolCallResolutionMessages);
    // continue handling the response as normal
  }
}

DALL-Eイメージ生成モデルを使用してイメージを生成する

この例では、指定された入力プロンプトからバッチ イメージを生成します。

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

async function main() {
  const endpoint = "https://myaccount.openai.azure.com/";
  const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));

  const deploymentName = "dalle-3";
  const prompt = "a monkey eating a banana";
  const size = "1024x1024";
  const n = 1;
  
  const results = await client.getImages(deploymentName, prompt, { n, size });

  for (const image of results.data) {
    console.log(`Image generation result URL: ${image.url}`);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

ビジネス データの分析

この例では、ビジネス データに関する入力チャットの質問に対するチャット応答を生成します。 ビジネス データは、Azure Cognitive Search インデックスを介して提供されます。 Azure Cognitive Search インデックスをデータ ソースとして設定する方法の詳細については、「クイック スタート: 独自のデータを使用して Azure OpenAI モデルとチャットする」を参照してください。

const { OpenAIClient } = require("@azure/openai");
const { DefaultAzureCredential } = require("@azure/identity");

async function main(){
  const endpoint = "https://myaccount.openai.azure.com/";
  const client = new OpenAIClient(endpoint, new DefaultAzureCredential());

  const deploymentId = "gpt-35-turbo";

  const messages = [
    { role: "user", content: "What's the most common customer feedback about our product?" },
  ];

  console.log(`Messages: ${messages.map((m) => m.content).join("\n")}`);

  const events = await client.streamChatCompletions(deploymentId, messages, { 
    maxTokens: 128,
    azureExtensionOptions: {
      extensions: [
        {
          type: "AzureCognitiveSearch",
          endpoint: "<Azure Cognitive Search endpoint>",
          key: "<Azure Cognitive Search admin key>",
          indexName: "<Azure Cognitive Search index name>",
        },
      ],
    },
  });
  for await (const event of events) {
    for (const choice of event.choices) {
      const delta = choice.delta?.content;
      if (delta !== undefined) {
        console.log(`Chatbot: ${delta}`);
      }
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

オーディオ ファイルの文字起こしと翻訳

Azure OpenAI の音声テキスト変換機能と翻訳機能を使用して、さまざまなオーディオ ファイル形式を文字起こしおよび翻訳できます。 次の例は、 メソッドを使用して、オーディオが getAudioTranscription 含まれる言語にオーディオを文字起こしする方法を示しています。 また、 メソッドを使用して getAudioTranslation 、オーディオを英語に翻訳および文字起こしすることもできます。

オーディオ ファイルは、NodeJS ファイル システム API を使用してメモリに読み込むことができます。 ブラウザーでは、API を使用してファイルを FileReader 読み込み、インスタンス メソッドの arrayBuffer 出力を メソッドに getAudioTranscription 渡すことができます。

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");
const fs = require("fs/promises");

async function main() {
  console.log("== Transcribe Audio Sample ==");

  const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
  const deploymentName = "whisper";
  const audio = await fs.readFile("< path to an audio file >");
  const result = await client.getAudioTranscription(deploymentName, audio);

  console.log(`Transcription: ${result.text}`);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

gpt-4-vision-preview を使用して画像とチャットする

この gpt-4-vision-preview モデルを使用すると、チャット入力候補への入力コンポーネントとして画像を使用できます。

これを行うには、チャット入力候補要求のユーザー メッセージに個別のコンテンツ 項目を指定します。

const url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
const deploymentName = "gpt-4-1106-preview";
const messages: ChatRequestMessage[] = [{role: "user", content: [{
  type: "image_url",
  imageUrl: {
    url,
    detail: "auto"
  }
}]}];

チャットの完了は通常どおりに進みますが、モデルでは、 の代わりにfinish_reasonより有益なfinish_details情報が報告される場合があります。

const result = await client.getChatCompletions(deploymentName, messages);
console.log(`Chatbot: ${result.choices[0].message?.content}`);

トラブルシューティング

ログ記録

ログの記録を有効にすると、エラーに関する有用な情報を明らかにするのに役立つ場合があります。 HTTP 要求と応答のログを表示するには、環境変数 AZURE_LOG_LEVELinfo に設定します。 または、@azure/loggersetLogLevel を呼び出して、実行時にログ記録を有効にすることもできます。

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

ログを有効にする方法の詳細については、@azure/logger パッケージに関するドキュメントを参照してください。