tenet-client 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,75 @@
1
+ """Tenet SDK — cloud judge client and local server client.
2
+
3
+ Framework-agnostic. The LangChain adapter classes (``TenetMiddleware``,
4
+ ``TenetCallbackHandler``, ``TenetGuard``) live in the separate
5
+ ``tenet-langchain`` package and depend on this one.
6
+
7
+ Surface:
8
+
9
+ - :class:`TenetCloudJudgeClient` — calls the cloud judge route at
10
+ ``https://api.tenetlabs.com/v1/judge/evaluate``. The primary
11
+ customer-facing entry point.
12
+ - :class:`TenetClient` — calls the local Tenet server (HTTP
13
+ ``http://127.0.0.1:19990``). Used by the Tenet desktop app and any
14
+ on-prem-deployed local server.
15
+ - :exc:`JudgeUnavailableError` / :exc:`TenetConnectionError` /
16
+ :exc:`TenetViolationError` — exception types for failure handling.
17
+ - ``CloudJudgeRequest`` / ``CloudJudgeResponse`` etc. — Pydantic
18
+ wire types if you need them.
19
+ """
20
+
21
+ from tenet_client.client import TenetClient
22
+ from tenet_client.cloud_client import TenetCloudJudgeClient
23
+ from tenet_client.cloud_models import (
24
+ CloudJudgeDecision,
25
+ CloudJudgePhase,
26
+ CloudJudgeRequest,
27
+ CloudJudgeResponse,
28
+ JudgeUnavailableError,
29
+ )
30
+ from tenet_client.decorators import JudgeBlocked, judged
31
+ from tenet_client.exceptions import TenetConnectionError, TenetViolationError
32
+ from tenet_client.policy import (
33
+ JudgeAction,
34
+ JudgeContext,
35
+ JudgePolicy,
36
+ JudgeVerdict,
37
+ )
38
+ from tenet_client.models import (
39
+ DetectResponse,
40
+ EvaluateRequest,
41
+ EvaluateResponse,
42
+ FindDecisionRequest,
43
+ FindDecisionResponse,
44
+ HealthResponse,
45
+ RedactResponse,
46
+ StoreDecisionRequest,
47
+ Violation,
48
+ )
49
+
50
+ __all__ = [
51
+ "CloudJudgeDecision",
52
+ "CloudJudgePhase",
53
+ "CloudJudgeRequest",
54
+ "CloudJudgeResponse",
55
+ "DetectResponse",
56
+ "EvaluateRequest",
57
+ "EvaluateResponse",
58
+ "FindDecisionRequest",
59
+ "FindDecisionResponse",
60
+ "HealthResponse",
61
+ "JudgeAction",
62
+ "JudgeBlocked",
63
+ "JudgeContext",
64
+ "JudgePolicy",
65
+ "JudgeUnavailableError",
66
+ "JudgeVerdict",
67
+ "RedactResponse",
68
+ "StoreDecisionRequest",
69
+ "TenetClient",
70
+ "TenetCloudJudgeClient",
71
+ "TenetConnectionError",
72
+ "TenetViolationError",
73
+ "Violation",
74
+ "judged",
75
+ ]
tenet_client/client.py ADDED
@@ -0,0 +1,191 @@
1
+ """Async and sync HTTP client wrapping the Tenet server API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from pathlib import Path
7
+
8
+ import httpx
9
+
10
+ from tenet_client.exceptions import TenetConnectionError
11
+ from tenet_client.models import (
12
+ DetectResponse,
13
+ EvaluateRequest,
14
+ EvaluateResponse,
15
+ FindDecisionRequest,
16
+ FindDecisionResponse,
17
+ HealthResponse,
18
+ RedactResponse,
19
+ StoreDecisionRequest,
20
+ )
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ _DEFAULT_URL = "http://127.0.0.1:19990"
25
+ _API_KEY_PATH = Path("~/.tenet/api_key").expanduser()
26
+
27
+
28
+ def _read_api_key() -> str | None:
29
+ """Read API key from ~/.tenet/api_key if it exists."""
30
+ try:
31
+ if _API_KEY_PATH.exists():
32
+ return _API_KEY_PATH.read_text().strip() or None
33
+ except OSError:
34
+ pass
35
+ return None
36
+
37
+
38
+ class TenetClient:
39
+ """HTTP client for the Tenet server API.
40
+
41
+ Supports both async and sync usage patterns.
42
+ Auto-reads the API key from ``~/.tenet/api_key`` if not provided.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ base_url: str = _DEFAULT_URL,
48
+ api_key: str | None = None,
49
+ timeout: float = 10.0,
50
+ fail_open: bool = True,
51
+ ):
52
+ if api_key is None:
53
+ api_key = _read_api_key()
54
+
55
+ self._base_url = base_url.rstrip("/")
56
+ self._api_key = api_key
57
+ self._timeout = timeout
58
+ self._fail_open = fail_open
59
+ self._async_client: httpx.AsyncClient | None = None
60
+ self._sync_client: httpx.Client | None = None
61
+
62
+ @property
63
+ def _headers(self) -> dict[str, str]:
64
+ if self._api_key:
65
+ return {"Authorization": f"Bearer {self._api_key}"}
66
+ return {}
67
+
68
+ # -- Async interface --
69
+
70
+ async def _get_async_client(self) -> httpx.AsyncClient:
71
+ if self._async_client is None or self._async_client.is_closed:
72
+ self._async_client = httpx.AsyncClient(
73
+ base_url=self._base_url,
74
+ headers=self._headers,
75
+ timeout=self._timeout,
76
+ )
77
+ return self._async_client
78
+
79
+ async def evaluate_async(self, request: EvaluateRequest) -> EvaluateResponse:
80
+ """Evaluate an agent action against tenet rules (async)."""
81
+ client = await self._get_async_client()
82
+ try:
83
+ resp = await client.post("/evaluate", json=request.model_dump())
84
+ resp.raise_for_status()
85
+ return EvaluateResponse.model_validate(resp.json())
86
+ except httpx.ConnectError as exc:
87
+ if self._fail_open:
88
+ logger.warning("Tenet server unreachable (fail_open=True): %s", exc)
89
+ return EvaluateResponse(
90
+ violations=[], has_violations=False, should_block=False,
91
+ processing_time_ms=0.0,
92
+ )
93
+ raise TenetConnectionError() from exc
94
+
95
+ async def health_async(self) -> HealthResponse:
96
+ client = await self._get_async_client()
97
+ resp = await client.get("/health")
98
+ resp.raise_for_status()
99
+ return HealthResponse.model_validate(resp.json())
100
+
101
+ async def detect_async(self, text: str) -> DetectResponse:
102
+ client = await self._get_async_client()
103
+ resp = await client.post("/detect", json={"text": text})
104
+ resp.raise_for_status()
105
+ return DetectResponse.model_validate(resp.json())
106
+
107
+ async def redact_async(self, text: str, session_id: str | None = None) -> RedactResponse:
108
+ client = await self._get_async_client()
109
+ payload: dict = {"text": text}
110
+ if session_id:
111
+ payload["session_id"] = session_id
112
+ resp = await client.post("/redact", json=payload)
113
+ resp.raise_for_status()
114
+ return RedactResponse.model_validate(resp.json())
115
+
116
+ async def find_decision_async(self, request: FindDecisionRequest) -> FindDecisionResponse:
117
+ client = await self._get_async_client()
118
+ resp = await client.post("/decisions/find", json=request.model_dump())
119
+ resp.raise_for_status()
120
+ return FindDecisionResponse.model_validate(resp.json())
121
+
122
+ async def store_decision_async(self, request: StoreDecisionRequest) -> None:
123
+ client = await self._get_async_client()
124
+ resp = await client.post("/decisions/store", json=request.model_dump())
125
+ resp.raise_for_status()
126
+
127
+ async def close_async(self) -> None:
128
+ if self._async_client and not self._async_client.is_closed:
129
+ await self._async_client.aclose()
130
+
131
+ # -- Sync interface --
132
+
133
+ def _get_sync_client(self) -> httpx.Client:
134
+ if self._sync_client is None or self._sync_client.is_closed:
135
+ self._sync_client = httpx.Client(
136
+ base_url=self._base_url,
137
+ headers=self._headers,
138
+ timeout=self._timeout,
139
+ )
140
+ return self._sync_client
141
+
142
+ def evaluate(self, request: EvaluateRequest) -> EvaluateResponse:
143
+ client = self._get_sync_client()
144
+ try:
145
+ resp = client.post("/evaluate", json=request.model_dump())
146
+ resp.raise_for_status()
147
+ return EvaluateResponse.model_validate(resp.json())
148
+ except httpx.ConnectError as exc:
149
+ if self._fail_open:
150
+ logger.warning("Tenet server unreachable (fail_open=True): %s", exc)
151
+ return EvaluateResponse(
152
+ violations=[], has_violations=False, should_block=False,
153
+ processing_time_ms=0.0,
154
+ )
155
+ raise TenetConnectionError() from exc
156
+
157
+ def health(self) -> HealthResponse:
158
+ client = self._get_sync_client()
159
+ resp = client.get("/health")
160
+ resp.raise_for_status()
161
+ return HealthResponse.model_validate(resp.json())
162
+
163
+ def detect(self, text: str) -> DetectResponse:
164
+ client = self._get_sync_client()
165
+ resp = client.post("/detect", json={"text": text})
166
+ resp.raise_for_status()
167
+ return DetectResponse.model_validate(resp.json())
168
+
169
+ def redact(self, text: str, session_id: str | None = None) -> RedactResponse:
170
+ client = self._get_sync_client()
171
+ payload: dict = {"text": text}
172
+ if session_id:
173
+ payload["session_id"] = session_id
174
+ resp = client.post("/redact", json=payload)
175
+ resp.raise_for_status()
176
+ return RedactResponse.model_validate(resp.json())
177
+
178
+ def find_decision(self, request: FindDecisionRequest) -> FindDecisionResponse:
179
+ client = self._get_sync_client()
180
+ resp = client.post("/decisions/find", json=request.model_dump())
181
+ resp.raise_for_status()
182
+ return FindDecisionResponse.model_validate(resp.json())
183
+
184
+ def store_decision(self, request: StoreDecisionRequest) -> None:
185
+ client = self._get_sync_client()
186
+ resp = client.post("/decisions/store", json=request.model_dump())
187
+ resp.raise_for_status()
188
+
189
+ def close(self) -> None:
190
+ if self._sync_client and not self._sync_client.is_closed:
191
+ self._sync_client.close()