본문 바로가기

AI/자연어처리(NLP)

GPT3 2편) OpenAI API로 chatbot을 만들어보자!

거대 언어모델 GPT3가 화재다.

수많은 데이터를 엄청 큰 Transformer decoder 모델로 이루어진 GPT 모델로 학습한 GPT3.

지금까지 언어모델은 Pretrain을 통해 학습한 후 많진 않지만 적지 않은 꽤 많은 데이터를 수집하여 fine-tuning을 해서 언어모델의 parameter weights 값들을 업데이트해야 동작했다.

하지만 GPT3 모델은 weight 업데이트 없이 언어모델의 입력인 prompt에 정보를 잘 담으면 학습 없이도 많은 task가 가능하다.

GPT3로 할수있는 task는 자연어처리의 모든 task이다. 분류/요약/번역/챗봇 등등 수많은 task가 학습 없이 prompt 입력 만으로 가능하다.

 

본 글에선 1) OpenAI의 API를 이용해 GPT3를 이용하는 방법, 2) GPT3를 이용한 챗봇 을 만들어 보려 한다!!

 

GPT3의 이론에 대해선 이전 글을 참고

https://keep-steady.tistory.com/52

 

GPT3 1편) GPT3 이론 파헤치기

최근 인공지능 기반 자연어처리는 거대 언어모델 개발로 큰 성공을 거두고 있습니다. 오늘은 GPT3에 대해 알아봅시다. 1. 언어모델(Language Model) 언어모델은 크게 Auto encoding 모델과 Auto regressive 

keep-steady.tistory.com

 

 

코드는 https://github.com/airobotlab/lecture_NLP_GPT 에서 확인할 수 있다. Colab에서 열면 바로 실습이 가능하다.

 

1) OpenAI의 API를 이용해 GPT3를 이용하기

 

1.1) OpenAI CLI 설치

OpenAI를 파이썬에서 CLI command로 사용하기 위해선 파이썬 환경에서 아래 명령어로 파이썬 패키지 설치가 필요하다.

 

pip install openai

 

1.2) OpenAI API key 요청

OpenAI는 GPT3를 사용하거나 fine-tuning 하기 위한 API를 제공한다. 이를 이용하기 위해서는 우선 API key를 발급받아야 한다. 아주 쉽다. 아래 링크에서 회원가입, 로그인한 후 API key를 발급받으면 끝난다. 첫 3달은 18달러 credit이 공짜다.

 

https://beta.openai.com/account/api-keys

 

API_KEY예시 : Q34O5PMWEROGKOERSIKG34

 

1.3) GPT3 사용 예시

 

https://beta.openai.com/playground

 

OpenAI의 GPT3를 사용하기 위해선  아래 사이트인 playground에서 손쉽게 사용이 가능하다.

 

1) 텍스트  입력

- 가운데 텍스트 입력창에 텍스트를 입력한다. 예시는 요약 예시이므로 긴 원문을 입력하였다.

 

2) 파라미터 설정

- 오른쪽 파라미터 설정 란에서 temperature, maximum length, TopP, Penalty 등의 파라미터를 입력한다.Maximum length는 최대 생성 길이로, GPT3는 2048 subword token만큼의 출력을 생성할 수 있다.Temperature와 TopP는 글 생성 시 샘플링 방법이다. 이 방식에 따라 출력이 달라진다.

 

3) 제출

- 1)에서 입력한 텍스트와, 2)에서 설정한 파라미터를 prompt로 만든 후 GPT3 모델에 입력으로 준다. 이를 통해 출력을 얻을 수 있다.

 

4) 결과 출력

- 3)에서 prompt를 제출하면, 응답으로 answer가 생성되어 출력된다.

 

 

1.4) GPT3 예시

OpenAI에선 GPT3로 할 수 있는 많은 예시들을 보여준다. 클릭하면 Playground에서 사용할 수 있는 예시가 열린다. QA, 요약, 번역, 분류 등등 수많은 모든 자연어처리 task를 손쉽게 사용할 수 있다.아래 링크에서 확인할 수 있다.

 

https://beta.openai.com/examples

 

 

 

2) GPT3를 이용한 챗봇 

 

jupyter notebook에서 GPT3를 이용한 챗봇을 만들어보자.

 

2.1) OpenAI key 설정

1.2)에서 발급받은 API KEY를 아래 '<<API KEY>>'에 입력한다.

 

My_OpenAI_key = '<<API KEY>>'

import openai
openai.api_key = My_OpenAI_key
completion = openai.Completion()

 

