Skip to content

Classifiers

The four classification entry points. Each Base… class takes its configuration as constructor arguments; each thin subclass looks the same configuration up in a registry by dataset name.

Hierarchy traversal

rac4os.agents.HierarchicalNavigation.BaseAgent.BaseHierarchicalNavigationAgent

Bases: Module

Classifies an item by walking the taxonomy top-down instead of retrieving candidates.

A dspy.ReAct agent is given four navigation tools over your classification system (get_root_categories, get_children, get_parent, get_code) and reasons its way from the first level down to a code, deciding at each step which branch to descend. Nothing is embedded and no vector store is involved, so this is the approach that works on a taxonomy you have only just described.

The tool descriptions are passed in rather than hardcoded, because what a tool should say about itself depends on how your codes are written: the agent reads them to decide which tool to call next.

Parameters:

Name Type Description Default
classification_name str

dataset name resolved through get_classification_system.

required
api_key str

credential for the LM provider.

required
model_name str

LiteLLM model identifier, e.g. "openai/gpt-4o-mini".

required
signature type[Signature]

the I/O contract; its docstring is the system prompt.

required
get_root_categories_doc str

tool description for listing the first level.

required
get_children_doc str

tool description for descending one level.

required
get_code_doc str

tool description for reading a single code.

required
get_parent_doc str

tool description for stepping back up one level.

required
api_base str | None

base URL of a self-hosted or proxied endpoint; None uses the provider's own.

None

Attributes:

Name Type Description
classification_system HierarchicalClassificationSystem

the taxonomy being navigated. This approach needs the hierarchy, so a flat ClassificationSystem will not do.

agent ReAct

the reasoning loop over the four tools.

lm LM

the language model this module pins for its own calls.

Source code in rac4os/agents/HierarchicalNavigation/BaseAgent.py
class BaseHierarchicalNavigationAgent(dspy.Module):
    """
    Classifies an item by walking the taxonomy top-down instead of retrieving candidates.

    A `dspy.ReAct` agent is given four navigation tools over your classification system
    (`get_root_categories`, `get_children`, `get_parent`, `get_code`) and reasons its way
    from the first level down to a code, deciding at each step which branch to descend.
    Nothing is embedded and no vector store is involved, so this is the approach that works
    on a taxonomy you have only just described.

    The tool descriptions are passed in rather than hardcoded, because what a tool should
    say about itself depends on how your codes are written: the agent reads them to decide
    which tool to call next.

    Parameters:
        classification_name (str): dataset name resolved through `get_classification_system`.
        api_key (str): credential for the LM provider.
        model_name (str): LiteLLM model identifier, e.g. "openai/gpt-4o-mini".
        signature (type[dspy.Signature]): the I/O contract; its docstring is the system prompt.
        get_root_categories_doc (str): tool description for listing the first level.
        get_children_doc (str): tool description for descending one level.
        get_code_doc (str): tool description for reading a single code.
        get_parent_doc (str): tool description for stepping back up one level.
        api_base (str|None): base URL of a self-hosted or proxied endpoint; None uses the provider's own.

    Attributes:
        classification_system (HierarchicalClassificationSystem): the taxonomy being
            navigated. This approach needs the hierarchy, so a flat `ClassificationSystem`
            will not do.
        agent (dspy.ReAct): the reasoning loop over the four tools.
        lm (dspy.LM): the language model this module pins for its own calls.
    """

    def __init__(
        self,
        classification_name: RegisteredClassifications,
        api_key: str,
        model_name: str,
        signature: type[dspy.Signature],
        get_root_categories_doc: str,
        get_children_doc: str,
        get_code_doc: str,
        get_parent_doc: str,
        api_base: str | None = None,
    ) -> None:
        """
        Builds the LM, loads the classification system and wires up the four navigation tools.

        Note that this configures `dspy` globally as well as storing the LM on the instance, so
        constructing a second classifier with a different model changes the global default. The
        `forward` methods pin their own LM, so already-constructed classifiers keep working.
        """
        assert model_name is not None
        assert classification_name is not None

        self.signature: type[dspy.Signature] = signature
        self.get_root_categories_doc: str = get_root_categories_doc
        self.get_children_doc: str = get_children_doc
        self.get_code_doc: str = get_code_doc
        self.get_parent_doc: str = get_parent_doc

        self.lm = dspy.LM(api_key=api_key, api_base=api_base, model=model_name)
        dspy.configure(lm=self.lm, track_usage=True)

        self.classification_name = classification_name
        self.classification_system: HierarchicalClassificationSystem = (
            get_classification_system(classification_name)
        )
        self.agent = dspy.ReAct(
            self.signature,
            tools=[
                dspy.Tool(
                    self.get_root_categories_tool,
                    name="get_root_categories",
                    desc=self.get_root_categories_doc,
                ),
                dspy.Tool(
                    self.get_children_tool,
                    name="get_children",
                    desc=self.get_children_doc,
                ),
                dspy.Tool(
                    self.get_parent_tool, name="get_parent", desc=self.get_parent_doc
                ),
                dspy.Tool(self.get_code_tool, name="get_code", desc=self.get_code_doc),
            ],
        )

    def get_code_tool(self, code: str) -> dict:
        """
        Tool: read the full record of one code.

        Parameters:
            code (str): the code to look up.

        Returns:
            dict: the `Code` record as a dict.
        """
        return self.classification_system.get_code(code).to_dict()

    def get_children_tool(self, code: str) -> list[dict]:
        """
        Tool: list the categories directly below a code, which is how the agent descends.

        Parameters:
            code (str): the parent code.

        Returns:
            list[dict]: one dict per direct child; empty for a leaf.
        """
        return [c.to_dict() for c in self.classification_system.get_children(code)]

    def get_parent_tool(self, code: str) -> dict:
        """
        Tool: step back up one level, which is how the agent recovers from a wrong branch.

        Parameters:
            code (str): the code whose parent is wanted.

        Returns:
            dict: the parent's `Code` record as a dict.
        """
        return self.classification_system.get_parent(code).to_dict()  # type: ignore

    def get_root_categories_tool(self) -> list[dict]:
        """
        Tool: list the first level of the taxonomy, where every traversal starts.

        Returns:
            list[dict]: one `code`/`description` dict per first-level category.
        """
        return self.classification_system.get_root_categories()

    def forward(self, **kwargs: Any) -> dspy.Prediction:
        """
        Classify one item.

        The signature's input fields are checked against the keyword arguments first, so a
        misnamed field surfaces immediately instead of as an obscure failure once the
        trajectory is already running. The call is wrapped in a `dspy.context` that pins this
        module's own LM, which makes it safe to hold several classifiers with different models
        in one process.

        Parameters:
            **kwargs (Any): one keyword argument per input field of the signature.

        Returns:
            dspy.Prediction: the signature's output fields, plus the ReAct trajectory under `thought_{i}`, `tool_name_{i}`, `tool_args_{i}` and `observation_{i}`.

        Raises:
            ValueError: if an input field declared by the signature was not passed.
        """
        missing = set(self.signature.input_fields) - kwargs.keys()
        if missing:
            raise ValueError(f"Missing input fields: {sorted(missing)}")

        with dspy.context(lm=self.lm, track_usage=True):
            return self.agent(**kwargs)

__init__

__init__(classification_name, api_key, model_name, signature, get_root_categories_doc, get_children_doc, get_code_doc, get_parent_doc, api_base=None)

Builds the LM, loads the classification system and wires up the four navigation tools.

Note that this configures dspy globally as well as storing the LM on the instance, so constructing a second classifier with a different model changes the global default. The forward methods pin their own LM, so already-constructed classifiers keep working.

