@tstdl/base 0.92.103 → 0.92.105

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ai/ai.service.js CHANGED
@@ -4,11 +4,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
4
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
+ var _a;
8
+ var AiService_1;
7
9
  import { FinishReason, FunctionCallingMode as GoogleFunctionCallingMode, VertexAI } from '@google-cloud/vertexai';
8
10
  import { GoogleGenerativeAI } from '@google/generative-ai';
9
11
  import { NotSupportedError } from '../errors/not-supported.error.js';
10
12
  import { Singleton } from '../injector/decorators.js';
11
13
  import { inject, injectArgument } from '../injector/inject.js';
14
+ import { Logger } from '../logger/logger.js';
12
15
  import { getShutdownSignal } from '../process-shutdown.js';
13
16
  import { DeferredPromise } from '../promise/deferred-promise.js';
14
17
  import { LazyPromise } from '../promise/lazy-promise.js';
@@ -38,9 +41,10 @@ const functionCallingModeMap = {
38
41
  force: GoogleFunctionCallingMode.ANY,
39
42
  none: GoogleFunctionCallingMode.NONE
40
43
  };
41
- let AiService = class AiService {
44
+ let AiService = AiService_1 = class AiService {
42
45
  #options = injectArgument(this, { optional: true }) ?? inject(AiServiceOptions);
43
46
  #fileService = inject(AiFileService, this.#options);
47
+ #logger = inject(Logger, AiService_1.name);
44
48
  #genAI = (isDefined(this.#options.vertex)
45
49
  ? new VertexAI({ project: this.#options.vertex.project, location: this.#options.vertex.location, googleAuthOptions: { apiKey: this.#options.apiKey, keyFile: this.#options.keyFile } })
46
50
  : new GoogleGenerativeAI(assertDefinedPass(this.#options.apiKey, 'Api key not defined')));
@@ -196,6 +200,7 @@ Always output the content and tags in ${options?.targetLanguage ?? 'the same lan
196
200
  return mergeGenerationStreamItems(items, request.generationSchema);
197
201
  }
198
202
  async *generateStream(request) {
203
+ this.#logger.verbose('Generating...');
199
204
  const googleFunctionDeclarations = isDefined(request.functions) ? await this.convertFunctions(request.functions) : undefined;
200
205
  const generationConfig = {
201
206
  maxOutputTokens: request.generationOptions?.maxOutputTokens,
@@ -234,6 +239,7 @@ Always output the content and tags in ${options?.targetLanguage ?? 'the same lan
234
239
  }
235
240
  catch (error) {
236
241
  if ((i < 20) && isError(error) && (error['status'] == 429)) {
242
+ this.#logger.verbose('429 Too Many Requests - trying again in 15 seconds');
237
243
  const canceled = await cancelableTimeout(15 * millisecondsPerSecond, getShutdownSignal());
238
244
  if (!canceled) {
239
245
  continue;
@@ -390,7 +396,7 @@ Always output the content and tags in ${options?.targetLanguage ?? 'the same lan
390
396
  return this.#genAI.getGenerativeModel({ model });
391
397
  }
392
398
  };
393
- AiService = __decorate([
399
+ AiService = AiService_1 = __decorate([
394
400
  Singleton()
395
401
  ], AiService);
396
402
  export { AiService };
@@ -134,7 +134,7 @@ let DocumentManagementService = DocumentManagementService_1 = class DocumentMana
134
134
  processQueues(cancellationSignal) {
135
135
  this.extractionQueue.process({ concurrency: 1, cancellationSignal }, async (job) => {
136
136
  const [entry] = objectEntries(job.data);
137
- this.logger.info(`Processing extraction job for ${entry?.[0]} "${entry?.[1]}"`);
137
+ this.logger.verbose(`Processing extraction job for ${entry?.[0]} ${entry?.[1]}`);
138
138
  await match(job.data)
139
139
  .with({ documentId: P.string.select() }, async (documentId) => this.enrichDocument(documentId))
140
140
  .with({ requestFileId: P.string.select() }, async (requestFileId) => this.enrichDocumentRequestFile(requestFileId))
@@ -142,7 +142,7 @@ let DocumentManagementService = DocumentManagementService_1 = class DocumentMana
142
142
  .exhaustive();
143
143
  }, this.logger);
144
144
  this.assignmentQueue.process({ concurrency: 1, cancellationSignal }, async (job) => {
145
- this.logger.info(`Processing assignment job "${job.data.requestAssignmentTaskId}"`);
145
+ this.logger.verbose(`Processing assignment job "${job.data.requestAssignmentTaskId}"`);
146
146
  await this.assignDocumentRequest(job.data.requestAssignmentTaskId);
147
147
  }, this.logger);
148
148
  }
@@ -554,6 +554,7 @@ let DocumentManagementService = DocumentManagementService_1 = class DocumentMana
554
554
  async enrichDocument(documentId) {
555
555
  const document = await this.documentService.load(documentId);
556
556
  const { properties, ...extractionResult } = await this.extractFileInformation(document.fileId, document.typeId);
557
+ this.logger.trace(`Applying extraction to document ${document.id}`);
557
558
  await this.documentService.transaction(async (documentService, transaction) => {
558
559
  await documentService.update(document.id, { ...extractionResult, validated: false });
559
560
  await this.setPropertyValues({ documentId, properties: properties }, transaction);
@@ -710,7 +711,10 @@ Ordne die Datei unter "file" der passenden Anforderungen unter "requests" zu. Gi
710
711
  const tmpFile = __addDisposableResource(env_1, await TemporaryFile.from(fileContentStream), true);
711
712
  const filePart = await this.#aiService.processFile({ path: tmpFile.path, mimeType: file.mimeType });
712
713
  const pages = file.mimeType.includes('pdf')
713
- ? await tryIgnoreLogAsync(this.logger, async () => getPdfPageCount(tmpFile.path), null)
714
+ ? await tryIgnoreLogAsync(this.logger, async () => {
715
+ this.logger.trace(`Extracting pdf page count for file ${fileId}`);
716
+ return getPdfPageCount(tmpFile.path);
717
+ }, null)
714
718
  : null;
715
719
  const types = await this.documentTypeService.session
716
720
  .select({
@@ -724,6 +728,7 @@ Ordne die Datei unter "file" der passenden Anforderungen unter "requests" zu. Gi
724
728
  .where(isString(assumeTypeId) ? eq(documentType.id, assumeTypeId) : undefined);
725
729
  const typeLabelEntries = types.map((type) => ({ id: type.typeId, label: `${type.categoryLabel} | ${type.typeGroup} | ${type.typeLabel}` }));
726
730
  const typeLabels = typeLabelEntries.map(({ label }) => label);
731
+ this.logger.trace(`Classifying document file ${fileId}`);
727
732
  const documentTypeGeneration = await this.#aiService.generate({
728
733
  ...defaultGenerationOptions,
729
734
  generationSchema: object({
@@ -763,6 +768,7 @@ Ordne die Datei unter "file" der passenden Anforderungen unter "requests" zu. Gi
763
768
  ? {}
764
769
  : { documentProperties: object(fromEntries(propertiesSchemaEntries)) })
765
770
  });
771
+ this.logger.trace(`Extracting document file ${fileId}`);
766
772
  const { json: extraction } = await this.#aiService.generate({
767
773
  model: 'gemini-2.0-flash',
768
774
  generationOptions: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tstdl/base",
3
- "version": "0.92.103",
3
+ "version": "0.92.105",
4
4
  "author": "Patrick Hein",
5
5
  "publishConfig": {
6
6
  "access": "public"
package/queue/queue.d.ts CHANGED
@@ -78,12 +78,12 @@ export declare abstract class Queue<T> implements Resolvable<QueueArgument> {
78
78
  process({ concurrency, cancellationSignal }: {
79
79
  concurrency?: number;
80
80
  cancellationSignal: CancellationSignal;
81
- }, handler: ProcessWorker<T>, errorHandler?: Logger | ((error: unknown) => void | Promise<void>)): void;
81
+ }, handler: ProcessWorker<T>, logger: Logger): void;
82
82
  processBatch({ batchSize, concurrency, cancellationSignal }: {
83
83
  batchSize?: number;
84
84
  concurrency?: number;
85
85
  cancellationSignal: CancellationSignal;
86
- }, handler: ProcessBatchWorker<T>, errorHandler?: Logger | ((error: unknown) => void | Promise<void>)): void;
86
+ }, handler: ProcessBatchWorker<T>, logger: Logger): void;
87
87
  private processWorker;
88
88
  private processBatchWorker;
89
89
  }
package/queue/queue.js CHANGED
@@ -1,4 +1,3 @@
1
- import { isDefined, isFunction } from '../utils/type-guards.js';
2
1
  import { millisecondsPerMinute } from '../utils/units.js';
3
2
  import { QueueEnqueueBatch } from './enqueue-batch.js';
4
3
  export const defaultJobPriority = 1000;
@@ -15,45 +14,39 @@ export class Queue {
15
14
  batch() {
16
15
  return new QueueEnqueueBatch(this);
17
16
  }
18
- process({ concurrency = 1, cancellationSignal }, handler, errorHandler) {
19
- const handleError = isFunction(errorHandler)
20
- ? errorHandler
21
- : isDefined(errorHandler)
22
- ? (error) => errorHandler.error(error)
23
- : undefined;
17
+ process({ concurrency = 1, cancellationSignal }, handler, logger) {
24
18
  for (let i = 0; i < concurrency; i++) {
25
- void this.processWorker(cancellationSignal, handler, handleError);
19
+ void this.processWorker(cancellationSignal, handler, logger);
26
20
  }
27
21
  }
28
- processBatch({ batchSize = 10, concurrency = 1, cancellationSignal }, handler, errorHandler) {
29
- const handleError = isFunction(errorHandler)
30
- ? errorHandler
31
- : isDefined(errorHandler)
32
- ? (error) => errorHandler.error(error)
33
- : undefined;
22
+ processBatch({ batchSize = 10, concurrency = 1, cancellationSignal }, handler, logger) {
34
23
  for (let i = 0; i < concurrency; i++) {
35
- void this.processBatchWorker(batchSize, cancellationSignal, handler, handleError);
24
+ void this.processBatchWorker(batchSize, cancellationSignal, handler, logger);
36
25
  }
37
26
  }
38
- async processWorker(cancellationSignal, handler, errorHandler) {
27
+ async processWorker(cancellationSignal, handler, logger) {
39
28
  for await (const job of this.getConsumer(cancellationSignal)) {
29
+ logger?.verbose(`Processing job ${job.id}`);
40
30
  try {
41
31
  await handler(job);
32
+ logger?.verbose(`Acknowledge job ${job.id}`);
42
33
  await this.acknowledge(job);
43
34
  }
44
35
  catch (error) {
45
- await errorHandler?.(error);
36
+ logger?.error(error);
46
37
  }
47
38
  }
48
39
  }
49
- async processBatchWorker(size, cancellationSignal, handler, errorHandler) {
40
+ async processBatchWorker(size, cancellationSignal, handler, logger) {
50
41
  for await (const jobs of this.getBatchConsumer(size, cancellationSignal)) {
42
+ logger?.verbose(`Processing ${jobs.length} jobs`);
51
43
  try {
52
44
  await handler(jobs);
45
+ logger?.verbose(`Acknowledge ${jobs.length} jobs`);
53
46
  await this.acknowledgeMany(jobs);
54
47
  }
55
48
  catch (error) {
56
- await errorHandler?.(error);
49
+ logger?.error(error);
57
50
  }
58
51
  }
59
52
  }