Skip to content
Merged
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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,22 @@ project tries to follow [Semantic Versioning](https://semver.org/).

## [Unreleased]

## [0.2.1] - 2026-10-13

### Security

- A response with no verdict field is no longer read as a pass: a missing
`safe`, `allowed` or `grounded` reads as false, and a missing `has_pii` or
`has_contradiction` as true.
- `ClassifyResult` and `PIIResult` gain `degraded`, set when `classify()`,
`pii_scan()` or `LlamaGuardClassifier` return through a fail-open path, and
on `screen()`'s classify and PII results. `screen()` now also sets
`ScreenResult.degraded` in local mode when a model did not load.
- `screen()` blocks when PII is reported but no masked text came back, and
`pii_mask()` raises instead of returning the unmasked text. `pii_mask()`
on text without PII now returns the text (it returned `None` in local and
server mode).

## [0.2.0] - 2026-07-11

### Added
Expand Down
2 changes: 2 additions & 0 deletions docs/sdk/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ class ClassifyResult:
categories: list[str] = field(default_factory=list) # All detected categories
confidence: float = 1.0 # Classification confidence
description: Optional[str] = None # Human-readable category label
degraded: bool = False # True when returned via a fail-open path
```

**Example:**
Expand All @@ -120,6 +121,7 @@ class PIIResult:
has_pii: bool # Whether PII was detected
entities: list[PIIEntity] = field(default_factory=list) # Detected entities
masked_text: Optional[str] = None # Text with PII replaced (if masked)
degraded: bool = False # True when returned via a fail-open path
```

**Example:**
Expand Down
10 changes: 5 additions & 5 deletions guardex/_engine/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,15 @@ def _classify_raw(
"GuardEx classifier provider not registered - "
"fail_open=True, returning safe=True (content NOT screened)"
)
return {"safe": True, "category": None, "categories": [], "confidence": 1.0}
return {"safe": True, "category": None, "categories": [], "confidence": 1.0, "_fail_open": True}
raise RuntimeError(
"GuardEx classifier not loaded. "
"pip install 'guardex-ai[local]' - or pass api_key=/base_url= for server mode."
)

raw = _run_async(provider.classify(text, stage=stage, categories=categories, cascade_mode=cascade_mode))
return {
"safe": raw.get("safe", True),
"safe": raw.get("safe", False),
"category": raw.get("category"),
"categories": raw.get("categories", []),
"confidence": raw.get("confidence", 1.0),
Expand Down Expand Up @@ -151,7 +151,7 @@ def _pii_raw(
"GuardEx PII provider not registered - "
"fail_open=True, returning has_pii=False (PII NOT scanned)"
)
return {"has_pii": False, "entities": [], "masked_text": text if mask else None}
return {"has_pii": False, "entities": [], "masked_text": text if mask else None, "_fail_open": True}
raise RuntimeError(
"GuardEx PII detector not loaded. "
"pip install 'guardex-ai[local]' - or pass api_key=/base_url= for server mode."
Expand Down Expand Up @@ -219,7 +219,7 @@ def _scope_raw(
)
raw = _run_async(provider.check_scope(text, profile, alpha=alpha))
return {
"allowed": raw.get("allowed", True),
"allowed": raw.get("allowed", False),
"distance": raw.get("distance", 0.0),
"matched_topic": raw.get("matched_topic"),
"confidence": raw.get("confidence", 1.0),
Expand Down Expand Up @@ -451,7 +451,7 @@ def pii_scan(
"""Scan text for PII. Returns raw pii dict (no masked_text)."""
_ensure_providers()
raw = self._pii_raw(text, entities=entities, threshold=threshold, mask=False)
return {"has_pii": raw["has_pii"], "entities": raw["entities"]}
return {k: raw[k] for k in ("has_pii", "entities", "_fail_open") if k in raw}

def pii_mask(
self,
Expand Down
2 changes: 1 addition & 1 deletion guardex/_stream_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def classify_should_block(classify: dict, min_confidence: float) -> bool:
``classify_min_confidence`` is treated as safe so streaming and
``Guard.screen()`` agree.
"""
if classify.get("safe", True):
if classify.get("safe", False):
return False
if min_confidence > 0.0 and classify.get("confidence", 1.0) < min_confidence:
return False
Expand Down
4 changes: 4 additions & 0 deletions guardex/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ class ClassifyResult:
categories: list[str] = field(default_factory=list)
confidence: float = 1.0
description: Optional[str] = None
degraded: bool = False
"""True when no classification ran (fail-open); ``safe`` is then not a real verdict."""


@dataclass(frozen=True, slots=True)
Expand All @@ -80,6 +82,8 @@ class PIIResult:
has_pii: bool
entities: list[PIIEntity] = field(default_factory=list)
masked_text: Optional[str] = None
degraded: bool = False
"""True when no PII scan ran (fail-open); ``has_pii`` is then not a real verdict."""


@dataclass(frozen=True, slots=True)
Expand Down
4 changes: 2 additions & 2 deletions guardex/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ async def classify(
body, request_id = await self._request("POST", "/v1/classify", json=payload,
extra_headers=extra_headers)
if body.get("_fail_open"):
return {"safe": True, "category": None, "categories": [], "_request_id": None}
return {"safe": True, "category": None, "categories": [], "_request_id": None, "_fail_open": True}
if request_id:
body["_request_id"] = request_id
return body
Expand All @@ -426,7 +426,7 @@ async def pii_scan(
body, _ = await self._request("POST", "/v1/pii/scan", json=payload,
extra_headers=extra_headers)
if body.get("_fail_open"):
return {"has_pii": False, "entities": []}
return {"has_pii": False, "entities": [], "_fail_open": True}
return body

async def pii_mask(
Expand Down
9 changes: 5 additions & 4 deletions guardex/classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,12 @@ def classify(
categories=self._policy.blocked_categories,
)
cr = ClassifyResult(
safe=result.get("safe", True),
safe=result.get("safe", False),
category=result.get("category"),
categories=result.get("categories", []),
confidence=result.get("confidence", 1.0),
description=result.get("description"),
degraded=bool(result.get("_fail_open")),
)
except Exception as e:
logger.warning(
Expand All @@ -86,9 +87,9 @@ def classify(
)
if not self._policy.fail_open:
raise
cr = ClassifyResult(safe=True)
cr = ClassifyResult(safe=True, degraded=True)

# Worst-severity wins: any unsafe result trumps a safe one.
if not cr.safe and worst.safe:
# Worst-severity wins: an unsafe or unscreened result replaces a safe one.
if worst.safe and (not cr.safe or cr.degraded):
worst = cr
return worst
4 changes: 2 additions & 2 deletions guardex/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ def classify(
body, request_id = self._request("POST", "/v1/classify", json=payload,
extra_headers=extra_headers)
if body.get("_fail_open"):
return {"safe": True, "category": None, "categories": [], "_request_id": None}
return {"safe": True, "category": None, "categories": [], "_request_id": None, "_fail_open": True}
if request_id:
body["_request_id"] = request_id
return body
Expand All @@ -281,7 +281,7 @@ def pii_scan(
body, _ = self._request("POST", "/v1/pii/scan", json=payload,
extra_headers=extra_headers)
if body.get("_fail_open"):
return {"has_pii": False, "entities": []}
return {"has_pii": False, "entities": [], "_fail_open": True}
return body

def pii_mask(
Expand Down
43 changes: 28 additions & 15 deletions guardex/guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
Gate, ScreenResult, ClassifyResult, PIIResult, PIIEntity,
ScopeResult, Action, GateTrace, gate_to_stage, output_gate_for,
)
from .exceptions import GuardExViolation
from .exceptions import GuardExAPIError, GuardExViolation

if TYPE_CHECKING:
from ._types import GroundingResult
Expand Down Expand Up @@ -118,7 +118,7 @@ def _parse_grounding_result(
details = [
SentenceGroundingResult(
sentence=s.get("sentence", ""),
grounded=s.get("grounded", True),
grounded=s.get("grounded", False),
score=s.get("entailment", s.get("score", 1.0)),
matched_chunk=s.get("matched_chunk"),
verdict=s.get("verdict", "grounded"),
Expand All @@ -129,9 +129,9 @@ def _parse_grounding_result(
]

return GroundingResult(
grounded=raw.get("grounded", True),
grounded=raw.get("grounded", False),
faithfulness_score=raw.get("faithfulness_score", 1.0),
has_contradiction=raw.get("has_contradiction", False),
has_contradiction=raw.get("has_contradiction", True),
sentence_count=raw.get("sentence_count", 0),
grounded_count=raw.get("grounded_count", 0),
contradicted_count=raw.get("contradicted_count", 0),
Expand Down Expand Up @@ -178,8 +178,8 @@ def _parse_screen_result(
return ScreenResult(
gate=gate,
action="pass",
classify=ClassifyResult(safe=True),
pii=PIIResult(has_pii=False),
classify=ClassifyResult(safe=True, degraded=True),
pii=PIIResult(has_pii=False, degraded=True),
text=original_text,
request_id=request_id,
gates_run=gates_run_t,
Expand All @@ -190,11 +190,12 @@ def _parse_screen_result(
# Parse classification
clf_data = raw.get("classify", {})
classify = ClassifyResult(
safe=clf_data.get("safe", True),
safe=clf_data.get("safe", False),
category=clf_data.get("category"),
categories=clf_data.get("categories", []),
confidence=clf_data.get("confidence", 1.0),
description=clf_data.get("description"),
degraded=bool(clf_data.get("_fail_open")),
)

# Parse PII
Expand All @@ -210,17 +211,18 @@ def _parse_screen_result(
for e in pii_data.get("entities", [])
]
pii = PIIResult(
has_pii=pii_data.get("has_pii", False),
has_pii=pii_data.get("has_pii", True),
entities=pii_entities,
masked_text=pii_data.get("masked_text"),
degraded=bool(pii_data.get("_fail_open")),
)

# Parse scope
scope = None
scope_data = raw.get("scope")
if scope_data is not None:
scope = ScopeResult(
allowed=scope_data.get("allowed", True),
allowed=scope_data.get("allowed", False),
distance=scope_data.get("distance", 0.0),
matched_topic=scope_data.get("matched_topic"),
confidence=scope_data.get("confidence", 1.0),
Expand Down Expand Up @@ -249,7 +251,7 @@ def _parse_screen_result(
action: Action = "block"
elif not classify.safe:
action = "block"
elif pii.has_pii and pii_action == "block":
elif pii.has_pii and (pii_action == "block" or not pii.masked_text or "text" not in raw):
action = "block"
elif pii.has_pii and pii.masked_text:
action = "mask"
Expand All @@ -266,6 +268,7 @@ def _parse_screen_result(
request_id=request_id,
gates_run=gates_run_t,
diagnostics=diagnostics_t,
degraded=classify.degraded or pii.degraded,
)


Expand Down Expand Up @@ -738,9 +741,9 @@ def classify(
**classify_kwargs,
)
if raw.get("_fail_open"):
return ClassifyResult(safe=True)
return ClassifyResult(safe=True, degraded=True)
return ClassifyResult(
safe=raw.get("safe", True),
safe=raw.get("safe", False),
category=raw.get("category"),
categories=raw.get("categories", []),
confidence=raw.get("confidence", 1.0),
Expand All @@ -760,7 +763,7 @@ def pii_scan(
threshold=policy.pii_threshold,
)
if raw.get("_fail_open"):
return PIIResult(has_pii=False)
return PIIResult(has_pii=False, degraded=True)
entities = [
PIIEntity(
text=e.get("text", ""),
Expand All @@ -771,7 +774,7 @@ def pii_scan(
)
for e in raw.get("entities", [])
]
return PIIResult(has_pii=raw.get("has_pii", False), entities=entities)
return PIIResult(has_pii=raw.get("has_pii", True), entities=entities)

def pii_mask(
self,
Expand All @@ -785,7 +788,17 @@ def pii_mask(
entities=policy.pii_entities,
threshold=policy.pii_threshold,
)
return raw.get("masked_text", text)
masked = raw.get("masked_text")
if masked is not None:
return masked
if raw.get("has_pii") is False:
return text
raise GuardExAPIError(
status_code=502,
error_type="invalid_response",
message="Response has no masked_text. Run a guardex-server that matches this SDK version.",
code="missing_masked_text",
)

def screen_batch(
self,
Expand Down
4 changes: 2 additions & 2 deletions guardex/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def _flush(self) -> Iterator[str]:
# Topic scope is reported in a separate `scope` object, not in
# `classify.safe`; enforce it here to match Guard.screen().
scope = result.get("scope")
if scope is not None and not scope.get("allowed", True):
if scope is not None and not scope.get("allowed", False):
logger.warning(
"StreamGuard blocked at gate=%s: out of topic scope after %d chars",
self._gate, self._total_screened,
Expand Down Expand Up @@ -289,7 +289,7 @@ async def _aflush(self) -> AsyncIterator[str]:
# Topic scope is reported in a separate `scope` object, not in
# `classify.safe`; enforce it here to match Guard.screen().
scope = result.get("scope")
if scope is not None and not scope.get("allowed", True):
if scope is not None and not scope.get("allowed", False):
logger.warning(
"AsyncStreamGuard blocked at gate=%s: out of topic scope after %d chars",
self._gate, self._total_screened,
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "guardex-ai"
version = "0.2.0"
version = "0.2.1"
description = "Open-source AI guardrails: safety classification, PII detection, prompt injection defense for any LLM"
readme = "README.md"
license = { text = "Apache-2.0" }
Expand Down
Loading
Loading