AI/NLP

[AI - NLP] Chat GPT를 API로 만들어보자.

전주호 2023. 4. 29. 17:21
반응형

요즘 ChatGPT를 굉장히 많은 곳에서 사용하고 있다.

 

간단한 것을 직접 구글에 검색해서 찾는 것이 아니라

ChatGPT에 물어보면 간편하게 확인할 수 있어서 좋다.

 

지금 진행중인 프로젝트에서

주어진 단어들을 포함하는 완벽한 문장을 만드는 기능이 필요해서

문장생성이 가능한 모델인 GPT 중 가장 인기가 많은 ChatGPT를 API로 만들어보자.

(python 코드로 진행됩니다.)

 

pip install openai

먼저! openai를 설치해준다.

 

import openai

API_KEY = 'your api key'
openai.api_key = API_KEY

first_query = 'Use these words in order, one at a time, to make a sentence.'
second_query = 'and translate to korean too'
words = ["my", "favorite", "singer", "song", "come out"]

content = first_query +' ['+','.join(words)+'] '+ last_query

print(content)

completion = openai.ChatCompletion.create(
  model = 'gpt-3.5-turbo',
  messages = [
    {'role': 'system', 'content': 'do your best!'},
    {'role': 'user', 'content': content}
  ],
  temperature = 0.9
)

print(completion['choices'][0]['message']['content'])

API Key를 따로 파일을 만들어 해주면 보안적으로 더욱 좋을 것이다.

(Git에 올릴 때 무조건! Key는 따로 파일을 만들어 사용하고 Git에는 올리지 않도록 한다.)

 

이렇게 자연스러운 결과가 나오는 것을 확인할 수 있다.

 

temperature을 0에 가깝게 하니 너무 딱딱한 말투가 나와 0.9 정도로 맞춰줬다.

 

작성 방법은 아래 공식 문서를 참고해보자!

https://platform.openai.com/docs/guides/chat/chat-vs-completions

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

다른 GPT 모델들을 사용했을 때 나오지 않았던 자연스러움과 정확도가 확인되어서

프로젝트에 사용하여 기능을 활용할 수 있다.


 

API Key는 Open AI 홈페이지에서 찾아볼 수 있다.

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

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

아래의 리스트에서 본인이 사용할 모델을 선택할 수 있다.

저는 gpt-3.5-turbo 를 선택했다! ( ChatGPT 에서 사용하는 모델 )

https://platform.openai.com/account/rate-limits

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

반응형