LangChain と ChatGPT を使って2種類のチャットボットを実行する説明である. 1つ目は,LangChain の公式ページに記載のプログラムをほぼそのまま実行. メッセージを日本語に翻訳することを行うコマンドラインチャットボットである. ここでは,dotenvを使用して環境変数 OPENAI_API_KEY を読み込み,翻訳を実行する. 2つ目はユーザー入力に応答し,会話履歴を保存しながら,GUI上に表示する対話型チャットボットのアプリケーションである. Tkinterを用いてGUIを構築し,ユーザーからのメッセージはテキストフィールドで受け付け,会話履歴の表示にはリストボックスとスクロールバーを使用している. 各プログラムはPythonで実現されている. ソースコードと実行手順を記載している.
【目次】
【関連する外部ページ】
チャットボットのアプリ
【サイト内の関連ページ】
【関連する外部ページ】
Python の公式ページ: https://www.python.org/
OpenAI の APIキーを準備する
【関連する外部ページ】
OpenAI の APIキーのページ
https://platform.openai.com/account/api-keys
料金の条件や利用履歴はこちらで確認.
cd %HOMEPATH% rmdir /s /q langchain mkdir langchain cd langchain type nul > .env notepad .env
「sk-...」の部分は,OpenAI の APIキー を設定する.
コマンドプロンプトを管理者として実行: 別ページ »で説明
python -m pip install -U --ignore-installed pip python -m pip install -U python-dotenv python -m pip install -U langchain openai
【関連する外部ページ】
cd %HOMEPATH% cd langchain notepad chatbot1.py
このプログラムは, LangChain の ChatBot ユースケースのページ: https://python.langchain.com/docs/use_cases/chatbots/ の「QuickStart」で公開されていたものを書き換えて使用している.
import dotenv dotenv.load_dotenv() from langchain.schema import AIMessage, HumanMessage, SystemMessage from langchain.chat_models import ChatOpenAI chat = ChatOpenAI() messages = [ SystemMessage(content="You are a helpful assistant that translates English to Japanese."), HumanMessage(content="I love programming.") ] print(chat(messages))
Python プログラムの実行
Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.
Python のまとめ: 別ページ »にまとめ
プログラムを chatbot1.pyのようなファイル名で保存したので, 「python chatbot1.py」のようなコマンドで行う.
python chatbot1.py
このプログラムは,ユーザーからのメッセージを受け取り,それを OpenAI の ChatGPT に送信して応答を得て,画面に表示する. ユーザーとAIの対話履歴は保存され,画面で過去の対話も閲覧可能である.
環境変数OPENAI_API_KEYは,dotenvモジュールを使用して読み込んでいる. GUIの構築には,Tkinterライブラリを用いている. 履歴の表示にはリストボックスとスクロールバーを用い,ユーザーからのメッセージ入力はテキストフィールドで受け付け,そのメッセージの送信のために「Send」ボタンを配置している.
cd %HOMEPATH% cd langchain notepad chatbot2.py
import dotenv dotenv.load_dotenv() from langchain.schema import ( AIMessage, HumanMessage, SystemMessage ) from langchain.chat_models import ChatOpenAI import tkinter as tk import textwrap #TEMPERATURE = 0 #MODEL_NAME = 'gpt-3.5-turbo' #chat = ChatOpenAI(temperature=TEMPERATURE, model_name=MODEL_NAME) chat = ChatOpenAI() WIDTH = 50 def do_chat(user_message): messages = [ SystemMessage(content="You are a helpful assistant. Do not include offensive, discriminatory or emotional language in your answers. You are always calm. You can answer all kinds of questions You can also give advice of all kinds. You can create Python programs, and develop programming ideas. You are as vivacious, idea-rich, and creative. Please answer in Formal Japanese. Thank you."), HumanMessage(content=user_message) ] ai_message = chat(messages) return ai_message.content def send_message(): user_message = entry_field.get("1.0", tk.END) first_line = True for part in user_message.split('\n'): wrapped_message = textwrap.wrap(part, width=50) for line in wrapped_message: if first_line: chat_history.insert(tk.END, "Q: " + line) first_line = False else: chat_history.insert(tk.END, line) entry_field.delete("1.0", tk.END) user_message = user_message.replace("\t", "").replace("\r", "").replace("\n", "") ai_message = do_chat(user_message) first_line = True for part in ai_message.split('\n'): wrapped_ai_message = textwrap.wrap(part, width=50) for line in wrapped_ai_message: if first_line: chat_history.insert(tk.END, "A: " + line) first_line = False else: chat_history.insert(tk.END, line) root = tk.Tk() root.title("Chat with AI") frame = tk.Frame(root) scroll = tk.Scrollbar(frame) chat_history = tk.Listbox(frame, yscrollcommand=scroll.set, width=2 * WIDTH) scroll.pack(side=tk.RIGHT, fill=tk.Y) chat_history.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) frame.pack() entry_field = tk.Text(root, width=2 * WIDTH, height=5) entry_field.pack() send_button = tk.Button(root, text="Send", command=send_message) send_button.pack() root.mainloop()
Python プログラムの実行
Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.
Python のまとめ: 別ページ »にまとめ
プログラムを chatbot2.pyのようなファイル名で保存したので, 「python chatbot2.py」のようなコマンドで行う.
python chatbot2.py