Skip to content

extension ¤

Extension classes of Nendo Core.

DistanceMetric ¤

Bases: str, Enum

Enum representing different types of resources used in Nendo.

NendoLibraryVectorExtension ¤

NendoLibraryVectorExtension(
    embedding_plugin: Optional[str] = None,
    default_distance: DistanceMetric = DistanceMetric.cosine,
    **kwargs
)

Bases: BaseModel

Extension class to implement library plugins with vector support.

Source code in src/nendo/library/extension.py
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
def __init__(  # noqa: D107
    self,
    embedding_plugin: Optional[str] = None,
    default_distance: DistanceMetric = DistanceMetric.cosine,
    **kwargs,
):
    super().__init__(**kwargs)
    if embedding_plugin is not None:
        try:
            self.embedding_plugin = getattr(
                self.nendo_instance.plugins,
                embedding_plugin,
            )
        except AttributeError:
            self.logger.warning(
                f"Plugin with name {embedding_plugin} has been configured "
                "for the NendoLibraryVectorExtension but is not loaded. "
                "Please make sure to install and enable the plugin "
                "to use the embedding features of the nendo library.",
            )
    else:
        # try to auto-detect an embedding plugin from the registry
        self.embedding_plugin = self._get_embedding_plugin()
        if self.embedding_plugin is None:
            self.logger.warning(
                "No embedding plugin was configured for the "
                "NendoLibraryVectorExtension and none was found in the "
                "PluginRegistry. Please make sure to install and enable one "
                "to use the embedding features of the nendo library.",
            )
    self._default_distance = default_distance

distance_metric abstractmethod property ¤

distance_metric

Return a function that computes the default distance metric..

add_embedding abstractmethod ¤

add_embedding(
    embedding: NendoEmbeddingBase,
) -> NendoEmbedding

Add a new embedding to the library.

Parameters:

Name Type Description Default
embedding NendoEmbeddingBase

The embedding to add.

required

Returns:

Type Description
NendoEmbedding

The added embedding.

Source code in src/nendo/library/extension.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
@abstractmethod
def add_embedding(
    self,
    embedding: NendoEmbeddingBase,
) -> NendoEmbedding:
    """Add a new embedding to the library.

    Args:
        embedding (NendoEmbeddingBase): The embedding to add.

    Returns:
        NendoEmbedding: The added embedding.
    """
    raise NotImplementedError

cosine_distance ¤

cosine_distance(vec1: ArrayLike, vec2: ArrayLike) -> float

Compute the cosine distance between the two given vectors.

Parameters:

Name Type Description Default
vec1 ArrayLike

The first vector.

required
vec2 ArrayLike

The second vector.

required

Raises:

Type Description
ValueError

If one of the vectors has zero norm, the cosine similarity is not defined and thus a ValueError is raised.

Returns:

Type Description
float

The cosine distance between the two vectors.

Source code in src/nendo/library/extension.py
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
def cosine_distance(
    self,
    vec1: npt.ArrayLike,
    vec2: npt.ArrayLike,
) -> float:
    """Compute the cosine distance between the two given vectors.

    Args:
        vec1 (npt.ArrayLike): The first vector.
        vec2 (npt.ArrayLike): The second vector.

    Raises:
        ValueError: If one of the vectors has zero norm, the cosine
            similarity is not defined and thus a `ValueError` is raised.

    Returns:
        float: The cosine distance between the two vectors.
    """
    dot_product = np.dot(vec1, vec2)
    norm_arr1 = np.linalg.norm(vec1)
    norm_arr2 = np.linalg.norm(vec2)
    norm_mult = norm_arr1 * norm_arr2
    if norm_mult == 0.0:
        raise ValueError("Division by zero in cosine similarity.")
    return dot_product / norm_mult

embed_collection ¤

embed_collection(
    collection: NendoCollection,
) -> List[NendoEmbedding]

Embed the given collection using the library's default embedding plugin.

Parameters:

Name Type Description Default
collection NendoCollection

The collection to be embedded.

required

Raises:

Type Description
NendoLibraryError

If not embedding plugin has been loaded.

Returns:

Type Description
List[NendoEmbedding]

A list of embeddings corresponding to the collection's tracks.

Source code in src/nendo/library/extension.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def embed_collection(self, collection: NendoCollection) -> List[NendoEmbedding]:
    """Embed the given collection using the library's default embedding plugin.

    Args:
        collection (NendoCollection): The collection to be embedded.

    Raises:
        NendoLibraryError: If not embedding plugin has been loaded.

    Returns:
        List[NendoEmbedding]: A list of embeddings corresponding to the
            collection's tracks.
    """
    if self.embedding_plugin is not None:
        return self.embedding_plugin(collection=collection)
    raise NendoLibraryError("No embedding plugin loaded. Cannot embed Collection.")

embed_text ¤

embed_text(text: str) -> ArrayLike

