クイックスタート: Azure OpenAI Service で GPT-35-Turbo と GPT-4 を使い始める

この記事を使用して、Azure OpenAI の使用を開始します。

前提条件

  • Azure サブスクリプション。無料で作成できます

  • 目的の Azure サブスクリプション内の Azure OpenAI に付与されたアクセス権。

    現時点では、このサービスへのアクセスは申請によってのみ許可されます。 Azure OpenAI へのアクセスを申請するには、https://aka.ms/oai/access のフォームに入力してください。 問題がある場合は、このリポジトリで問題をオープンしてお問い合わせください。

  • gpt-35-turbo または gpt-4 モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。

ヒント

統合された新しい Azure AI Studio (プレビュー) をお試しください。複数の Azure AI サービスの機能が統合されています。

Azure OpenAI Studio に移動する

https://oai.azure.com/ の Azure OpenAI Studio にアクセスし、OpenAI リソースにアクセスできる資格情報を使用してサインインします。 サインイン ワークフローの途中または後で、適切なディレクトリ、Azure サブスクリプション、Azure OpenAI リソースを選択します。

Azure OpenAI Studio のランディング ページで、[Chat playground] (チャット プレイグラウンド) を選びます。

Screenshot of the Azure OpenAI Studio landing page with Chat playground highlighted.

プレイグラウンド

Azure OpenAI Studio Chat のプレイグラウンドを通して、ノーコードのアプローチで OpenAI の機能を探索し始めましょう。 このページから、素早く機能を反復し、実験することができます。

Screenshot of the Chat playground page.

アシスタントのセットアップ

[Assistant setup] (アシスタントのセットアップ) ドロップダウンを使用して、事前に読み込まれたシステム メッセージの例をいくつか選択して開始できます。

システム メッセージ は、モデルがどのように振る舞うべきか、また、応答を生成するときに参照すべきコンテキストについての指示を与えます。 アシスタントのパーソナリティを記述したり、答えるべきことと答えるべきでないことを指示したり、応答のフォーマットを指示したりすることができます。

[Add few-shot examples] (少数ショットの例を追加する) では、コンテキスト内学習のためにモデルで使用される会話の例を指定できます。

Chat playground を使用している間、いつでも コードを表示 を選択し、現在のチャットセッションと設定の選択に基づいて、Python、curl、json のコードサンプルを見ることができます。 そして、このコードを使用して、現在プレイグラウンドで実行しているのと同じタスクを完了するアプリケーションを書くことができます。

チャット セッション

[送信] ボタンを選択すると、入力したテキストが入力候補 API に送信され、結果がテキスト ボックスに返されます。

現在の会話履歴を削除するには、[Clear chat] (チャットをクリアする) ボタンを選択します。

設定

名前 説明
デプロイメント 特定のモデルに関連付けられているデプロイ名。
気温 ランダム性を制御します。 温度を下げることは、モデルが生成する反復的で決定的な応答が増えることを意味します。 温度を上げると、予期しない応答や独創的な応答が増えます。 温度または Top P を調整してみてください。ただし、両方を調整しないでください。
最大長 (トークン) モデルの応答あたりのトークン数に制限を設定します。 API では、プロンプト (システム メッセージ、例、メッセージ履歴、ユーザー クエリを含む) とモデルの応答の間で共有される最大 4096 個のトークンがサポートされます。 1 つのトークンは一般的な英語テキストの約 4 文字です。
上位の確率 (Top P) 温度と同様に、これはランダム性を制御しますが、使用する方法が異なります。 Top P を下げると、モデルのトークンの選択が、可能性が高いトークンに絞り込まれます。 Top P を上げると、モデルは可能性の高いトークンと低いトークンの両方から選択できます。 温度または Top P を調整してみてください。ただし、両方を調整しないでください。
複数ターン会話 新しい API 要求ごとに含める過去のメッセージの数を選択します。 これは、新しいユーザー クエリのモデル コンテキストを提供するのに役立ちます。 この数を 10 に設定すると、5 つのユーザー クエリと 5 つのシステム応答が得られます。
停止シーケンス 停止シーケンスでは、モデルは目的のポイントで応答を終了します。 モデル応答は、指定されたシーケンスの前で終了するため、停止シーケンス テキストは含まれません。 GPT-35-Turbo の場合、<|im_end|> を使用すると、モデル応答でフォローアップ ユーザー クエリが生成されません。 最大 4 つの停止シーケンスを組み込むことができます。

パネルを表示する

デフォルトではアシスタントセットアップ、チャットセッション、設定の 3 つのパネルがあります。 パネルの表示 ではパネルの追加、削除、並べ替えができます。 もしパネルを閉じてしまい、元に戻したくなった場合は、パネルを表示 を使って失ったパネルを復元してください。

チャット セッションを開始する

  1. [Assistant setup] (アシスタントのセットアップ) ドロップダウンで、[Xbox customer support agent] (Xbox カスタマー サポート エージェント) を選択します

  2. システム メッセージを更新するかどうかをたずねるプロンプトが表示されたら、[続行] を選択します。

  3. [チャット セッション] ペインで、"I'm interested in buying a new Xbox (新しい Xbox の購入に関心がある)" という質問を入力し、[送信] を選択します。

  4. 次のような応答が返されます。

    Screenshot of a first question and answer in playground.

  5. "どのモデルが 4K をサポートしていますか?" など、フォローアップの質問を入力します

    Screenshot of follow-up question and answer in playground.

  6. 基本的な会話が行われたので、Assistant setup (アシスタントのセットアップ)コードの表示 を選択すると、これまでの会話全体の背後にあるコードが再生されます。

