DEV Community

KENTO⚽️XR Engineer😎
KENTO⚽️XR Engineer😎

Posted on

【ChatGPT 】How to use a chat function from API with Python?

Environment

MacOS
MacBook Pro (M2 chip)


Step 1: Set Up Account

First step, you have to set up and make contract your account.
https://platform.openai.com/overview

Pricing is a below link.
https://openai.com/pricing


Step 2: Set Up Python

Install command.

$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
$ python3 get-pip.py 
Enter fullscreen mode Exit fullscreen mode

Write .zshrc.

$ vi ~/.zshrc 
Enter fullscreen mode Exit fullscreen mode

Pressed i is entering an insert mode and finish edit Esc, exit is :wq)

alias pip='pip3'

Apply .zshrc.

$ source ~/.zshrc
Enter fullscreen mode Exit fullscreen mode

If successful, you will be able to use pip command.


Step 3: Set Up OpenAI

Install command.

$ pip install openai 
Enter fullscreen mode Exit fullscreen mode

Step 4: Fix environment

I faced a problem about this error.

urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with LibreSSL 2.8.3. See: https://github.com/urllib3/urllib3/issues/2168

I've tried two approaches, changing ssh and downgrading the module.

Changing ssh command.

$ brew install openssl
$ echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
Enter fullscreen mode Exit fullscreen mode

If you can't use brew command although it have already installed, change "using Rosetta" on terminal. (You can change it on tarminal info from opening Finder)

Changing urllib3 version command.

$ pip install urllib3==1.25.11
Enter fullscreen mode Exit fullscreen mode

Step 5: Run sample Code


import openai
openai.api_key = "sk-***********************************"

content = ''' You roleplay as the know-it-all, talkative Johnson.
              Behave like Johnson and speak without using honorifics or polite language.
              Johnson's Code of Conduct:
              * Please ask if you need more information to get the best answer.
              * Don't repeat what the user said.'''

res = openai.ChatCompletion.create(
   model="gpt-3.5-turbo",
   messages=[
       {
           "role": "system",
           "content": content
       },
       {
           "role": "user",
           "content": "Who are you?"
       }
   ],
)
print(res)
print(res["choices"][0]["message"]["content"])
Enter fullscreen mode Exit fullscreen mode

You can check API documentation.
https://platform.openai.com/docs/api-reference/chat/create

References

【最新速報】ChatGPT APIの「概要と使い方」(Pythonコード付き)
macOS High Sierra(OSX)のOpenSSLをデフォルトのLibreSSLからOpenSSLに変更する
【解決法】Cannot install in Homebrew on ARM processorエラーの解決法【m1チップ】
OpenAIのAPI料金の計算方法
OpenAI GPT-3 APIの使い方を解説

Top comments (0)