Source code in rac4os/agents/HierarchicalNavigation/BaseAgent.py
def __init__(
    self,
    classification_name: RegisteredClassifications,
    api_key: str,
    model_name: str,
    signature: type[dspy.Signature],
    get_root_categories_doc: str,
    get_children_doc: str,
    get_code_doc: str,
    get_parent_doc: str,
    api_base: str | None = None,
) -> None:
    """
    Builds the LM, loads the classification system and wires up the four navigation tools.

    Note that this configures `dspy` globally as well as storing the LM on the instance, so
    constructing a second classifier with a different model changes the global default. The
    `forward` methods pin their own LM, so already-constructed classifiers keep working.
    """
    assert model_name is not None
    assert classification_name is not None

    self.signature: type[dspy.Signature] = signature
    self.get_root_categories_doc: str = get_root_categories_doc
    self.get_children_doc: str = get_children_doc
    self.get_code_doc: str = get_code_doc
    self.get_parent_doc: str = get_parent_doc

    self.lm = dspy.LM(api_key=api_key, api_base=api_base, model=model_name)
    dspy.configure(lm=self.lm, track_usage=True)

    self.classification_name = classification_name
    self.classification_system: HierarchicalClassificationSystem = (
        get_classification_system(classification_name)
    )
    self.agent = dspy.ReAct(
        self.signature,
        tools=[
            dspy.Tool(
                self.get_root_categories_tool,
                name="get_root_categories",
                desc=self.get_root_categories_doc,
            ),
            dspy.Tool(
                self.get_children_tool,
                name="get_children",
                desc=self.get_children_doc,
            ),
            dspy.Tool(
                self.get_parent_tool, name="get_parent", desc=self.get_parent_doc
            ),
            dspy.Tool(self.get_code_tool, name="get_code", desc=self.get_code_doc),
        ],
    )

get_code_tool

get_code_tool(code)

Tool: read the full record of one code.

Parameters:

Name Type Description Default
code str

the code to look up.

required

Returns:

Name Type Description
dict dict

the Code record as a dict.

Source code in rac4os/agents/HierarchicalNavigation/BaseAgent.py
def get_code_tool(self, code: str) -> dict:
    """
    Tool: read the full record of one code.

    Parameters:
        code (str): the code to look up.

    Returns:
        dict: the `Code` record as a dict.
    """
    return self.classification_system.get_code(code).to_dict()

get_children_tool

get_children_tool(code)

Tool: list the categories directly below a code, which is how the agent descends.

Parameters:

Name Type Description Default
code str

the parent code.

required

Returns:

Type Description
list[dict]

list[dict]: one dict per direct child; empty for a leaf.

Source code in rac4os/agents/HierarchicalNavigation/BaseAgent.py
def get_children_tool(self, code: str) -> list[dict]:
    """
    Tool: list the categories directly below a code, which is how the agent descends.

    Parameters:
        code (str): the parent code.

    Returns:
        list[dict]: one dict per direct child; empty for a leaf.
    """
    return [c.to_dict() for c in self.classification_system.get_children(code)]

get_parent_tool

get_parent_tool(code)

Tool: step back up one level, which is how the agent recovers from a wrong branch.

Parameters:

Name Type Description Default
code str

the code whose parent is wanted.

required

Returns:

Name Type Description
dict dict

the parent's Code record as a dict.

Source code in rac4os/agents/HierarchicalNavigation/BaseAgent.py
def get_parent_tool(self, code: str) -> dict:
    """
    Tool: step back up one level, which is how the agent recovers from a wrong branch.

    Parameters:
        code (str): the code whose parent is wanted.

    Returns:
        dict: the parent's `Code` record as a dict.
    """
    return self.classification_system.get_parent(code).to_dict()  # type: ignore

get_root_categories_tool

get_root_categories_tool()

Tool: list the first level of the taxonomy, where every traversal starts.

Returns:

Type Description
list[dict]

list[dict]: one code/description dict per first-level category.

Source code in rac4os/agents/HierarchicalNavigation/BaseAgent.py
def get_root_categories_tool(self) -> list[dict]:
    """
    Tool: list the first level of the taxonomy, where every traversal starts.

    Returns:
        list[dict]: one `code`/`description` dict per first-level category.
    """
    return self.classification_system.get_root_categories()

forward

forward(**kwargs)

Classify one item.

The signature's input fields are checked against the keyword arguments first, so a misnamed field surfaces immediately instead of as an obscure failure once the trajectory is already running. The call is wrapped in a dspy.context that pins this module's own LM, which makes it safe to hold several classifiers with different models in one process.

Parameters:

Name Type Description Default
**kwargs Any

one keyword argument per input field of the signature.

{}

Returns:

Type Description
Prediction

dspy.Prediction: the signature's output fields, plus the ReAct trajectory under thought_{i}, tool_name_{i}, tool_args_{i} and observation_{i}.

Raises:

Type Description
ValueError

if an input field declared by the signature was not passed.

Source code in rac4os/agents/HierarchicalNavigation/BaseAgent.py
def forward(self, **kwargs: Any) -> dspy.Prediction:
    """
    Classify one item.

    The signature's input fields are checked against the keyword arguments first, so a
    misnamed field surfaces immediately instead of as an obscure failure once the
    trajectory is already running. The call is wrapped in a `dspy.context` that pins this
    module's own LM, which makes it safe to hold several classifiers with different models
    in one process.

    Parameters:
        **kwargs (Any): one keyword argument per input field of the signature.

    Returns:
        dspy.Prediction: the signature's output fields, plus the ReAct trajectory under `thought_{i}`, `tool_name_{i}`, `tool_args_{i}` and `observation_{i}`.

    Raises:
        ValueError: if an input field declared by the signature was not passed.
    """
    missing = set(self.signature.input_fields) - kwargs.keys()
    if missing:
        raise ValueError(f"Missing input fields: {sorted(missing)}")

    with dspy.context(lm=self.lm, track_usage=True):
        return self.agent(**kwargs)

rac4os.agents.HierarchicalNavigation.HierarchicalNavigationAgent.HierarchicalNavigationAgent

Bases: BaseHierarchicalNavigationAgent

BaseHierarchicalNavigationAgent with the bundled configurations in front of it.

CONFIGS holds a ready-made signature and the four tool descriptions per shipped classification, so only the credentials and the model have to be supplied. For your own taxonomy either add an entry to CONFIGS or construct BaseHierarchicalNavigationAgent directly and pass the signature and tool descriptions yourself; both are the same code path.

Parameters:

Name Type Description Default
classification_name str

a key of CONFIGS.

required
**kwargs Any

forwarded to BaseHierarchicalNavigationAgent, e.g. api_key, model_name, api_base.

{}
Source code in rac4os/agents/HierarchicalNavigation/HierarchicalNavigationAgent.py
class HierarchicalNavigationAgent(BaseHierarchicalNavigationAgent):

    """
    `BaseHierarchicalNavigationAgent` with the bundled configurations in front of it.

    `CONFIGS` holds a ready-made signature and the four tool descriptions per shipped
    classification, so only the credentials and the model have to be supplied. For your own
    taxonomy either add an entry to `CONFIGS` or construct
    `BaseHierarchicalNavigationAgent` directly and pass the signature and tool descriptions
    yourself; both are the same code path.

    Parameters:
        classification_name (str): a key of `CONFIGS`.
        **kwargs (Any): forwarded to `BaseHierarchicalNavigationAgent`, e.g. `api_key`, `model_name`, `api_base`.
    """
    CONFIGS = registry

    def __init__(
        self,
        classification_name:Literal["COICOP_2018", "ICATUS_2016", "SEA_2021"],
        **kwargs,
    ) -> None:
        """
        Looks the configuration up in `CONFIGS` and hands it to the base class.

        Anything you pass yourself is forwarded unchanged, so a bundled entry can be
        overridden per call.

        Raises:
            ValueError: if `classification_name` has no entry in `CONFIGS`.
        """
        if classification_name not in self.CONFIGS:
            raise ValueError(f"Unknown classification system: {classification_name}")

        super().__init__(
            classification_name=classification_name,
            **self.CONFIGS[classification_name],
            **kwargs,
        )

__init__

__init__(classification_name, **kwargs)

Looks the configuration up in CONFIGS and hands it to the base class.

Anything you pass yourself is forwarded unchanged, so a bundled entry can be overridden per call.

Raises:

Type Description
ValueError

if classification_name has no entry in CONFIGS.

Source code in rac4os/agents/HierarchicalNavigation/HierarchicalNavigationAgent.py
def __init__(
    self,
    classification_name:Literal["COICOP_2018", "ICATUS_2016", "SEA_2021"],
    **kwargs,
) -> None:
    """
    Looks the configuration up in `CONFIGS` and hands it to the base class.

    Anything you pass yourself is forwarded unchanged, so a bundled entry can be
    overridden per call.

    Raises:
        ValueError: if `classification_name` has no entry in `CONFIGS`.
    """
    if classification_name not in self.CONFIGS:
        raise ValueError(f"Unknown classification system: {classification_name}")

    super().__init__(
        classification_name=classification_name,
        **self.CONFIGS[classification_name],
        **kwargs,
    )