#Note: The openai-python library support for Azure OpenAI is in preview.
import os
import openai
openai.api_type = "azure"
openai.api_base = "https://docs-test-001.openai.azure.com/"
openai.api_version = "2023-05-15"
openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.ChatCompletion.create(
  engine="gpt-35-turbo", # replace this value with the deployment name you chose when you deployed the associated model.
  messages = [{"role":"system","content":"You are an Xbox customer support agent whose primary goal is to help users with issues they are experiencing with their Xbox devices. You are friendly and concise. You only provide factual answers to queries, and do not provide answers that are not related to Xbox."},{"role":"user","content":"How much is a PS5?"},{"role":"assistant","content":"I apologize, but I do not have information about the prices of other gaming devices such as the PS5. My primary focus is to assist with issues regarding Xbox devices. Is there a specific issue you are having with your Xbox device that I may be able to help with?"},{"role":"user","content":"I am interested in buying an Xbox?"},{"role":"assistant","content":"Great! There are several Xbox models available in the market, including the Xbox Series X, Xbox Series S, and Xbox One. The Xbox Series X is the latest and most powerful console, while the Xbox Series S is a more affordable option that still offers great performance. The Xbox One is the previous generation console, but it still has a large library of games available to play.\n\nBefore purchasing an Xbox, you may want to consider factors such as your budget, the types of games you want to play, and whether you want to play games in 4K resolution. Once you have decided on a console, you can purchase it from a retailer or directly from the Xbox website. Let me know if you have any other questions or concerns!"},{"role":"user","content":"Which models are 4K?"},{"role":"assistant","content":"Both the Xbox Series X and Xbox One X support 4K resolution gaming. The Xbox Series S, on the other hand, supports up to 1440p resolution gaming, but it can upscale games to 4K. It's worth noting that in order to take advantage of 4K gaming, you'll need a 4K TV or monitor that supports HDR (High Dynamic Range) and HDMI 2.0 or higher."}],
  temperature=0,
  max_tokens=350,
  top_p=0.95,
  frequency_penalty=0,
  presence_penalty=0,
  stop=None)

プロンプト構造の概要

[コードの表示] からサンプルを調べると、一般的な GPT 完了呼び出しの一部ではなかった一意のトークンがいくつか見つかります。 GPT-35-Turbo は、プロンプトのさまざまな部分を示すために特別なトークンを使用するようにトレーニングされています。 コンテンツは、<|im_start|> トークンと <|im_end|> トークンの間でモデルに提供されます。 プロンプトは、モデルのコンテキストまたは手順を含めることでモデルの準備に使用できるシステム メッセージから始まります。 その後、プロンプトには、ユーザーとアシスタントの間の一連のメッセージが含まれます。

プロンプトに対するアシスタントの応答が <|im_start|>assistant トークンの下に返され、アシスタントが応答を完了したことを示す <|im_end|> で終わります。 また、[Show raw syntax] (未加工の構文を表示する) トグル ボタンを使用すると、チャット セッション パネル内にこれらのトークンを表示することもできます。

GPT-35-Turbo および GPT-4 攻略ガイドでは、新しいプロンプト構造と gpt-35-turbo モデルを効果的に使用する方法を詳しく紹介します。

モデルをデプロイする

Azure OpenAI Studio でのエクスペリエンスに納得していただけたら、[デプロイ先] ボタンを選び、Studio から直接 Web アプリをデプロイできます。

A screenshot showing the model deployment button in Azure OpenAI Studio.

これにより、スタンドアロン Web アプリにデプロイするか、Copilot Studio (プレビュー) のコパイロットにデプロイするか (モデルで独自のデータを使用している場合) を選択するオプションが表示されます。

たとえば、Web アプリをデプロイすることを選択した場合は、次のようになります:

初めて Web アプリをデプロイする場合は、[新しい Web アプリを作成する] を選ぶ必要があります。 アプリの URL の一部となるアプリ名を決めます。 たとえば、「 https://<appname>.azurewebsites.net 」のように入力します。

発行されたアプリのサブスクリプション、リソース グループ、場所、価格プランを選びます。 既存のアプリを更新するには、[Publish to an existing web app](既存の Web アプリに発行する) を選び、ドロップダウン メニューから従来のアプリの名前を選びます。

Web アプリをデプロイする場合は、その使用に関する重要な考慮事項を参照してください。

リソースをクリーンアップする

Chat playground のテストが完了し、OpenAI リソースをクリーン アップして削除したい場合は、リソースまたはリソース グループを削除できます。 リソース グループを削除すると、それに関連付けられている他のリソースも削除されます。

次のステップ

ソース コード | パッケージ (NuGet) | サンプル| 取得拡張生成 (RAG) エンタープライズ チャット テンプレート |

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します
  • 目的の Azure サブスクリプション内の Azure OpenAI Service へのアクセスの許可。 現時点では、このサービスへのアクセスは申請によってのみ許可されます。 Azure OpenAI Service へのアクセスを申請するには、https://aka.ms/oai/access のフォームに入力してください。
  • .NET 7 SDK
  • gpt-35-turbo または gpt-4 モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。

設定

新しい .NET Core アプリを作成する

コンソール ウィンドウ (cmd、PowerShell、Bash など) で、dotnet new コマンドを使用し、azure-openai-quickstart という名前で新しいコンソール アプリを作成します。 このコマンドにより、次の C# ソース ファイルを 1 つ使用する単純な "Hello World" プロジェクトが作成されます: Program.cs

dotnet new console -n azure-openai-quickstart

新しく作成されたアプリ フォルダーにディレクトリを変更します。 次を使用してアプリケーションをビルドできます。

dotnet build

ビルドの出力に警告やエラーが含まれないようにする必要があります。

