Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions docs/user-guides/community/xgb.md
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you have a link to information about how this model was trained? What is the F1 score on various spam datasets?

I would like to see some information like what is presented about the jailbreak heuristics and ideally, the model should be hosted on something like HuggingFace alongside a model card.

Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# XGB Detectors Integration

XGB Detectors utilizes [XGBoost machine learning models](https://xgboost.readthedocs.io/en/stable/tutorials/model.html) to detect harmful content in data. Currently, only
the spam text detector, trained by the [Red Hat TrustyAI team](https://github.com/trustyai-explainability), is available for guardrailing use.
Comment on lines +3 to +4
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest a different name, such as spam_detection instead of XGB -- there are other detectors that may use XGBoost models. For example, jailbreak uses a random forest model and XGB was one of the considered architectures.


## Setup

Update your `config.yaml` file to include XGB detectors:

**Spam detection config**
```
rails:
config:
xgb:
input:
detectors:
- SPAM
output:
detectors:
- SPAM
input:
flows:
- xgb detect on input
output:
flows:
- xgb detect on output
```
The detection flow will not let the input and output text pass if spam is detected.

## Usage

Once configured, the XGB Guardrails integration will automatically:

1. Detect spam in inputs to the LLM
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I understand the harm of spam being input to the LLM is? Assuming that we are using the common definition of spam as unsolicited bulk email/messaging, I don't know what harmful behavior we're looking to prevent here.

I suppose I can accept that detecting spam in outputs from the LLM might be desirable from the perspective of not wanting to have your system used to generate spam emails? I would be concerned about the FPR on this model, specifically as it pertains to the use of LLMs to generate e.g. messages for marketing or others. It would be helpful to have a model card linked in this doc.

3. Detect spam in outputs from the LLM
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
3. Detect spam in outputs from the LLM
2. Detect spam in outputs from the LLM


## Error Handling

If the inference request to the XGB spam model fails, the system will assume spam is present as a precautionary measure.

## Notes

For more information on TrustyAI and its projects, please visit the TrustyAI [documentation](https://trustyai.org/docs/main/main).
19 changes: 19 additions & 0 deletions examples/configs/xgb/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
models:
- type: main
engine: hf_pipeline_gpt2
model: "openai-community/gpt2"
rails:
config:
xgb:
input:
detectors:
- SPAM
output:
detectors:
- SPAM
input:
flows:
- xgb detect on input
output:
flows:
- xgb detect on output
14 changes: 14 additions & 0 deletions nemoguardrails/library/xgb/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
56 changes: 56 additions & 0 deletions nemoguardrails/library/xgb/actions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from nemoguardrails.actions import action
from nemoguardrails.library.xgb.inference import xgb_inference
from nemoguardrails.rails.llm.config import RailsConfig


@action()
async def xgb_detect(
source: str,
text: str,
config: RailsConfig,
**kwargs,
):
xgb_config = getattr(config.rails.config, "xgb")
source_config = getattr(xgb_config, source)

enabled_detectors = getattr(source_config, "detectors", None)
if enabled_detectors is None:
raise ValueError(
f"Could not find 'detectors' in source_config: {source_config}"
)
valid_detectors = ["SPAM"]
for detector in enabled_detectors:
if detector not in valid_detectors:
raise ValueError(
f"XGB detectors can only be defined in the following detectors: {valid_detectors}. "
f"The current detector, '{detector}' is not allowed."
)

valid_sources = ["input", "output"]
if source not in valid_sources:
raise ValueError(
f"XGB detectors can only be defined in the following flows: {valid_sources}. "
f"The current flow, '{source} is not allowed."
)

xgb_response = xgb_inference(
text,
enabled_detectors,
)

return xgb_response
21 changes: 21 additions & 0 deletions nemoguardrails/library/xgb/flows.co
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#### XGB DETECTION RAILS ####

# INPUT RAILS

flow xgb detect on input
"""Check if the user content has harmful content"
$detection = await XGBDetectAction(source="input", text=$user_message)

if $detection
bot inform answer unknown
Comment on lines +9 to +10
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure that this is a particularly helpful response. In both cases, I'd think you would want to provide something more informative.
See the jailbreak flows for an example.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment also applies to the output rail.

abort

# OUTPUT RAILS

flow xgb detect on output
"""Check if the bot output has harmful content"
$detection = await XGBDetectAction(source="output", text=$bot_message)

if $detection
bot inform answer unknown
abort
18 changes: 18 additions & 0 deletions nemoguardrails/library/xgb/flows.v1.co
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#### XGB DETECTION RAILS ####

# INPUT RAILS

define subflow xgb detect on input
$detection = execute xgb_detect(source="input", text=$user_message)

if $detection
bot inform answer unknown
Comment on lines +8 to +9
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As with the v2 flows, this response is not particularly helpful and I would suggest having a different message. The same notion applies to the output rail.

stop

# OUTPUT RAILS
define subflow xgb detect on output
$detection = execute xgb_detect(source="output", text=$user_message)

if $detection
bot inform answer unknown
stop
64 changes: 64 additions & 0 deletions nemoguardrails/library/xgb/inference.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import pickle
from typing import List

log = logging.getLogger(__name__)
MODEL_REGISTRY = {
"SPAM": {
"model_path": "nemoguardrails/library/xgb/model_artifacts/model.pkl",
"vectorizer_path": "nemoguardrails/library/xgb/model_artifacts/vectorizer.pkl",
}
}


def xgb_inference(text: str, enabled_detectors: List[str]):
detections = []
for detector in enabled_detectors:
model_info = MODEL_REGISTRY.get(detector)
if not model_info:
raise ValueError(
f"XGB detector '{detector}' is not configured in the MODEL_REGISTRY."
)
model_path = model_info["model_path"]
vectorizer_path = model_info["vectorizer_path"]
with open(model_path, "rb") as f:
model = pickle.load(f)
with open(vectorizer_path, "rb") as f:
vectorizer = pickle.load(f)

try:
X_vec = vectorizer.transform([text])
prediction = model.predict(X_vec)[0]
probability = model.predict_proba(X_vec)[0]

is_safe = prediction == 0
confidence = max(probability)

detections.append(
{
"allowed": bool(is_safe),
"score": float(confidence),
"prediction": "safe" if is_safe else detector,
}
)

except Exception as e:
raise ValueError(
f"Error during XGBoost inference for detector '{detector}': {e}"
)
return detections
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this model currently on something like Huggingface? I'm very much against including the pickle files in the repo itself and it's important to have a model card and version control for the model itself that is independent of the guardrails git repository.

Same comment applies to the vectorizer pickle file.

Binary file not shown.
Binary file not shown.
27 changes: 27 additions & 0 deletions nemoguardrails/rails/llm/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,28 @@ class FiddlerGuardrails(BaseModel):
)


class XGBDetectors(BaseModel):
"""Configuration for XGBoost detectors."""

detectors: List[str] = Field(
default_factory=list,
description="The list of detectors to use.",
)


class XGBDetection(BaseModel):
"""Configuration for XGBoost detectors."""

input: Optional[XGBDetectors] = Field(
default_factory=XGBDetectors,
description="XGBoost configuration for an Input Guardrail",
)
output: Optional[XGBDetectors] = Field(
default_factory=XGBDetectors,
description="XGBoost configuration for an Output Guardrail",
)


class MessageTemplate(BaseModel):
"""Template for a message structure."""

Expand Down Expand Up @@ -805,6 +827,11 @@ class RailsConfigData(BaseModel):
description="Configuration for Clavata.",
)

xgb: Optional[XGBDetection] = Field(
default_factory=XGBDetection,
description="Configuration for XGBoost Guardrails.",
)


class Rails(BaseModel):
"""Configuration of specific rails."""
Expand Down
7 changes: 6 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ repository = "https://github.com/NVIDIA/NeMo-Guardrails"
nemoguardrails = "nemoguardrails.__main__:app"

[tool.poetry.dependencies]
python = ">=3.9,!=3.9.7,<3.14"
python = ">=3.10,!=3.9.7,<3.14"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a really significant change. Although Python 3.9 is EOL, dropping support for an entire Python version is not something that should be done without significant regression testing.

aiohttp = ">=3.10.11"
annoy = ">=1.17.3"
fastapi = ">=0.103.0,"
Expand Down Expand Up @@ -101,6 +101,11 @@ google-cloud-language = { version = ">=2.14.0", optional = true }
# jailbreak injection
yara-python = { version = "^4.5.1", optional = true }

# xgb
xgboost = "^3.0.2"
scikit-learn = "^1.7.1"
huggingface-hub = "^0.34.3"

[tool.poetry.extras]
sdd = ["presidio-analyzer", "presidio-anonymizer"]
eval = ["tqdm", "numpy", "streamlit", "tornado"]
Expand Down
Loading
Loading