repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
project-lakechain | github_2023 | awslabs | typescript | Lambda.processAossEvent | async processAossEvent(event: CloudEvent): Promise<any> {
const body: Record<string, any> = {
embeddings: await this.getEmbeddings(event),
...event.toJSON()
};
// Add an identifier to the body.
body.documentId = this.getId(event);
// If the document should be included, we add it to the body.
if (INCLUDE_DOCUMENT) {
body.text = await this.getDocument(event);
}
return (client.index({
index: INDEX_NAME,
body
}));
} | /**
* Inserts the given event and associated vector embeddings
* into the OpenSearch collection index.
* @note OpenSearch collections don't support identifiers
* when inserting documents in the index.
* @param event the event to process.
* @returns a promise that resolves when the event
* has been processed.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/opensearch-vector-storage-connector/src/lambdas/processor/index.ts#L144-L162 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.processEsEvent | async processEsEvent(event: CloudEvent): Promise<any> {
const body: Record<string, any> = {
embeddings: await this.getEmbeddings(event),
...event.toJSON()
};
// If the document should be included, we add it to the body.
if (INCLUDE_DOCUMENT) {
body.text = await this.getDocument(event);
}
return (client.index({
id: this.getId(event),
index: INDEX_NAME,
body
}));
} | /**
* Inserts the given event and associated vector embeddings
* into the OpenSearch collection index.
* @param event the event to process.
* @returns a promise that resolves when the event
* has been processed.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/opensearch-vector-storage-connector/src/lambdas/processor/index.ts#L171-L187 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.processEvent | async processEvent(event: CloudEvent): Promise<any> {
if (SERVICE_IDENTIFIER === 'es') {
return (this.processEsEvent(event));
} else if (SERVICE_IDENTIFIER === 'aoss') {
return (this.processAossEvent(event));
}
} | /**
* Stores the embeddings associated with the received
* document in the OpenSearch index.
* @param event the event to process.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/opensearch-vector-storage-connector/src/lambdas/processor/index.ts#L194-L200 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<any> {
return (await processPartialResponse(
event,
(record: SQSRecord) => this.processEvent(
CloudEvent.from(JSON.parse(record.body))
),
processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/opensearch-vector-storage-connector/src/lambdas/processor/index.ts#L210-L218 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnectorBuilder.withApiKey | public withApiKey(apiKey: secrets.ISecret) {
this.providerProps.apiKey = apiKey;
return (this);
} | /**
* Sets the API key to use.
* @param apiKey the API key to use.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L74-L77 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnectorBuilder.withIndexName | public withIndexName(indexName: string) {
this.providerProps.indexName = indexName;
return (this);
} | /**
* Sets the index name to use.
* @param indexName the index name to use.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L84-L87 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnectorBuilder.withNamespace | public withNamespace(namespace: string) {
this.providerProps.namespace = namespace;
return (this);
} | /**
* Sets the namespace to use.
* @param namespace the namespace to use.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L94-L97 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnectorBuilder.withControllerHostUrl | public withControllerHostUrl(controllerHostUrl: string) {
this.providerProps.controllerHostUrl = controllerHostUrl;
return (this);
} | /**
* Sets the controller host URL to use.
* @param controllerHostUrl the controller host URL to use.
* @returns the builder instance.
* @default https://api.pinecone.io
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L105-L108 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnectorBuilder.withIncludeText | public withIncludeText(includeText: boolean) {
this.providerProps.includeText = includeText;
return (this);
} | /**
* Sets whether to include the text associated
* with the embeddings in Pinecone.
* @param includeText whether to include the text
* associated with the embeddings in Pinecone.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L117-L120 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnectorBuilder.build | public build(): PineconeStorageConnector {
return (new PineconeStorageConnector(
this.scope,
this.identifier, {
...this.providerProps as PineconeStorageConnectorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `PineconeStorageConnector`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L126-L134 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnector.constructor | constructor(scope: Construct, id: string, props: PineconeStorageConnectorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
6 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
props = this.parse(PineconeStorageConnectorPropsSchema, props);
///////////////////////////////////////////
/////// Processing Function ///////
///////////////////////////////////////////
this.processor = new node.NodejsFunction(this, 'Processor', {
description: 'A function writing vector embeddings in a Pinecone index.',
entry: path.resolve(__dirname, 'lambdas', 'processor', 'index.js'),
vpc: props.vpc,
memorySize: props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
timeout: PROCESSING_TIMEOUT,
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup: this.logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
LAKECHAIN_CACHE_STORAGE: props.cacheStorage.id(),
API_KEY_SECRET_NAME: props.apiKey.secretName,
PINECONE_INDEX_NAME: props.indexName,
PINECONE_NAMESPACE: props.namespace,
PINECONE_CONTROLLER_HOST_URL: props.controllerHostUrl,
INCLUDE_TEXT: props.includeText ? 'true' : 'false'
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-secrets-manager'
]
}
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = this.processor.grantPrincipal;
// Plug the SQS queue into the lambda function.
this.processor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: props.batchSize ?? 2,
maxBatchingWindow: props.batchingWindow ?? cdk.Duration.seconds(10),
maxConcurrency: 5,
reportBatchItemFailures: true
}));
// Grant the lambda function permissions to
// read from the API key secret.
props.apiKey.grantRead(this.processor);
super.bind();
} | /**
* Pinecone data store constructor.
* @param scope the construct scope.
* @param id the construct identifier.
* @param props the construct properties.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L159-L225 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnector.grantReadProcessedDocuments | grantReadProcessedDocuments(_: iam.IGrantable): iam.Grant {
return ({} as iam.Grant);
} | /**
* Allows a grantee to read from the processed documents
* generated by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L231-L233 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnector.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'*/*'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L239-L243 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnector.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([]);
} | /**
* @returns an array of mime-types supported as output
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L249-L251 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnector.supportedComputeTypes | supportedComputeTypes(): ComputeType[] {
return ([
ComputeType.CPU
]);
} | /**
* @returns the supported compute types by a given
* middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L257-L261 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | PineconeStorageConnector.conditional | conditional() {
return (super
.conditional()
.and(when('type').equals('document-created'))
.and(when('data.metadata.properties.attrs.embeddings.vectors').exists())
);
} | /**
* @returns the middleware conditional statement defining
* in which conditions this middleware should be executed.
* In this case, we want the middleware to only be invoked
* when the document mime-type is supported, the event
* type is `document-created`, and embeddings are available
* in the document metadata.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/index.ts#L271-L277 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getId | private getId(event: CloudEvent) {
const metadata = event.data().metadata();
// If there is a chunk identifier that specifically
// identifies a chunk associated with the given document,
// we use that.
if (metadata.properties?.kind === 'text'
&& metadata.properties.attrs?.chunk) {
return (metadata.properties.attrs?.chunk.id);
}
return (event.data().document().id());
} | /**
* @param event the event associated with the
* received document.
* @returns a unique identifier for the given
* document that is fit to identify the vectors
* associated with the document.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/lambdas/processor/index.ts#L53-L65 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getEmbeddings | private getEmbeddings(event: CloudEvent): Promise<number[]> {
const metadata = event.data().metadata();
if (metadata.properties?.kind !== 'text'
|| !metadata.properties.attrs.embeddings) {
throw new Error('The event does not contain embeddings.');
}
return (metadata.properties.attrs.embeddings.vectors.resolve());
} | /**
* @param event the event associated with the
* received document.
* @returns a vector embedding object associated
* with the document.
* @throws if the vector embedding object could not
* be resolved.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/lambdas/processor/index.ts#L75-L84 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getMetadata | private async getMetadata(event: CloudEvent): Promise<RecordMetadata> {
const source = event.data().source();
const document = event.data().document();
const metadata = event.data().metadata();
const record: RecordMetadata = {};
if (metadata.properties?.kind !== 'text') {
throw new Error('The event is invalid.');
}
const attrs = metadata.properties.attrs;
// Saving chunk information.
if (attrs.chunk) {
record.chunkOrder = attrs.chunk.order;
if (attrs.chunk.startOffset) {
record.startOffset = attrs.chunk.startOffset;
}
if (attrs.chunk.endOffset) {
record.endOffset = attrs.chunk.endOffset;
}
}
// If `INCLUDE_TEXT` is set to `true`, and the document
// is a text document, we also include the original text
// in the record.
if (INCLUDE_TEXT && metadata.properties.kind === 'text') {
record.text = (await document.data().asBuffer()).toString('utf-8');
}
// Saving the document information.
record.sourceUrl = source.url().toString();
record.sourceType = source.mimeType();
record.documentUrl = document.url().toString();
record.documentType = document.mimeType();
// Saving metadata information.
if (metadata.title) {
record.title = metadata.title;
}
if (metadata.description) {
record.description = metadata.description;
}
if (metadata.image) {
record.image = metadata.image;
}
return (record);
} | /**
* @param event the event associated with the
* received document.
* @returns the metadata to associate with the
* vectors in Pinecone.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/lambdas/processor/index.ts#L92-L140 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.recordHandler | async recordHandler(record: SQSRecord): Promise<void> {
const event = CloudEvent.from(JSON.parse(record.body));
const pinecone = await createClient();
// Upsert the vector embeddings in Pinecone.
return (pinecone.upsert([{
id: this.getId(event),
values: await this.getEmbeddings(event),
metadata: await this.getMetadata(event)
}]));
} | /**
* Handles document events, retrieves their associated
* vector embeddings and metadata, and stores them in
* Pinecone.
* @param record the SQS record associated with
* the received document.
* @returns a promise resolved when the vector embeddings
* associated with the received document have been stored in Pinecone.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/lambdas/processor/index.ts#L151-L161 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context) {
return (await processPartialResponse(
event, this.recordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/pinecone-storage-connector/src/lambdas/processor/index.ts#L171-L175 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnectorBuilder.withApiKey | public withApiKey(apiKey: secrets.ISecret) {
this.providerProps.apiKey = apiKey;
return (this);
} | /**
* Sets the API key to use.
* @param apiKey the API key to use.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L74-L77 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnectorBuilder.withCollectionName | public withCollectionName(collectionName: string) {
this.providerProps.collectionName = collectionName;
return (this);
} | /**
* Sets the collection name to use.
* @param collectionName the collection name to use.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L84-L87 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnectorBuilder.withUrl | public withUrl(url: string) {
this.providerProps.url = url;
return (this);
} | /**
* Sets the Qdrant URL to use.
* @param url the Qdrant URL to use.
* @returns the builder instance.
* @example withUrl('https://xyz-example.eu-central.aws.cloud.qdrant.io:6333')
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L95-L98 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnectorBuilder.withStoreText | public withStoreText(storeText: boolean) {
this.providerProps.storeText = storeText;
return (this);
} | /**
* Sets whether to store the text associated
* with the embeddings in Qdrant as payload.
* @param includeText whether to store the text.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L106-L109 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnectorBuilder.withTextKey | public withTextKey(textKey: string) {
this.providerProps.textKey = textKey;
return (this);
} | /**
* Sets the payload key to use for the text in the Qdrant payload.
* @param textKey The key to use for the text in the Qdrant payload.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L116-L119 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnectorBuilder.withVectorName | public withVectorName(vectorName: string) {
this.providerProps.vectorName = vectorName;
return (this);
} | /**
* Sets the name of the vector to use.
* @param vectorName the name of the vector to use.
* @default '' Uses the default unnamed vector.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L127-L130 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnectorBuilder.build | public build(): QdrantStorageConnector {
return (new QdrantStorageConnector(
this.scope,
this.identifier, {
...this.providerProps as QdrantStorageConnectorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `QdrantStorageConnector`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L136-L144 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnector.constructor | constructor(scope: Construct, id: string, props: QdrantStorageConnectorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
6 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
props = this.parse(QdrantStorageConnectorPropsSchema, props);
///////////////////////////////////////////
/////// Processing Function ///////
///////////////////////////////////////////
this.processor = new node.NodejsFunction(this, 'Processor', {
description: 'A function writing vector embeddings in a Qdrant collection.',
entry: path.resolve(__dirname, 'lambdas', 'processor', 'index.js'),
vpc: props.vpc,
memorySize: props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
timeout: PROCESSING_TIMEOUT,
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup: this.logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
LAKECHAIN_CACHE_STORAGE: props.cacheStorage.id(),
QDRANT_API_KEY_SECRET_NAME: props.apiKey.secretName,
QDRANT_COLLECTION_NAME: props.collectionName,
QDRANT_URL: props.url,
QDRANT_STORE_TEXT: props.storeText ? 'true' : 'false',
QDRANT_TEXT_KEY: props.textKey,
QDRANT_VECTOR_NAME: props.vectorName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-secrets-manager'
]
}
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = this.processor.grantPrincipal;
// Plug the SQS queue into the lambda function.
this.processor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: props.batchSize ?? 2,
maxBatchingWindow: props.batchingWindow ?? cdk.Duration.seconds(10),
maxConcurrency: 5,
reportBatchItemFailures: true
}));
// Grant the lambda function permissions to
// read from the API key secret.
props.apiKey.grantRead(this.processor);
super.bind();
} | /**
* Qdrantdata store constructor.
* @param scope the construct scope.
* @param id the construct identifier.
* @param props the construct properties.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L169-L236 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnector.grantReadProcessedDocuments | grantReadProcessedDocuments(_: iam.IGrantable): iam.Grant {
return ({} as iam.Grant);
} | /**
* Allows a grantee to read from the processed documents
* generated by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L242-L244 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnector.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'*/*'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L250-L254 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnector.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([]);
} | /**
* @returns an array of mime-types supported as output
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L260-L262 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnector.supportedComputeTypes | supportedComputeTypes(): ComputeType[] {
return ([
ComputeType.CPU
]);
} | /**
* @returns the supported compute types by a given
* middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L268-L272 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | QdrantStorageConnector.conditional | conditional() {
return (super
.conditional()
.and(when('type').equals('document-created'))
.and(when('data.metadata.properties.attrs.embeddings.vectors').exists())
);
} | /**
* @returns the middleware conditional statement defining
* in which conditions this middleware should be executed.
* In this case, we want the middleware to only be invoked
* when the document mime-type is supported, the event
* type is `document-created`, and embeddings are available
* in the document metadata.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/index.ts#L282-L288 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getId | private getId(event: CloudEvent) {
const metadata = event.data().metadata();
// If there is a chunk identifier that specifically
// identifies a chunk associated with the given document,
// we use that.
if (metadata.properties?.kind === 'text'
&& metadata.properties.attrs?.chunk) {
return (metadata.properties.attrs?.chunk.id);
}
return (event.data().document().id());
} | /**
* @param event the event associated with the
* received document.
* @returns a unique identifier for the given
* document that is fit to identify the vectors
* associated with the document.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/lambdas/processor/index.ts#L57-L69 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getEmbeddings | private getEmbeddings(event: CloudEvent): Promise<number[]> {
const metadata = event.data().metadata();
if (metadata.properties?.kind !== 'text'
|| !metadata.properties.attrs.embeddings) {
throw new Error('The event does not contain embeddings.');
}
return (metadata.properties.attrs.embeddings.vectors.resolve());
} | /**
* @param event the event associated with the
* received document.
* @returns a vector embedding object associated
* with the document.
* @throws if the vector embedding object could not
* be resolved.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/lambdas/processor/index.ts#L79-L88 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getPayload | private async getPayload(event: CloudEvent): Promise<Record<string, any>> {
const source = event.data().source();
const document = event.data().document();
const metadata = event.data().metadata();
const record: Record<string, any> = {};
if (metadata.properties?.kind !== 'text') {
throw new Error('The event is invalid.');
}
const attrs = metadata.properties.attrs;
if (attrs.chunk) {
record.chunkOrder = attrs.chunk.order;
if (attrs.chunk.startOffset) {
record.startOffset = attrs.chunk.startOffset;
}
if (attrs.chunk.endOffset) {
record.endOffset = attrs.chunk.endOffset;
}
}
if (QDRANT_STORE_TEXT && metadata.properties.kind === 'text') {
record[QDRANT_TEXT_KEY] = (await document.data().asBuffer()).toString('utf-8');
}
record.sourceUrl = source.url().toString();
record.sourceType = source.mimeType();
record.documentUrl = document.url().toString();
record.documentType = document.mimeType();
record.id = this.getId(event);
if (metadata.title) {
record.title = metadata.title;
}
if (metadata.description) {
record.description = metadata.description;
}
if (metadata.image) {
record.image = metadata.image;
}
return (record);
} | /**
* @param event the event associated with the
* received document.
* @returns the payload to associate with the
* vectors in Qdrant
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/lambdas/processor/index.ts#L96-L139 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.recordHandler | async recordHandler(record: SQSRecord): Promise<void> {
const event = CloudEvent.from(JSON.parse(record.body));
const client = await createClient();
await client.upsert(QDRANT_COLLECTION_NAME, {
points: [{
id: uuidv4(),
vector: {
[QDRANT_VECTOR_NAME]: await this.getEmbeddings(event)
},
payload: await this.getPayload(event),
}],
wait: true
});
} | /**
* Handles document events, retrieves their associated
* vector embeddings and metadata, and stores them in
* Qdrant
* @param record the SQS record associated with
* the received document.
* @returns a promise resolved when the vector embeddings
* associated with the received document have been stored in Qdrant.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/lambdas/processor/index.ts#L150-L163 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context) {
return (await processPartialResponse(
event, this.recordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/qdrant-storage-connector/src/lambdas/processor/index.ts#L173-L177 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3StorageConnectorBuilder.withDestinationBucket | public withDestinationBucket(destination: s3.IBucket) {
this.providerProps.destinationBucket = destination;
return (this);
} | /**
* Specifies the destination bucket for the
* processed documents.
* @param destination the destination bucket.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/index.ts#L80-L83 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3StorageConnectorBuilder.withCopyDocuments | public withCopyDocuments(copyDocuments: boolean) {
this.providerProps.copyDocuments = copyDocuments;
return (this);
} | /**
* Specifies whether to copy the documents to the
* destination bucket. If set to false, only the
* document metadata will be copied.
* @default true
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/index.ts#L91-L94 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3StorageConnectorBuilder.withStorageClass | public withStorageClass(storageClass: StorageClass) {
this.providerProps.storageClass = storageClass;
return (this);
} | /**
* Specifies the storage class to use for storing
* documents in the destination bucket.
* @default STANDARD
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/index.ts#L101-L104 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3StorageConnectorBuilder.build | public build(): S3StorageConnector {
return (new S3StorageConnector(
this.scope,
this.identifier, {
...this.providerProps as S3StorageConnectorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `S3StorageConnector`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/index.ts#L110-L118 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3StorageConnector.constructor | constructor(scope: Construct, id: string, private props: S3StorageConnectorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
3 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validating the properties.
this.props = this.parse(S3StorageConnectorPropsSchema, props);
///////////////////////////////////////////
/////// Processing Function ///////
///////////////////////////////////////////
this.eventProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'Copy documents and their metadata to an S3 bucket.',
entry: path.resolve(__dirname, 'lambdas', 'document-handler', 'index.js'),
vpc: this.props.vpc,
memorySize: this.props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
timeout: PROCESSING_TIMEOUT,
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: this.props.kmsKey,
logGroup: this.logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SNS_TARGET_TOPIC: this.eventBus.topicArn,
TARGET_BUCKET: this.props.destinationBucket.bucketName,
COPY_DOCUMENTS: this.props.copyDocuments ? 'true' : 'false',
STORAGE_CLASS: this.props.storageClass
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-sns'
]
}
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = this.eventProcessor.grantPrincipal;
// Plug the SQS queue into the lambda function.
this.eventProcessor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: 5,
reportBatchItemFailures: true
}));
// Function permissions.
this.eventBus.grantPublish(this.eventProcessor);
this.props.destinationBucket.grantPut(this.eventProcessor);
super.bind();
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/index.ts#L140-L202 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3StorageConnector.grantReadProcessedDocuments | grantReadProcessedDocuments(_: iam.IGrantable): iam.Grant {
return ({} as iam.Grant);
} | /**
* Allows a grantee to read from the processed documents
* generated by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/index.ts#L208-L210 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3StorageConnector.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'*/*'
]);
} | /**
* @returns an array of mime-types supported as input
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/index.ts#L216-L220 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3StorageConnector.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/index.ts#L226-L228 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3StorageConnector.supportedComputeTypes | supportedComputeTypes(): ComputeType[] {
return ([
ComputeType.CPU
]);
} | /**
* @returns the supported compute types by a given
* middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/index.ts#L234-L238 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3StorageConnector.conditional | conditional() {
return (super
.conditional()
.and(when('type').equals('document-created'))
);
} | /**
* @returns the middleware conditional statement defining
* in which conditions this middleware should be executed.
* In this case, we want the middleware to only be invoked
* when the document mime-type is supported, and the event
* type is `document-created`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/index.ts#L247-L252 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.processEvent | async processEvent(event: CloudEvent): Promise<any> {
const data = event.data();
const document = data.document();
const outputPrefix = `output/${data.chainId()}`;
const sourceUri = S3DocumentDescriptor.fromUri(document.url());
const filename = document.filename().basename();
const promises = [];
// If `COPY_DOCUMENTS` is set to `true`, we copy the
// the current document to the target bucket.
if (COPY_DOCUMENTS) {
promises.push(s3.send(new CopyObjectCommand({
Bucket: TARGET_BUCKET,
Key: path.join(outputPrefix, filename),
CopySource: encodeURIComponent(
`${sourceUri.bucket()}/${sourceUri.key()}`
),
ContentType: document.mimeType(),
StorageClass: STORAGE_CLASS
})));
}
// We also copy the document metadata to the target bucket.
promises.push(s3.send(new PutObjectCommand({
Bucket: TARGET_BUCKET,
Key: path.join(outputPrefix, `${filename}.metadata.json`),
Body: JSON.stringify(event),
ContentType: 'application/json',
StorageClass: STORAGE_CLASS
})));
// We wait for all the promises to resolve.
await Promise.all(promises);
return (logger.info(event as any));
} | /**
* @param event the event to process.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/lambdas/document-handler/index.ts#L74-L109 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<SQSBatchResponse> {
return (await processPartialResponse(
event,
(record: SQSRecord) => this.processEvent(
CloudEvent.from(JSON.parse(record.body))
),
processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/s3-storage-connector/src/lambdas/document-handler/index.ts#L118-L126 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsStorageConnectorBuilder.withDestinationQueue | public withDestinationQueue(destination: sqs.Queue) {
this.providerProps.destinationQueue = destination;
return (this);
} | /**
* Specifies the destination SQS queue for the
* processed documents.
* @param destination the destination queue.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/sqs-storage-connector/src/index.ts#L50-L53 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsStorageConnectorBuilder.build | public build(): SqsStorageConnector {
return (new SqsStorageConnector(
this.scope,
this.identifier, {
...this.providerProps as SqsStorageConnectorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `SqsStorageConnector`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/sqs-storage-connector/src/index.ts#L59-L67 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsStorageConnector.constructor | constructor(scope: Construct, id: string, private props: SqsStorageConnectorProps) {
super(scope, id, description, props);
// Validating the properties.
this.props = this.parse(SqsStorageConnectorPropsSchema, props);
super.bind();
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/sqs-storage-connector/src/index.ts#L84-L91 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsStorageConnector.getInput | public getInput() {
return (this.props.destinationQueue);
} | /**
* We override the `getInput` method to return the user-provided
* queue. This way this middleware only acts as a passthrough between
* the previous middleware's SNS topics and the user-provided queue.
* @returns the user-provided SQS queue.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/sqs-storage-connector/src/index.ts#L99-L101 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsStorageConnector.grantReadProcessedDocuments | grantReadProcessedDocuments(_: iam.IGrantable): iam.Grant {
return ({} as iam.Grant);
} | /**
* Allows a grantee to read from the processed documents
* generated by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/sqs-storage-connector/src/index.ts#L107-L109 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsStorageConnector.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'*/*'
]);
} | /**
* @returns an array of mime-types supported as input
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/sqs-storage-connector/src/index.ts#L115-L119 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsStorageConnector.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/sqs-storage-connector/src/index.ts#L125-L127 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsStorageConnector.supportedComputeTypes | supportedComputeTypes(): ComputeType[] {
return ([
ComputeType.CPU
]);
} | /**
* @returns the supported compute types by a given
* middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/storage-connectors/sqs-storage-connector/src/index.ts#L133-L137 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessorBuilder.withModel | public withModel(model: AnthropicTextModel) {
this.middlewareProps.model = model;
return (this);
} | /**
* Sets the Anthropic model to use for generating text.
* @param model the Anthropic text model to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L83-L86 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessorBuilder.withModelParameters | public withModelParameters(parameters: ModelParameters) {
this.middlewareProps.modelParameters = parameters;
return (this);
} | /**
* Sets the parameters to pass to the text model.
* @param parameters the parameters to pass to the text model.
* @default {}
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L94-L97 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessorBuilder.withSystemPrompt | public withSystemPrompt(prompt: string) {
this.middlewareProps.systemPrompt = prompt;
return (this);
} | /**
* Sets the system prompt to use for generating text.
* @param prompt the system prompt to use for generating text.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L104-L107 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessorBuilder.withPrompt | public withPrompt(prompt: string | r.IReference<any>) {
let reference = null;
if (typeof prompt === 'string') {
reference = r.reference(r.value(prompt));
} else {
reference = prompt;
}
this.middlewareProps.prompt = reference;
return (this);
} | /**
* Sets the prompt to use for generating text.
* @param prompt the prompt to use for generating text.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L114-L125 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessorBuilder.withAssistantPrefill | public withAssistantPrefill(prefill: string) {
this.middlewareProps.assistantPrefill = prefill;
return (this);
} | /**
* Sets the assistant prefill to use for generating text.
* @param prefill the assistant prefill to use for generating text.
* @returns the current builder instance.
* @default ''
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L133-L136 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessorBuilder.withRegion | public withRegion(region: string) {
this.middlewareProps.region = region;
return (this);
} | /**
* Sets the AWS region in which the model
* will be invoked.
* @param region the AWS region in which the model
* will be invoked.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L145-L148 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessorBuilder.build | public build(): AnthropicTextProcessor {
return (new AnthropicTextProcessor(
this.scope,
this.identifier, {
...this.middlewareProps as AnthropicTextProcessorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `AnthropicTextProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L154-L162 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessor.constructor | constructor(scope: Construct, id: string, private props: AnthropicTextProcessorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
2 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
this.props = this.parse(AnthropicTextProcessorPropsSchema, props);
///////////////////////////////////////////
//////// Processing Storage ///////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
////////// Prompt Handler /////////
///////////////////////////////////////////
// If the given prompt is a static value, and it is bigger than a certain
// threshold, we upload the prompt to the internal storage and reference it
// in the lambda environment.
if (this.props.prompt.subject.type === 'value'
&& this.props.prompt.subject.value.length > 3072) {
new s3deploy.BucketDeployment(this, 'Prompt', {
sources: [s3deploy.Source.data('prompt.txt', this.props.prompt.subject.value)],
destinationBucket: this.storage.getBucket()
});
this.props.prompt = r.reference(r.url(`s3://${this.storage.getBucket().bucketName}/prompt.txt`));
}
///////////////////////////////////////////
////// Middleware Event Handler ////
///////////////////////////////////////////
this.eventProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'Generates text using Anthropic models on Amazon Bedrock.',
entry: path.resolve(__dirname, 'lambdas', 'handler', 'index.js'),
vpc: this.props.vpc,
memorySize: this.props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
timeout: PROCESSING_TIMEOUT,
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: this.props.kmsKey,
logGroup: this.logGroup,
insightsVersion: this.props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SNS_TARGET_TOPIC: this.eventBus.topicArn,
PROCESSED_FILES_BUCKET: this.storage.id(),
MODEL_ID: this.props.model.name,
SYSTEM_PROMPT: this.props.systemPrompt ?? '',
PROMPT: JSON.stringify(this.props.prompt),
ASSISTANT_PREFILL: this.props.assistantPrefill,
MODEL_PARAMETERS: JSON.stringify(this.props.modelParameters),
BEDROCK_REGION: this.props.region ?? cdk.Aws.REGION,
OVERFLOW_STRATEGY: this.props.overflowStrategy
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-sns'
]
}
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = this.eventProcessor.grantPrincipal;
// Plug the SQS queue into the lambda function.
this.eventProcessor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: this.props.batchSize ?? 1,
maxConcurrency: 2,
reportBatchItemFailures: true
}));
// Allow access to the Bedrock API.
this.eventProcessor.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
'bedrock:InvokeModel'
],
resources: [
`arn:${cdk.Aws.PARTITION}:bedrock:${this.props.region ?? cdk.Aws.REGION}::foundation-model/${this.props.model.name}`,
]
}));
// Grant the compute type permissions to
// write to the post-processing storage.
this.storage.grantReadWrite(this.grantPrincipal);
// Grant the compute type permissions to
// publish to the SNS topic.
this.eventBus.grantPublish(this.grantPrincipal);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L189-L296 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessor.grantReadProcessedDocuments | grantReadProcessedDocuments(grantee: iam.IGrantable): iam.Grant {
return (this.storage.grantRead(grantee));
} | /**
* Allows a grantee to read from the processed documents
* generated by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L302-L304 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return (this.props.model.inputs);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L310-L312 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessor.supportedOutputTypes | supportedOutputTypes(): string[] {
return (this.props.model.outputs);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L318-L320 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessor.supportedComputeTypes | supportedComputeTypes(): ComputeType[] {
return ([
ComputeType.CPU
]);
} | /**
* @returns the supported compute types by a given
* middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L326-L330 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextProcessor.conditional | conditional() {
return (super
.conditional()
.and(when('type').equals('document-created'))
);
} | /**
* @returns the middleware conditional statement defining
* in which conditions this middleware should be executed.
* In this case, we want the middleware to only be invoked
* when the document mime-type is supported, and the event
* type is `document-created`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/index.ts#L339-L344 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextModel.of | public static of(props: AnthropicTextModelProps) {
return (new AnthropicTextModel(props));
} | /**
* Create a new instance of the `AnthropicTextModel`
* by name.
* @param props the properties of the model.
* @returns a new instance of the `AnthropicTextModel`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/definitions/model.ts#L192-L194 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | AnthropicTextModel.constructor | constructor(props: AnthropicTextModelProps) {
this.name = props.name;
this.inputs = props.inputs;
this.outputs = props.outputs;
} | /**
* Constructs a new instance of the `AnthropicTextModel`.
* @param props the properties of the model.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/definitions/model.ts#L200-L204 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | groupBy | const groupBy = <T, K extends keyof any>(arr: T[], key: (i: T) => K) =>
arr.reduce((groups, item) => {
(groups[key(item)] ||= []).push(item);
return groups;
}, {} as Record<K, T[]>
); | /**
* Group an array of elements by a given key.
* @param arr the array to group.
* @param key the key to group by.
* @returns a record mapping the given key to the
* elements of the array.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/lambdas/handler/index.ts#L66-L71 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.resolveEvents | private async resolveEvents(event: CloudEvent): Promise<CloudEvent[]> {
const document = event.data().document();
if (document.mimeType() === 'application/cloudevents+json') {
const data = JSON.parse((await document
.data()
.asBuffer())
.toString('utf-8')
);
return (data.map((event: string) => CloudEvent.from(event)));
} else {
return ([event]);
}
} | /**
* Resolves the input documents to process.
* This function supports both single and composite events.
* @param event the received event.
* @returns a promise to an array of CloudEvents to process.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/lambdas/handler/index.ts#L87-L100 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getMessages | private async getMessages(event: CloudEvent) {
const prompt = (await event.resolve(USER_PROMPT)).toString('utf-8');
const messages = [{ role: 'user', content: [
{ type: 'text', text: prompt }
] as any[] }];
// Get the input documents.
const events = (await this
.resolveEvents(event))
.filter((e: CloudEvent) => {
const type = e.data().document().mimeType();
return (BASE_TEXT_INPUTS.includes(type) || BASE_IMAGE_INPUTS.includes(type));
});
// If no documents match the supported types, throw an error.
if (events.length === 0) {
throw new Error('No valid input documents found.');
}
// Group documents by either `text` or `image` type.
const group = groupBy(events, e => {
const type = e.data().document().mimeType();
return (BASE_TEXT_INPUTS.includes(type) ? 'text' : 'image');
});
// Text documents are concatenated into a single message
// in the case where we're handling a composite event.
if (group.text) {
let text = '';
if (group.text.length > 1) {
for (const [idx, e] of group.text.entries()) {
const document = e.data().document();
text += `Document ${idx + 1}\n${(await document.data().asBuffer()).toString('utf-8')}\n\n`;
}
} else {
const document = group.text[0].data().document();
text = (await document.data().asBuffer()).toString('utf-8');
}
messages[0].content.push({ type: 'text', text });
}
// Image documents are added as separate messages.
if (group.image) {
for (const e of group.image) {
const document = e.data().document();
const type = document.mimeType();
messages[0].content.push({
type: 'image',
source: {
type: 'base64',
media_type: type,
data: (await document.data().asBuffer()).toString('base64')
}
});
}
}
// Add the assistant prefill.
if (ASSISTANT_PREFILL) {
messages.push({ role: 'assistant', content: [
{ type: 'text', text: ASSISTANT_PREFILL }
] as any[] });
}
return (messages);
} | /**
* Computes a list of messages constructed from the input documents.
* @param event the received event.
* @returns an array of messages to use for generating text.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/lambdas/handler/index.ts#L107-L175 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getBody | private async getBody(event: CloudEvent) {
return ({
anthropic_version: 'bedrock-2023-05-31',
system: SYSTEM_PROMPT,
messages: await this.getMessages(event),
...MODEL_PARAMETERS
});
} | /**
* Constructs the body to pass to the Bedrock API.
* @param event the cloud event associated with the
* input document(s).
* @returns the body to pass to the Bedrock API.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/lambdas/handler/index.ts#L183-L190 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.transform | private async transform(event: CloudEvent): Promise<Buffer> {
const response = await bedrock.invokeModel({
body: JSON.stringify(await this.getBody(event)),
modelId: MODEL_ID,
accept: 'application/json',
contentType: 'application/json'
});
// Parse the response into a buffer.
let buffer = Buffer.from(
JSON.parse(response.body.transformToString()).content[0].text
);
// If an assistant prefill has been passed to the model, we
// prepend it to the generated text.
if (ASSISTANT_PREFILL) {
buffer = Buffer.concat([
Buffer.from(ASSISTANT_PREFILL),
buffer
]);
}
return (buffer);
} | /**
* Transforms the document using the given parameters.
* @param event the CloudEvent to process.
* @returns a promise to a buffer containing the transformed document.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/lambdas/handler/index.ts#L197-L220 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.recordHandler | async recordHandler(record: SQSRecord): Promise<CloudEvent> {
return (await this.processEvent(
CloudEvent.from(record.body)
));
} | /**
* @param record the SQS record to process that contains
* the EventBridge event providing information about the
* S3 event.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/lambdas/handler/index.ts#L254-L258 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | public async handler(event: SQSEvent, _: Context) {
return (await processPartialResponse(
event, this.recordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/anthropic/lambdas/handler/index.ts#L268-L272 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessorBuilder.withModel | public withModel(model: CohereTextModel) {
this.middlewareProps.model = model;
return (this);
} | /**
* Sets the Cohere model to use for generating text.
* @param model the Cohere text model to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L83-L86 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessorBuilder.withModelParameters | public withModelParameters(parameters: ModelParameters) {
this.middlewareProps.modelParameters = parameters;
return (this);
} | /**
* Sets the parameters to pass to the text model.
* @param parameters the parameters to pass to the text model.
* @default {}
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L94-L97 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessorBuilder.withPrompt | public withPrompt(prompt: string | r.IReference<any>) {
let reference = null;
if (typeof prompt === 'string') {
reference = r.reference(r.value(prompt));
} else {
reference = prompt;
}
this.middlewareProps.prompt = reference;
return (this);
} | /**
* Sets the prompt to use for generating text.
* @param prompt the prompt to use for generating text.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L104-L115 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessorBuilder.withRegion | public withRegion(region: string) {
this.middlewareProps.region = region;
return (this);
} | /**
* Sets the AWS region in which the model
* will be invoked.
* @param region the AWS region in which the model
* will be invoked.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L124-L127 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessorBuilder.build | public build(): CohereTextProcessor {
return (new CohereTextProcessor(
this.scope,
this.identifier, {
...this.middlewareProps as CohereTextProcessorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `CohereTextProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L133-L141 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessor.constructor | constructor(scope: Construct, id: string, private props: CohereTextProcessorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
2 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
this.props = this.parse(CohereTextProcessorPropsSchema, props);
///////////////////////////////////////////
//////// Processing Storage ///////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
////////// Prompt Handler /////////
///////////////////////////////////////////
// If the given prompt is a static value, and it is bigger than a certain
// threshold, we upload the prompt to the internal storage and reference it
// in the lambda environment.
if (this.props.prompt.subject.type === 'value'
&& this.props.prompt.subject.value.length > 3072) {
// Upload the prompt as a document in the internal storage.
new s3deploy.BucketDeployment(this, 'Prompt', {
sources: [s3deploy.Source.data('prompt.txt', this.props.prompt.subject.value)],
destinationBucket: this.storage.getBucket()
});
this.props.prompt = r.reference(r.url(`s3://${this.storage.getBucket().bucketName}/prompt.txt`));
}
///////////////////////////////////////////
////// Middleware Event Handler ////
///////////////////////////////////////////
this.eventProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'Generates text using Cohere models on Amazon Bedrock.',
entry: path.resolve(__dirname, 'lambdas', 'handler', 'index.js'),
vpc: this.props.vpc,
memorySize: this.props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
timeout: PROCESSING_TIMEOUT,
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: this.props.kmsKey,
logGroup: this.logGroup,
insightsVersion: this.props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SNS_TARGET_TOPIC: this.eventBus.topicArn,
PROCESSED_FILES_BUCKET: this.storage.id(),
MODEL_ID: this.props.model.name,
PROMPT: JSON.stringify(this.props.prompt),
MODEL_PARAMETERS: JSON.stringify(this.props.modelParameters),
BEDROCK_REGION: this.props.region ?? cdk.Aws.REGION,
OVERFLOW_STRATEGY: this.props.overflowStrategy
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-sns'
]
}
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = this.eventProcessor.grantPrincipal;
// Plug the SQS queue into the lambda function.
this.eventProcessor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: this.props.batchSize ?? 1,
maxConcurrency: 2,
reportBatchItemFailures: true
}));
// Allow access to the Bedrock API.
this.eventProcessor.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
'bedrock:InvokeModel'
],
resources: [
`arn:${cdk.Aws.PARTITION}:bedrock:${this.props.region ?? cdk.Aws.REGION}::foundation-model/${this.props.model.name}`,
]
}));
// Grant the compute type permissions to
// write to the post-processing storage.
this.storage.grantWrite(this.grantPrincipal);
// Grant the compute type permissions to
// publish to the SNS topic.
this.eventBus.grantPublish(this.grantPrincipal);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L168-L274 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessor.grantReadProcessedDocuments | grantReadProcessedDocuments(grantee: iam.IGrantable): iam.Grant {
return (this.storage.grantRead(grantee));
} | /**
* Allows a grantee to read from the processed documents
* generated by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L280-L282 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return (this.props.model.inputs);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L288-L290 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessor.supportedOutputTypes | supportedOutputTypes(): string[] {
return (this.props.model.outputs);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L296-L298 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessor.supportedComputeTypes | supportedComputeTypes(): ComputeType[] {
return ([
ComputeType.CPU
]);
} | /**
* @returns the supported compute types by a given
* middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L304-L308 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextProcessor.conditional | conditional() {
return (super
.conditional()
.and(when('type').equals('document-created'))
);
} | /**
* @returns the middleware conditional statement defining
* in which conditions this middleware should be executed.
* In this case, we want the middleware to only be invoked
* when the document mime-type is supported, and the event
* type is `document-created`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/index.ts#L317-L322 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextModel.of | public static of(props: CohereTextModelProps) {
return (new CohereTextModel(props));
} | /**
* Create a new instance of the `CohereTextModel`
* by name.
* @param props the properties of the model.
* @returns a new instance of the `CohereTextModel`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/definitions/model.ts#L127-L129 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereTextModel.constructor | constructor(props: CohereTextModelProps) {
this.name = props.name;
this.inputs = props.inputs;
this.outputs = props.outputs;
} | /**
* Constructs a new instance of the `CohereTextModel`.
* @param props the properties of the model.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/definitions/model.ts#L135-L139 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getPrompt | private async getPrompt(event: CloudEvent) {
const document = event.data().document();
const prompt = (await event.resolve(USER_PROMPT)).toString('utf-8');
const content = (await document.data().asBuffer()).toString('utf-8');
return (`${content}\n\n${prompt}`);
} | /**
* @param event the cloud event to use to resolve
* the prompt.
* @returns the prompt to use for generating text.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/lambdas/handler/index.ts#L66-L71 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getBody | private async getBody(event: CloudEvent) {
if (MODEL_ID?.includes('command-r')) {
return (JSON.stringify({
...MODEL_PARAMETERS,
message: await this.getPrompt(event)
}));
} else {
return (JSON.stringify({
...MODEL_PARAMETERS,
prompt: await this.getPrompt(event)
}));
}
} | /**
* @param event the CloudEvent to process.
* @returns the body to pass to the Bedrock API in the appropriate
* format given the model.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/lambdas/handler/index.ts#L78-L90 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.transform | private async transform(event: CloudEvent): Promise<Buffer> {
const response = await bedrock.invokeModel({
body: await this.getBody(event),
modelId: MODEL_ID,
accept: 'application/json',
contentType: 'application/json'
});
// Parse the response into a buffer.
if (MODEL_ID?.includes('command-r')) {
return (Buffer.from(
JSON.parse(response.body.transformToString()).text
));
} else {
return (Buffer.from(
JSON.parse(response.body.transformToString()).generations[0].text
));
}
} | /**
* Transforms the document using the given parameters.
* @param event the CloudEvent to process.
* @returns a promise to a buffer containing the transformed document.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/lambdas/handler/index.ts#L97-L115 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.recordHandler | async recordHandler(record: SQSRecord): Promise<CloudEvent> {
return (await this.processEvent(
CloudEvent.from(record.body)
));
} | /**
* @param record the SQS record to process that contains
* the EventBridge event providing information about the
* S3 event.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/lambdas/handler/index.ts#L149-L153 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | public async handler(event: SQSEvent, _: Context) {
return (await processPartialResponse(
event, this.recordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/cohere/lambdas/handler/index.ts#L163-L167 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | LlamaTextProcessorBuilder.withModel | public withModel(model: LlamaModel) {
this.middlewareProps.model = model;
return (this);
} | /**
* Sets the Llama model to use for generating text.
* @param model the Llama text model to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/bedrock-text-processors/src/impl/meta/index.ts#L83-L86 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.