Chat Models
LangChainのChatModelsは、会話型のAIチャットボットを開発するためのモジュールで、前提条件やコンテキストに基づいて応答することができるなど、会話の流れを管理するための機能を提供するよう設計されています。
AIと会話してみる
chat-memory-sample.py
import json
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain.schema import messages_to_dict
from langchain.prompts.chat import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
# ChatOpenAIクラスのインスタンスを作成、temperatureは0.7を指定
chat = ChatOpenAI(temperature=0.7)
# 会話の履歴を保持するためのオブジェクト
memory = ConversationBufferMemory(return_messages=True)
# テンプレートを定義
template = """
以下は、人間とAIのフレンドリーな会話です。
AIはその文脈から具体的な内容をたくさん教えてくれます。
AIは質問の答えを知らない場合、正直に「知らない」と答えます。
"""
# テンプレートを用いてプロンプトを作成
prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template(template),
MessagesPlaceholder(variable_name="history"),
HumanMessagePromptTemplate.from_template("{input}")
])
# AIとの会話を管理
conversation = ConversationChain(llm=chat, memory=memory, prompt=prompt)
# ユーザからの入力を受け取り、変数commandに代入
command = input("You: ")
while True:
response = conversation.predict(input=command)
print(f"AI: {response}")
command = input("You: ")
if command == "exit":
break
# memoryオブジェクトから会話の履歴を取得して、変数historyに代入
history = memory.chat_memory
# 会話履歴をJSON形式の文字列に変換、整形して変数messagesに代入
messages = json.dumps(messages_to_dict(history.messages), indent=2, ensure_ascii=False)
# 会話履歴を表示
print(f"memory: {messages}")
動画
会話の内容を保持してチャットのやり取りが成立している事がわかりますね。
おわりに
前回LangChainのLLMsモデルを試した際にはこちらでScript内で会話が成立するように予め記述してましたが、ChatModelsではリアルタイムで会話が可能で、更に内容も保持されている事が確認できました。LLMs同様にAgentを使うことでGoogle検索と連携させることも可能なのでより最新情報を用いた会話も可能です。
参照