🍏

discordbotにgpt-3.5-turboを組み込んだ

2023/03/03に公開

目的

  • gpt-3.5-turbo で会話の流れを考慮した対話ができるようになったっぽいので、discordbot に組み込む方法を考えた

想定

  • 動作する discord.py の bot がある

つくったもの

https://twitter.com/satory074/status/1631300256099909634

ソースコード

https://github.com/satory074/discordbot_chatgpt_sample


簡易解説

discord.py による bot 作成

discord.py による bot の作成方法は以下が参考になります。

古めの記事なので、bot の権限周りでエラーが発生すると思いますが、
この記事のソースコードと合わせて見て頂ければ動くかもしれません。

https://qiita.com/1ntegrale9/items/9d570ef8175cf178468f

会話履歴の作成

この記事のソースコードでは、chatgpt関数で返答取得のための会話履歴の作成を行っています。

「@」で会話を開始して以降の会話はスレッド内で行う、という方針をとり、
取得したスレッドのメッセージ履歴を、会話履歴として API を叩き、返答を取得しています。

chatGPT 仕様

OpenAI のドキュメントを読めばだいぶ動かせました。

https://platform.openai.com/docs/guides/chat?utm_medium=email&_hsmi=248356722&_hsenc=p2ANqtz-_k5-bc6Aud-31Jabul_tMFEXKbtd1OFhIrRmEi5jZA7Ze2f8hGsiY5u0CIfZl0NGoq1pXXUYnkVBGdM-ViA0f_572Jlg&utm_content=248356722&utm_source=hs_email

以下は返答を取得するための会話履歴を作成しています。

この記事のソースコードでは、ユーザの会話をuser、bot の会話をassistantとしてリストを作成しました。

# Note: you need to be using OpenAI Python v0.27.0 for the code below to work
import openai

openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
        {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
        {"role": "user", "content": "Where was it played?"}
    ]
)

以下は OpenAI からの返答内容です。

この記事のソースコードでは、choicesmessagecontent\nで結合したものを返答しています。

{
    "id": "chatcmpl-6p9XYPYSTTRi0xEviKjjilqrWU2Ve",
    "object": "chat.completion",
    "created": 1677649420,
    "model": "gpt-3.5-turbo",
    "usage": { "prompt_tokens": 56, "completion_tokens": 31, "total_tokens": 87 },
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "The 2020 World Series was played in Arlington, Texas at the Globe Life Field, which was the new home stadium for the Texas Rangers."
            },
            "finish_reason": "stop",
            "index": 0
        }
    ]
}

おわりに

bot と会話してたら 1 日が終わった

GitHubで編集を提案

Discussion