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

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

前提条件

  • Azure サブスクリプション。無料で作成できます
  • gpt-4o または gpt-4o-mini モデルがデプロイされた Azure OpenAI Service リソース。 最初の探索には、標準またはグローバル標準モデルのデプロイ タイプを使用することをお勧めします。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。

Azure OpenAI Studio に移動する

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

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

[Chat playground] (チャット プレイグラウンド) が強調表示されている Azure OpenAI Studio のランディング ページのスクリーンショット。

プレイグラウンド

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

[Chat playground] (チャット プレイグラウンド) ページのスクリーンショット。

セットアップ

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

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

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

チャット セッション

[Enter] ボタンを選択するか、右矢印アイコンを選択すると、入力したテキストがチャット入力候補 API に送信され、結果がテキスト ボックスに返されます。

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

主要な設定

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

コードの表示

モデルとのチャットを試したら、</> [コードの表示] ボタンを選択します。 これにより、これまでの会話全体の背後にあるコードを再生できます。

[コードの表示] エクスペリエンスのスクリーンショット。

プロンプト構造の概要

[コードの表示] からサンプルを調べると、会話が 3 つの異なるロール (systemuserassistant) に分割されていることがわかります。 モデルにメッセージを送信するたびに、その時点までの会話履歴全体が再送信されます。 チャット入力候補 API を使用する場合、モデルには過去に送信した内容の真のメモリがないため、モデルが適切に応答できるようにコンテキストの会話履歴を提供します。

チャット入力候補の攻略ガイド」では、新しいプロンプト構造とチャット入力候補モデルを効果的に使用する方法について詳しく説明しています。

モデルをデプロイする

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

Azure OpenAI Studio のモデル デプロイ ボタンを示すスクリーンショット。

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

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

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

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

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

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

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

次のステップ

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

前提条件

設定

新しい .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 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Azure portal の Azure OpenAI リソースの概要 UI のスクリーンショット。エンドポイントおよびアクセス キーの場所が赤色の丸で囲まれています。

環境変数

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

重要

API キーを使用する場合は、それを Azure Key Vault などの別の場所に安全に保存します。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。

AI サービスのセキュリティの詳細については、「Azure AI サービスに対する要求の認証」を参照してください。

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");

AzureOpenAIClient azureClient = new(
    new Uri(endpoint),
    new AzureKeyCredential(key));

// This must match the custom deployment name you chose for your model
ChatClient chatClient = azureClient.GetChatClient("gpt-35-turbo");

ChatCompletion completion = chatClient.CompleteChat(
    [
        new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
        new UserChatMessage("Does Azure OpenAI support customer managed keys?"),
        new AssistantChatMessage("Yes, customer managed keys are supported by Azure OpenAI"),
        new UserChatMessage("Do other Azure AI services support this too?")
    ]);

Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");

重要

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

dotnet run program.cs

出力

Assistant : Yes, many other Azure AI services also support customer managed keys, including Azure Cognitive Services, Azure Machine Learning, and Azure Databricks. By using customer managed keys, you can retain complete control over your encryption keys and provide an additional layer of security for your AI assets.

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

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

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

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

AzureOpenAIClient azureClient = new(
    new Uri(endpoint),
    new AzureKeyCredential(key));

// This must match the custom deployment name you chose for your model
ChatClient chatClient = azureClient.GetChatClient("gpt-35-turbo");

var chatUpdates = chatClient.CompleteChatStreamingAsync(
    [
        new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
        new UserChatMessage("Does Azure OpenAI support customer managed keys?"),
        new AssistantChatMessage("Yes, customer managed keys are supported by Azure OpenAI"),
        new UserChatMessage("Do other Azure AI services support this too?")
    ]);

await foreach(var chatUpdate in chatUpdates)
{
    if (chatUpdate.Role.HasValue)
    {
        Console.Write($"{chatUpdate.Role} : ");
    }
    
    foreach(var contentPart in chatUpdate.ContentUpdate)
    {
        Console.Write(contentPart.Text);
    }
}

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

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

次のステップ

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

前提条件

設定

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

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 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Azure portal の Azure OpenAI リソースの概要 UI のスクリーンショット。エンドポイントおよびアクセス キーの場所が赤色の丸で囲まれています。

環境変数

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

重要

