Skip to content

Commit

Permalink
community[patch]: Implement TTL for DynamoDBChatMessageHistory (#15478)
Browse files Browse the repository at this point in the history
- **Description:** Implement TTL for DynamoDBChatMessageHistory, 
  - **Issue:** see #15477,
  - **Dependencies:** N/A,

---------

Co-authored-by: Piyush Jain <[email protected]>
  • Loading branch information
brnaba-aws and 3coins authored Jan 29, 2024
1 parent 1bc8d9a commit 2db79ab
Showing 1 changed file with 18 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ class DynamoDBChatMessageHistory(BaseChatMessageHistory):
This may also contain global and local secondary index keys.
kms_key_id: an optional AWS KMS Key ID, AWS KMS Key ARN, or AWS KMS Alias for
client-side encryption
ttl: Optional Time-to-live (TTL) in seconds. Allows you to define a per-item
expiration timestamp that indicates when an item can be deleted from the
table. DynamoDB handles deletion of expired items without consuming
write throughput. To enable this feature on the table, follow the
[AWS DynamoDB documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/time-to-live-ttl-how-to.html)
"""

def __init__(
Expand All @@ -49,6 +54,8 @@ def __init__(
key: Optional[Dict[str, str]] = None,
boto3_session: Optional[Session] = None,
kms_key_id: Optional[str] = None,
ttl: Optional[int] = None,
ttl_key_name: str = "expireAt",
):
if boto3_session:
client = boto3_session.resource("dynamodb", endpoint_url=endpoint_url)
Expand All @@ -66,6 +73,8 @@ def __init__(
self.table = client.Table(table_name)
self.session_id = session_id
self.key: Dict = key or {primary_key_name: session_id}
self.ttl = ttl
self.ttl_key_name = ttl_key_name

if kms_key_id:
try:
Expand Down Expand Up @@ -134,7 +143,15 @@ def add_message(self, message: BaseMessage) -> None:
messages.append(_message)

try:
self.table.put_item(Item={**self.key, "History": messages})
if self.ttl:
import time

expireAt = int(time.time()) + self.ttl
self.table.put_item(
Item={**self.key, "History": messages, self.ttl_key_name: expireAt}
)
else:
self.table.put_item(Item={**self.key, "History": messages})
except ClientError as err:
logger.error(err)

Expand Down

0 comments on commit 2db79ab

Please sign in to comment.