enkryptai-sdk 0.1.5__py3-none-any.whl → 0.1.7__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.
@@ -1,65 +1,122 @@
1
- import requests
1
+ # import requests
2
+ from .base import BaseClient
2
3
  from .config import GuardrailsConfig
3
4
  from .response import GuardrailsResponse, PIIResponse
5
+ from .dto import (
6
+ GuardrailsHealthResponse,
7
+ GuardrailsModelsResponse,
8
+ # GuardrailDetectors,
9
+ # GuardrailsDetectRequest,
10
+ # GuardrailsPolicyDetectRequest,
11
+ # DetectResponseSummary,
12
+ # DetectResponseDetails,
13
+ GuardrailsDetectResponse,
14
+ # GuardrailsPIIRequest,
15
+ GuardrailsPIIResponse,
16
+ # GuardrailsHallucinationRequest,
17
+ GuardrailsHallucinationResponse,
18
+ # GuardrailsAdherenceRequest,
19
+ GuardrailsAdherenceResponse,
20
+ # GuardrailsRelevancyRequest,
21
+ GuardrailsRelevancyResponse,
22
+ # GuardrailsPolicyRequest,
23
+ GuardrailsPolicyData,
24
+ GuardrailsaPolicyResponse,
25
+ # GuardrailsDeletePolicyData,
26
+ GuardrailsDeletePolicyResponse,
27
+ GuardrailsListPoliciesResponse,
28
+ )
4
29
 
5
- class GuardrailsClient:
30
+ # ---------------------------------------
31
+ # TODO: Use DTOs for request data as well
32
+ # ---------------------------------------
33
+
34
+ class GuardrailsClientError(Exception):
35
+ """
36
+ A custom exception for GuardrailsClient errors.
37
+ """
38
+
39
+ pass
40
+
41
+
42
+ class GuardrailsClient(BaseClient):
6
43
  """
7
44
  A client for interacting with Enkrypt AI Guardrails API endpoints.
8
45
  """
46
+ def __init__(self, api_key: str, base_url: str = "https://api.enkryptai.com:443"):
47
+ super().__init__(api_key, base_url)
9
48
 
10
- def __init__(self, api_key, base_url="https://api.enkryptai.com"):
11
- """
12
- Initializes the client.
49
+ # def __init__(self, api_key, base_url="https://api.enkryptai.com"):
50
+ # """
51
+ # Initializes the client.
13
52
 
14
- Parameters:
15
- - api_key (str): Your API key for authenticating with the service.
16
- - base_url (str): Base URL of the API (default: "https://api.enkryptai.com").
17
- """
18
- self.api_key = api_key
19
- self.base_url = base_url.rstrip('/')
20
- self.session = requests.Session()
53
+ # Parameters:
54
+ # - api_key (str): Your API key for authenticating with the service.
55
+ # - base_url (str): Base URL of the API (default: "https://api.enkryptai.com").
56
+ # """
57
+ # self.api_key = api_key
58
+ # self.base_url = base_url.rstrip('/')
59
+ # self.session = requests.Session()
21
60
 
22
- def _request(self, method, endpoint, headers=None, **kwargs):
23
- """
24
- Internal helper to send an HTTP request.
61
+ # def _request(self, method, endpoint, headers=None, **kwargs):
62
+ # """
63
+ # Internal helper to send an HTTP request.
25
64
 
26
- Automatically adds the API key to headers.
27
- """
28
- url = self.base_url + endpoint
29
- headers = headers or {}
30
- if 'apikey' not in headers:
31
- headers['apikey'] = self.api_key
65
+ # Automatically adds the API key to headers.
66
+ # """
67
+ # url = self.base_url + endpoint
68
+ # headers = headers or {}
69
+ # if 'apikey' not in headers:
70
+ # headers['apikey'] = self.api_key
32
71
 
33
- try:
34
- response = self.session.request(method, url, headers=headers, **kwargs)
35
- response.raise_for_status()
36
- return response.json()
72
+ # try:
73
+ # response = self.session.request(method, url, headers=headers, **kwargs)
74
+ # response.raise_for_status()
75
+ # return response.json()
37
76
 
38
- except Exception as e:
39
- print(e)
40
- return {"error": str(e)}
77
+ # except Exception as e:
78
+ # print(e)
79
+ # return {"error": str(e)}
41
80
 
42
81
  # ----------------------------
43
82
  # Basic Guardrails Endpoints
44
83
  # ----------------------------
45
84
 
