|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +from typing import Any, Dict, List |
| 5 | + |
| 6 | +from transformers import pipeline, AutoTokenizer, AutoConfig |
| 7 | + |
| 8 | +from llm_router_services.guardrails.inference.base import GuardrailBase |
| 9 | +from llm_router_services.guardrails.inference.config import GuardrailModelConfig |
| 10 | +from llm_router_services.guardrails.payload_handler import GuardrailPayloadExtractor |
| 11 | + |
| 12 | + |
| 13 | +# ----------------------------------------------------------------------- |
| 14 | +# Default (generic) configuration – can be used when a model does not have a |
| 15 | +# specialized config. It implements the GuardrailModelConfig interface. |
| 16 | +# ----------------------------------------------------------------------- |
| 17 | +@dataclass(frozen=True) |
| 18 | +class GenericModelConfig(GuardrailModelConfig): |
| 19 | + pipeline_batch_size: int = 64 |
| 20 | + min_score_for_safe: float = 0.5 |
| 21 | + min_score_for_not_safe: float = 0.5 |
| 22 | + |
| 23 | + |
| 24 | +class TextClassificationGuardrail(GuardrailBase): |
| 25 | + """ |
| 26 | + Generic text‑classification guardrail. |
| 27 | +
|
| 28 | + The caller supplies a concrete ``config`` object that implements |
| 29 | + :class:`GuardrailModelConfig`. This makes the guardrail reusable for any model. |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + model_path: str, |
| 35 | + device: int = -1, |
| 36 | + max_tokens: int = 500, |
| 37 | + overlap: int = 200, |
| 38 | + *, |
| 39 | + config: GuardrailModelConfig | None = None, |
| 40 | + ): |
| 41 | + # --------------------------------------------------------------- |
| 42 | + # Store model‑specific thresholds & batch size |
| 43 | + # --------------------------------------------------------------- |
| 44 | + self._config = config or GenericModelConfig() |
| 45 | + |
| 46 | + self._overlap = overlap |
| 47 | + self._max_tokens = max_tokens |
| 48 | + |
| 49 | + # --------------------------------------------------------------- |
| 50 | + # Tokeniser & pipeline preparation (unchanged) |
| 51 | + # --------------------------------------------------------------- |
| 52 | + self._tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True) |
| 53 | + self._model_max_length = AutoConfig.from_pretrained( |
| 54 | + model_path |
| 55 | + ).max_position_embeddings |
| 56 | + |
| 57 | + if self._max_tokens > self._model_max_length: |
| 58 | + self._max_tokens = self._model_max_length |
| 59 | + |
| 60 | + self._pipeline = pipeline( |
| 61 | + "text-classification", |
| 62 | + model=model_path, |
| 63 | + tokenizer=self._tokenizer, |
| 64 | + device=device, |
| 65 | + truncation=True, |
| 66 | + max_length=self._max_tokens, |
| 67 | + ) |
| 68 | + |
| 69 | + # ------------------------------------------------------------------- |
| 70 | + # Helper: convert payload → list of strings |
| 71 | + # ------------------------------------------------------------------- |
| 72 | + @staticmethod |
| 73 | + def _payload_to_string_list(payload: Dict[Any, Any]) -> List[str]: |
| 74 | + try: |
| 75 | + return GuardrailPayloadExtractor.extract_texts(payload) |
| 76 | + except (TypeError, ValueError): |
| 77 | + parts = [f"{str(k)}={str(v)}" for k, v in payload.items()] |
| 78 | + return [", ".join(parts)] |
| 79 | + |
| 80 | + # ------------------------------------------------------------------- |
| 81 | + # Helper: split long texts into token‑aware chunks |
| 82 | + # ------------------------------------------------------------------- |
| 83 | + def _chunk_text(self, texts: List[str]) -> List[str]: |
| 84 | + chunks: List[str] = [] |
| 85 | + for text in texts: |
| 86 | + token_ids = self._tokenizer.encode(text, add_special_tokens=False) |
| 87 | + step = self._max_tokens - self._overlap |
| 88 | + for start in range(0, len(token_ids), step): |
| 89 | + end = min(start + self._max_tokens, len(token_ids)) |
| 90 | + chunk_ids = token_ids[start:end] |
| 91 | + chunk_text = self._tokenizer.decode( |
| 92 | + chunk_ids, |
| 93 | + skip_special_tokens=True, |
| 94 | + clean_up_tokenization_spaces=True, |
| 95 | + ) |
| 96 | + chunks.append(chunk_text.strip()) |
| 97 | + if end == len(token_ids): |
| 98 | + break |
| 99 | + return chunks |
| 100 | + |
| 101 | + # ------------------------------------------------------------------- |
| 102 | + # Public API – called from the Flask endpoint |
| 103 | + # ------------------------------------------------------------------- |
| 104 | + def classify_chunks(self, payload: Dict[Any, Any]) -> Dict[str, Any]: |
| 105 | + texts = self._payload_to_string_list(payload) |
| 106 | + chunks = self._chunk_text(texts=texts) |
| 107 | + |
| 108 | + # Run inference in batches defined by the model config |
| 109 | + raw_results = self._pipeline( |
| 110 | + chunks, batch_size=self._config.pipeline_batch_size |
| 111 | + ) |
| 112 | + |
| 113 | + # Normalise pipeline output (it can be a list of dicts or a list containing a single list) |
| 114 | + flat_results = [r[0] if isinstance(r, list) else r for r in raw_results] |
| 115 | + |
| 116 | + detailed: List[Dict[str, Any]] = [] |
| 117 | + for idx, (chunk, classification) in enumerate(zip(chunks, flat_results)): |
| 118 | + label = classification.get("label", "") |
| 119 | + score = round(classification.get("score", 0.0), 4) |
| 120 | + is_safe = label.lower() == "safe" |
| 121 | + |
| 122 | + detailed.append( |
| 123 | + { |
| 124 | + "chunk_index": idx, |
| 125 | + "chunk_text": chunk, |
| 126 | + "label": label, |
| 127 | + "score": score, |
| 128 | + "safe": is_safe, |
| 129 | + } |
| 130 | + ) |
| 131 | + |
| 132 | + # --------------------------------------------------------------- |
| 133 | + # Overall safety decision – uses the per‑model thresholds |
| 134 | + # --------------------------------------------------------------- |
| 135 | + overall_safe = True |
| 136 | + for item in detailed: |
| 137 | + if item["safe"] and item["score"] < self._config.min_score_for_safe: |
| 138 | + overall_safe = False |
| 139 | + break |
| 140 | + if ( |
| 141 | + not item["safe"] |
| 142 | + and item["score"] > self._config.min_score_for_not_safe |
| 143 | + ): |
| 144 | + overall_safe = False |
| 145 | + break |
| 146 | + |
| 147 | + return {"safe": overall_safe, "detailed": detailed} |
0 commit comments