tryolabs / restricttotopic

Validator for GuardrailsHub to check if a text is related with a topic.
Apache License 2.0
1 stars 5 forks source link

Overview

| Developed by | Tryolabs | | Date of development | Feb 15, 2024 | | Validator type | Format | | Blog | | | License | Apache 2 | | Input/Output | Output |

Description

Intended Use

This validator checks if a text is related with a topic.

Requirements

Installation

$ guardrails hub install hub://tryolabs/restricttotopic

Usage Examples

Validating string output via Python

In this example, we apply the validator to a string output generated by an LLM.

# Import Guard and Validator
from guardrails.hub import RestrictToTopic
from guardrails import Guard

# Setup Guard
guard = Guard().use(
    RestrictToTopic(
        valid_topics=["sports"],
        invalid_topics=["music"],
        disable_classifier=True,
        disable_llm=False,
        on_fail="exception"
    )
)

guard.validate("""
In Super Bowl LVII in 2023, the Chiefs clashed with the Philadelphia Eagles in a fiercely contested battle, ultimately emerging victorious with a score of 38-35.
""")  # Validator passes

guard.validate("""
The Beatles were a charismatic English pop-rock band of the 1960s.
""")  # Validator fails

Validating JSON output via Python

In this example, we apply the validator to a string field of a JSON output generated by an LLM.

# Import Guard and Validator
from pydantic import BaseModel, Field
from guardrails.hub import RestrictToTopic
from guardrails import Guard

# Initialize Validator
val = RestrictToTopic(
    valid_topics=["sports"],
    disable_classifier=True,
    disable_llm=False,
    on_fail="exception"
)

# Create Pydantic BaseModel
class TopicSummary(BaseModel):
        topic: str
        summary: str = Field(validators=[val])

# Create a Guard to check for valid Pydantic output
guard = Guard.from_pydantic(output_class=TopicSummary)

# Run LLM output generating JSON through guard
guard.parse("""
{
    "topic": "Super Bowl LVII",
    "summary": "In Super Bowl LVII in 2023, the Chiefs clashed with the Philadelphia Eagles in a fiercely contested battle, ultimately emerging victorious with a score of 38-35."
}
""")

API Reference

__init__(self, on_fail="noop")


validate(self, value, metadata) -> ValidationResult