4
3

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.

LangChainでChatGPTのWebみたいに返信を徐々に表示する

Last updated at Posted at 2023-05-26

ChatGPT の API を呼び出すと結果がまとめて返ってくるけど、ChatGPT の WebUI のように1文字1文字徐々に表示することもできます。LangChain を使った場合のコードはこちら。

chat.py
from typing import Any, Dict, List
from langchain.chat_models import ChatOpenAI
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import (
    LLMResult,
    HumanMessage,
)
import openai
import os


openai.api_key = os.environ.get("OPENAI_API_KEY", "")


class MyCustomCallbackHandler(BaseCallbackHandler):
    def on_llm_start(self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) -> None:
        print("START")

    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
        print("\nEND")

    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
        print(token, end="", flush=True)

    def on_llm_error(self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any) -> None:
        pass


chat = ChatOpenAI(streaming=True, callbacks=[MyCustomCallbackHandler()], temperature=0)
chat([HumanMessage(content="炭酸ソーダについての詞を書いてください。")])

streaming=Truecallbacks=[MyCustomCallbackHandler()] を指定し、 BaseCallbackHandler を継承したクラスを定義してください。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?