...
Build succeeded.
 0 Warning(s)
 0 Error(s)
...

以下を使って、OpenAI .NET クライアント ライブラリをインストールします。

dotnet add package Azure.AI.OpenAI --prerelease

キーとエンドポイントを取得する

Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントキーが必要です。

変数名
ENDPOINT この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 Azure OpenAI Studio>[プレイグラウンド]>[コード ビュー] で値を確認することもできます。 エンドポイントの例: https://docs-test-001.openai.azure.com/
API-KEY この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。

Azure portal でリソースに移動します。 [エンドポイントとキー][リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1 または KEY2 を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境変数

キーとエンドポイントの永続的な環境変数を作成して割り当てます。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

サンプル アプリケーションを作成する

プロジェクト ディレクトリから program.cs ファイルを開いて、以下のコードに置き換えます。

応答ストリーミングなし

using Azure;
using Azure.AI.OpenAI;
using static System.Environment;

string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
string key = GetEnvironmentVariable("AZURE_OPENAI_API_KEY");

OpenAIClient client = new(new Uri(endpoint), new AzureKeyCredential(key));

var chatCompletionsOptions = new ChatCompletionsOptions()
{
    DeploymentName = "gpt-35-turbo", //This must match the custom deployment name you chose for your model
    Messages =
    {
        new ChatRequestSystemMessage("You are a helpful assistant."),
        new ChatRequestUserMessage("Does Azure OpenAI support customer managed keys?"),
        new ChatRequestAssistantMessage("Yes, customer managed keys are supported by Azure OpenAI."),
        new ChatRequestUserMessage("Do other Azure AI services support this too?"),
    },
    MaxTokens = 100
};

Response<ChatCompletions> response = client.GetChatCompletions(chatCompletionsOptions);

Console.WriteLine(response.Value.Choices[0].Message.Content);

Console.WriteLine();

重要

運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 資格情報のセキュリティについて詳しくは、Azure AI サービスのセキュリティに関する記事をご覧ください。

dotnet run program.cs

出力

Yes, many of the Azure AI services support customer managed keys. Some examples include Text Analytics, Speech Services, and Translator. However, it's important to note that not all services support customer managed keys, so it's best to check the documentation for each individual service to see if it is supported.

これは、結果を出力する前に、モデルが応答全体を生成するまで待機します。 または、応答を非同期的にストリーミングして結果を出力する場合は、 program.cs の内容を次の例のコードに置き換えることができます。

ストリーミングを使用した非同期

using Azure;
using Azure.AI.OpenAI;
using static System.Environment;

string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
string key = GetEnvironmentVariable("AZURE_OPENAI_API_KEY");

OpenAIClient client = new(new Uri(endpoint), new AzureKeyCredential(key));

var chatCompletionsOptions = new ChatCompletionsOptions()
{
    DeploymentName= "gpt-35-turbo", //This must match the custom deployment name you chose for your model
    Messages =
    {
        new ChatRequestSystemMessage("You are a helpful assistant."),
        new ChatRequestUserMessage("Does Azure OpenAI support customer managed keys?"),
        new ChatRequestAssistantMessage("Yes, customer managed keys are supported by Azure OpenAI."),
        new ChatRequestUserMessage("Do other Azure AI services support this too?"),
    },
    MaxTokens = 100
};

await foreach (StreamingChatCompletionsUpdate chatUpdate in client.GetChatCompletionsStreaming(chatCompletionsOptions))
{
    if (chatUpdate.Role.HasValue)
    {
        Console.Write($"{chatUpdate.Role.Value.ToString().ToUpperInvariant()}: ");
    }
    if (!string.IsNullOrEmpty(chatUpdate.ContentUpdate))
    {
        Console.Write(chatUpdate.ContentUpdate);
    }
}

リソースをクリーンアップする

Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。

次のステップ

ソース コード | パッケージ (Go)| サンプル

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します
  • 目的の Azure サブスクリプション内の Azure OpenAI Service へのアクセスの許可。 現時点では、このサービスへのアクセスは申請によってのみ許可されます。 Azure OpenAI Service へのアクセスを申請するには、https://aka.ms/oai/access のフォームに入力してください。
  • Go 1.21.0 以降がローカルにインストールされていること。
  • gpt-35-turbo モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。

設定

キーとエンドポイントを取得する

Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントキーが必要です。

変数名
ENDPOINT この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 Azure OpenAI Studio>[プレイグラウンド]>[コード ビュー] で値を確認することもできます。 エンドポイントの例: https://docs-test-001.openai.azure.com/
API-KEY この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。

Azure portal でリソースに移動します。 [エンドポイントとキー][リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1 または KEY2 を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境変数

キーとエンドポイントの永続的な環境変数を作成して割り当てます。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

サンプル アプリケーションを作成する

chat_completions.go という名前の新しいファイルを作成します。 次のコードを chat_completions.go ファイルにコピーします。

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
)

func main() {
	azureOpenAIKey := os.Getenv("AZURE_OPENAI_API_KEY")
    //modelDeploymentID = deployment name, if model name and deployment name do not match change this value to name chosen when you deployed the model.
	modelDeploymentID := "gpt-35-turbo" 

	// Ex: "https://<your-azure-openai-host>.openai.azure.com"
	azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")

	if azureOpenAIKey == "" || modelDeploymentID == "" || azureOpenAIEndpoint == "" {
		fmt.Fprintf(os.Stderr, "Skipping example, environment variables missing\n")
		return
	}

	keyCredential, err := azopenai.NewKeyCredential(azureOpenAIKey)

	if err != nil {
		//  TODO: Update the following line with your application specific error handling logic
		log.Fatalf("ERROR: %s", err)
	}

	client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, keyCredential, nil)

	if err != nil {
		//  TODO: Update the following line with your application specific error handling logic
		log.Fatalf("ERROR: %s", err)
	}

	// This is a conversation in progress.
	// NOTE: all messages, regardless of role, count against token usage for this API.
	messages := []azopenai.ChatMessage{
		// You set the tone and rules of the conversation with a prompt as the system role.
		{Role: to.Ptr(azopenai.ChatRoleSystem), Content: to.Ptr("You are a helpful assistant.")},

		// The user asks a question
		{Role: to.Ptr(azopenai.ChatRoleUser), Content: to.Ptr("Does Azure OpenAI support customer managed keys?")},

		// The reply would come back from the Azure OpenAI model. You'd add it to the conversation so we can maintain context.
		{Role: to.Ptr(azopenai.ChatRoleAssistant), Content: to.Ptr("Yes, customer managed keys are supported by Azure OpenAI")},

		// The user answers the question based on the latest reply.
		{Role: to.Ptr(azopenai.ChatRoleUser), Content: to.Ptr("Do other Azure AI services support this too?")},

		// from here you'd keep iterating, sending responses back from the chat completions API
	}

	resp, err := client.GetChatCompletions(context.TODO(), azopenai.ChatCompletionsOptions{
		// This is a conversation in progress.
		// NOTE: all messages count against token usage for this API.
		Messages:   messages,
		Deployment: modelDeploymentID,
	}, nil)

	if err != nil {
		//  TODO: Update the following line with your application specific error handling logic
		log.Fatalf("ERROR: %s", err)
	}

	for _, choice := range resp.Choices {
		fmt.Fprintf(os.Stderr, "Content[%d]: %s\n", *choice.Index, *choice.Message.Content)
	}

}

