본문 바로가기
📁 [4] 개발자 정보 & 코드 노트/C#

C# Windows Forms 강의 82편: 자연어 처리 기반 채팅봇 제작 - ChatGPT API 활용

by wawManager 2025. 4. 27.

 

1. 강의 개요

이번 강의에서는 ChatGPT API를 활용해 자연어 처리(NLP) 기반 채팅봇 애플리케이션을 제작합니다.
ChatGPT는 사용자의 질문에 대해 자연스러운 응답을 생성할 수 있는 강력한 언어 모델로,
이 강의에서는 API를 호출하여 사용자와의 대화를 구현합니다.
Windows Forms UI를 통해 입력한 질문에 대한 응답을 실시간으로 출력하는 방법을 배워봅니다.


2. 학습 목표

  • OpenAI의 ChatGPT API를 사용해 대화형 AI 기능 구현
  • HTTP 요청을 통해 OpenAI API 호출
  • ChatGPT의 응답을 UI에 실시간으로 표시
  • 사용자의 질문 이력을 관리

3. 기능 요구사항

필수 기능

1️⃣ 질문 입력 및 응답 표시:

  • 사용자가 입력한 질문에 대해 ChatGPT 응답 표시

2️⃣ 대화 이력 관리:

  • 이전 질문 및 응답을 저장하여 대화 흐름 유지

3️⃣ UI 구성 및 동작:

  • TextBox와 Button을 사용한 입력 및 응답 표시

4. 실습: ChatGPT 채팅봇 애플리케이션 제작

1️⃣ 사전 준비

  1. OpenAI API 키 발급:
  2. NuGet 패키지 설치:
    • RestSharp 패키지 설치 (HTTP 요청을 위한 라이브러리).
    • 설치 명령:
      Install-Package RestSharp
      

2️⃣ 폼 구성

  • 폼(Form) 이름: Form1
  • 컨트롤 배치:

컨트롤 타입 이름 위치 크기

TextBox txtUserInput 폼 하단 왼쪽 (400 x 30)
Button btnSend 폼 하단 오른쪽 (100 x 30)
ListBox lstChatHistory 폼 상단 전체 (500 x 400)

📌 폼 디자인 예시:

--------------------------------------------------
|         [ListBox - 대화 기록 표시]             |
--------------------------------------------------
| [User Input: TextBox]    [Send 버튼]           |
--------------------------------------------------

3️⃣ 코드 작성

(1) OpenAI API 호출

using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RestSharp;
using Newtonsoft.Json;

namespace WindowsFormsApp_ChatGPT
{
    public partial class Form1 : Form
    {
        private const string ApiUrl = "https://api.openai.com/v1/completions";
        private const string ApiKey = "YOUR_API_KEY"; // 발급받은 OpenAI API 키

        public Form1()
        {
            InitializeComponent();
        }

        // 버튼 클릭 시 질문 전송
        private async void btnSend_Click(object sender, EventArgs e)
        {
            string userInput = txtUserInput.Text.Trim();

            if (string.IsNullOrEmpty(userInput))
            {
                MessageBox.Show("질문을 입력하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            lstChatHistory.Items.Add($"사용자: {userInput}");
            txtUserInput.Clear();

            string response = await GetChatGPTResponse(userInput);
            if (!string.IsNullOrEmpty(response))
            {
                lstChatHistory.Items.Add($"ChatGPT: {response}");
            }
        }

        // ChatGPT API 호출
        private async Task GetChatGPTResponse(string prompt)
        {
            try
            {
                var client = new RestClient(ApiUrl);
                var request = new RestRequest(Method.POST);

                // HTTP 헤더 추가
                request.AddHeader("Authorization", $"Bearer {ApiKey}");
                request.AddHeader("Content-Type", "application/json");

                // 요청 바디 구성
                var requestBody = new
                {
                    model = "text-davinci-003",
                    prompt = prompt,
                    max_tokens = 150
                };
                request.AddJsonBody(requestBody);

                // API 호출 및 응답 수신
                var response = await client.ExecuteAsync(request);
                if (response.IsSuccessful)
                {
                    dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content);
                    return jsonResponse.choices[0].text.ToString().Trim();
                }
                else
                {
                    MessageBox.Show($"API 호출 실패: {response.StatusCode}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"오류 발생: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return string.Empty;
        }
    }
}

(2) Designer 코드

        private void InitializeComponent()
        {
            this.txtUserInput = new TextBox();
            this.btnSend = new Button();
            this.lstChatHistory = new ListBox();

            // User Input TextBox 설정
            this.txtUserInput.Location = new System.Drawing.Point(10, 420);
            this.txtUserInput.Size = new System.Drawing.Size(400, 30);

            // Send Button 설정
            this.btnSend.Location = new System.Drawing.Point(420, 420);
            this.btnSend.Size = new System.Drawing.Size(100, 30);
            this.btnSend.Text = "Send";
            this.btnSend.Click += new EventHandler(this.btnSend_Click);

            // Chat History ListBox 설정
            this.lstChatHistory.Location = new System.Drawing.Point(10, 10);
            this.lstChatHistory.Size = new System.Drawing.Size(510, 400);

            // Form 설정
            this.ClientSize = new System.Drawing.Size(540, 460);
            this.Controls.Add(this.txtUserInput);
            this.Controls.Add(this.btnSend);
            this.Controls.Add(this.lstChatHistory);
            this.Text = "ChatGPT 채팅봇";
        }

4️⃣ 실행 결과

1️⃣ 질문 입력 및 전송

  • TextBox에 질문 입력 → "Send" 버튼 클릭

2️⃣ ChatGPT 응답 표시

  • ListBox에 사용자의 질문과 ChatGPT의 응답 표시

3️⃣ 대화 이력 관리

  • ListBox에 이전 질문과 응답이 모두 저장되어 대화 흐름 유지

5. 주요 개념 요약

  • OpenAI API: ChatGPT 모델을 호출하여 자연어 처리를 수행
  • RestSharp: HTTP 요청 및 응답 처리를 위한 라이브러리
  • JSON: 요청 및 응답 데이터를 직렬화/역직렬화하여 처리
  • Task: 비동기 API 호출을 위한 C#의 기본 클래스

 

 

📌 #CSharp #WindowsForms #ChatGPT #OpenAIAPI #RestSharp #NLP