チャットボットアプリケーションのプログラム(Python,LangChain,OpenAI API を使用)(Windows 上)
LangChain と ChatGPT を使って2種類のチャットボットを実行する説明である. 1つ目は,LangChain の公式ページに記載のプログラムをほぼそのまま実行. メッセージを日本語に翻訳することを行うコマンドラインチャットボットである. ここでは,dotenvを使用して環境変数 OPENAI_API_KEY を読み込み,翻訳を実行する. 2つ目はユーザー入力に応答し,会話履歴を保存しながら,GUI上に表示する対話型チャットボットのアプリケーションである. Tkinterを用いてGUIを構築し,ユーザーからのメッセージはテキストフィールドで受け付け,会話履歴の表示にはリストボックスとスクロールバーを使用している. 各プログラムはPythonで実現されている. ソースコードと実行手順を記載している.
【目次】
【関連する外部ページ】
- LangChain の 公式のページ: https://www.langchain.com/
- LangChain の ChatBot ユースケースのページ: https://python.langchain.com/v0.1/docs/use_cases/chatbots/
チャットボットのアプリ
前準備
Python 3.10 のインストール(Windows 上)
Pythonは,プログラミング言語の1つ.
【手順】
- Windows で,コマンドプロンプトを管理者として実行
コマンドプロンプトを管理者として実行: 別ページ »で説明
- 次のコマンドを実行
次のコマンドは,Python ランチャーとPython 3.10をインストールする.
【関連する外部ページ】
- Python の公式ページ: https://www.python.org/
【サイト内の関連ページ】
【関連項目】 Python
LangChain を使用したチャットボットの Python プログラム(Python,LangChain,OpenAI API を使用)(Windows 上)
OpenAPI の API キーの取得
OpenAI の APIキーを準備する
【関連する外部ページ】
- OpenAI の API キーのページ
- 料金の条件や利用履歴はこちらで確認.
OpenAPI の API キーを .env ファイルに保存
- OpenAI の APIキーを準備する
OpenAI の APIキーのページ
https://platform.openai.com/api-keys
料金の条件や利用履歴はこちらで確認.
- Windows で,コマンドプロンプトを実行
- エディタを起動
cd /d c:%HOMEPATH% rmdir /s /q langchain mkdir langchain cd langchain type nul > .env notepad .env
- エディタで 「export OPENAI_API_KEY=sk-...」のように書く.
「sk-...」の部分は,OpenAI の APIキー を設定する.
dotenv, LangChain, openai のインストール
- Windows で,コマンドプロンプトを管理者として実行
コマンドプロンプトを管理者として実行: 別ページ »で説明
- 次のコマンドを実行.
python -m pip install -U --ignore-installed pip python -m pip install -U python-dotenv python -m pip install -U langchain openai
プログラム1.LangChain を使用したチャットボットを動かしてみる
【関連する外部ページ】
- LangChain の 公式のページ: https://www.langchain.com/
- LangChain の ChatBot ユースケースのページ: https://python.langchain.com/v0.1/docs/use_cases/chatbots/
- Windows で,コマンドプロンプトを実行
- エディタを起動
cd /d c:%HOMEPATH% cd langchain notepad chatbot1.py
- エディタで,次のプログラムを保存
このプログラムは, LangChain の ChatBot ユースケースのページ: https://python.langchain.com/v0.1/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 プログラムの実行
- Windows では python (Python ランチャーは py)
- Ubuntu では python3
Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.
Python のまとめ: 別ページ »にまとめ
プログラムを chatbot1.pyのようなファイル名で保存したので, 「python chatbot1.py」のようなコマンドで行う.
python chatbot1.py
- 実行の結果,OpenAI API 経由でチャットが実行され,結果が表示される.
プログラム2.LangChain を使用したチャットボットのプログラム(画面で対話)
このプログラムは,ユーザーからのメッセージを受け取り,それを OpenAI の ChatGPT に送信して応答を得て,画面に表示する. ユーザーとAIの対話履歴は保存され,画面で過去の対話も閲覧可能である.
環境変数OPENAI_API_KEYは,dotenvモジュールを使用して読み込んでいる. GUIの構築には,Tkinterライブラリを用いている. 履歴の表示にはリストボックスとスクロールバーを用い,ユーザーからのメッセージ入力はテキストフィールドで受け付け,そのメッセージの送信のために「Send」ボタンを配置している.
- Windows で,コマンドプロンプトを実行
- エディタを起動
cd /d c:%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 プログラムの実行
- Windows では python (Python ランチャーは py)
- Ubuntu では python3
Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.
Python のまとめ: 別ページ »にまとめ
プログラムを chatbot2.pyのようなファイル名で保存したので, 「python chatbot2.py」のようなコマンドで行う.
python chatbot2.py
- 実行の結果,チャットボットの画面が開き,対話ができる.