DS DevShelfHub Projects · AI tools
Tutorials / LangChain / Reference / Classes / InMemoryChatMessageHistory
Memory langchain-core Beginner

InMemoryChatMessageHistory: Reference Guide

By DevShelfHub

Store conversation history in memory.

What is InMemoryChatMessageHistory?

InMemoryChatMessageHistory stores a list of BaseMessage objects in a Python dict keyed by session ID. It implements the BaseChatMessageHistory interface, which means it can be dropped into RunnableWithMessageHistory as the get_session_history factory — no other changes needed. Because storage is in-process, the history is gone when the process exits.

The typical usage pattern is to create one InMemoryChatMessageHistory per logical session and store them in a module-level dict keyed by session_id. The RunnableWithMessageHistory wrapper then calls your factory, retrieves the right history object, prepends the stored messages to each new input before invoking the chain, and appends the output to the history automatically. You never manipulate the message list directly.

For development this is ideal — zero dependencies, instant setup, easy to inspect with .messages. For any deployment where conversations must survive a restart (or where multiple server processes run), migrate to a persistent store. LangChain ships SQLChatMessageHistory (SQLite/PostgreSQL), RedisChatMessageHistory, and DynamoDBChatMessageHistory — all share the same BaseChatMessageHistory interface, so swapping is a one-line change.

When to Use

You're developing a chatbot or prototype. Use InMemoryChatMessageHistory for development.

Use Cases

  • Development testing
  • Prototype chatbots
  • Temporary conversations
  • CLI tools
  • Session-based chat
  • Testing

Key Features

  • Simple storage
  • Fast access
  • No external DB
  • Easy to use
  • RunnableWithMessageHistory compatible
  • Debug-friendly

When NOT to Use

For production—use persistent storage (PostgreSQL, Redis).

Notes

History is per-process and not thread-safe by default

The shared store dict is not protected by a lock. In async or multi-threaded servers, concurrent writes to the same session_id can corrupt the message list. Use a threading.Lock or async lock around store access, or switch to a database-backed store (SQLChatMessageHistory, RedisChatMessageHistory) which handles concurrency natively.

RunnableWithMessageHistory expects a specific input key

By default, RunnableWithMessageHistory looks for "input" in the invocation dict and "history" or "chat_history" in the chain prompt. Pass input_messages_key="input" and history_messages_key="chat_history" explicitly if your prompt uses different placeholder names to avoid a KeyError at runtime.

Migrating to persistent storage is a one-line swap

Replace InMemoryChatMessageHistory with SQLChatMessageHistory(session_id=..., connection="sqlite:///chat.db") in your get_session_history factory. The interface is identical — no other code changes. For Redis: RedisChatMessageHistory(session_id=..., url="redis://localhost:6379").

clear() wipes the session but does not delete the key

Calling history.clear() empties the message list but leaves the key in your store dict. If you want to truly reset a session and reclaim memory, delete the key: del store[session_id]. This matters in long-running services with many short-lived sessions.

Import

python
from langchain_core.chat_history import InMemoryChatMessageHistory

Usage Examples

Per-session History with RunnableWithMessageHistory

python
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory

store = {}

def get_session_history(session_id: str):
    if session_id not in store:
        store[session_id] = InMemoryChatMessageHistory()
    return store[session_id]

with_history = RunnableWithMessageHistory(chain, get_session_history)

Multi-turn Session with Persistent Context

python
config = {"configurable": {"session_id": "user-123"}}
response1 = with_history.invoke(
    {"input": "My name is Alice"},
    config=config,
)
response2 = with_history.invoke(
    {"input": "What is my name?"},
    config=config,
)  # Returns "Alice" — history was retained

Inspect Stored Message History

python
# Inspect stored messages at any time
history = store["user-123"]
for msg in history.messages:
    print(type(msg).__name__, ":", msg.content[:60])

Common Pitfalls

❌ Use in production—data lost on restart

✅ Use PostgresSaver or equivalent for production

Browse the full LangChain API reference index to explore more classes, methods, and decorators, or start with the LangChain introduction tutorial for end-to-end context on building with InMemoryChatMessageHistory and the wider framework.

InMemoryChatMessageHistory FAQ

What is InMemoryChatMessageHistory in LangChain?

Store conversation history in memory. InMemoryChatMessageHistory stores a list of BaseMessage objects in a Python dict keyed by session ID. It implements the BaseChatMessageHistory interface, which means it can be dropped into RunnableWithMessageHistory as the get_session_history factory — no other changes needed. Because storage is in-process, the history is gone when the process exits. The typical usage pattern is to create one InMemoryChatMessageHistory per logical session and store them in a module-level dic…

Which package provides InMemoryChatMessageHistory?

DevShelfHub documents InMemoryChatMessageHistory from the langchain-core package. Pin your installed LangChain version and match imports to the snippet on this page.

When should I use InMemoryChatMessageHistory?

You're developing a chatbot or prototype. Use InMemoryChatMessageHistory for development.

When should I avoid using InMemoryChatMessageHistory?

For production—use persistent storage (PostgreSQL, Redis).

How do I import InMemoryChatMessageHistory in Python?

from langchain_core.chat_history import InMemoryChatMessageHistory

Where can I explore more LangChain API reference pages?

Open the LangChain API reference index on DevShelfHub to browse classes, methods, and decorators, each with runnable examples, parameters, common mistakes, and cross-links.