@tstdl/base 0.93.123 → 0.93.126

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.
Files changed (219) hide show
  1. package/ai/genkit/tests/multi-region.test.js +6 -6
  2. package/ai/index.d.ts +2 -6
  3. package/ai/index.js +2 -6
  4. package/ai/parser/index.d.ts +1 -0
  5. package/ai/parser/index.js +1 -0
  6. package/ai/parser/parser.d.ts +12 -0
  7. package/ai/parser/parser.js +28 -0
  8. package/ai/prompts/build.d.ts +21 -0
  9. package/ai/prompts/build.js +25 -0
  10. package/ai/prompts/index.d.ts +2 -0
  11. package/ai/prompts/index.js +2 -0
  12. package/ai/prompts/instructions-formatter.d.ts +9 -22
  13. package/ai/prompts/instructions-formatter.js +20 -7
  14. package/ai/prompts/instructions.js +1 -1
  15. package/ai/prompts/steering.d.ts +27 -0
  16. package/ai/prompts/steering.js +54 -0
  17. package/ai/tests/instructions-formatter.test.js +115 -0
  18. package/ai/tests/steering.test.js +37 -0
  19. package/application/application.d.ts +2 -1
  20. package/application/application.js +3 -0
  21. package/authentication/client/module.d.ts +1 -1
  22. package/authentication/client/module.js +4 -5
  23. package/authentication/tests/authentication-ancillary.service.test.js +1 -1
  24. package/authentication/tests/authentication.api-controller.test.js +3 -1
  25. package/authentication/tests/authentication.api-request-token.provider.test.js +1 -1
  26. package/authentication/tests/authentication.client-service.test.js +1 -1
  27. package/authentication/tests/authentication.service.test.js +1 -1
  28. package/authentication/tests/subject.service.test.js +1 -1
  29. package/circuit-breaker/tests/circuit-breaker.test.js +1 -1
  30. package/document-management/api/document-management.api.d.ts +16 -16
  31. package/document-management/api/document-management.api.js +12 -12
  32. package/document-management/models/ai-configuration.d.ts +59 -0
  33. package/document-management/models/ai-configuration.js +1 -0
  34. package/document-management/models/document-assignment-scope.model.js +2 -4
  35. package/document-management/models/document-assignment-task.model.js +2 -4
  36. package/document-management/models/document-collection-assignment.model.js +2 -4
  37. package/document-management/models/document-collection.model.js +2 -3
  38. package/document-management/models/document-content.model.d.ts +6 -0
  39. package/document-management/models/document-content.model.js +32 -0
  40. package/document-management/models/document-property-value.model.js +1 -2
  41. package/document-management/models/document-request-collection-assignment.model.js +2 -4
  42. package/document-management/models/document-request.model.js +2 -4
  43. package/document-management/models/document-tag-assignment.model.js +2 -3
  44. package/document-management/models/document-validation-execution-related-document.model.js +2 -4
  45. package/document-management/models/document-validation-execution.model.js +2 -5
  46. package/document-management/models/document-workflow.model.d.ts +2 -1
  47. package/document-management/models/document-workflow.model.js +4 -5
  48. package/document-management/models/document.model.js +2 -3
  49. package/document-management/models/index.d.ts +2 -0
  50. package/document-management/models/index.js +2 -0
  51. package/document-management/server/api/document-management.api.d.ts +7 -7
  52. package/document-management/server/api/document-management.api.js +9 -9
  53. package/document-management/server/configure.d.ts +4 -1
  54. package/document-management/server/configure.js +9 -4
  55. package/document-management/server/drizzle/{0000_silly_chimera.sql → 0000_curious_nighthawk.sql} +8 -28
  56. package/document-management/server/drizzle/meta/0000_snapshot.json +14 -286
  57. package/document-management/server/drizzle/meta/_journal.json +2 -2
  58. package/document-management/server/module.d.ts +2 -0
  59. package/document-management/server/module.js +1 -0
  60. package/document-management/server/schemas.d.ts +2 -1
  61. package/document-management/server/services/document-file.service.d.ts +6 -6
  62. package/document-management/server/services/document-file.service.js +7 -81
  63. package/document-management/server/services/document-management-ai-provider.service.d.ts +66 -0
  64. package/document-management/server/services/document-management-ai-provider.service.js +2 -0
  65. package/document-management/server/services/document-management-ai.service.d.ts +44 -7
  66. package/document-management/server/services/document-management-ai.service.js +332 -329
  67. package/document-management/server/services/document-validation.service.d.ts +1 -1
  68. package/document-management/server/services/document-workflow.service.d.ts +4 -3
  69. package/document-management/server/services/document-workflow.service.js +26 -9
  70. package/document-management/server/services/document.service.d.ts +7 -3
  71. package/document-management/server/services/document.service.js +13 -4
  72. package/document-management/server/services/index.d.ts +1 -0
  73. package/document-management/server/services/index.js +1 -0
  74. package/document-management/server/validators/ai-validation-executor.d.ts +419 -12
  75. package/document-management/server/validators/ai-validation-executor.js +51 -46
  76. package/document-management/server/validators/single-document-validation-executor.d.ts +1 -3
  77. package/document-management/server/validators/single-document-validation-executor.js +2 -4
  78. package/document-management/service-models/document.service-model.d.ts +3 -3
  79. package/document-management/service-models/document.service-model.js +1 -1
  80. package/document-management/tests/ai-config-hierarchy.test.d.ts +1 -0
  81. package/document-management/tests/ai-config-hierarchy.test.js +64 -0
  82. package/document-management/tests/ai-config-integration.test.d.ts +1 -0
  83. package/document-management/tests/ai-config-integration.test.js +125 -0
  84. package/document-management/tests/ai-config-merge.test.d.ts +1 -0
  85. package/document-management/tests/ai-config-merge.test.js +38 -0
  86. package/document-management/tests/document-management-ai-overrides.test.d.ts +1 -0
  87. package/document-management/tests/document-management-ai-overrides.test.js +64 -0
  88. package/document-management/tests/document-management-core.test.js +6 -6
  89. package/document-management/tests/document-management.api.test.js +5 -5
  90. package/document-management/tests/document-statistics.service.test.js +10 -6
  91. package/document-management/tests/document-validation-ai-overrides.test.d.ts +1 -0
  92. package/document-management/tests/document-validation-ai-overrides.test.js +85 -0
  93. package/document-management/tests/document.service.test.js +15 -11
  94. package/document-management/tests/enum-helpers.test.js +5 -5
  95. package/examples/document-management/ai-provider.d.ts +20 -0
  96. package/examples/document-management/ai-provider.js +74 -0
  97. package/examples/document-management/main.js +9 -6
  98. package/examples/injector/graph-example.d.ts +1 -0
  99. package/examples/injector/graph-example.js +340 -0
  100. package/injector/decorators.d.ts +4 -4
  101. package/injector/decorators.js +5 -6
  102. package/injector/forward-ref.d.ts +15 -0
  103. package/injector/forward-ref.js +20 -0
  104. package/injector/graph.d.ts +113 -0
  105. package/injector/graph.js +631 -0
  106. package/injector/index.d.ts +2 -0
  107. package/injector/index.js +2 -0
  108. package/injector/inject.d.ts +15 -15
  109. package/injector/injector.d.ts +101 -13
  110. package/injector/injector.js +103 -59
  111. package/injector/resolve-chain.d.ts +20 -6
  112. package/injector/resolve-chain.js +39 -14
  113. package/injector/tests/advanced.test.d.ts +1 -0
  114. package/injector/tests/advanced.test.js +116 -0
  115. package/injector/tests/async-init.test.d.ts +1 -0
  116. package/injector/tests/async-init.test.js +77 -0
  117. package/injector/tests/basic.test.d.ts +1 -0
  118. package/injector/tests/basic.test.js +114 -0
  119. package/injector/tests/hierarchical.test.d.ts +1 -0
  120. package/injector/tests/hierarchical.test.js +59 -0
  121. package/injector/tests/lifecycles.test.d.ts +1 -0
  122. package/injector/tests/lifecycles.test.js +109 -0
  123. package/injector/token.d.ts +2 -1
  124. package/injector/token.js +4 -1
  125. package/injector/type-info.d.ts +1 -5
  126. package/injector/types.d.ts +4 -10
  127. package/logger/tests/pretty-print.test.d.ts +1 -0
  128. package/logger/{formatters → tests}/pretty-print.test.js +1 -1
  129. package/logger/transports/console.d.ts +3 -2
  130. package/logger/transports/console.js +4 -3
  131. package/notification/api/notification.api.d.ts +26 -6
  132. package/notification/api/notification.api.js +15 -4
  133. package/notification/client/notification-client.d.ts +6 -0
  134. package/notification/client/notification-client.js +13 -3
  135. package/notification/models/in-app-notification.model.d.ts +9 -3
  136. package/notification/models/in-app-notification.model.js +32 -11
  137. package/notification/models/notification-log.model.js +2 -3
  138. package/notification/server/api/notification.api-controller.d.ts +1 -0
  139. package/notification/server/api/notification.api-controller.js +7 -1
  140. package/notification/server/drizzle/{0000_oval_rage.sql → 0000_wise_pyro.sql} +22 -4
  141. package/notification/server/drizzle/meta/0000_snapshot.json +249 -37
  142. package/notification/server/drizzle/meta/_journal.json +2 -2
  143. package/notification/server/module.d.ts +5 -0
  144. package/notification/server/module.js +6 -1
  145. package/notification/server/providers/in-app-channel-provider.js +1 -0
  146. package/notification/server/schemas.d.ts +3 -2
  147. package/notification/server/schemas.js +3 -2
  148. package/notification/server/services/notification.service.d.ts +11 -6
  149. package/notification/server/services/notification.service.js +138 -42
  150. package/notification/tests/notification-api.test.js +16 -6
  151. package/notification/tests/notification-client.test.d.ts +1 -0
  152. package/notification/tests/{unit/notification-client.test.js → notification-client.test.js} +5 -5
  153. package/notification/tests/notification-flow.test.js +45 -7
  154. package/notification/tests/notification-sse.service.test.js +1 -1
  155. package/notification/tests/notification-type.service.test.js +1 -1
  156. package/object-storage/s3/s3.object-storage.js +3 -0
  157. package/object-storage/s3/tests/s3.object-storage.integration.test.js +1 -1
  158. package/orm/server/drizzle/schema-converter.js +5 -3
  159. package/orm/tests/repository-attributes.test.js +10 -17
  160. package/orm/tests/repository-cti-mapping.test.js +2 -2
  161. package/orm/tests/repository-cti-soft-delete.test.js +1 -1
  162. package/orm/tests/repository-cti.test.js +19 -33
  163. package/orm/tests/repository-extra-coverage.test.js +1 -1
  164. package/orm/tests/repository-search.test.js +5 -2
  165. package/orm/tests/schema-converter.test.js +1 -0
  166. package/orm/tests/transaction-safety.test.js +1 -1
  167. package/package.json +7 -9
  168. package/rate-limit/tests/postgres-rate-limiter.test.js +6 -16
  169. package/renderer/d2.d.ts +77 -0
  170. package/renderer/d2.js +68 -0
  171. package/renderer/graphviz.d.ts +47 -0
  172. package/renderer/graphviz.js +58 -0
  173. package/renderer/index.d.ts +4 -0
  174. package/renderer/index.js +4 -0
  175. package/renderer/typst.d.ts +57 -0
  176. package/renderer/typst.js +62 -0
  177. package/rpc/adapters/readable-stream.adapter.d.ts +3 -0
  178. package/rpc/adapters/readable-stream.adapter.js +5 -1
  179. package/rpc/rpc.js +28 -3
  180. package/rpc/tests/rpc.integration.test.js +3 -1
  181. package/schema/schemas/nullable.js +1 -1
  182. package/task-queue/task-queue.d.ts +2 -0
  183. package/task-queue/task-queue.js +6 -2
  184. package/task-queue/tests/complex.test.js +1 -1
  185. package/task-queue/tests/dependencies.test.js +3 -3
  186. package/task-queue/tests/extensive-dependencies.test.js +1 -1
  187. package/task-queue/tests/queue.test.js +1 -1
  188. package/task-queue/tests/worker.test.js +4 -7
  189. package/test5.js +52 -8
  190. package/{unit-test → testing}/integration-setup.d.ts +1 -0
  191. package/{unit-test → testing}/integration-setup.js +13 -0
  192. package/utils/base64.d.ts +7 -0
  193. package/utils/base64.js +10 -1
  194. package/utils/noop.d.ts +7 -1
  195. package/utils/noop.js +7 -1
  196. package/ai/ai-file.service.d.ts +0 -57
  197. package/ai/ai-file.service.js +0 -233
  198. package/ai/ai-session.d.ts +0 -38
  199. package/ai/ai-session.js +0 -50
  200. package/ai/ai.service.d.ts +0 -126
  201. package/ai/ai.service.js +0 -481
  202. package/ai/functions.d.ts +0 -9
  203. package/ai/functions.js +0 -38
  204. package/ai/module.d.ts +0 -26
  205. package/ai/module.js +0 -25
  206. package/ai/types.d.ts +0 -229
  207. package/ai/types.js +0 -33
  208. package/latex/index.d.ts +0 -1
  209. package/latex/index.js +0 -1
  210. package/typst/index.d.ts +0 -1
  211. package/typst/index.js +0 -1
  212. package/typst/render.d.ts +0 -23
  213. package/typst/render.js +0 -32
  214. /package/{logger/formatters/pretty-print.test.d.ts → ai/tests/instructions-formatter.test.d.ts} +0 -0
  215. /package/{notification/tests/unit/notification-client.test.d.ts → ai/tests/steering.test.d.ts} +0 -0
  216. /package/{latex/render.d.ts → renderer/latex.d.ts} +0 -0
  217. /package/{latex/render.js → renderer/latex.js} +0 -0
  218. /package/{unit-test → testing}/index.d.ts +0 -0
  219. /package/{unit-test → testing}/index.js +0 -0
