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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
import {
    GetResponse,
    QueryResponse,
    AddResponse,
    CollectionMetadata,
    ConfigOptions,
    GetParams,
    AddParams,
    UpsertParams,
    ModifyCollectionParams,
    UpdateParams,
    QueryParams,
    PeekParams,
    DeleteParams
} from "./types";
import { IEmbeddingFunction } from './embeddings/IEmbeddingFunction';
import { ApiApi as DefaultApi } from "./generated";
import { handleError, handleSuccess } from "./utils";
import { toArray, toArrayOfArrays } from "./utils";


export class Collection {
    public name: string;
    public id: string;
    public metadata: CollectionMetadata | undefined;
    /**
     * @ignore
     */
    private api: DefaultApi & ConfigOptions;
    /**
     * @ignore
     */
    public embeddingFunction: IEmbeddingFunction | undefined;

    /**
     * @ignore
     */
    constructor(
        name: string,
        id: string,
        api: DefaultApi,
        metadata?: CollectionMetadata,
        embeddingFunction?: IEmbeddingFunction
    ) {
        this.name = name;
        this.id = id;
        this.metadata = metadata;
        this.api = api;
        if (embeddingFunction !== undefined)
            this.embeddingFunction = embeddingFunction;
    }

    /**
     * @ignore
     */
    private setName(name: string): void {
        this.name = name;
    }
    /**
     * @ignore
     */
    private setMetadata(metadata: CollectionMetadata | undefined): void {
        this.metadata = metadata;
    }

    /**
     * @ignore
     */
    private async validate(
        require_embeddings_or_documents: boolean, // set to false in the case of Update
        ids: string | string[],
        embeddings: number[] | number[][] | undefined,
        metadatas?: object | object[],
        documents?: string | string[],
    ) {

        if (require_embeddings_or_documents) {
            if ((embeddings === undefined) && (documents === undefined)) {
                throw new Error(
                    "embeddings and documents cannot both be undefined",
                );
            }
        }

        if ((embeddings === undefined) && (documents !== undefined)) {
            const documentsArray = toArray(documents);
            if (this.embeddingFunction !== undefined) {
                embeddings = await this.embeddingFunction.generate(documentsArray);
            } else {
                throw new Error(
                    "embeddingFunction is undefined. Please configure an embedding function"
                );
            }
        }
        if (embeddings === undefined)
            throw new Error("embeddings is undefined but shouldnt be");

        const idsArray = toArray(ids);
        const embeddingsArray: number[][] = toArrayOfArrays(embeddings);

        let metadatasArray: object[] | undefined;
        if (metadatas === undefined) {
            metadatasArray = undefined;
        } else {
            metadatasArray = toArray(metadatas);
        }

        let documentsArray: (string | undefined)[] | undefined;
        if (documents === undefined) {
            documentsArray = undefined;
        } else {
            documentsArray = toArray(documents);
        }

        // validate all ids are strings
        for (let i = 0; i < idsArray.length; i += 1) {
            if (typeof idsArray[i] !== "string") {
                throw new Error(
                    `Expected ids to be strings, found ${typeof idsArray[i]} at index ${i}`
                );
            }
        }

        if (
            (embeddingsArray !== undefined &&
                idsArray.length !== embeddingsArray.length) ||
            (metadatasArray !== undefined &&
                idsArray.length !== metadatasArray.length) ||
            (documentsArray !== undefined &&
                idsArray.length !== documentsArray.length)
        ) {
            throw new Error(
                "ids, embeddings, metadatas, and documents must all be the same length"
            );
        }

        const uniqueIds = new Set(idsArray);
        if (uniqueIds.size !== idsArray.length) {
            const duplicateIds = idsArray.filter((item, index) => idsArray.indexOf(item) !== index);
            throw new Error(
                `Expected IDs to be unique, found duplicates for: ${duplicateIds}`,
            );
        }

        return [idsArray, embeddingsArray, metadatasArray, documentsArray]
    }

