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
ExtractPagesTask.toJSON
public toJSON() { return (this.props); }
/** * @returns the JSON representation of the task. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/pdf-text-converter/src/definitions/tasks/extract-pages-task.ts#L191-L193
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RecursiveCharacterTextSplitterBuilder.withChunkSize
public withChunkSize(chunkSize: number) { this.providerProps.chunkSize = chunkSize; return (this); }
/** * Sets the chunk size. * @param chunkSize the chunk size to assign. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/recursive-character-text-splitter/src/index.ts#L90-L93
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RecursiveCharacterTextSplitterBuilder.withChunkOverlap
public withChunkOverlap(chunkOverlap: number) { this.providerProps.chunkOverlap = chunkOverlap; return (this); }
/** * Sets the chunk overlap. * @param chunkOverlap the chunk overlap to assign. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/recursive-character-text-splitter/src/index.ts#L99-L102
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RecursiveCharacterTextSplitterBuilder.withSeparators
public withSeparators(separators: string[]) { this.providerProps.separators = separators; return (this); }
/** * Sets the separators to use between chunks. * @param separators the separators to use. * @returns the builder itself. * @default ["\n\n", "\n", " ", ""] */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/recursive-character-text-splitter/src/index.ts#L110-L113
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RecursiveCharacterTextSplitterBuilder.build
public build(): RecursiveCharacterTextSplitter { return (new RecursiveCharacterTextSplitter( this.scope, this.identifier, { ...this.providerProps as RecursiveCharacterTextSplitterProps, ...this.props } )); }
/** * @returns a new instance of the `RecursiveCharacterTextSplitter` * service constructed with the given parameters. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/recursive-character-text-splitter/src/index.ts#L119-L127
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RecursiveCharacterTextSplitter.constructor
constructor(scope: Construct, id: string, props: RecursiveCharacterTextSplitterProps) { super(scope, id, description, { ...props, queueVisibilityTimeout: cdk.Duration.seconds( 6 * PROCESSING_TIMEOUT.toSeconds() ) }); // Validate the properties. props = this.parse(RecursiveCharacterTextSplitterPropsSchema, props); /////////////////////////////////////////// ///////// Processing Storage ////// /////////////////////////////////////////// this.storage = new CacheStorage(this, 'Storage', { encryptionKey: props.kmsKey }); /////////////////////////////////////////// ////// Middleware Event Handler //// /////////////////////////////////////////// this.processor = new node.NodejsFunction(this, 'Compute', { description: 'Middleware splitting text documents in chunks.', entry: path.resolve(__dirname, 'lambdas', 'text-splitter', '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, SNS_TARGET_TOPIC: this.eventBus.topicArn, PROCESSED_FILES_BUCKET: this.storage.id(), SEPARATORS: JSON.stringify(props.separators ?? DEFAULT_SEPARATORS), CHUNK_SIZE: `${props.chunkSize ?? DEFAULT_CHUNK_SIZE}`, CHUNK_OVERLAP: `${props.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP}` }, 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.processor.grantPrincipal; // Plug the SQS queue into the lambda function. this.processor.addEventSource(new sources.SqsEventSource(this.eventQueue, { batchSize: props.batchSize ?? 5, reportBatchItemFailures: true })); // Function permissions. this.storage.grantReadWrite(this.processor); this.eventBus.grantPublish(this.processor); super.bind(); }
/** * Construct constructor. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/recursive-character-text-splitter/src/index.ts#L154-L225
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RecursiveCharacterTextSplitter.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/recursive-character-text-splitter/src/index.ts#L231-L233
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RecursiveCharacterTextSplitter.supportedInputTypes
supportedInputTypes(): string[] { return ([ 'text/plain' ]); }
/** * @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/recursive-character-text-splitter/src/index.ts#L239-L243
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RecursiveCharacterTextSplitter.supportedOutputTypes
supportedOutputTypes(): string[] { return ([ 'text/plain' ]); }
/** * @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/recursive-character-text-splitter/src/index.ts#L249-L253
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RecursiveCharacterTextSplitter.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/recursive-character-text-splitter/src/index.ts#L259-L263
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RecursiveCharacterTextSplitter.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/recursive-character-text-splitter/src/index.ts#L272-L277
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
Lambda.getMetadata
getMetadata(chunk: string, order: number, total: number): DocumentMetadata { return ({ properties: { kind: 'text', attrs: { chunk: { id: crypto .createHash('sha256') .update(chunk) .digest('hex'), order, total } } } }); }
/** * @param chunk the chunk of text to return metadata for. * @param order the order of the chunk. * @param total the total number of chunks in the document. * @returns the metadata for the chunk. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/recursive-character-text-splitter/src/lambdas/text-splitter/index.ts#L67-L83
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
Lambda.processEvent
async processEvent(event: CloudEvent): Promise<CloudEvent> { const document = event.data().document(); // We load the text file in memory. const text = (await document.data().asBuffer()).toString('utf-8'); // Create the text splitter. const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: CHUNK_SIZE, chunkOverlap: CHUNK_OVERLAP, separators: SEPARATORS }); // Split the text into chunks. const chunks = await textSplitter.splitText(text); const total = chunks.length; // Publish each chunk as a separate document. for (const [idx, chunk] of chunks.entries()) { await this.onChunk(chunk, idx, total, event); } return (event); }
/** * @param event the event to process. * @note the next decorator will automatically forward the * returned cloud event to the next middlewares */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/recursive-character-text-splitter/src/lambdas/text-splitter/index.ts#L124-L147
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/text-processors/recursive-character-text-splitter/src/lambdas/text-splitter/index.ts#L156-L164
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RegexpTextSplitterBuilder.withSeparator
public withSeparator(separator: string | RegExp) { this.providerProps.separator = separator; return (this); }
/** * Sets the separator. * @param separator a string or regular expression * to use as a separator. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/regexp-text-splitter/src/index.ts#L75-L78
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RegexpTextSplitterBuilder.build
public build(): RegexpTextSplitter { return (new RegexpTextSplitter( this.scope, this.identifier, { ...this.providerProps as RegexpTextSplitterProps, ...this.props } )); }
/** * @returns a new instance of the `RegexpTextSplitter` * service constructed with the given parameters. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/regexp-text-splitter/src/index.ts#L84-L92
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RegexpTextSplitter.constructor
constructor(scope: Construct, id: string, props: RegexpTextSplitterProps) { super(scope, id, description, { ...props, queueVisibilityTimeout: cdk.Duration.seconds( 6 * PROCESSING_TIMEOUT.toSeconds() ) }); // Validate the properties. props = this.parse(RegexpTextSplitterPropsSchema, props); /////////////////////////////////////////// ///////// Processing Storage ////// /////////////////////////////////////////// this.storage = new CacheStorage(this, 'Storage', { encryptionKey: props.kmsKey }); /////////////////////////////////////////// ////// Separator serialization ///// /////////////////////////////////////////// const separator = props.separator instanceof RegExp ? props.separator.toString() : props.separator; /////////////////////////////////////////// ////// Middleware Event Handler //// /////////////////////////////////////////// this.processor = new node.NodejsFunction(this, 'Compute', { description: 'Middleware splitting text documents in chunks.', entry: path.resolve(__dirname, 'lambdas', 'text-splitter', '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, SNS_TARGET_TOPIC: this.eventBus.topicArn, PROCESSED_FILES_BUCKET: this.storage.id(), SEPARATOR_TYPE: props.separator instanceof RegExp ? 'regexp' : 'string', SEPARATOR: separator }, 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.processor.grantPrincipal; // Plug the SQS queue into the lambda function. this.processor.addEventSource(new sources.SqsEventSource(this.eventQueue, { batchSize: props.batchSize ?? 5, reportBatchItemFailures: true })); // Function permissions. this.storage.grantWrite(this.processor); this.eventBus.grantPublish(this.processor); super.bind(); }
/** * Construct constructor. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/regexp-text-splitter/src/index.ts#L119-L199
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RegexpTextSplitter.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/regexp-text-splitter/src/index.ts#L205-L207
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RegexpTextSplitter.supportedInputTypes
supportedInputTypes(): string[] { return ([ 'text/plain' ]); }
/** * @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/regexp-text-splitter/src/index.ts#L213-L217
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RegexpTextSplitter.supportedOutputTypes
supportedOutputTypes(): string[] { return ([ 'text/plain' ]); }
/** * @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/regexp-text-splitter/src/index.ts#L223-L227
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RegexpTextSplitter.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/regexp-text-splitter/src/index.ts#L233-L237
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
RegexpTextSplitter.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/regexp-text-splitter/src/index.ts#L246-L251
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
splitText
const splitText = (text: string): string[] => { let separator: any = SEPARATOR; // If the separator is a regexp, we deserialize the regexp expression. if (SEPARATOR_TYPE === 'regexp') { separator = new RegExp( SEPARATOR.slice(1, SEPARATOR.lastIndexOf('/')), SEPARATOR.slice(SEPARATOR.lastIndexOf('/') + 1) ); } return (text .split(separator) .map((t) => t.trim()) ); };
/** * Splits the given text into an array of substrings * based on the specified separator. * @param text the text to split. * @returns an array of substrings. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/regexp-text-splitter/src/lambdas/text-splitter/index.ts#L57-L72
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
Lambda.getMetadata
getMetadata(chunk: string, order: number, total: number): DocumentMetadata { return ({ properties: { kind: 'text', attrs: { chunk: { id: crypto .createHash('sha256') .update(chunk) .digest('hex'), order, total } } } }); }
/** * @param chunk the chunk of text to return metadata for. * @param order the order of the chunk. * @param total the total number of chunks in the document. * @returns the metadata for the chunk. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/regexp-text-splitter/src/lambdas/text-splitter/index.ts#L88-L104
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
Lambda.processEvent
async processEvent(event: CloudEvent): Promise<CloudEvent> { const document = event.data().document(); // We load the text file in memory. const text = (await document.data().asBuffer()).toString('utf-8'); // Split the text into chunks. const chunks = splitText(text); const total = chunks.length; // Publish each chunk as a separate document. for (const [idx, chunk] of chunks.entries()) { await this.onChunk(chunk, idx, total, event); } return (event); }
/** * @param event the event to process. * @note the next decorator will automatically forward the * returned cloud event to the next middlewares */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/regexp-text-splitter/src/lambdas/text-splitter/index.ts#L145-L161
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/text-processors/regexp-text-splitter/src/lambdas/text-splitter/index.ts#L170-L178
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SemanticOntologyExtractorBuilder.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/semantic-ontology-extractor/src/index.ts#L90-L93
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SemanticOntologyExtractorBuilder.withOntologyClassifier
public withOntologyClassifier(ontologyClassifier: DefaultOntologyClassifier | CustomOntologyClassifier) { this.middlewareProps.ontologyClassifier = ontologyClassifier; return (this); }
/** * Sets the ontology classifier to use to extract * semantic ontology from documents. * @param ontologyClassifier the ontology classifier to use. * @returns the current builder instance. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/index.ts#L101-L104
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SemanticOntologyExtractorBuilder.build
public build(): SemanticOntologyExtractor { return (new SemanticOntologyExtractor( this.scope, this.identifier, { ...this.middlewareProps as SemanticOntologyExtractorProps, ...this.props } )); }
/** * @returns a new instance of the `SemanticOntologyExtractor` * service constructed with the given parameters. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/index.ts#L110-L118
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SemanticOntologyExtractor.constructor
constructor(scope: Construct, id: string, private props: SemanticOntologyExtractorProps) { super(scope, id, description, { ...props, queueVisibilityTimeout: cdk.Duration.seconds( 2 * PROCESSING_TIMEOUT.toSeconds() ) }); // Validate the properties. this.props = this.parse(SemanticOntologyExtractorPropsSchema, props); /////////////////////////////////////////// ////// Middleware Event Handler //// /////////////////////////////////////////// this.eventProcessor = new node.NodejsFunction(this, 'Compute', { description: 'Extracts semantic ontology from processed documents.', 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, LAKECHAIN_CACHE_STORAGE: this.props.cacheStorage.id(), BEDROCK_REGION: this.props.region ?? cdk.Aws.REGION, MODEL_ID: DEFAULT_MODEL_ID, ONTOLOGY_CLASSIFIER_PROPS: JSON.stringify( this.props.ontologyClassifier ) }, 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: 3, 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/*`, ] })); // 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/semantic-ontology-extractor/src/index.ts#L139-L216
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SemanticOntologyExtractor.grantReadProcessedDocuments
grantReadProcessedDocuments(grantee: iam.IGrantable): iam.Grant { // Since this middleware simply passes through the data // from the previous middleware, we grant any subsequent // middlewares in the pipeline read access to the // data of all source middlewares. for (const source of this.sources) { source.grantReadProcessedDocuments(grantee); } 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/text-processors/semantic-ontology-extractor/src/index.ts#L222-L231
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SemanticOntologyExtractor.supportedInputTypes
supportedInputTypes(): string[] { return ([ ...BASE_TEXT_INPUTS, ...BASE_IMAGE_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/semantic-ontology-extractor/src/index.ts#L237-L242
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SemanticOntologyExtractor.supportedOutputTypes
supportedOutputTypes(): string[] { return (this.supportedInputTypes()); }
/** * @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/semantic-ontology-extractor/src/index.ts#L248-L250
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SemanticOntologyExtractor.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/semantic-ontology-extractor/src/index.ts#L256-L260
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SemanticOntologyExtractor.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/semantic-ontology-extractor/src/index.ts#L269-L274
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
parse
const parse = (schema: z.ZodSchema, opts: CustomOntologyClassifierProps): any => { const options: ErrorMessageOptions = { delimiter: { component: ' - ', }, path: { enabled: true, type: 'zodPathArray', label: 'Path: ', }, code: { enabled: false }, message: { enabled: true, label: '', }, transform: ({ errorMessage, index }) => { return (`❗ Custom Ontology Classifier - Error #${index + 1}: ${errorMessage}`); } }; const result = schema.safeParse(opts); if (!result.success) { throw new Error(generateErrorMessage(result.error.issues, options)); } return (result.data); };
/** * An internal helper allowing to validate schemas using a * predefined visualization for error messages. * @param schema the Zod schema to use to validate the properties. * @param opts the options to validate. * @returns the parsed properties. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L80-L107
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifierBuilder.withNodes
public withNodes(nodes: Node[] | 'automatic'): CustomOntologyClassifierBuilder { this.props.nodes = nodes; return (this); }
/** * Sets the nodes defined in the ontology. * @param nodes the nodes defined in the ontology. * @returns the current builder instance. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L171-L174
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifierBuilder.withEdges
public withEdges(edges: Edge[] | 'automatic'): CustomOntologyClassifierBuilder { this.props.edges = edges; return (this); }
/** * Sets the edges defined in the ontology. * @param edges the edges defined in the ontology. * @returns the current builder instance. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L181-L184
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifierBuilder.build
public build(): CustomOntologyClassifier { return (CustomOntologyClassifier.from(this.props)); }
/** * @returns a new instance of the `CustomOntologyClassifier` * classifier constructed with the given parameters. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L190-L192
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.constructor
constructor(public props: CustomOntologyClassifierProps) { this.defaultClassifier = new DefaultOntologyClassifier.Builder().build(); }
/** * Creates a new instance of the `CustomOntologyClassifier` class. * @param props the task properties. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L214-L216
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.classifierType
public classifierType(): string { return (this.props.classifierType); }
/** * @returns the type of the classifier. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L221-L223
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.nodes
public nodes(): Node[] | 'automatic' { return (this.props.nodes); }
/** * @returns the nodes defined in the ontology. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L228-L230
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.edges
public edges(): Edge[] | 'automatic' { return (this.props.edges); }
/** * @returns the edges defined in the ontology. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L235-L237
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.from
public static from(props: any) { return (new CustomOntologyClassifier( parse(CustomOntologyClassifierPropsSchema, props) )); }
/** * Creates a new instance of the `CustomOntologyClassifier` class. * @param props the task properties. * @returns a new instance of the `CustomOntologyClassifier` class. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L244-L248
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.getPrompts
public getPrompts(): Prompt[] { const prompts = this.defaultClassifier.getPrompts(); let userPrompt = USER_PROMPT; // Nodes definition. if (this.nodes() === 'automatic') { userPrompt += ` Define the nodes automatically based on your analysis of the documents. The nodes cannot be of type "Document", "Author", "Publisher", "Topic", "Class", or "Kind" as they are reserved types. `; } else { userPrompt += ` Attempt to extract the following nodes from the documents. Only include nodes for which the properties are found in the document; do not include nodes without properties. <json> ${JSON.stringify(this.nodes(), null, 2)} </json> `; } if (this.edges() === 'automatic') { userPrompt += ` Define the edges in the nodes based on your analysis of the documents. Create edges using capital letters and underscores such as "IS_ASSOCIATED_WITH" or "PARTICIPATED_IN". `; } else { userPrompt += ` Attempt to extract the following edges from the documents. Only include edges for which the source and target nodes are found in the document; do not include edges without source or target nodes. <json> ${JSON.stringify(this.edges(), null, 2)} </json> `; } // Add custom prompts. prompts.push({ type: 'custom', systemPrompt: SYSTEM_PROMPT, userPrompt }); return (prompts); }
/** * @returns the prompts to execute to extract the * semantic ontology from documents. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L254-L297
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.isNodeValid
private isNodeValid(node: any): boolean { return (node && node.id && node.type && node.description && Array.isArray(node.props) ); }
/** * Validates the given node. * @param node the node to validate. * @returns `true` if the node is valid; `false` otherwise. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L304-L311
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.getId
private getId(node: any): string { const attribute = node.props.find((prop: any) => prop.uniqueIdentifier); return (attribute ? `${node.type}-${attribute.value}` : `${node.type}-${randomUUID()}`); }
/** * A helper defining the unique identifier of node. * This makes it possible to namespace nodes, and honors * the `uniqueIdentifier` attribute. * @param node the node to get the id for. * @returns the unique identifier of the node. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L320-L323
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.makeGraph
private async makeGraph(event: CloudEvent, json: any): Promise<CloudEvent> { const metadata = event.data().metadata(); const cache = new CacheStorage(); let graph: DirectedGraph; // If the graph does not exist, we create it. if (metadata.ontology) { graph = await metadata.ontology.resolve(); } else { graph = new DirectedGraph(); } // Add the nodes to the graph. for (const node of json.nodes) { if (this.isNodeValid(node)) { const props: Record<string, any> = { type: node.type, attrs: { description: node.description, isHead: node.isHead } }; // Set a unique identifier for the node. const id = this.getId(node); // Add the properties to the node. node.props .filter((prop: any) => prop.name && prop.value) .forEach((prop: any) => props.attrs[prop.name] = prop.value); // Add the node to the graph. graph.addNode(id, props); // Update all edges that have the node as a source or target // in `json.edges` to match the new node id. for (const edge of json.edges) { if (edge.source === node.id) { edge.source = id; } if (edge.target === node.id) { edge.target = id; } } } } // Add the edges to the graph. for (const edge of json.edges) { if (graph.hasNode(edge.source) && graph.hasNode(edge.target)) { const props: Record<string, any> = { type: edge.type, attrs: { description: edge.description } }; // Add the properties to the edge. (edge.props ?? []) .filter((prop: any) => prop.name && prop.value) .forEach((prop: any) => props.attrs[prop.name] = prop.value); // Add the edge to the graph. graph.addEdge(edge.source, edge.target, props); } } // Save the graph in the cache storage. metadata.ontology = await cache.put('ontology', graph); return (Promise.resolve(event)); }
/** * Creates a graph from the given JSON object. * @param event the cloud event to update. * @param json the JSON object extracted from the LLM. * @returns the updated cloud event. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L331-L402
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.update
public async update(json: any, prompt: Prompt, event: CloudEvent): Promise<CloudEvent> { if (prompt.type === 'default') { return (Promise.resolve( this.defaultClassifier.update(json, prompt, event) )); } else if (prompt.type === 'custom') { return (this.makeGraph(event, json)); } else { throw new Error(`Unknown prompt type: ${prompt.type}`); } }
/** * Updates the given cloud event based on the answer generated by the LLM * and the prompt. * @param json the JSON object extracted from the LLM. * @param prompt the prompt used to generate the JSON object. * @param event the cloud event to update. * @returns the updated cloud event. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L412-L422
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
CustomOntologyClassifier.toJSON
public toJSON() { return (this.props); }
/** * @returns the JSON representation of the classifier. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/custom-ontology-classifier.ts#L427-L429
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
DefaultOntologyClassifier.constructor
constructor(public props: DefaultOntologyClassifierProps) {}
/** * Creates a new instance of the `DefaultOntologyClassifier` class. * @param props the task properties. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/default-ontology-classifier.ts#L108-L108
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
DefaultOntologyClassifier.classifierType
public classifierType(): string { return (this.props.classifierType); }
/** * @returns the type of the classifier. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/default-ontology-classifier.ts#L113-L115
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
DefaultOntologyClassifier.from
public static from(props: any) { return (new DefaultOntologyClassifier( DefaultOntologyClassifierPropsSchema.parse(props) )); }
/** * Creates a new instance of the `DefaultOntologyClassifier` class. * @param props the task properties. * @returns a new instance of the `DefaultOntologyClassifier` class. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/default-ontology-classifier.ts#L122-L126
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
DefaultOntologyClassifier.getPrompts
public getPrompts(): Prompt[] { return ([{ type: 'default', userPrompt: USER_PROMPT, systemPrompt: SYSTEM_PROMPT }]); }
/** * @returns the prompts to execute to extract the * semantic ontology from documents. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/default-ontology-classifier.ts#L132-L138
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
DefaultOntologyClassifier.update
public update(json: any, _: Prompt, event: CloudEvent): Promise<CloudEvent> { const metadata = event.data().metadata(); // Document type. if (json.type) { metadata.type = json.type; } // Dates. if (json.createdAt) { metadata.createdAt = json.createdAt; } if (json.updatedAt) { metadata.updatedAt = json.updatedAt; } // Title. if (json.title) { metadata.title = json.title; } // Description. if (json.description) { metadata.description = json.description; } // Keywords. if (Array.isArray(json.keywords)) { if (!metadata.keywords?.length) { metadata.keywords = json.keywords; } else { metadata.keywords.push(...json.keywords); } } // Topics. if (Array.isArray(json.topics) && json.topics.length) { if (!metadata.topics?.length) { metadata.topics = json.topics; } else { metadata.topics.push(...json.topics); } } // Authors. if (Array.isArray(json.authors) && json.authors.length) { metadata.authors = json.authors; } // Language. if (json.language) { metadata.language = json.language; } return (Promise.resolve(event)); }
/** * Updates the given cloud event based on the answer generated by the LLM * and the prompt. * @param json the JSON object extracted from the LLM. * @param _ the prompt used to generate the JSON object. * @param event the cloud event to update. * @returns the updated cloud event. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/default-ontology-classifier.ts#L148-L203
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
DefaultOntologyClassifier.toJSON
public toJSON() { return (this.props); }
/** * @returns the JSON representation of the classifier. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/definitions/classifiers/default-ontology-classifier.ts#L208-L210
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/semantic-ontology-extractor/src/lambdas/handler/index.ts#L66-L79
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/semantic-ontology-extractor/src/lambdas/handler/index.ts#L113-L117
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/semantic-ontology-extractor/src/lambdas/handler/index.ts#L127-L131
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/semantic-ontology-extractor/src/lambdas/handler/invoke.ts#L63-L68
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
getMessages
const getMessages = async (events: CloudEvent[], prompt: Prompt) => { const messages = [{ role: 'user', content: [ { type: 'text', text: prompt.userPrompt } ] as any[] }]; // Get the input documents. events = events.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') } }); } } // Prepend the assistant prompt with a `{` character // to guide the LLM to generate a JSON object. messages.push({ role: 'assistant', content: [ { type: 'text', text: '{' } ] 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/semantic-ontology-extractor/src/lambdas/handler/invoke.ts#L75-L139
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
getBody
const getBody = async (events: CloudEvent[], prompt: Prompt) => { return ({ anthropic_version: 'bedrock-2023-05-31', system: prompt.systemPrompt, messages: await getMessages(events, prompt), max_tokens: 4096, temperature: 0.3 }); };
/** * 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/semantic-ontology-extractor/src/lambdas/handler/invoke.ts#L147-L155
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
parseJson
const parseJson = (data: string) => { try { return (JSON.parse(data)); } catch (err) { // If the document is not a valid JSON, we attempt to extract // the JSON object embedded within the string. const firstBracket = data.indexOf('{'); const lastBracket = data.lastIndexOf('}'); return (JSON.parse( data.slice(firstBracket, lastBracket + 1) )); } };
/** * A helper function used to parse a JSON document * embedded within the given string. * @param data the string to parse. * @returns a JSON object. * @throws an error if the JSON document cannot be extracted. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/semantic-ontology-extractor/src/lambdas/handler/invoke.ts#L164-L176
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SentenceTextSplitterBuilder.withMaxBytesLength
public withMaxBytesLength(maxBytesLength: number) { this.providerProps.maxBytesLength = maxBytesLength; return (this); }
/** * Sets the maximum number of bytes to keep * for a chunk. * @param maxBytesLength the maximum number of bytes * to keep for a chunk. * @returns the builder itself. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/sentence-text-splitter/src/index.ts#L72-L75
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SentenceTextSplitterBuilder.build
public build(): SentenceTextSplitter { return (new SentenceTextSplitter( this.scope, this.identifier, { ...this.providerProps as SentenceTextSplitterProps, ...this.props } )); }
/** * @returns a new instance of the `SentenceTextSplitter` * service constructed with the given parameters. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/sentence-text-splitter/src/index.ts#L81-L89
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SentenceTextSplitter.constructor
constructor(scope: Construct, id: string, props: SentenceTextSplitterProps) { super(scope, id, description, { ...props, queueVisibilityTimeout: cdk.Duration.seconds( 6 * PROCESSING_TIMEOUT.toSeconds() ) }); // Validate the properties. props = this.parse(SentenceTextSplitterPropsSchema, props); /////////////////////////////////////////// ///////// Processing Storage ////// /////////////////////////////////////////// this.storage = new CacheStorage(this, 'Storage', { encryptionKey: props.kmsKey }); /////////////////////////////////////////// ////// Middleware Event Handler //// /////////////////////////////////////////// this.processor = new lambda.DockerImageFunction(this, 'Compute', { description: 'A function splitting text documents in chunks.', code: lambda.DockerImageCode.fromImageAsset( path.resolve(__dirname, 'lambdas', 'text-splitter') ), vpc: props.vpc, memorySize: props.maxMemorySize ?? DEFAULT_MEMORY_SIZE, timeout: PROCESSING_TIMEOUT, architecture: lambda.Architecture.X86_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, SNS_TARGET_TOPIC: this.eventBus.topicArn, PROCESSED_FILES_BUCKET: this.storage.id(), MAX_BYTES_LENGTH: `${props.maxBytesLength}`, CACHE_DIR: '/tmp' } }); // 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 ?? 5, reportBatchItemFailures: true })); // Function permissions. this.storage.grantWrite(this.processor); this.eventBus.grantPublish(this.processor); super.bind(); }
/** * Construct constructor. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/sentence-text-splitter/src/index.ts#L116-L180
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SentenceTextSplitter.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/sentence-text-splitter/src/index.ts#L186-L188
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SentenceTextSplitter.supportedInputTypes
supportedInputTypes(): string[] { return ([ 'text/plain' ]); }
/** * @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/sentence-text-splitter/src/index.ts#L194-L198
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SentenceTextSplitter.supportedOutputTypes
supportedOutputTypes(): string[] { return ([ 'text/plain' ]); }
/** * @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/sentence-text-splitter/src/index.ts#L204-L208
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SentenceTextSplitter.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/sentence-text-splitter/src/index.ts#L214-L218
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SentenceTextSplitter.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/sentence-text-splitter/src/index.ts#L227-L232
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractorBuilder.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/structured-entity-extractor/src/index.ts#L87-L90
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractorBuilder.withSchema
public withSchema(schema: z.ZodSchema<any>) { this.middlewareProps.schema = schema; return (this); }
/** * Sets the schema to use to extract structured * entities from documents. * @param schema the schema to use to extract structured * entities from documents. * @returns the current builder instance. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/index.ts#L99-L102
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractorBuilder.withOutputType
public withOutputType(outputType: 'json' | 'metadata') { this.middlewareProps.outputType = outputType; return (this); }
/** * Sets the output type of the structured entities. * @param outputType the output type of the structured entities. * @returns the current builder instance. * @default 'json' */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/index.ts#L110-L113
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractorBuilder.withModel
public withModel(model: Model) { this.middlewareProps.model = model; return (this); }
/** * Sets the model to use for structured entity extraction. * @param model the model to use for structured entity extraction. * @returns the current builder instance. * @default 'anthropic.claude-3-sonnet-20240229-v1:0' */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/index.ts#L121-L124
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractorBuilder.withInstructions
public withInstructions(instructions: string) { this.middlewareProps.instructions = instructions; return (this); }
/** * Sets optional instruction to pass to the model to guide it * in extracting structured entities. * @param instructions optional instruction to pass to the model to guide it * in extracting structured entities. * @returns the current builder instance. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/index.ts#L133-L136
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractorBuilder.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/structured-entity-extractor/src/index.ts#L144-L147
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractorBuilder.build
public build(): StructuredEntityExtractor { return (new StructuredEntityExtractor( this.scope, this.identifier, { ...this.middlewareProps as StructuredEntityExtractorProps, ...this.props } )); }
/** * @returns a new instance of the `StructuredEntityExtractor` * service constructed with the given parameters. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/index.ts#L153-L161
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractor.constructor
constructor(scope: Construct, id: string, private props: StructuredEntityExtractorProps) { super(scope, id, description, { ...props, queueVisibilityTimeout: cdk.Duration.seconds( 2 * PROCESSING_TIMEOUT.toSeconds() ) }); // Validate the properties. this.props = this.parse(StructuredEntityExtractorPropsSchema, props); /////////////////////////////////////////// //////// Processing Storage /////// /////////////////////////////////////////// this.storage = new CacheStorage(this, 'Storage', { encryptionKey: props.kmsKey }); /////////////////////////////////////////// ////////// Schema Handler ///////// /////////////////////////////////////////// // Convert the Zod schema to a JSON schema. const jsonSchema = zodToJsonSchema(this.props.schema) as any; // Stringified JSON schema. const schema = JSON.stringify(jsonSchema); // Ensure the root schema is an object. if (jsonSchema.type !== 'object') { throw new Error(` The root schema you provide must be of type 'object'. `); } // Create a reference to the schema. let reference: r.IReference<any> = r.reference(r.value(schema)); // If the schema is bigger than a certain threshold, we upload the schema // to the internal storage and reference it in the lambda environment. if (schema.length > 3072) { new s3deploy.BucketDeployment(this, 'Schema', { sources: [s3deploy.Source.data('schema', schema)], destinationBucket: this.storage.getBucket() }); reference = r.reference(r.url(`s3://${this.storage.getBucket().bucketName}/schema`)); } /////////////////////////////////////////// ////// Middleware Event Handler //// /////////////////////////////////////////// this.eventProcessor = new node.NodejsFunction(this, 'Compute', { description: 'Extracts structured entities from processed documents.', 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(), LAKECHAIN_CACHE_STORAGE: this.props.cacheStorage.id(), BEDROCK_REGION: this.props.region ?? cdk.Aws.REGION, MODEL_ID: this.props.model, SCHEMA: JSON.stringify(reference), OUTPUT_TYPE: this.props.outputType, INSTRUCTIONS: this.props.instructions ?? '', MODEL_PARAMETERS: JSON.stringify(this.props.modelParameters) }, 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: this.props.maxConcurrency ?? 3, 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/*`, ] })); // Grant the compute type permissions to // publish to the SNS topic. this.eventBus.grantPublish(this.grantPrincipal); // Grant the compute type permissions to // write to the storage. this.storage.grantWrite(this.grantPrincipal); super.bind(); }
/** * Construct constructor. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/index.ts#L187-L308
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractor.grantReadProcessedDocuments
grantReadProcessedDocuments(grantee: iam.IGrantable): iam.Grant { if (this.props.outputType === 'json') { return (this.storage.grantRead(grantee)); } else { // Since this middleware simply passes through the data // from the previous middleware, we grant any subsequent // middlewares in the pipeline read access to the // data of all source middlewares. for (const source of this.sources) { source.grantReadProcessedDocuments(grantee); } 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/text-processors/structured-entity-extractor/src/index.ts#L314-L327
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractor.supportedInputTypes
supportedInputTypes(): string[] { return ([ 'text/plain', 'text/markdown', 'text/csv', 'text/html', 'application/x-subrip', 'text/vtt', 'application/json', 'application/xml', 'application/cloudevents+json' ]); }
/** * @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/structured-entity-extractor/src/index.ts#L333-L345
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractor.supportedOutputTypes
supportedOutputTypes(): string[] { return (this.props.outputType === 'json' ? ['application/json'] : this.supportedInputTypes() ); }
/** * @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/structured-entity-extractor/src/index.ts#L351-L356
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractor.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/structured-entity-extractor/src/index.ts#L362-L366
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
StructuredEntityExtractor.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/structured-entity-extractor/src/index.ts#L375-L380
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/structured-entity-extractor/src/lambdas/handler/index.ts#L123-L136
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
Lambda.getContent
private async getContent(events: CloudEvent[]): Promise<ContentBlock[]> { const content = [{ text: USER_PROMPT }]; // Add additional instructions if available. if (INSTRUCTIONS) { content.push({ text: `Here are additional instructions you must follow when extracting structured data: <instructions> ${INSTRUCTIONS} </instructions>` }); } // Add the documents to the prompt. for (const event of events) { const document = event.data().document(); const text = (await document.data().asBuffer()).toString('utf-8'); content.push({ text: `<document>\n${text}\n</document>` }); } return (content); }
/** * Creates the content array to pass to the model. * @param events the events to create a prompt for. * @returns a promise to an array of messages to pass to the model. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/lambdas/handler/index.ts#L143-L168
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
Lambda.parseOutput
private parseOutput(result: any, validateFn: any) { const output = result.output?.message; const content = output?.content; const response = content.find((item: any) => 'toolUse' in item); if (result.stopReason !== 'tool_use') { throw new InvalidResponseException('The data extraction tool was not invoked.'); } if (!response?.toolUse) { throw new InvalidResponseException('The data extraction tool did not return any results.'); } // Validate the extracted data. const isValid = validateFn(response.toolUse.input); if (!isValid) { throw new InvalidSchemaException(validateFn.errors, response); } return (response.toolUse.input); }
/** * Parses the output of the data extraction tool. * @param result the result of the data extraction. * @param validateFn the validation function to use. * @returns the structured data extracted from the documents. * @throws an error if the data extraction fails. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/lambdas/handler/index.ts#L177-L196
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
Lambda.extract
private async extract(events: CloudEvent[], maxRetries = DEFAULT_MAX_RETRIES): Promise<any> { const messages: Message[] = [{ role: 'user', content: await this.getContent(events) }]; // The JSON schema to extract structured data from // the provided documents. const schema = JSON.parse( await events[0].resolve(SCHEMA_REFERENCE) ); // The validation function to use. const validate = ajv.compile(schema); // For up to `maxRetries` attempts, we will try to extract // structured data from the documents. while (maxRetries-- > 0) { const result = await bedrock.send(new ConverseCommand({ modelId: MODEL_ID, system: [{ text: SYSTEM_PROMPT }], messages, toolConfig: { tools: [{ toolSpec: { name: TOOL_NAME, description: 'A function receiving the results of the data extraction.', inputSchema: { json: schema } } }], toolChoice: { tool: { name: TOOL_NAME } } }, inferenceConfig: MODEL_PARAMETERS })); // We add the assistant response to the messages. messages.push(result.output!.message!); // Parse and validate the extracted data. try { return (this.parseOutput(result, validate)); } catch (error) { if (error instanceof InvalidSchemaException) { // The extracted data are invalid, we want to prompt the model // with the errors to correct the generated data. messages.push({ role: 'user', content: [{ toolResult: { toolUseId: error.getResponse().toolUse.toolUseId, content: [{ text: `${ERROR_PROMPT}\n${JSON.stringify(error.getErrors())}` }], status: 'error' } }] }); } } } throw new Error('Failed to extract structured data.'); }
/** * Extracts structured data from the provided documents. * @param events the CloudEvents to process. * @param maxRetries the maximum number of retries to attempt. * @returns a promise to an object containing the structured data * matching the given schema. * @throws an error if the data extraction fails. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/lambdas/handler/index.ts#L206-L276
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/structured-entity-extractor/src/lambdas/handler/index.ts#L321-L325
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/structured-entity-extractor/src/lambdas/handler/index.ts#L335-L339
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
InvalidResponseException.constructor
constructor(description: string) { super(description); }
/** * `InvalidResponseException` constructor. * @param description the description of the exception. * @param errors the errors that caused the response to be invalid. * @param response the response that is not valid. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/lambdas/handler/exceptions/invalid-response.ts#L29-L31
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
InvalidSchemaException.constructor
constructor(private errors: ErrorObject[], private response: any) { super(`The extracted data are invalid : ${JSON.stringify(errors)}`); }
/** * `InvalidSchemaException` constructor. * @param errors the errors that caused the response to be invalid. * @param response the response that is not valid. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/lambdas/handler/exceptions/invalid-schema.ts#L30-L32
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
InvalidSchemaException.getResponse
public getResponse(): any { return (this.response); }
/** * @returns the response that is not valid. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/lambdas/handler/exceptions/invalid-schema.ts#L37-L39
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
InvalidSchemaException.getErrors
public getErrors(): ErrorObject[] { return (this.errors); }
/** * @returns the errors that caused the response to be invalid. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/structured-entity-extractor/src/lambdas/handler/exceptions/invalid-schema.ts#L44-L46
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SubtitleProcessorBuilder.withOutputFormats
public withOutputFormats(...outputFormats: OutputFormat[]) { this.providerProps.outputFormats = outputFormats; return (this); }
/** * Sets the chunk size. * @param chunkSize the chunk size to assign. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/subtitle-processor/src/index.ts#L75-L78
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SubtitleProcessorBuilder.build
public build(): SubtitleProcessor { return (new SubtitleProcessor( this.scope, this.identifier, { ...this.providerProps as SubtitleProcessorProps, ...this.props } )); }
/** * @returns a new instance of the `SubtitleProcessor` * service constructed with the given parameters. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/subtitle-processor/src/index.ts#L84-L92
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SubtitleProcessor.constructor
constructor(scope: Construct, id: string, private props: SubtitleProcessorProps) { super(scope, id, description, { ...props, queueVisibilityTimeout: cdk.Duration.seconds( 3 * PROCESSING_TIMEOUT.toSeconds() ) }); // Validate the properties. this.props = this.parse(SubtitleProcessorPropsSchema, props); /////////////////////////////////////////// ///////// Processing Storage ////// /////////////////////////////////////////// this.storage = new CacheStorage(this, 'Storage', { encryptionKey: this.props.kmsKey }); /////////////////////////////////////////// ////// Middleware Event Handler //// /////////////////////////////////////////// this.processor = new node.NodejsFunction(this, 'Compute', { description: 'A middleware parsing subtitle documents.', entry: path.resolve(__dirname, 'lambdas', 'parser', '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(), OUTPUT_FORMATS: JSON.stringify(this.props.outputFormats) }, 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.processor.grantPrincipal; // Plug the SQS queue into the lambda function. this.processor.addEventSource(new sources.SqsEventSource(this.eventQueue, { batchSize: this.props.batchSize ?? 5, reportBatchItemFailures: true })); // Function permissions. this.storage.grantWrite(this.processor); this.eventBus.grantPublish(this.processor); super.bind(); }
/** * Construct constructor. */
https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/subtitle-processor/src/index.ts#L119-L188
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SubtitleProcessor.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/subtitle-processor/src/index.ts#L194-L196
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SubtitleProcessor.supportedInputTypes
supportedInputTypes(): string[] { return ([ 'text/vtt', 'application/x-subrip' ]); }
/** * @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/subtitle-processor/src/index.ts#L202-L207
4285173e80584eedfc1a8424d3d1b6c1a7038088
project-lakechain
github_2023
awslabs
typescript
SubtitleProcessor.supportedOutputTypes
supportedOutputTypes(): string[] { const outputs = []; for (const format of this.props.outputFormats) { if (format === 'text') { outputs.push('text/plain'); } else if (format === 'json') { outputs.push('application/json'); } } return (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/subtitle-processor/src/index.ts#L213-L224
4285173e80584eedfc1a8424d3d1b6c1a7038088