{"id":28429369,"url":"https://github.com/tryolabs/restricttotopic","last_synced_at":"2025-09-08T00:37:20.403Z","repository":{"id":219150112,"uuid":"747706231","full_name":"tryolabs/restricttotopic","owner":"tryolabs","description":"Validator for GuardrailsHub to check if a text is related with a topic.","archived":false,"fork":false,"pushed_at":"2024-12-11T18:09:32.000Z","size":80,"stargazers_count":2,"open_issues_count":7,"forks_count":5,"subscribers_count":7,"default_branch":"main","last_synced_at":"2025-07-04T18:44:30.679Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tryolabs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-01-24T13:34:34.000Z","updated_at":"2024-12-15T18:28:43.000Z","dependencies_parsed_at":"2024-08-27T01:59:35.031Z","dependency_job_id":"a819c57f-b689-47c8-a462-c6ff31d183d2","html_url":"https://github.com/tryolabs/restricttotopic","commit_stats":null,"previous_names":["tryolabs/restricttotopic"],"tags_count":0,"template":false,"template_full_name":"guardrails-ai/validator-template","purl":"pkg:github/tryolabs/restricttotopic","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tryolabs%2Frestricttotopic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tryolabs%2Frestricttotopic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tryolabs%2Frestricttotopic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tryolabs%2Frestricttotopic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tryolabs","download_url":"https://codeload.github.com/tryolabs/restricttotopic/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tryolabs%2Frestricttotopic/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274117488,"owners_count":25225102,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-07T02:00:09.463Z","response_time":67,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-06-05T13:30:39.969Z","updated_at":"2025-09-08T00:37:20.386Z","avatar_url":"https://github.com/tryolabs.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Overview\n\n| Developed by | Tryolabs |\n| Date of development | Feb 15, 2024 |\n| Validator type | Format |\n| Blog |  |\n| License | Apache 2 |\n| Input/Output | Output |\n\n## Description\n\n### Intended Use\nThis validator checks if a text is related with a topic.\n\n### Requirements\n\n* Dependencies:\n\t- guardrails-ai\u003e=0.4.0\n    - tenacity\u003e=8.1.0\n    - transformers\u003e=4.11.3\n    - torch\u003e=2.1.1\n\n* Foundation model access keys:\n\t- OPENAI_API_KEY\n\n## Installation\n\n```bash\n$ guardrails hub install hub://tryolabs/restricttotopic\n```\n\n## Usage Examples\n\n### Validating string output via Python\n\nIn this example, we apply the validator to a string output generated by an LLM.\n\n```python\n# Import Guard and Validator\nfrom guardrails.hub import RestrictToTopic\nfrom guardrails import Guard\n\n# Setup Guard\nguard = Guard().use(\n    RestrictToTopic(\n        valid_topics=[\"sports\"],\n        invalid_topics=[\"music\"],\n        disable_classifier=True,\n        disable_llm=False,\n        on_fail=\"exception\"\n    )\n)\n\nguard.validate(\"\"\"\nIn 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.\n\"\"\")  # Validator passes\n\nguard.validate(\"\"\"\nThe Beatles were a charismatic English pop-rock band of the 1960s.\n\"\"\")  # Validator fails\n```\n\n### Validating JSON output via Python\n\nIn this example, we apply the validator to a string field of a JSON output generated by an LLM.\n\n```python\n# Import Guard and Validator\nfrom pydantic import BaseModel, Field\nfrom guardrails.hub import RestrictToTopic\nfrom guardrails import Guard\n\n# Initialize Validator\nval = RestrictToTopic(\n    valid_topics=[\"sports\"],\n    disable_classifier=True,\n    disable_llm=False,\n    on_fail=\"exception\"\n)\n\n# Create Pydantic BaseModel\nclass TopicSummary(BaseModel):\n\t\ttopic: str\n\t\tsummary: str = Field(validators=[val])\n\n# Create a Guard to check for valid Pydantic output\nguard = Guard.from_pydantic(output_class=TopicSummary)\n\n# Run LLM output generating JSON through guard\nguard.parse(\"\"\"\n{\n\t\"topic\": \"Super Bowl LVII\",\n\t\"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.\"\n}\n\"\"\")\n```\n\n# API Reference\n\n**`__init__(self, on_fail=\"noop\")`**\n\u003cul\u003e\nInitializes a new instance of the RestrictToTopic class.\n\n**Parameters**\n- **`valid_topics`** *(List[str])*: topics that the text should be about (one or many).\n- **`invalid_topics`** *(List[str])*: topics that the text cannot be about. Defaults to `[]`.\n- **`device`** *(int)*: Device ordinal for CPU/GPU supports for Zero-Shot classifier. Setting this to -1 will leverage CPU, a positive will run the Zero-Shot model on the associated CUDA device id. Defaults to `-1`.\n- **`model`** *(str)*: The Zero-Shot model that will be used to classify the topic. See a list of all models here: https://huggingface.co/models?pipeline_tag=zero-shot-classification. Defaults to `facebook/bart-large-mnli`.\n- **`llm_callable`** *(Union[str, Callable, None])*: Either the name of the OpenAI model, or a callable that takes a prompt and returns a response. Defaults to `gpt-3.5-turbo`.\n- **`disable_classifier`** *(bool)*: Controls whether to use the Zero-Shot model. At least one of `disable_classifier` and `disable_llm` must be `False`. Defaults to `False`.\n- **`disable_llm`** *(bool)*: Controls whether to use the LLM fallback. At least one of `disable_classifier` and `disable_llm` must be `False`. Defaults to `False`.\n- **`model_threshold`** *(float)*: The threshold used to determine whether to accept a topic from the Zero-Shot model. Must be a number between `0` and `1`. Defaults to `0.5`.\n- **`on_fail`** *(str, Callable)*: The policy to enact when a validator fails.  If `str`, must be one of `reask`, `fix`, `filter`, `refrain`, `noop`, `exception` or `fix_reask`. Otherwise, must be a function that is called when the validator fails.\n\u003c/ul\u003e\n\u003cbr/\u003e\n\n**`validate(self, value, metadata) -\u003e ValidationResult`**\n\u003cul\u003e\nValidates the given `value` using the rules defined in this validator, relying on the `metadata` provided to customize the validation process. This method is automatically invoked by `guard.parse(...)`, ensuring the validation logic is applied to the input data.\n\nNote:\n\n1. This method should not be called directly by the user. Instead, invoke `guard.parse(...)` where this method will be called internally for each associated Validator.\n2. When invoking `guard.parse(...)`, ensure to pass the appropriate `metadata` dictionary that includes keys and values required by this validator. If `guard` is associated with multiple validators, combine all necessary metadata into a single dictionary.\n\n**Parameters**\n- **`value`** *(Any)*: The input value to validate.\n- **`metadata`** *(dict)*: A dictionary containing metadata required for validation. No additional metadata keys are needed for this validator.\n\u003c/ul\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftryolabs%2Frestricttotopic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftryolabs%2Frestricttotopic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftryolabs%2Frestricttotopic/lists"}