    /**
     * Add items to the collection
     * @param {Object} params - The parameters for the query.
     * @param {ID | IDs} [params.ids] - IDs of the items to add.
     * @param {Embedding | Embeddings} [params.embeddings] - Optional embeddings of the items to add.
     * @param {Metadata | Metadatas} [params.metadatas] - Optional metadata of the items to add.
     * @param {Document | Documents} [params.documents] - Optional documents of the items to add.
    * @returns {Promise<AddResponse>} - The response from the API. True if successful.
     *
     * @example
     * ```typescript
     * const response = await collection.add({
     *   ids: ["id1", "id2"],
     *   embeddings: [[1, 2, 3], [4, 5, 6]],
     *   metadatas: [{ "key": "value" }, { "key": "value" }],
     *   documents: ["document1", "document2"]
     * });
     * ```
     */
    public async add({
        ids,
        embeddings,
        metadatas,
        documents,
    }: AddParams): Promise<AddResponse> {

        const [idsArray, embeddingsArray, metadatasArray, documentsArray] = await this.validate(
            true,
            ids,
            embeddings,
            metadatas,
            documents
        )

        const response = await this.api.add(this.id,
            {
                // @ts-ignore
                ids: idsArray,
                embeddings: embeddingsArray as number[][], // We know this is defined because of the validate function
                // @ts-ignore
                documents: documentsArray,
                // @ts-ignore
                metadatas: metadatasArray,
            }, this.api.options)
            .then(handleSuccess)
            .catch(handleError);

        return response
    }

    /**
     * Upsert items to the collection
     * @param {Object} params - The parameters for the query.
     * @param {ID | IDs} [params.ids] - IDs of the items to add.
     * @param {Embedding | Embeddings} [params.embeddings] - Optional embeddings of the items to add.
     * @param {Metadata | Metadatas} [params.metadatas] - Optional metadata of the items to add.
     * @param {Document | Documents} [params.documents] - Optional documents of the items to add.
     * @returns {Promise<boolean>} - The response from the API. True if successful.
     *
     * @example
     * ```typescript
     * const response = await collection.upsert({
     *   ids: ["id1", "id2"],
     *   embeddings: [[1, 2, 3], [4, 5, 6]],
     *   metadatas: [{ "key": "value" }, { "key": "value" }],
     *   documents: ["document1", "document2"],
     * });
     * ```
     */
    public async upsert({
        ids,
        embeddings,
        metadatas,
        documents,
    }: UpsertParams): Promise<boolean> {
        const [idsArray, embeddingsArray, metadatasArray, documentsArray] = await this.validate(
            true,
            ids,
            embeddings,
            metadatas,
            documents
        )

        const response = await this.api.upsert(this.id,
            {
                //@ts-ignore
                ids: idsArray,
                embeddings: embeddingsArray as number[][], // We know this is defined because of the validate function
                //@ts-ignore
                documents: documentsArray,
                //@ts-ignore
                metadatas: metadatasArray,
            },
            this.api.options
        )
            .then(handleSuccess)
            .catch(handleError);

        return response

    }

    /**
     * Count the number of items in the collection
     * @returns {Promise<number>} - The response from the API.
     *
     * @example
     * ```typescript
     * const response = await collection.count();
     * ```
     */
    public async count(): Promise<number> {
        const response = await this.api.count(this.id, this.api.options);
        return handleSuccess(response);
    }

    /**
     * Modify the collection name or metadata
     * @param {Object} params - The parameters for the query.
     * @param {string} [params.name] - Optional new name for the collection.
     * @param {CollectionMetadata} [params.metadata] - Optional new metadata for the collection.
     * @returns {Promise<void>} - The response from the API.
     *
     * @example
     * ```typescript
     * const response = await collection.modify({
     *   name: "new name",
     *   metadata: { "key": "value" },
     * });
     * ```
     */
    public async modify({
        name,
        metadata
    }: ModifyCollectionParams = {}): Promise<void> {
        const response = await this.api
            .updateCollection(
                this.id,
                {
                    new_name: name,
                    new_metadata: metadata,
                },
                this.api.options
            )
            .then(handleSuccess)
            .catch(handleError);

        this.setName(name || this.name);
        this.setMetadata(metadata || this.metadata);

        return response;
    }

