16
9

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のChatModelsとMemoryを使ってチャット上で会話を記憶させる

Last updated at Posted at 2023-04-05

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}")

動画

会話の内容を保持してチャットのやり取りが成立している事がわかりますね。
sample_out (1).gif

おわりに

前回LangChainのLLMsモデルを試した際にはこちらでScript内で会話が成立するように予め記述してましたが、ChatModelsではリアルタイムで会話が可能で、更に内容も保持されている事が確認できました。LLMs同様にAgentを使うことでGoogle検索と連携させることも可能なのでより最新情報を用いた会話も可能です。

参照

16
9
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
16
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?