重要

運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 資格情報のセキュリティについて詳しくは、Azure AI サービスのセキュリティに関する記事をご覧ください。

コマンド プロンプトを開き、以下を実行します。

go mod init chat_completions.go

次に、以下を実行します。

go mod tidy
go run chat_completions.go

出力

Content[0]: Yes, many Azure AI services also support customer managed keys. These services enable you to bring your own encryption keys for data at rest, which provides you with more control over the security of your data.

リソースをクリーンアップする

Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。

次のステップ

その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください

ソース コード | 成果物 (Maven) | サンプル | 取得拡張生成 (RAG) エンタープライズ チャット テンプレート | IntelliJ IDEA

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します
  • 目的の Azure サブスクリプション内の Azure OpenAI Service へのアクセスの許可。 現時点では、このサービスへのアクセスは申請によってのみ許可されます。 Azure OpenAI Service へのアクセスを申請するには、https://aka.ms/oai/access のフォームに入力してください。

設定

キーとエンドポイントを取得する

Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントキーが必要です。

変数名
ENDPOINT この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 Azure OpenAI Studio>[プレイグラウンド]>[コード ビュー] で値を確認することもできます。 エンドポイントの例: https://docs-test-001.openai.azure.com/
API-KEY この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。

Azure portal でリソースに移動します。 [エンドポイントとキー][リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1 または KEY2 を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境変数

キーとエンドポイントの永続的な環境変数を作成して割り当てます。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

新しい Java アプリケーションを作成する

新しい Gradle プロジェクトを作成します。

コンソール ウィンドウ (cmd、PowerShell、Bash など) で、ご利用のアプリ用に新しいディレクトリを作成し、そこに移動します。

mkdir myapp && cd myapp

作業ディレクトリから gradle init コマンドを実行します。 次のコマンドを実行すると、build.gradle.kts を含む、Gradle 用の重要なビルド ファイルが作成されます。これは、アプリケーションを作成して構成するために、実行時に使用されます。

gradle init --type basic

DSL を選択するよう求められたら、Kotlin を選択します。

Java SDK をインストールする

このクイックスタートでは、Gradle 依存関係マネージャーを使用します。 クライアント ライブラリとその他の依存関係マネージャーの情報については、Maven Central Repository を参照してください。

build.gradle.kts を検索し、任意の IDE またはテキスト エディターで開きます。 その後、次のビルド構成をコピーします。 この構成では、エントリ ポイントが OpenAIQuickstart クラスである Java アプリケーションとしてプロジェクトを定義します。 これによって、Azure AI Vision ライブラリがインポートされます。

plugins {
    java
    application
}
application { 
    mainClass.set("OpenAIQuickstart")
}
repositories {
    mavenCentral()
}
dependencies {
    implementation(group = "com.azure", name = "azure-ai-openai", version = "1.0.0-beta.3")
    implementation("org.slf4j:slf4j-simple:1.7.9")
}

サンプル アプリケーションを作成する

  1. Java ファイルを作成します。

    作業ディレクトリから次のコマンドを実行し、プロジェクト ソース フォルダーを作成します。

    mkdir -p src/main/java
    

    新しいフォルダーに移動し、OpenAIQuickstart.java という名前のファイルを作成します。

  2. 適当なエディターまたは IDE で OpenAIQuickstart.java を開き、次のコードを貼り付けます。

    import com.azure.ai.openai.OpenAIClient;
    import com.azure.ai.openai.OpenAIClientBuilder;
    import com.azure.ai.openai.models.ChatChoice;
    import com.azure.ai.openai.models.ChatCompletions;
    import com.azure.ai.openai.models.ChatCompletionsOptions;
    import com.azure.ai.openai.models.ChatMessage;
    import com.azure.ai.openai.models.ChatRole;
    import com.azure.ai.openai.models.CompletionsUsage;
    import com.azure.core.credential.AzureKeyCredential;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class GetChatCompletionsSample {
    
        public static void main(String[] args) {
            String azureOpenaiKey = System.getenv("AZURE_OPENAI_API_KEY");;
            String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT");;
            String deploymentOrModelId = "gpt-35-turbo";
    
          OpenAIClient client = new OpenAIClientBuilder()
                .endpoint(endpoint)
                .credential(new AzureKeyCredential(azureOpenaiKey))
                .buildClient();
    
            List<ChatMessage> chatMessages = new ArrayList<>();
            chatMessages.add(new ChatMessage(ChatRole.SYSTEM, "You are a helpful assistant"));
            chatMessages.add(new ChatMessage(ChatRole.USER, "Does Azure OpenAI support customer managed keys?"));
            chatMessages.add(new ChatMessage(ChatRole.ASSISTANT, "Yes, customer managed keys are supported by Azure OpenAI?"));
            chatMessages.add(new ChatMessage(ChatRole.USER, "Do other Azure AI services support this too?"));
    
            ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, new ChatCompletionsOptions(chatMessages));
    
            System.out.printf("Model ID=%s is created at %s.%n", chatCompletions.getId(), chatCompletions.getCreatedAt());
            for (ChatChoice choice : chatCompletions.getChoices()) {
                ChatMessage message = choice.getMessage();
                System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole());
                System.out.println("Message:");
                System.out.println(message.getContent());
            }
    
            System.out.println();
            CompletionsUsage usage = chatCompletions.getUsage();
            System.out.printf("Usage: number of prompt token is %d, "
                    + "number of completion token is %d, and number of total tokens in request and response is %d.%n",
                usage.getPromptTokens(), usage.getCompletionTokens(), usage.getTotalTokens());
        }
    }  
    

    重要

    運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 資格情報のセキュリティについて詳しくは、Azure AI サービスのセキュリティに関する記事をご覧ください。

  3. プロジェクトのルート フォルダーに戻り、次のようにしてアプリをビルドします。

    gradle build
    

    次に、gradle run コマンドでそれを実行します。

    gradle run
    