Agentic RAG

rac4os.agents.RAG.BaseAgentRAG.BaseRAGAgent

Bases: Module

Classifies an item with the retriever exposed to the model as a tool.

A dspy.ReAct agent gets one tool, search_category, and decides for itself how often and with which query to use it. Where the linear pipeline is bound by its single initial query, this agent can reformulate and search again when the candidates it got back do not fit, which is what makes it the approach to reach for when retrieval is the part that fails.

The cost of that is variance: how many model calls an item takes is decided by the model, not by you.

Parameters:

Name Type Description Default
classification_system ClassificationSystem

the taxonomy to classify against, built by you or resolved from a dataset name with get_classification_system. Only the flat interface is used, so a ClassificationSystem is enough; a HierarchicalClassificationSystem is accepted and is what a registered dataset resolves to.

required
api_key str

credential for the LM provider.

required
model_name str

LiteLLM model identifier, e.g. "openai/gpt-4o-mini".

required
signature type[Signature]

the I/O contract; its docstring is the system prompt. Exactly one output field name must contain "code", which is the field the predicted code is read from.

required
search_category_tool_doc str

tool description the agent reads to decide how to query the store. Say what a good query looks like for your labels here.

required
store Retriever

a filled retriever; this class never indexes.

required
api_base str | None

base URL of a self-hosted or proxied endpoint; None uses the provider's own.

None
output_validation bool

whether to check the predicted code against the classification system after each call and record the outcome on the prediction as status. Costs one dictionary lookup; turn it off only if you want the model's raw answer untouched.

True
**generation_kwargs Any

forwarded to dspy.LM, e.g. temperature, max_tokens, top_p, seed, cache or num_retries. Anything dspy.LM does not name itself is handed on to LiteLLM, so whatever your provider accepts can be set here.

{}

Attributes:

Name Type Description
classification_system ClassificationSystem

the taxonomy the predicted code is validated against.

output_code_key str

the single output field whose name contains "code"; the field status is derived from.

store Retriever

the retriever behind the tool.

agent ReAct

the reasoning loop over the search tool.

lm LM

the language model this module pins for its own calls.

Source code in rac4os/agents/RAG/BaseAgentRAG.py
class BaseRAGAgent(dspy.Module):
    """
    Classifies an item with the retriever exposed to the model as a tool.

    A `dspy.ReAct` agent gets one tool, `search_category`, and decides for itself how often
    and with which query to use it. Where the linear pipeline is bound by its single
    initial query, this agent can reformulate and search again when the candidates it got
    back do not fit, which is what makes it the approach to reach for when retrieval is the
    part that fails.

    The cost of that is variance: how many model calls an item takes is decided by the
    model, not by you.

    Parameters:
        classification_system (ClassificationSystem): the taxonomy to classify against, built by you or resolved from a dataset name with `get_classification_system`. Only the flat interface is used, so a `ClassificationSystem` is enough; a `HierarchicalClassificationSystem` is accepted and is what a registered dataset resolves to.
        api_key (str): credential for the LM provider.
        model_name (str): LiteLLM model identifier, e.g. "openai/gpt-4o-mini".
        signature (type[dspy.Signature]): the I/O contract; its docstring is the system
            prompt. Exactly one output field name must contain "code", which is the field
            the predicted code is read from.
        search_category_tool_doc (str): tool description the agent reads to decide how to query the store. Say what a good query looks like for your labels here.
        store (Retriever): a filled retriever; this class never indexes.
        api_base (str|None): base URL of a self-hosted or proxied endpoint; None uses the provider's own.
        output_validation (bool): whether to check the predicted code against the classification system after each call and record the outcome on the prediction as `status`. Costs one dictionary lookup; turn it off only if you want the model's raw answer untouched.
        **generation_kwargs (Any): forwarded to `dspy.LM`, e.g. `temperature`, `max_tokens`, `top_p`, `seed`, `cache` or `num_retries`. Anything `dspy.LM` does not name itself is handed on to LiteLLM, so whatever your provider accepts can be set here.

    Attributes:
        classification_system (ClassificationSystem): the taxonomy the predicted code is
            validated against.
        output_code_key (str): the single output field whose name contains "code"; the field `status` is derived from.
        store (Retriever): the retriever behind the tool.
        agent (dspy.ReAct): the reasoning loop over the search tool.
        lm (dspy.LM): the language model this module pins for its own calls.
    """

    def __init__(
        self,
        api_key: str,
        model_name: str,
        signature: type[dspy.Signature],
        search_category_tool_doc: str,
        classification_system: ClassificationSystem,
        store: Retriever,
        api_base: str | None = None,
        output_validation: bool = True,
        **generation_kwargs,
    ) -> None:
        """
        Builds the LM and wraps the store's `search_category` into the agent's single tool.

        The signature is required to declare exactly one output field whose name contains
        "code"; that field is what `forward` validates.

        Note that this configures `dspy` globally as well as storing the LM on the instance, so
        constructing a second classifier with a different model changes the global default.
        `forward` pins its own LM, so already-constructed classifiers keep working.
        """
        super().__init__()

        assert model_name is not None, "Please specify the generator's model name"
        assert signature is not None, (
            "Signature cannot be None, please specify a signature"
        )
        assert sum("code" in f for f in signature.output_fields) == 1, (
            "Signature must contain exactly one output field that contains the string 'code', e.g. 'coicop_code', that indicates the classified code."
            f"Field in signature are currently: {signature.output_fields}"
        )

        self.signature = signature
        self.search_category_tool_doc = search_category_tool_doc

        self.lm = dspy.LM(
            api_key=api_key, api_base=api_base, model=model_name, **generation_kwargs
        )
        dspy.configure(lm=self.lm, track_usage=True)

        self.classification_system = classification_system
        self.store = store

        self.signature = self.signature

        self.agent = dspy.ReAct(
            self.signature,  # type: ignore
            tools=[
                dspy.Tool(
                    self.store.search_category,
                    name="search_category",
                    desc=self.search_category_tool_doc,
                )
            ],
        )

        self.output_validation = output_validation
        self.output_code_key = next(
            field for field in signature.output_fields if "code" in field
        )

    def forward(self, **kwargs: Any) -> dspy.Prediction:
        """
        Classify one item.

        The signature's input fields are checked against the keyword arguments first, so a
        misnamed field surfaces immediately instead of as an obscure failure once the
        trajectory is already running. The call is wrapped in a `dspy.context` that pins this
        module's own LM, which makes it safe to hold several classifiers with different models
        in one process.

        Parameters:
            **kwargs (Any): one keyword argument per input field of the signature.

        Returns:
            dspy.Prediction: the signature's output fields, the ReAct trajectory under `thought_{i}`, `tool_name_{i}`, `tool_args_{i}` and `observation_{i}`, and `status`.

        The `status` field says what became of the predicted code: `"valid_code"` if it is
        a code of the classification system, `"invalid_code"` if it is not (which covers a
        hallucinated code, a code written in the wrong notation, and an empty or missing
        answer alike), or `"no_validation"` when `output_validation` is off. The prediction
        is returned either way, so an unusable answer has to be filtered on rather than
        caught. When it is `"invalid_code"`, the trajectory is worth reading: it shows
        whether the agent ever saw a fitting candidate.

        Raises:
            ValueError: if an input field declared by the signature was not passed.
        """
        missing = set(self.signature.input_fields) - kwargs.keys()
        if missing:
            raise ValueError(f"Missing input fields: {sorted(missing)}")

        with dspy.context(lm=self.lm, track_usage=True):
            prediction = self.agent(**kwargs)

        if not self.output_validation:
            prediction.status = "no_validation"
            return prediction

        predicted_code = prediction.get(self.output_code_key)

        prediction.status = (
            "valid_code"
            if self.classification_system.is_valid_code(code=predicted_code)
            else "invalid_code"
        )

        return prediction

__init__