    /**
     * Get items from the collection
     * @param {Object} params - The parameters for the query.
     * @param {ID | IDs} [params.ids] - Optional IDs of the items to get.
     * @param {Where} [params.where] - Optional where clause to filter items by.
     * @param {PositiveInteger} [params.limit] - Optional limit on the number of items to get.
     * @param {PositiveInteger} [params.offset] - Optional offset on the items to get.
     * @param {IncludeEnum[]} [params.include] - Optional list of items to include in the response.
     * @param {WhereDocument} [params.whereDocument] - Optional where clause to filter items by.
     * @returns {Promise<GetResponse>} - The response from the server.
     *
     * @example
     * ```typescript
     * const response = await collection.get({
     *   ids: ["id1", "id2"],
     *   where: { "key": "value" },
     *   limit: 10,
     *   offset: 0,
     *   include: ["embeddings", "metadatas", "documents"],
     *   whereDocument: { $contains: "value" },
     * });
     * ```
     */
    public async get({
        ids,
        where,
        limit,
        offset,
        include,
        whereDocument,
    }: GetParams = {}): Promise<GetResponse> {
        let idsArray = undefined;
        if (ids !== undefined) idsArray = toArray(ids);

        return await this.api
            .aGet(this.id, {
                ids: idsArray,
                where,
                limit,
                offset,
                //@ts-ignore
                include,
                where_document: whereDocument,
            }, this.api.options)
            .then(handleSuccess)
            .catch(handleError);
    }

    /**
     * Update the embeddings, documents, and/or metadatas of existing items
     * @param {Object} params - The parameters for the query.
     * @param {ID | IDs} [params.ids] - The IDs of the items to update.
     * @param {Embedding | Embeddings} [params.embeddings] - Optional embeddings to update.
     * @param {Metadata | Metadatas} [params.metadatas] - Optional metadatas to update.
     * @param {Document | Documents} [params.documents] - Optional documents to update.
     * @returns {Promise<boolean>} - The API Response. True if successful. Else, error.
     *
     * @example
     * ```typescript
     * const response = await collection.update({
     *   ids: ["id1", "id2"],
     *   embeddings: [[1, 2, 3], [4, 5, 6]],
     *   metadatas: [{ "key": "value" }, { "key": "value" }],
     *   documents: ["new document 1", "new document 2"],
     * });
     * ```
     */
    public async update({
        ids,
        embeddings,
        metadatas,
        documents,
    }: UpdateParams): Promise<boolean> {
        if (
            embeddings === undefined &&
            documents === undefined &&
            metadatas === undefined
        ) {
            throw new Error(
                "embeddings, documents, and metadatas cannot all be undefined"
            );
        } else if (embeddings === undefined && documents !== undefined) {
            const documentsArray = toArray(documents);
            if (this.embeddingFunction !== undefined) {
                embeddings = await this.embeddingFunction.generate(documentsArray);
            } else {
                throw new Error(
                    "embeddingFunction is undefined. Please configure an embedding function"
                );
            }
        }

        // backend expects None if metadatas is undefined
        if (metadatas !== undefined) metadatas = toArray(metadatas);
        if (documents !== undefined) documents = toArray(documents);

        var resp = await this.api
            .update(
                this.id,
                {
                    ids: toArray(ids),
                    embeddings: embeddings ? toArrayOfArrays(embeddings) : undefined,
                    documents: documents,
                    metadatas: metadatas
                },
                this.api.options
            )
            .then(handleSuccess)
            .catch(handleError);

        return resp;
    }