出力

Model ID=chatcmpl-7JYnyE4zpd5gaIfTRH7hNpeVsvAw4 is created at 1684896378.
Index: 0, Chat Role: assistant.
Message:
Yes, most of the Azure AI services support customer managed keys. However, there may be some exceptions, so it is best to check the documentation of each specific service to confirm.

Usage: number of prompt token is 59, number of completion token is 36, and number of total tokens in request and response is 95.

リソースをクリーンアップする

Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。

次のステップ

ソース コード | 成果物 (Maven) | サンプル

前提条件

設定

キーとエンドポイントを取得する

Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントキーが必要です。

変数名
ENDPOINT この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 Azure OpenAI Studio>[プレイグラウンド]>[コード ビュー] で値を確認することもできます。 エンドポイントの例: https://docs-test-001.openai.azure.com/
API-KEY この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。

Azure portal でリソースに移動します。 [エンドポイントとキー][リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1 または KEY2 を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境変数

キーとエンドポイントの永続的な環境変数を作成して割り当てます。

Note

Spring AI の既定のモデル名は gpt-35-turbo です。 別の名前でモデルをデプロイした場合にのみ、SPRING_AI_AZURE_OPENAI_MODEL 値を指定する必要があります。

export SPRING_AI_AZURE_OPENAI_API_KEY="REPLACE_WITH_YOUR_KEY_VALUE_HERE"
export SPRING_AI_AZURE_OPENAI_ENDPOINT="REPLACE_WITH_YOUR_ENDPOINT_HERE"
export SPRING_AI_AZURE_OPENAI_MODEL="REPLACE_WITH_YOUR_MODEL_NAME_HERE"

新しい Spring アプリケーションを作成する

新しい Spring プロジェクトを作成します。

Bash ウィンドウで、アプリの新しいディレクトリを作成し、移動します。

mkdir ai-chat-demo && cd ai-chat-demo

作業ディレクトリから spring init コマンドを実行します。 このコマンドは、main の Java クラス ソース ファイルや Maven ベースのプロジェクト管理に使用される pom.xml ファイルなど、Spring プロジェクトの標準ディレクトリ構造を作成します。

spring init -a ai-chat-demo -n AIChat --force --build maven -x

生成されるファイルとフォルダーは次のような構造になります。

ai-chat-demo/
|-- pom.xml
|-- mvn
|-- mvn.cmd
|-- HELP.md
|-- src/
    |-- main/
    |   |-- resources/
    |   |   |-- application.properties
    |   |-- java/
    |       |-- com/
    |           |-- example/
    |               |-- aichatdemo/
    |                   |-- AiChatApplication.java
    |-- test/
        |-- java/
            |-- com/
                |-- example/
                    |-- aichatdemo/
                        |-- AiChatApplicationTests.java

Spring アプリケーションを編集する

  1. pom.xml ファイルを編集します。

    プロジェクト ディレクトリのルートから、任意のエディターまたは IDE で pom.xml ファイルを開き、次の内容でファイルを上書きします:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>3.2.0</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>ai-chat-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>AIChat</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>17</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.experimental.ai</groupId>
                <artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId>
                <version>0.7.0-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
        <repositories>
            <repository>
                <id>spring-snapshots</id>
                <name>Spring Snapshots</name>
                <url>https://repo.spring.io/snapshot</url>
                <releases>
                    <enabled>false</enabled>
                </releases>
            </repository>
        </repositories>
    </project>
    
  2. src/main/java/com/example/aichatdemo フォルダーから、任意のエディターまたは IDE で AiChatApplication.java を開き、次のコードを貼り付けます:

    package com.example.aichatdemo;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.ai.client.AiClient;
    import org.springframework.ai.prompt.Prompt;
    import org.springframework.ai.prompt.messages.ChatMessage;
    import org.springframework.ai.prompt.messages.Message;
    import org.springframework.ai.prompt.messages.MessageType;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class AiChatApplication implements CommandLineRunner
    {
        private static final String ROLE_INFO_KEY = "role";
    
        @Autowired
        private AiClient aiClient;
    
        public static void main(String[] args) {
            SpringApplication.run(AiChatApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception
        {
            System.out.println(String.format("Sending chat prompts to AI service. One moment please...\r\n"));
    
            final List<Message> msgs = new ArrayList<>();
    
            msgs.add(new ChatMessage(MessageType.SYSTEM, "You are a helpful assistant"));
            msgs.add(new ChatMessage(MessageType.USER, "Does Azure OpenAI support customer managed keys?"));
            msgs.add(new ChatMessage(MessageType.ASSISTANT, "Yes, customer managed keys are supported by Azure OpenAI?"));
            msgs.add(new ChatMessage(MessageType.USER, "Do other Azure AI services support this too?"));
    
            final var resps = aiClient.generate(new Prompt(msgs));
    
            System.out.println(String.format("Prompt created %d generated response(s).", resps.getGenerations().size()));
    
            resps.getGenerations().stream()
              .forEach(gen -> {
                  final var role = gen.getInfo().getOrDefault(ROLE_INFO_KEY, MessageType.ASSISTANT.getValue());
    
                  System.out.println(String.format("Generated respose from \"%s\": %s", role, gen.getText()));
              });
        }
    
    }
    

    重要

    運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 資格情報のセキュリティについて詳しくは、Azure AI サービスのセキュリティに関する記事をご覧ください。

  3. プロジェクトのルート フォルダーに戻り、次のコマンドを使ってアプリを実行します:

    ./mvnw spring-boot:run
    

出力

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.1.5)

2023-11-07T13:31:10.884-06:00  INFO 6248 --- [           main] c.example.aichatdemo.AiChatApplication   : No active profile set, falling back to 1 default profile: "default"
2023-11-07T13:31:11.595-06:00  INFO 6248 --- [           main] c.example.aichatdemo.AiChatApplication   : Started AiChatApplication in 0.994 seconds (process running for 1.28)
Sending chat prompts to AI service. One moment please...

Prompt created 1 generated response(s).
Generated respose from "assistant": Yes, other Azure AI services also support customer managed keys. Azure AI Services, Azure Machine Learning, and other AI services in Azure provide options for customers to manage and control their encryption keys. This allows customers to have greater control over their data and security.

リソースをクリーンアップする

Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。

次のステップ

その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください

ソース コード | パッケージ (npm) | サンプル | 取得拡張生成 (RAG) エンタープライズ チャット テンプレート|

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します
  • 目的の Azure サブスクリプション内の Azure OpenAI Service へのアクセスの許可。 現時点では、このサービスへのアクセスは申請によってのみ許可されます。 Azure OpenAI Service へのアクセスを申請するには、https://aka.ms/oai/access のフォームに入力してください。
  • Node.js の LTS バージョン
  • gpt-35-turbo または gpt-4 モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。

設定

キーとエンドポイントを取得する

Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントキーが必要です。

変数名
ENDPOINT この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 Azure OpenAI Studio>[プレイグラウンド]>[コード ビュー] で値を確認することもできます。 エンドポイントの例: https://docs-test-001.openai.azure.com/
API-KEY この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。

Azure portal でリソースに移動します。 [エンドポイントとキー][リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1 または KEY2 を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境変数

キーとエンドポイントの永続的な環境変数を作成して割り当てます。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

Node アプリケーションを作成する

コンソール ウィンドウ (cmd、PowerShell、Bash など) で、ご利用のアプリ用に新しいディレクトリを作成し、そこに移動します。 次に、npm init コマンドを実行し、package.json ファイルを使用してノード アプリケーションを作成します。

npm init

クライアント ライブラリをインストールする

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

npm install @azure/openai

アプリの package.json ファイルは依存関係を含めて更新されます。

サンプル アプリケーションを作成する

新しいプロジェクトを作成するコマンド プロンプトを開き、ChatCompletion.js という名前の新しいファイルを作成します。 次のコードを ChatCompletion.js ファイルにコピーします。

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] ;
const azureApiKey = process.env["AZURE_OPENAI_API_KEY"] ;

const messages = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content: "Does Azure OpenAI support customer managed keys?" },
  { role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI" },
  { role: "user", content: "Do other Azure AI services support this too" },
];

async function main() {
  console.log("== Chat Completions Sample ==");

  const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
  const deploymentId = "gpt-35-turbo";
  const result = await client.getChatCompletions(deploymentId, messages);

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

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

module.exports = { main };

重要

運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 資格情報のセキュリティについて詳しくは、Azure AI サービスのセキュリティに関する記事をご覧ください。

次のコマンドを使用してこのスクリプトを実行します。

node.exe ChatCompletion.js

出力

== Chat Completions Sample ==
{
  role: 'assistant',
  content: 'Yes, most Azure AI services support customer managed keys. It is always best to check the specific service documentation to confirm this.'
}

リソースをクリーンアップする

Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。

次のステップ

ライブラリ ソース コード | パッケージ (PyPI) | 取得拡張生成 (RAG) エンタープライズ チャット テンプレート |

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します
  • 目的の Azure サブスクリプション内の Azure OpenAI Service に付与されたアクセス。 現時点では、このサービスへのアクセスは申請によってのみ許可されます。 Azure OpenAI Service へのアクセスを申請するには、https://aka.ms/oai/access のフォームに入力してください。
  • Python 3.8 以降のバージョン
  • 次の Python ライブラリ: os。
  • gpt-35-turbo または gpt-4 モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。

設定

次を使用して、OpenAI Python クライアント ライブラリをインストールします。

pip install openai

Note

このライブラリは OpenAI によって管理されており、現在はプレビュー段階です。 このライブラリの最新の更新を追跡するには、リリース履歴または version.py のコミット履歴を参照してください。

キーとエンドポイントを取得する

Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントキーが必要です。

変数名
ENDPOINT この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 Azure OpenAI Studio>[プレイグラウンド]>[コード ビュー] で値を確認することもできます。 エンドポイントの例: https://docs-test-001.openai.azure.com/
API-KEY この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。

Azure portal でリソースに移動します。 [エンドポイントとキー][リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1 または KEY2 を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境変数

キーとエンドポイントの永続的な環境変数を作成して割り当てます。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

新しい Python アプリケーションを作成する

  1. quickstart.py という名前の新しい Python ファイルを作成します。 次に、任意のエディターまたは IDE で開きます。

  2. quickstart.py の内容を次のコードに置き換えます。

model 変数は、GPT-3.5-Turbo または GPT-4 モデルのデプロイ時に選択したデプロイ名に設定する必要があります。 モデル名の入力では、基になるモデル名と同じデプロイ名を選択しないとエラーが発生します。

import os
from openai import AzureOpenAI

client = AzureOpenAI(
  azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"), 
  api_key=os.getenv("AZURE_OPENAI_API_KEY"),  
  api_version="2024-02-01"
)

response = client.chat.completions.create(
    model="gpt-35-turbo", # model = "deployment_name".
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Does Azure OpenAI support customer managed keys?"},
        {"role": "assistant", "content": "Yes, customer managed keys are supported by Azure OpenAI."},
        {"role": "user", "content": "Do other Azure AI services support this too?"}
    ]
)

print(response.choices[0].message.content)

重要

運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 資格情報のセキュリティについて詳しくは、Azure AI サービスのセキュリティに関する記事をご覧ください。

  1. クイック スタート ファイルに対して次の python コマンドを使用して、アプリケーションを実行します。

    python quickstart.py
    

出力

{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "Yes, most of the Azure AI services support customer managed keys. However, not all services support it. You can check the documentation of each service to confirm if customer managed keys are supported.",
        "role": "assistant"
      }
    }
  ],
  "created": 1679001781,
  "id": "chatcmpl-6upLpNYYOx2AhoOYxl9UgJvF4aPpR",
  "model": "gpt-3.5-turbo-0301",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 39,
    "prompt_tokens": 58,
    "total_tokens": 97
  }
}
Yes, most of the Azure AI services support customer managed keys. However, not all services support it. You can check the documentation of each service to confirm if customer managed keys are supported.

