빠른 시작: Azure OpenAI 서비스에서 GPT-35-Turbo 및 GPT-4 사용 시작

이 문서를 사용하여 Azure OpenAI 사용을 시작합니다.

필수 조건

  • Azure 구독 – 체험 구독을 만듭니다.

  • 원하는 Azure 구독의 Azure OpenAI에 대한 액세스 권한.

    현재 이 서비스에 대한 액세스 권한은 애플리케이션에서만 부여됩니다. https://aka.ms/oai/access에서 양식을 작성하여 Azure OpenAI에 대한 액세스를 신청할 수 있습니다. 문제가 있는 경우 이 리포지토리에서 문제를 엽니다.

  • gpt-35-turbo 또는 gpt-4 모델이 배포된 Azure OpenAI Service 리소스입니다. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.

여러 Azure AI 서비스의 기능을 통합한 새로운 통합 Azure AI Studio(미리 보기)를 사용해 보세요.

Azure OpenAI Studio로 이동

https://oai.azure.com/에서 Azure OpenAI Studio로 이동한 다음, OpenAI 리소스에 액세스할 수 있는 자격 증명으로 로그인합니다. 로그인 워크플로 도중 또는 이후에 적절한 디렉터리, Azure 구독 및 Azure OpenAI 리소스를 선택합니다.

Azure OpenAI Studio 방문 페이지에서 채팅 플레이그라운드를 선택합니다.

채팅 플레이그라운드가 강조 표시된 Azure OpenAI Studio 방문 페이지의 스크린샷.

플레이그라운드

Azure OpenAI Studio 채팅 플레이그라운드를 통해 코드 없는 접근 방식으로 Azure OpenAI 기능 탐색을 시작합니다. 이 페이지에서 쉽게 기능을 반복하고 실험해 볼 수 있습니다.

채팅 플레이그라운드 페이지 스크린샷.

도우미 설정

도우미 설정 드롭다운을 사용하여 미리 로드된 몇 가지 시스템 메시지 예제를 선택하여 시작할 수 있습니다.

시스템 메시지는 동작하는 방법과 응답을 생성할 때 참조해야 하는 컨텍스트에 대한 지침을 모델에 제공합니다. 도우미의 성격을 설명하고, 대답해야 하는 것과 대답해서는 안 되는 것을 말하고, 응답의 형식을 지정하는 방법을 말할 수 있습니다.

몇 가지 샷 예제를 추가하면 모델이 컨텍스트 내 학습에 사용하는 대화형 예제를 제공할 수 있습니다.

채팅 플레이그라운드를 사용하는 동안 언제든지 코드 보기를 선택하여 현재 채팅 세션 및 설정 선택 사항에 따라 미리 채워진 Python, curl 및 json 코드 샘플을 볼 수 있습니다. 그런 다음, 이 코드를 사용하고 애플리케이션을 작성하여 현재 플레이그라운드에서 수행하고 있는 것과 동일한 작업을 완료할 수 있습니다.

채팅 세션

보내기 단추를 선택하면 입력한 텍스트가 완료 API로 전송되고 결과가 다시 텍스트 상자로 반환됩니다.

채팅 지우기 단추를 선택하여 현재 대화 기록을 삭제합니다.

설정

