ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 핫한 ChatGPT의 API 오픈 소식 및 사용기
    BIG DATA & AI 2023. 3. 10. 11:03
    반응형

    ChatGPT의 등장

    요즈음 인공지능의 발전 속도는 거의 빅뱅의 우주팽창을 보는 것 같다. 갈수록 빠른 시간에 이전보다 훨씬 높은 성능을 보이고 있고, 이제는 기술적인 이슈를 넘어서 사용성, 개인 정보 등의 문제까지 화두가 되고 있고 무엇보다 전공자 뿐만 아니라 비전공자들도 AI에 대한 관심을 많이 가지는 부분에서 대중적인 인식에 대한 확산이 많이 되었다고도 느낀다.

    GPT-3를 기반으로 한 대규모 언어 모델이 나오면서 꽤 AI 씬에서는 센세이션이 일어났었는데, 최근에 OpenAI에서 ChatGPT라는 초초초대규모 언어 모델이 등장하면서 정말 세상이 뒤집어졌다(?).

    간단한 예제 코드도 척척 만들어내는 ChatGPT

    그 인기가 어느 정도냐면, ChatGPT는 문서 작성에 능하기 때문에 꽤 많은 동료들이 업무 보조용으로 비서처럼 두고 쓰기도 하는 것부터 시작해서, ChatGPT 전용 prompt를 입력하는 직업을 구하는 공고도 나온다. 더 나아가서 최근 'ChatGPT를 사용해서 블로그 포스팅 쓰는 법, 유튜브 하는 법, 돈 버는 법 ...' 이런 세미나들이 우후죽순으로 쏟아져 나온다.

    정말 hot하다고 볼 수 있는데, 최근에 -한 일주일 전?- OpenAI에서 ChatGPT API를 추가해줘서 IT기업들이 서비스에 너도나도 ChatGPT를 붙여서 빠르게 출시하고 있다. 나도 이 트렌드에 한 번 몸담아 보고 싶어서 python을 이용하여 간단한 예제들을 테스트 해 보려고 한다. ㅎㅎ


     

    ChatGPT API 예제

    우선 API는 유료인가? 궁금증이 생길 텐데 결론은 그렇다고 한다. 단 계정을 생성하면 $18의 무료 credit을 주고, 1000개의 토큰에 약 $0.002라고 하니 개인적인 프로젝트용으로 사용한다면 무료 credit을 이용해도 충분하다고 생각된다.

    오늘 5번 호출해서 $0.00005 썼다.

    API는 Python, Node.js 이렇게 두가지 타입의 package로 제공되고 본 포스팅에서는 CURL, python을 이용한 두 가지의 방법으로 API 호출을 해 보려고 한다.

     

    API Key 발급받기

    우선 API를 호출하기 위해서는 API key가 필요하다.

    1. OpenAI 플랫폼에 접속한다.
      https://platform.openai.com/overview
    2. 로그인 후, 우측 상단의 Personal > View API Keys로 들어가서 아래의 Create new secret key를 눌러 key를 발급해준다.

     

    이제 발급받은 key로 아래와 같이 test를 해 보자. YOUR_API_KEY 부분에 방금 발급받은 KEY를 넣어주면 된다.

    CURL 예제

    curl https://api.openai.com/v1/chat/completions \
      -H 'Content-Type: application/json' \
      -H 'Authorization: Bearer YOUR_API_KEY' \
      -d '{
      "model": "gpt-3.5-turbo",
      "messages": [{"role": "user", "content": "Hello!"}]
    }'

    ChatGPT에게 Hello!를 보냈더니 Hi there! How can I assist you today? 라고 온 것을 확인할 수 있다. 😀😀

    $ ./curl_example.sh 
    {"id":"chatcmpl-6sLC7QTiDj8pMZO7iqhSNgOu5AtkR","object":"chat.completion","created":1678409203,"model":"gpt-3.5-turbo-0301","usage":{"prompt_tokens":9,"completion_tokens":12,"total_tokens":21},"choices":[{"message":{"role":"assistant","content":"\n\nHi there! How can I assist you today?"},"finish_reason":"stop","index":0}]}

     

    Python 예제

    이제 python에서도 간단한 예제를 실행해 보자. 우선 아래 command로 ChatGPT를 호출하기 위한 openai 패키지를 설치해 준다. 모델도 openai 서버에 있기 때문에 간단한 REST API 요청을 위한 패키지라고 볼 수 있으며 매우 가볍다.

    $ pip install openai

     

    아까와 같이 YOUR_API_KEY 부분에 key를 넣어 주어 코드를 작성해 보자. 편하게 결과를 보기 위해서 응답 JSON 객체 중에서는 content만 표시하도록 해주었다.

    import os
    import openai
    
    openai.api_key = YOUR_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."
      }]
    )
    
    if completion:
      choice = completion["choices"][0]
      response = choice["message"]["content"]
      print(response)

    코드를 실행하니 아래와 같은 응답이 오는 것을 볼 수 있다. 매번 느끼는 거지만 ChatGPT는 질문에 굉장히 정성스럽게 답변해 주면서도 수다스러운 것 같다.

    $ python example.py 
    
    
    Ahoy mateys! Gather round, for I've got 'nother tale to tell ye! Let me spin ye a yarn about the ChatGPT API, arrr!
    
    This here API be the treasure ye've been searchin' for your entire life, me hearties! With it, ye can access a plethora of chatbot functionalities that'll make yer website or app the envy of all who sail the seas of the internet.
    
    With ChatGPT API, ye can create yer very own AI chatbots that can converse with yer customers, aid in customer support, carry out live chat, and more. It be the perfect tool for businesses to connect wit' their audience and provide them with personalized experiences.
    
    Thanks to its intuitive design and easy-to-use interface, even the most technologically challenged crewmembers can navigate it with ease. It be built on strong foundations and follows modern standards, so ye can be sure it'll last ye through the toughest of storms.
    
    And best of all, it be available to all ye who dare to take the plunge, with affordable rates that won't plunder yer coffers. So come aboard, me hearties, and lay yer hands on the ChatGPT API, and ye'll be shiverin' the timbers of yer competitors in no time!

    이제 API 쓰는 법도 알았으니, 추후 나만의 어플리케이션에 ChatGPT를 쓰기를 기대해본다! Good Luck 🎈🎈

     


    Reference

    https://platform.openai.com/docs/libraries/python-bindings

     

    OpenAI API

    An API for accessing new AI models developed by OpenAI

    platform.openai.com

     

    반응형

    댓글

Written by Emily.