19
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

StreamlitでChatGPTのStreamを表示する

Posted at

環境

  • 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

参考

19
10
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
19
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?