이름 설명
배포 특정 모델과 연결된 배포 이름입니다.
온도 임의성을 제어합니다. 온도를 낮추면 모델이 더 반복적이고 결정된 응답을 생성합니다. 온도를 높이면 예기치 않거나 창의적인 응답이 발생합니다. 온도 또는 상위 P를 조정하되 둘 다 조정하지는 마세요.
최대 길이(토큰) 모델 응답당 토큰 수 한도를 설정합니다. API는 프롬프트(시스템 메시지, 예제, 메시지 기록 및 사용자 쿼리 포함)와 모델의 응답 간에 공유되는 최대 4,096개의 토큰을 지원합니다. 한 토큰은 일반적인 영어 텍스트의 경우 약 4자입니다.
상위 확률 온도와 마찬가지로 임의성을 제어하지만 다른 방법을 사용합니다. 상위 P를 낮추면 모델의 토큰 선택이 유사 토큰으로 좁혀지게 됩니다. 상위 P를 늘리면 모델이 가능성이 높고 낮은 토큰 중에서 선택할 수 있습니다. 온도 또는 상위 P를 조정하되 둘 다 조정하지는 마세요.
멀티 턴 대화 각 새 API 요청에 포함할 과거 메시지 수를 선택합니다. 이렇게 하면 새 사용자 쿼리에 대한 모델 컨텍스트를 제공할 수 있습니다. 이 숫자를 10으로 설정하면 5개의 사용자 쿼리와 5개의 시스템 응답이 생성됩니다.
중지 시퀀스 중지 시퀀스는 모델이 원하는 지점에서 응답을 종료하도록 합니다. 모델 응답은 지정된 시퀀스 이전에 종료되므로 중지 시퀀스 텍스트가 포함되지 않습니다. GPT-35-Turbo의 경우 <|im_end|>를 사용하면 모델 응답이 후속 사용자 쿼리를 생성하지 않습니다. 최대 4개의 중지 시퀀스를 포함할 수 있습니다.

창 표시

기본적으로 도우미 설정, 채팅 세션 및 설정의 세 가지 패널이 있습니다. 패널 표시를 사용하면 패널을 추가, 제거하고 다시 정렬할 수 있습니다. 패널을 닫고 다시 가져와야 하는 경우 패널 표시를 사용하여 손실된 패널을 복원합니다.

채팅 세션 시작

  1. 도우미 설정 드롭다운에서 Xbox 고객 지원 에이전트를 선택합니다.

  2. 시스템 메시지를 업데이트할지 묻는 메시지가 표시되면 계속을 선택합니다.

  3. 채팅 세션 창에서 "새 Xbox를 구입하는 데 관심이 있습니다"라는 질문을 입력하고 보내기를 선택합니다.

  4. 다음과 유사한 응답이 수신됩니다.

    플레이그라운드의 첫 번째 질문과 대답 스크린샷.

  5. "4K를 지원하는 모델은 무엇입니까?"와 같은 후속 질문을 입력합니다.

    플레이그라운드의 후속 질문 및 답변 스크린샷.

  6. 이제 기본 대화가 있으므로 도우미 설정에서 코드 보기를 선택하면 지금까지 진행된 전체 대화 뒤에 코드가 재생됩니다.

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

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

프롬프트 구조 이해

코드 보기에서 샘플을 검사하면 일반적인 GPT 완료 호출에 포함되지 않은 몇 가지 고유한 토큰을 확인할 수 있습니다. GPT-35-Turbo는 프롬프트의 다양한 부분을 설명하기 위해 특수 토큰을 사용하도록 학습되었습니다. 콘텐츠는 <|im_start|><|im_end|> 토큰 사이에서 모델에 제공됩니다. 프롬프트는 모델에 대한 컨텍스트 또는 지침을 포함하여 모델을 대비시키는 데 사용할 수 있는 시스템 메시지로 시작합니다. 그런 다음, 프롬프트에 사용자와 도우미 간의 일련의 메시지가 포함됩니다.

그러면 프롬프트에 대한 도우미의 응답이 <|im_start|>assistant 토큰 아래에 반환되고 도우미가 응답을 완료했음을 나타내는 <|im_end|>로 끝납니다. 원시 구문 표시 토글 단추를 사용하여 채팅 세션 패널 내에서 이러한 토큰을 표시할 수도 있습니다.

GPT-35-Turbo 및 GPT-4 방법 가이드는 새로운 프롬프트 구조와 gpt-35-turbo 모델을 효과적으로 사용하는 방법에 대한 심층적인 소개를 제공합니다.

모델 배포

Azure OpenAI Studio의 환경에 만족하면 배포 대상 단추를 선택하여 스튜디오에서 직접 웹앱을 배포할 수 있습니다.

Azure OpenAI Studio의 모델 배포 단추를 보여 주는 스크린샷.

