ChatGPT API用 プロンプト

お約束ではあるんだけれども、これを機にプログラムに取り組んでいる人もいると思うので、サンプルを残してみる。応答メッセージ出力のところは、お好みでどうぞ。

"""
    ChatGPT API用プロンプト
"""
import openai
import time

# API設定
openai.api_key = 設定してね
# 会話履歴
history = []

# プロンプト
while True:
    # メッセージ・コマンド入力待ち 
    message = input(">").strip()

    # 問い合わせ内容なし
    if not message :
        continue
    # コマンドチェック メッセージ送信でなく操作を与える場合
    if len(message) <= 4 :
        command = message.lower()
        # 処理終了 他にもメッセージのファイル出力とか、履歴を遡る件数の設定、ヘルプがあってもいい
        if command == "exit" or command == "bye":
            break

    # メッセージを履歴に追加
    history.append({"role": "user", "content": message})
    # 10件分遡る(この辺りはパラメータにしていい)
    conversation = history[-10:]
    # 設定を与える方はここで、conversation の先頭に設定を挿入

    # メッセージ問い合わせ
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages= list(conversation)
    )
    # 応答メッセージ取得
    message = response["choices"][0]["message"]["content"]
    message = message.strip()
    # メッセージ履歴追加
    history.append({"role": "assistant", "content": message})
    # 応答メッセージ表示
    for i in range(len(message)):
        print(message[i], end="", flush=True)
        time.sleep(0.01)
    # 改行
    print("\r\n\r\n", end="")

タイトルとURLをコピーしました