Embed the given text using the library's default embedding plugin.

Parameters:

Name Type Description Default
text str

The text to be embedded.

required

Raises:

Type Description
NendoLibraryError

If not embedding plugin has been loaded.

Returns:

Type Description
ArrayLike

The embedding vector corresponding to the text.

Source code in src/nendo/library/extension.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def embed_text(self, text: str) -> npt.ArrayLike:
    """Embed the given text using the library's default embedding plugin.

    Args:
        text (str): The text to be embedded.

    Raises:
        NendoLibraryError: If not embedding plugin has been loaded.

    Returns:
        npt.ArrayLike: The embedding vector corresponding to the text.
    """
    if self.embedding_plugin is not None:
        _, emb = self.embedding_plugin(text=text)
        return emb
    raise NendoLibraryError("No embedding plugin loaded. Cannot embed track.")

embed_track ¤

embed_track(track: NendoTrack) -> NendoEmbedding

Embed the given track using the library's default embedding plugin.

Parameters:

Name Type Description Default
track NendoTrack

The track to be embedded.

required

Raises:

Type Description
NendoLibraryError

If not embedding plugin has been loaded.

Returns:

Type Description
NendoEmbedding

The object representing the track embedding.

Source code in src/nendo/library/extension.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def embed_track(self, track: NendoTrack) -> NendoEmbedding:
    """Embed the given track using the library's default embedding plugin.

    Args:
        track (NendoTrack): The track to be embedded.

    Raises:
        NendoLibraryError: If not embedding plugin has been loaded.

    Returns:
        NendoEmbedding: The object representing the track embedding.
    """
    if self.embedding_plugin is not None:
        return self.embedding_plugin(track=track)
    raise NendoLibraryError("No embedding plugin loaded. Cannot embed track.")

embedding_distance ¤

embedding_distance(
    embedding1: NendoEmbedding,
    embedding2: NendoEmbedding,
    distance_metric: Optional[DistanceMetric] = None,
) -> float

Compute the distance between two NendoEmbedding objects.

If no distance metric is specified, the default distance metric configured upon extension initialization is used.

Parameters:

Name Type Description Default
embedding1 NendoEmbedding

The first embedding.

required
embedding2 NendoEmbedding

The second embedding.

required

Raises:

Type Description
ValueError

If the chosen distance metric is unknown.

Returns:

Type Description
float

The distance between the two embedding vectors.

Source code in src/nendo/library/extension.py
 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
def embedding_distance(
    self,
    embedding1: NendoEmbedding,
    embedding2: NendoEmbedding,
    distance_metric: Optional[DistanceMetric] = None,
) -> float:
    """Compute the distance between two `NendoEmbedding` objects.

    If no distance metric is specified, the default distance metric
    configured upon extension initialization is used.

    Args:
        embedding1 (NendoEmbedding): The first embedding.
        embedding2 (NendoEmbedding): The second embedding.

    Raises:
        ValueError: If the chosen distance metric is unknown.

    Returns:
        float: The distance between the two embedding vectors.
    """
    metric = distance_metric or self._default_distance
    if metric == DistanceMetric.euclidean:
        return self.euclidean_distance(
            vec1=embedding1.embedding,
            vec2=embedding2.embedding,
        )
    if metric == DistanceMetric.cosine:
        return self.cosine_distance(
            vec1=embedding1.embedding,
            vec2=embedding2.embedding,
        )
    if metric == DistanceMetric.max_inner_product:
        return self.max_inner_product_distance(
            vec1=embedding1.embedding,
            vec2=embedding2.embedding,
        )
    raise ValueError(
        f"Got unexpected value for distance: {metric}. "
        f"Should be one of {', '.join([ds.value for ds in DistanceMetric])}.",
    )

euclidean_distance ¤

euclidean_distance(
    vec1: ArrayLike, vec2: ArrayLike
) -> float

Compute the euclidean (L2) distance between the two given vectors.

Parameters:

Name Type Description Default
vec1 ArrayLike

The first vector.

required
vec2 ArrayLike

The second vector.

required

Returns:

Type Description
float

The euclidean distance between the two vectors.

Source code in src/nendo/library/extension.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def euclidean_distance(
    self,
    vec1: npt.ArrayLike,
    vec2: npt.ArrayLike,
) -> float:
    """Compute the euclidean (L2) distance between the two given vectors.

    Args:
        vec1 (npt.ArrayLike): The first vector.
        vec2 (npt.ArrayLike): The second vector.

    Returns:
        float: The euclidean distance between the two vectors.
    """
    distance = np.linalg.norm(vec1 - vec2)
    return 1 / (1 + distance)

get_embedding abstractmethod ¤

get_embedding(
    embedding_id: UUID,
) -> Optional[NendoEmbedding]

Retrieve a specific embedding from the library.

Parameters:

Name Type Description Default
embedding_id UUID

ID of the embedding to retrieve.

required

