Memory, base class¶
This implements the Cassandra-specific I/O facilities, and is then used by LangChain to power every other, more sophisticated, abstraction around keeping chat memory.
In [1]:
Copied!
from langchain.memory import CassandraChatMessageHistory
from langchain.memory import CassandraChatMessageHistory
A database connection is needed. (If on a Colab, the only supported option is the cloud service Astra DB.)
In [2]:
Copied!
# Ensure loading of database credentials into environment variables:
import os
from dotenv import load_dotenv
load_dotenv("../../../.env")
import cassio
# Ensure loading of database credentials into environment variables:
import os
from dotenv import load_dotenv
load_dotenv("../../../.env")
import cassio
Select your choice of database by editing this cell, if needed:
In [3]:
Copied!
database_mode = "cassandra" # "cassandra" / "astra_db"
database_mode = "cassandra" # "cassandra" / "astra_db"
In [4]:
Copied!
if database_mode == "astra_db":
cassio.init(
database_id=os.environ["ASTRA_DB_ID"],
token=os.environ["ASTRA_DB_APPLICATION_TOKEN"],
keyspace=os.environ.get("ASTRA_DB_KEYSPACE"), # this is optional
)
if database_mode == "astra_db":
cassio.init(
database_id=os.environ["ASTRA_DB_ID"],
token=os.environ["ASTRA_DB_APPLICATION_TOKEN"],
keyspace=os.environ.get("ASTRA_DB_KEYSPACE"), # this is optional
)
In [5]:
Copied!
if database_mode == "cassandra":
from cqlsession import getCassandraCQLSession, getCassandraCQLKeyspace
cassio.init(
session=getCassandraCQLSession(),
keyspace=getCassandraCQLKeyspace(),
)
if database_mode == "cassandra":
from cqlsession import getCassandraCQLSession, getCassandraCQLKeyspace
cassio.init(
session=getCassandraCQLSession(),
keyspace=getCassandraCQLKeyspace(),
)
Create the ChatMessageHistory¶
In [6]:
Copied!
message_history = CassandraChatMessageHistory(
session_id='test-session',
session=None,
keyspace=None,
ttl_seconds = 3600,
)
message_history.clear()
message_history = CassandraChatMessageHistory(
session_id='test-session',
session=None,
keyspace=None,
ttl_seconds = 3600,
)
message_history.clear()
The memory starts empty:
In [7]:
Copied!
message_history.messages
message_history.messages
Out[7]:
[]
Insert and retrieve chat messages¶
In [8]:
Copied!
message_history.add_user_message('Hello, I am human.')
message_history.add_user_message('Hello, I am human.')
In [9]:
Copied!
message_history.add_ai_message('Hello, I am the bot.')
message_history.add_ai_message('Hello, I am the bot.')
In [10]:
Copied!
message_history.messages
message_history.messages
Out[10]:
[HumanMessage(content='Hello, I am human.', additional_kwargs={}, example=False), AIMessage(content='Hello, I am the bot.', additional_kwargs={}, example=False)]
In [11]:
Copied!
message_history.clear()
message_history.clear()
In [12]:
Copied!
message_history.messages
message_history.messages
Out[12]:
[]