使用本文開始使用 Azure OpenAI。
必要條件
- Azure 訂用帳戶 - 建立免費帳戶。
- 已部署
gpt-4o
或gpt-4o-mini
模型的 Azure OpenAI 服務資源。 建議您使用標準或全域標準模型 部署類型 進行初始探索。 如需模型部署的詳細資訊,請參閱資源部署指南。
移至 Azure AI Foundry
流覽至 Azure AI Foundry 入口網站 ,並使用可存取 Azure OpenAI 資源的認證登入。 在登入工作流程期間 (或之後),選取適當的目錄、Azure 訂用帳戶和 Azure OpenAI 資源。
從 Azure AI Foundry,選取 [聊天遊樂場]。
遊樂場
透過 Azure AI Foundry Chat 遊樂場,開始使用無程式代碼方法探索 Azure OpenAI 服務功能。 您可以透過此頁面,快速逐一查看並實驗各種功能。
設定
您可以使用 *[提示範例] 下拉式清單選取一些預先載入的 [系統訊息] 範例,以開始使用。
[系統訊息] 能為模型提供其行為的相關指示,以及其在產生回應時應該參考的任何內容。 您可以描述助理的特質、告訴其應該和不應該回答的內容,以及告訴其設定回應的格式。
使用聊天遊樂場時,您可以隨時選取 [檢視程式碼],以查看根據您目前的聊天工作階段和設定選取項目所預先填入的 Python、curl 和 json 程式碼範例。 然後,您可以取得此程式碼並撰寫應用程式,以完成您目前正在使用遊樂場執行的相同工作。
聊天工作階段
選取 [輸入] 按鈕或選取向右鍵圖示,會將輸入的文字傳送至聊天完成 API,而結果會傳回至文字方塊。
選取 [清除聊天] 按鈕,以刪除目前的交談歷程記錄。
金鑰設定
名稱 | 說明 |
---|---|
部署 | 與特定模型相關聯的部署名稱。 |
新增您的資料 | |
參數 | 改變模型回應的自訂參數。 當您開始使用時,我們建議針對大部分參數使用預設值 |
溫度 | 控制隨機性。 降低溫度表示模型會產生更多重複的確定性回應。 提升溫度會產生更多非預期或令人意外的回應。 您可試著調整溫度或 Top P,但不可同時調整兩者。 |
最大回應 (語彙基元) | 設定每個模型回應的權杖數目限制。 最新模型上的 API 支援在提示 (包括系統訊息、範例、訊息歷程記錄,以及使用者查詢) 和模型的回應之間共用最多 128,000 個語彙基元。 每個語彙基元大約是一般英文文字的四個字元。 |
頂端 p | 類似於溫度,此設定能控制隨機性,但會使用不同的方法。 降低 Top P 會將模型的語彙基元選取範圍縮小至可能性較高的內容。 增加 Top P 會讓模型從所有可能性的語彙基元中進行挑選。 您可試著調整溫度或 Top P,但不可同時調整兩者。 |
停止序列 | 停止序列會使模型在所需的時間點結束其回應。 模型回應會在指定的序列之前結束,因此不會包含停止序列文字。 針對 GPT-35-Turbo,使用 <|im_end|> 可確保模型回應不會產生後續的使用者查詢。 您可以包括多達四個停止序列。 |
檢視程式碼
嘗試與模型聊天後,請選取 [</> 檢視程式碼] 按鈕。 這會讓您重新執行到目前為止整個交談背後的程式碼:
了解提示結構
如果您檢查檢視程式碼中的範例,您會發現交談分成三個不同的角色 system
、user
、assistant
。 每次將模型訊息傳送到該點為止的整個交談記錄都會被重新傳送。 使用聊天完成 API 時,模型不會真正記住您過去傳送的內容,因此您可以提供內容的交談記錄,讓模型能夠正確回應。
聊天完成操作指南提供新提示結構的深入介紹,以及如何有效地使用聊天完成模型。
部署模型
一旦您對體驗感到滿意,您可以選取 [部署至] 按鈕,直接從入口網站部署Web應用程式。
這可讓您選擇將模型部署至獨立的 Web 應用程式,或部署為 Copilot Studio (預覽) 中的一個副手 (若您在模型上使用自己的資料)。
例如,如果您選擇部署 Web 應用程式:
第一次部署 Web 應用程式時,您應該選取 [建立新的 Web 應用程式]。 選擇應用程式的名稱,其會成為應用程式 URL 的一部分。 例如: https://<appname>.azurewebsites.net
。
選取已發佈應用程式的訂用帳戶、資源群組、位置和定價方案。 若要更新現有的應用程式,請選取 [發佈到現有的 Web 應用程式],然後從下拉式功能表中選擇先前應用程式的名稱。
如果您選擇部署 Web 應用程式,請參閱使用方式的重要考量。
清除資源
測試聊天遊樂場之後,如果您想要清除並移除 Azure OpenAI 資源,可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。
下一步
- 請參閱
gpt-35-turbo
,深入了解如何使用新的 模型。 - 如需更多範例,請參閱 Azure OpenAI 範例 GitHub 存放庫 (英文)
原始程式碼 | 套件 (NuGet) | 範例| 擷取擴增生成 (RAG) 企業聊天範本 |
必要條件
- Azure 訂用帳戶 - 建立免費帳戶
- .NET 7 SDK
- 已部署
gpt-4o
模型的 Azure OpenAI 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南。
Microsoft Entra ID 必要條件
針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:
- 使用 Microsoft Entra ID 安裝用於無密鑰驗證的 Azure CLI。
- 將
Cognitive Services User
角色指派給您的使用者帳戶。 您可以在存取控制 (IAM)>下的 [Azure 入口網站 中指派角色。
設定
建立新的資料夾
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 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理>下找到此值。 |
OPENAI_API_VERSION |
深入瞭解 API 版本。 您可以在程式代碼中變更版本,或使用環境變數。 |
執行快速入門
本快速入門中的範例程式代碼會針對建議的無密鑰驗證使用 Microsoft Entra 識別碼。 如果您想要使用 API 金鑰,可以將 DefaultAzureCredential
物件取代為 AzureKeyCredential
物件。
AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential());
您可以使用串流或非串流來獲取聊天結果。 下列程式代碼範例示範如何使用這兩種方法。 第一個範例示範如何使用非串流方法,第二個範例示範如何使用串流方法。
沒有回應串流
若要執行快速啟動,請遵循下列步驟:
將
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 存放庫
必要條件
Microsoft Entra ID 必要條件
針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:
- 使用 Microsoft Entra ID 安裝用於無密鑰驗證的 Azure CLI。
- 將
Cognitive Services User
角色指派給您的使用者帳戶。 您可以在存取控制 (IAM)>下的 [Azure 入口網站 中指派角色。
設定
建立新的資料夾
chat-quickstart
,並使用下列命令移至快速入門資料夾:mkdir chat-quickstart && cd chat-quickstart
如需使用 Microsoft Entra ID 的建議 無密鑰驗證,請使用下列命令登入 Azure:
az login
擷取資源資訊
您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:
變數名稱 | 值 |
---|---|
AZURE_OPENAI_ENDPOINT |
在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理>下找到此值。 |
OPENAI_API_VERSION |
深入瞭解 API 版本。 您可以在程式代碼中變更版本,或使用環境變數。 |
執行快速入門
本快速入門中的範例程式代碼會針對建議的無密鑰驗證使用 Microsoft Entra 識別碼。 如果您要使用 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 訂用帳戶 - 建立免費帳戶
- Gradle 建置工具,或其他相依性管理員。
- 已部署
gpt-4
模型的 Azure OpenAI 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南。
Microsoft Entra ID 必要條件
針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:
- 使用 Microsoft Entra ID 安裝用於無密鑰驗證的 Azure CLI。
- 將
Cognitive Services User
角色指派給您的使用者帳戶。 您可以在存取控制 (IAM)>下的 [Azure 入口網站 中指派角色。
設定
建立新的資料夾
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 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理>下找到此值。 |
OPENAI_API_VERSION |
深入瞭解 API 版本。 您可以在程式代碼中變更版本,或使用環境變數。 |
執行應用程式
本快速入門中的範例程式代碼會針對建議的無密鑰驗證使用 Microsoft Entra 識別碼。 如果您想要使用 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 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南。 此範例假設部署名稱符合模型名稱gpt-4
設定
擷取金鑰和端點
若要成功對 Azure OpenAI 進行呼叫,您需要端點和金鑰。
變數名稱 | 值 |
---|---|
ENDPOINT |
檢查來自 Azure 入口網站 的資源時,可以在 [金鑰與端點] 區段中找到服務端點。 或者,您也可以透過 Azure AI Foundry 入口網站中的 [部署 ] 頁面來尋找端點。 範例端點為:https://docs-test-001.openai.azure.com/ 。 |
API-KEY |
從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1 或 KEY2 。 |
移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [金鑰和端點] 區段。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1
或 KEY2
。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。
環境變數
為您的金鑰和端點建立及指派永續性環境變數。
重要
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果您使用 API 金鑰,請將它安全地儲存在 Azure 金鑰保存庫。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱搭配 Azure 金鑰保存庫 的 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
命令。 此命令會為您的 Spring 專案建立標準目錄結構 (包括主要 JAVA 類別來源檔案),以及用於管理 Maven 型專案的 pom.xml 檔案。
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.3.4</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> <spring-ai.version>1.0.0-M5</spring-ai.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-bom</artifactId> <version>${spring-ai.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project>
使用慣用的編輯器或 IDE,從 src/main/java/com/example/aichatdemo 資料夾開啟 AiChatApplication.java,並貼上下列程式碼:
package com.example.aichatdemo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.chat.client.ChatClient; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class AiChatApplication { private static final Logger log = LoggerFactory.getLogger(AiChatApplication.class); public static void main(String[] args) { SpringApplication.run(AiChatApplication.class, args); } @Bean CommandLineRunner commandLineRunner(ChatClient.Builder builder) { return args -> { var chatClient = builder.build(); log.info("Sending chat prompts to AI service. One moment please..."); String response = chatClient.prompt() .user("What was Microsoft's original internal codename for the project that eventually became Azure?") .call() .content(); log.info("Response: {}", response); }; } }
重要
在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需有關認證安全性的詳細資訊,請參閱 Azure AI 服務安全性一文。
瀏覽回專案根資料夾,並使用下列命令執行應用程式:
./mvnw spring-boot:run
輸出
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.3.4)
2025-03-14T13:35:30.145-04:00 INFO 93252 --- [AIChat] [ main] c.example.aichatdemo.AiChatApplication : Starting AiChatApplication using Java 23.0.2 with PID 93252 (/Users/vega/dev/msft/spring-ai-samples/ai-chat-demo/target/classes started by vega in /Users/vega/dev/msft/spring-ai-samples/ai-chat-demo)
2025-03-14T13:35:30.146-04:00 INFO 93252 --- [AIChat] [ main] c.example.aichatdemo.AiChatApplication : No active profile set, falling back to 1 default profile: "default"
2025-03-14T13:35:30.500-04:00 INFO 93252 --- [AIChat] [ main] c.example.aichatdemo.AiChatApplication : Started AiChatApplication in 0.445 seconds (process running for 0.633)
2025-03-14T13:35:30.501-04:00 INFO 93252 --- [AIChat] [ main] c.example.aichatdemo.AiChatApplication : Sending chat prompts to AI service. One moment please...
2025-03-14T13:35:31.950-04:00 INFO 93252 --- [AIChat] [ main] c.example.aichatdemo.AiChatApplication : Response: Microsoft's original internal codename for the project that eventually became Azure was "Project Red Dog." This initiative ultimately led to the development and launch of the Microsoft Azure cloud computing platform.
清除資源
如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。
下一步
如需更多範例,請參閱 Azure OpenAI 範例 GitHub 存放庫
原始程式碼 (英文) | 套件 (npm) (英文) | 範例 (英文)
注意
本指南使用 最新的 OpenAI npm 套件 ,現在完全支援 Azure OpenAI。 如果您要尋找舊版 Azure OpenAI JavaScript SDK 的程式代碼範例,這些範例目前仍 可在此存放庫中取得。
必要條件
- Azure 訂用帳戶 - 建立免費帳戶
- LTS 版本的 Node.js
- Azure CLI 用於本地開發環境中的無密碼驗證,請使用 Azure CLI 登入以建立必要內容。
- 已部署數列模型的 Azure OpenAI 服務資源
gpt-4
。 如需模型部署的詳細資訊,請參閱資源部署指南。
Microsoft Entra ID 必要條件
針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:
- 使用 Microsoft Entra ID 安裝用於無密鑰驗證的 Azure CLI。
- 將
Cognitive Services User
角色指派給您的使用者帳戶。 您可以在存取控制 (IAM)>下的 [Azure 入口網站 中指派角色。
設定
建立新的資料夾
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 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理>下找到此值。 |
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
自變數互斥;一次只能傳遞一個。 您可能需要從系統移除 API 金鑰的預先存在環境變數。 即使Microsoft Entra ID 程式代碼範例並未明確參考 API 金鑰環境變數,但如果系統存在執行此範例的實例,仍會產生此錯誤。
清除資源
如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。
下一步
原始程式碼 (英文) | 套件 (npm) (英文) | 範例 (英文)
注意
本指南使用 最新的 OpenAI npm 套件 ,現在完全支援 Azure OpenAI。 如果您要尋找舊版 Azure OpenAI JavaScript SDK 的程式代碼範例,這些範例目前仍 可在此存放庫中取得。
必要條件
- Azure 訂用帳戶 - 建立免費帳戶
- LTS 版本的 Node.js
- TypeScript
- Azure CLI 用於本地開發環境中的無密碼驗證,請使用 Azure CLI 登入以建立必要內容。
- 部署於 Azure OpenAI 服務資源中的
gpt-4
系列模型。 如需模型部署的詳細資訊,請參閱資源部署指南。
Microsoft Entra ID 必要條件
針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:
- 使用 Microsoft Entra ID 安裝用於無密鑰驗證的 Azure CLI。
- 將
Cognitive Services User
角色指派給您的使用者帳戶。 您可以在存取控制 (IAM)>下的 [Azure 入口網站 中指派角色。
設定
建立新的資料夾
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 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理>下找到此值。 |
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); });
建立檔案
tsconfig.json
以轉譯 TypeScript 程式代碼,並複製 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
自變數互斥;一次只能傳遞一個。 您可能需要從系統移除 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 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南。
設定
使用下列項目安裝 OpenAI Python 用戶端程式庫:
pip install openai
注意
程式庫是由 OpenAI 進行維護。 參照版本歷程記錄來追蹤程式庫的最新更新。
擷取金鑰和端點
若要成功對 Azure OpenAI 進行呼叫,您需要端點和金鑰。
變數名稱 | 值 |
---|---|
ENDPOINT |
檢查來自 Azure 入口網站 的資源時,可以在 [金鑰與端點] 區段中找到服務端點。 或者,您也可以透過 Azure AI Foundry 入口網站中的 [部署 ] 頁面來尋找端點。 範例端點為:https://docs-test-001.openai.azure.com/ 。 |
API-KEY |
從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1 或 KEY2 。 |
移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [金鑰和端點] 區段。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1
或 KEY2
。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。
環境變數
為您的金鑰和端點建立及指派永續性環境變數。
重要
我們建議使用適用於 Azure 資源的受控識別搭配 Microsoft Entra ID 驗證,以避免使用在雲端執行的應用程式儲存認證。
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果使用 API 金鑰,請將密鑰安全地儲存在 Azure 金鑰保存庫、定期輪替密鑰,並使用角色型存取控制和網路存取限制來限制對 Azure 金鑰保存庫 的存取。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱搭配 Azure 金鑰保存庫 的 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 的內容取代為下列程式碼。
當您部署 GPT-3.5-Turbo 或 GPT-4 模型時,您需要將 model
變數設定為您選擇的部署名稱。 除非您選擇與基礎模型名稱相同的部署名稱,否則輸入模型名稱會導致錯誤。
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 存放庫
REST API 規格 | (英文)
必要條件
設定
擷取金鑰和端點
若要成功對 Azure OpenAI 進行呼叫,您需要端點和金鑰。
變數名稱 | 值 |
---|---|
ENDPOINT |
檢查來自 Azure 入口網站 的資源時,可以在 [金鑰與端點] 區段中找到服務端點。 或者,您也可以透過 Azure AI Foundry 入口網站中的 [部署 ] 頁面來尋找端點。 範例端點為:https://docs-test-001.openai.azure.com/ 。 |
API-KEY |
從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1 或 KEY2 。 |
移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [金鑰和端點] 區段。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1
或 KEY2
。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。
環境變數
為您的金鑰和端點建立及指派永續性環境變數。
重要
我們建議使用適用於 Azure 資源的受控識別搭配 Microsoft Entra ID 驗證,以避免使用在雲端執行的應用程式儲存認證。
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果使用 API 金鑰,請將密鑰安全地儲存在 Azure 金鑰保存庫、定期輪替密鑰,並使用角色型存取控制和網路存取限制來限制對 Azure 金鑰保存庫 的存取。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱搭配 Azure 金鑰保存庫 的 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 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南。
- 已部署
gpt-4o
模型的 Azure OpenAI 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南。
Microsoft Entra ID 必要條件
針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:
- 使用 Microsoft Entra ID 安裝用於無密鑰驗證的 Azure CLI。
- 將
Cognitive Services User
角色指派給您的使用者帳戶。 您可以在存取控制 (IAM)>下的 [Azure 入口網站 中指派角色。
擷取資源資訊
您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:
變數名稱 | 值 |
---|---|
AZURE_OPENAI_ENDPOINT |
在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理>下找到此值。 |
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 Vault 的 PowerShell 祕密管理。 如需有關認證安全性的詳細資訊,請參閱 Azure AI 服務安全性一文。
使用 PowerShell 執行腳本。 在此範例中
-Depth
,我們使用 參數來確保不會截斷輸出。./quickstart.ps1 | ConvertTo-Json -Depth 4
輸出
腳本的輸出是 JSON 物件,其中包含來自 Azure OpenAI 服務的回應。 輸出看起來類似以下內容:
{
"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 存放庫