RunnableWithMessageHistoryによるrunnableのラップ

あるrunnableであるsome_runnableがあるとき,会話履歴を組み込むには次の形にする.

from langchain_core.runnables.history import RunnableWithMessageHistory

with_message_history = RunnableWithMessageHistory(
runnable=some_runnable,
get_session_history=get_session_history,
input_messages_key="input",
history_messages_key="history",
output_messages_key="output",
)

with_message_history.invoke(
{"input": input},
config={"configurable": {"session_id": session_id}}
)

RunnableWithMessageHistoryは引数にとったrunnableをラップする造りである.

プロンプト

promptを引数に持ったsome_runnableでは,promptを呼び出すときにhistoryを組み入れる.

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

prompt = ChatPromptTemplate.from_messages(
[
("system", "日本語で応答するアシスタントです。"),
MessagesPlaceholder(variable_name="history"),
("human", "{input}"),
]
)

get_session_history

from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory

store = {}

def get_session_history(session_id: str) -> BaseChatMessageHistory:
if session_id not in store:
store[session_id] = ChatMessageHistory()
return store[session_id]

全履歴をとり続けるとトークンを浪費するので,ChatMessageHistoryのところは改変の必要があるかもしれない.