API キーを使用する場合は、それを Azure Key Vault などの別の場所に安全に保存します。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。

AI サービスのセキュリティの詳細については、「Azure AI サービスに対する要求の認証」を参照してください。

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"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
)

func main() {
	azureOpenAIKey := os.Getenv("AZURE_OPENAI_API_KEY")
	modelDeploymentID := os.Getenv("YOUR_MODEL_DEPLOYMENT_NAME")
    maxTokens:= int32(400)


	// 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 := azcore.NewKeyCredential(azureOpenAIKey)

	// In Azure OpenAI you must deploy a model before you can use it in your client. For more information
	// see here: https://video2.skills-academy.com/azure/cognitive-services/openai/how-to/create-resource
	client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, keyCredential, nil)

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

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

		// The user asks a question
		&azopenai.ChatRequestUserMessage{Content: azopenai.NewChatRequestUserMessageContent("Does Azure OpenAI support customer managed keys?")},

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

		// The user answers the question based on the latest reply.
		&azopenai.ChatRequestUserMessage{Content: azopenai.NewChatRequestUserMessageContent("What other Azure Services support customer managed keys?")},

		// from here you'd keep iterating, sending responses back from ChatGPT
	}

	gotReply := false

	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,
		DeploymentName: &modelDeploymentID,
		MaxTokens: &maxTokens,
	}, nil)

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

	for _, choice := range resp.Choices {
		gotReply = true

		if choice.ContentFilterResults != nil {
			fmt.Fprintf(os.Stderr, "Content filter results\n")

			if choice.ContentFilterResults.Error != nil {
				fmt.Fprintf(os.Stderr, "  Error:%v\n", choice.ContentFilterResults.Error)
			}

			fmt.Fprintf(os.Stderr, "  Hate: sev: %v, filtered: %v\n", *choice.ContentFilterResults.Hate.Severity, *choice.ContentFilterResults.Hate.Filtered)
			fmt.Fprintf(os.Stderr, "  SelfHarm: sev: %v, filtered: %v\n", *choice.ContentFilterResults.SelfHarm.Severity, *choice.ContentFilterResults.SelfHarm.Filtered)
			fmt.Fprintf(os.Stderr, "  Sexual: sev: %v, filtered: %v\n", *choice.ContentFilterResults.Sexual.Severity, *choice.ContentFilterResults.Sexual.Filtered)
			fmt.Fprintf(os.Stderr, "  Violence: sev: %v, filtered: %v\n", *choice.ContentFilterResults.Violence.Severity, *choice.ContentFilterResults.Violence.Filtered)
		}

		if choice.Message != nil && choice.Message.Content != nil {
			fmt.Fprintf(os.Stderr, "Content[%d]: %s\n", *choice.Index, *choice.Message.Content)
		}

		if choice.FinishReason != nil {
			// this choice's conversation is complete.
			fmt.Fprintf(os.Stderr, "Finish reason[%d]: %s\n", *choice.Index, *choice.FinishReason)
		}
	}

	if gotReply {
		fmt.Fprintf(os.Stderr, "Received chat completions reply\n")
	}

}

重要

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

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

go mod init chat_completions.go

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

go mod tidy
go run chat_completions.go

出力

Content filter results
  Hate: sev: safe, filtered: false
  SelfHarm: sev: safe, filtered: false
  Sexual: sev: safe, filtered: false
  Violence: sev: safe, filtered: false
Content[0]: As of my last update in early 2023, in Azure, several AI services support the use of customer-managed keys (CMKs) through Azure Key Vault. This allows customers to have control over the encryption keys used to secure their data at rest. The services that support this feature typically fall under Azure's range of cognitive services and might include:

1. Azure Cognitive Search: It supports using customer-managed keys to encrypt the index data.
2. Azure Form Recognizer: For data at rest, you can use customer-managed keys for added security.
3. Azure Text Analytics: CMKs can be used for encrypting your data at rest.
4. Azure Blob Storage: While not exclusively an AI service, it's often used in conjunction with AI services to store data, and it supports customer-managed keys for encrypting blob data.

Note that the support for CMKs can vary by service and sometimes even by the specific feature within the service. Additionally, the landscape of cloud services is fast evolving, and new features, including security capabilities, are frequently added. Therefore, it's recommended to check the latest Azure documentation or contact Azure support for the most current information about CMK support for any specific Azure AI service.
Finish reason[0]: stop
Received chat completions reply

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

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