    /**
     * Performs a query on the collection using the specified parameters.
     *
     * @param {Object} params - The parameters for the query.
     * @param {Embedding | Embeddings} [params.queryEmbeddings] - Optional query embeddings to use for the search.
     * @param {PositiveInteger} [params.nResults] - Optional number of results to return (default is 10).
     * @param {Where} [params.where] - Optional query condition to filter results based on metadata values.
     * @param {string | string[]} [params.queryTexts] - Optional query text(s) to search for in the collection.
     * @param {WhereDocument} [params.whereDocument] - Optional query condition to filter results based on document content.
     * @param {IncludeEnum[]} [params.include] - Optional array of fields to include in the result, such as "metadata" and "document".
     *
     * @returns {Promise<QueryResponse>} A promise that resolves to the query results.
     * @throws {Error} If there is an issue executing the query.
     * @example
     * // Query the collection using embeddings
     * const results = await collection.query({
     *   queryEmbeddings: [[0.1, 0.2, ...], ...],
     *   nResults: 10,
     *   where: {"name": {"$eq": "John Doe"}},
     *   include: ["metadata", "document"]
     * });
     * @example
     * ```js
     * // Query the collection using query text
     * const results = await collection.query({
     *   queryTexts: "some text",
     *   nResults: 10,
     *   where: {"name": {"$eq": "John Doe"}},
     *   include: ["metadata", "document"]
     * });
     * ```
     *
     */
    public async query({
        queryEmbeddings,
        nResults,
        where,
        queryTexts,
        whereDocument,
        include,
    }: QueryParams): Promise<QueryResponse> {
        if (nResults === undefined) nResults = 10
        if (queryEmbeddings === undefined && queryTexts === undefined) {
            throw new Error(
                "queryEmbeddings and queryTexts cannot both be undefined"
            );
        } else if (queryEmbeddings === undefined && queryTexts !== undefined) {
            const queryTextsArray = toArray(queryTexts);
            if (this.embeddingFunction !== undefined) {
                queryEmbeddings = await this.embeddingFunction.generate(queryTextsArray);
            } else {
                throw new Error(
                    "embeddingFunction is undefined. Please configure an embedding function"
                );
            }
        }
        if (queryEmbeddings === undefined)
            throw new Error("embeddings is undefined but shouldnt be");

        const query_embeddingsArray = toArrayOfArrays(queryEmbeddings);

        return await this.api
            .getNearestNeighbors(this.id, {
                query_embeddings: query_embeddingsArray,
                where,
                n_results: nResults,
                where_document: whereDocument,
                //@ts-ignore
                include: include,
            }, this.api.options)
            .then(handleSuccess)
            .catch(handleError);
    }

    /**
     * Peek inside the collection
     * @param {Object} params - The parameters for the query.
     * @param {PositiveInteger} [params.limit] - Optional number of results to return (default is 10).
     * @returns {Promise<GetResponse>} A promise that resolves to the query results.
     * @throws {Error} If there is an issue executing the query.
     *
     * @example
     * ```typescript
     * const results = await collection.peek({
     *   limit: 10
     * });
     * ```
     */
    public async peek({ limit }: PeekParams = {}): Promise<GetResponse> {
        if (limit === undefined) limit = 10;
        const response = await this.api.aGet(this.id, {
            limit: limit,
        }, this.api.options);
        return handleSuccess(response);
    }

    /**
     * Deletes items from the collection.
     * @param {Object} params - The parameters for deleting items from the collection.
     * @param {ID | IDs} [params.ids] - Optional ID or array of IDs of items to delete.
     * @param {Where} [params.where] - Optional query condition to filter items to delete based on metadata values.
     * @param {WhereDocument} [params.whereDocument] - Optional query condition to filter items to delete based on document content.
     * @returns {Promise<string[]>} A promise that resolves to the IDs of the deleted items.
     * @throws {Error} If there is an issue deleting items from the collection.
     *
     * @example
     * ```typescript
     * const results = await collection.delete({
     *   ids: "some_id",
     *   where: {"name": {"$eq": "John Doe"}},
     *   whereDocument: {"$contains":"search_string"}
     * });
     * ```
     */
    public async delete({
        ids,
        where,
        whereDocument
    }: DeleteParams = {}): Promise<string[]> {
        let idsArray = undefined;
        if (ids !== undefined) idsArray = toArray(ids);
        return await this.api
            .aDelete(this.id, { ids: idsArray, where: where, where_document: whereDocument }, this.api.options)
            .then(handleSuccess)
            .catch(handleError);
    }
}