이를 통해 모델에서 자체 데이터를 사용하는 경우 독립형 웹 애플리케이션에 배포하거나 Copilot Studio(미리 보기)의 Copilot에 배포할 수 있는 옵션이 제공됩니다.

예를 들어 웹앱을 배포하도록 선택하는 경우:

웹앱을 처음 배포할 때 새 웹앱 만들기를 선택해야 합니다. 앱 URL의 일부가 될 앱의 이름을 선택합니다. 예: https://<appname>.azurewebsites.net.

게시된 앱에 대한 구독, 리소스 그룹, 위치 및 가격 책정 계획을 선택합니다. 기존 앱을 업데이트하려면 기존 웹앱에 게시를 선택하고 드롭다운 메뉴에서 이전 앱의 이름을 선택합니다.

웹앱을 배포하도록 선택하는 경우 웹앱을 사용하기 위한 중요한 고려 사항을 참조하세요.

리소스 정리

채팅 플레이그라운드 테스트가 완료된 후 Azure OpenAI 리소스를 정리하고 제거하려는 경우 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.

다음 단계

소스 코드 | 패키지(NuGet) | 샘플| RAG(Retrieval Augmented Generation) 엔터프라이즈 채팅 템플릿 |

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • 원하는 Azure 구독의 Azure OpenAI Service에 부여된 액세스 권한. 현재 이 서비스에 대한 액세스 권한은 애플리케이션에서만 부여됩니다. https://aka.ms/oai/access에서 양식을 작성하여 Azure OpenAI Service에 대한 액세스를 신청할 수 있습니다.
  • .NET 7 SDK
  • gpt-35-turbo 또는 gpt-4 모델이 배포된 Azure OpenAI Service 리소스입니다. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.

설정

새 .NET Core 애플리케이션 만들기

콘솔 창(예: cmd, PowerShell 또는 Bash)에서 dotnet new 명령을 사용하여 azure-openai-quickstart라는 새 콘솔 앱을 만듭니다. 이 명령은 program.cs라는 단일 C# 원본 파일을 사용하여 간단한 "Hello World" 프로젝트를 만듭니다.

dotnet new console -n azure-openai-quickstart

새로 만든 앱 폴더로 디렉터리를 변경합니다. 다음을 통해 애플리케이션을 빌드할 수 있습니다.

dotnet build

빌드 출력에 경고나 오류가 포함되지 않아야 합니다.

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

다음을 사용하여 OpenAI .NET 클라이언트 라이브러리를 설치합니다.

dotnet add package Azure.AI.OpenAI --prerelease

키 및 엔드포인트 검색

Azure OpenAI에 대해 성공적으로 호출하려면 엔드포인트가 필요합니다.

변수 이름
ENDPOINT 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. 또는 Azure OpenAI Studio>플레이그라운드>코드 보기에서 값을 찾을 수 있습니다. 예제 엔드포인트는 https://docs-test-001.openai.azure.com/입니다.
API-KEY 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2를 사용할 수 있습니다.

Azure Portal에서 해당 리소스로 이동합니다. 키 및 엔드포인트 섹션은 리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1 또는 KEY2를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.

엔드포인트 및 액세스 키 위치가 빨간색 원으로 표시된 Azure Portal의 OpenAI 리소스에 대한 개요 UI 스크린샷.

환경 변수

키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

샘플 애플리케이션 만들기

프로젝트 디렉터리에서 program.cs 파일을 열고, 다음 코드로 바꿉니다.

응답 스트리밍 없음

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

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

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

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

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

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

Console.WriteLine();

Important

프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자격 증명 보안에 대한 자세한 내용은 Azure AI 서비스 보안 문서를 참조하세요.

dotnet run program.cs

출력

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

결과를 인쇄하기 전에 모델이 전체 응답을 생성할 때까지 기다립니다. 또는 응답을 비동기식으로 스트리밍하고 결과를 인쇄하려는 경우 program.cs의 콘텐츠를 다음 예의 코드로 바꿀 수 있습니다.