次のステップ

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

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

前提条件

設定

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

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 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Azure portal の Azure OpenAI リソースの概要 UI のスクリーンショット。エンドポイントおよびアクセス キーの場所が赤色の丸で囲まれています。

環境変数

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

重要

API キーを使用する場合は、それを Azure Key Vault などの別の場所に安全に保存します。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。

AI サービスのセキュリティの詳細については、「Azure AI サービスに対する要求の認証」を参照してください。

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.10")
    implementation("org.slf4j:slf4j-simple:1.7.9")
}

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

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

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

    mkdir -p src/main/java
    

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

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

    package com.azure.ai.openai.usage;
    
    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.ChatRequestAssistantMessage;
    import com.azure.ai.openai.models.ChatRequestMessage;
    import com.azure.ai.openai.models.ChatRequestSystemMessage;
    import com.azure.ai.openai.models.ChatRequestUserMessage;
    import com.azure.ai.openai.models.ChatResponseMessage;
    import com.azure.ai.openai.models.CompletionsUsage;
    import com.azure.core.credential.AzureKeyCredential;
    import com.azure.core.util.Configuration;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class OpenAIQuickstart {
    
        public static void main(String[] args) {
            String azureOpenaiKey = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_API_KEY");
            String endpoint = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT");
            String deploymentOrModelId = "{azure-open-ai-deployment-model-id}";
    
            OpenAIClient client = new OpenAIClientBuilder()
                .endpoint(endpoint)
                .credential(new AzureKeyCredential(azureOpenaiKey))
                .buildClient();
    
            List<ChatRequestMessage> chatMessages = new ArrayList<>();
            chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant."));
            chatMessages.add(new ChatRequestUserMessage("Does Azure OpenAI support customer managed keys?"));
            chatMessages.add(new ChatRequestAssistantMessage("Yes, customer managed keys are supported by Azure OpenAI?"));
            chatMessages.add(new ChatRequestUserMessage("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()) {
                ChatResponseMessage 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 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Azure portal の Azure OpenAI リソースの概要 UI のスクリーンショット。エンドポイントおよびアクセス キーの場所が赤色の丸で囲まれています。

環境変数

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

重要

API キーを使用する場合は、それを Azure Key Vault などの別の場所に安全に保存します。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。

AI サービスのセキュリティの詳細については、「Azure AI サービスに対する要求の認証」を参照してください。

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) | サンプル

Note

この記事は、Azure OpenAI を完全にサポートするようになった最新の OpenAI npm パッケージを使用するように更新されました。 レガシ Azure OpenAI JavaScript SDK のコード サンプルをお探しであれば、それらはまだこちらのリポジトリで入手可能です

前提条件

設定

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

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 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Azure portal の Azure OpenAI リソースの概要 UI のスクリーンショット。エンドポイントおよびアクセス キーの場所が赤色の丸で囲まれています。

環境変数

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

重要

API キーを使用する場合は、それを Azure Key Vault などの別の場所に安全に保存します。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。

AI サービスのセキュリティの詳細については、「Azure AI サービスに対する要求の認証」を参照してください。

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 を使用して、JavaScript に必要なパッケージをインストールします。

npm install openai dotenv @azure/identity

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

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

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

import "dotenv/config";
import { AzureOpenAI } from "openai";
import type {
  ChatCompletion,
  ChatCompletionCreateParamsNonStreaming,
} from "openai/resources/index";

// You will need to set these environment variables or edit the following values
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";

// Required Azure OpenAI deployment name and API version
const apiVersion = "2024-08-01-preview";
const deploymentName = "gpt-4o-mini"; //This must match your deployment name.

function getClient(): AzureOpenAI {
  return new AzureOpenAI({
    endpoint,
    apiKey,
    apiVersion,
    deployment: deploymentName,
  });
}

function createMessages(): ChatCompletionCreateParamsNonStreaming {
  return {
    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?" },
    ],
    model: "",
  };
}
async function printChoices(completion: ChatCompletion): Promise<void> {
  for (const choice of completion.choices) {
    console.log(choice.message);
  }
}
export async function main() {
  const client = getClient();
  const messages = createMessages();
  const result = await client.chat.completions.create(messages);
  await printChoices(result);
}

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

次のコマンドを実行して、スクリプトをビルドします。

tsc

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

node.exe Completion.js

出力

== Chat Completions Sample ==
{
  content: 'Yes, several other Azure AI services also support customer managed keys for enhanced security and control over encryption keys.',
  role: 'assistant'
}

Microsoft Entra ID

重要

前の例では、キーベースの認証を示しています。 キーベースの認証のテストが成功したら、次のコード サンプルで示す、より安全な Microsoft Entra ID を認証に使用することをお勧めします。 [Microsoft Entra ID] の使用を開始するには、いくつかの追加の前提条件が必要です。

import {
  DefaultAzureCredential,
  getBearerTokenProvider,
} from "@azure/identity";
import "dotenv/config";
import { AzureOpenAI } from "openai";
import type {
  ChatCompletion,
  ChatCompletionCreateParamsNonStreaming,
} from "openai/resources/index";

// You will need to set these environment variables or edit the following values
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";

// Required Azure OpenAI deployment name and API version
const apiVersion = "2024-08-01-preview";
const deploymentName = "gpt-4o-mini"; //This must match your deployment name.

function getClient(): AzureOpenAI {
  const scope = "https://cognitiveservices.azure.com/.default";
  const azureADTokenProvider = getBearerTokenProvider(
    new DefaultAzureCredential(),
    scope
  );
  return new AzureOpenAI({
    endpoint,
    azureADTokenProvider,
    deployment: deploymentName,
    apiVersion,
  });
}

function createMessages(): ChatCompletionCreateParamsNonStreaming {
  return {
    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?" },
    ],
    model: "",
  };
}
async function printChoices(completion: ChatCompletion): Promise<void> {
  for (const choice of completion.choices) {
    console.log(choice.message);
  }
}
export async function main() {
  const client = getClient();
  const messages = createMessages();
  const result = await client.chat.completions.create(messages);
  await printChoices(result);
}

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

Note

"エラーが発生しました。OpenAIError: apiKey および azureADTokenProvider 引数は相互に排他的で、一度に渡すことができるのは 1 つだけです。" というエラーが発生した場合API キーの既存の環境変数をシステムから削除することが必要な場合があります。 Microsoft Entra ID コード サンプルで API キー環境変数を明示的に参照していなくても、このサンプルを実行するシステムに API キー環境変数が存在する場合、このエラーが生成されます。

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

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

次のステップ

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

前提条件

設定

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

pip install openai

Note

このライブラリは、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 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Azure portal の Azure OpenAI リソースの概要 UI のスクリーンショット。エンドポイントおよびアクセス キーの場所が赤色の丸で囲まれています。

環境変数

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

重要

API キーを使用する場合は、それを Azure Key Vault などの別の場所に安全に保存します。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。

AI サービスのセキュリティの詳細については、「Azure AI サービスに対する要求の認証」を参照してください。

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 攻略ガイドでは、これらの新しいモデルとやり取りするためのオプションを詳しく紹介します。

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

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

次のステップ

Rest API 仕様 |

前提条件

設定

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

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 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Azure portal の Azure OpenAI リソースの概要 UI のスクリーンショット。エンドポイントおよびアクセス キーの場所が赤色の丸で囲まれています。

環境変数

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

重要

API キーを使用する場合は、それを Azure Key Vault などの別の場所に安全に保存します。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。

AI サービスのセキュリティの詳細については、「Azure AI サービスに対する要求の認証」を参照してください。

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 攻略ガイドでは、これらの新しいモデルとやり取りするためのオプションを詳しく紹介します。

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

Azure 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 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。

Azure portal の Azure OpenAI リソースの概要 UI のスクリーンショット。エンドポイントおよびアクセス キーの場所が赤色の丸で囲まれています。

環境変数

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

重要

API キーを使用する場合は、それを Azure Key Vault などの別の場所に安全に保存します。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。

AI サービスのセキュリティの詳細については、「Azure AI サービスに対する要求の認証」を参照してください。

$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 = '2024-02-01' # 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 攻略ガイドでは、これらの新しいモデルとやり取りするためのオプションを詳しく紹介します。

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

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

次のステップ