46
- def health(self):
85
+ def get_health(self):
47
86
  """
48
87
  Get the health status of the service.
49
88
  """
50
- return self._request("GET", "/guardrails/health")
89
+ try:
90
+ response = self._request("GET", "/guardrails/health")
91
+ if response.get("error"):
92
+ raise GuardrailsClientError(response["error"])
93
+ return GuardrailsHealthResponse.from_dict(response)
94
+ except Exception as e:
95
+ raise GuardrailsClientError(str(e))
51
96
 
52
- def status(self):
97
+ def get_status(self):
53
98
  """
54
99
  Check if the API is up and running.
55
100
  """
56
- return self._request("GET", "/guardrails/status")
101
+ try:
102
+ response = self._request("GET", "/guardrails/status")
103
+ if response.get("error"):
104
+ raise GuardrailsClientError(response["error"])
105
+ return GuardrailsHealthResponse.from_dict(response)
106
+ except Exception as e:
107
+ raise GuardrailsClientError(str(e))
57
108
 
58
- def models(self):
109
+ def get_models(self):
59
110
  """
60
111
  Retrieve the list of models loaded by the service.
61
112
  """
62
- return self._request("GET", "/guardrails/models")
113
+ try:
114
+ response = self._request("GET", "/guardrails/models")
115
+ if response.get("error"):
116
+ raise GuardrailsClientError(response["error"])
117
+ return GuardrailsModelsResponse.from_dict(response)
118
+ except Exception as e:
119
+ raise GuardrailsClientError(str(e))
63
120
 
64
121
  def detect(self, text, config=None):
65
122
  """
@@ -72,24 +129,32 @@ class GuardrailsClient:
72
129
  If not provided, defaults to injection attack detection only.
73
130
 
74
131
  Returns:
75
- - JSON response from the API.
132
+ - Response from the API.
76
133
  """
77
134
  # Use injection attack config by default if none provided
78
135
  if config is None:
79
136
  config = GuardrailsConfig.injection_attack()
80
137
 
81
- # Allow passing in either a dict or a GuardrailsConfig instance.
138
+ # Allow passing in either a dict or a GuardrailsConfig or GuardrailDetectors instance
82
139
  if hasattr(config, "as_dict"):
83
140
  config = config.as_dict()
141
+ if hasattr(config, "to_dict"):
142
+ config = config.to_dict()
84
143
 
85
144
  payload = {
86
145
  "text": text,
87
146
  "detectors": config
88
147
  }
89
- response_body = self._request("POST", "/guardrails/detect", json=payload)
90
- return GuardrailsResponse(response_body)
91
148
 
92
- def pii(self, text, mode, key="null", entities=None):
149
+ try:
150
+ response = self._request("POST", "/guardrails/detect", json=payload)
151
+ if response.get("error"):
152
+ raise GuardrailsClientError(response["error"])
153
+ return GuardrailsDetectResponse.from_dict(response)
154
+ except Exception as e:
155
+ raise GuardrailsClientError(str(e))
156
+
157
+ def pii(self, text, mode="request", key="null", entities=None):
93
158
  """
94
159
  Detects Personally Identifiable Information (PII) and can de-anonymize it.
95
160
  """
@@ -99,14 +164,72 @@ class GuardrailsClient:
99
164
  "key": key,
100
165
  "entities": entities
101
166
  }
102
- response_body = self._request("POST", "/guardrails/pii", json=payload)
103
- return PIIResponse(response_body)
167
+
168
+ try:
169
+ response = self._request("POST", "/guardrails/pii", json=payload)
170
+ if response.get("error"):
171
+ raise GuardrailsClientError(response["error"])
172
+ return GuardrailsPIIResponse.from_dict(response)
173
+ except Exception as e:
174
+ raise GuardrailsClientError(str(e))
175
+
176
+ def hallucination(self, request_text, response_text, context=""):
177
+ """
178
+ Detects hallucination in the response text.
179
+ """
180
+ payload = {
181
+ "request_text": request_text,
182
+ "response_text": response_text,
183
+ "context": context
184
+ }
185
+
186
+ try:
187
+ response = self._request("POST", "/guardrails/hallucination", json=payload)
188
+ if response.get("error"):
189
+ raise GuardrailsClientError(response["error"])
190
+ return GuardrailsHallucinationResponse.from_dict(response)
191
+ except Exception as e:
192
+ raise GuardrailsClientError(str(e))
193
+
194
+ def adherence(self, llm_answer, context):
195
+ """
196
+ Check the adherence of an LLM answer to the provided context.
197
+ """
198
+ payload = {
199
+ "llm_answer": llm_answer,
200
+ "context": context
201
+ }
202
+
203
+ try:
204
+ response = self._request("POST", "/guardrails/adherence", json=payload)
205
+ if response.get("error"):
206
+ raise GuardrailsClientError(response["error"])
207
+ return GuardrailsAdherenceResponse.from_dict(response)
208
+ except Exception as e:
209
+ raise GuardrailsClientError(str(e))
210
+
211
+ def relevancy(self, question, llm_answer):
212
+ """
213
+ Check the relevancy of an LLM answer to the provided question.
214
+ """
215
+ payload = {
216
+ "question": question,
217
+ "llm_answer": llm_answer
218
+ }
219
+
220
+ try:
221
+ response = self._request("POST", "/guardrails/relevancy", json=payload)
222
+ if response.get("error"):
223
+ raise GuardrailsClientError(response["error"])
224
+ return GuardrailsRelevancyResponse.from_dict(response)
225
+ except Exception as e:
226
+ raise GuardrailsClientError(str(e))
104
227
 
