Skip to content

Retrievers

See Retrievers for how to build and fill one.

Retriever

The abstract interface the classifiers are typed against. Implement these four methods to substitute a different vector store or search service.

rac4os._vector_database.Retriever.Retriever

Bases: ABC

Abstract class that integrates with all rac4os classifiers that build on retrieval. If you want to use a custom retrieval approach that is not supported by rac4os use this class and implement your custom logic here. If the approach does not need to build a custom, vector database just do not implement the related methods, just implement the search_category method. This is the only method that is required for the retrieval based classification approaches.

Source code in rac4os/_vector_database/Retriever.py
class Retriever(ABC):

    """
    Abstract class that integrates with all `rac4os` classifiers that build on retrieval. If you want to use a custom retrieval approach that is not supported 
    by `rac4os` use this class and implement your custom logic here. If the approach does not need to build a custom, vector database just do not implement the
    related methods, just implement the search_category method. This is the only method that is required for the retrieval based classification approaches.
    """

    @abstractmethod
    def __init__(self, **kwargs) -> None:
        """
        Set up whatever the backend needs to answer `search_category`.

        Nothing in the package calls this with a fixed argument list, so an implementation is
        free to take whatever its backend needs: a path and a collection name for a local
        store, a URL and a key for a hosted search service.

        Parameters:
            **kwargs (Any): whatever your implementation requires.
        """
        ...

    @abstractmethod
    def create_collection(self,
        ids:list[str],
        documents:list[str],
        metadatas:list[dict]
    )->None:
        """
        Write a batch of documents into the backend.

        Only needed when your retriever builds its own index. A wrapper around an existing
        search service can leave this unimplemented.

        Parameters:
            ids (list[str]): unique id per document.
            documents (list[str]): the texts that get embedded and searched over.
            metadatas (list[dict]): one metadata dict per document, carrying everything about the code that is not the searched text.
        """
        ...

    @abstractmethod
    def index(
        self,
        classification_system:ClassificationSystem,
        codes_to_include:list[str]|None=None,   
        **kwargs       
    )->None:
        """
        Fill the retriever from a classification system.

        Only needed when your retriever builds its own index. This is the method that decides
        what a category's searchable text is: the choice of what to embed, and what to keep
        alongside as metadata, is the single biggest lever on retrieval quality.

        Parameters:
            classification_system (ClassificationSystem): the taxonomy to index.
            codes_to_include (list[str]|None): restrict indexing to these codes; None indexes every code in the system.
            **kwargs (Any): implementation-specific options.
        """
        ...

    @abstractmethod
    def search_category(
        self,
        query:str,
        k:int,
        where:dict|None=None
    )->Any:
        """
        Return the k categories closest to a query.

        This is the only method the retrieval-based classifiers actually call, so it is the
        only one you have to implement. Each returned candidate is serialised into the
        generator's prompt as it comes back from here, which means the shape you return is the
        shape the model reasons over.

        Parameters:
            query (str): the text to search for.
            k (int): how many candidates to return.
            where (dict|None): optional metadata filter, e.g. restricting results to one level or one branch.

        Returns:
            Any: k candidates, each carrying at least the code and the text that was matched.
        """
        ...

__init__ abstractmethod

__init__(**kwargs)

Set up whatever the backend needs to answer search_category.

Nothing in the package calls this with a fixed argument list, so an implementation is free to take whatever its backend needs: a path and a collection name for a local store, a URL and a key for a hosted search service.

Parameters:

Name Type Description Default
**kwargs Any

whatever your implementation requires.

{}
Source code in rac4os/_vector_database/Retriever.py
@abstractmethod
def __init__(self, **kwargs) -> None:
    """
    Set up whatever the backend needs to answer `search_category`.

    Nothing in the package calls this with a fixed argument list, so an implementation is
    free to take whatever its backend needs: a path and a collection name for a local
    store, a URL and a key for a hosted search service.

    Parameters:
        **kwargs (Any): whatever your implementation requires.
    """
    ...