스트리밍과 비동기

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

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

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

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

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

리소스 정리

Azure OpenAI 리소스를 정리하고 제거하려면 해당 리소스를 삭제할 수 있습니다. 리소스를 삭제하기 전에 먼저 배포된 모델을 삭제해야 합니다.

다음 단계

소스 코드 | 패키지(Go)| 샘플

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • 원하는 Azure 구독의 Azure OpenAI Service에 부여된 액세스 권한. 현재 이 서비스에 대한 액세스 권한은 애플리케이션에서만 부여됩니다. https://aka.ms/oai/access에서 양식을 작성하여 Azure OpenAI Service에 대한 액세스를 신청할 수 있습니다.
  • Go 1.21.0 이상이 로컬로 설치되었습니다.
  • gpt-35-turbo 모델이 배포된 Azure OpenAI Service 리소스. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.

설정

키 및 엔드포인트 검색

Azure OpenAI에 대해 성공적으로 호출하려면 엔드포인트가 필요합니다.

변수 이름
ENDPOINT 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. 또는 Azure OpenAI Studio>플레이그라운드>코드 보기에서 값을 찾을 수 있습니다. 예제 엔드포인트는 https://docs-test-001.openai.azure.com/입니다.
API-KEY 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2를 사용할 수 있습니다.

Azure Portal에서 해당 리소스로 이동합니다. 키 및 엔드포인트 섹션은 리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1 또는 KEY2를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.

엔드포인트 및 액세스 키 위치가 빨간색 원으로 표시된 Azure Portal의 OpenAI 리소스에 대한 개요 UI 스크린샷.

환경 변수

키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

샘플 애플리케이션 만들기

chat_completions.go라는 새 파일을 만듭니다. 다음 코드를 chat_completions.go 파일에 복사합니다.

package main

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

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

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

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

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

	keyCredential, err := azopenai.NewKeyCredential(azureOpenAIKey)

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

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

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

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

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

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

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

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

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

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

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

}

Important

프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자격 증명 보안에 대한 자세한 내용은 Azure AI 서비스 보안 문서를 참조하세요.

이제 명령 프롬프트를 열고 다음을 실행합니다.

go mod init chat_completions.go

다음 실행:

go mod tidy
go run chat_completions.go

출력

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

리소스 정리

Azure OpenAI 리소스를 정리하고 제거하려면 해당 리소스를 삭제할 수 있습니다. 리소스를 삭제하기 전에 먼저 배포된 모델을 삭제해야 합니다.

다음 단계

더 많은 예제를 보려면 Azure OpenAI 샘플 GitHub 리포지토리를 체크 아웃합니다.

소스 코드 | Artifact(Maven) | 샘플 | RAG(Retrieval Augmented Generation) 엔터프라이즈 채팅 템플릿 | IntelliJ IDEA

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • 원하는 Azure 구독의 Azure OpenAI Service에 부여된 액세스 권한. 현재 이 서비스에 대한 액세스 권한은 애플리케이션에서만 부여됩니다. https://aka.ms/oai/access에서 양식을 작성하여 Azure OpenAI Service에 대한 액세스를 신청할 수 있습니다.
  • Gradle 빌드 도구 또는 다른 종속성 관리자
  • gpt-35-turbo 또는 gpt-4 모델이 배포된 Azure OpenAI Service 리소스입니다. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.

설정

키 및 엔드포인트 검색

Azure OpenAI에 대해 성공적으로 호출하려면 엔드포인트가 필요합니다.

변수 이름
ENDPOINT 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. 또는 Azure OpenAI Studio>플레이그라운드>코드 보기에서 값을 찾을 수 있습니다. 예제 엔드포인트는 https://docs-test-001.openai.azure.com/입니다.
API-KEY 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2를 사용할 수 있습니다.

Azure Portal에서 해당 리소스로 이동합니다. 키 및 엔드포인트 섹션은 리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1 또는 KEY2를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.

