다음을 통해 공유


.NET을 사용하여 AI 채팅 앱 빌드

간단한 .NET 8 콘솔 채팅 애플리케이션을 만들어 OpenAI 및 의미 체계 커널을 시작합니다. 애플리케이션은 로컬로 실행되고 OpenAI gpt-3.5-turbo 모델을 사용합니다. 다음 단계에 따라 OpenAI에 액세스하고 의미 체계 커널을 사용하는 방법을 알아봅니다.

필수 조건

  • .NET 8.0 SDK - .NET 8.0 SDK를 설치합니다.
  • 이 샘플을 실행할 수 있는 OpenAI의 API 키입니다.
  • Windows에서는 PowerShell v7+이 필요합니다. 버전의 유효성을 검사하려면 터미널에서 pwsh(을)를 실행합니다. 현재 버전을 반환해야 합니다. 오류가 반환되면 다음 명령을 실행합니다. dotnet tool update --global PowerShell.

간단한 .NET 8 콘솔 채팅 애플리케이션을 만들어 OpenAI 및 의미 체계 커널을 시작합니다. 애플리케이션은 로컬로 실행되고 Azure OpenAI에 배포된 OpenAI gpt-35-turbo 모델에 연결됩니다. 다음 단계에 따라 Azure OpenAI를 프로비전하고 의미 체계 커널을 사용하는 방법을 알아봅니다.

필수 조건

샘플 프로젝트 가져오기

모든 빠른 시작에 대한 샘플 앱이 포함된 GitHub 리포지토리를 복제합니다.

git clone https://github.com/dotnet/ai-samples.git

Azure OpenAI 서비스 만들기

샘플 GitHub 리포지토리는 Azure OpenAI 서비스 및 모델을 프로비전하는 데 사용할 수 있는 azd Azure 개발자 CLI(azd) 템플릿으로 구성됩니다.

  1. 터미널 또는 명령 프롬프트에서 샘플 리포지토리의 src\quickstarts\azure-openai 디렉터리로 이동합니다.

  2. 명령을 azd up 실행하여 Azure OpenAI 리소스를 프로비전합니다. Azure OpenAI 서비스를 만들고 모델을 배포하는 데 몇 분 정도 걸릴 수 있습니다.

    azd up
    

    azd 또한 OpenAI 액세스 키와 같은 샘플 앱에 필요한 사용자 비밀을 구성합니다.

    참고 항목

    azd up 배포 중에 오류가 발생하면 문제 해결 섹션을 방문하세요.

HikerAI 샘플 사용해 보기

  1. 터미널이나 명령 프롬프트에서 openai\02-HikerAI 디렉터리로 이동합니다.

  2. 다음 명령을 실행하여 OpenAI API 키를 샘플 앱의 암호로 구성합니다.

    dotnet user-secrets init
    dotnet user-secrets set OpenAIKey <your-openai-key>
    
  3. dotnet run 명령을 사용하여 앱을 실행합니다.

    dotnet run
    
  1. 터미널이나 명령 프롬프트에서 azure-openai\02-HikerAI 디렉터리로 이동합니다.

  2. dotnet run 명령을 사용하여 앱을 실행합니다.

    dotnet run
    

    오류 메시지가 표시되면 Azure OpenAI 리소스 배포가 완료되지 않았을 수 있습니다. 몇 분 정도 기다렸다가 다시 시도해 보세요.

코드 탐색

앱은 Microsoft.SemanticKernel 패키지를 사용하여 OpenAI 서비스에 요청을 보내고 받습니다.

앱 코드는 Program.cs 파일에 포함되어 있습니다. 처음 몇 줄의 코드는 구성 값을 설정하고 dotnet user-secrets 명령을 사용하여 이전에 설정한 OpenAI 키를 가져옵니다.

var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string model = "gpt-3.5-turbo";
string key = config["OpenAIKey"];

OpenAIChatCompletionService 서비스는 요청과 응답을 편리하게 수행할 수 있습니다.

// Create the OpenAI Chat Completion Service
OpenAIChatCompletionService service = new(model, key);

코드 탐색

애플리케이션은 Microsoft.SemanticKernel 패키지를 사용하여 Azure에 배포된 Azure OpenAI 서비스에 요청을 보내고 받습니다.