メッセージの構造について

GPT-35-Turbo および GPT-4 モデルは、会話形式の入力を処理するように最適化されています。 messages 変数は、システム、ユーザー、アシスタントによって示された会話内のさまざまなロールを持つディクショナリの配列を渡します。 システム メッセージを使用して、モデルの応答方法に関するコンテキストまたは指示を含めることで、モデルを準備できます。

GPT-35-Turbo および GPT-4 攻略ガイドでは、これらの新しいモデルとやり取りするためのオプションを詳しく紹介します。

リソースをクリーンアップする

OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。

次のステップ

Rest API 仕様 |

前提条件

  • Azure サブスクリプション。無料で作成できます
  • 目的の Azure サブスクリプション内の Azure OpenAI Service に付与されたアクセス。 現時点では、このサービスへのアクセスは申請によってのみ許可されます。 Azure OpenAI Service へのアクセスを申請するには、https://aka.ms/oai/access のフォームに入力してください。
  • gpt-35-turbo または gpt-4 モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。

設定

キーとエンドポイントを取得する

Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントキーが必要です。

変数名
ENDPOINT この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 Azure OpenAI Studio>[プレイグラウンド]>[コード ビュー] で値を確認することもできます。 エンドポイントの例: https://docs-test-001.openai.azure.com/
API-KEY この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。