Returns:

Type Description
Optional[NendoEmbedding]

The embedding if the ID was found. None otherwise.

Source code in src/nendo/library/extension.py
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
@abstractmethod
def get_embedding(
    self,
    embedding_id: uuid.UUID,
) -> Optional[NendoEmbedding]:
    """Retrieve a specific embedding from the library.

    Args:
        embedding_id (uuid.UUID): ID of the embedding to retrieve.

    Returns:
        Optional[NendoEmbedding]: The embedding if the ID was found.
            None otherwise.
    """
    raise NotImplementedError

get_embeddings abstractmethod ¤

get_embeddings(
    track_id: Optional[UUID] = None,
    plugin_name: Optional[str] = None,
    plugin_version: Optional[str] = None,
) -> List[NendoEmbedding]

Get a list of embeddings by filtering for track ID and plugin specifics.

Parameters:

Name Type Description Default
track_id Optional[UUID]

The track ID to which the embeddings should be related. Defaults to None.

None
plugin_name Optional[str]

The name of the plugin used to create the embeddings. Defaults to None.

None
plugin_version Optional[str]

The version of the plugin used to create the embeddings. Defaults to None.

None

Returns:

Type Description
List[NendoEmbedding]

List of embeddings that fulfill the defined filter criteria.

Source code in src/nendo/library/extension.py
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@abstractmethod
def get_embeddings(
    self,
    track_id: Optional[uuid.UUID] = None,
    plugin_name: Optional[str] = None,
    plugin_version: Optional[str] = None,
) -> List[NendoEmbedding]:
    """Get a list of embeddings by filtering for track ID and plugin specifics.

    Args:
        track_id (Optional[uuid.UUID], optional): The track ID to which the
            embeddings should be related. Defaults to None.
        plugin_name (Optional[str], optional): The name of the plugin used to
            create the embeddings. Defaults to None.
        plugin_version (Optional[str], optional): The version of the plugin used
            to create the embeddings. Defaults to None.

    Returns:
        List[NendoEmbedding]: List of embeddings that fulfill the defined filter
            criteria.
    """
    raise NotImplementedError

max_inner_product_distance ¤

max_inner_product_distance(
    vec1: ArrayLike, vec2: ArrayLike
) -> float

Compute the maximum inner product distance between the two given vectors.

Parameters:

Name Type Description Default
vec1 ArrayLike

The first vector.

required
vec2 ArrayLike

The second vector.

required

Returns:

Type Description
float

The maximum inner product distance between the two vectors.

Source code in src/nendo/library/extension.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def max_inner_product_distance(
    self,
    vec1: npt.ArrayLike,
    vec2: npt.ArrayLike,
) -> float:
    """Compute the maximum inner product distance between the two given vectors.

    Args:
        vec1 (npt.ArrayLike): The first vector.
        vec2 (npt.ArrayLike): The second vector.

    Returns:
        float: The maximum inner product distance between the two vectors.
    """
    return np.max(np.inner(vec1, vec2))

nearest_by_query ¤

