跳到主要內容
Open In ColabOpen on GitHub

AWS DynamoDB

Amazon AWS DynamoDB 是一項完全託管的 NoSQL 資料庫服務,可提供快速且可預測的效能以及無縫的可擴展性。

本筆記本說明如何使用 DynamoDBDynamoDBChatMessageHistory 類別來儲存聊天訊息歷史記錄。

設定

首先,請確保您已正確設定 AWS CLI。然後確保您已安裝 langchain-community 套件,因此我們需要安裝它。我們還需要安裝 boto3 套件。

pip install -U langchain-community boto3

設定 LangSmith 以獲得一流的可觀察性也很有幫助(但不是必需的)

# os.environ["LANGSMITH_TRACING"] = "true"
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass()
from langchain_community.chat_message_histories import (
DynamoDBChatMessageHistory,
)

建立表格

現在,建立 DynamoDB 表格,我們將在其中儲存訊息

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?')]

具有自訂端點 URL 的 DynamoDBChatMessageHistory

有時指定要連線的 AWS 端點的 URL 很有用。例如,當您針對 Localstack 在本機執行時。對於這些情況,您可以透過建構函式中的 endpoint_url 參數指定 URL。

history = DynamoDBChatMessageHistory(
table_name="SessionTable",
session_id="0",
endpoint_url="https://127.0.0.1.localstack.cloud:4566",
)

具有複合鍵的 DynamoDBChatMessageHistory

DynamoDBChatMessageHistory 的預設鍵是 {"SessionId": self.session_id},但您可以修改它以符合您的表格設計。

主索引鍵名稱

您可以透過在建構函式中傳入 primary_key_name 值來修改主索引鍵,從而產生以下結果:{self.primary_key_name: self.session_id}

複合鍵

當使用現有的 DynamoDB 表格時,您可能需要將索引鍵結構從預設值修改為包含排序索引鍵的結構。若要執行此操作,您可以使用 key 參數。

傳遞索引鍵的值將覆寫 primary_key 參數,且產生的索引鍵結構將是傳遞的值。

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",
)

# Wait until the table exists.
composite_table.meta.client.get_waiter("table_exists").wait(TableName="CompositeTable")

# Print out some data about the table.
print(composite_table.item_count)
0
my_key = {
"PK": "session_id::0",
"SK": "langchain_history",
}

composite_key_history = DynamoDBChatMessageHistory(
table_name="CompositeTable",
session_id="0",
endpoint_url="https://127.0.0.1.localstack.cloud:4566",
key=my_key,
)

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

composite_key_history.messages
[HumanMessage(content='hello, composite dynamodb table!')]

鏈接

我們可以輕鬆地將此訊息歷史記錄類別與 LCEL Runnables 結合使用

為此,我們會想要使用 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",
)
# This is where we configure the session id
config = {"configurable": {"session_id": "<SESSION_ID>"}}
chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)
AIMessage(content='Hello Bob! How can I assist you today?')
chain_with_history.invoke({"question": "Whats my name"}, config=config)
AIMessage(content='Your name is Bob! Is there anything specific you would like assistance with, Bob?')

這個頁面有幫助嗎?