开源数据层
DynamoDB 数据层
开源数据层
DynamoDB 数据层
这个数据层也支持 BaseStorageClient
,使您能够将元素存储到 AWS S3 或 Azure Blob Storage 中。
示例
以下是设置此数据层的一个示例。首先安装 boto3
pip install boto3
导入自定义数据层和存储客户端,并在您的 Chainlit 应用程序开始时设置 cl_data._data_layer
变量。
import chainlit.data as cl_data
from chainlit.data.dynamodb import DynamoDBDataLayer
from chainlit.data.storage_clients.s3 import S3StorageClient
storage_client = S3StorageClient(bucket="<Your Bucket>")
cl_data._data_layer = DynamoDBDataLayer(table_name="<Your Table>", storage_provider=storage_client)
表结构
这里是用于创建 DynamoDB 表的 CloudFormation 模板
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"DynamoDBTable": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "<YOUR-TABLE-NAME>",
"AttributeDefinitions": [
{
"AttributeName": "PK",
"AttributeType": "S"
},
{
"AttributeName": "SK",
"AttributeType": "S"
},
{
"AttributeName": "UserThreadPK",
"AttributeType": "S"
},
{
"AttributeName": "UserThreadSK",
"AttributeType": "S"
}
],
"KeySchema": [
{
"AttributeName": "PK",
"KeyType": "HASH"
},
{
"AttributeName": "SK",
"KeyType": "RANGE"
}
],
"GlobalSecondaryIndexes": [
{
"IndexName": "UserThread",
"KeySchema": [
{
"AttributeName": "UserThreadPK",
"KeyType": "HASH"
},
{
"AttributeName": "UserThreadSK",
"KeyType": "RANGE"
}
],
"Projection": {
"ProjectionType": "INCLUDE",
"NonKeyAttributes": ["id", "name"]
}
}
],
"BillingMode": "PAY_PER_REQUEST"
}
}
}
}
日志记录
DynamoDB 数据层定义了 chainlit 日志记录器的一个子记录器。
import logging
from chainlit import logger
logger.getChild("DynamoDB").setLevel(logging.DEBUG)
限制
不支持按正面/负面反馈进行筛选。
数据层方法不是异步的。Boto3 不是异步的,因此数据层使用了非异步的阻塞式 I/O。
设计
这个实现采用了单一表设计(Single Table Design)。一个表中存在 4 种不同的实体类型,通过 PK 和 SK 中的前缀进行标识。
以下是实体类型
type User = {
PK: "USER#{user.identifier}"
SK: "USER"
// ...PersistedUser
}
type Thread = {
PK: f"THREAD#{thread_id}"
SK: "THREAD"
// GSI: UserThread for querying in list_threads
UserThreadPK: f"USER#{user_id}"
UserThreadSK: f"TS#{ts}"
// ...ThreadDict
}
type Step = {
PK: f"THREAD#{threadId}"
SK: f"STEP#{stepId}"
// ...StepDict
// feedback is stored as part of step.
// NOTE: feedback.value is stored as Decimal in dynamo which is not json serializable
feedback?: Feedback
}
type Element = {
"PK": f"THREAD#{threadId}"
"SK": f"ELEMENT#{element.id}"
// ...ElementDict
}