create_collection abstractmethod

create_collection(ids, documents, metadatas)

Write a batch of documents into the backend.

Only needed when your retriever builds its own index. A wrapper around an existing search service can leave this unimplemented.

Parameters:

Name Type Description Default
ids list[str]

unique id per document.

required
documents list[str]

the texts that get embedded and searched over.

required
metadatas list[dict]

one metadata dict per document, carrying everything about the code that is not the searched text.

required
Source code in rac4os/_vector_database/Retriever.py
@abstractmethod
def create_collection(self,
    ids:list[str],
    documents:list[str],
    metadatas:list[dict]
)->None:
    """
    Write a batch of documents into the backend.

    Only needed when your retriever builds its own index. A wrapper around an existing
    search service can leave this unimplemented.

    Parameters:
        ids (list[str]): unique id per document.
        documents (list[str]): the texts that get embedded and searched over.
        metadatas (list[dict]): one metadata dict per document, carrying everything about the code that is not the searched text.
    """
    ...

index abstractmethod

index(classification_system, codes_to_include=None, **kwargs)

Fill the retriever from a classification system.

Only needed when your retriever builds its own index. This is the method that decides what a category's searchable text is: the choice of what to embed, and what to keep alongside as metadata, is the single biggest lever on retrieval quality.

Parameters:

Name Type Description Default
classification_system ClassificationSystem

the taxonomy to index.

required
codes_to_include list[str] | None

restrict indexing to these codes; None indexes every code in the system.

None
**kwargs Any

implementation-specific options.

{}
Source code in rac4os/_vector_database/Retriever.py
@abstractmethod
def index(
    self,
    classification_system:ClassificationSystem,
    codes_to_include:list[str]|None=None,   
    **kwargs       
)->None:
    """
    Fill the retriever from a classification system.

    Only needed when your retriever builds its own index. This is the method that decides
    what a category's searchable text is: the choice of what to embed, and what to keep
    alongside as metadata, is the single biggest lever on retrieval quality.

    Parameters:
        classification_system (ClassificationSystem): the taxonomy to index.
        codes_to_include (list[str]|None): restrict indexing to these codes; None indexes every code in the system.
        **kwargs (Any): implementation-specific options.
    """
    ...

search_category abstractmethod

search_category(query, k, where=None)

Return the k categories closest to a query.

This is the only method the retrieval-based classifiers actually call, so it is the only one you have to implement. Each returned candidate is serialised into the generator's prompt as it comes back from here, which means the shape you return is the shape the model reasons over.

Parameters:

Name Type Description Default
query str

the text to search for.

required
k int

how many candidates to return.

required
where dict | None

optional metadata filter, e.g. restricting results to one level or one branch.

None

Returns:

Name Type Description
Any Any

k candidates, each carrying at least the code and the text that was matched.

Source code in rac4os/_vector_database/Retriever.py
@abstractmethod
def search_category(
    self,
    query:str,
    k:int,
    where:dict|None=None
)->Any:
    """
    Return the k categories closest to a query.

    This is the only method the retrieval-based classifiers actually call, so it is the
    only one you have to implement. Each returned candidate is serialised into the
    generator's prompt as it comes back from here, which means the shape you return is the
    shape the model reasons over.

    Parameters:
        query (str): the text to search for.
        k (int): how many candidates to return.
        where (dict|None): optional metadata filter, e.g. restricting results to one level or one branch.

    Returns:
        Any: k candidates, each carrying at least the code and the text that was matched.
    """
    ...

VectorStore

rac4os._vector_database.vector_store.VectorStore

Bases: Retriever

Interface for filling and querying the chromaDB (persistent) client. Builds a chromaDB collection from a predefined ClassificationSystem

Parameters:

Name Type Description Default
collection_name str

name of the collection to create/load

required
chromadb_path str

path of the persistent client to load or create

required
embedding_function_type str