엔드포인트 및 액세스 키 위치가 빨간색 원으로 표시된 Azure Portal의 OpenAI 리소스에 대한 개요 UI 스크린샷.

환경 변수

키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

새 Java 애플리케이션 만들기

새 Gradle 프로젝트를 만듭니다.

콘솔 창(예: cmd, PowerShell 또는 Bash)에서 앱에 대한 새 디렉터리를 만들고 이 디렉터리로 이동합니다.

mkdir myapp && cd myapp

작업 디렉터리에서 gradle init 명령을 실행합니다. 이 명령은 build.gradle.kts를 포함하여 런타임에 애플리케이션을 만들고 구성하는 데 사용되는 Gradle용 필수 빌드 파일을 만듭니다.

gradle init --type basic

DSL을 선택하라는 메시지가 표시되면 Kotlin을 선택합니다.

Java SDK 설치

이 빠른 시작에서는 Gradle 종속성 관리자를 사용합니다. 다른 종속성 관리자에 대한 클라이언트 라이브러리 및 정보는 Maven 중앙 리포지토리에서 찾을 수 있습니다.

build.gradle.kts를 찾고, 원하는 IDE 또는 텍스트 편집기에서 엽니다. 그런 다음, 다음 빌드 구성을 복사합니다. 이 구성은 프로젝트를 진입점이 OpenAI빠른 시작 클래스인 Java 애플리케이션으로 정의합니다. Azure AI Vision 라이브러리를 가져옵니다.

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

샘플 애플리케이션 만들기

  1. Java 파일을 만듭니다.

    작업 디렉터리에서 다음 명령을 실행하여 프로젝트 원본 폴더를 만듭니다.

    mkdir -p src/main/java
    

    새 폴더로 이동하여 OpenAIQuickstart.java라는 파일을 만듭니다.

  2. 선호하는 편집기 또는 IDE에서 OpenAIQuickstart.java 파일을 열고 다음 코드를 붙여넣습니다.

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

    Important

    프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자격 증명 보안에 대한 자세한 내용은 Azure AI 서비스 보안 문서를 참조하세요.

  3. 프로젝트 루트 폴더로 돌아가서 다음을 사용하여 앱을 빌드합니다.

    gradle build
    

    그런 다음, gradle run 명령을 사용하여 실행합니다.

    gradle run
    

출력

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

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

리소스 정리

Azure OpenAI 리소스를 정리하고 제거하려면 해당 리소스를 삭제할 수 있습니다. 리소스를 삭제하기 전에 먼저 배포된 모델을 삭제해야 합니다.

다음 단계

소스 코드 | Artifacts(Maven) | 샘플

필수 조건

설정

키 및 엔드포인트 검색

Azure OpenAI에 대해 성공적으로 호출하려면 엔드포인트가 필요합니다.

변수 이름
ENDPOINT 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. 또는 Azure OpenAI Studio>플레이그라운드>코드 보기에서 값을 찾을 수 있습니다. 예제 엔드포인트는 https://docs-test-001.openai.azure.com/입니다.
API-KEY 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2를 사용할 수 있습니다.

Azure Portal에서 해당 리소스로 이동합니다. 키 및 엔드포인트 섹션은 리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1 또는 KEY2를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.

엔드포인트 및 액세스 키 위치가 빨간색 원으로 표시된 Azure Portal의 OpenAI 리소스에 대한 개요 UI 스크린샷.

환경 변수

키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.

참고 항목

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 애플리케이션 편집

  1. pom.xml 파일을 편집합니다.

    프로젝트 디렉터리의 루트에서 원하는 편집기나 IDE로 pom.xml 파일을 열고 다음 콘텐츠로 파일을 덮어씁니다.

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>3.2.0</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>ai-chat-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>AIChat</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>17</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.experimental.ai</groupId>
                <artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId>
                <version>0.7.0-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
        <repositories>
            <repository>
                <id>spring-snapshots</id>
                <name>Spring Snapshots</name>
                <url>https://repo.spring.io/snapshot</url>
                <releases>
                    <enabled>false</enabled>
                </releases>
            </repository>
        </repositories>
    </project>
    
  2. src/main/java/com/example/aichatdemo 폴더에서 원하는 편집기나 IDE로 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()));
              });
        }
    
    }
    

    Important

    프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자격 증명 보안에 대한 자세한 내용은 Azure AI 서비스 보안 문서를 참조하세요.

  3. 프로젝트 루트 폴더로 다시 이동하고 다음 명령을 사용하여 앱을 실행합니다.

    ./mvnw spring-boot:run
    