nearest_by_query(
    query: str,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[List[str]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, UUID]] = None,
    collection_id: Optional[Union[str, UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[NendoTrack]

Obtain the n nearest neighboring tracks to a query string.

Parameters:

Name Type Description Default
query str

The query from which to start the neighbor search.

required
limit int

Limit the number of returned results. Default is 10.

10
offset Optional[int]

Offset into the paginated results (requires limit).

None
filters Optional[dict]

Dictionary containing the filters to apply. Defaults to None.

None
search_meta dict

Dictionary containing the keywords to search for over the track.resource.meta field. The dictionary's values should contain singular search tokens and the keys currently have no effect but might in the future. Defaults to {}.

None
track_type Union[str, List[str]]

Track type to filter for. Can be a singular type or a list of types. Defaults to None.

None
user_id Union[str, UUID]

The user ID to filter for.

None
collection_id Union[str, UUID]

Collection id to which the filtered tracks must have a relationship. Defaults to None.

None
plugin_names list

List used for applying the filter only to data of certain plugins. If None, all plugin data related to the track is used for filtering.

None
embedding_name str

Name of the embedding plugin for which to retrieve and compare the vectors. If none is given, the name of the currently configured embedding plugin for the library vector extension is used.

None
embedding_version str

Version of the embedding plugin for which to retrieve and compare the vectors. If none is given, the version of the currently configured embedding plugin for the library vector extension is used.

None
distance_metric Optional[DistanceMetric]

The distance metric to use. Defaults to None.

None

Returns:

Type Description
List[NendoTrack]

The list of tracks corresponding to the n nearest embedding vectors of the given query string.

Source code in src/nendo/library/extension.py
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
542
def nearest_by_query(
    self,
    query: str,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[List[str]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    collection_id: Optional[Union[str, uuid.UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[NendoTrack]:
    """Obtain the n nearest neighboring tracks to a query string.

    Args:
        query (str): The query from which to start the neighbor search.
        limit (int): Limit the number of returned results. Default is 10.
        offset (Optional[int]): Offset into the paginated results (requires limit).
        filters (Optional[dict]): Dictionary containing the filters to apply.
            Defaults to None.
        search_meta (dict): Dictionary containing the keywords to search for
            over the track.resource.meta field. The dictionary's values
            should contain singular search tokens and the keys currently have no
            effect but might in the future. Defaults to {}.
        track_type (Union[str, List[str]], optional): Track type to filter for.
            Can be a singular type or a list of types. Defaults to None.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        collection_id (Union[str, uuid.UUID], optional): Collection id to
            which the filtered tracks must have a relationship. Defaults to None.
        plugin_names (list, optional): List used for applying the filter only to
            data of certain plugins. If None, all plugin data related to the track
            is used for filtering.
        embedding_name (str, optional): Name of the embedding plugin for which to
            retrieve and compare the vectors. If none is given, the name of the
            currently configured embedding plugin for the library vector extension
            is used.
        embedding_version (str, optional): Version of the embedding plugin for
            which to retrieve and compare the vectors. If none is given, the
            version of the currently configured embedding plugin for the library
            vector extension is used.
        distance_metric (Optional[DistanceMetric], optional): The distance metric
            to use. Defaults to None.

    Returns:
        List[NendoTrack]: The list of tracks corresponding to the n nearest
            embedding vectors of the given query string.
    """
    tracks_and_scores = self.nearest_by_query_with_score(
        query=query,
        limit=limit,
        offset=offset,
        filters=filters,
        search_meta=search_meta,
        track_type=track_type,
        user_id=user_id,
        collection_id=collection_id,
        plugin_names=plugin_names,
        embedding_name=embedding_name,
        embedding_version=embedding_version,
        distance_metric=distance_metric,
    )
    return [track for track, _ in tracks_and_scores]

nearest_by_query_with_score ¤

nearest_by_query_with_score(
    query: str,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[List[str]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, UUID]] = None,
    collection_id: Optional[Union[str, UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[Tuple[NendoTrack, float]]

Obtain the n nearest neighboring tracks to a query, together with scores.

Parameters:

Name Type Description Default
query str

The query from which to start the neighbor search.

required
limit int

Limit the number of returned results. Default is 10.

10
offset Optional[int]

Offset into the paginated results (requires limit).

None
filters Optional[dict]

Dictionary containing the filters to apply. Defaults to None.

None
search_meta dict

Dictionary containing the keywords to search for over the track.resource.meta field. The dictionary's values should contain singular search tokens and the keys currently have no effect but might in the future. Defaults to {}.

None
track_type Union[str, List[str]]

Track type to filter for. Can be a singular type or a list of types. Defaults to None.

None
user_id Union[str, UUID]

The user ID to filter for.

None
collection_id Union[str, UUID]

Collection id to which the filtered tracks must have a relationship. Defaults to None.

None
plugin_names list

List used for applying the filter only to data of certain plugins. If None, all plugin data related to the track is used for filtering.

None
embedding_name str

Name of the embedding plugin for which to retrieve and compare the vectors. If none is given, the name of the currently configured embedding plugin for the library vector extension is used.

None
embedding_version str

Version of the embedding plugin for which to retrieve and compare the vectors. If none is given, the version of the currently configured embedding plugin for the library vector extension is used.

None
distance_metric Optional[DistanceMetric]

The distance metric to use. Defaults to None.

None

Returns:

Type Description
List[Tuple[NendoTrack, float]]

List of tuples containing a track in the first position and their distance ("score") in the second position, ordered by their distance in ascending order.

Source code in src/nendo/library/extension.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
def nearest_by_query_with_score(
    self,
    query: str,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[List[str]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    collection_id: Optional[Union[str, uuid.UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[Tuple[NendoTrack, float]]:
    """Obtain the n nearest neighboring tracks to a query, together with scores.

    Args:
        query (str): The query from which to start the neighbor search.
        limit (int): Limit the number of returned results. Default is 10.
        offset (Optional[int]): Offset into the paginated results (requires limit).
        filters (Optional[dict]): Dictionary containing the filters to apply.
            Defaults to None.
        search_meta (dict): Dictionary containing the keywords to search for
            over the track.resource.meta field. The dictionary's values
            should contain singular search tokens and the keys currently have no
            effect but might in the future. Defaults to {}.
        track_type (Union[str, List[str]], optional): Track type to filter for.
            Can be a singular type or a list of types. Defaults to None.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        collection_id (Union[str, uuid.UUID], optional): Collection id to
            which the filtered tracks must have a relationship. Defaults to None.
        plugin_names (list, optional): List used for applying the filter only to
            data of certain plugins. If None, all plugin data related to the track
            is used for filtering.
        embedding_name (str, optional): Name of the embedding plugin for which to
            retrieve and compare the vectors. If none is given, the name of the
            currently configured embedding plugin for the library vector extension
            is used.
        embedding_version (str, optional): Version of the embedding plugin for
            which to retrieve and compare the vectors. If none is given, the
            version of the currently configured embedding plugin for the library
            vector extension is used.
        distance_metric (Optional[DistanceMetric], optional): The distance metric
            to use. Defaults to None.

    Returns:
        List[Tuple[NendoTrack, float]]: List of tuples containing a track in
            the first position and their distance ("score") in the second
            position, ordered by their distance in ascending order.
    """
    query_embedding = self.embed_text(query)
    return self.nearest_by_vector_with_score(
        vec=query_embedding,
        limit=limit,
        offset=offset,
        filters=filters,
        search_meta=search_meta,
        track_type=track_type,
        user_id=user_id,
        collection_id=collection_id,
        plugin_names=plugin_names,
        embedding_name=embedding_name,
        embedding_version=embedding_version,
        distance_metric=distance_metric,
    )

nearest_by_track ¤

nearest_by_track(
    track: NendoTrack,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[Dict[str, List[str]]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, UUID]] = None,
    collection_id: Optional[Union[str, UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[NendoTrack]

Obtain the n nearest neighboring tracks to a track from the library.

Parameters:

Name Type Description Default
track NendoTrack

The track from which to start the neighbor search.

required
limit int

Limit the number of returned results. Default is 10.

10
offset Optional[int]

Offset into the paginated results (requires limit).

None
filters Optional[dict]

Dictionary containing the filters to apply. Defaults to None.

None
search_meta dict

Dictionary containing the keywords to search for over the track.resource.meta field. The dictionary's values should contain singular search tokens and the keys currently have no effect but might in the future. Defaults to {}.

None
track_type Union[str, List[str]]

Track type to filter for. Can be a singular type or a list of types. Defaults to None.

None
user_id Union[str, UUID]

The user ID to filter for.

None
collection_id Union[str, UUID]

Collection id to which the filtered tracks must have a relationship. Defaults to None.

None
plugin_names list

List used for applying the filter only to data of certain plugins. If None, all plugin data related to the track is used for filtering.

None
embedding_name str

Name of the embedding plugin for which to retrieve and compare the vectors. If none is given, the name of the first embedding found for that track is used. If no embedding exists, the name of the currently configured embedding plugin for the library vector extension is used.

None
embedding_version str

Version of the embedding plugin for which to retrieve and compare the vectors. If none is given, the name of the first embedding found for that track is used. If no embedding exists,the version of the currently configured embedding plugin for the library vector extension is used.

None
distance_metric Optional[DistanceMetric]

The distance metric to use. Defaults to None.

None

Returns:

Type Description
List[NendoTrack]

The list of tracks corresponding to the n nearest embedding vectors of the given target track.

Source code in src/nendo/library/extension.py
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
def nearest_by_track(
    self,
    track: NendoTrack,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[Dict[str, List[str]]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    collection_id: Optional[Union[str, uuid.UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[NendoTrack]:
    """Obtain the n nearest neighboring tracks to a track from the library.

    Args:
        track (NendoTrack): The track from which to start the neighbor search.
        limit (int): Limit the number of returned results. Default is 10.
        offset (Optional[int]): Offset into the paginated results (requires limit).
        filters (Optional[dict]): Dictionary containing the filters to apply.
            Defaults to None.
        search_meta (dict): Dictionary containing the keywords to search for
            over the track.resource.meta field. The dictionary's values
            should contain singular search tokens and the keys currently have no
            effect but might in the future. Defaults to {}.
        track_type (Union[str, List[str]], optional): Track type to filter for.
            Can be a singular type or a list of types. Defaults to None.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        collection_id (Union[str, uuid.UUID], optional): Collection id to
            which the filtered tracks must have a relationship. Defaults to None.
        plugin_names (list, optional): List used for applying the filter only to
            data of certain plugins. If None, all plugin data related to the track
            is used for filtering.
        embedding_name (str, optional): Name of the embedding plugin for which to
            retrieve and compare the vectors. If none is given, the name of the
            first embedding found for that track is used. If no embedding exists,
            the name of the currently configured embedding plugin for the library
            vector extension is used.
        embedding_version (str, optional): Version of the embedding plugin for
            which to retrieve and compare the vectors. If none is given, the name
            of the first embedding found for that track is used. If no embedding
            exists,the version of the currently configured embedding plugin for
            the library vector extension is used.
        distance_metric (Optional[DistanceMetric], optional): The distance metric
            to use. Defaults to None.

    Returns:
        List[NendoTrack]: The list of tracks corresponding to the n nearest
            embedding vectors of the given target track.
    """
    tracks_and_scores = self.nearest_by_track_with_score(
        track=track,
        limit=limit,
        offset=offset,
        filters=filters,
        search_meta=search_meta,
        track_type=track_type,
        user_id=user_id,
        collection_id=collection_id,
        plugin_names=plugin_names,
        embedding_name=embedding_name,
        embedding_version=embedding_version,
        distance_metric=distance_metric,
    )
    return [track for track, _ in tracks_and_scores]

nearest_by_track_with_score ¤

nearest_by_track_with_score(
    track: NendoTrack,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[Dict[str, List[str]]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, UUID]] = None,
    collection_id: Optional[Union[str, UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[Tuple[NendoTrack, float]]

Obtain the n nearest neighbors to a track, together with their distances.

Parameters:

Name Type Description Default
track NendoTrack

The track from which to start the neighbor search.

required
limit int

Limit the number of returned results. Default is 10.

10
offset Optional[int]

Offset into the paginated results (requires limit).

None
filters Optional[dict]

Dictionary containing the filters to apply. Defaults to None.

None
search_meta dict

Dictionary containing the keywords to search for over the track.resource.meta field. The dictionary's values should contain singular search tokens and the keys currently have no effect but might in the future. Defaults to {}.

None
track_type Union[str, List[str]]

Track type to filter for. Can be a singular type or a list of types. Defaults to None.

None
user_id Union[str, UUID]

The user ID to filter for.

None
collection_id Union[str, UUID]

Collection id to which the filtered tracks must have a relationship. Defaults to None.

None
plugin_names list

List used for applying the filter only to data of certain plugins. If None, all plugin data related to the track is used for filtering.

None
embedding_name str

Name of the embedding plugin for which to retrieve and compare the vectors. If none is given, the name of the first embedding found for that track is used. If no embedding exists, the name of the currently configured embedding plugin for the library vector extension is used.

None
embedding_version str

Version of the embedding plugin for which to retrieve and compare the vectors. If none is given, the name of the first embedding found for that track is used. If no embedding exists,the version of the currently configured embedding plugin for the library vector extension is used.

None
distance_metric Optional[DistanceMetric]

The distance metric to use. Defaults to None.

None

Returns:

Type Description
List[Tuple[NendoTrack, float]]

List of tuples containing a track in the first position and their distance ("score") in the second position, ordered by their distance in ascending order.

Source code in src/nendo/library/extension.py
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
def nearest_by_track_with_score(
    self,
    track: NendoTrack,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[Dict[str, List[str]]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    collection_id: Optional[Union[str, uuid.UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[Tuple[NendoTrack, float]]:
    """Obtain the n nearest neighbors to a track, together with their distances.

    Args:
        track (NendoTrack): The track from which to start the neighbor search.
        limit (int): Limit the number of returned results. Default is 10.
        offset (Optional[int]): Offset into the paginated results (requires limit).
        filters (Optional[dict]): Dictionary containing the filters to apply.
            Defaults to None.
        search_meta (dict): Dictionary containing the keywords to search for
            over the track.resource.meta field. The dictionary's values
            should contain singular search tokens and the keys currently have no
            effect but might in the future. Defaults to {}.
        track_type (Union[str, List[str]], optional): Track type to filter for.
            Can be a singular type or a list of types. Defaults to None.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        collection_id (Union[str, uuid.UUID], optional): Collection id to
            which the filtered tracks must have a relationship. Defaults to None.
        plugin_names (list, optional): List used for applying the filter only to
            data of certain plugins. If None, all plugin data related to the track
            is used for filtering.
        embedding_name (str, optional): Name of the embedding plugin for which to
            retrieve and compare the vectors. If none is given, the name of the
            first embedding found for that track is used. If no embedding exists,
            the name of the currently configured embedding plugin for the library
            vector extension is used.
        embedding_version (str, optional): Version of the embedding plugin for
            which to retrieve and compare the vectors. If none is given, the name
            of the first embedding found for that track is used. If no embedding
            exists,the version of the currently configured embedding plugin for
            the library vector extension is used.
        distance_metric (Optional[DistanceMetric], optional): The distance metric
            to use. Defaults to None.

    Returns:
        List[Tuple[NendoTrack, float]]: List of tuples containing a track in
            the first position and their distance ("score") in the second
            position, ordered by their distance in ascending order.
    """
    plugin_name = (
        embedding_name
        if embedding_name is not None
        else (
            self.embedding_plugin.plugin_name
            if self.embedding_plugin is not None
            else None
        )
    )
    plugin_version = (
        embedding_version
        if embedding_version is not None
        else (
            self.embedding_plugin.plugin_version
            if self.embedding_plugin is not None
            else None
        )
    )
    track_embeddings = self.get_embeddings(
        track_id=track.id,
        plugin_name=plugin_name,
        plugin_version=plugin_version,
    )
    if len(track_embeddings) < 1:
        track_embedding = self.embed_track(track)
    else:
        track_embedding = track_embeddings[0]
        plugin_name = track_embedding.plugin_name
        plugin_version = track_embedding.plugin_version

    nearest = self.nearest_by_vector_with_score(
        vec=track_embedding.embedding,
        limit=limit + 1,
        offset=offset,
        filters=filters,
        search_meta=search_meta,
        track_type=track_type,
        user_id=user_id,
        collection_id=collection_id,
        plugin_names=plugin_names,
        embedding_name=plugin_name,
        embedding_version=plugin_version,
        distance_metric=distance_metric,
    )
    return nearest[1:]

nearest_by_vector ¤

nearest_by_vector(
    vec: ArrayLike,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[List[str]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, UUID]] = None,
    collection_id: Optional[Union[str, UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[NendoTrack]

Obtain the n nearest neighboring tracks to a vector from the library.

Parameters:

Name Type Description Default
vec ArrayLike

The vector from which to start the neighbor search.

required
limit int

Limit the number of returned results. Default is 10.

10
offset Optional[int]

Offset into the paginated results (requires limit).

None
filters Optional[dict]

Dictionary containing the filters to apply. Defaults to None.

None
search_meta dict

Dictionary containing the keywords to search for over the track.resource.meta field. The dictionary's values should contain singular search tokens and the keys currently have no effect but might in the future. Defaults to {}.

None
track_type Union[str, List[str]]

Track type to filter for. Can be a singular type or a list of types. Defaults to None.

None
user_id Union[str, UUID]

The user ID to filter for.

None
collection_id Union[str, UUID]

Collection id to which the filtered tracks must have a relationship. Defaults to None.

None
plugin_names list

List used for applying the filter only to data of certain plugins. If None, all plugin data related to the track is used for filtering.

None
embedding_name str

Name of the embedding plugin for which to retrieve and compare the vectors. If none is given, the name of the currently configured embedding plugin for the library vector extension is used.

None
embedding_version str

Version of the embedding plugin for which to retrieve and compare the vectors. If none is given, the version of the currently configured embedding plugin for the library vector extension is used.

None
distance_metric Optional[DistanceMetric]

The distance metric to use. Defaults to None.

None

Returns:

Type Description
List[NendoTrack]

The list of tracks corresponding to the n nearest embedding vectors of the given target vector.

Source code in src/nendo/library/extension.py
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
def nearest_by_vector(
    self,
    vec: npt.ArrayLike,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[List[str]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    collection_id: Optional[Union[str, uuid.UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[NendoTrack]:
    """Obtain the n nearest neighboring tracks to a vector from the library.

    Args:
        vec (numpy.typing.ArrayLike): The vector from which to start the neighbor search.
        limit (int): Limit the number of returned results. Default is 10.
        offset (Optional[int]): Offset into the paginated results (requires limit).
        filters (Optional[dict]): Dictionary containing the filters to apply.
            Defaults to None.
        search_meta (dict): Dictionary containing the keywords to search for
            over the track.resource.meta field. The dictionary's values
            should contain singular search tokens and the keys currently have no
            effect but might in the future. Defaults to {}.
        track_type (Union[str, List[str]], optional): Track type to filter for.
            Can be a singular type or a list of types. Defaults to None.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        collection_id (Union[str, uuid.UUID], optional): Collection id to
            which the filtered tracks must have a relationship. Defaults to None.
        plugin_names (list, optional): List used for applying the filter only to
            data of certain plugins. If None, all plugin data related to the track
            is used for filtering.
        embedding_name (str, optional): Name of the embedding plugin for which to
            retrieve and compare the vectors. If none is given, the name of the
            currently configured embedding plugin for the library vector extension
            is used.
        embedding_version (str, optional): Version of the embedding plugin for
            which to retrieve and compare the vectors. If none is given, the
            version of the currently configured embedding plugin for the library
            vector extension is used.
        distance_metric (Optional[DistanceMetric], optional): The distance metric
            to use. Defaults to None.

    Returns:
        List[NendoTrack]: The list of tracks corresponding to the n nearest
            embedding vectors of the given target vector.
    """
    tracks_and_scores = self.get_similar_by_vector_with_score(
        vec=vec,
        limit=limit,
        offset=offset,
        filters=filters,
        search_meta=search_meta,
        track_type=track_type,
        user_id=user_id,
        collection_id=collection_id,
        plugin_names=plugin_names,
        embedding_name=embedding_name,
        embedding_version=embedding_version,
        distance_metric=distance_metric,
    )
    return [track for track, _ in tracks_and_scores]

nearest_by_vector_with_score ¤

nearest_by_vector_with_score(
    vec: ArrayLike,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[Dict[str, List[str]]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, UUID]] = None,
    collection_id: Optional[Union[str, UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[Tuple[NendoTrack, float]]

Obtain the n nearest neighbors to a vector, together with their distances.

Parameters:

Name Type Description Default
vec ArrayLike

The vector from which to start the neighbor search.

required
limit int

Limit the number of returned results. Default is 10.

10
offset Optional[int]

Offset into the paginated results (requires limit).

None
filters Optional[dict]

Dictionary containing the filters to apply. Defaults to None.

None
search_meta dict

Dictionary containing the keywords to search for over the track.resource.meta field. The dictionary's values should contain singular search tokens and the keys currently have no effect but might in the future. Defaults to {}.

None
track_type Union[str, List[str]]

Track type to filter for. Can be a singular type or a list of types. Defaults to None.

None
user_id Union[str, UUID]

The user ID to filter for.

None
collection_id Union[str, UUID]

Collection id to which the filtered tracks must have a relationship. Defaults to None.

None
plugin_names list

List used for applying the filter only to data of certain plugins. If None, all plugin data related to the track is used for filtering.

None
embedding_name str

Name of the embedding plugin for which to retrieve and compare the vectors. If none is given, the name of the currently configured embedding plugin for the library vector extension is used.

None
embedding_version str

Version of the embedding plugin for which to retrieve and compare the vectors. If none is given, the version of the currently configured embedding plugin for the library vector extension is used.

None
distance_metric Optional[DistanceMetric]

The distance metric to use. Defaults to None.

None

Returns:

Type Description
List[Tuple[NendoTrack, float]]

List of tuples containing a track in the first position and their distance ("score") in the second position, ordered by their distance in ascending order.

Source code in src/nendo/library/extension.py
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
def nearest_by_vector_with_score(
    self,
    vec: npt.ArrayLike,
    limit: int = 10,
    offset: Optional[int] = None,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[Dict[str, List[str]]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    collection_id: Optional[Union[str, uuid.UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    embedding_name: Optional[str] = None,
    embedding_version: Optional[str] = None,
    distance_metric: Optional[DistanceMetric] = None,
) -> List[Tuple[NendoTrack, float]]:
    """Obtain the n nearest neighbors to a vector, together with their distances.

    Args:
        vec (numpy.typing.ArrayLike): The vector from which to start the neighbor
            search.
        limit (int): Limit the number of returned results. Default is 10.
        offset (Optional[int]): Offset into the paginated results (requires limit).
        filters (Optional[dict]): Dictionary containing the filters to apply.
            Defaults to None.
        search_meta (dict): Dictionary containing the keywords to search for
            over the track.resource.meta field. The dictionary's values
            should contain singular search tokens and the keys currently have no
            effect but might in the future. Defaults to {}.
        track_type (Union[str, List[str]], optional): Track type to filter for.
            Can be a singular type or a list of types. Defaults to None.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        collection_id (Union[str, uuid.UUID], optional): Collection id to
            which the filtered tracks must have a relationship. Defaults to None.
        plugin_names (list, optional): List used for applying the filter only to
            data of certain plugins. If None, all plugin data related to the track
            is used for filtering.
        embedding_name (str, optional): Name of the embedding plugin for which to
            retrieve and compare the vectors. If none is given, the name of the
            currently configured embedding plugin for the library vector extension
            is used.
        embedding_version (str, optional): Version of the embedding plugin for
            which to retrieve and compare the vectors. If none is given, the
            version of the currently configured embedding plugin for the library
            vector extension is used.
        distance_metric (Optional[DistanceMetric], optional): The distance metric
            to use. Defaults to None.

    Returns:
        List[Tuple[NendoTrack, float]]: List of tuples containing a track in
            the first position and their distance ("score") in the second
            position, ordered by their distance in ascending order.
    """
    raise NotImplementedError

remove_embedding abstractmethod ¤

remove_embedding(embedding_id: UUID) -> bool

Remove an embedding from the library.

Parameters:

Name Type Description Default
embedding_id UUID

The ID of the embedding to remove.

required

Returns:

Type Description
bool

True if the embedding was successfully removed, False otherwise.

Source code in src/nendo/library/extension.py
692
693
694
695
696
697
698
699
700
701
702
@abstractmethod
def remove_embedding(self, embedding_id: uuid.UUID) -> bool:
    """Remove an embedding from the library.

    Args:
        embedding_id (uuid.UUID): The ID of the embedding to remove.

    Returns:
        bool: True if the embedding was successfully removed, False otherwise.
    """
    raise NotImplementedError

update_embedding abstractmethod ¤

update_embedding(
    embedding: NendoEmbedding,
) -> NendoEmbedding

Update an existing embedding in the library.

Parameters:

Name Type Description Default
embedding NendoEmbedding

The updated embedding.

required

Returns:

Type Description
NendoEmbedding

The updated embedding.

Source code in src/nendo/library/extension.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
@abstractmethod
def update_embedding(
    self,
    embedding: NendoEmbedding,
) -> NendoEmbedding:
    """Update an existing embedding in the library.

    Args:
        embedding (NendoEmbedding): The updated embedding.

    Returns:
        NendoEmbedding: The updated embedding.
    """
    raise NotImplementedError