AWS DynamoDB
Amazon AWS DynamoDB is a fully managed
NoSQL
database service that provides fast and predictable performance with seamless scalability.
This notebook goes over how to use DynamoDB
to store chat message history with DynamoDBChatMessageHistory
class.
Setup
First make sure you have correctly configured the AWS CLI. Then make sure you have installed the langchain-community
package, so we need to install that. We also need to install the boto3
package.
pip install -U langchain-community boto3
It's also helpful (but not needed) to set up LangSmith for best-in-class observability
# os.environ["LANGSMITH_TRACING"] = "true"
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass()
from langchain_community.chat_message_histories import (
DynamoDBChatMessageHistory,
)
Create Table
Now, create the DynamoDB
Table where we will be storing messages:
import boto3
# Get the service resource.
dynamodb = boto3.resource("dynamodb")
# Create the DynamoDB table.
table = dynamodb.create_table(
TableName="SessionTable",
KeySchema=[{"AttributeName": "SessionId", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "SessionId", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
# Wait until the table exists.
table.meta.client.get_waiter("table_exists").wait(TableName="SessionTable")
# Print out some data about the table.
print(table.item_count)
0
DynamoDBChatMessageHistory
history = DynamoDBChatMessageHistory(table_name="SessionTable", session_id="0")
history.add_user_message("hi!")
history.add_ai_message("whats up?")
history.messages
[HumanMessage(content='hi!'), AIMessage(content='whats up?')]
DynamoDBChatMessageHistory with Custom Endpoint URL
Sometimes it is useful to specify the URL to the AWS endpoint to connect to. For instance, when you are running locally against Localstack. For those cases you can specify the URL via the endpoint_url
parameter in the constructor.
history = DynamoDBChatMessageHistory(
table_name="SessionTable",
session_id="0",
endpoint_url="http://localhost.localstack.cloud:4566",
)
DynamoDBChatMessageHistory With Composite Keys
The default key for DynamoDBChatMessageHistory is {"SessionId": self.session_id}
, but you can modify this to match your table design.