この記事を使用して、Azure OpenAI の使用を開始します。
前提条件
- Azure サブスクリプション。無料で作成できます。
gpt-4o
またはgpt-4o-mini
モデルがデプロイされた Azure OpenAI Service リソース。 最初の探索には、標準またはグローバル標準モデルのデプロイ タイプを使用することをお勧めします。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。
Azure AI Foundry に移動する
Azure AI Foundry ポータルに移動し、Azure OpenAI リソースにアクセスできる資格情報でサインインします。 サインイン ワークフローの途中または後で、適切なディレクトリ、Azure サブスクリプション、Azure OpenAI リソースを選択します。
Azure AI Foundry から、[チャット プレイグラウンド] を選択します。
プレイグラウンド
Azure AI Foundry のチャット プレイグラウンドを使って、ノーコード アプローチで Azure OpenAI Service 機能の探索を始めましょう。 このページから、素早く機能を反復し、実験することができます。
セットアップ
*[プロンプト サンプル] ドロップダウンを使用して、事前に読み込まれたシステム メッセージの例をいくつか選択して開始できます。
システム メッセージ は、モデルがどのように振る舞うべきか、また、応答を生成するときに参照すべきコンテキストについての指示を与えます。 アシスタントのパーソナリティを記述したり、答えるべきことと答えるべきでないことを指示したり、応答のフォーマットを指示したりすることができます。
Chat playground を使用している間、いつでも コードを表示 を選択し、現在のチャットセッションと設定の選択に基づいて、Python、curl、json のコードサンプルを見ることができます。 そして、このコードを使用して、現在プレイグラウンドで実行しているのと同じタスクを完了するアプリケーションを書くことができます。
チャット セッション
[Enter] ボタンを選択するか、右矢印アイコンを選択すると、入力したテキストがチャット入力候補 API に送信され、結果がテキスト ボックスに返されます。
現在の会話履歴を削除するには、[Clear chat] (チャットをクリアする) ボタンを選択します。
主要な設定
名前 | 説明 |
---|---|
デプロイメント | 特定のモデルに関連付けられているデプロイ名。 |
データの追加 | |
パラメーター | モデルの応答を変更するカスタム パラメーター。 最初は、ほとんどのパラメーターに既定値を使用することをお勧めします |
気温 | ランダム性を制御します。 温度を下げることは、モデルが生成する反復的で決定的な応答が増えることを意味します。 温度を上げると、予期しない応答や独創的な応答が増えます。 温度または Top P を調整してみてください。ただし、両方を調整しないでください。 |
最大応答 (トークン) | モデルの応答あたりのトークン数に制限を設定します。 最新モデルの API では、プロンプト (システム メッセージ、例、メッセージ履歴、ユーザー クエリを含む) とモデルの応答の間で共有される最大 128,000 個のトークンがサポートされます。 1 つのトークンは一般的な英語テキストの約 4 文字です。 |
Top p | 温度と同様に、これはランダム性を制御しますが、使用する方法が異なります。 Top P を下げると、モデルのトークンの選択が、可能性が高いトークンに絞り込まれます。 Top P を上げると、モデルは可能性の高いトークンと低いトークンの両方から選択できます。 温度または Top P を調整してみてください。ただし、両方を調整しないでください。 |
停止シーケンス | 停止シーケンスでは、モデルは目的のポイントで応答を終了します。 モデル応答は、指定されたシーケンスの前で終了するため、停止シーケンス テキストは含まれません。 GPT-35-Turbo の場合、<|im_end|> を使用すると、モデル応答でフォローアップ ユーザー クエリが生成されません。 最大 4 つの停止シーケンスを組み込むことができます。 |
コードの表示
モデルとのチャットを試したら、</> [コードの表示] ボタンを選択します。 これにより、これまでの会話全体の背後にあるコードを再生できます。
プロンプト構造の概要
[コードの表示] からサンプルを調べると、会話が 3 つの異なるロール (system
、user
、assistant
) に分割されていることがわかります。 モデルにメッセージを送信するたびに、その時点までの会話履歴全体が再送信されます。 チャット入力候補 API を使用する場合、モデルには過去に送信した内容の真のメモリがないため、モデルが適切に応答できるようにコンテキストの会話履歴を提供します。
「チャット入力候補の攻略ガイド」では、新しいプロンプト構造とチャット入力候補モデルを効果的に使用する方法について詳しく説明しています。
モデルをデプロイする
エクスペリエンスに満足したら、[デプロイ] ボタンを選択して、ポータルから Web アプリを直接デプロイできます。
これにより、スタンドアロン Web アプリにデプロイするか、Copilot Studio (プレビュー) のコパイロットにデプロイするか (モデルで独自のデータを使用している場合) を選択するオプションが表示されます。
たとえば、Web アプリをデプロイすることを選択した場合は、次のようになります:
初めて Web アプリをデプロイする場合は、[新しい Web アプリを作成する] を選ぶ必要があります。 アプリの URL の一部となるアプリ名を決めます。 たとえば、「 https://<appname>.azurewebsites.net
」のように入力します。
発行されたアプリのサブスクリプション、リソース グループ、場所、価格プランを選びます。 既存のアプリを更新するには、[Publish to an existing web app](既存の Web アプリに発行する) を選び、ドロップダウン メニューから従来のアプリの名前を選びます。
Web アプリをデプロイする場合は、その使用に関する重要な考慮事項を参照してください。
リソースをクリーンアップする
Chat playground のテストが完了し、Azure OpenAI リソースをクリーン アップして削除したい場合は、リソースまたはリソース グループを削除できます。 リソース グループを削除すると、それに関連付けられている他のリソースも削除されます。
次のステップ
gpt-35-turbo
を使用して新しい モデルを操作する方法について学習します。- その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください
ソース コード | パッケージ (NuGet) | サンプル| 取得拡張生成 (RAG) エンタープライズ チャット テンプレート |
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- .NET 7 SDK
gpt-4o
モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。
Microsoft Entra ID の前提条件
Microsoft Entra ID で推奨されるキーレス認証の場合、次のことを行う必要があります。
- Microsoft Entra ID でのキーレス認証に使われる Azure CLI をインストールします。
- ユーザー アカウントに
Cognitive Services User
ロールを割り当てます。 Azure portal の [アクセス制御 (IAM)]>[ロールの割り当ての追加] で、ロールを割り当てることができます。
設定
chat-quickstart
新しいフォルダーを作成し、次のコマンドを使用してクイック スタート フォルダーに移動します。mkdir chat-quickstart && cd chat-quickstart
次のコマンドを使用して新しいコンソール アプリケーションを作成します。
dotnet new console
dotnet add package コマンドを使用して、OpenAI .NET クライアント ライブラリをインストールします。
dotnet add package Azure.AI.OpenAI --prerelease
Microsoft Entra ID を使用する推奨されるキーレス認証の場合、次のコマンドを使用して Azure.Identity パッケージをインストールします。
dotnet add package Azure.Identity
Microsoft Entra ID を使用する推奨されるキーレス認証の場合、次のコマンドを使用して Azure にサインインします。
az login
リソース情報の取得
Azure OpenAI リソースでアプリケーションを認証するには、次の情報を取得する必要があります。
変数名 | 価値 |
---|---|
AZURE_OPENAI_ENDPOINT |
この値は、Azure portal からリソースを調べる際の キーとエンドポイント セクションにあります。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
この値は、モデルのデプロイ時にデプロイに対して選択したカスタム名に対応します。 この値は、Azure portal の [リソース管理]>[モデル デプロイ] にあります。 |
OPENAI_API_VERSION |
API バージョンの詳細を参照してください。 コードでバージョンを変更することも、環境変数を使用することもできます。 |
クイック スタートを実行する
このクイックスタートのサンプル コードでは、推奨されるキーレス認証に Microsoft Entra ID を使用します。 API キーを使用する場合は、 DefaultAzureCredential
オブジェクトを AzureKeyCredential
オブジェクトに置き換えることができます。
AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential());
ストリーミングまたは非ストリーミングを使用して、チャットの完了を取得できます。 次のコード例は、両方のメソッドを使用する方法を示しています。 最初の例は非ストリーミング メソッドの使用方法を示し、2 番目の例はストリーミング メソッドの使用方法を示しています。
応答ストリーミングなし
クイック スタートを実行するには、次の手順に従います。
Program.cs
の内容を次のコードに置き換え、プレースホルダーの値を自分の値で更新します。using Azure; using Azure.Identity; using OpenAI.Assistants; using Azure.AI.OpenAI; using OpenAI.Chat; using static System.Environment; string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? "https://<your-resource-name>.openai.azure.com/"; string key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? "<your-key>"; // Use the recommended keyless credential instead of the AzureKeyCredential credential. AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential()); //AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key)); // This must match the custom deployment name you chose for your model ChatClient chatClient = openAIClient.GetChatClient("gpt-4o"); 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}");
次のコマンドでアプリケーションを実行します。
dotnet run
出力
Assistant: Arrr, ye be askin’ a fine question, matey! Aye, several Azure AI services support customer-managed keys (CMK)! This lets ye take the wheel and secure yer data with encryption keys stored in Azure Key Vault. Services such as Azure Machine Learning, Azure Cognitive Search, and others also offer CMK fer data protection. Always check the specific service's documentation fer the latest updates, as features tend to shift swifter than the tides, aye!
これは、結果を出力する前に、モデルが応答全体を生成するまで待機します。 または、応答を非同期的にストリーミングして結果を出力する場合は、Program.cs の内容を次の例のコードに置き換えることができます。
非同期ストリーミング
クイック スタートを実行するには、次の手順に従います。
Program.cs
の内容を次のコードに置き換え、プレースホルダーの値を自分の値で更新します。using Azure; using Azure.Identity; using OpenAI.Assistants; using Azure.AI.OpenAI; using OpenAI.Chat; using static System.Environment; string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? "https://<your-resource-name>.openai.azure.com/"; string key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? "<your-key>"; // Use the recommended keyless credential instead of the AzureKeyCredential credential. AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential()); //AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key)); // This must match the custom deployment name you chose for your model ChatClient chatClient = openAIClient.GetChatClient("gpt-4o"); 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); } }
次のコマンドでアプリケーションを実行します。
dotnet run
出力
Assistant: Arrr, ye be askin’ a fine question, matey! Aye, several Azure AI services support customer-managed keys (CMK)! This lets ye take the wheel and secure yer data with encryption keys stored in Azure Key Vault. Services such as Azure Machine Learning, Azure Cognitive Search, and others also offer CMK fer data protection. Always check the specific service's documentation fer the latest updates, as features tend to shift swifter than the tides, aye!
リソースをクリーンアップする
Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。
次のステップ
- .NET 用の独自のデータ サンプルを使用してチャットを開始する
- その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- Go 1.21.0 以降がローカルにインストールされていること。
gpt-4
モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。
Microsoft Entra ID の前提条件
Microsoft Entra ID で推奨されるキーレス認証の場合、次のことを行う必要があります。
- Microsoft Entra ID でのキーレス認証に使われる Azure CLI をインストールします。
- ユーザー アカウントに
Cognitive Services User
ロールを割り当てます。 Azure portal の [アクセス制御 (IAM)]>[ロールの割り当ての追加] で、ロールを割り当てることができます。
セットアップ
chat-quickstart
新しいフォルダーを作成し、次のコマンドを使用してクイック スタート フォルダーに移動します。mkdir chat-quickstart && cd chat-quickstart
Microsoft Entra ID を使用する推奨されるキーレス認証の場合、次のコマンドを使用して Azure にサインインします。
az login
リソース情報の取得
Azure OpenAI リソースでアプリケーションを認証するには、次の情報を取得する必要があります。
変数名 | 価値 |
---|---|
AZURE_OPENAI_ENDPOINT |
この値は、Azure portal からリソースを調べる際の キーとエンドポイント セクションにあります。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
この値は、モデルのデプロイ時にデプロイに対して選択したカスタム名に対応します。 この値は、Azure portal の [リソース管理]>[モデル デプロイ] にあります。 |
OPENAI_API_VERSION |
API バージョンの詳細を参照してください。 コードでバージョンを変更することも、環境変数を使用することもできます。 |
クイック スタートを実行する
このクイックスタートのサンプル コードでは、推奨されるキーレス認証に Microsoft Entra ID を使用します。 API キーを使用する場合は、 NewDefaultAzureCredential
の実装を NewKeyCredential
に置き換えることができます。
azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")
credential, err := azidentity.NewDefaultAzureCredential(nil)
client, err := azopenai.NewClient(azureOpenAIEndpoint, credential, nil)
サンプルを実行するには
chat_completions_keyless.go という名前の新しいファイルを作成します。 次のコードを chat_completions_keyless.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/azidentity" ) func main() { azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT") modelDeploymentID := "gpt-4o" maxTokens:= int32(400) credential, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Printf("ERROR: %s", err) return } client, err := azopenai.NewClient( azureOpenAIEndpoint, credential, nil) if err != nil { log.Printf("ERROR: %s", err) return } // This is a conversation in progress. // All messages, regardless of role, count against token usage for this API. messages := []azopenai.ChatRequestMessageClassification{ // System message sets the tone and rules of the conversation. &azopenai.ChatRequestSystemMessage{ Content: azopenai.NewChatRequestSystemMessageContent( "You are a helpful assistant."), }, // The user asks a question &azopenai.ChatRequestUserMessage{ Content: azopenai.NewChatRequestUserMessageContent( "Can I use honey as a substitute for sugar?"), }, // The reply would come back from the model. You // add it to the conversation so we can maintain context. &azopenai.ChatRequestAssistantMessage{ Content: azopenai.NewChatRequestAssistantMessageContent( "Yes, you can use use honey as a substitute for sugar."), }, // The user answers the question based on the latest reply. &azopenai.ChatRequestUserMessage{ Content: azopenai.NewChatRequestUserMessageContent( "What other ingredients can I use as a substitute for sugar?"), }, // From here you can keep iterating, sending responses back from the chat model. } gotReply := false resp, err := client.GetChatCompletions(context.TODO(), azopenai.ChatCompletionsOptions{ // This is a conversation in progress. // All messages count against token usage for this API. Messages: messages, DeploymentName: &modelDeploymentID, MaxTokens: &maxTokens, }, nil) if err != nil { // Implement 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 { // The conversation for this choice 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") } }
次のコマンドを実行して、新しい Go モジュールを作成します。
go mod init chat_completions_keyless.go
go mod tidy
を実行して、必要な依存関係をインストールします。go mod tidy
次のコマンドを実行してサンプルを実行します。
go run chat_completions_keyless.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]: There are many alternatives to sugar that you can use, depending on the type of recipe you’re making and your dietary needs or taste preferences. Here are some popular sugar substitutes:
---
### **Natural Sweeteners**
1. **Honey**
- Sweeter than sugar and adds moisture, with a distinct flavor.
- Substitution: Use ¾ cup honey for 1 cup sugar, and reduce the liquid in your recipe by 2 tablespoons. Lower the baking temperature by 25°F to prevent over-browning.
2. **Maple Syrup**
- Adds a rich, earthy sweetness with a hint of maple flavor.
- Substitution: Use ¾ cup syrup for 1 cup sugar. Reduce liquids by 3 tablespoons.
3. **Agave Nectar**
- Sweeter and milder than honey, it dissolves well in cold liquids.
- Substitution: Use ⅔ cup agave for 1 cup sugar. Reduce liquids in the recipe slightly.
4. **Molasses**
- A byproduct of sugar production with a robust, slightly bitter flavor.
- Substitution: Use 1 cup of molasses for 1 cup sugar. Reduce liquid by ¼ cup and consider combining it with other sweeteners due to its strong flavor.
5. **Coconut Sugar**
- Made from the sap of coconut palms, it has a rich, caramel-like flavor.
- Substitution: Use it in a 1:1 ratio for sugar.
6. **Date Sugar** (or Medjool Dates)
- Made from ground, dried dates, or blended into a puree, offering a rich, caramel taste.
- Substitution: Use 1:1 for sugar. Adjust liquid in recipes if needed.
---
### **Calorie-Free or Reduced-Calorie Sweeteners**
1. **Stevia**
- A natural sweetener derived from stevia leaves, hundreds of
Finish reason[0]: length
Received chat completions reply
リソースをクリーンアップする
Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。
次のステップ
その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください
ソース コード | 成果物 (Maven) | サンプル | 取得拡張生成 (RAG) エンタープライズ チャット テンプレート | IntelliJ IDEA
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- 最新バージョンの Java Development Kit (JDK)
- Gradle ビルド ツール、または別の依存関係マネージャー。
gpt-4
モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。
Microsoft Entra ID の前提条件
Microsoft Entra ID で推奨されるキーレス認証の場合、次のことを行う必要があります。
- Microsoft Entra ID でのキーレス認証に使われる Azure CLI をインストールします。
- ユーザー アカウントに
Cognitive Services User
ロールを割り当てます。 Azure portal の [アクセス制御 (IAM)]>[ロールの割り当ての追加] で、ロールを割り当てることができます。
設定
chat-quickstart
新しいフォルダーを作成し、次のコマンドを使用してクイック スタート フォルダーに移動します。mkdir chat-quickstart && cd chat-quickstart
Apache Maven をインストールします。 次に
mvn -v
を実行して、インストールが成功したことを確認します。プロジェクトのルートに新しい
pom.xml
ファイルを作成し、その中に以下のコードをコピーします:<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.azure.samples</groupId> <artifactId>quickstart-dall-e</artifactId> <version>1.0.0-SNAPSHOT</version> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>com.azure</groupId> <artifactId>azure-ai-openai</artifactId> <version>1.0.0-beta.10</version> </dependency> <dependency> <groupId>com.azure</groupId> <artifactId>azure-core</artifactId> <version>1.53.0</version> </dependency> <dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.15.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.9</version> </dependency> </dependencies> </project>
Azure OpenAI SDK と依存関係をインストールします。
mvn clean dependency:copy-dependencies
Microsoft Entra ID を使用する推奨されるキーレス認証の場合、次のコマンドを使用して Azure にサインインします。
az login
リソース情報の取得
Azure OpenAI リソースでアプリケーションを認証するには、次の情報を取得する必要があります。
変数名 | 価値 |
---|---|
AZURE_OPENAI_ENDPOINT |
この値は、Azure portal からリソースを調べる際の キーとエンドポイント セクションにあります。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
この値は、モデルのデプロイ時にデプロイに対して選択したカスタム名に対応します。 この値は、Azure portal の [リソース管理]>[モデル デプロイ] にあります。 |
OPENAI_API_VERSION |
API バージョンの詳細を参照してください。 コードでバージョンを変更することも、環境変数を使用することもできます。 |
アプリを実行する
このクイックスタートのサンプル コードでは、推奨されるキーレス認証に Microsoft Entra ID を使用します。 API キーを使用する場合は、 DefaultAzureCredential
オブジェクトを AzureKeyCredential
オブジェクトに置き換えることができます。
OpenAIClient client = new OpenAIClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
以下の手順に従って、音声認識のためのコンソール アプリケーションを作成します。
同じプロジェクト ルート ディレクトリ に Quickstart.java という名前の新しいファイルを作成します。
次のコードを Quickstart.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.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.identity.DefaultAzureCredentialBuilder; import com.azure.core.util.Configuration; import java.util.ArrayList; import java.util.List; public class QuickstartEntra { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT"); String deploymentOrModelId = "gpt-4o"; // Use the recommended keyless credential instead of the AzureKeyCredential credential. OpenAIClient client = new OpenAIClientBuilder() .endpoint(endpoint) .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); List<ChatRequestMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant.")); chatMessages.add(new ChatRequestUserMessage("Can I use honey as a substitute for sugar?")); chatMessages.add(new ChatRequestAssistantMessage("Yes, you can use use honey as a substitute for sugar.")); chatMessages.add(new ChatRequestUserMessage("What other ingredients can I use as a substitute for sugar?")); 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()); } }
新しいコンソール アプリケーションを実行してイメージを生成します。
javac Quickstart.java -cp ".;target\dependency\*" java -cp ".;target\dependency\*" Quickstart
出力
Model ID=chatcmpl-BDgC0Yr8YNhZFhLABQYfx6QfERsVO is created at 2025-03-21T23:35:52Z.
Index: 0, Chat Role: assistant.
Message:
If you're looking to replace sugar in cooking, baking, or beverages, there are several alternatives you can use depending on your tastes, dietary needs, and the recipe. Here's a list of common sugar substitutes:
### **Natural Sweeteners**
1. **Honey**
- Sweeter than sugar, so you may need less.
- Adds moisture to recipes.
- Adjust liquids and cooking temperature when baking to avoid over-browning.
2. **Maple Syrup**
- Provides a rich, complex flavor.
- Can be used in baking, beverages, and sauces.
- Reduce the liquid content slightly in recipes.
3. **Agave Syrup**
- Sweeter than sugar and has a mild flavor.
- Works well in drinks, smoothies, and desserts.
- Contains fructose, so use sparingly.
4. **Date Sugar or Date Paste**
- Made from dates, it's a whole-food sweetener with fiber and nutrients.
- Great for baked goods and smoothies.
- May darken recipes due to its color.
5. **Coconut Sugar**
- Similar in taste and texture to brown sugar.
- Less refined than white sugar.
- Slightly lower glycemic index, but still contains calories.
6. **Molasses**
- Dark, syrupy byproduct of sugar refining.
- Strong flavor; best for specific recipes like gingerbread or BBQ sauce.
### **Artificial Sweeteners**
1. **Stevia**
- Extracted from the leaves of the stevia plant.
- Virtually calorie-free and much sweeter than sugar.
- Available as liquid, powder, or granulated.
2. **Erythritol**
- A sugar alcohol with few calories and a clean, sweet taste.
- Doesn?t caramelize like sugar.
- Often blended with other sweeteners.
3. **Xylitol**
- A sugar alcohol similar to erythritol.
- Commonly used in baking and beverages.
- Toxic to pets (especially dogs), so handle carefully.
### **Whole Fruits**
1. **Mashed Bananas**
- Natural sweetness works well in baking.
- Adds moisture to recipes.
- Can replace sugar partially or fully depending on the dish.
2. **Applesauce (Unsweetened)**
- Adds sweetness and moisture to baked goods.
- Reduce other liquids in the recipe accordingly.
3. **Pureed Dates, Figs, or Prunes**
- Dense sweetness with added fiber and nutrients.
- Ideal for energy bars, smoothies, and baking.
### **Other Options**
1. **Brown Rice Syrup**
- Less sweet than sugar, with a mild flavor.
- Good for granola bars and baked goods.
2. **Yacon Syrup**
- Extracted from the root of the yacon plant.
- Sweet and rich in prebiotics.
- Best for raw recipes.
3. **Monk Fruit Sweetener**
- Natural sweetener derived from monk fruit.
- Often mixed with erythritol for easier use.
- Provides sweetness without calories.
### **Tips for Substitution**
- Sweeteners vary in sweetness, texture, and liquid content, so adjust recipes accordingly.
- When baking, reducing liquids or fats slightly may be necessary.
- Taste test when possible to ensure the sweetness level matches your preference.
Whether you're seeking healthier options, low-calorie substitutes, or simply alternatives for flavor, these sugar substitutes can work for a wide range of recipes!
Usage: number of prompt token is 60, number of completion token is 740, and number of total tokens in request and response is 800.
リソースをクリーンアップする
Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。
次のステップ
- Java 用の独自のデータ サンプルを使用してチャットを開始する
- その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください
ソース コード | 成果物 (Maven) | サンプル
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- 最新バージョンの Java Development Kit (JDK)
- Spring Boot CLI ツール
gpt-4
モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。 この例では、デプロイ名がモデル名gpt-4
と一致することを前提としています
セットアップ
キーとエンドポイントを取得する
Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントとキーが必要です。
変数名 | 価値 |
---|---|
ENDPOINT |
サービス エンドポイントは、Azure portal でリソースを調べるときに、[キーとエンドポイント] セクションで確認できます。 または、Azure AI Foundry ポータルの [デプロイ] ページからエンドポイントを見つけることができます。 エンドポイントの例: https://docs-test-001.openai.azure.com/ 。 |
API-KEY |
この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。 |
Azure portal でリソースに移動します。 [キーとエンドポイント] セクションは、[リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1
または KEY2
を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。
環境変数
キーとエンドポイントの永続的な環境変数を作成して割り当てます。
重要
API キーは慎重に使用してください。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。 API キーを使用する場合は、Azure Key Vault 内に安全に保存してください。 アプリで API キーを安全に使用する方法の詳細については、Azure Key Vault を使用した API キーに関するページを参照してください。
AI サービスのセキュリティの詳細については、「Azure AI サービスに対する要求の認証」を参照してください。
注意
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 アプリケーションを編集する
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>
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 サービスのセキュリティに関する記事をご覧ください。
プロジェクトのルート フォルダーに戻り、次のコマンドを使ってアプリを実行します:
./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) | サンプル
メモ
このガイドでは、Azure OpenAI を完全にサポートするようになった最新の OpenAI npm パッケージを使用します。 レガシ Azure OpenAI JavaScript SDK のコード サンプルをお探しの場合は、現時点ではまだこちらのリポジトリから入手可能です。
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- Node.js の LTS バージョン
- Azure CLI をローカル開発環境でのパスワードレス認証に使用する場合は、Azure CLI でサインインして必要なコンテキストを作成します。
gpt-4
シリーズ モデルがデプロイされた Azure OpenAI サービス リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。
Microsoft Entra ID の前提条件
Microsoft Entra ID で推奨されるキーレス認証の場合、次のことを行う必要があります。
- Microsoft Entra ID でのキーレス認証に使われる Azure CLI をインストールします。
- ユーザー アカウントに
Cognitive Services User
ロールを割り当てます。 Azure portal の [アクセス制御 (IAM)]>[ロールの割り当ての追加] で、ロールを割り当てることができます。
セットアップ
chat-quickstart
新しいフォルダーを作成し、次のコマンドを使用してクイック スタート フォルダーに移動します。mkdir chat-quickstart && cd chat-quickstart
次のコマンドで
package.json
を作成します。npm init -y
次を使用して JavaScript 用の OpenAI クライアント ライブラリをインストールします。
npm install openai
推奨されるパスワードレス認証は次のとおりです。
npm install @azure/identity
リソース情報の取得
Azure OpenAI リソースでアプリケーションを認証するには、次の情報を取得する必要があります。
変数名 | 価値 |
---|---|
AZURE_OPENAI_ENDPOINT |
この値は、Azure portal からリソースを調べる際の キーとエンドポイント セクションにあります。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
この値は、モデルのデプロイ時にデプロイに対して選択したカスタム名に対応します。 この値は、Azure portal の [リソース管理]>[モデル デプロイ] にあります。 |
OPENAI_API_VERSION |
API バージョンの詳細を参照してください。 コードでバージョンを変更することも、環境変数を使用することもできます。 |
注意事項
SDK で推奨されるキーレス認証を使用するには、AZURE_OPENAI_API_KEY
環境変数が設定されていないことを確認します。
サンプル アプリケーションを作成する
次のコードを使用して
index.js
ファイルを作成します。const { AzureOpenAI } = require("openai"); const { DefaultAzureCredential, getBearerTokenProvider } = require("@azure/identity"); // You will need to set these environment variables or edit the following values const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint"; const apiVersion = process.env.OPENAI_API_VERSION || "2024-05-01-preview"; const deployment = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "gpt-4o"; //This must match your deployment name. // keyless authentication const credential = new DefaultAzureCredential(); const scope = "https://cognitiveservices.azure.com/.default"; const azureADTokenProvider = getBearerTokenProvider(credential, scope); async function main() { const client = new AzureOpenAI({ endpoint, apiKey, azureADTokenProvider, deployment }); const result = await client.chat.completions.create({ 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: "", }); 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 にサインインします。
az login
JavaScript ファイルを実行します。
node index.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'
}
メモ
"エラーが発生しました。OpenAIError: apiKey
および azureADTokenProvider
引数は相互に排他的で、一度に渡すことができるのは 1 つだけです。" というエラーが発生した場合API キーの既存の環境変数をシステムから削除することが必要な場合があります。 Microsoft Entra ID コード サンプルで明示的に API キー環境変数を参照していなくても、このサンプルを実行するシステムにそれが存在していれば、このエラーは発生し続けます。
リソースをクリーンアップする
Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。
次のステップ
- Azure OpenAI の概要
- JavaScript 用の独自のデータ サンプルを使用してチャットを開始する
- その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください
ソース コード | パッケージ (npm) | サンプル
注
このガイドでは、Azure OpenAI を完全にサポートするようになった最新の OpenAI npm パッケージを使用します。 レガシ Azure OpenAI JavaScript SDK のコード サンプルをお探しの場合は、現時点ではまだこちらのリポジトリから入手可能です。
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- Node.js の LTS バージョン
- TypeScript
- Azure CLI をローカル開発環境でのパスワードレス認証に使用する場合は、Azure CLI でサインインして必要なコンテキストを作成します。
gpt-4
シリーズ モデルがデプロイされた Azure OpenAI サービス リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。
Microsoft Entra ID の前提条件
Microsoft Entra ID で推奨されるキーレス認証の場合、次のことを行う必要があります。
- Microsoft Entra ID でのキーレス認証に使われる Azure CLI をインストールします。
- ユーザー アカウントに
Cognitive Services User
ロールを割り当てます。 Azure portal の [アクセス制御 (IAM)]>[ロールの割り当ての追加] で、ロールを割り当てることができます。
セットアップ
chat-quickstart
新しいフォルダーを作成し、次のコマンドを使用してクイック スタート フォルダーに移動します。mkdir chat-quickstart && cd chat-quickstart
次のコマンドで
package.json
を作成します。npm init -y
次のコマンドを使用して、
package.json
を ECMAScript に更新します。npm pkg set type=module
次を使用して JavaScript 用の OpenAI クライアント ライブラリをインストールします。
npm install openai
推奨されるパスワードレス認証は次のとおりです。
npm install @azure/identity
リソース情報の取得
Azure OpenAI リソースでアプリケーションを認証するには、次の情報を取得する必要があります。
変数名 | 価値 |
---|---|
AZURE_OPENAI_ENDPOINT |
この値は、Azure portal からリソースを調べる際の キーとエンドポイント セクションにあります。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
この値は、モデルのデプロイ時にデプロイに対して選択したカスタム名に対応します。 この値は、Azure portal の [リソース管理]>[モデル デプロイ] にあります。 |
OPENAI_API_VERSION |
API バージョンの詳細を参照してください。 コードでバージョンを変更することも、環境変数を使用することもできます。 |
注意事項
SDK で推奨されるキーレス認証を使用するには、AZURE_OPENAI_API_KEY
環境変数が設定されていないことを確認します。
サンプル アプリケーションを作成する
次のコードを使用して
index.ts
ファイルを作成します。import { AzureOpenAI } from "openai"; import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity"; 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 || "Your endpoint"; // Required Azure OpenAI deployment name and API version const apiVersion = process.env.OPENAI_API_VERSION || "2024-08-01-preview"; const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "gpt-4o-mini"; //This must match your deployment name. // keyless authentication const credential = new DefaultAzureCredential(); const scope = "https://cognitiveservices.azure.com/.default"; const azureADTokenProvider = getBearerTokenProvider(credential, scope); function getClient(): AzureOpenAI { return new AzureOpenAI({ endpoint, azureADTokenProvider, 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); });
TypeScript コードをトランスパイルするために
tsconfig.json
ファイルを作成して、ECMAScript 向けの次のコードをコピーします。{ "compilerOptions": { "module": "NodeNext", "target": "ES2022", // Supports top-level await "moduleResolution": "NodeNext", "skipLibCheck": true, // Avoid type errors from node_modules "strict": true // Enable strict type-checking options }, "include": ["*.ts"] }
TypeScript から JavaScript にトランスパイルします。
tsc
次のコマンドを使用して、コードを実行します。
node index.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'
}
注
"エラーが発生しました。OpenAIError: apiKey
および azureADTokenProvider
引数は相互に排他的で、一度に渡すことができるのは 1 つだけです。" というエラーが発生した場合API キーの既存の環境変数をシステムから削除することが必要な場合があります。 Microsoft Entra ID コード サンプルで明示的に API キー環境変数を参照していなくても、このサンプルを実行するシステムにそれが存在していれば、このエラーは発生し続けます。
リソースをクリーンアップする
Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。
次のステップ
- Azure OpenAI の概要
- その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください
ライブラリ ソース コード | パッケージ (PyPI) | 取得拡張生成 (RAG) エンタープライズ チャット テンプレート |
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- Python 3.8 以降のバージョン。
- 次の Python ライブラリ: os。
gpt-35-turbo
またはgpt-4
モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。
設定
次を使用して、OpenAI Python クライアント ライブラリをインストールします。
pip install openai
注
このライブラリは、OpenAI によって保持されます。 このライブラリの最新の更新を追跡するには、リリース履歴を参照してください。
キーとエンドポイントを取得する
Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントとキーが必要です。
変数名 | 値 |
---|---|
ENDPOINT |
サービス エンドポイントは、Azure portal でリソースを調べるときに、[キーとエンドポイント] セクションで確認できます。 または、Azure AI Foundry ポータルの [デプロイ] ページからエンドポイントを見つけることができます。 エンドポイントの例: https://docs-test-001.openai.azure.com/ 。 |
API-KEY |
この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。 |
Azure portal でリソースに移動します。 [キーとエンドポイント] セクションは、[リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1
または KEY2
を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。
環境変数
キーとエンドポイントの永続的な環境変数を作成して割り当てます。
重要
Microsoft Entra 認証と Azure リソースのマネージド ID を併用して、クラウドで実行されるアプリケーションに資格情報を格納しないようにすることをお勧めします。
API キーは慎重に使用してください。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。 API キーを使用する場合は、Azure Key Vault に安全に保存し、キーを定期的にローテーションし、ロールベースのアクセス制御とネットワーク アクセス制限を使用して Azure Key Vault へのアクセスを制限してください。 アプリで 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 アプリケーションを作成する
quickstart.py という名前の新しい Python ファイルを作成します。 次に、任意のエディターまたは IDE で開きます。
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 サービスのセキュリティに関する記事をご覧ください。
クイック スタート ファイルに対して次の
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 リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。
次のステップ
- 攻略ガイドで、GPT-35-Turbo および GPT-4 モデルとやり取りする方法について確認します。
- Python 用の独自のデータ サンプルを使用してチャットを開始する
- その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください
前提条件
- Azure サブスクリプション。無料で作成できます。
gpt-35-turbo
またはgpt-4
モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。
設定
キーとエンドポイントを取得する
Azure OpenAI に対して正常に呼び出しを行うには、エンドポイントとキーが必要です。
変数名 | 価値 |
---|---|
ENDPOINT |
サービス エンドポイントは、Azure portal でリソースを調べるときに、[キーとエンドポイント] セクションで確認できます。 または、Azure AI Foundry ポータルの [デプロイ] ページからエンドポイントを見つけることができます。 エンドポイントの例: https://docs-test-001.openai.azure.com/ 。 |
API-KEY |
この値は、Azure portal からリソースを確認する際に、 [Keys & Endpoint](キーとエンドポイント) セクションで確認することができます。 KEY1 または KEY2 を使用できます。 |
Azure portal でリソースに移動します。 [キーとエンドポイント] セクションは、[リソース管理] セクションにあります。 エンドポイントとアクセス キーをコピーします。これらは、API 呼び出しを認証するために両方とも必要です。 KEY1
または KEY2
を使用できます。 常に 2 つのキーを用意しておくと、サービスを中断させることなく、キーのローテーションと再生成を安全に行うことができます。
環境変数
キーとエンドポイントの永続的な環境変数を作成して割り当てます。
重要
Microsoft Entra 認証と Azure リソースのマネージド ID を併用して、クラウドで実行されるアプリケーションに資格情報を格納しないようにすることをお勧めします。
API キーは慎重に使用してください。 API キーは、コード内に直接含めないようにし、絶対に公開しないでください。 API キーを使用する場合は、Azure Key Vault に安全に保存し、キーを定期的にローテーションし、ロールベースのアクセス制御とネットワーク アクセス制限を使用して Azure Key Vault へのアクセスを制限してください。 アプリで 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 リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。
次のステップ
- 攻略ガイドで、GPT-35-Turbo および GPT-4 モデルとやり取りする方法について確認します。
- その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- 最新バージョンの PowerShell 7 または Windows PowerShell 5.1 のいずれかを使用できます。
- モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。
gpt-4o
モデルがデプロイされた Azure OpenAI Service リソース。 モデル デプロイの詳細については、リソース デプロイ ガイドを参照してください。
Microsoft Entra ID の前提条件
Microsoft Entra ID で推奨されるキーレス認証の場合、次のことを行う必要があります。
- Microsoft Entra ID でのキーレス認証に使われる Azure CLI をインストールします。
- ユーザー アカウントに
Cognitive Services User
ロールを割り当てます。 Azure portal の [アクセス制御 (IAM)]>[ロールの割り当ての追加] で、ロールを割り当てることができます。
リソース情報の取得
Azure OpenAI リソースでアプリケーションを認証するには、次の情報を取得する必要があります。
変数名 | 価値 |
---|---|
AZURE_OPENAI_ENDPOINT |
この値は、Azure portal からリソースを調べる際の キーとエンドポイント セクションにあります。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
この値は、モデルのデプロイ時にデプロイに対して選択したカスタム名に対応します。 この値は、Azure portal の [リソース管理]>[モデル デプロイ] にあります。 |
OPENAI_API_VERSION |
API バージョンの詳細を参照してください。 コードでバージョンを変更することも、環境変数を使用することもできます。 |
新しい PowerShell スクリプトの作成
Microsoft Entra ID を使用する推奨されるキーレス認証の場合、次のコマンドを使用して Azure にサインインします。
az login
quickstart.ps1という名前の新しい PowerShell ファイル を 作成します。 次に、任意のエディターまたは IDE で開きます。
quickstart.ps1 の内容を次のコードで置き換えます。
engine
変数を、GPT-4o モデルのデプロイ時に選択したデプロイ名に設定する必要があります。 基になるモデル名と同じデプロイ名を選ばないと、モデル名の入力時にエラーが発生します。# Azure OpenAI metadata variables $openai = @{ api_base = $Env:AZURE_OPENAI_ENDPOINT api_version = '2024-10-21' # This can change in the future. name = 'gpt-4o' # The name you chose for your model deployment. } # Use the recommended keyless authentication via bearer token. $headers = [ordered]@{ #'api-key' = $Env:AZURE_OPENAI_API_KEY 'Authorization' = "Bearer $($Env:DEFAULT_AZURE_CREDENTIAL_TOKEN)" } # Completion text $messages = @() $messages += @{ role = 'system' content = 'You are a helpful assistant.' } $messages += @{ role = 'user' content = 'Can I use honey as a substitute for sugar?' } $messages += @{ role = 'assistant' content = 'Yes, you can use honey as a substitute for sugar.' } $messages += @{ role = 'user' content = 'What other ingredients can I use as a substitute for sugar?' } # 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 サービスのセキュリティに関する記事をご覧ください。
PowerShell を使用してスクリプトを実行します。 この例では、出力が切り捨てられないように、
-Depth
パラメーターを使用しています。./quickstart.ps1 | ConvertTo-Json -Depth 4
出力
スクリプトの出力は、Azure OpenAI サービスからの応答を含む JSON オブジェクトです。 出力は、次のようになります。
{
"choices": [
{
"content_filter_results": {
"custom_blocklists": {
"filtered": false
},
"hate": {
"filtered": false,
"severity": "safe"
},
"protected_material_code": {
"filtered": false,
"detected": false
},
"protected_material_text": {
"filtered": false,
"detected": false
},
"self_harm": {
"filtered": false,
"severity": "safe"
},
"sexual": {
"filtered": false,
"severity": "safe"
},
"violence": {
"filtered": false,
"severity": "safe"
}
},
"finish_reason": "stop",
"index": 0,
"logprobs": null,
"message": {
"content": "There are many alternatives to sugar that can be used in cooking and baking, depending on your dietary needs, taste preferences, and the type of recipe you're making. Here are some popular sugar substitutes:\n\n---\n\n### 1. **Natural Sweeteners**\n - **Maple Syrup**: A natural sweetener with a rich, distinct flavor. Use about ¾ cup of maple syrup for every cup of sugar, and reduce the liquid in the recipe slightly.\n - **Agave Nectar**: A liquid sweetener that’s sweeter than sugar. Use about ⅔ cup of agave nectar for each cup of sugar, and reduce the liquid in the recipe.\n - **Coconut Sugar**: Made from the sap of the coconut palm, it has a mild caramel flavor. Substitute in a 1:1 ratio for sugar.\n - **Molasses**: A by-product of sugar production, molasses is rich in flavor and best for recipes like gingerbread or barbecue sauce. Adjust quantities based on the recipe.\n - **Stevia (Natural)**: Derived from the stevia plant, it's intensely sweet and available in liquid or powder form. Use sparingly, as a little goes a long way.\n\n---\n\n### 2. **Fruit-Based Sweeteners**\n - **Ripe Bananas**: Mashed bananas work well for baking recipes like muffins or pancakes. Use about ½ cup of mashed banana for every cup of sugar and reduce the liquid slightly.\n - **Applesauce**: Unsweetened applesauce adds sweetness and moisture to baked goods. Replace sugar in a 1:1 ratio, but reduce the liquid by ¼ cup.\n - **Dates/Date Paste**: Blend dates with water to make a paste, which works well in recipes like energy bars, cakes, or smoothies. Use in a 1:1 ratio for sugar.\n - **Fruit Juices (e.g., orange juice)**: Can be used to impart natural sweetness but is best suited for specific recipes like marinades or desserts.\n\n---\n\n### 3. **Artificial and Low-Calorie Sweeteners**\n - **Erythritol**: A sugar alcohol with no calories. Substitute in equal amounts, but be careful as it may cause a cooling sensation in some recipes.\n - **Xylitol**: Another sugar alcohol, often used in gum and candies. It’s a 1:1 sugar substitute but may affect digestion if consumed in large quantities.\n - **Monk Fruit Sweetener**: A natural, calorie-free sweetener that’s significantly sweeter than sugar. Follow the product packaging for exact substitution measurements.\n - **Aspartame, Sucralose, or Saccharin** (Artificial Sweeteners): Often used for calorie reduction in beverages or desserts. Follow package instructions for substitution.\n\n---\n\n### 4. **Other Natural Alternatives**\n - **Brown Rice Syrup**: A sticky, malt-flavored syrup used in granolas or desserts. Substitute 1 ¼ cups of brown rice syrup for every cup of sugar.\n - **Barley Malt Syrup**: A thick, dark syrup with a distinct flavor. It can replace sugar but might require recipe adjustments due to its strong taste.\n - **Yacon Syrup**: Made from the root of the yacon plant, it’s similar in texture to molasses and has a mild sweetness.\n\n---\n\n### General Tips for Substituting Sugar:\n- **Adjust Liquids:** Many liquid sweeteners (like honey or maple syrup) require reducing the liquid in the recipe to maintain texture.\n- **Baking Powder Adjustment:** If replacing sugar with an acidic sweetener (e.g., honey or molasses), you might need to add a little baking soda to neutralize acidity.\n- **Flavor Changes:** Some substitutes, like molasses or coconut sugar, have distinct flavors that can influence the taste of your recipe.\n- **Browning:** Sugar contributes to caramelization and browning in baked goods. Some alternatives may yield lighter-colored results.\n\nBy trying out different substitutes, you can find what works best for your recipes!",
"refusal": null,
"role": "assistant"
}
}
],
"created": 1742602230,
"id": "chatcmpl-BDgjWjEboQ0z6r58pvSBgH842JbB2",
"model": "gpt-4o-2024-11-20",
"object": "chat.completion",
"prompt_filter_results": [
{
"prompt_index": 0,
"content_filter_results": {
"custom_blocklists": {
"filtered": false
},
"hate": {
"filtered": false,
"severity": "safe"
},
"jailbreak": {
"filtered": false,
"detected": false
},
"self_harm": {
"filtered": false,
"severity": "safe"
},
"sexual": {
"filtered": false,
"severity": "safe"
},
"violence": {
"filtered": false,
"severity": "safe"
}
}
}
],
"system_fingerprint": "fp_a42ed5ff0c",
"usage": {
"completion_tokens": 836,
"completion_tokens_details": {
"accepted_prediction_tokens": 0,
"audio_tokens": 0,
"reasoning_tokens": 0,
"rejected_prediction_tokens": 0
},
"prompt_tokens": 60,
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 0
},
"total_tokens": 896
}
}
注釈
未加工の出力を表示する場合は、 ConvertTo-Json
の手順をスキップできます。
./quickstart.ps1
出力は次のようになります。
choices : {@{content_filter_results=; finish_reason=stop; index=0; logprobs=; message=}}
created : 1742602727
id : chatcmpl-BDgrX0BF38mZuszFeyU1NKZSiRpSX
model : gpt-4o-2024-11-20
object : chat.completion
prompt_filter_results : {@{prompt_index=0; content_filter_results=}}
system_fingerprint : fp_b705f0c291
usage : @{completion_tokens=944; completion_tokens_details=; prompt_tokens=60; prompt_tokens_details=; total_tokens=1004}
powershell.ps1 スクリプトの内容を編集して、オブジェクト全体または特定のプロパティを返すことができます。 たとえば、返されたテキストを返すには、スクリプトの最後の行 (return $response
) を次のように置き換えることができます。
return $response.choices.message.content
次に、スクリプトをもう一度実行します。
./quickstart.ps1
出力は次のようになります。
There are several ingredients that can be used as substitutes for sugar, depending on the recipe and your dietary preferences. Here are some popular options:
---
### **Natural Sweeteners**
1. **Maple Syrup**
- Flavor: Rich and slightly caramel-like.
- Use: Works well in baking, sauces, oatmeal, and beverages.
- Substitution: Replace sugar in a 1:1 ratio but reduce the liquid in your recipe by about 3 tablespoons per cup of maple syrup.
2. **Agave Nectar**
- Flavor: Mildly sweet, less pronounced than honey.
- Use: Good for beverages, desserts, and dressings.
- Substitution: Use about 2/3 cup of agave nectar for every 1 cup of sugar, and reduce other liquids slightly.
3. **Molasses**
- Flavor: Strong, earthy, and slightly bitter.
- Use: Perfect for gingerbread, cookies, and marinades.
- Substitution: Replace sugar in equal amounts, but adjust for the strong flavor.
4. **Date Paste**
- Flavor: Naturally sweet with hints of caramel.
- Use: Works well in energy bars, smoothies, or baking recipes.
- Substitution: Blend pitted dates with water to create paste (about 1:1 ratio). Use equal amounts in recipes.
5. **Coconut Sugar**
- Flavor: Similar to brown sugar, mildly caramel-like.
- Use: Excellent for baking.
- Substitution: Replace sugar in a 1:1 ratio.
---
### **Low-Calorie Sweeteners**
1. **Stevia**
- Flavor: Very sweet but can have a slightly bitter aftertaste.
- Use: Works in beverages, desserts, and some baked goods.
- Substitution: Use less—around 1 teaspoon of liquid stevia or 1/2 teaspoon stevia powder for 1 cup of sugar. Check the package for exact conversion.
2. **Erythritol**
- Flavor: Similar to sugar but less sweet.
- Use: Perfect for baked goods and beverages.
- Substitution: Replace sugar using a 1:1 ratio, though you may need to adjust for less sweetness.
3. **Xylitol**
- Flavor: Similar to sugar.
- Use: Great for baking or cooking but avoid using it for recipes requiring caramelization.
- Substitution: Use a 1:1 ratio.
---
### **Fruit-Based Sweeteners**
1. **Mashed Bananas**
- Flavor: Sweet with a fruity note.
- Use: Great for muffins, cakes, and pancakes.
- Substitution: Use 1 cup mashed banana for 1 cup sugar, but reduce liquid slightly in the recipe.
2. **Applesauce**
- Flavor: Mildly sweet.
- Use: Excellent for baked goods like muffins or cookies.
- Substitution: Replace sugar 1:1, but reduce other liquids slightly.
3. **Fruit Juice Concentrates**
- Flavor: Sweet with fruity undertones.
- Use: Works well in marinades, sauces, and desserts.
- Substitution: Use equal amounts, but adjust liquid content.
---
### **Minimal-Processing Sugars**
1. **Raw Honey**
- Flavor: Sweet with floral undertones.
- Use: Good for baked goods and beverages.
- Substitution: Replace sugar in a 1:1 ratio, but reduce other liquids slightly.
2. **Brown Rice Syrup**
- Flavor: Mildly sweet with a hint of nuttiness.
- Use: Suitable for baked goods and granola bars.
- Substitution: Use 1-1/4 cups of syrup for 1 cup of sugar, and decrease liquid in the recipe.
---
### Tips for Substitution:
- Adjust for sweetness: Some substitutes are sweeter or less sweet than sugar, so amounts may need tweaking.
- Baking considerations: Sugar affects texture, browning, and moisture. If you replace it, you may need to experiment to get the desired result.
- Liquid adjustments: Many natural sweeteners are liquid, so you’ll often need to reduce the amount of liquid in your recipe.
Would you like help deciding the best substitute for a specific recipe?
メッセージの構造について
GPT-4 モデルは、会話として書式設定された入力を操作するように最適化されています。 messages
変数は、システム、ユーザー、アシスタントによって示された会話内のさまざまなロールを持つディクショナリの配列を渡します。 システム メッセージを使用して、モデルの応答方法に関するコンテキストまたは指示を含めることで、モデルを準備できます。
GPT-4 のハウツー ガイドでは、これらのモデルと通信するためのオプションについて詳しく説明します。
リソースをクリーンアップする
Azure OpenAI リソースをクリーンアップして削除したい場合は、リソースを削除できます。 リソースを削除する前に、まずデプロイされたモデルを削除する必要があります。
次のステップ
- GPT-4 モデルを操作する方法の詳細については、 ハウツー ガイドを参照してください。
- その他の例については、Azure OpenAI サンプルの GitHub リポジトリを参照してください