Claude3 API で遊ぶDiscord bot
はじめに
Claude3はAntoropicのLLMです
Proプラン(月額 $20)のOpusモデルは部分的にはGPT4を超えた…!
とか最近騒がれている気がするClaude3ですが、
APIだったらサブスク無しでも使えるかなーとか思い
Discord botに組み込むことにしました
なお、Claude3のAPIの設定などは以下のnpakaさんnoteを大変参考にしています
Google Colab で Claude 3 の テキスト生成 を試す|npaka (note.com)
また、Discord Bot自体の作り方については、えるさんの過去noteを参照いただければ
Discord bot with chatGPT 作成日記|える (note.com)
それにしても、、最近noteの文中のリンクが展開されなくって困ってるんですよね…
なんで??
実装方法
まずはnpakaさんnoteを参考に以下を実施します
・APIキーの取得
・パッケージのインストール
・環境変数の準備
次に、実装部分を作っていきます
だいたい参考noteの通りなんですが、以下の感じにしました
import discord
import os
import anthropic
### discord initial
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
anthropic = anthropic.Anthropic()
def split_text(text, chunk_size=1500):
# テキスト文字列をchunk_sizeで指定した大きさに分割し、リストに格納する
return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.author.bot == True:
return
await message.channel.send("---")
input_text = message.content
answer = anthropic.messages.create(
model="claude-3-opus-20240229",
max_tokens=1000,
temperature=0.2,
system="あなたは優秀なAIアシスタントです。",
messages=[
{"role": "user", "content": input_text}
]
)
splitted_text = split_text(answer.content[0].text)
for chunk in splitted_text:
await message.channel.send(chunk)
client.run(os.environ['BOT_KEY'])
解説は、、まあ参考noteにだいたい書いてるしいいかな?
この記述をファイル(例えばmain.py)に記載して
実行(例えばpython main.py) するとBotが起動するので
後はdiscordてやり取りします
結果
出来ました!✨
この結果はsonnetですが、レスポンスはサックサクだし
回答内容も思ったよりいい感じです
今の実装では過去会話が参照出来ないのですが、
実装を見直しても良いし、使い方でカバーしてもいいかなあとか思ったり
この記事が気に入ったらサポートをしてみませんか?