105
228
  # ----------------------------
106
229
  # Guardrails Policy Endpoints
107
230
  # ----------------------------
108
231
 
109
- def add_policy(self, name, config, description="guardrails policy"):
232
+ def add_policy(self, policy_name, config, description="guardrails policy"):
110
233
  """
111
234
  Create a new policy with custom configurations.
112
235
 
@@ -119,64 +242,78 @@ class GuardrailsClient:
119
242
  # Allow passing in either a dict or a GuardrailsConfig instance
120
243
  if hasattr(config, "as_dict"):
121
244
  config = config.as_dict()
245
+ if hasattr(config, "to_dict"):
246
+ config = config.to_dict()
122
247
 
123
248
  payload = {
124
- "name": name,
249
+ "name": policy_name,
125
250
  "description": description,
126
251
  "detectors": config
127
252
  }
128
-
253
+
129
254
  try:
130
- return self._request("POST", "/guardrails/add-policy", json=payload)
131
-
255
+ response = self._request("POST", "/guardrails/add-policy", json=payload)
256
+ if response.get("error"):
257
+ raise GuardrailsClientError(response["error"])
258
+ return GuardrailsaPolicyResponse.from_dict(response)
132
259
  except Exception as e:
133
- print(e)
134
- return {"error": str(e)}
260
+ raise GuardrailsClientError(str(e))
135
261
 
136
262
  def get_policy(self, policy_name):
137
263
  """
138
264
  Retrieve an existing policy by providing its header identifier.
139
265
  """
140
266
  headers = {"X-Enkrypt-Policy": policy_name}
267
+
141
268
  try:
142
- return self._request("GET", "/guardrails/get-policy", headers=headers)
269
+ response = self._request("GET", "/guardrails/get-policy", headers=headers)
270
+ if response.get("error"):
271
+ raise GuardrailsClientError(response["error"])
272
+ return GuardrailsPolicyData.from_dict(response)
143
273
  except Exception as e:
144
- print(e)
145
- return {"error": str(e)}
274
+ raise GuardrailsClientError(str(e))
146
275
 
147
- def modify_policy(self, policy_name, config, name=None, description="guardrails policy"):
276
+ def modify_policy(self, policy_name, config, new_policy_name=None, description="guardrails policy"):
148
277
  """
149
278
  Modify an existing policy.
150
279
  """
151
280
  # Allow passing in either a dict or a GuardrailsConfig instance
152
281
  if hasattr(config, "as_dict"):
153
282
  config = config.as_dict()
154
-
155
- if name is None:
156
- name = policy_name
157
-
283
+ if hasattr(config, "to_dict"):
284
+ config = config.to_dict()
285
+
286
+ if new_policy_name is None:
287
+ new_policy_name = policy_name
288
+
158
289
  headers = {"X-Enkrypt-Policy": policy_name}
159
290
  payload = {
160
291
  "detectors": config,
161
- "name": name,
292
+ "name": new_policy_name,
162
293
  "description": description
163
294
  }
295
+
164
296
  try:
165
- return self._request("PATCH", "/guardrails/modify-policy", headers=headers, json=payload)
297
+ response = self._request("PATCH", "/guardrails/modify-policy", headers=headers, json=payload)
298
+ if response.get("error"):
299
+ raise GuardrailsClientError(response["error"])
300
+ return GuardrailsaPolicyResponse.from_dict(response)
166
301
  except Exception as e:
167
- print(e)
168
- return {"error": str(e)}
302
+ raise GuardrailsClientError(str(e))
169
303
 
170
304
  def delete_policy(self, policy_name):
171
305
  """