출력

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

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

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

리소스 정리

Azure OpenAI 리소스를 정리하고 제거하려면 해당 리소스를 삭제할 수 있습니다. 리소스를 삭제하기 전에 먼저 배포된 모델을 삭제해야 합니다.

다음 단계

더 많은 예제를 보려면 Azure OpenAI 샘플 GitHub 리포지토리를 체크 아웃합니다.

소스 코드 | 패키지(npm) | 샘플 | RAG(Retrieval Augmented Generation) 엔터프라이즈 채팅 템플릿|

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • 원하는 Azure 구독의 Azure OpenAI Service에 부여된 액세스 권한. 현재 이 서비스에 대한 액세스 권한은 애플리케이션에서만 부여됩니다. https://aka.ms/oai/access에서 양식을 작성하여 Azure OpenAI Service에 대한 액세스를 신청할 수 있습니다.
  • Node.js의 LTS 버전
  • gpt-35-turbo 또는 gpt-4 모델이 배포된 Azure OpenAI Service 리소스입니다. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.

설정

키 및 엔드포인트 검색

Azure OpenAI에 대해 성공적으로 호출하려면 엔드포인트가 필요합니다.

변수 이름
ENDPOINT 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. 또는 Azure OpenAI Studio>플레이그라운드>코드 보기에서 값을 찾을 수 있습니다. 예제 엔드포인트는 https://docs-test-001.openai.azure.com/입니다.
API-KEY 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2를 사용할 수 있습니다.

Azure Portal에서 해당 리소스로 이동합니다. 키 및 엔드포인트 섹션은 리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1 또는 KEY2를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.

엔드포인트 및 액세스 키 위치가 빨간색 원으로 표시된 Azure Portal의 OpenAI 리소스에 대한 개요 UI 스크린샷.

환경 변수

키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

노드 애플리케이션 만들기

콘솔 창(예: cmd, PowerShell 또는 Bash)에서 앱에 대한 새 디렉터리를 만들고 이 디렉터리로 이동합니다. 그런 다음 npm init 명령을 실행하여 package.json 파일이 있는 노드 애플리케이션을 만듭니다.

npm init

클라이언트 라이브러리 설치

npm을 사용하여 JavaScript용 Azure OpenAI 클라이언트 라이브러리를 설치합니다.

npm install @azure/openai

종속성이 있는 앱의 package.json 파일이 업데이트됩니다.

샘플 애플리케이션 만들기

새 프로젝트를 원하는 명령 프롬프트를 열고 ChatCompletion.js라는 새 파일을 만듭니다. 다음 코드를 ChatCompletion.js 파일에 복사합니다.

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

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

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

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

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

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

module.exports = { main };

Important

프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자격 증명 보안에 대한 자세한 내용은 Azure AI 서비스 보안 문서를 참조하세요.

다음 명령을 사용하여 스크립트를 실행합니다.

node.exe ChatCompletion.js

출력

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

리소스 정리

Azure OpenAI 리소스를 정리하고 제거하려면 해당 리소스를 삭제할 수 있습니다. 리소스를 삭제하기 전에 먼저 배포된 모델을 삭제해야 합니다.

다음 단계

