LoginSignup
1
1
この記事誰得? 私しか得しないニッチな技術で記事投稿!

gpt3.5turboでしりとりbotを作ってみた

Last updated at Posted at 2023-06-16
1 / 8

目的

gpt4 api waitlistに並ぶ時の目的にしりとりbotって書いちゃったので@elonmuskに悪いので作ります


chatgptとしりとりをしよう!

できるか聞いてやってみました

トークのリンク

できるようです。なのでプログラムを書いてもらいましょう


環境とコード

環境はほぼ今の最新(2023/06/14)です

Name Version
python3 3.11.3
openai 0.27.8
json 不明
Pyaudio 0.2.13
wave 不明
requests 2.28.2
argparse 不明
main.py
import openai
import json
import os
import pyaudio
import wave
import requests
import argparse

openai.api_key = "APIKEY"

def whisper():
    model_id = "whisper-1"
    file_path = "latest.wav"
    with open(file_path, "rb") as audio_file:
        response = openai.Audio.transcribe(
            file=audio_file,
            model=model_id,
            response_format="text"
        )
    print("今あなたが言った事:"+response)
    return(response)


def rokuon():

    # 録音設定
    CHUNK = 1024  # バッファサイズ
    FORMAT = pyaudio.paInt16  # サンプルサイズ
    CHANNELS = 1  # モノラル
    RATE = 44100  # サンプリングレート
    RECORD_SECONDS = 2  # 録音する秒数
    OUTPUT_FILE = "latest.wav"  # 録音データの保存先ファイル名

# PyAudioオブジェクトの作成
    audio = pyaudio.PyAudio()

# 録音ストリームの開始
    stream = audio.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK)

    print("聞き取っています..")

    frames = []  # 録音データを格納するリスト

    # 録音データの取得
    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)

    print("分析しています..")

    stream.stop_stream()
    stream.close()
    audio.terminate()

    wf = wave.open(OUTPUT_FILE, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(audio.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()

HOSTNAME='localhost'

def gpt35turbo(prompt):
    completion = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are playing a game of shiritori with a bot. 回答は必ず日本語"},
            {"role": "user", "content": prompt}
        ]
    )
    
    response = completion.choices[0].message
    bot_response = response['content']
    
    return bot_response

def play_shiritori():
    print("しりとりbotへようこそ!")
    print("スタートするには最初の単語を入力してね!")
    
    while True:
        user_input = input("あなた: ")
        #rokuon()
        #user_input = whisper()
        
        if user_input[len(user_input) - 1] == "":
            print("んがついてるよーばいばいー")
            break
        if user_input.lower() == "やめる":
            print("プレイ感謝!")
            break
        
        bot_response = gpt35turbo(user_input)
        print("しりとりbot:", bot_response)

play_shiritori()

コードです。
内容はみて感じ取っていただきたいのですが、とりあえずまだrokuonとwhisperは殺してあります
解説するとwhisperはほぼこれのコピペです


動かすとこんな感じです↓

Bash
mimikonadeshiko@udon$ shiritori % python3 main.py
しりとりbotへようこそ!
スタートするには最初の単語を入力してね!
あなた:   にく
しりとりbot  : くつした
あなた: たんぽぽ
しりとりbot  : ポテト
あなた: とんかつ
しりとりbot  : すし

たまに変なことを言うけどまぁまぁいい感じです


そして音声を有効化(下記部分をアンコメント)すると

main.py
        #rokuon()
        #user_input = whisper()

音声しりとりができました!!!

実際動かしてみました、個人の感想ですが 結構認識精度は高い気がします。



突然ですがしりとりしていて字が詰まるときってありますよね

そうなんです こいつが言ってから2秒以内に喋らなければいけないスーパー鬼畜しりとりbotなので
enterキーを押すまで話を聞かない仕様に変更しました


main.py
        key = input("言う言葉が決まったらenterキーを押してね..  ")
        if key == "":
            rokuon()

これでしりとりで字が詰まっても大丈夫ですね!

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