Azure portal でリソースに移動します。 [エンドポイントとキー][リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1 または KEY2 を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境変数

キーとエンドポイントの永続的な環境変数を作成して割り当てます。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

REST API

Bash シェルで、次のコマンドを実行します。 gpt-35-turbo は、GPT-35-Turbo または GPT-4 モデルのデプロイ時に選択したデプロイ名に置き換える必要があります。 モデル名の入力では、基になるモデル名と同じデプロイ名を選択しないとエラーが発生します。

curl $AZURE_OPENAI_ENDPOINT/openai/deployments/gpt-35-turbo/chat/completions?api-version=2024-02-01 \
  -H "Content-Type: application/json" \
  -H "api-key: $AZURE_OPENAI_API_KEY" \
  -d '{"messages":[{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Does Azure OpenAI support customer managed keys?"},{"role": "assistant", "content": "Yes, customer managed keys are supported by Azure OpenAI."},{"role": "user", "content": "Do other Azure AI services support this too?"}]}'

エンドポイントの例を含めたコマンドの最初の行の形式は、curl https://docs-test-001.openai.azure.com/openai/deployments/{YOUR-DEPLOYMENT_NAME_HERE}/chat/completions?api-version=2024-02-01 \ ようになります。エラーが発生した場合は、エンドポイントと /openai/deployments の区切りで / が重複していないことを再確認してください。

このコマンドを通常の Windows コマンド プロンプトで実行する場合は、テキストを変更して、\ と改行を削除する必要があります。

重要

運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 資格情報のセキュリティについて詳しくは、Azure AI サービスのセキュリティに関する記事をご覧ください。

出力

{"id":"chatcmpl-6v7mkQj980V1yBec6ETrKPRqFjNw9",
"object":"chat.completion","created":1679072642,
"model":"gpt-35-turbo",
"usage":{"prompt_tokens":58,
"completion_tokens":68,
"total_tokens":126},
"choices":[{"message":{"role":"assistant",
"content":"Yes, other Azure AI services also support customer managed keys. Azure AI services offer multiple options for customers to manage keys, such as using Azure Key Vault, customer-managed keys in Azure Key Vault or customer-managed keys through Azure Storage service. This helps customers ensure that their data is secure and access to their services is controlled."},"finish_reason":"stop","index":0}]}

読みやすいように出力形式が調整されています。実際の出力は改行のない単一のテキスト ブロックです。

メッセージの構造について

GPT-35-Turbo および GPT-4 モデルは、会話形式の入力を処理するように最適化されています。 messages 変数は、システム、ユーザー、アシスタントによって示された会話内のさまざまなロールを持つディクショナリの配列を渡します。 システム メッセージを使用して、モデルの応答方法に関するコンテキストまたは指示を含めることで、モデルを準備できます。

GPT-35-Turbo および GPT-4 攻略ガイドでは、これらの新しいモデルとやり取りするためのオプションを詳しく紹介します。

リソースをクリーンアップする

OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。

次のステップ

前提条件

キーとエンドポイントを取得する

Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントキーが必要です。

変数名
ENDPOINT この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 Azure OpenAI Studio>[プレイグラウンド]>[コード ビュー] で値を確認することもできます。 エンドポイントの例: https://docs-test-001.openai.azure.com/
API-KEY この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。

Azure portal でリソースに移動します。 [エンドポイントとキー][リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1 または KEY2 を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint & access keys location circled in red.

キーとエンドポイントの永続的な環境変数を作成して割り当てます。

環境変数

$Env:AZURE_OPENAI_API_KEY = 'YOUR_KEY_VALUE'
$Env:AZURE_OPENAI_ENDPOINT = 'YOUR_ENDPOINT'

新しい PowerShell スクリプトの作成

  1. quickstart.ps1 という名前の新しい PowerShell ファイルを作成します。 次に、任意のエディターまたは IDE で開きます。

  2. quickstart.ps1 の内容を次のコードで置き換えます。 engine 変数は、GPT-35-Turbo または GPT-4 モデルのデプロイ時に選択したデプロイ名に設定する必要があります。 モデル名の入力では、基になるモデル名と同じデプロイ名を選択しないとエラーが発生します。

    # Azure OpenAI metadata variables
    $openai = @{
       api_key     = $Env:AZURE_OPENAI_API_KEY
       api_base    = $Env:AZURE_OPENAI_ENDPOINT # your endpoint should look like the following https://YOUR_RESOURCE_NAME.openai.azure.com/
       api_version = '2023-05-15' # this may change in the future
       name        = 'YOUR-DEPLOYMENT-NAME-HERE' #This will correspond to the custom name you chose for your deployment when you deployed a model.
    }
    
    # Completion text
    $messages = @()
    $messages += @{
      role = 'system'
      content = 'You are a helpful assistant.'
    }
    $messages += @{
      role = 'user'
      content = 'Does Azure OpenAI support customer managed keys?'
    }
    $messages += @{
      role = 'assistant'
      content = 'Yes, customer managed keys are supported by Azure OpenAI.'
    }
    $messages += @{
      role = 'user'
      content = 'Do other Azure AI services support this too?'
    }
    
    # Header for authentication
    $headers = [ordered]@{
       'api-key' = $openai.api_key
    }
    
    # Adjust these values to fine-tune completions
    $body = [ordered]@{
       messages = $messages
    } | ConvertTo-Json
    
    # Send a request to generate an answer
    $url = "$($openai.api_base)/openai/deployments/$($openai.name)/chat/completions?api-version=$($openai.api_version)"
    
    $response = Invoke-RestMethod -Uri $url -Headers $headers -Body $body -Method Post -ContentType 'application/json'
    return $response
    

    重要

    運用環境では、Azure Key Valut を使用した PowerShell Secret Management のような安全な方法で認証情報を保存し、アクセスしてください。 資格情報のセキュリティについて詳しくは、Azure AI サービスのセキュリティに関する記事をご覧ください。

  3. PowerShell を使用してスクリプトを実行します。

    ./quickstart.ps1
    

出力

# the output of the script will be a .NET object containing the response
id      : chatcmpl-7sdJJRC6fDNGnfHMdfHXvPkYFbaVc
object  : chat.completion
created : 1693255177
model   : gpt-35-turbo
choices : {@{index=0; finish_reason=stop; message=}}
usage   : @{completion_tokens=67; prompt_tokens=55; total_tokens=122}

# convert the output to JSON
./quickstart.ps1 | ConvertTo-Json -Depth 3

# or to view the text returned, select the specific object property
$reponse = ./quickstart.ps1
$response.choices.message.content

メッセージの構造について

GPT-35-Turbo および GPT-4 モデルは、会話形式の入力を処理するように最適化されています。 messages 変数は、システム、ユーザー、アシスタントによって示された会話内のさまざまなロールを持つディクショナリの配列を渡します。 システム メッセージを使用して、モデルの応答方法に関するコンテキストまたは指示を含めることで、モデルを準備できます。

GPT-35-Turbo および GPT-4 攻略ガイドでは、これらの新しいモデルとやり取りするためのオプションを詳しく紹介します。

リソースをクリーンアップする

OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。

次のステップ