langchain_core.runnables.history.RunnableWithMessageHistory¶
class langchain_core.runnables.history.RunnableWithMessageHistory[source]¶
Bases: RunnableBindingBase
A runnable that manages chat message history for another runnable.
Base runnable must have inputs and outputs that can be converted to a list of BaseMessages.
RunnableWithMessageHistory must always be called with a config that contains session_id, e.g. ``{“configurable”: {“session_id”: “<SESSION_ID>”}}`.
Example (dict input):from typing import Optional
from langchain.chat_models import ChatAnthropic
from langchain.memory.chat_message_histories import RedisChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
prompt = ChatPromptTemplate.from_messages([
    ("system", "You're an assistant who's good at {ability}"),
    MessagesPlaceholder(variable_name="history"),
    ("human", "{question}"),
])
chain = prompt | ChatAnthropic(model="claude-2")
chain_with_history = RunnableWithMessageHistory(
    chain,
    RedisChatMessageHistory,
    input_messages_key="question",
    history_messages_key="history",
)
chain_with_history.invoke(
    {"ability": "math", "question": "What does cosine mean?"},
    config={"configurable": {"session_id": "foo"}}
)
# -> "Cosine is ..."
chain_with_history.invoke(
    {"ability": "math", "question": "What's its inverse"},
    config={"configurable": {"session_id": "foo"}}
)
# -> "The inverse of cosine is called arccosine ..."
Example (get_session_history takes two keys, user_id and conversation id):store = {}
def get_session_history(