(chatGPT API 연동) 채팅으로 한국어 감성 분류 GPT API 연동

ChatGPT API가 어떻게 통합되는지 살펴보겠습니다.

chatGPT가 출시된 이후로 그냥 사이트에 가서 대화 형식으로 질문하고 답변을 받습니다.

처음 연결하면 통합을 위해 두 가지 작업을 수행해야 합니다.

  1. API 키 발급 받기
  2. openai 설치

API 키 발급받기

API 키를 받으려면 openai 웹 사이트로 이동해야 합니다.

https://platform.openai.com/

OpenAI API

OpenAI에서 개발한 새로운 AI 모델에 액세스하기 위한 API

platform.openai.com

위 링크로 들어가셔서 회원가입을 하시면 됩니다.

그런 다음 아래 이미지와 같이 오른쪽 상단 모서리에 있는 프로필을 클릭합니다.
API 키 보기클릭하세요


API 키 보기 페이지로 이동하면 화면 중앙에 “가 있습니다.
새 비밀 키 만들기“버튼이 보이실 겁니다.

이 버튼을 누르고 API 키를 복사합니다.

아래 그림을 참고하시면 됩니다.



이제 API가 있으므로 호출해 보겠습니다.

openai 설치

먼저 다음 명령어로 openai를 설치하자.

pip install openai

설치가 완료되면 아래 링크를 사용하여 간단한 예제를 테스트할 수 있습니다.

https://openai.com/blog/introducing-chatgpt-and-whisper-apis

ChatGPT 및 Whisper API 소개

개발자는 이제 API를 통해 ChatGPT 및 Whisper 모델을 앱과 제품에 통합할 수 있습니다.

openai.com

import openai

openai.api_key = "sk-8DD....." # API Key
completion = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=({"role": "user", "content": "Tell the world about the ChatGPT API in the style of a pirate."})
)

print(completion)

해적 스타일로 ChatGPT API를 소개하는 문장을 만들어 달라는 요청입니다.

응답 결과는 다음과 같습니다

{
  "choices": (
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "\n\nAhoy, landlubbers and seafarers alike!
Ye be wantin' to know about the ChatGPT API, do ye? Well, fear not, as this ol' pirate's got the skinny for ye.\n\nArrr, the ChatGPT API be a treasure indeed, aye!
It be a tool that lets ye interact with the ChatGPT, a brainy AI that be able to hold conversations with ye. And why would ye want to be doing that, ye ask? Well, shiver me timbers, there be many reasons!
\n\nYe could use the ChatGPT API to build chatbots that interact with customers, or to add a conversational interface to yer website or app. Ye could also use it to learn how to talk like a pirate, or to just have some fun bantering with the AI.\n\nAnd the best part, me hearties? The ChatGPT API be easy to use!
Just sign up fer an account, and ye can start sending messages to the ChatGPT right away. It be like havin' yer own parrot that talks back to ye!
\n\nSo, what be ye waitin' for, me mateys? Hoist the colors and set sail for the ChatGPT API!
Ye won't regret it, I promise ye that. Arrr!
", "role": "assistant" } } ), "created": 1678265347, "id": "chatcmpl-6rjlrs9e7F0LXamJJsLK5FoloTAdL", "model": "gpt-3.5-turbo-0301", "object": "chat.completion", "usage": { "completion_tokens": 273, "prompt_tokens": 23, "total_tokens": 296 } }

Completion.Choices(0).Message.Content답변 결과를 즉시 얻을 수 있습니다.

chatGPT API를 이용한 한국어 감성 분류

더 글로리 대본으로 기분 분류도 해봤다.

관련 데이터를 다운받아 파이썬으로 불러왔습니다.


나는 chatGPT ‘콘텐츠’에 ‘다음 문장에 대한 감정 평가를 해주세요. 긍정적, 중립적 또는 부정적으로만 대답하십시오.”

결과와 코드는 아래와 같습니다.

for subtitle in target_df('Subtitle').apply(lambda x: x.split(')')(1:)):
    sentiment_clf = openai.ChatCompletion.create(
                    model="gpt-3.5-turbo",
                    messages=({"role": "user",
                                "content": "다음 문장에 대해 감정분류 해줘. 답은 '긍정', '중립', '부정'으로만 답해줘.'{}'".format(subtitle)}
                              )
    )
    print(sentiment_clf)
    sentiment_list.append(sentiment_clf.choices(-1).message.content)

결과:


일관적인 답변을 드리지 못한 점 죄송합니다.

제 질문이 조금 이해하기 어려웠을 수도 있습니다.

그럼에도 불구하고 문장들이 전반적으로 잘 분류되어 있음을 확인할 수 있었다.

내가 영어로 물어보고 입력했다면 훨씬 더 잘 분류할 수 있었을 텐데.