Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 6개 있습니다.)
.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록
; https://www.sysnet.pe.kr/2/0/13344

닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작
; https://www.sysnet.pe.kr/2/0/13451

닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법
; https://www.sysnet.pe.kr/2/0/13452

닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI)
; https://www.sysnet.pe.kr/2/0/13454

닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용
; https://www.sysnet.pe.kr/2/0/13455

닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성
; https://www.sysnet.pe.kr/2/0/13456




C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작

(2025-06-22 업데이트) 아래의 내용은 Preview 버전을 기반으로 작성한 것이라, 현재는 코드가 변경되었습니다. 대충 이런 식의 예제로 바뀌었으니 참고하세요.

using Azure;
using Azure.AI.OpenAI;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel;

namespace ConsoleApp1;

// https://github.com/Azure/azure-sdk-for-net/blob/Azure.AI.OpenAI_2.1.0/sdk/openai/Azure.AI.OpenAI/README.md
// Install-Package Azure.AI.OpenAI
internal class Program
{
    static void Main(string[] args)
    {
        string azureOpenAIKey = "...[azure openai key]...";
        string azureOpenAIEndpoint = "...[azure openai endpoint]...";

        string chatDeployment = "my_gpt35_turbo";

        AzureOpenAIClient azureClient = new(
            new Uri(azureOpenAIEndpoint),
            new ApiKeyCredential(azureOpenAIKey));

        ChatClient chatClient = azureClient.GetChatClient(chatDeployment);

        ChatCompletion completion = chatClient.CompleteChat(
            [
                // System messages represent instructions or other guidance about how the assistant should behave
                new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
                // User messages represent user input, whether historical or the most recent input
                new UserChatMessage("Hi, can you help me?"),
                // Assistant messages in a request represent conversation history for responses
                new AssistantChatMessage("Arrr! Of course, me hearty! What can I do for ye?"),
                new UserChatMessage("What's the best way to train a parrot?"),
            ]);

        Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");
    }
}




이번 글도, .NET Conf 2023에서 다 나온 내용입니다. ^^

Build Intelligent Apps with .NET and Azure
; https://youtu.be/xEFO1sQ2bUc?t=27190

정리하는 차원에서 ^^ 그대로 베껴 보겠습니다. 이번 글은 사전 작업이 필요한데요, 동영상에 나온 소스 코드를 그대로 따라 하려면 "Azure OpenAI" 서비스를 생성해 두어야 합니다.

Azure OpenAI 서비스 신청 방법
; https://www.sysnet.pe.kr/2/0/13449

그런 다음, "Model deployments" 메뉴로 들어가,

azure_openai_chatgpt_2.png

"Manage Deployments" 버튼을 눌러 "https://oai.azure.com/portal" 페이지로 이동한 후, "배포"를 하나 만들어 둡니다.

azure_openai_chatgpt_3.png

(이때 입력한 이름을 나중에 코드로 사용할 것입니다.)

참고로, 위의 모델 선택에 GPT-4가 없는데요, 현재(2023-11-22) Sweden Central, Canada East, Switzerland North 3개의 Region만 지원한다고 합니다. 다른 지역은 기다려야 할 듯! ^^




아마도 다들 한 번쯤은 openai 홈페이지에서 GPT 챗 서비스를 이용해 본 적이 있을 텐데요,

ChatGPT
; https://chat.openai.com/

사실, 저 과정을 OpenAI API를 이용해 그대로 구현할 수 있습니다. 여기서는 "Build Intelligent Apps with .NET and Azure" 동영상에서 나온 코드를 따라 그대로 구현해 보겠습니다.

이를 위해 간단하게 .NET 8 Console 프로젝트를 생성하고, 패키지 관리자를 이용해 Azure.AI.OpenAI를 참조 추가합니다.

Install-Package Azure.AI.OpenAI -Pre

그다음 소스 코드에서 OpenAIClient 인스턴스를 생성해야 하는데요, 이를 위해서는 Azure OpenAI 서비스의 Endpoint 정보와 Key가 필요한데, 이것은 Azure Portal 화면에서 구할 수 있습니다.

azure_openai_chatgpt_1.png

그리하여 다음과 같이 초기화할 수 있고,

namespace ConsoleApp1;

using Azure;
using Azure.AI.OpenAI;
using System;

internal class Program
{
    // Install-Package Azure.AI.OpenAI -Pre
    static async Task Main(string[] args)
    {
        string azureOpenAIKey = "...[azure openai key]...";
        string azureOpenAIEndpoint = "...[azure openai endpoint]...";

        OpenAIClient openAIClient = new OpenAIClient(new System.Uri(azureOpenAIEndpoint), new AzureKeyCredential(azureOpenAIKey));
    }
}

이전에 기록했던 "Deployment" 이름과 몇 가지 옵션으로 ChatCompletionsOptions 인스턴스를 만든 후,

string chatDeployment = "my_gpt35_turbo"; // replace your deployment name here 

var options = new ChatCompletionsOptions
{
    DeploymentName = chatDeployment,
    MaxTokens = 400,
    Temperature = 0.2f,  // Precise <-> Creativity
    FrequencyPenalty = 0.0f, // 
    PresencePenalty = 0.0f,
    NucleusSamplingFactor = 0.95f // Top P
};

ChatGPT 서비스와 유사하게 동작하도록 System 프롬프트를 설정합니다.

string systemMessage = "Assistant is a large language model trained by OpenAI";

options.Messages.Clear();
options.Messages.Add(new ChatMessage(ChatRole.System, systemPrompt));

이후부터는, ChatGPT 채팅창에서 했던 대화 작업을 반복 루프로 처리하고, 또한 그 과정에서 대화 문맥을 options.Messages에 유지하면 됩니다. (물론, 토큰 한계까지만 가능합니다.)

Console.WriteLine($"System: {systemPrompt}");

while (true)
{
    Console.Write("Your prompt: ");
    var userPrompt = Console.ReadLine();
    if (userPrompt?.ToLowerInvariant() == "q")
    {
        break;
    }

    Console.WriteLine($"User: {userPrompt}");
    options.Messages.Add(new ChatMessage(ChatRole.User, userPrompt));

    var assistantResponse = await openAIClient.GetChatCompletionsAsync(options);
    var response = assistantResponse.Value.Choices[0].Message.Content;
    Console.WriteLine($"Assistant: {response}");
    options.Messages.Add(new ChatMessage(ChatRole.Assistant, response));
}

즉, 대화 주제 하나마다 저렇게 options 하나로 대응하면 (또는 options.Messages.Clear() 하거나) 그게 바로 ChatGPT 홈페이지의 서비스가 되는 것입니다. 간단하죠? ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/22/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  [26]  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13351정성태5/11/202314900VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/202314679오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/202314178.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제 [1]파일 다운로드1
13348정성태5/10/202315862.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/202316118.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/202315612오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/202317743.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/202318689.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/202316409디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/202313560.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/202313766닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/202313937오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/202315911닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/202313517닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/202315521Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/202314936.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/202316772.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/202315426Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/202312248Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/202313219Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/202312225오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/202314234Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/202314199Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/202313813VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/202314329VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/202317697.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  [26]  27  28  29  30  ...