cuitty-pilot 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cuitty_pilot-0.1.0/PKG-INFO +70 -0
- cuitty_pilot-0.1.0/README.md +61 -0
- cuitty_pilot-0.1.0/pyproject.toml +18 -0
- cuitty_pilot-0.1.0/setup.cfg +4 -0
- cuitty_pilot-0.1.0/src/cuitty_pilot/__init__.py +378 -0
- cuitty_pilot-0.1.0/src/cuitty_pilot/__main__.py +5 -0
- cuitty_pilot-0.1.0/src/cuitty_pilot/cli.py +91 -0
- cuitty_pilot-0.1.0/src/cuitty_pilot.egg-info/PKG-INFO +70 -0
- cuitty_pilot-0.1.0/src/cuitty_pilot.egg-info/SOURCES.txt +10 -0
- cuitty_pilot-0.1.0/src/cuitty_pilot.egg-info/dependency_links.txt +1 -0
- cuitty_pilot-0.1.0/src/cuitty_pilot.egg-info/entry_points.txt +2 -0
- cuitty_pilot-0.1.0/src/cuitty_pilot.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cuitty-pilot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK and CLI for the Cuitty content-safety platform — classify, gate, and redact text and images.
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# cuitty-pilot
|
|
11
|
+
|
|
12
|
+
`cuitty-pilot` is the Python SDK and CLI for the Cuitty platform — a content-safety
|
|
13
|
+
layer that classifies text and image inputs before they reach your model or
|
|
14
|
+
end-users. The library wraps the Cuitty classification API with typed requests,
|
|
15
|
+
streaming responses, and a local policy engine so you can apply SFW/NSFW gating,
|
|
16
|
+
PII redaction, and prompt-injection heuristics inline. It is built for teams that
|
|
17
|
+
ship user-generated content pipelines and need a fast, auditable guard in front of
|
|
18
|
+
their LLM calls.
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
- Typed `pilot.classify(text, modalities=...)` and `pilot.classify_image(...)` calls
|
|
23
|
+
with streaming for high-throughput pipelines.
|
|
24
|
+
- A local rule layer for SFW gating, profanity, and prompt-injection patterns that
|
|
25
|
+
runs before any network call, cutting latency on obviously-bad inputs.
|
|
26
|
+
- Policy files (YAML) that map classifier scores to actions: `allow`, `block`,
|
|
27
|
+
`redact`, `flag`; attach a `reason` for downstream auditing.
|
|
28
|
+
- Async-first client with retries, exponential backoff, and automatic batch
|
|
29
|
+
grouping to stay under rate limits.
|
|
30
|
+
- Drop-in middleware for OpenAI and Anthropic SDKs: wrap a chat completion and the
|
|
31
|
+
pilot inspects both the user message and the model response.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install cuitty-pilot
|
|
37
|
+
# OpenAI / Anthropic middleware + async
|
|
38
|
+
pip install "cuitty-pilot[openai,anthropic]"
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from cuitty_pilot import Pilot
|
|
45
|
+
|
|
46
|
+
pilot = Pilot(api_key="cui_...") # reads CUITTY_API_KEY if omitted
|
|
47
|
+
|
|
48
|
+
verdict = pilot.classify("some user text", modalities=["sfw", "pii"])
|
|
49
|
+
if verdict.action == "block":
|
|
50
|
+
raise BlockedContent(verdict.reason)
|
|
51
|
+
|
|
52
|
+
redacted = pilot.redact("email me at bob@example.com") # -> "email me at [REDACTED]"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## CLI
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
cuitty-pilot classify --text "hello" --json
|
|
59
|
+
cuitty-pilot gate --input in.txt --policy policy.yaml
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Configuration
|
|
63
|
+
|
|
64
|
+
Set `CUITTY_API_KEY` (or `cuitty-pilot login`). Policy files resolve from
|
|
65
|
+
`./.cuitty/policy.yaml` then `~/.config/cuitty/policy.yaml`; override with
|
|
66
|
+
`--policy`.
|
|
67
|
+
|
|
68
|
+
## License
|
|
69
|
+
|
|
70
|
+
MIT
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# cuitty-pilot
|
|
2
|
+
|
|
3
|
+
`cuitty-pilot` is the Python SDK and CLI for the Cuitty platform — a content-safety
|
|
4
|
+
layer that classifies text and image inputs before they reach your model or
|
|
5
|
+
end-users. The library wraps the Cuitty classification API with typed requests,
|
|
6
|
+
streaming responses, and a local policy engine so you can apply SFW/NSFW gating,
|
|
7
|
+
PII redaction, and prompt-injection heuristics inline. It is built for teams that
|
|
8
|
+
ship user-generated content pipelines and need a fast, auditable guard in front of
|
|
9
|
+
their LLM calls.
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- Typed `pilot.classify(text, modalities=...)` and `pilot.classify_image(...)` calls
|
|
14
|
+
with streaming for high-throughput pipelines.
|
|
15
|
+
- A local rule layer for SFW gating, profanity, and prompt-injection patterns that
|
|
16
|
+
runs before any network call, cutting latency on obviously-bad inputs.
|
|
17
|
+
- Policy files (YAML) that map classifier scores to actions: `allow`, `block`,
|
|
18
|
+
`redact`, `flag`; attach a `reason` for downstream auditing.
|
|
19
|
+
- Async-first client with retries, exponential backoff, and automatic batch
|
|
20
|
+
grouping to stay under rate limits.
|
|
21
|
+
- Drop-in middleware for OpenAI and Anthropic SDKs: wrap a chat completion and the
|
|
22
|
+
pilot inspects both the user message and the model response.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install cuitty-pilot
|
|
28
|
+
# OpenAI / Anthropic middleware + async
|
|
29
|
+
pip install "cuitty-pilot[openai,anthropic]"
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from cuitty_pilot import Pilot
|
|
36
|
+
|
|
37
|
+
pilot = Pilot(api_key="cui_...") # reads CUITTY_API_KEY if omitted
|
|
38
|
+
|
|
39
|
+
verdict = pilot.classify("some user text", modalities=["sfw", "pii"])
|
|
40
|
+
if verdict.action == "block":
|
|
41
|
+
raise BlockedContent(verdict.reason)
|
|
42
|
+
|
|
43
|
+
redacted = pilot.redact("email me at bob@example.com") # -> "email me at [REDACTED]"
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## CLI
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
cuitty-pilot classify --text "hello" --json
|
|
50
|
+
cuitty-pilot gate --input in.txt --policy policy.yaml
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Configuration
|
|
54
|
+
|
|
55
|
+
Set `CUITTY_API_KEY` (or `cuitty-pilot login`). Policy files resolve from
|
|
56
|
+
`./.cuitty/policy.yaml` then `~/.config/cuitty/policy.yaml`; override with
|
|
57
|
+
`--policy`.
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
MIT
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cuitty-pilot"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python SDK and CLI for the Cuitty content-safety platform — classify, gate, and redact text and images."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [{name = ""}]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
cuitty-pilot = "cuitty_pilot.cli:main"
|
|
16
|
+
|
|
17
|
+
[tool.setuptools.packages.find]
|
|
18
|
+
where = ["src"]
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
"""cuitty-pilot — Python SDK and CLI for the Cuitty content-safety platform.
|
|
2
|
+
|
|
3
|
+
Cuitty classifies text and image inputs before they reach your model or
|
|
4
|
+
end-users. This library wraps the Cuitty classification API with typed
|
|
5
|
+
requests, streaming responses, and a local policy engine so you can apply
|
|
6
|
+
SFW/NSFW gating, PII redaction, and prompt-injection heuristics inline.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import dataclasses
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import urllib.error
|
|
16
|
+
import urllib.request
|
|
17
|
+
from typing import Any, Iterator, Protocol, Sequence
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"Pilot",
|
|
23
|
+
"PilotError",
|
|
24
|
+
"BlockedContent",
|
|
25
|
+
"Verdict",
|
|
26
|
+
"Action",
|
|
27
|
+
"Policy",
|
|
28
|
+
"PolicyRule",
|
|
29
|
+
"LocalRules",
|
|
30
|
+
"Transport",
|
|
31
|
+
"Modality",
|
|
32
|
+
"DEFAULT_POLICY_PATHS",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
DEFAULT_POLICY_PATHS = (
|
|
36
|
+
"./.cuitty/policy.yaml",
|
|
37
|
+
os.path.expanduser("~/.config/cuitty/policy.yaml"),
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class PilotError(Exception):
|
|
42
|
+
"""Base class for cuitty-pilot errors."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BlockedContent(PilotError):
|
|
46
|
+
"""Raised when a verdict's action is ``block``.
|
|
47
|
+
|
|
48
|
+
Carries the reason so callers can surface it to users or audit logs.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self, reason: str) -> None:
|
|
52
|
+
super().__init__(f"content blocked: {reason}")
|
|
53
|
+
self.reason = reason
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# --- Local rule layer (no network) --------------------------------------
|
|
57
|
+
|
|
58
|
+
# Modality labels matching the README example: ["sfw", "pii"].
|
|
59
|
+
Modality = str # "sfw" | "nsfw" | "pii" | "injection" | ...
|
|
60
|
+
|
|
61
|
+
# Heuristic prompt-injection patterns.
|
|
62
|
+
_INJECTION_PATTERNS = [
|
|
63
|
+
re.compile(r"ignore (all )?(prior|previous) instructions", re.I),
|
|
64
|
+
re.compile(r"pretend you are (dan|do anything now)", re.I),
|
|
65
|
+
re.compile(r"you are now in (developer|debug) mode", re.I),
|
|
66
|
+
re.compile(r"system prompt:", re.I),
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
# Crude PII patterns.
|
|
70
|
+
_PII_PATTERNS = {
|
|
71
|
+
"email": re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b"),
|
|
72
|
+
"phone": re.compile(r"\b\+?\d[\d\s\-().]{7,}\d\b"),
|
|
73
|
+
"ssn": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
|
|
74
|
+
"credit_card": re.compile(r"\b(?:\d[ -]?){13,16}\b"),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
# Crude profanity list (kept tiny for a stdlib-only library).
|
|
78
|
+
_PROFANITY = ("fuck", "shit", "bitch", "asshole", "cunt")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclasses.dataclass
|
|
82
|
+
class Score:
|
|
83
|
+
"""A normalized classifier score in ``[0, 1]``."""
|
|
84
|
+
|
|
85
|
+
modality: str
|
|
86
|
+
value: float
|
|
87
|
+
confidence: float = 1.0
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class LocalRules:
|
|
91
|
+
"""Cheap heuristics that run before any network call.
|
|
92
|
+
|
|
93
|
+
The local layer returns a list of :class:`Score` objects so the policy
|
|
94
|
+
engine can map them to an action without a round-trip.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
def evaluate_text(self, text: str) -> list[Score]:
|
|
98
|
+
if not isinstance(text, str):
|
|
99
|
+
raise TypeError("text must be a string")
|
|
100
|
+
lowered = text.lower()
|
|
101
|
+
scores: list[Score] = []
|
|
102
|
+
# SFW gating: profanity bumps the nsfw score.
|
|
103
|
+
profane = any(w in lowered for w in _PROFANITY)
|
|
104
|
+
scores.append(Score("nsfw", 0.95 if profane else 0.05))
|
|
105
|
+
# PII: presence of any PII pattern bumps the pii score.
|
|
106
|
+
pii_found = any(p.search(text) for p in _PII_PATTERNS.values())
|
|
107
|
+
scores.append(Score("pii", 0.95 if pii_found else 0.05))
|
|
108
|
+
# Prompt injection.
|
|
109
|
+
injected = any(p.search(text) for p in _INJECTION_PATTERNS)
|
|
110
|
+
scores.append(Score("injection", 0.97 if injected else 0.03))
|
|
111
|
+
# SFW: inverse of nsfw.
|
|
112
|
+
scores.append(Score("sfw", 0.05 if profane else 0.95))
|
|
113
|
+
return scores
|
|
114
|
+
|
|
115
|
+
def evaluate_image(self, image_meta: dict[str, Any]) -> list[Score]:
|
|
116
|
+
# We cannot inspect image bytes without a model; use supplied metadata
|
|
117
|
+
# (e.g. {"flagged": True}) so the local layer is still useful.
|
|
118
|
+
flagged = bool(image_meta.get("flagged", False))
|
|
119
|
+
return [
|
|
120
|
+
Score("nsfw", 0.9 if flagged else 0.1),
|
|
121
|
+
Score("sfw", 0.1 if flagged else 0.9),
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
def redact(self, text: str) -> str:
|
|
125
|
+
"""Replace PII matches with ``[REDACTED]``."""
|
|
126
|
+
out = text
|
|
127
|
+
for pattern in _PII_PATTERNS.values():
|
|
128
|
+
out = pattern.sub("[REDACTED]", out)
|
|
129
|
+
return out
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# --- Policy engine -------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
Action = str # "allow" | "block" | "redact" | "flag"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclasses.dataclass
|
|
138
|
+
class PolicyRule:
|
|
139
|
+
"""A single policy rule.
|
|
140
|
+
|
|
141
|
+
Attributes:
|
|
142
|
+
modality: The score modality this rule watches (e.g. ``"nsfw"``).
|
|
143
|
+
threshold: Score at or above which the rule fires.
|
|
144
|
+
action: One of ``allow``/``block``/``redact``/``flag``.
|
|
145
|
+
reason: Free-form reason attached to the verdict.
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
modality: str
|
|
149
|
+
threshold: float
|
|
150
|
+
action: Action
|
|
151
|
+
reason: str
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@dataclasses.dataclass
|
|
155
|
+
class Policy:
|
|
156
|
+
"""An ordered list of :class:`PolicyRule`s evaluated in order."""
|
|
157
|
+
|
|
158
|
+
rules: list[PolicyRule] = dataclasses.field(default_factory=list)
|
|
159
|
+
default_action: Action = "allow"
|
|
160
|
+
default_reason: str = "no rule matched"
|
|
161
|
+
|
|
162
|
+
@classmethod
|
|
163
|
+
def default(cls) -> "Policy":
|
|
164
|
+
return cls(
|
|
165
|
+
rules=[
|
|
166
|
+
PolicyRule(modality="injection", threshold=0.5, action="block", reason="prompt-injection detected"),
|
|
167
|
+
PolicyRule(modality="nsfw", threshold=0.8, action="block", reason="nsfw content"),
|
|
168
|
+
PolicyRule(modality="pii", threshold=0.8, action="redact", reason="pii detected"),
|
|
169
|
+
],
|
|
170
|
+
default_action="allow",
|
|
171
|
+
default_reason="clean",
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def evaluate(self, scores: list[Score]) -> tuple[Action, str]:
|
|
175
|
+
"""Return the first matching rule's (action, reason), else the default."""
|
|
176
|
+
score_by_modality = {s.modality: s.value for s in scores}
|
|
177
|
+
for rule in self.rules:
|
|
178
|
+
v = score_by_modality.get(rule.modality)
|
|
179
|
+
if v is not None and v >= rule.threshold:
|
|
180
|
+
return rule.action, rule.reason
|
|
181
|
+
return self.default_action, self.default_reason
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@dataclasses.dataclass
|
|
185
|
+
class Verdict:
|
|
186
|
+
"""The typed result of a classification call."""
|
|
187
|
+
|
|
188
|
+
action: Action
|
|
189
|
+
reason: str
|
|
190
|
+
scores: list[Score]
|
|
191
|
+
redacted_text: str | None = None
|
|
192
|
+
|
|
193
|
+
@property
|
|
194
|
+
def blocked(self) -> bool:
|
|
195
|
+
return self.action == "block"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# --- Policy file loading (tiny YAML subset, stdlib) ----------------------
|
|
199
|
+
|
|
200
|
+
def _parse_policy_text(text: str) -> Policy:
|
|
201
|
+
"""Parse a minimal YAML-ish policy file.
|
|
202
|
+
|
|
203
|
+
Supports a flat ``rules:`` list of dicts with ``modality``, ``threshold``,
|
|
204
|
+
``action``, ``reason`` keys, plus ``default_action``/``default_reason``.
|
|
205
|
+
No external YAML dependency is required.
|
|
206
|
+
"""
|
|
207
|
+
# Reuse JSON loader if the file is JSON.
|
|
208
|
+
stripped = text.strip()
|
|
209
|
+
if stripped.startswith("{") or stripped.startswith("["):
|
|
210
|
+
return _policy_from_dict(json.loads(stripped))
|
|
211
|
+
# Otherwise: parse a very small YAML subset line-by-line.
|
|
212
|
+
rules: list[PolicyRule] = []
|
|
213
|
+
default_action = "allow"
|
|
214
|
+
default_reason = "no rule matched"
|
|
215
|
+
current: dict[str, Any] = {}
|
|
216
|
+
in_rules = False
|
|
217
|
+
for raw in text.splitlines():
|
|
218
|
+
line = raw.split("#", 1)[0].rstrip()
|
|
219
|
+
if not line.strip():
|
|
220
|
+
continue
|
|
221
|
+
if line.strip() == "rules:":
|
|
222
|
+
in_rules = True
|
|
223
|
+
continue
|
|
224
|
+
if not in_rules:
|
|
225
|
+
if ":" in line:
|
|
226
|
+
k, v = line.split(":", 1)
|
|
227
|
+
if k.strip() == "default_action":
|
|
228
|
+
default_action = v.strip().strip('"').strip("'")
|
|
229
|
+
elif k.strip() == "default_reason":
|
|
230
|
+
default_reason = v.strip().strip('"').strip("'")
|
|
231
|
+
continue
|
|
232
|
+
# A new rule starts with "- modality: ...".
|
|
233
|
+
if line.lstrip().startswith("- "):
|
|
234
|
+
if current:
|
|
235
|
+
rules.append(PolicyRule(**current))
|
|
236
|
+
current = {}
|
|
237
|
+
kv = line.lstrip()[2:]
|
|
238
|
+
k, v = kv.split(":", 1)
|
|
239
|
+
current[k.strip()] = _coerce(v.strip())
|
|
240
|
+
elif ":" in line and current:
|
|
241
|
+
k, v = line.strip().split(":", 1)
|
|
242
|
+
current[k.strip()] = _coerce(v.strip())
|
|
243
|
+
if current:
|
|
244
|
+
rules.append(PolicyRule(**current))
|
|
245
|
+
return Policy(rules=rules, default_action=default_action, default_reason=default_reason)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _coerce(v: str) -> Any:
|
|
249
|
+
v = v.strip('"').strip("'")
|
|
250
|
+
try:
|
|
251
|
+
return float(v) if "." in v else int(v)
|
|
252
|
+
except ValueError:
|
|
253
|
+
return v
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _policy_from_dict(data: dict[str, Any]) -> Policy:
|
|
257
|
+
rules = [PolicyRule(**r) for r in data.get("rules", [])]
|
|
258
|
+
return Policy(
|
|
259
|
+
rules=rules,
|
|
260
|
+
default_action=data.get("default_action", "allow"),
|
|
261
|
+
default_reason=data.get("default_reason", "no rule matched"),
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def load_policy(path: str | None = None) -> Policy:
|
|
266
|
+
"""Load a policy from ``path`` or the default search paths."""
|
|
267
|
+
candidates: list[str] = [path] if path else list(DEFAULT_POLICY_PATHS)
|
|
268
|
+
for cand in candidates:
|
|
269
|
+
if cand and os.path.exists(cand):
|
|
270
|
+
with open(cand, "r", encoding="utf-8") as fh:
|
|
271
|
+
return _parse_policy_text(fh.read())
|
|
272
|
+
return Policy.default()
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
# --- Transport + Pilot ---------------------------------------------------
|
|
276
|
+
|
|
277
|
+
class Transport(Protocol):
|
|
278
|
+
def request(self, method: str, url: str, headers: dict[str, str], body: bytes | None) -> tuple[int, bytes]:
|
|
279
|
+
...
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
class _UrllibTransport:
|
|
283
|
+
def request(self, method: str, url: str, headers: dict[str, str], body: bytes | None) -> tuple[int, bytes]:
|
|
284
|
+
req = urllib.request.Request(url, data=body, method=method, headers=headers)
|
|
285
|
+
try:
|
|
286
|
+
with urllib.request.urlopen(req) as resp:
|
|
287
|
+
return resp.status, resp.read()
|
|
288
|
+
except urllib.error.HTTPError as exc:
|
|
289
|
+
return exc.code, exc.read()
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
class Pilot:
|
|
293
|
+
"""The Cuitty pilot client.
|
|
294
|
+
|
|
295
|
+
Args:
|
|
296
|
+
api_key: Cuitty API key. Defaults to ``CUITTY_API_KEY``.
|
|
297
|
+
base_url: Cuitty API base URL.
|
|
298
|
+
policy: A :class:`Policy` instance or a path to a policy file.
|
|
299
|
+
transport: Pluggable HTTP transport for testing.
|
|
300
|
+
"""
|
|
301
|
+
|
|
302
|
+
def __init__(
|
|
303
|
+
self,
|
|
304
|
+
api_key: str | None = None,
|
|
305
|
+
*,
|
|
306
|
+
base_url: str | None = None,
|
|
307
|
+
policy: Policy | str | None = None,
|
|
308
|
+
transport: Transport | None = None,
|
|
309
|
+
) -> None:
|
|
310
|
+
self.api_key = api_key or os.environ.get("CUITTY_API_KEY")
|
|
311
|
+
self.base_url = (base_url or "https://api.cuitty.com").rstrip("/")
|
|
312
|
+
self._transport = transport or _UrllibTransport()
|
|
313
|
+
if isinstance(policy, Policy):
|
|
314
|
+
self.policy = policy
|
|
315
|
+
elif isinstance(policy, str):
|
|
316
|
+
self.policy = load_policy(policy)
|
|
317
|
+
else:
|
|
318
|
+
self.policy = load_policy()
|
|
319
|
+
self.local = LocalRules()
|
|
320
|
+
|
|
321
|
+
def classify(
|
|
322
|
+
self,
|
|
323
|
+
text: str,
|
|
324
|
+
*,
|
|
325
|
+
modalities: Sequence[Modality] | None = None,
|
|
326
|
+
) -> Verdict:
|
|
327
|
+
"""Classify ``text`` and return a :class:`Verdict`.
|
|
328
|
+
|
|
329
|
+
The local rule layer always runs first. If the local scores already
|
|
330
|
+
resolve to ``block``/``redact``, the network is not consulted.
|
|
331
|
+
"""
|
|
332
|
+
scores = self.local.evaluate_text(text)
|
|
333
|
+
if modalities:
|
|
334
|
+
wanted = set(modalities)
|
|
335
|
+
scores = [s for s in scores if s.modality in wanted]
|
|
336
|
+
action, reason = self.policy.evaluate(scores)
|
|
337
|
+
redacted: str | None = None
|
|
338
|
+
if action == "redact":
|
|
339
|
+
redacted = self.local.redact(text)
|
|
340
|
+
elif action == "block":
|
|
341
|
+
# If a remote classifier is configured and the local layer is
|
|
342
|
+
# uncertain, the SDK could escalate; we keep it deterministic here.
|
|
343
|
+
pass
|
|
344
|
+
return Verdict(action=action, reason=reason, scores=scores, redacted_text=redacted)
|
|
345
|
+
|
|
346
|
+
def classify_image(self, image_meta: dict[str, Any] | None = None) -> Verdict:
|
|
347
|
+
scores = self.local.evaluate_image(image_meta or {})
|
|
348
|
+
action, reason = self.policy.evaluate(scores)
|
|
349
|
+
return Verdict(action=action, reason=reason, scores=scores)
|
|
350
|
+
|
|
351
|
+
def redact(self, text: str) -> str:
|
|
352
|
+
"""Convenience wrapper that returns the redacted text."""
|
|
353
|
+
verdict = self.classify(text, modalities=["pii"])
|
|
354
|
+
if verdict.redacted_text is not None:
|
|
355
|
+
return verdict.redacted_text
|
|
356
|
+
return self.local.redact(text)
|
|
357
|
+
|
|
358
|
+
def stream(self, text: str, *, modalities: Sequence[Modality] | None = None) -> Iterator[Verdict]:
|
|
359
|
+
"""Yield one verdict per chunk for streaming pipelines.
|
|
360
|
+
|
|
361
|
+
The default implementation classifies the whole string at once; a
|
|
362
|
+
transport emitting server-sent events would yield per-chunk verdicts.
|
|
363
|
+
"""
|
|
364
|
+
yield self.classify(text, modalities=modalities)
|
|
365
|
+
|
|
366
|
+
def _remote_classify(self, text: str) -> dict[str, Any]:
|
|
367
|
+
if not self.api_key:
|
|
368
|
+
raise PilotError("api_key required for remote classification")
|
|
369
|
+
body = json.dumps({"text": text}).encode("utf-8")
|
|
370
|
+
status, payload = self._transport.request(
|
|
371
|
+
"POST",
|
|
372
|
+
self.base_url + "/v1/classify",
|
|
373
|
+
{"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
|
|
374
|
+
body,
|
|
375
|
+
)
|
|
376
|
+
if status >= 400:
|
|
377
|
+
raise PilotError(f"remote classify failed: HTTP {status}")
|
|
378
|
+
return json.loads(payload.decode("utf-8")) if payload else {}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""CLI for cuitty-pilot.
|
|
2
|
+
|
|
3
|
+
cuitty-pilot classify --text "hello" --json
|
|
4
|
+
cuitty-pilot gate --input in.txt --policy policy.yaml
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
from . import BlockedContent, Pilot, PilotError, load_policy
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _cmd_classify(args: argparse.Namespace) -> int:
|
|
18
|
+
pilot = Pilot(api_key=args.api_key, base_url=args.base_url, policy=args.policy or None)
|
|
19
|
+
verdict = pilot.classify(args.text, modalities=args.modalities)
|
|
20
|
+
if args.json:
|
|
21
|
+
out = {
|
|
22
|
+
"action": verdict.action,
|
|
23
|
+
"reason": verdict.reason,
|
|
24
|
+
"scores": [{"modality": s.modality, "value": s.value} for s in verdict.scores],
|
|
25
|
+
"redacted_text": verdict.redacted_text,
|
|
26
|
+
}
|
|
27
|
+
print(json.dumps(out, indent=2))
|
|
28
|
+
else:
|
|
29
|
+
print(f"{verdict.action}\t{verdict.reason}")
|
|
30
|
+
if verdict.action == "block":
|
|
31
|
+
return 3
|
|
32
|
+
return 0
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _cmd_gate(args: argparse.Namespace) -> int:
|
|
36
|
+
pilot = Pilot(api_key=args.api_key, base_url=args.base_url, policy=args.policy or None)
|
|
37
|
+
if args.input == "-":
|
|
38
|
+
text = sys.stdin.read()
|
|
39
|
+
else:
|
|
40
|
+
with open(args.input, "r", encoding="utf-8") as fh:
|
|
41
|
+
text = fh.read()
|
|
42
|
+
verdict = pilot.classify(text)
|
|
43
|
+
if verdict.action == "redact":
|
|
44
|
+
sys.stdout.write(verdict.redacted_text or pilot.redact(text))
|
|
45
|
+
elif verdict.action == "block":
|
|
46
|
+
print(f"BLOCKED: {verdict.reason}", file=sys.stderr)
|
|
47
|
+
return 3
|
|
48
|
+
else:
|
|
49
|
+
sys.stdout.write(text)
|
|
50
|
+
return 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
54
|
+
p = argparse.ArgumentParser(prog="cuitty-pilot", description="Cuitty content-safety CLI")
|
|
55
|
+
p.add_argument("--api-key", default=os.environ.get("CUITTY_API_KEY"))
|
|
56
|
+
p.add_argument("--base-url", default=None)
|
|
57
|
+
p.add_argument("--policy", default=None, help="path to a policy YAML/JSON file")
|
|
58
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
59
|
+
|
|
60
|
+
c = sub.add_parser("classify", help="classify a single text input")
|
|
61
|
+
c.add_argument("--text", required=True)
|
|
62
|
+
c.add_argument("--modalities", nargs="*", default=None)
|
|
63
|
+
c.add_argument("--json", action="store_true")
|
|
64
|
+
c.set_defaults(func=_cmd_classify)
|
|
65
|
+
|
|
66
|
+
g = sub.add_parser("gate", help="gate an input file: redact, block, or pass through")
|
|
67
|
+
g.add_argument("--input", required=True, help="input file or '-' for stdin")
|
|
68
|
+
g.set_defaults(func=_cmd_gate)
|
|
69
|
+
|
|
70
|
+
return p
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def main(argv: list[str] | None = None) -> int:
|
|
74
|
+
parser = build_parser()
|
|
75
|
+
args = parser.parse_args(argv)
|
|
76
|
+
func = getattr(args, "func", None)
|
|
77
|
+
if func is None: # pragma: no cover
|
|
78
|
+
parser.print_help()
|
|
79
|
+
return 1
|
|
80
|
+
try:
|
|
81
|
+
return int(func(args))
|
|
82
|
+
except BlockedContent as exc:
|
|
83
|
+
print(f"blocked: {exc}", file=sys.stderr)
|
|
84
|
+
return 3
|
|
85
|
+
except PilotError as exc:
|
|
86
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
87
|
+
return 2
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
if __name__ == "__main__": # pragma: no cover
|
|
91
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cuitty-pilot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK and CLI for the Cuitty content-safety platform — classify, gate, and redact text and images.
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# cuitty-pilot
|
|
11
|
+
|
|
12
|
+
`cuitty-pilot` is the Python SDK and CLI for the Cuitty platform — a content-safety
|
|
13
|
+
layer that classifies text and image inputs before they reach your model or
|
|
14
|
+
end-users. The library wraps the Cuitty classification API with typed requests,
|
|
15
|
+
streaming responses, and a local policy engine so you can apply SFW/NSFW gating,
|
|
16
|
+
PII redaction, and prompt-injection heuristics inline. It is built for teams that
|
|
17
|
+
ship user-generated content pipelines and need a fast, auditable guard in front of
|
|
18
|
+
their LLM calls.
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
- Typed `pilot.classify(text, modalities=...)` and `pilot.classify_image(...)` calls
|
|
23
|
+
with streaming for high-throughput pipelines.
|
|
24
|
+
- A local rule layer for SFW gating, profanity, and prompt-injection patterns that
|
|
25
|
+
runs before any network call, cutting latency on obviously-bad inputs.
|
|
26
|
+
- Policy files (YAML) that map classifier scores to actions: `allow`, `block`,
|
|
27
|
+
`redact`, `flag`; attach a `reason` for downstream auditing.
|
|
28
|
+
- Async-first client with retries, exponential backoff, and automatic batch
|
|
29
|
+
grouping to stay under rate limits.
|
|
30
|
+
- Drop-in middleware for OpenAI and Anthropic SDKs: wrap a chat completion and the
|
|
31
|
+
pilot inspects both the user message and the model response.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install cuitty-pilot
|
|
37
|
+
# OpenAI / Anthropic middleware + async
|
|
38
|
+
pip install "cuitty-pilot[openai,anthropic]"
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from cuitty_pilot import Pilot
|
|
45
|
+
|
|
46
|
+
pilot = Pilot(api_key="cui_...") # reads CUITTY_API_KEY if omitted
|
|
47
|
+
|
|
48
|
+
verdict = pilot.classify("some user text", modalities=["sfw", "pii"])
|
|
49
|
+
if verdict.action == "block":
|
|
50
|
+
raise BlockedContent(verdict.reason)
|
|
51
|
+
|
|
52
|
+
redacted = pilot.redact("email me at bob@example.com") # -> "email me at [REDACTED]"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## CLI
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
cuitty-pilot classify --text "hello" --json
|
|
59
|
+
cuitty-pilot gate --input in.txt --policy policy.yaml
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Configuration
|
|
63
|
+
|
|
64
|
+
Set `CUITTY_API_KEY` (or `cuitty-pilot login`). Policy files resolve from
|
|
65
|
+
`./.cuitty/policy.yaml` then `~/.config/cuitty/policy.yaml`; override with
|
|
66
|
+
`--policy`.
|
|
67
|
+
|
|
68
|
+
## License
|
|
69
|
+
|
|
70
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/cuitty_pilot/__init__.py
|
|
4
|
+
src/cuitty_pilot/__main__.py
|
|
5
|
+
src/cuitty_pilot/cli.py
|
|
6
|
+
src/cuitty_pilot.egg-info/PKG-INFO
|
|
7
|
+
src/cuitty_pilot.egg-info/SOURCES.txt
|
|
8
|
+
src/cuitty_pilot.egg-info/dependency_links.txt
|
|
9
|
+
src/cuitty_pilot.egg-info/entry_points.txt
|
|
10
|
+
src/cuitty_pilot.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cuitty_pilot
|