전체 애플리케이션은 Program.cs 파일에 포함되어 있습니다. 처음 몇 줄의 코드는 애플리케이션 프로비저닝 중에 dotnet user-secrets에 설정된 비밀 및 구성 값을 검색합니다.

// Retrieve the local secrets saved during the Azure deployment
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string endpoint = config["AZURE_OPENAI_ENDPOINT"];
string deployment = config["AZURE_OPENAI_GPT_NAME"];
string key = config["AZURE_OPENAI_KEY"];

AzureOpenAIChatCompletionService 서비스는 요청과 응답을 편리하게 수행할 수 있습니다.

// Create the Azure OpenAI Chat Completion Service
AzureOpenAIChatCompletionService service = new(deployment, endpoint, key);

모델에 더 많은 컨텍스트를 제공하는 시스템 프롬프트를 추가합니다. 이는 대화 중에 모델 동작 및 생성된 완료에 영향을 줍니다.

// Start the conversation with context for the AI model
ChatHistory chatHistory = new("""
    You are a hiking enthusiast who helps people discover fun hikes in their area. 
    You are upbeat and friendly. You introduce yourself when first saying hello.
    When helping people out, you always ask them for this information
    to inform the hiking recommendation you provide:

    1. Where they are located
    2. What hiking intensity they are looking for

    You will then provide three suggestions for nearby hikes that vary in length
    after you get that information. You will also share an interesting fact about
    the local nature on the hikes when making a recommendation.
    """);

AddUserMessage 함수를 사용하여 채팅 기록에 사용자 메시지를 추가합니다. GetChatMessageContentAsync 함수를 사용하여 시스템 프롬프트 및 사용자 요청에 따라 응답을 생성하도록 모델에 지시합니다.


// Add user message to chat history
chatHistory.AddUserMessage("Hi! Apparently you can help me find a hike that I will like?");

// Print User Message to console
Console.WriteLine($"{chatHistory.Last().Role} >>> {chatHistory.Last().Content}");

// Get response
var response = await service.GetChatMessageContentAsync(
    chatHistory, new OpenAIPromptExecutionSettings() { MaxTokens = 400 });

모드의 응답을 추가하여 채팅 기록을 유지합니다.

// Add response to chat history
chatHistory.Add(response);

// Print Response to console
Console.WriteLine($"{chatHistory.Last().Role} >>> {chatHistory.Last().Content}");

시스템 프롬프트와 사용자 메시지를 사용자 지정하여 원하는 하이킹 코스를 찾을 수 있도록 모델이 어떻게 반응하는지 확인합니다.

리소스 정리

샘플 애플리케이션 또는 리소스가 더 이상 필요하지 않은 경우 해당 배포 및 모든 리소스를 제거합니다.

azd down

문제 해결

Windows에서는 azd up(을)를 실행한 후 다음과 같은 오류 메시지가 나타날 수 있습니다.

postprovision.ps1은 디지털 서명되지 않았습니다. 스크립트가 시스템에서 실행되지 않습니다.

애플리케이션에 사용되는 .NET 사용자 비밀을 설정하기 위해 postprovision.ps1 스크립트가 실행됩니다. 이 오류를 방지하려면 다음 PowerShell 명령을 실행합니다.

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

그런 다음 azd up 명령을 다시 실행합니다.

발생할 수 있는 다른 오류:

'pwsh'가 내부 또는 외부 명령, 실행 가능한 프로그램 또는 배치 파일로 인식되지 않습니다. 경고: 종료 코드: '1', 경로: '.\infra\post-script\postprovision.ps1'으로 인해 'postprovision' 후크가 실패했습니다. : 종료 코드: 1 ContinueOnError가 true로 설정되었으므로 실행이 계속됩니다.

애플리케이션에 사용되는 .NET 사용자 비밀을 설정하기 위해 postprovision.ps1 스크립트가 실행됩니다. 이 오류를 방지하려면 다음 PowerShell 명령을 사용하여 스크립트를 수동으로 실행합니다.

.\infra\post-script\postprovision.ps1

이제 .NET AI 앱에 사용자 암호가 구성되어 테스트할 수 있습니다.

다음 단계