__init__(api_key, model_name, signature, search_category_tool_doc, classification_system, store, api_base=None, output_validation=True, **generation_kwargs)

Builds the LM and wraps the store's search_category into the agent's single tool.

The signature is required to declare exactly one output field whose name contains "code"; that field is what forward validates.

Note that this configures dspy globally as well as storing the LM on the instance, so constructing a second classifier with a different model changes the global default. forward pins its own LM, so already-constructed classifiers keep working.

Source code in rac4os/agents/RAG/BaseAgentRAG.py
def __init__(
    self,
    api_key: str,
    model_name: str,
    signature: type[dspy.Signature],
    search_category_tool_doc: str,
    classification_system: ClassificationSystem,
    store: Retriever,
    api_base: str | None = None,
    output_validation: bool = True,
    **generation_kwargs,
) -> None:
    """
    Builds the LM and wraps the store's `search_category` into the agent's single tool.

    The signature is required to declare exactly one output field whose name contains
    "code"; that field is what `forward` validates.

    Note that this configures `dspy` globally as well as storing the LM on the instance, so
    constructing a second classifier with a different model changes the global default.
    `forward` pins its own LM, so already-constructed classifiers keep working.
    """
    super().__init__()

    assert model_name is not None, "Please specify the generator's model name"
    assert signature is not None, (
        "Signature cannot be None, please specify a signature"
    )
    assert sum("code" in f for f in signature.output_fields) == 1, (
        "Signature must contain exactly one output field that contains the string 'code', e.g. 'coicop_code', that indicates the classified code."
        f"Field in signature are currently: {signature.output_fields}"
    )

    self.signature = signature
    self.search_category_tool_doc = search_category_tool_doc

    self.lm = dspy.LM(
        api_key=api_key, api_base=api_base, model=model_name, **generation_kwargs
    )
    dspy.configure(lm=self.lm, track_usage=True)

    self.classification_system = classification_system
    self.store = store

    self.signature = self.signature

    self.agent = dspy.ReAct(
        self.signature,  # type: ignore
        tools=[
            dspy.Tool(
                self.store.search_category,
                name="search_category",
                desc=self.search_category_tool_doc,
            )
        ],
    )

    self.output_validation = output_validation
    self.output_code_key = next(
        field for field in signature.output_fields if "code" in field
    )

forward

forward(**kwargs)

Classify one item.

The signature's input fields are checked against the keyword arguments first, so a misnamed field surfaces immediately instead of as an obscure failure once the trajectory is already running. The call is wrapped in a dspy.context that pins this module's own LM, which makes it safe to hold several classifiers with different models in one process.

Parameters:

Name Type Description Default
**kwargs Any

one keyword argument per input field of the signature.

{}

Returns:

Type Description
Prediction

dspy.Prediction: the signature's output fields, the ReAct trajectory under thought_{i}, tool_name_{i}, tool_args_{i} and observation_{i}, and status.

The status field says what became of the predicted code: "valid_code" if it is a code of the classification system, "invalid_code" if it is not (which covers a hallucinated code, a code written in the wrong notation, and an empty or missing answer alike), or "no_validation" when output_validation is off. The prediction is returned either way, so an unusable answer has to be filtered on rather than caught. When it is "invalid_code", the trajectory is worth reading: it shows whether the agent ever saw a fitting candidate.

Raises:

Type Description
ValueError

if an input field declared by the signature was not passed.

Source code in rac4os/agents/RAG/BaseAgentRAG.py
def forward(self, **kwargs: Any) -> dspy.Prediction:
    """
    Classify one item.

    The signature's input fields are checked against the keyword arguments first, so a
    misnamed field surfaces immediately instead of as an obscure failure once the
    trajectory is already running. The call is wrapped in a `dspy.context` that pins this
    module's own LM, which makes it safe to hold several classifiers with different models
    in one process.

    Parameters:
        **kwargs (Any): one keyword argument per input field of the signature.

    Returns:
        dspy.Prediction: the signature's output fields, the ReAct trajectory under `thought_{i}`, `tool_name_{i}`, `tool_args_{i}` and `observation_{i}`, and `status`.

    The `status` field says what became of the predicted code: `"valid_code"` if it is
    a code of the classification system, `"invalid_code"` if it is not (which covers a
    hallucinated code, a code written in the wrong notation, and an empty or missing
    answer alike), or `"no_validation"` when `output_validation` is off. The prediction
    is returned either way, so an unusable answer has to be filtered on rather than
    caught. When it is `"invalid_code"`, the trajectory is worth reading: it shows
    whether the agent ever saw a fitting candidate.

    Raises:
        ValueError: if an input field declared by the signature was not passed.
    """
    missing = set(self.signature.input_fields) - kwargs.keys()
    if missing:
        raise ValueError(f"Missing input fields: {sorted(missing)}")

    with dspy.context(lm=self.lm, track_usage=True):
        prediction = self.agent(**kwargs)

    if not self.output_validation:
        prediction.status = "no_validation"
        return prediction

    predicted_code = prediction.get(self.output_code_key)

    prediction.status = (
        "valid_code"
        if self.classification_system.is_valid_code(code=predicted_code)
        else "invalid_code"
    )

    return prediction

rac4os.agents.RAG.RAGAgent.RAGAgent

Bases: BaseRAGAgent

BaseRAGAgent with the bundled configurations in front of it.

CONFIGS holds a ready-made signature and search-tool description per shipped classification, so only the store, the credentials and the model have to be supplied. For your own taxonomy either add an entry to CONFIGS or construct BaseRAGAgent directly; both are the same code path.

The classification system is resolved from classification_name unless you pass a classification_system of your own, which is what lets one already-built taxonomy be shared between classifiers instead of being loaded again per classifier.

Parameters:

Name Type Description Default
classification_name str

a key of CONFIGS.

required
**kwargs Any

forwarded to BaseRAGAgent, e.g. store, api_key, model_name, output_validation, or a classification_system to use instead of the one classification_name would resolve to.

{}
Source code in rac4os/agents/RAG/RAGAgent.py
class RAGAgent(BaseRAGAgent):
    """
    `BaseRAGAgent` with the bundled configurations in front of it.

    `CONFIGS` holds a ready-made signature and search-tool description per shipped
    classification, so only the store, the credentials and the model have to be supplied.
    For your own taxonomy either add an entry to `CONFIGS` or construct `BaseRAGAgent`
    directly; both are the same code path.

    The classification system is resolved from `classification_name` unless you pass a
    `classification_system` of your own, which is what lets one already-built taxonomy be
    shared between classifiers instead of being loaded again per classifier.

    Parameters:
        classification_name (str): a key of `CONFIGS`.
        **kwargs (Any): forwarded to `BaseRAGAgent`, e.g. `store`, `api_key`, `model_name`,
            `output_validation`, or a `classification_system` to use instead of the one
            `classification_name` would resolve to.
    """

    CONFIGS = registry

    def __init__(
        self,
        classification_name: Literal[
            "COICOP_2018", "ICATUS_2016", "SEA_2021", "SEA_2021_REPHRASED"
        ],
        **kwargs,
    ) -> None:
        """
        Looks the configuration up in `CONFIGS` and hands it to the base class.

        Anything you pass yourself is forwarded unchanged, so a bundled entry can be
        overridden per call. The classification system is built from `classification_name`,
        unless one was passed in, in which case that one is used and the name only selects
        the configuration.

        Raises:
            ValueError: if `classification_name` has no entry in `CONFIGS`.
        """
        if classification_name not in self.CONFIGS:
            raise ValueError(f"Unknown classification system: {classification_name}")

        super().__init__(
            classification_system=kwargs.pop("classification_system", None)
            or get_classification_system(classification_name),
            **self.CONFIGS[classification_name],
            **kwargs,
        )

        self.classification_name = classification_name

__init__

__init__(classification_name, **kwargs)

Looks the configuration up in CONFIGS and hands it to the base class.

Anything you pass yourself is forwarded unchanged, so a bundled entry can be overridden per call. The classification system is built from classification_name, unless one was passed in, in which case that one is used and the name only selects the configuration.

Raises:

Type Description
ValueError

if classification_name has no entry in CONFIGS.

