이 문서를 사용하여 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 기능 탐색을 시작합니다. 이 페이지에서 쉽게 기능을 반복하고 실험해 볼 수 있습니다.
설치 프로그램
*프롬프트 샘플 드롭다운을 사용하여 몇 가지 미리 로드된 시스템 메시지 예를 선택하여 시작할 수 있습니다.
시스템 메시지는 동작하는 방법과 응답을 생성할 때 참조해야 하는 컨텍스트에 대한 지침을 모델에 제공합니다. 도우미의 성격을 설명하고, 대답해야 하는 것과 대답해서는 안 되는 것을 말하고, 응답의 형식을 지정하는 방법을 말할 수 있습니다.
채팅 플레이그라운드를 사용하는 동안 언제든지 코드 보기를 선택하여 현재 채팅 세션 및 설정 선택 사항에 따라 미리 채워진 Python, curl 및 json 코드 샘플을 볼 수 있습니다. 그런 다음, 이 코드를 사용하고 애플리케이션을 작성하여 현재 플레이그라운드에서 수행하고 있는 것과 동일한 작업을 완료할 수 있습니다.
채팅 세션
Enter 단추를 선택하거나 오른쪽 화살표 아이콘을 선택하면 입력한 텍스트가 채팅 완료 API로 전송되고 결과는 텍스트 상자로 다시 반환됩니다.
채팅 지우기 단추를 선택하여 현재 대화 기록을 삭제합니다.
키 설정
이름 | 설명 |
---|---|
배포 | 특정 모델과 연결된 배포 이름입니다. |
데이터 추가 | |
매개 변수 | 모델 응답을 변경하는 사용자 지정 매개 변수. 시작할 때는 대부분의 매개 변수에 대해 기본값을 사용하는 것이 좋습니다. |
온도 | 임의성을 제어합니다. 온도를 낮추면 모델이 더 반복적이고 결정된 응답을 생성합니다. 온도를 높이면 예기치 않거나 창의적인 응답이 발생합니다. 온도 또는 상위 P를 조정하되 둘 다 조정하지는 마세요. |
최대 응답(토큰) | 모델 응답당 토큰 수 한도를 설정합니다. 최신 모델의 API는 프롬프트(시스템 메시지, 예, 메시지 기록, 사용자 쿼리 포함)와 모델의 응답 간에 공유되는 최대 128,000개의 토큰을 지원합니다. 한 토큰은 일반적인 영어 텍스트의 경우 약 4자입니다. |
위쪽 p | 온도와 마찬가지로 임의성을 제어하지만 다른 방법을 사용합니다. 상위 P를 낮추면 모델의 토큰 선택이 유사 토큰으로 좁혀지게 됩니다. 상위 P를 늘리면 모델이 가능성이 높고 낮은 토큰 중에서 선택할 수 있습니다. 온도 또는 상위 P를 조정하되 둘 다 조정하지는 마세요. |
중지 시퀀스 | 중지 시퀀스는 모델이 원하는 지점에서 응답을 종료하도록 합니다. 모델 응답은 지정된 시퀀스 이전에 종료되므로 중지 시퀀스 텍스트가 포함되지 않습니다. GPT-35-Turbo의 경우 <|im_end|> 를 사용하면 모델 응답이 후속 사용자 쿼리를 생성하지 않습니다. 최대 4개의 중지 시퀀스를 포함할 수 있습니다. |
코드 보기
모델과 채팅을 시도해 본 후 </> 코드 보기 단추를 선택합니다. 이렇게 하면 지금까지의 대화에 대한 코드를 다시 볼 수 있습니다.
프롬프트 구조 이해
코드 보기의 샘플을 살펴보면 대화가 system
, user
, assistant
의 세 가지 역할로 구분되어 있는 것을 알 수 있습니다. 모델에게 메시지를 보낼 때마다 해당 지점까지의 전체 대화 기록이 다시 전송됩니다. 채팅 완료 API를 사용하면 모델은 과거에 보낸 내용을 실제로 기억하지 못하므로 모델이 적절하게 응답할 수 있도록 컨텍스트를 제공하는 대화 기록을 제공해야 합니다.
채팅 완료 사용 방법 가이드는 새 프롬프트 구조에 대한 심층적인 소개와 채팅 완료 모델을 효과적으로 사용하는 방법을 제공합니다.
모델 배포
환경에 만족하면 배포 단추를 선택하여 포털에서 직접 웹앱을 배포할 수 있습니다.
이를 통해 모델에서 자체 데이터를 사용하는 경우 독립형 웹 애플리케이션에 배포하거나 Copilot Studio(미리 보기)의 Copilot에 배포할 수 있는 옵션이 제공됩니다.
예를 들어 웹앱을 배포하도록 선택하는 경우:
웹앱을 처음 배포할 때 새 웹앱 만들기를 선택해야 합니다. 앱 URL의 일부가 될 앱의 이름을 선택합니다. 예: https://<appname>.azurewebsites.net
.
게시된 앱에 대한 구독, 리소스 그룹, 위치 및 가격 책정 계획을 선택합니다. 기존 앱을 업데이트하려면 기존 웹앱에 게시를 선택하고 드롭다운 메뉴에서 이전 앱의 이름을 선택합니다.
웹앱을 배포하도록 선택하는 경우 웹앱을 사용하기 위한 중요한 고려 사항을 참조하세요.
리소스 정리
채팅 플레이그라운드 테스트가 완료된 후 Azure OpenAI 리소스를 정리하고 제거하려는 경우 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.
다음 단계
gpt-35-turbo
를 통해 새로운 모델로 작업하는 방법에 대해 자세히 알아봅니다.- 더 많은 예제를 보려면 Azure OpenAI 샘플 GitHub 리포지토리를 체크 아웃합니다.
소스 코드 | 패키지(NuGet) | 샘플| RAG(Retrieval Augmented Generation) 엔터프라이즈 채팅 템플릿 |
필수 조건
- 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)>역할을 할당할 수 있습니다.
설정
#D0 새 폴더를 만들고 다음 명령을 사용하여 빠른 시작 폴더로 이동합니다.
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 키를 사용하려는 경우 #D0 개체를 #D1 개체로 바꿀 수 있습니다.
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 리포지토리를 체크 아웃합니다.
필수 조건
- 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)>역할을 할당할 수 있습니다.
설정
#D0 새 폴더를 만들고 다음 명령을 사용하여 빠른 시작 폴더로 이동합니다.
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 리포지토리를 체크 아웃합니다.
소스 코드 | Artifact(Maven) | 샘플 | RAG(Retrieval Augmented Generation) 엔터프라이즈 채팅 템플릿 | IntelliJ IDEA
필수 조건
- Azure 구독 - 체험 구독 만들기
- JDK(Java Development Kit)의 현재 버전
- Gradle 빌드 도구 또는 다른 종속성 관리자
gpt-4
모델이 배포된 Azure OpenAI Service 리소스. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.
Microsoft Entra ID 필수 구성 요소
Microsoft Entra ID를 사용하는 권장 키 없는 인증의 경우 다음을 수행해야 합니다.
- Microsoft Entra ID를 사용하여 키 없는 인증에 사용되는 Azure CLI 를 설치합니다.
- 사용자 계정에
Cognitive Services User
역할을 할당합니다. Azure Portal의 액세스 제어(IAM)>역할을 할당할 수 있습니다.
설정
#D0 새 폴더를 만들고 다음 명령을 사용하여 빠른 시작 폴더로 이동합니다.
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 키를 사용하려는 경우 #D0 개체를 #D1 개체로 바꿀 수 있습니다.
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 리포지토리를 체크 아웃합니다.
소스 코드 | Artifacts(Maven) | 샘플
필수 조건
- Azure 구독 - 체험 구독 만들기
- JDK(Java Development Kit)의 현재 버전
- 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에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2 를 사용할 수 있습니다. |
Azure Portal에서 해당 리소스로 이동합니다. 키 및 엔드포인트 섹션은 리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1
또는 KEY2
를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.
환경 변수
키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.
중요한
주의해서 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
명령을 실행합니다. 이 명령은 기본 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로 Ai채팅Application.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 리포지토리를 체크 아웃합니다.
참고
이 가이드에서는 Azure OpenAI를 완전히 지원하는 최신 OpenAI npm 패키지를 사용합니다. 레거시 Azure OpenAI JavaScript SDK에 대한 코드 예제를 찾는 경우 현재 이 리포지토리에서 계속 사용할 수 있습니다.
필수 조건
- Azure 구독 - 체험 구독 만들기
- Node.js의 LTS 버전
- 로컬 개발 환경에서 암호 없는 인증에 사용되는 Azure CLI는 Azure CLI로 로그인하여 필요한 컨텍스트를 만듭니다.
- Azure OpenAI 서비스 리소스에
gpt-4
시리즈 모델이 배포되어 있습니다. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.
Microsoft Entra ID 필수 구성 요소
Microsoft Entra ID를 사용하는 권장 키 없는 인증의 경우 다음을 수행해야 합니다.
- Microsoft Entra ID를 사용하여 키 없는 인증에 사용되는 Azure CLI 를 설치합니다.
- 사용자 계정에
Cognitive Services User
역할을 할당합니다. Azure Portal의 액세스 제어(IAM)>역할을 할당할 수 있습니다.
설정
#D0 새 폴더를 만들고 다음 명령을 사용하여 빠른 시작 폴더로 이동합니다.
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
함께 사용할 수 없으며 한 번에 하나만 전달할 수 있습니다. 시스템에서 API 키에 대한 기존 환경 변수를 제거해야 할 수 있습니다. Microsoft Entra ID 코드 샘플이 API 키 환경 변수를 명시적으로 참조하지 않더라도 이 샘플을 실행하는 시스템에 있는 경우 이 오류는 여전히 생성됩니다.
리소스 정리
Azure OpenAI 리소스를 정리하고 제거하려면 해당 리소스를 삭제할 수 있습니다. 리소스를 삭제하기 전에 먼저 배포된 모델을 삭제해야 합니다.
다음 단계
- Azure OpenAI 개요
- JavaScript용 사용자 고유의 데이터 샘플을 사용하여 채팅 시작
- 더 많은 예제를 보려면 Azure OpenAI 샘플 GitHub 리포지토리를 체크 아웃합니다.
참고
이 가이드에서는 Azure OpenAI를 완전히 지원하는 최신 OpenAI npm 패키지를 사용합니다. 레거시 Azure OpenAI JavaScript SDK에 대한 코드 예제를 찾는 경우 현재 이 리포지토리에서 계속 사용할 수 있습니다.
필수 조건
- Azure 구독 - 체험 구독 만들기
- Node.js의 LTS 버전
- TypeScript
- 로컬 개발 환경에서 암호 없는 인증에 사용되는 Azure CLI는 Azure CLI로 로그인하여 필요한 컨텍스트를 만듭니다.
- Azure OpenAI 서비스 리소스로,
gpt-4
시리즈 모델이 배포되었습니다. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.
Microsoft Entra ID 필수 구성 요소
Microsoft Entra ID를 사용하는 권장 키 없는 인증의 경우 다음을 수행해야 합니다.
- Microsoft Entra ID를 사용하여 키 없는 인증에 사용되는 Azure CLI 를 설치합니다.
- 사용자 계정에
Cognitive Services User
역할을 할당합니다. Azure Portal의 액세스 제어(IAM)>역할을 할당할 수 있습니다.
설정
#D0 새 폴더를 만들고 다음 명령을 사용하여 빠른 시작 폴더로 이동합니다.
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); });
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(Retrieval Augmented Generation) 엔터프라이즈 채팅 템플릿 |
필수 조건
- 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에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2 를 사용할 수 있습니다. |
Azure Portal에서 해당 리소스로 이동합니다. 키 및 엔드포인트 섹션은 리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1
또는 KEY2
를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.
환경 변수
키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.
중요
클라우드에서 실행되는 애플리케이션에 자격 증명을 저장하지 않으려면 Microsoft Entra ID 인증과 함께 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의 내용을 다음 코드로 바꿉니다.
GPT-35-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 서비스 보안 문서를 참조하세요.
quickstart 파일의
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에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2 를 사용할 수 있습니다. |
Azure Portal에서 해당 리소스로 이동합니다. 키 및 엔드포인트 섹션은 리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1
또는 KEY2
를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.
환경 변수
키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.
중요
클라우드에서 실행되는 애플리케이션에 자격 증명을 저장하지 않으려면 Microsoft Entra ID 인증과 함께 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 서비스 리소스. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.
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의 내용을 다음 코드로 바꿉니다. GPT-4o 모델을 배포할 때 선택한 배포 이름으로 변수를 설정
engine
해야 합니다. 기본 모델 이름과 동일한 배포 이름을 선택하지 않으면 모델 이름을 입력하면 오류가 발생합니다.# 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
출력
스크립트의 출력은 Azure OpenAI Service의 응답을 포함하는 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 리포지토리를 체크 아웃합니다.