이 빠른 시작에서는 구조화된 출력으로 응답을 요청하는 채팅 앱을 만듭니다. 구조적 출력 응답은 일반 텍스트 대신 지정한 형식의 채팅 응답입니다. 이 빠른 시작에서 만든 채팅 앱은 다양한 제품 리뷰의 감정을 분석하여 사용자 지정 열거형의 값에 따라 각 검토를 분류합니다.
필수 조건
- .NET 8 이상 버전
- Visual Studio Code (선택 사항)
AI 서비스 구성
Azure Portal을 사용하여 Azure OpenAI 서비스 및 모델을 프로비전하려면 Azure OpenAI 서비스 리소스 만들기 및 배포 문서의 단계를 완료합니다. "모델 배포" 단계에서 gpt-4o 모델을 선택합니다.
채팅 앱 만들기
다음 단계를 완료하여 AI 모델에 연결하는 콘솔 앱을 만듭니다 gpt-4o .
터미널 창에서 앱을 만들 디렉터리로 이동하고 다음 명령을 사용하여 새 콘솔 앱을
dotnet new만듭니다.dotnet new console -o SOChatSOChat디렉터리로 이동하고 필요한 패키지를 앱에 추가합니다.dotnet add package Azure.AI.OpenAI dotnet add package Azure.Identity dotnet add package Microsoft.Extensions.AI dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease dotnet add package Microsoft.Extensions.Configuration dotnet add package Microsoft.Extensions.Configuration.UserSecrets다음 명령을 실행하여 Azure OpenAI 엔드포인트, 모델 이름 및 테넌트 ID에 대한 앱 비밀 추가합니다.
dotnet user-secrets init dotnet user-secrets set AZURE_OPENAI_ENDPOINT <your-Azure-OpenAI-endpoint> dotnet user-secrets set AZURE_OPENAI_GPT_NAME gpt-4o dotnet user-secrets set AZURE_TENANT_ID <your-tenant-ID>비고
사용자 환경에 따라 테넌트 ID가 필요하지 않을 수 있습니다. 그 경우 DefaultAzureCredential를 인스턴스화하는 코드에서 그것을 제거하십시오.
선택한 편집기에서 새 앱을 엽니다.
코드 추가
다양한 감정을 설명하는 열거형을 정의합니다.
public enum Sentiment { Positive, Negative, Neutral }모델과 통신할 IChatClient를 만듭니다.
IConfigurationRoot config = new ConfigurationBuilder() .AddUserSecrets<Program>() .Build(); string endpoint = config["AZURE_OPENAI_ENDPOINT"]; string model = config["AZURE_OPENAI_GPT_NAME"]; string tenantId = config["AZURE_TENANT_ID"]; // Get a chat client for the Azure OpenAI endpoint. AzureOpenAIClient azureClient = new( new Uri(endpoint), new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = tenantId })); IChatClient chatClient = azureClient .GetChatClient(deploymentName: model) .AsIChatClient();비고
DefaultAzureCredential 는 사용자 환경 또는 로컬 도구에서 인증 자격 증명을 검색합니다. Visual Studio 또는 Azure CLI에 로그인하는 데 사용한 계정에
Azure AI Developer역할을 할당해야 합니다. 자세한 내용은 .NET을 사용하여 Azure AI 서비스에 인증하는 방법에 대해를 참조하세요. 단일 제품 검토로 모델에 요청을 보낸 다음 분석된 감정을 콘솔에 출력합니다. 요청된 구조적 출력 형식을 확장 메서드에 형식 인수 ChatClientStructuredOutputExtensions.GetResponseAsync<T>(IChatClient, String, ChatOptions, Nullable<Boolean>, CancellationToken) 로 전달하여 선언합니다.
string review = "I'm happy with the product!"; var response = await chatClient.GetResponseAsync<Sentiment>($"What's the sentiment of this review? {review}"); Console.WriteLine($"Sentiment: {response.Result}");이 코드는 다음과 유사한 출력을 생성합니다.
Sentiment: Positive단일 검토를 분석하는 대신 리뷰 컬렉션을 분석할 수 있습니다.
string[] inputs = [ "Best purchase ever!", "Returned it immediately.", "Hello", "It works as advertised.", "The packaging was damaged but otherwise okay." ]; foreach (var i in inputs) { var response2 = await chatClient.GetResponseAsync<Sentiment>($"What's the sentiment of this review? {i}"); Console.WriteLine($"Review: {i} | Sentiment: {response2.Result}"); }이 코드는 다음과 유사한 출력을 생성합니다.
Review: Best purchase ever! | Sentiment: Positive Review: Returned it immediately. | Sentiment: Negative Review: Hello | Sentiment: Neutral Review: It works as advertised. | Sentiment: Neutral Review: The packaging was damaged but otherwise okay. | Sentiment: Neutral분석된 열거형 값만 요청하는 대신 분석된 값과 함께 텍스트 응답을 요청할 수 있습니다.
텍스트 응답 및 분석된 감정을 포함하도록 레코드 형식 을 정의합니다.
record SentimentRecord(string ResponseText, Sentiment ReviewSentiment);(이 레코드 형식은 기본 생성자 구문을 사용하여 정의됩니다. 기본 생성자는 클래스의 인스턴스를 인스턴스화하는 데 필요한 매개 변수와 형식 정의를 결합합니다. C# 컴파일러는 기본 생성자 매개 변수에 대한 공용 속성을 생성합니다.)
레코드 형식을 형식 인수로 사용하여 요청을 다음으로
GetResponseAsync<T>보냅니다.var review3 = "This product worked okay."; var response3 = await chatClient.GetResponseAsync<SentimentRecord>($"What's the sentiment of this review? {review3}"); Console.WriteLine($"Response text: {response3.Result.ResponseText}"); Console.WriteLine($"Sentiment: {response3.Result.ReviewSentiment}");이 코드는 다음과 유사한 출력을 생성합니다.
Response text: Certainly, I have analyzed the sentiment of the review you provided. Sentiment: Neutral
자원을 정리하세요
더 이상 필요하지 않은 경우 Azure OpenAI 리소스 및 GPT-4 모델 배포를 삭제합니다.
- Azure PortalAzure OpenAI 리소스로 이동합니다.
- Azure OpenAI 리소스를 선택한 다음, 삭제선택합니다.
참고하십시오
.NET