Source code in rac4os/agents/RAG/RAGAgent.py
def __init__(
    self,
    classification_name: Literal[
        "COICOP_2018", "ICATUS_2016", "SEA_2021", "SEA_2021_REPHRASED"
    ],
    **kwargs,
) -> None:
    """
    Looks the configuration up in `CONFIGS` and hands it to the base class.

    Anything you pass yourself is forwarded unchanged, so a bundled entry can be
    overridden per call. The classification system is built from `classification_name`,
    unless one was passed in, in which case that one is used and the name only selects
    the configuration.

    Raises:
        ValueError: if `classification_name` has no entry in `CONFIGS`.
    """
    if classification_name not in self.CONFIGS:
        raise ValueError(f"Unknown classification system: {classification_name}")

    super().__init__(
        classification_system=kwargs.pop("classification_system", None)
        or get_classification_system(classification_name),
        **self.CONFIGS[classification_name],
        **kwargs,
    )

    self.classification_name = classification_name

Linear RAG

rac4os.rag.BaseRAG.BaseRAGCoT

Bases: Module

Classifies an item by retrieving once and reasoning once.

The item is embedded, the k nearest categories are pulled from the retriever, serialised to JSON and placed in the signature's context field next to the item, and a dspy.ChainOfThought picks one of them. One retrieval call and one model call per item, which makes it the cheapest of the three approaches and the one to try first.

Its structural weakness is worth knowing before you choose it: retrieval happens once, on the raw item, before any reasoning. If the correct category is not among the k retrieved, no amount of generator quality recovers it. The retriever's accuracy at k is therefore a ceiling on the whole pipeline, and measuring it on its own tells you whether you have a retrieval problem or a generation problem.

The classification system is passed in even though the linear pipeline never traverses it: it is what the predicted code is validated against, and having it here means one taxonomy object can be shared by every approach instead of each loading its own.

Parameters:

Name Type Description Default
classification_system ClassificationSystem

the taxonomy to classify against, built by you or resolved from a dataset name with get_classification_system. Only the flat interface is used, so a ClassificationSystem is enough; a HierarchicalClassificationSystem is accepted and is what a registered dataset resolves to.

required
api_key str

credential for the LM provider.

required
model_name str

LiteLLM model identifier, e.g. "openai/gpt-4o-mini".

required
signature type[Signature]

the I/O contract; its docstring is the system prompt. Exactly one output field name must contain "code", which is the field the predicted code is read from.

required
query_field str

name of the signature input field that holds the item.

required
context_field str

name of the signature input field that holds the candidate list.

required
store Retriever

a filled retriever; this class never indexes.

required
api_base str | None

base URL of a self-hosted or proxied endpoint; None uses the provider's own.

None
output_validation bool

whether to check the predicted code against the classification system after each call and record the outcome on the prediction as status. Costs one dictionary lookup; turn it off only if you want the model's raw answer untouched.

True
**generation_kwargs Any

forwarded to dspy.LM, e.g. temperature, max_tokens, top_p, seed, cache or num_retries. Anything dspy.LM does not name itself is handed on to LiteLLM, so whatever your provider accepts can be set here.

{}

Attributes:

Name Type Description
classification_system ClassificationSystem

the taxonomy, also used to validate the predicted code.

output_code_key str

the single output field whose name contains "code"; the field status is derived from.

store Retriever

the retriever the candidates come from.

CoT ChainOfThought

the generation step.

lm LM

the language model configured for this module.

Source code in rac4os/rag/BaseRAG.py
class BaseRAGCoT(dspy.Module):
    """
    Classifies an item by retrieving once and reasoning once.

    The item is embedded, the k nearest categories are pulled from the retriever,
    serialised to JSON and placed in the signature's context field next to the item, and a
    `dspy.ChainOfThought` picks one of them. One retrieval call and one model call per
    item, which makes it the cheapest of the three approaches and the one to try first.

    Its structural weakness is worth knowing before you choose it: retrieval happens once,
    on the raw item, before any reasoning. If the correct category is not among the k
    retrieved, no amount of generator quality recovers it. The retriever's accuracy at k is
    therefore a ceiling on the whole pipeline, and measuring it on its own tells you
    whether you have a retrieval problem or a generation problem.

    The classification system is passed in even though the linear pipeline never
    traverses it: it is what the predicted code is validated against, and having it here
    means one taxonomy object can be shared by every approach instead of each loading
    its own.

    Parameters:
        classification_system (ClassificationSystem): the taxonomy to classify against, built by you or resolved from a dataset name with `get_classification_system`. Only the flat interface is used, so a `ClassificationSystem` is enough; a `HierarchicalClassificationSystem` is accepted and is what a registered dataset resolves to.
        api_key (str): credential for the LM provider.
        model_name (str): LiteLLM model identifier, e.g. "openai/gpt-4o-mini".
        signature (type[dspy.Signature]): the I/O contract; its docstring is the system
            prompt. Exactly one output field name must contain "code", which is the field
            the predicted code is read from.
        query_field (str): name of the signature input field that holds the item.
        context_field (str): name of the signature input field that holds the candidate list.
        store (Retriever): a filled retriever; this class never indexes.
        api_base (str|None): base URL of a self-hosted or proxied endpoint; None uses the provider's own.
        output_validation (bool): whether to check the predicted code against the classification system after each call and record the outcome on the prediction as `status`. Costs one dictionary lookup; turn it off only if you want the model's raw answer untouched.
        **generation_kwargs (Any): forwarded to `dspy.LM`, e.g. `temperature`, `max_tokens`, `top_p`, `seed`, `cache` or `num_retries`. Anything `dspy.LM` does not name itself is handed on to LiteLLM, so whatever your provider accepts can be set here.

    Attributes:
        classification_system (ClassificationSystem): the taxonomy, also used to validate
            the predicted code.
        output_code_key (str): the single output field whose name contains "code"; the field `status` is derived from.
        store (Retriever): the retriever the candidates come from.
        CoT (dspy.ChainOfThought): the generation step.
        lm (dspy.LM): the language model configured for this module.
    """

    def __init__(
        self,
        classification_system: ClassificationSystem,
        api_key: str,
        model_name: str,
        signature: type[dspy.Signature],
        query_field: str,
        context_field: str,
        store: Retriever,
        api_base: str | None = None,
        output_validation: bool = True,
        **generation_kwargs,
    ) -> None:
        """
        Builds the LM, loads the classification system and the chain-of-thought step.

        `query_field` and `context_field` are asserted against the signature's declared input
        fields, and the signature is required to declare exactly one output field whose name
        contains "code", so a name that does not exist fails here rather than at the first
        call.

        Unlike the agentic classifiers, `forward` does not pin an LM per call: this module
        relies on the global `dspy.configure` made here. If you run several classifiers with
        different models in one process, construct each one immediately before use.
        """
        assert model_name is not None
        assert query_field is not None
        assert context_field is not None
        assert query_field in list(signature.input_fields.keys())
        assert context_field in list(signature.input_fields.keys())
        assert sum("code" in f for f in signature.output_fields) == 1, (
            "Signature must contain exactly one output field that contains the string 'code', e.g. 'coicop_code', that indicates the classified code."
            f"Field in signature are currently: {signature.output_fields}"
        )

        self.signature: type[dspy.Signature] = signature
        self.query_field = query_field
        self.context_field = context_field

        self.lm = dspy.LM(
            api_key=api_key, api_base=api_base, model=model_name, **generation_kwargs
        )
        dspy.configure(lm=self.lm, track_usage=True)

        self.classification_system = classification_system

        self.store = store

        self.CoT = dspy.ChainOfThought(
            signature=self.signature  # type: ignore
        )

        self.output_validation = output_validation
        self.output_code_key = next(
            field for field in self.signature.output_fields if "code" in field
        )

    def forward(self, query: str, k: int, where: dict | None = None) -> dspy.Prediction:
        """
        Retrieve candidates for one item and classify it over them.

        Parameters:
            query (str): the item to classify, used both as the retrieval query and as the item the generator sees.
            k (int): how many candidates to retrieve. Raising it makes the correct category more likely to be present and gives the model more chances to pick a wrong one, and it spends context that competes with how richly each candidate is described.
            where (dict|None): metadata filter passed straight to the store, e.g. `{"level": 3}` to retrieve only one level. Matches the metadata as your loader emitted it, so a level that left the loader as a string has to be filtered as one.

        Returns:
            dspy.Prediction: the signature's output fields, `reasoning` from the chain of thought, and `status`.

        The `status` field says what became of the predicted code: `"valid_code"` if it is
        a code of the classification system, `"invalid_code"` if it is not (which covers a
        hallucinated code, a code written in the wrong notation, and an empty or missing
        answer alike), or `"no_validation"` when `output_validation` is off. The prediction
        is returned either way, so an unusable answer has to be filtered on rather than
        caught.
        """
        retrieved_context = self.store.search_category(query, k, where=where)
        retrieved_context_str = json.dumps(
            retrieved_context, indent=4, ensure_ascii=False
        )

        prediction = self.CoT(
            **{
                self.query_field: query,
                self.context_field: retrieved_context_str,
            }
        )

        if not self.output_validation:
            prediction.status = "no_validation"
            return prediction

        predicted_code = prediction.get(self.output_code_key)

        prediction.status = (
            "valid_code"
            if self.classification_system.is_valid_code(code=predicted_code)
            else "invalid_code"
        )

        return prediction

