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

비밀번호

댓글 작성자
 




... 151  152  153  154  155  156  157  158  159  160  161  162  [163]  164  165  ...
NoWriterDateCnt.TitleFile(s)
1034정성태5/2/201128871.NET Framework: 211. 파일 잠금 없이 .NET 어셈블리의 버전을 구하는 방법 [2]파일 다운로드1
1033정성태5/1/201135032웹: 19. IIS Express - appcmd.exe를 이용한 applicationHost.config 변경 [2]
1032정성태5/1/201131709웹: 18. IIS Express를 NT 서비스로 변경
1031정성태4/30/201132532웹: 17. IIS Express - "IIS Installed Versions Manager Interface"의 IIISExpressProcessUtility 구하는 방법 [1]파일 다운로드1
1030정성태4/30/201155265개발 환경 구성: 118. IIS Express - localhost 이외의 호스트 이름으로 접근하는 방법 [4]파일 다운로드1
1029정성태4/28/201143754개발 환경 구성: 117. XCopy에서 파일/디렉터리 확인 질문 없애기 [2]
1028정성태4/27/201141000오류 유형: 119. Visual Studio 2010 SP1 설치 후 Windows Phone 개발자 도구로 인한 재설치 문제 [3]
1027정성태4/25/201130164디버깅 기술: 40. 상황별 GetFunctionPointer 반환값 정리 - x86파일 다운로드1
1026정성태4/25/201149132디버깅 기술: 39. DebugDiag 1.1을 사용한 덤프 분석 [7]
1025정성태4/24/201131148개발 환경 구성: 116. IIS 7 관리자 - Active Directory Certification Authority로부터 SSL 사이트 인증서 받는 방법 [2]
1024정성태4/22/201132366오류 유형: 118. Windows 2008 서버에서 Event Viewer / PowerShell 실행 시 비정상 종료되는 문제 [1]
1023정성태4/20/201133133.NET Framework: 210. Windbg 환경에서 확인해 본 .NET 메서드 JIT 컴파일 전과 후 [1]
1022정성태4/19/201128040디버깅 기술: 38. .NET Disassembly 창에서의 F11(Step-into) 키 동작파일 다운로드1
1021정성태4/18/201130498디버깅 기술: 37. .NET 4.0 응용 프로그램의 Main 함수에 BreakPoint 걸기
1020정성태4/18/201131676오류 유형: 117. Failed to find runtime DLL (mscorwks.dll), 0x80004005
1019정성태4/17/201132397디버깅 기술: 36. Visual Studio의 .NET Disassembly 창의 call 호출에 사용되는 주소의 의미는? [1]파일 다운로드1
1018정성태4/16/201136344오류 유형: 116. 윈도우 업데이트 오류 - 0x8020000E
1017정성태4/14/201130818개발 환경 구성: 115. MSBuild - x86/x64, .NET 2/4, debug/release 빌드에 대한 배치 처리파일 다운로드1
1016정성태4/13/201147082개발 환경 구성: 114. Windows Thin PC 설치 [2]
1015정성태4/9/201132144.NET Framework: 209. AutoReset, ManualReset, Monitor.Wait의 차이파일 다운로드1
1014정성태4/7/2011109574오류 유형: 115. ORA-12516: TNS:listener could not find available handler with matching protocol stack [2]
1013정성태4/7/201127403Team Foundation Server: 45. SharePoint 2010 + TFS 2010 환경에서 ProcessGuidance.html 파일 다운로드 문제
1012정성태4/6/201136402.NET Framework: 208. WCF - 접속된 클라이언트의 IP 주소 알아내는 방법 [1]
1011정성태3/31/201138660오류 유형: 114. 인증서 갱신 오류 - The request contains no certificate template information.
1010정성태3/30/201129545개발 환경 구성: 113. 응용 프로그램 디자인 스케치 도구 - SketchFlow [4]
1009정성태3/29/201141660개발 환경 구성: 112. Visual Studio 2010 - .NET Framework 소스 코드 디버깅 [4]
... 151  152  153  154  155  156  157  158  159  160  161  162  [163]  164  165  ...