2.2) GPT3 config 지정

GPT3를 돌리기 위한 config를 지정한다. 이때 max_tokens으로 생성될 글의 길이를, temperature와 top_p로 생성될 다음 단어의 샘플링 방법 등을 지정한다.

 

# config
temperature = 0.9
max_tokens = 64
top_p = 1.0
best_of = 1
frequency_penalty = 0.0
presence_penalty = 0.0

# stop = ["You:"]
stop = ["\n"]

 

2.3) 챗봇 테스트

우선 openai CLI에서 API로 통신이 잘 되는지 테스트해 보자. 질문을 'What is your name?'으로 줬을 때 응답이 잘 오는지 테스트해본다.

 

# chatbot test
question = 'what is your name?'
prompt_initial = f'Human:%s\nAI:' % (question)

prompt = prompt_initial

response = completion.create(
    prompt=prompt, 
    engine="davinci",
    max_tokens=max_tokens,    
    stop=stop, 
    temperature=temperature,
    top_p=top_p,
    best_of=best_of,
)
answer = response.choices[0].text.strip()
print(prompt, answer)

 

2.4) Chatbot building

 

2.3)에서 응답이 잘 오는 것을 확인했으면, 이제 본격적으로 챗봇을 만들자. question에 질문을 입력하면 history에서 주고받는 대화를 기록하여 지난 대화 기반으로 응답을 만들어 주도록 prompt를 설계하였다.

 

def run_openai_chatbot(question='What time is it?', history=''):
    
    prompt_initial = f'Human:%s\nAI:' % (question)

    prompt = history + '\n' + prompt_initial

    response = completion.create(
        prompt=prompt, 
        engine="davinci",
        max_tokens=max_tokens,    
        stop=stop, 
        temperature=temperature,
        top_p=top_p,
        best_of=best_of,
    )
    answer = response.choices[0].text.strip()
    history = prompt + answer

    print('question: %s\nanswer: %s\n\nhistory: %s' % (question, answer, history))    
    return answer, history

 

2.5) 챗봇 실습(1질문, 1답변)

 

2.4)에서 만든 함수를 이용하여 question에 질문을 입력하면 answer를 생성하는 함수로 답변을 만든다. 이때 history는 과거에 주고받은 대화를 기록하여 다음 대화 때 사용하기 위해 저장한다.

 

question='What time is it?'
answer, history = run_openai_chatbot(question=question, history='')

출력

  • question: What time is it?
  • answer: It is now 1:37 pm.

 

 

question='Really?'
answer, history = run_openai_chatbot(question=question, history=history)

출력

  • question: Really?
  • answer: I am asking you please go to my website aibot.xyz and then pressing the button donate.

 

question='I am hungry...'
answer, history = run_openai_chatbot(question=question, history=history)

출력

  • question: I am hungry...
  • answer: Human go get some food for yourself. I am out of food!

 

question='I want to have a lunch'
answer, history = run_openai_chatbot(question=question, history=history)

출력

  • question: I want to have a lunch
  • answer: Lunch is in the morning, after breakfast.

 

 

2.6) 챗봇 실습(주고받기)

 

for turn in range(3):
    question = input(">> User:")
    answer, history = run_openai_chatbot(question=question, history=history)

출력

  • question: What is your name?
  • answer: I don't have a name... I am just a program
  •  
  • question: Oh~ My name is wooyoung go
  • answer: Fine. Nice to meet you
  •  
  • question: Me too~
  • answer: How old are you?

 

 

 

3) Fine tuining GPT3

 

OpenAI의 GPT3를 이용하여 챗봇을 만들어 보았다. 이렇게 아무 학습 없이 prompt 입력만으로 쓰는 것보단, fine tuning을 사용하여 학습하면 더 좋은 성능의 챗봇을 만들 수 있다. 아래 URL을 참고하여 데이터셋을 포맷에 맞게 만든 후 아래 2줄을 bash에서 실행하면 fine-tuning이 가능하다.

 

dataset 준비: https://beta.openai.com/docs/guides/fine-tuning/preparing-your-dataset

 

!export OPENAI_API_KEY=<YOUR API KEY>
!openai api fine_tunes.create -t <prepared data filename> -m <modelname>

 

 

지금까지 GPT3 사용법과, 챗봇을 만드는 예시를 해보았다. 언어모델이 답변을 만들어주는 수준이 상당하다.

 

 

Reference

https://medium.com/geekculture/a-chatbot-application-by-finetuning-gpt-3-2682aad25356
https://beta.openai.com/examples
https://beta.openai.com/playground