__init__

__init__(classification_system, api_key, model_name, signature, query_field, context_field, store, api_base=None, output_validation=True, **generation_kwargs)

Builds the LM, loads the classification system and the chain-of-thought step.

query_field and context_field are asserted against the signature's declared input fields, and the signature is required to declare exactly one output field whose name contains "code", so a name that does not exist fails here rather than at the first call.

Unlike the agentic classifiers, forward does not pin an LM per call: this module relies on the global dspy.configure made here. If you run several classifiers with different models in one process, construct each one immediately before use.

Source code in rac4os/rag/BaseRAG.py
def __init__(
    self,
    classification_system: ClassificationSystem,
    api_key: str,
    model_name: str,
    signature: type[dspy.Signature],
    query_field: str,
    context_field: str,
    store: Retriever,
    api_base: str | None = None,
    output_validation: bool = True,
    **generation_kwargs,
) -> None:
    """
    Builds the LM, loads the classification system and the chain-of-thought step.

    `query_field` and `context_field` are asserted against the signature's declared input
    fields, and the signature is required to declare exactly one output field whose name
    contains "code", so a name that does not exist fails here rather than at the first
    call.

    Unlike the agentic classifiers, `forward` does not pin an LM per call: this module
    relies on the global `dspy.configure` made here. If you run several classifiers with
    different models in one process, construct each one immediately before use.
    """
    assert model_name is not None
    assert query_field is not None
    assert context_field is not None
    assert query_field in list(signature.input_fields.keys())
    assert context_field in list(signature.input_fields.keys())
    assert sum("code" in f for f in signature.output_fields) == 1, (
        "Signature must contain exactly one output field that contains the string 'code', e.g. 'coicop_code', that indicates the classified code."
        f"Field in signature are currently: {signature.output_fields}"
    )

    self.signature: type[dspy.Signature] = signature
    self.query_field = query_field
    self.context_field = context_field

    self.lm = dspy.LM(
        api_key=api_key, api_base=api_base, model=model_name, **generation_kwargs
    )
    dspy.configure(lm=self.lm, track_usage=True)

    self.classification_system = classification_system

    self.store = store

    self.CoT = dspy.ChainOfThought(
        signature=self.signature  # type: ignore
    )

    self.output_validation = output_validation
    self.output_code_key = next(
        field for field in self.signature.output_fields if "code" in field
    )

forward

forward(query, k, where=None)

Retrieve candidates for one item and classify it over them.

Parameters:

Name Type Description Default
query str

the item to classify, used both as the retrieval query and as the item the generator sees.

required
k int

how many candidates to retrieve. Raising it makes the correct category more likely to be present and gives the model more chances to pick a wrong one, and it spends context that competes with how richly each candidate is described.

required
where dict | None

metadata filter passed straight to the store, e.g. {"level": 3} to retrieve only one level. Matches the metadata as your loader emitted it, so a level that left the loader as a string has to be filtered as one.

None

Returns:

Type Description
Prediction

dspy.Prediction: the signature's output fields, reasoning from the chain of thought, and status.

The status field says what became of the predicted code: "valid_code" if it is a code of the classification system, "invalid_code" if it is not (which covers a hallucinated code, a code written in the wrong notation, and an empty or missing answer alike), or "no_validation" when output_validation is off. The prediction is returned either way, so an unusable answer has to be filtered on rather than caught.

Source code in rac4os/rag/BaseRAG.py
def forward(self, query: str, k: int, where: dict | None = None) -> dspy.Prediction:
    """
    Retrieve candidates for one item and classify it over them.

    Parameters:
        query (str): the item to classify, used both as the retrieval query and as the item the generator sees.
        k (int): how many candidates to retrieve. Raising it makes the correct category more likely to be present and gives the model more chances to pick a wrong one, and it spends context that competes with how richly each candidate is described.
        where (dict|None): metadata filter passed straight to the store, e.g. `{"level": 3}` to retrieve only one level. Matches the metadata as your loader emitted it, so a level that left the loader as a string has to be filtered as one.

    Returns:
        dspy.Prediction: the signature's output fields, `reasoning` from the chain of thought, and `status`.

    The `status` field says what became of the predicted code: `"valid_code"` if it is
    a code of the classification system, `"invalid_code"` if it is not (which covers a
    hallucinated code, a code written in the wrong notation, and an empty or missing
    answer alike), or `"no_validation"` when `output_validation` is off. The prediction
    is returned either way, so an unusable answer has to be filtered on rather than
    caught.
    """
    retrieved_context = self.store.search_category(query, k, where=where)
    retrieved_context_str = json.dumps(
        retrieved_context, indent=4, ensure_ascii=False
    )

    prediction = self.CoT(
        **{
            self.query_field: query,
            self.context_field: retrieved_context_str,
        }
    )

    if not self.output_validation:
        prediction.status = "no_validation"
        return prediction

    predicted_code = prediction.get(self.output_code_key)

    prediction.status = (
        "valid_code"
        if self.classification_system.is_valid_code(code=predicted_code)
        else "invalid_code"
    )

    return prediction

rac4os.rag.RAG.RAGChainOfThought

Bases: BaseRAGCoT

BaseRAGCoT with the bundled configurations in front of it.

CONFIGS holds a signature and the two field names per shipped classification, so only the store, the credentials and the model have to be supplied. For your own taxonomy either add an entry to CONFIGS or construct BaseRAGCoT directly and pass the signature and field names yourself; both are the same code path.

The classification system is resolved from classification_name unless you pass a classification_system of your own, which is what lets one already-built taxonomy be shared between classifiers instead of being loaded again per classifier.

Parameters:

Name Type Description Default
classification_name str

a key of CONFIGS.

required
**kwargs Any

forwarded to BaseRAGCoT, e.g. store, api_key, model_name, output_validation, or a classification_system to use instead of the one classification_name would resolve to.

