今回はAIチャットボットを作れる「Chainlit」を使ってみたいと思います。
Chainlitとは?
Chainlitは、チャットボットインターフェースを手軽に構築できるPythonライブラリです。
チャットボットを作成するのに。必要な機能が一通り用意されている他、LangChainとの連携により、会話型AIや対話アプリケーションの開発を容易にし、特定の言語変換機能など、多様なチェーンを組み込むことが可能です。
Chainlitの使い方
前提条件としてPythonがインストールされている必要があります。
pip install chainlit
インストールが完了したら以下のコマンドで実行してください。
chainlit hello
ブラウザで以下のようなチャットUIが表示されたらセットアップは完了です。
またhttp://localhost:8000 からもアクセスできます。

ここまでセットアップは完了です。
ChainlitにLangChainを統合する方法
次の公式サイトの情報をもとに実装してみます。
LangChain - Chainlit
LangChainについては以下の記事から
大規模言語モデルを自由に操れるPythonライブラリ「Langchain」を使ってみた
まず必要なPythonライブラリをインストールします。
pip install langchain
pip install python-dotenv
langchainが大規模言語モデルを扱うためのライブラリでpython-dotenvがAPIキーを.envファイルから環境変数として設定するためライブラリです。
Chainlitのルートディレクトリにapp.pyファイルと.envファイルを作成します。
app.py
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.schema import StrOutputParser
from langchain.schema.runnable import Runnable
from langchain.schema.runnable.config import RunnableConfig
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')
import chainlit as cl
@cl.on_chat_start
async def on_chat_start():
model = ChatOpenAI(api_key=api_key, model="gpt-3.5-turbo", streaming=True)
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"Please provide appropriate responses to the questions.",
),
("human", "{question}"),
]
)
runnable = prompt | model | StrOutputParser()
cl.user_session.set("runnable", runnable)
@cl.on_message
async def on_message(message: cl.Message):
runnable = cl.user_session.get("runnable")
msg = cl.Message(content="")
async for chunk in runnable.astream(
{"question": message.content},
config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
):
await msg.stream_token(chunk)
await msg.send()
.env
OPENAI_API_KEY=Your-API-Key
.envのYour-API-Keyは実際のAPIキーを設定して下さい。
APIキーの設定は次から
OpenAIのAPIとは?概要からAPIキーを取得する方法まで
アプリを実行する
ターミナルを開いてapp.pyが含まれるディレクトリに移動します。
その後、以下のコマンドを実行してください。
chainlit run app.py -w
http://localhost:8000でアクセスが可能になります。
実行するとチャットの画面が表示され会話することができます。