@@ -1,233 +0,0 @@
1
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
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
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- };
7
- import { createReadStream } from 'node:fs';
8
- import { stat } from 'node:fs/promises';
9
- import { Readable } from 'node:stream';
10
- import { ReadableStream as NodeReadableStream } from 'node:stream/web';
11
- import { Storage } from '@google-cloud/storage';
12
- import { FileState, GoogleGenAI } from '@google/genai';
13
- import { CancellationSignal } from '../cancellation/token.js';
14
- import { AsyncEnumerable } from '../enumerable/async-enumerable.js';
15
- import { DetailsError } from '../errors/details.error.js';
16
- import { Singleton } from '../injector/decorators.js';
17
- import { inject, injectArgument } from '../injector/inject.js';
18
- import { Logger } from '../logger/logger.js';
19
- import { createArray } from '../utils/array/array.js';
20
- import { backoffGenerator } from '../utils/backoff.js';
21
- import { formatBytes } from '../utils/format.js';
22
- import { readBinaryStream } from '../utils/stream/stream-reader.js';
23
- import { assertDefinedPass, isBlob, isDefined, isUndefined } from '../utils/type-guards.js';
24
- import { AiModuleOptions } from './module.js';
25
- import { isPathFileInput } from './types.js';
26
- /**
27
- * Manages file uploads and state for use with AI models.
28
- * Handles both Google Generative AI File API and Google Cloud Storage for Vertex AI.
29
- */
30
- let AiFileService = class AiFileService {
31
- #options = injectArgument(this, { optional: true }) ?? inject(AiModuleOptions);
32
- #genAI = new GoogleGenAI({
33
- vertexai: isDefined(this.#options.vertex?.project),
34
- project: this.#options.vertex?.project,
35
- location: this.#options.vertex?.location,
36
- googleAuthOptions: isDefined(this.#options.vertex?.project) ? { apiKey: this.#options.apiKey, keyFile: this.#options.keyFile } : undefined,
37
- apiKey: isUndefined(this.#options.vertex?.project) ? assertDefinedPass(this.#options.apiKey, 'Api key not defined') : undefined,
38
- });
39
- #storage = isDefined(this.#options.vertex) ? new Storage({ keyFile: assertDefinedPass(this.#options.keyFile, 'Key file not defined'), projectId: this.#options.vertex.project }) : undefined;
40
- #fileMap = new Map();
41
- #fileUriMap = new Map();
42
- #logger = inject(Logger, 'AiFileService');
43
- #cancellationSignal = inject(CancellationSignal);
44
- #backoffOptions = {
45
- cancellationSignal: this.#cancellationSignal,
46
- strategy: 'linear',
47
- initialDelay: 1000,
48
- increase: 500,
49
- jitter: 0.2,
50
- maximumDelay: 10000,
51
- };
52
- #bucket;
53
- /**
54
- * Uploads and processes a single file, making it available for AI model consumption.
55
- * @param fileInput The file to process.
56
- * @returns A promise that resolves to a {@link FileContentPart} for use in AI requests.
57
- */
58
- async processFile(fileInput) {
59
- const file = await this.getFile(fileInput);
60
- this.#fileMap.set(file.id, file);
61
- this.#fileUriMap.set(file.uri, file);
62
- return { file: file.id };
63
- }
64
- /**
65
- * Uploads and processes multiple files in parallel, making them available for AI model consumption.
66
- * @param fileInputs The files to process.
67
- * @returns A promise that resolves to an array of {@link FileContentPart} for use in AI requests.
68
- */
69
- async processFiles(fileInputs) {
70
- const files = await this.getFiles(fileInputs);
71
- return files.map((file) => {
72
- this.#fileMap.set(file.id, file);
73
- this.#fileUriMap.set(file.uri, file);
74
- return { file: file.id };
75
- });
76
- }
77
- /**
78
- * Retrieves a file by its internal ID.
79
- * The file must have been processed by this service instance before.
80
- * @param id The internal ID of the file.
81
- * @returns The file, or `undefined` if not found.
82
- */
83
- getFileById(id) {
84
- return this.#fileMap.get(id);
85
- }
86
- /**
87
- * Retrieves a file by its URI (e.g., GCS URI).
88
- * The file must have been processed by this service instance before.
89
- * @param uri The URI of the file.
90
- * @returns The file, or `undefined` if not found.
91
- */
92
- getFileByUri(uri) {
93
- return this.#fileUriMap.get(uri);
94
- }
95
- async getFile(fileInput) {
96
- const id = crypto.randomUUID();
97
- const file = await this.uploadFile(fileInput, id);
98
- this.#logger.verbose(`Processing file "${id}"...`);
99
- await this.waitForFileActive(file);
100
- return file;
101
- }
102
- async getFiles(fileInputs) {
103
- const ids = createArray(fileInputs.length, () => crypto.randomUUID());
104
- const files = await AsyncEnumerable.from(fileInputs).parallelMap(5, true, async (file, index) => await this.uploadFile(file, ids[index])).toArray();
105
- this.#logger.verbose(`Processing ${fileInputs.length} files...`);
106
- await this.waitForFilesActive(files);
107
- return files;
108
- }
109
- async uploadFile(fileInput, id) {
110
- if (isDefined(this.#storage)) {
111
- return await this.uploadFileVertex(fileInput, id);
112
- }
113
- return await this.uploadFileGenAi(fileInput, id);
114
- }
115
- async uploadFileVertex(fileInput, id) {
116
- const bucket = await this.getBucket();
117
- const file = bucket.file(id);
118
- let stream;
119
- let contentType;
120
- let size;
121
- if (isBlob(fileInput)) {
122
- stream = Readable.fromWeb(fileInput.stream());
123
- contentType = fileInput.type;
124
- size = fileInput.size;
125
- }
126
- else if (isPathFileInput(fileInput)) {
127
- const stats = await stat(fileInput.path);
128
- stream = createReadStream(fileInput.path);
129
- contentType = fileInput.mimeType;
130
- size = stats.size;
131
- }
132
- else {
133
- stream = Readable.fromWeb(fileInput.stream);
134
- contentType = fileInput.mimeType;
135
- size = fileInput.size;
136
- }
137
- this.#logger.verbose(`Uploading file "${id}"${isDefined(size) ? ` (${formatBytes(size)})` : ''}...`);
138
- await file.save(stream, { contentType, resumable: false });
139
- return {
140
- id,
141
- name: id,
142
- uri: `gs://${bucket.name}/${file.name}`,
143
- mimeType: contentType,
144
- };
145
- }
146
- async uploadFileGenAi(fileInput, id) {
147
- let uploadData;
148
- let contentType;
149
- let size;
150
- if (isBlob(fileInput)) {
151
- uploadData = fileInput;
152
- contentType = fileInput.type;
153
- size = fileInput.size;
154
- }
155
- else if (isPathFileInput(fileInput)) {
156
- const fileState = await stat(fileInput.path);
157
- uploadData = fileInput.path;
158
- contentType = fileInput.mimeType;
159
- size = fileState.size;
160
- }
161
- else {
162
- const fileBytes = await readBinaryStream(fileInput.stream);
163
- const blob = new Blob([fileBytes], { type: fileInput.mimeType });
164
- uploadData = blob;
165
- contentType = blob.type;
166
- size = blob.size;
167
- }
168
- this.#logger.verbose(`Uploading file "${id}" (${formatBytes(size)})...`);
169
- // upload supports paths and blobs, but not streams (yet)
170
- const response = await this.#genAI.files.upload({ file: uploadData, config: { mimeType: contentType } });
171
- return {
172
- id,
173
- name: assertDefinedPass(response.name, 'Missing file name'),
174
- uri: assertDefinedPass(response.uri, 'Missing file uri'),
175
- mimeType: assertDefinedPass(response.mimeType, 'Missing file mime type'),
176
- };
177
- }
178
- async getBucket() {
179
- if (isUndefined(this.#options.vertex)) {
180
- throw new Error('Not using Vertex');
181
- }
182
- if (isDefined(this.#bucket)) {
183
- return this.#bucket;
184
- }
185
- const bucketName = assertDefinedPass(this.#options.vertex.bucket, 'Bucket not specified');
186
- const bucket = this.#storage.bucket(bucketName);
187
- const [exists] = await bucket.exists();
188
- if (!exists) {
189
- this.#logger.info(`Bucket "${bucketName}" not found, creating...`);
190
- const [createdBucket] = await this.#storage.createBucket(bucketName, {
191
- location: this.#options.vertex.location,
192
- lifecycle: {
193
- rule: [{
194
- action: { type: 'Delete' },
195
- condition: { age: 1 },
196
- }],
197
- },
198
- });
199
- this.#bucket = createdBucket;
200
- }
201
- else {
202
- this.#bucket = bucket;
203
- }
204
- return this.#bucket;
205
- }
206
- async waitForFileActive(file) {
207
- if (isDefined(this.#options.vertex)) {
208
- // For Vertex, uploads to GCS are instantly "active"
209
- return;
210
- }
211
- for await (const backoff of backoffGenerator(this.#backoffOptions)) {
212
- const state = await this.#genAI.files.get({ name: file.name });
213
- if (state.state == FileState.ACTIVE) {
214
- this.#logger.verbose(`File "${file.id}" is active.`);
215
- return;
216
- }
217
- if (state.state == FileState.FAILED) {
218
- throw new DetailsError(state.error?.message ?? `Failed to process file ${state.name}`, state.error?.details);
219
- }
220
- backoff();
221
- }
222
- }
223
- async waitForFilesActive(files) {
224
- // parallelizing does not help here, as each file upload is independently processed in the background
225
- for (const file of files) {
226
- await this.waitForFileActive(file);
227
- }
228
- }
229
- };
230
- AiFileService = __decorate([
231
- Singleton()
232
- ], AiFileService);
233
- export { AiFileService };
@@ -1,38 +0,0 @@
1
- import type { OneOrMany } from '../types/index.js';
2
- import type { AiService, CallFunctionsOptions, SpecializedGenerationResult } from './ai.service.js';
3
- import type { Content, GenerationRequest, GenerationResult, SchemaFunctionDeclarations, SchemaFunctionDeclarationsResult } from './types.js';
4
- /**
5
- * Represents a conversational session with an AI model.
6
- *
7
- * This class maintains the history of contents (messages) in a conversation,
8
- * allowing for stateful, multi-turn interactions with the AI.
9
- */
10
- export declare class AiSession {
11
- #private;
12
- /**
13
- * The history of contents in the session.
14
- */
15
- readonly contents: Content[];
16
- /**
17
- * Creates an instance of `AiSession`.
18
- * @param aiService The {@link AiService} instance to use for AI interactions.
19
- */
20
- constructor(aiService: AiService);
21
- /**
22
- * Adds new content to the session's history without triggering a generation.
23
- * @param content The content or contents to add.
24
- */
25
- addContent(content: OneOrMany<Content>): void;
26
- /**
27
- * Prompts the model to call one or more functions based on the provided context and session history.
28
- * The new user content and the resulting model response (function calls) are automatically added to the session history.
29
- * @param options The options for the function call request.
30
- */
31
- callFunctions<const T extends SchemaFunctionDeclarations>(options: CallFunctionsOptions<T>): Promise<SpecializedGenerationResult<SchemaFunctionDeclarationsResult<T>[]>>;
32
- /**
33
- * Generates content from the model based on the provided request and the current session history.
34
- * The new user content and the resulting model response are automatically added to the session history.
35
- * @param request The generation request.
36
- */
37
- generate(request: GenerationRequest): Promise<GenerationResult>;
38
- }
package/ai/ai-session.js DELETED
@@ -1,50 +0,0 @@
1
- import { toArray } from '../utils/array/array.js';
2
- /**
3
- * Represents a conversational session with an AI model.
4
- *
5
- * This class maintains the history of contents (messages) in a conversation,
6
- * allowing for stateful, multi-turn interactions with the AI.
7
- */
8
- export class AiSession {
9
- #aiService;
10
- /**
11
- * The history of contents in the session.
12
- */
13
- contents = [];
14
- /**
15
- * Creates an instance of `AiSession`.
16
- * @param aiService The {@link AiService} instance to use for AI interactions.
17
- */
18
- constructor(aiService) {
19
- this.#aiService = aiService;
20
- }
21
- /**
22
- * Adds new content to the session's history without triggering a generation.
23
- * @param content The content or contents to add.
24
- */
25
- addContent(content) {
26
- this.contents.push(...toArray(content));
27
- }
28
- /**
29
- * Prompts the model to call one or more functions based on the provided context and session history.
30
- * The new user content and the resulting model response (function calls) are automatically added to the session history.
31
- * @param options The options for the function call request.
32
- */
33
- async callFunctions(options) {
34
- this.contents.push(...toArray(options.contents));
35
- const result = await this.#aiService.callFunctions({ ...options, contents: this.contents });
36
- this.contents.push(result.raw.content);
37
- return result;
38
- }
39
- /**
40
- * Generates content from the model based on the provided request and the current session history.
41
- * The new user content and the resulting model response are automatically added to the session history.
42
- * @param request The generation request.
43
- */
44
- async generate(request) {
45
- this.contents.push(...toArray(request.contents));
46
- const result = await this.#aiService.generate({ ...request, contents: this.contents });
47
- this.contents.push(result.content);
48
- return result;
49
- }
50
- }
@@ -1,126 +0,0 @@
1
- import type { Resolvable, resolveArgumentType } from '../injector/interfaces.js';
2
- import { type SchemaTestable } from '../schema/index.js';
3
- import type { Enumeration as EnumerationType, EnumerationValue } from '../types/index.js';
4
- import { AiSession } from './ai-session.js';
5
- import { AiModuleOptions } from './module.js';
6
- import { type AiModel, type FileContentPart, type FileInput, type GenerationOptions, type GenerationRequest, type GenerationResult, type SchemaFunctionDeclarations, type SchemaFunctionDeclarationsResult } from './types.js';
7
- /**
8
- * A generation result that includes a specialized, typed result alongside the raw generation data.
9
- * @template T The type of the specialized result.
10
- */
11
- export type SpecializedGenerationResult<T> = {
12
- /** The specialized, typed result. */
13
- result: T;
14
- /** The raw, underlying generation result from the AI model. */
15
- raw: GenerationResult;
16
- };
17
- /**
18
- * An async generator for specialized generation results, which also provides access to the final raw generation data.
19
- * @template T The type of the specialized result yielded by the generator.
20
- */
21
- export type SpecializedGenerationResultGenerator<T> = AsyncGenerator<T> & {
22
- raw: Promise<GenerationResult>;
23
- };
24
- export type AiServiceArgument = AiModuleOptions;
25
- export type ClassificationResult<T extends EnumerationType> = {
26
- types: {
27
- type: EnumerationValue<T>;
28
- confidence: 'high' | 'medium' | 'low';
29
- }[] | null;
30
- };
31
- export type AnalyzeContentResult<T extends EnumerationType> = {
32
- content: string[];
33
- documentTypes: ClassificationResult<T>[];
34
- tags: string[];
35
- };
36
- /**
37
- * Options for a function-calling request.
38
- * @template T The schema declarations for the available functions.
39
- */
40
- export type CallFunctionsOptions<T extends SchemaFunctionDeclarations> = Pick<GenerationRequest, 'contents' | 'model' | 'systemInstruction' | 'functionCallingMode'> & GenerationOptions & {
41
- /** The function declarations available for the model to call. */
42
- functions: T;
43
- };
44
- /**
45
- * A service for interacting with Google's Generative AI models (Gemini).
46
- *
47
- * This service provides methods for content generation, function calling, and file processing,
48
- * supporting both standard Google AI and Vertex AI endpoints.
49
- */
50
- export declare class AiService implements Resolvable<AiServiceArgument> {
51
- #private;
52
- /**
53
- * The default AI model to use for requests if not specified otherwise.
54
- */
55
- readonly defaultModel: AiModel;
56
- readonly [resolveArgumentType]: AiServiceArgument;
57
- /**
58
- * Creates a new {@link AiSession} for managing conversational history.
59
- */
60
- createSession(): AiSession;
61
- /**
62
- * Processes a single file for use in AI requests by uploading it and making it available to the model.
63
- * @param fileInput The file to process.
64
- * @returns A promise that resolves to a {@link FileContentPart} which can be included in a generation request.
65
- */
66
- processFile(fileInput: FileInput): Promise<FileContentPart>;
67
- /**
68
- * Processes multiple files in parallel for use in AI requests.
69
- * @param fileInputs The files to process.
70
- * @returns A promise that resolves to an array of {@link FileContentPart}s which can be included in generation requests.
71
- */
72
- processFiles(fileInputs: FileInput[]): Promise<FileContentPart[]>;
73
- /**
74
- * Creates a file content part from a previously processed file ID.
75
- * This does not re-upload the file.
76
- * @param id The ID of the file, obtained from {@link AiFileService.processFile} or {@link AiFileService.processFiles}.
77
- * @returns A {@link FileContentPart} for use in a generation request.
78
- */
79
- getFileById(id: string): FileContentPart;
80
- /**
81
- * A high-level method to prompt the model to call one or more functions.
82
- * This method sends the request and parses the model's response to identify function calls.
83
- * If the function declaration includes a handler, it will be executed automatically.
84
- * @param options The options for the function call request.
85
- * @returns A promise that resolves to a {@link SpecializedGenerationResult} containing the function call results.
86
- */
87
- callFunctions<const T extends SchemaFunctionDeclarations>(options: CallFunctionsOptions<T>): Promise<SpecializedGenerationResult<SchemaFunctionDeclarationsResult<T>[]>>;
88
- /**
89
- * A streaming version of `callFunctions`.
90
- * Yields function call results as they are received from the model.
91
- * If function declarations include handlers, they are executed as soon as a complete function call is parsed.
92
- * @param options The options for the function call request.
93
- * @returns A {@link SpecializedGenerationResultGenerator} that yields function call results.
94
- */
95
- callFunctionsStream<const T extends SchemaFunctionDeclarations>(options: CallFunctionsOptions<T>): SpecializedGenerationResultGenerator<SchemaFunctionDeclarationsResult<T>>;
96
- /**
97
- * Generates content from the model based on a request.
98
- * This method waits for the full response from the model. For streaming, use {@link generateStream}.
99
- * @param request The generation request.
100
- * @returns A promise that resolves to the complete {@link GenerationResult}.
101
- */
102
- generate<S>(request: GenerationRequest<S>): Promise<GenerationResult<S>>;
103
- /**
104
- * Generates content as a stream.
105
- * Yields partial generation results as they are received from the model.
106
- * @param request The generation request.
107
- * @returns An `AsyncGenerator` that yields {@link GenerationResult} chunks.
108
- */
109
- generateStream<S>(request: GenerationRequest<S>): AsyncGenerator<GenerationResult<S>>;
110
- private _callFunctionsStream;
111
- private getModelOutputTokenLimit;
112
- private _getModelOutputTokenLimit;
113
- private convertContents;
114
- private convertContent;
115
- private convertFunctions;
116
- private convertGoogleContent;
117
- private mapModel;
118
- }
119
- /**
120
- * Merges an array of streaming generation results into a single, consolidated result.
121
- * This is useful for combining the chunks from a streaming response into a final object.
122
- * @param items The array of {@link GenerationResult} items from a stream.
123
- * @param schema An optional schema to parse the merged JSON output.
124
- * @returns A single, merged {@link GenerationResult}.
125
- */
126
- export declare function mergeGenerationStreamItems<S>(items: GenerationResult<S>[], schema?: SchemaTestable<S>): GenerationResult<S>;