0
1

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.

NiceGUIでChatGPTのStreamを表示する

Posted at

環境

  • python = 3.10
  • nicegui = 1.3.13
  • openai = 0.28.0

実装

2023-09-23-nicegui.gif

NiceGUIで、上記の図のようにChatGPTの出力結果をStreamで表示するには、次のようにします。

from nicegui import ui
import openai

input_text = ui.input(label="入力")
result = ui.label()

async def generate(e):
    input_text = e.sender.value
    completion = await openai.ChatCompletion.acreate(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": input_text}],
        max_tokens=100,
        stream=True,
    )
    async for chunk in completion:
        next = chunk['choices'][0]['delta'].get('content', '')
        result.text += next

input_text.on("keydown.enter", generate)


ui.run()

NiceGUIは、非同期でイベントハンドラーを定義しないと表示の更新がブロックされてしまいます。ChatCompletionで、create()ではなくacreate()を使い、stream=Trueとすることで非同期ジェネレータで返却されるため、これを扱うことでストリームを表示できます。

参考

0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?