which backend embeds documents and queries - "openai", "ollama" or "sentence_transformers".

required
embedding_batch_size int

how many documents go per collection.add call. Raise it for a local model, keep it low for a remote API.

16
**embedding_kwargs Any

forwarded untouched to the chosen embedding function, e.g. model_name, url, api_key. Both sides of a collection go through the same model, so a collection is only meaningful together with the model that built it.

{}
Source code in rac4os/_vector_database/vector_store.py
class VectorStore(Retriever):
    """
    Interface for filling and querying the chromaDB (persistent) client.
    Builds a chromaDB collection from a predefined ClassificationSystem

    Parameters:
        collection_name (str): name of the collection to create/load
        chromadb_path (str): path of the persistent client to load or create
        embedding_function_type (str): which backend embeds documents and
            queries - "openai", "ollama" or "sentence_transformers".
        embedding_batch_size (int): how many documents go per `collection.add`
            call. Raise it for a local model, keep it low for a remote API.
        **embedding_kwargs (Any): forwarded untouched to the chosen embedding
            function, e.g. `model_name`, `url`, `api_key`. Both sides of a
            collection go through the same model, so a collection is only
            meaningful together with the model that built it.
    """

    def __init__(
        self,
        collection_name: str,
        chromadb_path: str,
        embedding_function_type: Literal["openai", "ollama", "sentence_transformers"],
        embedding_batch_size: int = 16,
        **embedding_kwargs,
    ) -> None:
        """
        Opens the persistent chromaDB client and gets or creates the collection.

        The embedding function is built here from `embedding_function_type` and
        `embedding_kwargs` and attached to the collection, so queries are embedded with the
        same model that indexed it. The collection is created with cosine distance.

        Nothing is indexed by constructing a store: an existing collection is reused as it
        stands, and a new one starts empty until `index` is called. This is why pointing at the
        wrong `collection_name` shows up as an empty candidate list rather than as an error.
        """
        self.collection_name = collection_name
        self.chromadb_path = chromadb_path
        self.embedding_function_type = embedding_function_type
        self.embedding_batch_size = embedding_batch_size
        self.chroma_client = chromadb.PersistentClient(path=chromadb_path)
        print("Setting up embedding function and collection!")
        self.collection = self.chroma_client.get_or_create_collection(
            name=collection_name,
            embedding_function=get_ef(
                embedding_function_type=self.embedding_function_type, **embedding_kwargs
            ),  # type: ignore
            configuration={"hnsw": {"space": "cosine"}},
        )

    def create_collection(
        self, ids: list[str], documents: list[str], metadatas: list[dict]
    ) -> None:
        """
        Fills the chromaDB clients collection with the contents, that will be searchable afterwards.

        Paramters:
            ids (list[str]): ids of the given tuple
            documents (list[str]): documents to be indexed/vectorised
            metadatas (list[dict[str, Any]]): metadata of the documents to be inserted into the db
        """

        batch_size = self.embedding_batch_size

        for i in range(0, len(ids), batch_size):
            self.collection.add(
                ids=ids[i : i + batch_size],
                documents=documents[i : i + batch_size],
                metadatas=metadatas[i : i + batch_size],  # type: ignore
            )
        print("Sucessfully indexed classification system")

    def index(
        self,
        classification_system: ClassificationSystem,
        codes_to_include: list[str] | None = None,
        **kwargs,
    ) -> None:
        """
        Interface for indexing a `ClassificationSystem`. Takes a `ClassificationSystem` object and inserts it into
        a chromaDB collection of the persistent client. All the codes of the given classification system will be index,
        based on their description, which will serve as documents, all other information associated with code, will be
        stored in the metadata of the tuples. If you only want to index a certain subset of the classification system use
        codes_to_include, and insert a list of codes to index. One thing is important to notice at this point. Because chromaDB
        does not allow, metadata entries themselves to be dictionaries, all dicts will be dumped to a json-string.

        Parameters:
            classification_system (ClassificationSystem): classification system to be index in the vector store
            codes_to_include (list[str]|None): list of codes to be indexed, when this paramter is left blank all entries of the classification system will indexed.
            **kwargs (Any): additional key word args, at this points they will be ignored.

        Returns:
            None


        """

        def flatten(c: dict) -> dict:
            """
            Reduce one code record to chromaDB-storable metadata.

            chromaDB rejects metadata values that are themselves dicts, so anything that is not a
            scalar is dumped to a JSON string. The side effect is that the contents of those dumped
            fields cannot be filtered on afterwards with `where`. `description` is left out because
            it is indexed as the document rather than as metadata, and `search_category` puts it
            back on the result.

            Parameters:
                c (dict): a `Code` record as a dict.

            Returns:
                dict: the same record with `description` removed and every non-scalar value JSON-encoded.
            """
            return {
                k: (
                    v
                    if isinstance(v, (str, int, float, bool, type(None)))
                    else json.dumps(v, ensure_ascii=False)
                )  # this is sketchy dont know why this is the fix, for chroma raising an error, chroma dont likes when the meta dict itself contains dicts
                # also makes it not possible to later search those dumped categories
                for k, v in c.items()
                if k != "description"
            }

        if codes_to_include is None:
            codes = [c.to_dict() for c in classification_system.codes]
        else:
            codes = [
                c.to_dict()
                for c in classification_system.codes
                if c.code in codes_to_include
            ]

        ids = [f"id_{c['code']}" for c in codes]
        documents = [c["description"] for c in codes]
        metadatas = [flatten(c=c) for c in codes]

        self.create_collection(
            ids=ids,
            documents=documents,
            metadatas=metadatas,  # type: ignore
        )

    def search_category(
        self, query: str, k: int, where: dict[str, Any] | None = None
    ) -> list[dict[str, Any]]:
        """
        Function for searching the indexed chromaDB collection of the classification system.

        Paramters:
            query (str): query to search the collection
            k (int): number of DB entries to be returned
            where (dict[str,Any]|None): optional metadata filter which can be used to set contraints to the returned results. See chromaDB documentation for references.

        Returns:
            list of k codes that are the result of the similiarity search.

        """

        result = self.collection.query(query_texts=[query], n_results=k, where=where)
        if result is not None:
            output = result["metadatas"][0]  # type: ignore
            docs = result["documents"][0]  # type: ignore
            for o, d in zip(output, docs):
                o["description"] = d  # type: ignore
            return output
        else:
            raise Exception("Error occured while searching for code")