라이브러리 소스 코드 | 패키지(PyPi) | RAG(Retrieval Augmented Generation) 엔터프라이즈 채팅 템플릿 |

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • 원하는 Azure 구독의 Azure OpenAI 서비스에 부여된 액세스 권한. 현재 이 서비스에 대한 액세스 권한은 애플리케이션에서만 부여됩니다. https://aka.ms/oai/access에서 양식을 작성하여 Azure OpenAI Service에 대한 액세스를 신청할 수 있습니다.
  • Python 3.8 이상 버전
  • 다음 Python 라이브러리: os
  • gpt-35-turbo 또는 gpt-4 모델이 배포된 Azure OpenAI Service 리소스입니다. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.

설정

다음을 사용하여 OpenAI Python 클라이언트 라이브러리를 설치합니다.

pip install openai

참고 항목

이 라이브러리는 OpenAI에서 유지 관리되며 현재 미리 보기 상태입니다. 라이브러리에 대한 최신 업데이트를 추적하려면 릴리스 기록 또는 version.py 커밋 기록을 참조하세요.

키 및 엔드포인트 검색

Azure OpenAI에 대해 성공적으로 호출하려면 엔드포인트가 필요합니다.

변수 이름
ENDPOINT 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. 또는 Azure OpenAI Studio>플레이그라운드>코드 보기에서 값을 찾을 수 있습니다. 예제 엔드포인트는 https://docs-test-001.openai.azure.com/입니다.
API-KEY 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2를 사용할 수 있습니다.

Azure Portal에서 해당 리소스로 이동합니다. 키 및 엔드포인트 섹션은 리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1 또는 KEY2를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.

엔드포인트 및 액세스 키 위치가 빨간색 원으로 표시된 Azure Portal의 OpenAI 리소스에 대한 개요 UI 스크린샷.

환경 변수

키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

새 Python 애플리케이션 만들기

  1. quickstart.py라는 새 Python 파일을 만듭니다. 선호하는 편집기 또는 IDE에서 이 파일을 엽니다.

  2. quickstart.py의 내용을 다음 코드로 바꿉니다.

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)

Important

프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자격 증명 보안에 대한 자세한 내용은 Azure AI 서비스 보안 문서를 참조하세요.

  1. 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 리소스를 정리하고 제거하려면 해당 리소스를 삭제할 수 있습니다. 리소스를 삭제하기 전에 먼저 배포된 모델을 삭제해야 합니다.

다음 단계

REST API 사양 |

필수 조건

  • Azure 구독 – 체험 구독을 만듭니다.
  • 원하는 Azure 구독의 Azure OpenAI 서비스에 부여된 액세스 권한. 현재 이 서비스에 대한 액세스 권한은 애플리케이션에서만 부여됩니다. https://aka.ms/oai/access에서 양식을 작성하여 Azure OpenAI Service에 대한 액세스를 신청할 수 있습니다.
  • gpt-35-turbo 또는 gpt-4 모델이 배포된 Azure OpenAI Service 리소스입니다. 모델 배포에 대한 자세한 내용은 리소스 배포 가이드를 참조하세요.

설정

키 및 엔드포인트 검색

Azure OpenAI에 대해 성공적으로 호출하려면 엔드포인트가 필요합니다.

변수 이름
ENDPOINT 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. 또는 Azure OpenAI Studio>플레이그라운드>코드 보기에서 값을 찾을 수 있습니다. 예제 엔드포인트는 https://docs-test-001.openai.azure.com/입니다.
API-KEY 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2를 사용할 수 있습니다.

Azure Portal에서 해당 리소스로 이동합니다. 키 및 엔드포인트 섹션은 리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1 또는 KEY2를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.

엔드포인트 및 액세스 키 위치가 빨간색 원으로 표시된 Azure Portal의 OpenAI 리소스에 대한 개요 UI 스크린샷.

환경 변수

키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.

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 명령 프롬프트에서 이 명령을 실행하려면 텍스트를 변경하여 \ 및 줄 바꿈을 제거해야 합니다.

Important

프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자격 증명 보안에 대한 자세한 내용은 Azure AI 서비스 보안 문서를 참조하세요.

출력

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

읽기 용이성을 위해 조정된 출력 서식입니다. 실제 출력은 줄 바꿈이 없는 단일 텍스트 블록입니다.

메시지 구조 이해

