cognitivfusion 0.2.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.
- cognitivfusion-0.2.0/LICENSE +21 -0
- cognitivfusion-0.2.0/MANIFEST.in +4 -0
- cognitivfusion-0.2.0/PKG-INFO +103 -0
- cognitivfusion-0.2.0/README.md +79 -0
- cognitivfusion-0.2.0/cognitivfusion/__init__.py +7 -0
- cognitivfusion-0.2.0/cognitivfusion/client.py +623 -0
- cognitivfusion-0.2.0/cognitivfusion/errors.py +23 -0
- cognitivfusion-0.2.0/cognitivfusion/py.typed +0 -0
- cognitivfusion-0.2.0/cognitivfusion.egg-info/PKG-INFO +103 -0
- cognitivfusion-0.2.0/cognitivfusion.egg-info/SOURCES.txt +12 -0
- cognitivfusion-0.2.0/cognitivfusion.egg-info/dependency_links.txt +1 -0
- cognitivfusion-0.2.0/cognitivfusion.egg-info/top_level.txt +1 -0
- cognitivfusion-0.2.0/pyproject.toml +48 -0
- cognitivfusion-0.2.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CognitivFusion
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cognitivfusion
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Zero-dependency Python SDK for the CognitivFusion HR AI Governance API.
|
|
5
|
+
Author-email: CognitivFusion <engineering@cognitivfusion.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://cognitivfusion.com
|
|
8
|
+
Project-URL: Documentation, https://staging.cognitivfusion.com/docs
|
|
9
|
+
Keywords: cognitivfusion,ai-governance,eu-ai-act,hr-tech,compliance,llm-gateway,pii-redaction,hitl
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# cognitivfusion (Python SDK)
|
|
26
|
+
|
|
27
|
+
Zero-dependency Python 3.9+ SDK for the CognitivFusion HR AI Governance API.
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install cognitivfusion
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Quickstart — Option A: Wrap any LLM call in 5 lines (`cf.govern`)
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import os
|
|
39
|
+
from cognitivfusion import CognitivFusionClient
|
|
40
|
+
|
|
41
|
+
cf = CognitivFusionClient(
|
|
42
|
+
api_key=os.environ["CF_API_KEY"],
|
|
43
|
+
base_url="https://staging.cognitivfusion.com",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
result = cf.govern(
|
|
47
|
+
prompt="Shortlist candidates for the senior backend engineer role.",
|
|
48
|
+
jurisdiction="UK",
|
|
49
|
+
call_model=lambda prompt, system_prompt: my_llm_call(prompt, system_prompt),
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
if not result.allowed:
|
|
53
|
+
print("Blocked at:", result.blocked_at, "Audit ID:", result.audit_id)
|
|
54
|
+
else:
|
|
55
|
+
print("Approved output:", result.output)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Quickstart — Option B: Drop-in AI Gateway (OpenAI / Anthropic / Gemini)
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
import os
|
|
62
|
+
from openai import OpenAI
|
|
63
|
+
from cognitivfusion import CognitivFusionClient
|
|
64
|
+
|
|
65
|
+
cf = CognitivFusionClient(
|
|
66
|
+
api_key=os.environ["CF_API_KEY"],
|
|
67
|
+
base_url="https://staging.cognitivfusion.com",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
gw = cf.gateway_config(
|
|
71
|
+
"openai",
|
|
72
|
+
upstream_api_key=os.environ["OPENAI_API_KEY"],
|
|
73
|
+
customer_id="acme-corp-123",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
client = OpenAI(base_url=gw["base_url"], api_key="unused", default_headers=gw["headers"])
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## B2B2B HR-Tech Partners (Per-Employer Isolation)
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
cf.provision_sub_tenant(
|
|
83
|
+
company_name="Acme Logistics Ltd",
|
|
84
|
+
external_customer_id="acme-corp-123",
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
acme = cf.for_customer("acme-corp-123")
|
|
88
|
+
verdict = acme.verify("Draft an interview rubric for warehouse supervisors.", jurisdiction="UK")
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Security Guarantees
|
|
92
|
+
|
|
93
|
+
- Uses only Python standard library (`urllib.request`, `json`) — zero third-party supply-chain dependencies.
|
|
94
|
+
- Enforces `https://` (`http://` allowed only for `localhost`, `127.0.0.1`, `[::1]`).
|
|
95
|
+
- Blocks HTTP redirects so Bearer API keys are never forwarded to foreign hosts.
|
|
96
|
+
- Masks the API key in `repr(client)` and `str(client)`.
|
|
97
|
+
- Validates integer audit IDs and UUID path parameters before sending requests.
|
|
98
|
+
|
|
99
|
+
## Run Tests
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
PYTHONPATH=packages/python-sdk python3 -m unittest discover -s packages/python-sdk/tests -v
|
|
103
|
+
```
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# cognitivfusion (Python SDK)
|
|
2
|
+
|
|
3
|
+
Zero-dependency Python 3.9+ SDK for the CognitivFusion HR AI Governance API.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install cognitivfusion
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quickstart — Option A: Wrap any LLM call in 5 lines (`cf.govern`)
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import os
|
|
15
|
+
from cognitivfusion import CognitivFusionClient
|
|
16
|
+
|
|
17
|
+
cf = CognitivFusionClient(
|
|
18
|
+
api_key=os.environ["CF_API_KEY"],
|
|
19
|
+
base_url="https://staging.cognitivfusion.com",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
result = cf.govern(
|
|
23
|
+
prompt="Shortlist candidates for the senior backend engineer role.",
|
|
24
|
+
jurisdiction="UK",
|
|
25
|
+
call_model=lambda prompt, system_prompt: my_llm_call(prompt, system_prompt),
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
if not result.allowed:
|
|
29
|
+
print("Blocked at:", result.blocked_at, "Audit ID:", result.audit_id)
|
|
30
|
+
else:
|
|
31
|
+
print("Approved output:", result.output)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quickstart — Option B: Drop-in AI Gateway (OpenAI / Anthropic / Gemini)
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import os
|
|
38
|
+
from openai import OpenAI
|
|
39
|
+
from cognitivfusion import CognitivFusionClient
|
|
40
|
+
|
|
41
|
+
cf = CognitivFusionClient(
|
|
42
|
+
api_key=os.environ["CF_API_KEY"],
|
|
43
|
+
base_url="https://staging.cognitivfusion.com",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
gw = cf.gateway_config(
|
|
47
|
+
"openai",
|
|
48
|
+
upstream_api_key=os.environ["OPENAI_API_KEY"],
|
|
49
|
+
customer_id="acme-corp-123",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
client = OpenAI(base_url=gw["base_url"], api_key="unused", default_headers=gw["headers"])
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## B2B2B HR-Tech Partners (Per-Employer Isolation)
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
cf.provision_sub_tenant(
|
|
59
|
+
company_name="Acme Logistics Ltd",
|
|
60
|
+
external_customer_id="acme-corp-123",
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
acme = cf.for_customer("acme-corp-123")
|
|
64
|
+
verdict = acme.verify("Draft an interview rubric for warehouse supervisors.", jurisdiction="UK")
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Security Guarantees
|
|
68
|
+
|
|
69
|
+
- Uses only Python standard library (`urllib.request`, `json`) — zero third-party supply-chain dependencies.
|
|
70
|
+
- Enforces `https://` (`http://` allowed only for `localhost`, `127.0.0.1`, `[::1]`).
|
|
71
|
+
- Blocks HTTP redirects so Bearer API keys are never forwarded to foreign hosts.
|
|
72
|
+
- Masks the API key in `repr(client)` and `str(client)`.
|
|
73
|
+
- Validates integer audit IDs and UUID path parameters before sending requests.
|
|
74
|
+
|
|
75
|
+
## Run Tests
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
PYTHONPATH=packages/python-sdk python3 -m unittest discover -s packages/python-sdk/tests -v
|
|
79
|
+
```
|
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
"""Zero-dependency Python SDK for the CognitivFusion HR AI Governance API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple
|
|
12
|
+
|
|
13
|
+
from .errors import CFApiError, CFRedirectError
|
|
14
|
+
|
|
15
|
+
_LOCAL_HOSTS = {"localhost", "127.0.0.1", "[::1]", "::1"}
|
|
16
|
+
_UUID_RE = re.compile(
|
|
17
|
+
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
|
18
|
+
re.IGNORECASE,
|
|
19
|
+
)
|
|
20
|
+
_CUSTOMER_ID_RE = re.compile(r"^[A-Za-z0-9._:@/-]{1,128}$")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _assert_no_header_injection(value: str, label: str) -> str:
|
|
24
|
+
if "\r" in value or "\n" in value:
|
|
25
|
+
raise ValueError(f"{label} must not contain CR or LF characters")
|
|
26
|
+
return value
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _validate_customer_id(value: str) -> str:
|
|
30
|
+
trimmed = value.strip()
|
|
31
|
+
if not _CUSTOMER_ID_RE.match(trimmed):
|
|
32
|
+
raise ValueError("customer_id must be 1-128 safe identifier characters")
|
|
33
|
+
return trimmed
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _assert_https_or_local_url(raw: str, label: str) -> str:
|
|
37
|
+
parsed = urllib.parse.urlparse(raw)
|
|
38
|
+
if parsed.scheme not in ("https", "http") or not parsed.netloc:
|
|
39
|
+
raise ValueError(f"{label} is not a valid URL: {raw}")
|
|
40
|
+
host = (parsed.hostname or "").lower()
|
|
41
|
+
if parsed.scheme != "https" and host not in _LOCAL_HOSTS:
|
|
42
|
+
raise ValueError(f"{label} must use https:// (http:// is allowed only for localhost)")
|
|
43
|
+
return raw
|
|
44
|
+
|
|
45
|
+
TransportFn = Callable[
|
|
46
|
+
[str, str, Dict[str, str], Optional[bytes], float],
|
|
47
|
+
Tuple[int, Dict[str, str], bytes],
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
52
|
+
"""Refuses HTTP redirects so Bearer API keys never forward to foreign hosts."""
|
|
53
|
+
|
|
54
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[override]
|
|
55
|
+
raise CFRedirectError(
|
|
56
|
+
f"Refusing HTTP {code} redirect from CognitivFusion API to protect credentials"
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _default_transport(
|
|
61
|
+
method: str,
|
|
62
|
+
url: str,
|
|
63
|
+
headers: Dict[str, str],
|
|
64
|
+
body: Optional[bytes],
|
|
65
|
+
timeout_s: float,
|
|
66
|
+
) -> Tuple[int, Dict[str, str], bytes]:
|
|
67
|
+
req = urllib.request.Request(url=url, data=body, headers=headers, method=method)
|
|
68
|
+
host = (urllib.parse.urlparse(url).hostname or "").lower()
|
|
69
|
+
handlers: List[Any] = [_NoRedirectHandler()]
|
|
70
|
+
if host in _LOCAL_HOSTS:
|
|
71
|
+
handlers.append(urllib.request.ProxyHandler({}))
|
|
72
|
+
opener = urllib.request.build_opener(*handlers)
|
|
73
|
+
try:
|
|
74
|
+
with opener.open(req, timeout=timeout_s) as resp:
|
|
75
|
+
status = getattr(resp, "status", resp.getcode())
|
|
76
|
+
resp_headers = {k.lower(): v for k, v in resp.headers.items()}
|
|
77
|
+
return int(status), resp_headers, resp.read()
|
|
78
|
+
except urllib.error.HTTPError as exc:
|
|
79
|
+
resp_headers = {k.lower(): v for k, v in (exc.headers.items() if exc.headers else [])}
|
|
80
|
+
payload = exc.read() if hasattr(exc, "read") else b""
|
|
81
|
+
return int(exc.code), resp_headers, payload
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _audit_id_segment(audit_id: int) -> str:
|
|
85
|
+
if isinstance(audit_id, bool) or not isinstance(audit_id, int) or audit_id < 1:
|
|
86
|
+
raise ValueError(f"audit_id must be a positive integer, got: {audit_id!r}")
|
|
87
|
+
return str(audit_id)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _uuid_segment(value: str, label: str) -> str:
|
|
91
|
+
if not isinstance(value, str) or not _UUID_RE.match(value):
|
|
92
|
+
raise ValueError(f"{label} must be a valid UUID, got: {value!r}")
|
|
93
|
+
return value
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass
|
|
97
|
+
class GovernResult:
|
|
98
|
+
"""Structured result from `CognitivFusionClient.govern()`."""
|
|
99
|
+
|
|
100
|
+
allowed: bool
|
|
101
|
+
blocked_at: Optional[str]
|
|
102
|
+
output: Optional[str]
|
|
103
|
+
ingress: Dict[str, Any]
|
|
104
|
+
egress: Optional[Dict[str, Any]]
|
|
105
|
+
audit_id: Optional[int]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class CognitivFusionClient:
|
|
109
|
+
"""Typed, zero-dependency client for the CognitivFusion HR AI Governance API."""
|
|
110
|
+
|
|
111
|
+
def __init__(
|
|
112
|
+
self,
|
|
113
|
+
api_key: str,
|
|
114
|
+
base_url: str,
|
|
115
|
+
timeout_s: float = 30.0,
|
|
116
|
+
sub_tenant_id: Optional[str] = None,
|
|
117
|
+
customer_id: Optional[str] = None,
|
|
118
|
+
transport: Optional[TransportFn] = None,
|
|
119
|
+
) -> None:
|
|
120
|
+
if not api_key or not isinstance(api_key, str):
|
|
121
|
+
raise ValueError("api_key is required")
|
|
122
|
+
_assert_no_header_injection(api_key, "api_key")
|
|
123
|
+
if not base_url or not isinstance(base_url, str):
|
|
124
|
+
raise ValueError("base_url is required")
|
|
125
|
+
_assert_https_or_local_url(base_url, "base_url")
|
|
126
|
+
|
|
127
|
+
if sub_tenant_id is not None:
|
|
128
|
+
_uuid_segment(sub_tenant_id, "sub_tenant_id")
|
|
129
|
+
|
|
130
|
+
self.__api_key = api_key
|
|
131
|
+
self._base_url = base_url.rstrip("/")
|
|
132
|
+
self._timeout_s = float(timeout_s)
|
|
133
|
+
self._default_sub_tenant_id = sub_tenant_id
|
|
134
|
+
self._default_customer_id = _validate_customer_id(customer_id) if customer_id else None
|
|
135
|
+
self._transport: TransportFn = transport or _default_transport
|
|
136
|
+
|
|
137
|
+
def __repr__(self) -> str:
|
|
138
|
+
return (
|
|
139
|
+
f"CognitivFusionClient(base_url={self._base_url!r}, "
|
|
140
|
+
f"customer_id={self._default_customer_id!r}, "
|
|
141
|
+
f"sub_tenant_id={self._default_sub_tenant_id!r}, api_key='***')"
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
__str__ = __repr__
|
|
145
|
+
|
|
146
|
+
def for_customer(self, customer_id: str) -> "CognitivFusionClient":
|
|
147
|
+
"""Return a scoped client targeting an owned employer sub-tenant via X-CF-Customer-Id."""
|
|
148
|
+
if not customer_id or not customer_id.strip():
|
|
149
|
+
raise ValueError("customer_id is required")
|
|
150
|
+
return CognitivFusionClient(
|
|
151
|
+
api_key=self.__api_key,
|
|
152
|
+
base_url=self._base_url,
|
|
153
|
+
timeout_s=self._timeout_s,
|
|
154
|
+
customer_id=customer_id.strip(),
|
|
155
|
+
transport=self._transport,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
def for_sub_tenant(self, sub_tenant_id: str) -> "CognitivFusionClient":
|
|
159
|
+
"""Return a scoped client targeting an owned employer sub-tenant via X-CF-Sub-Tenant-Id."""
|
|
160
|
+
return CognitivFusionClient(
|
|
161
|
+
api_key=self.__api_key,
|
|
162
|
+
base_url=self._base_url,
|
|
163
|
+
timeout_s=self._timeout_s,
|
|
164
|
+
sub_tenant_id=_uuid_segment(sub_tenant_id, "sub_tenant_id"),
|
|
165
|
+
transport=self._transport,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def govern(
|
|
169
|
+
self,
|
|
170
|
+
prompt: str,
|
|
171
|
+
call_model: Callable[[str, Optional[str]], str],
|
|
172
|
+
*,
|
|
173
|
+
jurisdiction: str = "UK",
|
|
174
|
+
initiator_type: str = "user",
|
|
175
|
+
check_egress: bool = True,
|
|
176
|
+
use_refactored_prompt: bool = False,
|
|
177
|
+
sub_tenant_id: Optional[str] = None,
|
|
178
|
+
customer_id: Optional[str] = None,
|
|
179
|
+
) -> GovernResult:
|
|
180
|
+
"""
|
|
181
|
+
One-call wrapper for HR-tech integrations:
|
|
182
|
+
1. Governs `prompt` before your LLM runs.
|
|
183
|
+
2. Skips `call_model` if ingress is blocked.
|
|
184
|
+
3. Governs the LLM's output before returning it (when `check_egress=True`).
|
|
185
|
+
"""
|
|
186
|
+
if not prompt or not prompt.strip():
|
|
187
|
+
raise ValueError("prompt is required")
|
|
188
|
+
if not callable(call_model):
|
|
189
|
+
raise TypeError("call_model must be callable")
|
|
190
|
+
|
|
191
|
+
ingress = self.verify(
|
|
192
|
+
prompt=prompt,
|
|
193
|
+
jurisdiction=jurisdiction,
|
|
194
|
+
initiator_type=initiator_type,
|
|
195
|
+
action_state="pending",
|
|
196
|
+
stage="ingress",
|
|
197
|
+
sub_tenant_id=sub_tenant_id,
|
|
198
|
+
customer_id=customer_id,
|
|
199
|
+
)
|
|
200
|
+
if not ingress.get("allowed"):
|
|
201
|
+
return GovernResult(
|
|
202
|
+
allowed=False,
|
|
203
|
+
blocked_at="ingress",
|
|
204
|
+
output=None,
|
|
205
|
+
ingress=ingress,
|
|
206
|
+
egress=None,
|
|
207
|
+
audit_id=ingress.get("audit_id"),
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
prompt_to_send = (
|
|
211
|
+
str(ingress.get("refactored_prompt") or prompt) if use_refactored_prompt else prompt
|
|
212
|
+
)
|
|
213
|
+
raw_output = call_model(prompt_to_send, ingress.get("system_prompt_injection"))
|
|
214
|
+
|
|
215
|
+
if not check_egress:
|
|
216
|
+
return GovernResult(
|
|
217
|
+
allowed=True,
|
|
218
|
+
blocked_at=None,
|
|
219
|
+
output=raw_output,
|
|
220
|
+
ingress=ingress,
|
|
221
|
+
egress=None,
|
|
222
|
+
audit_id=ingress.get("audit_id"),
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
egress = self.verify(
|
|
226
|
+
prompt=prompt,
|
|
227
|
+
jurisdiction=jurisdiction,
|
|
228
|
+
initiator_type=initiator_type,
|
|
229
|
+
action_state="pending",
|
|
230
|
+
stage="egress",
|
|
231
|
+
response=raw_output,
|
|
232
|
+
sub_tenant_id=sub_tenant_id,
|
|
233
|
+
customer_id=customer_id,
|
|
234
|
+
)
|
|
235
|
+
if not egress.get("allowed"):
|
|
236
|
+
return GovernResult(
|
|
237
|
+
allowed=False,
|
|
238
|
+
blocked_at="egress",
|
|
239
|
+
output=None,
|
|
240
|
+
ingress=ingress,
|
|
241
|
+
egress=egress,
|
|
242
|
+
audit_id=egress.get("audit_id"),
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
return GovernResult(
|
|
246
|
+
allowed=True,
|
|
247
|
+
blocked_at=None,
|
|
248
|
+
output=raw_output,
|
|
249
|
+
ingress=ingress,
|
|
250
|
+
egress=egress,
|
|
251
|
+
audit_id=egress.get("audit_id") or ingress.get("audit_id"),
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
def gateway_config(
|
|
255
|
+
self,
|
|
256
|
+
provider: str,
|
|
257
|
+
upstream_api_key: str,
|
|
258
|
+
*,
|
|
259
|
+
sub_tenant_id: Optional[str] = None,
|
|
260
|
+
customer_id: Optional[str] = None,
|
|
261
|
+
upstream_base_url: Optional[str] = None,
|
|
262
|
+
) -> Dict[str, Any]:
|
|
263
|
+
"""Return drop-in `base_url` and `headers` for official OpenAI, Anthropic, or Gemini SDKs."""
|
|
264
|
+
if not upstream_api_key:
|
|
265
|
+
raise ValueError("upstream_api_key is required")
|
|
266
|
+
_assert_no_header_injection(upstream_api_key, "upstream_api_key")
|
|
267
|
+
paths = {
|
|
268
|
+
"openai": "/api/v1/gateway/openai/v1",
|
|
269
|
+
"anthropic": "/api/v1/gateway/anthropic",
|
|
270
|
+
"gemini": "/api/v1/gateway/gemini",
|
|
271
|
+
}
|
|
272
|
+
if provider not in paths:
|
|
273
|
+
raise ValueError(f"Unsupported gateway provider: {provider!r}")
|
|
274
|
+
|
|
275
|
+
headers: Dict[str, str] = {
|
|
276
|
+
"Authorization": f"Bearer {self.__api_key}",
|
|
277
|
+
"x-upstream-key": upstream_api_key,
|
|
278
|
+
}
|
|
279
|
+
if upstream_base_url:
|
|
280
|
+
headers["x-upstream-base-url"] = _assert_https_or_local_url(upstream_base_url, "upstream_base_url")
|
|
281
|
+
|
|
282
|
+
sub = sub_tenant_id or self._default_sub_tenant_id
|
|
283
|
+
cust = customer_id or self._default_customer_id
|
|
284
|
+
if sub:
|
|
285
|
+
headers["X-CF-Sub-Tenant-Id"] = _uuid_segment(sub, "sub_tenant_id")
|
|
286
|
+
elif cust:
|
|
287
|
+
headers["X-CF-Customer-Id"] = _validate_customer_id(cust)
|
|
288
|
+
|
|
289
|
+
return {"base_url": f"{self._base_url}{paths[provider]}", "headers": headers}
|
|
290
|
+
|
|
291
|
+
def verify(
|
|
292
|
+
self,
|
|
293
|
+
prompt: str,
|
|
294
|
+
*,
|
|
295
|
+
jurisdiction: Optional[str] = None,
|
|
296
|
+
initiator_type: Optional[str] = None,
|
|
297
|
+
action_state: Optional[str] = None,
|
|
298
|
+
stage: Optional[str] = None,
|
|
299
|
+
response: Optional[str] = None,
|
|
300
|
+
sub_tenant_id: Optional[str] = None,
|
|
301
|
+
customer_id: Optional[str] = None,
|
|
302
|
+
) -> Dict[str, Any]:
|
|
303
|
+
"""POST /api/v1/verify."""
|
|
304
|
+
payload: Dict[str, Any] = {"prompt": prompt}
|
|
305
|
+
if jurisdiction is not None:
|
|
306
|
+
payload["jurisdiction"] = jurisdiction
|
|
307
|
+
if initiator_type is not None:
|
|
308
|
+
payload["initiator_type"] = initiator_type
|
|
309
|
+
if action_state is not None:
|
|
310
|
+
payload["action_state"] = action_state
|
|
311
|
+
if stage is not None:
|
|
312
|
+
payload["stage"] = stage
|
|
313
|
+
if response is not None:
|
|
314
|
+
payload["response"] = response
|
|
315
|
+
return self._request(
|
|
316
|
+
"POST",
|
|
317
|
+
"/api/v1/verify",
|
|
318
|
+
payload=payload,
|
|
319
|
+
sub_tenant_id=sub_tenant_id,
|
|
320
|
+
customer_id=customer_id,
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
def verify_stream(
|
|
324
|
+
self,
|
|
325
|
+
prompt: str,
|
|
326
|
+
*,
|
|
327
|
+
jurisdiction: Optional[str] = None,
|
|
328
|
+
sub_tenant_id: Optional[str] = None,
|
|
329
|
+
customer_id: Optional[str] = None,
|
|
330
|
+
) -> Iterator[Dict[str, Any]]:
|
|
331
|
+
"""POST /api/v1/verify/stream: yield parsed SSE events."""
|
|
332
|
+
payload: Dict[str, Any] = {"prompt": prompt}
|
|
333
|
+
if jurisdiction is not None:
|
|
334
|
+
payload["jurisdiction"] = jurisdiction
|
|
335
|
+
headers = self._build_headers(has_body=True, sub_tenant_id=sub_tenant_id, customer_id=customer_id)
|
|
336
|
+
headers["Accept"] = "text/event-stream"
|
|
337
|
+
raw_bytes = json.dumps(payload).encode("utf-8")
|
|
338
|
+
status, _, body = self._transport(
|
|
339
|
+
"POST",
|
|
340
|
+
f"{self._base_url}/api/v1/verify/stream",
|
|
341
|
+
headers,
|
|
342
|
+
raw_bytes,
|
|
343
|
+
self._timeout_s,
|
|
344
|
+
)
|
|
345
|
+
text = body.decode("utf-8", errors="replace")
|
|
346
|
+
if status < 200 or status >= 300:
|
|
347
|
+
self._raise_http_error(status, text)
|
|
348
|
+
|
|
349
|
+
for block in re.split(r"\r?\n\r?\n", text):
|
|
350
|
+
if not block.strip():
|
|
351
|
+
continue
|
|
352
|
+
event_name = "message"
|
|
353
|
+
data_lines: List[str] = []
|
|
354
|
+
for line in re.split(r"\r?\n", block):
|
|
355
|
+
if line.startswith("event:"):
|
|
356
|
+
event_name = line[6:].strip()
|
|
357
|
+
elif line.startswith("data:"):
|
|
358
|
+
data_lines.append(line[5:].lstrip())
|
|
359
|
+
if not data_lines:
|
|
360
|
+
continue
|
|
361
|
+
joined = "\n".join(data_lines)
|
|
362
|
+
parsed: Any = joined
|
|
363
|
+
try:
|
|
364
|
+
parsed = json.loads(joined)
|
|
365
|
+
except json.JSONDecodeError:
|
|
366
|
+
pass
|
|
367
|
+
yield {"event": event_name, "data": parsed}
|
|
368
|
+
|
|
369
|
+
def suggest_rewrite(
|
|
370
|
+
self,
|
|
371
|
+
prompt: str,
|
|
372
|
+
*,
|
|
373
|
+
jurisdiction: Optional[str] = None,
|
|
374
|
+
sub_tenant_id: Optional[str] = None,
|
|
375
|
+
customer_id: Optional[str] = None,
|
|
376
|
+
) -> Dict[str, Any]:
|
|
377
|
+
payload: Dict[str, Any] = {"prompt": prompt}
|
|
378
|
+
if jurisdiction is not None:
|
|
379
|
+
payload["jurisdiction"] = jurisdiction
|
|
380
|
+
return self._request(
|
|
381
|
+
"POST",
|
|
382
|
+
"/api/v1/verify/suggest-rewrite",
|
|
383
|
+
payload=payload,
|
|
384
|
+
sub_tenant_id=sub_tenant_id,
|
|
385
|
+
customer_id=customer_id,
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
def list_audit(
|
|
389
|
+
self,
|
|
390
|
+
*,
|
|
391
|
+
limit: Optional[int] = None,
|
|
392
|
+
offset: Optional[int] = None,
|
|
393
|
+
sub_tenant_id: Optional[str] = None,
|
|
394
|
+
customer_id: Optional[str] = None,
|
|
395
|
+
) -> Dict[str, Any]:
|
|
396
|
+
qs = self._encode_query({"limit": limit, "offset": offset})
|
|
397
|
+
return self._request(
|
|
398
|
+
"GET",
|
|
399
|
+
f"/api/v1/audit{qs}",
|
|
400
|
+
sub_tenant_id=sub_tenant_id,
|
|
401
|
+
customer_id=customer_id,
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
def get_receipt(
|
|
405
|
+
self,
|
|
406
|
+
audit_id: int,
|
|
407
|
+
*,
|
|
408
|
+
sub_tenant_id: Optional[str] = None,
|
|
409
|
+
customer_id: Optional[str] = None,
|
|
410
|
+
) -> Dict[str, Any]:
|
|
411
|
+
return self._request(
|
|
412
|
+
"GET",
|
|
413
|
+
f"/api/v1/audit/{_audit_id_segment(audit_id)}/receipt",
|
|
414
|
+
sub_tenant_id=sub_tenant_id,
|
|
415
|
+
customer_id=customer_id,
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
def get_explanation(
|
|
419
|
+
self,
|
|
420
|
+
audit_id: int,
|
|
421
|
+
*,
|
|
422
|
+
sub_tenant_id: Optional[str] = None,
|
|
423
|
+
customer_id: Optional[str] = None,
|
|
424
|
+
) -> Dict[str, Any]:
|
|
425
|
+
return self._request(
|
|
426
|
+
"GET",
|
|
427
|
+
f"/api/v1/audit/{_audit_id_segment(audit_id)}/explanation",
|
|
428
|
+
sub_tenant_id=sub_tenant_id,
|
|
429
|
+
customer_id=customer_id,
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
# ── B2B2B Partner Sub-Tenant Management ──────────────────────────────────
|
|
433
|
+
|
|
434
|
+
def provision_sub_tenant(
|
|
435
|
+
self,
|
|
436
|
+
company_name: str,
|
|
437
|
+
external_customer_id: str,
|
|
438
|
+
*,
|
|
439
|
+
email: Optional[str] = None,
|
|
440
|
+
tier: Optional[str] = None,
|
|
441
|
+
inherit_byok: Optional[bool] = None,
|
|
442
|
+
) -> Dict[str, Any]:
|
|
443
|
+
payload: Dict[str, Any] = {
|
|
444
|
+
"company_name": company_name,
|
|
445
|
+
"external_customer_id": external_customer_id,
|
|
446
|
+
}
|
|
447
|
+
if email is not None:
|
|
448
|
+
payload["email"] = email
|
|
449
|
+
if tier is not None:
|
|
450
|
+
payload["tier"] = tier
|
|
451
|
+
if inherit_byok is not None:
|
|
452
|
+
payload["inherit_byok"] = inherit_byok
|
|
453
|
+
return self._request("POST", "/api/v1/partner/sub-tenants", payload=payload, include_sub_tenant=False)
|
|
454
|
+
|
|
455
|
+
def list_sub_tenants(
|
|
456
|
+
self,
|
|
457
|
+
*,
|
|
458
|
+
limit: Optional[int] = None,
|
|
459
|
+
offset: Optional[int] = None,
|
|
460
|
+
include_archived: bool = False,
|
|
461
|
+
) -> Dict[str, Any]:
|
|
462
|
+
qs = self._encode_query(
|
|
463
|
+
{"limit": limit, "offset": offset, "include_archived": "true" if include_archived else None}
|
|
464
|
+
)
|
|
465
|
+
return self._request("GET", f"/api/v1/partner/sub-tenants{qs}", include_sub_tenant=False)
|
|
466
|
+
|
|
467
|
+
def get_sub_tenant(self, sub_tenant_id: str) -> Dict[str, Any]:
|
|
468
|
+
return self._request(
|
|
469
|
+
"GET",
|
|
470
|
+
f"/api/v1/partner/sub-tenants/{_uuid_segment(sub_tenant_id, 'sub_tenant_id')}",
|
|
471
|
+
include_sub_tenant=False,
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
def create_sub_tenant_key(
|
|
475
|
+
self,
|
|
476
|
+
sub_tenant_id: str,
|
|
477
|
+
*,
|
|
478
|
+
name: Optional[str] = None,
|
|
479
|
+
scopes: Optional[List[str]] = None,
|
|
480
|
+
expires_in_days: Optional[int] = None,
|
|
481
|
+
) -> Dict[str, Any]:
|
|
482
|
+
payload: Dict[str, Any] = {}
|
|
483
|
+
if name is not None:
|
|
484
|
+
payload["name"] = name
|
|
485
|
+
if scopes is not None:
|
|
486
|
+
payload["scopes"] = scopes
|
|
487
|
+
if expires_in_days is not None:
|
|
488
|
+
payload["expires_in_days"] = expires_in_days
|
|
489
|
+
return self._request(
|
|
490
|
+
"POST",
|
|
491
|
+
f"/api/v1/partner/sub-tenants/{_uuid_segment(sub_tenant_id, 'sub_tenant_id')}/keys",
|
|
492
|
+
payload=payload,
|
|
493
|
+
include_sub_tenant=False,
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
def list_iam_audit(
|
|
497
|
+
self,
|
|
498
|
+
*,
|
|
499
|
+
event_type: Optional[str] = None,
|
|
500
|
+
limit: Optional[int] = None,
|
|
501
|
+
offset: Optional[int] = None,
|
|
502
|
+
sub_tenant_id: Optional[str] = None,
|
|
503
|
+
customer_id: Optional[str] = None,
|
|
504
|
+
) -> Dict[str, Any]:
|
|
505
|
+
qs = self._encode_query({"event_type": event_type, "limit": limit, "offset": offset})
|
|
506
|
+
return self._request(
|
|
507
|
+
"GET",
|
|
508
|
+
f"/api/v1/admin/iam-audit{qs}",
|
|
509
|
+
sub_tenant_id=sub_tenant_id,
|
|
510
|
+
customer_id=customer_id,
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
def list_webhook_deliveries(
|
|
514
|
+
self,
|
|
515
|
+
*,
|
|
516
|
+
status: Optional[str] = None,
|
|
517
|
+
limit: Optional[int] = None,
|
|
518
|
+
sub_tenant_id: Optional[str] = None,
|
|
519
|
+
customer_id: Optional[str] = None,
|
|
520
|
+
) -> Dict[str, Any]:
|
|
521
|
+
qs = self._encode_query({"status": status, "limit": limit})
|
|
522
|
+
return self._request(
|
|
523
|
+
"GET",
|
|
524
|
+
f"/api/v1/admin/webhooks/deliveries{qs}",
|
|
525
|
+
sub_tenant_id=sub_tenant_id,
|
|
526
|
+
customer_id=customer_id,
|
|
527
|
+
)
|
|
528
|
+
|
|
529
|
+
def retry_webhook_delivery(
|
|
530
|
+
self,
|
|
531
|
+
delivery_id: str,
|
|
532
|
+
*,
|
|
533
|
+
sub_tenant_id: Optional[str] = None,
|
|
534
|
+
customer_id: Optional[str] = None,
|
|
535
|
+
) -> Dict[str, Any]:
|
|
536
|
+
return self._request(
|
|
537
|
+
"POST",
|
|
538
|
+
f"/api/v1/admin/webhooks/deliveries/{_uuid_segment(delivery_id, 'delivery_id')}/retry",
|
|
539
|
+
sub_tenant_id=sub_tenant_id,
|
|
540
|
+
customer_id=customer_id,
|
|
541
|
+
)
|
|
542
|
+
|
|
543
|
+
def health(self) -> Dict[str, Any]:
|
|
544
|
+
return self._request("GET", "/health", include_sub_tenant=False)
|
|
545
|
+
|
|
546
|
+
def readyz(self) -> Dict[str, Any]:
|
|
547
|
+
return self._request("GET", "/readyz", include_sub_tenant=False)
|
|
548
|
+
|
|
549
|
+
# ── Internal HTTP helpers ────────────────────────────────────────────────
|
|
550
|
+
|
|
551
|
+
@staticmethod
|
|
552
|
+
def _encode_query(params: Dict[str, Any]) -> str:
|
|
553
|
+
filtered = {k: str(v) for k, v in params.items() if v is not None}
|
|
554
|
+
if not filtered:
|
|
555
|
+
return ""
|
|
556
|
+
return "?" + urllib.parse.urlencode(filtered)
|
|
557
|
+
|
|
558
|
+
def _build_headers(
|
|
559
|
+
self,
|
|
560
|
+
*,
|
|
561
|
+
has_body: bool,
|
|
562
|
+
sub_tenant_id: Optional[str] = None,
|
|
563
|
+
customer_id: Optional[str] = None,
|
|
564
|
+
include_sub_tenant: bool = True,
|
|
565
|
+
) -> Dict[str, str]:
|
|
566
|
+
headers: Dict[str, str] = {
|
|
567
|
+
"Authorization": f"Bearer {self.__api_key}",
|
|
568
|
+
"Accept": "application/json",
|
|
569
|
+
}
|
|
570
|
+
if has_body:
|
|
571
|
+
headers["Content-Type"] = "application/json"
|
|
572
|
+
if include_sub_tenant:
|
|
573
|
+
sub = sub_tenant_id or self._default_sub_tenant_id
|
|
574
|
+
cust = customer_id or self._default_customer_id
|
|
575
|
+
if sub:
|
|
576
|
+
headers["X-CF-Sub-Tenant-Id"] = _uuid_segment(sub, "sub_tenant_id")
|
|
577
|
+
elif cust:
|
|
578
|
+
headers["X-CF-Customer-Id"] = _validate_customer_id(cust)
|
|
579
|
+
return headers
|
|
580
|
+
|
|
581
|
+
@staticmethod
|
|
582
|
+
def _raise_http_error(status: int, text: str) -> None:
|
|
583
|
+
data: Any = None
|
|
584
|
+
if text:
|
|
585
|
+
try:
|
|
586
|
+
data = json.loads(text)
|
|
587
|
+
except json.JSONDecodeError:
|
|
588
|
+
data = text
|
|
589
|
+
if isinstance(data, dict) and isinstance(data.get("error"), str):
|
|
590
|
+
detail = data.get("detail") if isinstance(data.get("detail"), str) else None
|
|
591
|
+
raise CFApiError(status, data["error"], detail=detail, body=data)
|
|
592
|
+
raise CFApiError(status, f"HTTP {status}", body=data)
|
|
593
|
+
|
|
594
|
+
def _request(
|
|
595
|
+
self,
|
|
596
|
+
method: str,
|
|
597
|
+
path: str,
|
|
598
|
+
*,
|
|
599
|
+
payload: Optional[Dict[str, Any]] = None,
|
|
600
|
+
sub_tenant_id: Optional[str] = None,
|
|
601
|
+
customer_id: Optional[str] = None,
|
|
602
|
+
include_sub_tenant: bool = True,
|
|
603
|
+
) -> Dict[str, Any]:
|
|
604
|
+
headers = self._build_headers(
|
|
605
|
+
has_body=payload is not None,
|
|
606
|
+
sub_tenant_id=sub_tenant_id,
|
|
607
|
+
customer_id=customer_id,
|
|
608
|
+
include_sub_tenant=include_sub_tenant,
|
|
609
|
+
)
|
|
610
|
+
body_bytes = json.dumps(payload).encode("utf-8") if payload is not None else None
|
|
611
|
+
status, _, raw = self._transport(
|
|
612
|
+
method,
|
|
613
|
+
f"{self._base_url}{path}",
|
|
614
|
+
headers,
|
|
615
|
+
body_bytes,
|
|
616
|
+
self._timeout_s,
|
|
617
|
+
)
|
|
618
|
+
text = raw.decode("utf-8", errors="replace")
|
|
619
|
+
if status < 200 or status >= 300:
|
|
620
|
+
self._raise_http_error(status, text)
|
|
621
|
+
if not text:
|
|
622
|
+
return {}
|
|
623
|
+
return json.loads(text)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""CognitivFusion SDK exceptions."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CFApiError(Exception):
|
|
7
|
+
"""Raised when the CognitivFusion Governance API returns a non-2xx status."""
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
status: int,
|
|
12
|
+
message: str,
|
|
13
|
+
detail: Optional[str] = None,
|
|
14
|
+
body: Any = None,
|
|
15
|
+
) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.status = status
|
|
18
|
+
self.detail = detail
|
|
19
|
+
self.body = body
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CFRedirectError(RuntimeError):
|
|
23
|
+
"""Raised when an HTTP redirect is encountered (blocked to protect API keys)."""
|
|
File without changes
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cognitivfusion
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Zero-dependency Python SDK for the CognitivFusion HR AI Governance API.
|
|
5
|
+
Author-email: CognitivFusion <engineering@cognitivfusion.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://cognitivfusion.com
|
|
8
|
+
Project-URL: Documentation, https://staging.cognitivfusion.com/docs
|
|
9
|
+
Keywords: cognitivfusion,ai-governance,eu-ai-act,hr-tech,compliance,llm-gateway,pii-redaction,hitl
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# cognitivfusion (Python SDK)
|
|
26
|
+
|
|
27
|
+
Zero-dependency Python 3.9+ SDK for the CognitivFusion HR AI Governance API.
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install cognitivfusion
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Quickstart — Option A: Wrap any LLM call in 5 lines (`cf.govern`)
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import os
|
|
39
|
+
from cognitivfusion import CognitivFusionClient
|
|
40
|
+
|
|
41
|
+
cf = CognitivFusionClient(
|
|
42
|
+
api_key=os.environ["CF_API_KEY"],
|
|
43
|
+
base_url="https://staging.cognitivfusion.com",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
result = cf.govern(
|
|
47
|
+
prompt="Shortlist candidates for the senior backend engineer role.",
|
|
48
|
+
jurisdiction="UK",
|
|
49
|
+
call_model=lambda prompt, system_prompt: my_llm_call(prompt, system_prompt),
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
if not result.allowed:
|
|
53
|
+
print("Blocked at:", result.blocked_at, "Audit ID:", result.audit_id)
|
|
54
|
+
else:
|
|
55
|
+
print("Approved output:", result.output)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Quickstart — Option B: Drop-in AI Gateway (OpenAI / Anthropic / Gemini)
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
import os
|
|
62
|
+
from openai import OpenAI
|
|
63
|
+
from cognitivfusion import CognitivFusionClient
|
|
64
|
+
|
|
65
|
+
cf = CognitivFusionClient(
|
|
66
|
+
api_key=os.environ["CF_API_KEY"],
|
|
67
|
+
base_url="https://staging.cognitivfusion.com",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
gw = cf.gateway_config(
|
|
71
|
+
"openai",
|
|
72
|
+
upstream_api_key=os.environ["OPENAI_API_KEY"],
|
|
73
|
+
customer_id="acme-corp-123",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
client = OpenAI(base_url=gw["base_url"], api_key="unused", default_headers=gw["headers"])
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## B2B2B HR-Tech Partners (Per-Employer Isolation)
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
cf.provision_sub_tenant(
|
|
83
|
+
company_name="Acme Logistics Ltd",
|
|
84
|
+
external_customer_id="acme-corp-123",
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
acme = cf.for_customer("acme-corp-123")
|
|
88
|
+
verdict = acme.verify("Draft an interview rubric for warehouse supervisors.", jurisdiction="UK")
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Security Guarantees
|
|
92
|
+
|
|
93
|
+
- Uses only Python standard library (`urllib.request`, `json`) — zero third-party supply-chain dependencies.
|
|
94
|
+
- Enforces `https://` (`http://` allowed only for `localhost`, `127.0.0.1`, `[::1]`).
|
|
95
|
+
- Blocks HTTP redirects so Bearer API keys are never forwarded to foreign hosts.
|
|
96
|
+
- Masks the API key in `repr(client)` and `str(client)`.
|
|
97
|
+
- Validates integer audit IDs and UUID path parameters before sending requests.
|
|
98
|
+
|
|
99
|
+
## Run Tests
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
PYTHONPATH=packages/python-sdk python3 -m unittest discover -s packages/python-sdk/tests -v
|
|
103
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
cognitivfusion/__init__.py
|
|
6
|
+
cognitivfusion/client.py
|
|
7
|
+
cognitivfusion/errors.py
|
|
8
|
+
cognitivfusion/py.typed
|
|
9
|
+
cognitivfusion.egg-info/PKG-INFO
|
|
10
|
+
cognitivfusion.egg-info/SOURCES.txt
|
|
11
|
+
cognitivfusion.egg-info/dependency_links.txt
|
|
12
|
+
cognitivfusion.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cognitivfusion
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cognitivfusion"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Zero-dependency Python SDK for the CognitivFusion HR AI Governance API."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "CognitivFusion", email = "engineering@cognitivfusion.com" },
|
|
14
|
+
]
|
|
15
|
+
requires-python = ">=3.9"
|
|
16
|
+
dependencies = []
|
|
17
|
+
keywords = [
|
|
18
|
+
"cognitivfusion",
|
|
19
|
+
"ai-governance",
|
|
20
|
+
"eu-ai-act",
|
|
21
|
+
"hr-tech",
|
|
22
|
+
"compliance",
|
|
23
|
+
"llm-gateway",
|
|
24
|
+
"pii-redaction",
|
|
25
|
+
"hitl",
|
|
26
|
+
]
|
|
27
|
+
classifiers = [
|
|
28
|
+
"Development Status :: 4 - Beta",
|
|
29
|
+
"Intended Audience :: Developers",
|
|
30
|
+
"Operating System :: OS Independent",
|
|
31
|
+
"Programming Language :: Python :: 3",
|
|
32
|
+
"Programming Language :: Python :: 3.9",
|
|
33
|
+
"Programming Language :: Python :: 3.10",
|
|
34
|
+
"Programming Language :: Python :: 3.11",
|
|
35
|
+
"Programming Language :: Python :: 3.12",
|
|
36
|
+
"Programming Language :: Python :: 3.13",
|
|
37
|
+
"Typing :: Typed",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[project.urls]
|
|
41
|
+
Homepage = "https://cognitivfusion.com"
|
|
42
|
+
Documentation = "https://staging.cognitivfusion.com/docs"
|
|
43
|
+
|
|
44
|
+
[tool.setuptools.packages.find]
|
|
45
|
+
include = ["cognitivfusion*"]
|
|
46
|
+
|
|
47
|
+
[tool.setuptools.package-data]
|
|
48
|
+
cognitivfusion = ["py.typed"]
|