__init__

__init__(collection_name, chromadb_path, embedding_function_type, embedding_batch_size=16, **embedding_kwargs)

Opens the persistent chromaDB client and gets or creates the collection.

The embedding function is built here from embedding_function_type and embedding_kwargs and attached to the collection, so queries are embedded with the same model that indexed it. The collection is created with cosine distance.

Nothing is indexed by constructing a store: an existing collection is reused as it stands, and a new one starts empty until index is called. This is why pointing at the wrong collection_name shows up as an empty candidate list rather than as an error.

Source code in rac4os/_vector_database/vector_store.py
def __init__(
    self,
    collection_name: str,
    chromadb_path: str,
    embedding_function_type: Literal["openai", "ollama", "sentence_transformers"],
    embedding_batch_size: int = 16,
    **embedding_kwargs,
) -> None:
    """
    Opens the persistent chromaDB client and gets or creates the collection.

    The embedding function is built here from `embedding_function_type` and
    `embedding_kwargs` and attached to the collection, so queries are embedded with the
    same model that indexed it. The collection is created with cosine distance.

    Nothing is indexed by constructing a store: an existing collection is reused as it
    stands, and a new one starts empty until `index` is called. This is why pointing at the
    wrong `collection_name` shows up as an empty candidate list rather than as an error.
    """
    self.collection_name = collection_name
    self.chromadb_path = chromadb_path
    self.embedding_function_type = embedding_function_type
    self.embedding_batch_size = embedding_batch_size
    self.chroma_client = chromadb.PersistentClient(path=chromadb_path)
    print("Setting up embedding function and collection!")
    self.collection = self.chroma_client.get_or_create_collection(
        name=collection_name,
        embedding_function=get_ef(
            embedding_function_type=self.embedding_function_type, **embedding_kwargs
        ),  # type: ignore
        configuration={"hnsw": {"space": "cosine"}},
    )