{}
Source code in rac4os/rag/RAG.py
class RAGChainOfThought(BaseRAGCoT):
    """
    `BaseRAGCoT` with the bundled configurations in front of it.

    `CONFIGS` holds a signature and the two field names per shipped classification, so only
    the store, the credentials and the model have to be supplied. For your own taxonomy
    either add an entry to `CONFIGS` or construct `BaseRAGCoT` directly and pass the
    signature and field names yourself; both are the same code path.

    The classification system is resolved from `classification_name` unless you pass a
    `classification_system` of your own, which is what lets one already-built taxonomy be
    shared between classifiers instead of being loaded again per classifier.

    Parameters:
        classification_name (str): a key of `CONFIGS`.
        **kwargs (Any): forwarded to `BaseRAGCoT`, e.g. `store`, `api_key`, `model_name`,
            `output_validation`, or a `classification_system` to use instead of the one
            `classification_name` would resolve to.
    """

    CONFIGS = {  # noqa: RUF012
        "COICOP_2018": {
            "signature": registry.CoicopRAGChainOfThoughtSignature,
            "query_field": "input_expense",
            "context_field": "retrieved_candidates",
        },
        "ICATUS_2016": {
            "signature": registry.IcatusRAGChainOfThoughtSignature,
            "query_field": "input_activity",
            "context_field": "retrieved_candidates",
        },
        "SEA_2021": {
            "signature": registry.SeaRAGChainOfThoughtSignature,
            "query_field": "input_expense",
            "context_field": "retrieved_candidates",
        },
        "SEA_2021_REPHRASED": {
            "signature": registry.SeaRAGChainOfThoughtSignature,
            "query_field": "input_expense",
            "context_field": "retrieved_candidates",
        },
    }

    def __init__(
        self,
        classification_name: Literal[
            "COICOP_2018", "ICATUS_2016", "SEA_2021", "SEA_2021_REPHRASED"
        ],
        **kwargs,
    ) -> None:
        """
        Looks the configuration up in `CONFIGS` and hands it to `BaseRAGCoT`.

        Anything you pass yourself is forwarded unchanged, so a bundled signature or field name
        can be overridden per call. The classification system is built from
        `classification_name`, unless one was passed in, in which case that one is used and
        the name only selects the configuration.

        Raises:
            ValueError: if `classification_name` has no entry in `CONFIGS`.
        """
        if classification_name not in self.CONFIGS:
            raise ValueError(f"Unknown classification system: {classification_name}")

        super().__init__(
            classification_system=kwargs.pop("classification_system", None)
            or get_classification_system(classification_name),
            **self.CONFIGS[classification_name],
            **kwargs,
        )
        self.classification_name = classification_name

__init__

__init__(classification_name, **kwargs)

Looks the configuration up in CONFIGS and hands it to BaseRAGCoT.

Anything you pass yourself is forwarded unchanged, so a bundled signature or field name can be overridden per call. The classification system is built from classification_name, unless one was passed in, in which case that one is used and the name only selects the configuration.

Raises:

Type Description
ValueError

if classification_name has no entry in CONFIGS.

Source code in rac4os/rag/RAG.py
def __init__(
    self,
    classification_name: Literal[
        "COICOP_2018", "ICATUS_2016", "SEA_2021", "SEA_2021_REPHRASED"
    ],
    **kwargs,
) -> None:
    """
    Looks the configuration up in `CONFIGS` and hands it to `BaseRAGCoT`.

    Anything you pass yourself is forwarded unchanged, so a bundled signature or field name
    can be overridden per call. The classification system is built from
    `classification_name`, unless one was passed in, in which case that one is used and
    the name only selects the configuration.

    Raises:
        ValueError: if `classification_name` has no entry in `CONFIGS`.
    """
    if classification_name not in self.CONFIGS:
        raise ValueError(f"Unknown classification system: {classification_name}")

    super().__init__(
        classification_system=kwargs.pop("classification_system", None)
        or get_classification_system(classification_name),
        **self.CONFIGS[classification_name],
        **kwargs,
    )
    self.classification_name = classification_name

Rephrase-Retrieve-Respond

rac4os.rag.RAG.QueryRephraser

Bases: Module

Rewrites a raw item into a retrieval query in the vocabulary of the classification's labels. It does not classify.

Picks the rephrasing signature for classification_name from self.mapping and runs it on its own lm, which can be the same LM as the Respond step or a smaller, cheaper one.

Called as rephraser(query=...); returns a dspy.Prediction with rephrased_query. The input field name of the signature (input_expense / input_activity) is handled internally, so callers never need to know it.

Source code in rac4os/rag/RAG.py
class QueryRephraser(dspy.Module):
    """
    Rewrites a raw item into a retrieval query in the vocabulary of the
    classification's labels. It does not classify.

    Picks the rephrasing signature for `classification_name` from
    `self.mapping` and runs it on its own `lm`, which can be the same LM as
    the Respond step or a smaller, cheaper one.

    Called as `rephraser(query=...)`; returns a `dspy.Prediction` with
    `rephrased_query`. The input field name of the signature
    (`input_expense` / `input_activity`) is handled internally, so callers
    never need to know it.
    """

    def __init__(
        self,
        lm: dspy.LM,
        classification_name: str | None,
        signature: type[dspy.Signature] | None = None,
    ) -> None:
        """
        Picks the rephrasing signature and builds the one-shot predictor that runs it.

        Either `classification_name` must be a key of the internal mapping or an explicit
        `signature` must be given; passing `classification_name=None` together with your own
        signature is how you rephrase for a taxonomy that is not bundled. The signature's first
        input field is read off here, so callers never have to know what it is called.

        Raises:
            AssertionError: if neither a known classification name nor a signature was given.
        """
        super().__init__()
        self.lm = lm
        self.mapping = {
            "COICOP_2018": registry.CoicopRephrasingSignature,
            "ICATUS_2016": registry.IcatusRephrasingSignature,
            "SEA_2021": registry.SeaRephrasingSignature,
            "SEA_2021_REPHRASED": registry.SeaRephrasingSignature,
        }

        assert classification_name in self.mapping or signature is not None, (
            f"No rephrasing signature for '{classification_name}'"
        )

        self.classification_name = classification_name
        self.signature = self.mapping.get(classification_name, signature)

        self.input_field = next(iter(self.signature.input_fields))
        self.rephrase = dspy.Predict(self.signature)

    def forward(self, query: str) -> dspy.Prediction:
        """
        Rewrite one item into a retrieval query.

        Runs on this module's own LM through a `dspy.context`, so the rewrite can use a smaller
        and cheaper model than the classification step. An empty rewrite falls back to the
        original item, so the pipeline can never end up retrieving on an empty query.

        Parameters:
            query (str): the raw item.

        Returns:
            dspy.Prediction: carries `rephrased_query`; the original item if the rewrite came back empty.
        """
        with dspy.context(lm=self.lm):
            prediction = self.rephrase(**{self.input_field: query})
        rephrased = (prediction.rephrased_query or "").strip()
        return dspy.Prediction(rephrased_query=rephrased or query)

__init__

__init__(lm, classification_name, signature=None)

Picks the rephrasing signature and builds the one-shot predictor that runs it.

Either classification_name must be a key of the internal mapping or an explicit signature must be given; passing classification_name=None together with your own signature is how you rephrase for a taxonomy that is not bundled. The signature's first input field is read off here, so callers never have to know what it is called.

Raises:

Type Description
AssertionError

if neither a known classification name nor a signature was given.

Source code in rac4os/rag/RAG.py
def __init__(
    self,
    lm: dspy.LM,
    classification_name: str | None,
    signature: type[dspy.Signature] | None = None,
) -> None:
    """
    Picks the rephrasing signature and builds the one-shot predictor that runs it.

    Either `classification_name` must be a key of the internal mapping or an explicit
    `signature` must be given; passing `classification_name=None` together with your own
    signature is how you rephrase for a taxonomy that is not bundled. The signature's first
    input field is read off here, so callers never have to know what it is called.

    Raises:
        AssertionError: if neither a known classification name nor a signature was given.
    """
    super().__init__()
    self.lm = lm
    self.mapping = {
        "COICOP_2018": registry.CoicopRephrasingSignature,
        "ICATUS_2016": registry.IcatusRephrasingSignature,
        "SEA_2021": registry.SeaRephrasingSignature,
        "SEA_2021_REPHRASED": registry.SeaRephrasingSignature,
    }

    assert classification_name in self.mapping or signature is not None, (
        f"No rephrasing signature for '{classification_name}'"
    )

    self.classification_name = classification_name
    self.signature = self.mapping.get(classification_name, signature)

    self.input_field = next(iter(self.signature.input_fields))
    self.rephrase = dspy.Predict(self.signature)

forward

forward(query)

Rewrite one item into a retrieval query.

Runs on this module's own LM through a dspy.context, so the rewrite can use a smaller and cheaper model than the classification step. An empty rewrite falls back to the original item, so the pipeline can never end up retrieving on an empty query.

Parameters:

Name Type Description Default
query str

the raw item.

required

Returns:

Type Description
Prediction

dspy.Prediction: carries rephrased_query; the original item if the rewrite came back empty.