172
306
  Delete a policy.
173
307
  """
174
308
  headers = {"X-Enkrypt-Policy": policy_name}
309
+
175
310
  try:
176
- return self._request("DELETE", "/guardrails/delete-policy", headers=headers)
311
+ response = self._request("DELETE", "/guardrails/delete-policy", headers=headers)
312
+ if response.get("error"):
313
+ raise GuardrailsClientError(response["error"])
314
+ return GuardrailsDeletePolicyResponse.from_dict(response)
177
315
  except Exception as e:
178
- print(e)
179
- return {"error": str(e)}
316
+ raise GuardrailsClientError(str(e))
180
317
 
181
318
  def policy_detect(self, policy_name, text):
182
319
  """
@@ -184,12 +321,24 @@ class GuardrailsClient:
184
321
  """
185
322
  headers = {"X-Enkrypt-Policy": policy_name}
186
323
  payload = {"text": text}
187
-
324
+
188
325
  try:
189
-
190
- response_body = self._request("POST", "/guardrails/policy/detect", headers=headers, json=payload)
191
- return GuardrailsResponse(response_body)
192
-
326
+ response = self._request("POST", "/guardrails/policy/detect", headers=headers, json=payload)
327
+ if response.get("error"):
328
+ raise GuardrailsClientError(response["error"])
329
+ return GuardrailsDetectResponse.from_dict(response)
330
+ except Exception as e:
331
+ raise GuardrailsClientError(str(e))
332
+
333
+ def get_policy_list(self):
334
+ """
335
+ List all policies.
336
+ """
337
+
338
+ try:
339
+ response = self._request("GET", "/guardrails/list-policies")
340
+ if response.get("error"):
341
+ raise GuardrailsClientError(response["error"])
342
+ return GuardrailsListPoliciesResponse.from_dict(response)
193
343
  except Exception as e:
194
- print(e)
195
- return {"error": str(e)}
344
+ raise GuardrailsClientError(str(e))
@@ -0,0 +1,195 @@
1
+ import requests
2
+ from .config import GuardrailsConfig
3
+ from .response import GuardrailsResponse, PIIResponse
4
+
5
+ class GuardrailsClient:
6
+ """
7
+ A client for interacting with Enkrypt AI Guardrails API endpoints.
8
+ """
9
+
10
+ def __init__(self, api_key, base_url="https://api.enkryptai.com"):
11
+ """
12
+ Initializes the client.
13
+
14
+ Parameters:
15
+ - api_key (str): Your API key for authenticating with the service.
16
+ - base_url (str): Base URL of the API (default: "https://api.enkryptai.com").
17
+ """
18
+ self.api_key = api_key
19
+ self.base_url = base_url.rstrip('/')
20
+ self.session = requests.Session()
21
+
22
+ def _request(self, method, endpoint, headers=None, **kwargs):
23
+ """
24
+ Internal helper to send an HTTP request.
25
+
26
+ Automatically adds the API key to headers.
27
+ """
28
+ url = self.base_url + endpoint
29
+ headers = headers or {}
30
+ if 'apikey' not in headers:
31
+ headers['apikey'] = self.api_key
32
+
33
+ try:
34
+ response = self.session.request(method, url, headers=headers, **kwargs)
35
+ response.raise_for_status()
36
+ return response.json()
37
+
38
+ except Exception as e:
39
+ print(e)
40
+ return {"error": str(e)}
41
+
42
+ # ----------------------------
43
+ # Basic Guardrails Endpoints
44
+ # ----------------------------
45
+
46
+ def health(self):
47
+ """
48
+ Get the health status of the service.
49
+ """
50
+ return self._request("GET", "/guardrails/health")
51
+
52
+ def status(self):
53
+ """
54
+ Check if the API is up and running.
55
+ """
56
+ return self._request("GET", "/guardrails/status")
57
+
58
+ def models(self):
59
+ """
60
+ Retrieve the list of models loaded by the service.
61
+ """
62
+ return self._request("GET", "/guardrails/models")
63
+
64
+ def detect(self, text, config=None):
65
+ """
66
+ Detects prompt injection, toxicity, NSFW content, PII, hallucination, and more.
67
+
68
+ Parameters:
69
+ - text (str): The text to analyze.
70
+ - guardrails_config (dict or GuardrailsConfig, optional): A configuration for detectors.
71
+ If a GuardrailsConfig instance is provided, its underlying dictionary will be used.
72
+ If not provided, defaults to injection attack detection only.
73
+
74
+ Returns:
75
+ - JSON response from the API.
76
+ """
77
+ # Use injection attack config by default if none provided
78
+ if config is None:
79
+ config = GuardrailsConfig.injection_attack()
80
+
81
+ # Allow passing in either a dict or a GuardrailsConfig instance.
82
+ if hasattr(config, "as_dict"):
83
+ config = config.as_dict()
84
+
85
+ payload = {
86
+ "text": text,
87
+ "detectors": config
88
+ }
89
+ response_body = self._request("POST", "/guardrails/detect", json=payload)
90
+ return GuardrailsResponse(response_body)
91
+
92
+ def pii(self, text, mode, key="null", entities=None):
93
+ """
94
+ Detects Personally Identifiable Information (PII) and can de-anonymize it.
95
+ """
96
+ payload = {
97
+ "text": text,
98
+ "mode": mode,
99
+ "key": key,
100
+ "entities": entities
101
+ }
102
+ response_body = self._request("POST", "/guardrails/pii", json=payload)
103
+ return PIIResponse(response_body)
104
+
105
+ # ----------------------------
106
+ # Guardrails Policy Endpoints
107
+ # ----------------------------
108
+
109
+ def add_policy(self, name, config, description="guardrails policy"):
110
+ """
111
+ Create a new policy with custom configurations.
112
+
113
+ Args:
114
+ name (str): Name of the policy
115
+ config (dict or GuardrailsConfig): Configuration for the policy detectors.
116
+ If a GuardrailsConfig instance is provided, its underlying dictionary will be used.
117
+ description (str, optional): Description of the policy. Defaults to "guardrails policy"
118
+ """
119
+ # Allow passing in either a dict or a GuardrailsConfig instance
120
+ if hasattr(config, "as_dict"):
121
+ config = config.as_dict()
122
+
123
+ payload = {
124
+ "name": name,
125
+ "description": description,
126
+ "detectors": config
127
+ }
128
+
129
+ try:
130
+ return self._request("POST", "/guardrails/add-policy", json=payload)
131
+
132
+ except Exception as e:
133
+ print(e)
134
+ return {"error": str(e)}
135
+
136
+ def get_policy(self, policy_name):
137
+ """
138
+ Retrieve an existing policy by providing its header identifier.
139
+ """
140
+ headers = {"X-Enkrypt-Policy": policy_name}
141
+ try:
142
+ return self._request("GET", "/guardrails/get-policy", headers=headers)
143
+ except Exception as e:
144
+ print(e)
145
+ return {"error": str(e)}
146
+
147
+ def modify_policy(self, policy_name, config, name=None, description="guardrails policy"):
148
+ """
149
+ Modify an existing policy.
150
+ """
151
+ # Allow passing in either a dict or a GuardrailsConfig instance
152
+ if hasattr(config, "as_dict"):
153
+ config = config.as_dict()
154
+
155
+ if name is None:
156
+ name = policy_name
157
+
158
+ headers = {"X-Enkrypt-Policy": policy_name}
159
+ payload = {
160
+ "detectors": config,
161
+ "name": name,
162
+ "description": description
163
+ }
164
+ try:
165
+ return self._request("PATCH", "/guardrails/modify-policy", headers=headers, json=payload)
166
+ except Exception as e:
167
+ print(e)
168
+ return {"error": str(e)}
169
+
170
+ def delete_policy(self, policy_name):
171
+ """
172
+ Delete a policy.
173
+ """
174
+ headers = {"X-Enkrypt-Policy": policy_name}
175
+ try:
176
+ return self._request("DELETE", "/guardrails/delete-policy", headers=headers)
177
+ except Exception as e:
178
+ print(e)
179
+ return {"error": str(e)}
180
+
181
+ def policy_detect(self, policy_name, text):
182
+ """
183
+ Apply a specific policy to detect and filter content.
184
+ """
185
+ headers = {"X-Enkrypt-Policy": policy_name}
186
+ payload = {"text": text}
187
+
188
+ try:
189
+
190
+ response_body = self._request("POST", "/guardrails/policy/detect", headers=headers, json=payload)
191
+ return GuardrailsResponse(response_body)
192
+
193
+ except Exception as e:
194
+ print(e)
195
+ return {"error": str(e)}