create_collection

create_collection(ids, documents, metadatas)

Fills the chromaDB clients collection with the contents, that will be searchable afterwards.

Paramters

ids (list[str]): ids of the given tuple documents (list[str]): documents to be indexed/vectorised metadatas (list[dict[str, Any]]): metadata of the documents to be inserted into the db

Source code in rac4os/_vector_database/vector_store.py
def create_collection(
    self, ids: list[str], documents: list[str], metadatas: list[dict]
) -> None:
    """
    Fills the chromaDB clients collection with the contents, that will be searchable afterwards.

    Paramters:
        ids (list[str]): ids of the given tuple
        documents (list[str]): documents to be indexed/vectorised
        metadatas (list[dict[str, Any]]): metadata of the documents to be inserted into the db
    """

    batch_size = self.embedding_batch_size

    for i in range(0, len(ids), batch_size):
        self.collection.add(
            ids=ids[i : i + batch_size],
            documents=documents[i : i + batch_size],
            metadatas=metadatas[i : i + batch_size],  # type: ignore
        )
    print("Sucessfully indexed classification system")

index

index(classification_system, codes_to_include=None, **kwargs)

Interface for indexing a ClassificationSystem. Takes a ClassificationSystem object and inserts it into a chromaDB collection of the persistent client. All the codes of the given classification system will be index, based on their description, which will serve as documents, all other information associated with code, will be stored in the metadata of the tuples. If you only want to index a certain subset of the classification system use codes_to_include, and insert a list of codes to index. One thing is important to notice at this point. Because chromaDB does not allow, metadata entries themselves to be dictionaries, all dicts will be dumped to a json-string.

Parameters:

Name Type Description Default
classification_system ClassificationSystem

classification system to be index in the vector store

required
codes_to_include list[str] | None

list of codes to be indexed, when this paramter is left blank all entries of the classification system will indexed.

None
**kwargs Any

additional key word args, at this points they will be ignored.

{}

Returns:

Type Description
None

None

Source code in rac4os/_vector_database/vector_store.py
def index(
    self,
    classification_system: ClassificationSystem,
    codes_to_include: list[str] | None = None,
    **kwargs,
) -> None:
    """
    Interface for indexing a `ClassificationSystem`. Takes a `ClassificationSystem` object and inserts it into
    a chromaDB collection of the persistent client. All the codes of the given classification system will be index,
    based on their description, which will serve as documents, all other information associated with code, will be
    stored in the metadata of the tuples. If you only want to index a certain subset of the classification system use
    codes_to_include, and insert a list of codes to index. One thing is important to notice at this point. Because chromaDB
    does not allow, metadata entries themselves to be dictionaries, all dicts will be dumped to a json-string.

    Parameters:
        classification_system (ClassificationSystem): classification system to be index in the vector store
        codes_to_include (list[str]|None): list of codes to be indexed, when this paramter is left blank all entries of the classification system will indexed.
        **kwargs (Any): additional key word args, at this points they will be ignored.

    Returns:
        None


    """

    def flatten(c: dict) -> dict:
        """
        Reduce one code record to chromaDB-storable metadata.

        chromaDB rejects metadata values that are themselves dicts, so anything that is not a
        scalar is dumped to a JSON string. The side effect is that the contents of those dumped
        fields cannot be filtered on afterwards with `where`. `description` is left out because
        it is indexed as the document rather than as metadata, and `search_category` puts it
        back on the result.

        Parameters:
            c (dict): a `Code` record as a dict.

        Returns:
            dict: the same record with `description` removed and every non-scalar value JSON-encoded.
        """
        return {
            k: (
                v
                if isinstance(v, (str, int, float, bool, type(None)))
                else json.dumps(v, ensure_ascii=False)
            )  # this is sketchy dont know why this is the fix, for chroma raising an error, chroma dont likes when the meta dict itself contains dicts
            # also makes it not possible to later search those dumped categories
            for k, v in c.items()
            if k != "description"
        }

    if codes_to_include is None:
        codes = [c.to_dict() for c in classification_system.codes]
    else:
        codes = [
            c.to_dict()
            for c in classification_system.codes
            if c.code in codes_to_include
        ]

    ids = [f"id_{c['code']}" for c in codes]
    documents = [c["description"] for c in codes]
    metadatas = [flatten(c=c) for c in codes]

    self.create_collection(
        ids=ids,
        documents=documents,
        metadatas=metadatas,  # type: ignore
    )