Source code in rac4os/rag/RAG.py
def forward(self, query: str) -> dspy.Prediction:
    """
    Rewrite one item into a retrieval query.

    Runs on this module's own LM through a `dspy.context`, so the rewrite can use a smaller
    and cheaper model than the classification step. An empty rewrite falls back to the
    original item, so the pipeline can never end up retrieving on an empty query.

    Parameters:
        query (str): the raw item.

    Returns:
        dspy.Prediction: carries `rephrased_query`; the original item if the rewrite came back empty.
    """
    with dspy.context(lm=self.lm):
        prediction = self.rephrase(**{self.input_field: query})
    rephrased = (prediction.rephrased_query or "").strip()
    return dspy.Prediction(rephrased_query=rephrased or query)

rac4os.rag.RAG.RRR_RAGChainOfThought

Bases: RAGChainOfThought

Rephrase-Retrieve-Respond on top of RAGChainOfThought.

  1. Rephrase - self.rephrasing_module (a QueryRephraser) turns the raw item into a query in the vocabulary of the classification's labels.
  2. Retrieve - the rephrased query is embedded and the k nearest codes are pulled from the vector store.
  3. Respond - the parent's ChainOfThought classifies the ORIGINAL item over the retrieved candidates. The rephrasing only steers retrieval; it never replaces the item the model has to classify, so detail the rephraser dropped is not lost.

Parameters (on top of RAGChainOfThought): rephraser (QueryRephraser) - the Rephrase step, with its own LM and prompt. The two steps are configured independently: **generation_kwargs passed here reach the Respond step, while the Rephrase step takes its settings from the dspy.LM given to the rephraser.

Source code in rac4os/rag/RAG.py
class RRR_RAGChainOfThought(RAGChainOfThought):
    """
    Rephrase-Retrieve-Respond on top of `RAGChainOfThought`.

    1. Rephrase - `self.rephrasing_module` (a `QueryRephraser`) turns the raw
       item into a query in the vocabulary of the classification's labels.
    2. Retrieve - the rephrased query is embedded and the k nearest codes are
       pulled from the vector store.
    3. Respond - the parent's ChainOfThought classifies the ORIGINAL item over
       the retrieved candidates. The rephrasing only steers retrieval; it never
       replaces the item the model has to classify, so detail the rephraser
       dropped is not lost.

    Parameters (on top of `RAGChainOfThought`):
        rephraser (QueryRephraser) - the Rephrase step, with its own LM and prompt. The
            two steps are configured independently: `**generation_kwargs` passed here
            reach the Respond step, while the Rephrase step takes its settings from the
            `dspy.LM` given to the rephraser.
    """

    def __init__(
        self,
        rephraser: QueryRephraser,
        *args,
        **kwargs,
    ) -> None:
        """
        Builds the linear pipeline and puts the Rephrase step in front of it.

        Parameters:
            rephraser (QueryRephraser): the Rephrase step.
            *args (Any): forwarded to `RAGChainOfThought`.
            **kwargs (Any): forwarded to `RAGChainOfThought`, e.g. `classification_name`, `store`, `api_key`, `model_name`.
        """
        super().__init__(*args, **kwargs)

        self.rephrasing_module = rephraser

    def forward(self, query: str, k: int, where: dict | None = None) -> dspy.Prediction:
        """
        Rewrite the item, retrieve on the rewritten query, then classify the original item.

        The rewrite steers retrieval only. The generator still sees the item as it came in, so
        detail the rephraser dropped cannot be lost from the decision itself. The query that
        was actually retrieved on is attached to the prediction as `rephrased_query`, which is
        what you inspect when a result looks wrong: it separates a bad rewrite from a bad
        choice among good candidates.

        Parameters:
            query (str): the item to classify.
            k (int): how many candidates to retrieve.
            where (dict|None): metadata filter passed straight to the store.

        Returns:
            dspy.Prediction: the signature's output fields, `reasoning`, `rephrased_query`, and `status`.

        `status` is set exactly as in `BaseRAGCoT.forward`. Read it together with
        `rephrased_query`: an `"invalid_code"` next to a rewrite that drifted away from the
        item points at the Rephrase step, not at the generator.
        """
        rephrased_query = self.rephrasing_module(query=query).rephrased_query
        retrieved_context = self.store.search_category(rephrased_query, k, where=where)
        retrieved_context_str = json.dumps(
            retrieved_context, indent=4, ensure_ascii=False
        )
        with dspy.context(lm=self.lm, track_usage=True):
            prediction = self.CoT(
                **{
                    self.query_field: query,
                    self.context_field: retrieved_context_str,
                }
            )
        # Keep the rewritten query for logging and info later
        prediction.rephrased_query = rephrased_query

        if not self.output_validation:
            prediction.status = "no_validation"
            return prediction

        predicted_code = prediction.get(self.output_code_key)

        prediction.status = (
            "valid_code"
            if self.classification_system.is_valid_code(code=predicted_code)
            else "invalid_code"
        )

        return prediction

__init__

__init__(rephraser, *args, **kwargs)

Builds the linear pipeline and puts the Rephrase step in front of it.

Parameters:

Name Type Description Default
rephraser QueryRephraser

the Rephrase step.

required
*args Any

forwarded to RAGChainOfThought.

()
**kwargs Any

forwarded to RAGChainOfThought, e.g. classification_name, store, api_key, model_name.

{}
Source code in rac4os/rag/RAG.py
def __init__(
    self,
    rephraser: QueryRephraser,
    *args,
    **kwargs,
) -> None:
    """
    Builds the linear pipeline and puts the Rephrase step in front of it.

    Parameters:
        rephraser (QueryRephraser): the Rephrase step.
        *args (Any): forwarded to `RAGChainOfThought`.
        **kwargs (Any): forwarded to `RAGChainOfThought`, e.g. `classification_name`, `store`, `api_key`, `model_name`.
    """
    super().__init__(*args, **kwargs)

    self.rephrasing_module = rephraser

forward

forward(query, k, where=None)

Rewrite the item, retrieve on the rewritten query, then classify the original item.

The rewrite steers retrieval only. The generator still sees the item as it came in, so detail the rephraser dropped cannot be lost from the decision itself. The query that was actually retrieved on is attached to the prediction as rephrased_query, which is what you inspect when a result looks wrong: it separates a bad rewrite from a bad choice among good candidates.

Parameters:

Name Type Description Default
query str

the item to classify.

required
k int

how many candidates to retrieve.

required
where dict | None

metadata filter passed straight to the store.

None

Returns:

Type Description
Prediction

dspy.Prediction: the signature's output fields, reasoning, rephrased_query, and status.

status is set exactly as in BaseRAGCoT.forward. Read it together with rephrased_query: an "invalid_code" next to a rewrite that drifted away from the item points at the Rephrase step, not at the generator.

Source code in rac4os/rag/RAG.py
def forward(self, query: str, k: int, where: dict | None = None) -> dspy.Prediction:
    """
    Rewrite the item, retrieve on the rewritten query, then classify the original item.

    The rewrite steers retrieval only. The generator still sees the item as it came in, so
    detail the rephraser dropped cannot be lost from the decision itself. The query that
    was actually retrieved on is attached to the prediction as `rephrased_query`, which is
    what you inspect when a result looks wrong: it separates a bad rewrite from a bad
    choice among good candidates.

    Parameters:
        query (str): the item to classify.
        k (int): how many candidates to retrieve.
        where (dict|None): metadata filter passed straight to the store.

    Returns:
        dspy.Prediction: the signature's output fields, `reasoning`, `rephrased_query`, and `status`.

    `status` is set exactly as in `BaseRAGCoT.forward`. Read it together with
    `rephrased_query`: an `"invalid_code"` next to a rewrite that drifted away from the
    item points at the Rephrase step, not at the generator.
    """
    rephrased_query = self.rephrasing_module(query=query).rephrased_query
    retrieved_context = self.store.search_category(rephrased_query, k, where=where)
    retrieved_context_str = json.dumps(
        retrieved_context, indent=4, ensure_ascii=False
    )
    with dspy.context(lm=self.lm, track_usage=True):
        prediction = self.CoT(
            **{
                self.query_field: query,
                self.context_field: retrieved_context_str,
            }
        )
    # Keep the rewritten query for logging and info later
    prediction.rephrased_query = rephrased_query

    if not self.output_validation:
        prediction.status = "no_validation"
        return prediction

    predicted_code = prediction.get(self.output_code_key)

    prediction.status = (
        "valid_code"
        if self.classification_system.is_valid_code(code=predicted_code)
        else "invalid_code"
    )

    return prediction