1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ChatGPT をターミナルで動かす

Posted at

OpenAI ChatGPT API を使って、ターミナルで ChatGPT を動かす。

'''Chat with OpenAI GPT-3
How to use:
# 1. Install the OpenAI Python library
# pip install openai
# 2. Get your OpenAI API key from https://beta.openai.com/account/api-keys
# 3. Set your OpenAI API key as an environment variable, e.g.: export OPENAI_API_KEY=<YOUR_API_KEY>

How to run:
# python chat.py
'''
import openai


messages = [{"role": "system", "content": "あなたは優秀な助手です。"}]

while True:

    # 入力を受け取る。改行を含む文章を入力できるようにする。
    prompt = ''
    while input_text := input("Q: "):
        prompt += input_text
    messages.append({"role": "user", "content": prompt})

    # OpenAI GPT-3 に入力を渡す
    r = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages,
        temperature=0.9,
        max_tokens=1200,
        top_p=1,
        frequency_penalty=0.5,
        presence_penalty=0.5,
    )

    # 返答を表示する
    res_text = r.choices[0].message.content
    print(f'A: {res_text}')

    # 返答をメッセージに追加する
    messages.append({"role": "assistant", "content": res_text})

ポイント

  • role という概念がある。 system はメタ的な指示。 user はあなたのインプット。 assistant は ChatGPT からのレスポンス

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?