LoginSignup
7

StreamlitでChatGPTのStreamを表示する

環境

  • Python 3.10
  • Streamlit 1.21.0
  • openai 0.27.4

Colab (Jupyter)

Colabなどを用いてChatGPTのstream=Trueにした時にストリームで表示するにはいくつか方法が考えられますが、print(end='')などで連結しながら出力するのが手軽だと思います。

import openai

completion = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "昔々あるところに"}],
    stream=True,
)
for chunk in completion:
    next = chunk['choices'][0]['delta'].get('content', '')
    print(next, end='')

2023-04-16_chatgpt_colab.gif

お好みに応じて、以下のコードで途中に改行を入れたりします。

if "。" in next:
    print("")

Streamlit

StreamlitでChatGPTのStreamを出力するには、streamlit.empty()で要素のコンテナを作っておいて、連結したテキストを都度表示します。

import openai
import streamlit

input_text = streamlit.text_input('入力')
if len(input_text) > 0:
    completion = openai.ChatCompletion.create(
        model='gpt-3.5-turbo',
        messages=[{"role": "user", "content": input_text}],
        stream=True,
    )
    result_area = streamlit.empty()
    text = ''
    for chunk in completion:
        next = chunk['choices'][0]['delta'].get('content', '')
        text += next
        result_area.write(text)

2023-04-16_chatgpt_streamlit.gif

参考

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
What you can do with signing up
7