search_category

search_category(query, k, where=None)

Function for searching the indexed chromaDB collection of the classification system.

Paramters

query (str): query to search the collection k (int): number of DB entries to be returned where (dict[str,Any]|None): optional metadata filter which can be used to set contraints to the returned results. See chromaDB documentation for references.

Returns:

Type Description
list[dict[str, Any]]

list of k codes that are the result of the similiarity search.

Source code in rac4os/_vector_database/vector_store.py
def search_category(
    self, query: str, k: int, where: dict[str, Any] | None = None
) -> list[dict[str, Any]]:
    """
    Function for searching the indexed chromaDB collection of the classification system.

    Paramters:
        query (str): query to search the collection
        k (int): number of DB entries to be returned
        where (dict[str,Any]|None): optional metadata filter which can be used to set contraints to the returned results. See chromaDB documentation for references.

    Returns:
        list of k codes that are the result of the similiarity search.

    """

    result = self.collection.query(query_texts=[query], n_results=k, where=where)
    if result is not None:
        output = result["metadatas"][0]  # type: ignore
        docs = result["documents"][0]  # type: ignore
        for o, d in zip(output, docs):
            o["description"] = d  # type: ignore
        return output
    else:
        raise Exception("Error occured while searching for code")

Embedding functions

rac4os._vector_database.vector_store.get_ef

get_ef(embedding_function_type, **kwargs)

Takes an embedding function type, maps the embedding function type to the correct interface and returns the loaded ef interface, given the defined kwargs.

Paramters

embedding_function_type (Literal["openai", "ollama", "sentence_transformers"]): tpye of embedding function to use. **kwargs (Any): arguments used to specify what model and paramters to use when loading the embedding function. Must correspond to what the chromaDB embedding function takes as input

Returns:

Type Description
EmbeddingFunction

embedding function

Source code in rac4os/_vector_database/vector_store.py
def get_ef(embedding_function_type: EFType, **kwargs) -> EmbeddingFunction:
    """
    Takes an embedding function type, maps the embedding function type
    to the correct interface and returns the loaded ef interface, given the
    defined kwargs.

    Paramters:
        embedding_function_type (Literal["openai", "ollama", "sentence_transformers"]): tpye of embedding function to use.
        **kwargs (Any): arguments used to specify what model and paramters to use when loading the embedding function. Must correspond to what the chromaDB embedding function takes as input

    Returns:
        embedding function

    """
    try:
        ef_cls = _EMEBEDDIG_FUNCTIONS[embedding_function_type]
    except KeyError:
        raise ValueError(
            f"Unknown embedding function: {embedding_function_type!r}"
        ) from None
    try:
        return ef_cls(**kwargs)
    except (ImportError, ValueError) as e:
        if "not installed" in str(e) or isinstance(e, ImportError):
            raise ImportError(
                f"The {embedding_function_type!r} embedding backend needs an extra: "
                f'pip install "rac4os[{_EXTRA[embedding_function_type]}]"'
            ) from e
        raise