GPT-35-Turbo 및 GPT-4 모델은 대화형식의 입력 작업에 최적화되어 있습니다. messages 변수는 시스템, 사용자 및 도우미가 기술하는 대화에서 서로 다른 역할을 가진 사전 배열을 전달합니다. 시스템 메시지는 모델이 응답하는 방법에 대한 컨텍스트 또는 지침을 포함하여 모델을 대비시키는 데 사용할 수 있습니다.

GPT-35-Turbo 및 GPT-4 방법 가이드는 이러한 새로운 모델과 통신하기 위한 옵션에 대해 심층적으로 소개합니다.

리소스 정리

Azure OpenAI 리소스를 정리하고 제거하려면 해당 리소스를 삭제할 수 있습니다. 리소스를 삭제하기 전에 먼저 배포된 모델을 삭제해야 합니다.

다음 단계

필수 조건

키 및 엔드포인트 검색

Azure OpenAI에 대해 성공적으로 호출하려면 엔드포인트가 필요합니다.

변수 이름
ENDPOINT 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. 또는 Azure OpenAI Studio>플레이그라운드>코드 보기에서 값을 찾을 수 있습니다. 예제 엔드포인트는 https://docs-test-001.openai.azure.com/입니다.
API-KEY 이 값은 Azure Portal에서 리소스를 검사할 때 키 및 엔드포인트 섹션에서 찾을 수 있습니다. KEY1 또는 KEY2를 사용할 수 있습니다.

Azure Portal에서 해당 리소스로 이동합니다. 엔드포인트 및 키리소스 관리 섹션에서 찾을 수 있습니다. 엔드포인트 및 액세스 키를 복사합니다. API 호출을 인증하는 데 모두 필요합니다. KEY1 또는 KEY2를 사용할 수 있습니다. 항상 두 개의 키를 사용하면 서비스 중단 없이 키를 안전하게 회전하고 다시 생성할 수 있습니다.

엔드포인트 & 액세스 키 위치에 빨간색 원이 표시된 Azure Portal의 Azure OpenAI 리소스 개요 UI 스크린샷

키 및 엔드포인트에 대한 영구 환경 변수를 만들고 할당합니다.

환경 변수

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

새 PowerShell 스크립트 만들기

  1. 빠른 시작.ps1이라는 새 PowerShell 파일을 만듭니다. 선호하는 편집기 또는 IDE에서 이 파일을 엽니다.

  2. quickstart.ps1의 내용을 다음 코드로 바꿉니다. GPT-35-Turbo 또는 GPT-4 모델을 배포할 때 선택한 배포 이름으로 engine 변수를 설정해야 합니다. 기본 모델 이름과 동일한 배포 이름을 선택하지 않으면 모델 이름을 입력할 때 오류가 발생합니다.

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

    Important

    프로덕션의 경우 Azure Key Vault를 사용한 PowerShell 비밀 관리와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자격 증명 보안에 대한 자세한 내용은 Azure AI 서비스 보안 문서를 참조하세요.

  3. PowerShell을 사용하여 스크립트를 실행합니다.

    ./quickstart.ps1
    

출력

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

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

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

메시지 구조 이해

GPT-35-Turbo 및 GPT-4 모델은 대화형식의 입력 작업에 최적화되어 있습니다. messages 변수는 시스템, 사용자 및 도우미가 기술하는 대화에서 서로 다른 역할을 가진 사전 배열을 전달합니다. 시스템 메시지는 모델이 응답하는 방법에 대한 컨텍스트 또는 지침을 포함하여 모델을 대비시키는 데 사용할 수 있습니다.

GPT-35-Turbo 및 GPT-4 방법 가이드는 이러한 새로운 모델과 통신하기 위한 옵션에 대해 심층적으로 소개합니다.

리소스 정리

Azure OpenAI 리소스를 정리하고 제거하려면 해당 리소스를 삭제할 수 있습니다. 리소스를 삭제하기 전에 먼저 배포된 모델을 삭제해야 합니다.

다음 단계