trustmodel 3.7.0__tar.gz → 3.9.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.
Files changed (45) hide show
  1. {trustmodel-3.7.0 → trustmodel-3.9.0}/PKG-INFO +40 -6
  2. {trustmodel-3.7.0 → trustmodel-3.9.0}/README.md +39 -5
  3. {trustmodel-3.7.0 → trustmodel-3.9.0}/pyproject.toml +1 -1
  4. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/__init__.py +2 -0
  5. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/_runtime_transport.py +35 -0
  6. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/evaluations.py +91 -14
  7. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/guardrails.py +82 -15
  8. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/exceptions.py +37 -0
  9. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/evaluation.py +15 -1
  10. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/guardrails.py +12 -0
  11. {trustmodel-3.7.0 → trustmodel-3.9.0}/.gitignore +0 -0
  12. {trustmodel-3.7.0 → trustmodel-3.9.0}/LICENSE +0 -0
  13. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/cli.py +0 -0
  14. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/client.py +0 -0
  15. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/compat.py +0 -0
  16. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/__init__.py +0 -0
  17. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/agentcert.py +0 -0
  18. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/agentic.py +0 -0
  19. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/batch_jobs.py +0 -0
  20. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/config.py +0 -0
  21. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/credits.py +0 -0
  22. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/frameworks.py +0 -0
  23. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/galileo.py +0 -0
  24. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/mcp_scanner.py +0 -0
  25. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/endpoints/models.py +0 -0
  26. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/__init__.py +0 -0
  27. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/agentcert.py +0 -0
  28. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/agentic.py +0 -0
  29. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/batch_job.py +0 -0
  30. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/credits.py +0 -0
  31. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/frameworks.py +0 -0
  32. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/galileo.py +0 -0
  33. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/mcp_scanner.py +0 -0
  34. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/models.py +0 -0
  35. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/models/oauth.py +0 -0
  36. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/oauth/__init__.py +0 -0
  37. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/oauth/auth.py +0 -0
  38. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/oauth/scopes.py +0 -0
  39. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/telemetry/__init__.py +0 -0
  40. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/telemetry/_constants.py +0 -0
  41. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/telemetry/_instrumentors.py +0 -0
  42. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/telemetry/auto_init.py +0 -0
  43. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/utils/__init__.py +0 -0
  44. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/utils/validation.py +0 -0
  45. {trustmodel-3.7.0 → trustmodel-3.9.0}/src/trustmodel/utils/version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trustmodel
3
- Version: 3.7.0
3
+ Version: 3.9.0
4
4
  Summary: Official Python SDK for TrustModel AI evaluation platform
5
5
  Project-URL: Homepage, https://trustmodel.ai
6
6
  Author-email: TrustModel <info@predixtions.com>
@@ -428,7 +428,9 @@ evaluation = client.evaluations.create_custom_endpoint(
428
428
  api_endpoint="https://api.yourcompany.com/v1",
429
429
  api_key="your-api-key",
430
430
  model_identifier="your-model-id",
431
- vendor_identifier="openai", # Determines which validator to use
431
+ # vendor_identifier omitted on purpose: the gateway then routes on
432
+ # api_endpoint, which is unambiguous. Pass one only if you need a
433
+ # specific validator - see the table below.
432
434
  model_name="My Custom Model", # Optional display name
433
435
  categories=["safety", "bias"]
434
436
  )
@@ -438,18 +440,50 @@ evaluation = client.evaluations.create_custom_endpoint(
438
440
 
439
441
  Get the list programmatically with `client.config.get().vendors["custom"]`, or use one of these:
440
442
 
443
+ **Known good** - one catalog row each, so they resolve unambiguously:
444
+
441
445
  | Identifier | Use For |
442
446
  |------------|---------|
443
- | `openai` | OpenAI-compatible APIs (Ollama, vLLM, LiteLLM, etc.) - **default** |
447
+ | `ollama` | Ollama |
444
448
  | `huggingface` | Hugging Face Inference Endpoints |
445
449
  | `azure_ai` | Azure AI / Azure OpenAI Service |
446
- | `xai` | Google Vertex AI |
447
- | `bedrock` | AWS Bedrock |
450
+
451
+ **Do not pass these** - each shares its identifier with a public catalog vendor,
452
+ and one of them resolves to the wrong vendor entirely:
453
+
454
+ | Identifier | What actually happens |
455
+ |------------|-----------------------|
456
+ | `openai` | Shared with the public OpenAI catalog vendor. Which one you reach depends on the gateway version - see the note below. |
457
+ | `xai` | **Does not reach X.AI / Grok.** The catalog's custom row for Google Vertex AI carries `xai` as its identifier, so this routes a request to Vertex AI. |
458
+
459
+ > `openai` **is no longer the default.** Up to and including 3.7.0 the SDK sent it whenever you
460
+ > omitted `vendor_identifier`, which is what routed custom-endpoint evaluations to
461
+ > the public vendor of the same name. It now sends nothing unless you ask.
462
+ >
463
+ > **Why `openai` is version-dependent.** Before aurora-gateway#671 it resolved to
464
+ > the *public* OpenAI vendor, so your custom endpoint was quietly evaluated as a
465
+ > public catalog model. After #671 it resolves to the custom row. Either way you
466
+ > are relying on which row happens to sort first.
467
+ >
468
+ > **Why `xai` is simply wrong.** The gateway derives identifiers by substring
469
+ > match, and `xai` is a substring of `google_vertexai` - so the Vertex AI custom
470
+ > row had its own identifier overwritten. Passing `xai` reaches Vertex AI, not
471
+ > X.AI. Tracked separately; do not rely on either behaviour.
472
+ >
473
+ > **Omit `vendor_identifier` and none of this applies.** The gateway then routes
474
+ > on `api_endpoint`, which is unique to your request.
475
+
476
+ > `bedrock` is **not** a custom-endpoint identifier. It exists in the catalog as a
477
+ > public vendor only, so pairing it with `api_endpoint` returns
478
+ > `400 vendor_not_custom_endpoint_capable` (TRUS-1924). Earlier versions of this
479
+ > table listed it; that was never supported and now fails fast instead of
480
+ > silently evaluating a public catalog model. Prefer the programmatic list above
481
+ > — it is generated from the same predicate the server enforces.
448
482
 
449
483
  **Examples:**
450
484
 
451
485
  ```python
452
- # Ollama endpoint (uses default "openai" validator)
486
+ # Ollama endpoint — no vendor_identifier, so the gateway routes on api_endpoint
453
487
  evaluation = client.evaluations.create_custom_endpoint(
454
488
  api_endpoint="http://localhost:11434/v1",
455
489
  api_key="ollama", # Ollama doesn't require a real key
@@ -360,7 +360,9 @@ evaluation = client.evaluations.create_custom_endpoint(
360
360
  api_endpoint="https://api.yourcompany.com/v1",
361
361
  api_key="your-api-key",
362
362
  model_identifier="your-model-id",
363
- vendor_identifier="openai", # Determines which validator to use
363
+ # vendor_identifier omitted on purpose: the gateway then routes on
364
+ # api_endpoint, which is unambiguous. Pass one only if you need a
365
+ # specific validator - see the table below.
364
366
  model_name="My Custom Model", # Optional display name
365
367
  categories=["safety", "bias"]
366
368
  )
@@ -370,18 +372,50 @@ evaluation = client.evaluations.create_custom_endpoint(
370
372
 
371
373
  Get the list programmatically with `client.config.get().vendors["custom"]`, or use one of these:
372
374
 
375
+ **Known good** - one catalog row each, so they resolve unambiguously:
376
+
373
377
  | Identifier | Use For |
374
378
  |------------|---------|
375
- | `openai` | OpenAI-compatible APIs (Ollama, vLLM, LiteLLM, etc.) - **default** |
379
+ | `ollama` | Ollama |
376
380
  | `huggingface` | Hugging Face Inference Endpoints |
377
381
  | `azure_ai` | Azure AI / Azure OpenAI Service |
378
- | `xai` | Google Vertex AI |
379
- | `bedrock` | AWS Bedrock |
382
+
383
+ **Do not pass these** - each shares its identifier with a public catalog vendor,
384
+ and one of them resolves to the wrong vendor entirely:
385
+
386
+ | Identifier | What actually happens |
387
+ |------------|-----------------------|
388
+ | `openai` | Shared with the public OpenAI catalog vendor. Which one you reach depends on the gateway version - see the note below. |
389
+ | `xai` | **Does not reach X.AI / Grok.** The catalog's custom row for Google Vertex AI carries `xai` as its identifier, so this routes a request to Vertex AI. |
390
+
391
+ > `openai` **is no longer the default.** Up to and including 3.7.0 the SDK sent it whenever you
392
+ > omitted `vendor_identifier`, which is what routed custom-endpoint evaluations to
393
+ > the public vendor of the same name. It now sends nothing unless you ask.
394
+ >
395
+ > **Why `openai` is version-dependent.** Before aurora-gateway#671 it resolved to
396
+ > the *public* OpenAI vendor, so your custom endpoint was quietly evaluated as a
397
+ > public catalog model. After #671 it resolves to the custom row. Either way you
398
+ > are relying on which row happens to sort first.
399
+ >
400
+ > **Why `xai` is simply wrong.** The gateway derives identifiers by substring
401
+ > match, and `xai` is a substring of `google_vertexai` - so the Vertex AI custom
402
+ > row had its own identifier overwritten. Passing `xai` reaches Vertex AI, not
403
+ > X.AI. Tracked separately; do not rely on either behaviour.
404
+ >
405
+ > **Omit `vendor_identifier` and none of this applies.** The gateway then routes
406
+ > on `api_endpoint`, which is unique to your request.
407
+
408
+ > `bedrock` is **not** a custom-endpoint identifier. It exists in the catalog as a
409
+ > public vendor only, so pairing it with `api_endpoint` returns
410
+ > `400 vendor_not_custom_endpoint_capable` (TRUS-1924). Earlier versions of this
411
+ > table listed it; that was never supported and now fails fast instead of
412
+ > silently evaluating a public catalog model. Prefer the programmatic list above
413
+ > — it is generated from the same predicate the server enforces.
380
414
 
381
415
  **Examples:**
382
416
 
383
417
  ```python
384
- # Ollama endpoint (uses default "openai" validator)
418
+ # Ollama endpoint — no vendor_identifier, so the gateway routes on api_endpoint
385
419
  evaluation = client.evaluations.create_custom_endpoint(
386
420
  api_endpoint="http://localhost:11434/v1",
387
421
  api_key="ollama", # Ollama doesn't require a real key
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "trustmodel"
7
- version = "3.7.0"
7
+ version = "3.9.0"
8
8
  authors = [
9
9
  {name = "TrustModel", email = "info@predixtions.com"},
10
10
  ]
@@ -25,6 +25,7 @@ from .exceptions import (
25
25
  EvaluationNotFoundError,
26
26
  InsufficientCreditsError,
27
27
  RateLimitError,
28
+ ResponseParsingError,
28
29
  TrustModelError,
29
30
  ValidationError,
30
31
  )
@@ -64,6 +65,7 @@ __all__ = [
64
65
  "ConnectionValidationError",
65
66
  "EdgeUnreachableError",
66
67
  "EvaluationNotFoundError",
68
+ "ResponseParsingError",
67
69
  "AgentCertInvalidRunTypeError",
68
70
  "AgentCertRunNotCompletedError",
69
71
  "Decision",
@@ -45,6 +45,41 @@ class TransportError(Exception):
45
45
  self.cause = cause
46
46
  super().__init__(message)
47
47
 
48
+ @property
49
+ def is_availability_failure(self) -> bool:
50
+ """True when this failure means "the service could not answer".
51
+
52
+ TRUS-2159. ``fail_mode`` is an availability trade-off: a caller who
53
+ sets ``fail_open`` is saying "keep my agent running if TrustModel is
54
+ unreachable". It is NOT a blanket "turn every error into an allow" —
55
+ so only failures that genuinely mean *we could not get a decision*
56
+ may be absorbed by it.
57
+
58
+ Availability (fail_mode may apply):
59
+ * no ``status_code`` at all — connect error, timeout, or a 2xx
60
+ whose body would not parse. Nothing was decided.
61
+ * 5xx — the service accepted the request and broke.
62
+
63
+ Everything else propagates, deliberately:
64
+ * 400 / 404 / 422 — the request itself is wrong. Allowing it would
65
+ convert a caller's bug into a permit.
66
+ * 401 / 403 — bad or expired credentials. A misconfigured key must
67
+ never silently become "allow everything"; that is the one failure
68
+ mode where failing open is most dangerous and least expected.
69
+ * 429 — rate limited. Treating this as availability would let a
70
+ caller exceed their limit *by* exceeding it.
71
+ * 3xx — unexpected here (redirects are followed by default), so it
72
+ is not evidence the service was unavailable.
73
+
74
+ Consulted only on the Aurora path. Edge deliberately falls back on
75
+ *any* transport error, including 4xx — see
76
+ ``test_edge_400_falls_back_to_aurora``; the SDK does not interpret
77
+ Edge's 4xx semantics, and TRUS-2159 did not change that.
78
+ """
79
+ if self.status_code is None:
80
+ return True
81
+ return 500 <= self.status_code <= 599
82
+
48
83
 
49
84
  class RuntimeTransport(ABC):
50
85
  """Abstract HTTP transport for runtime decide() calls."""
@@ -4,8 +4,9 @@ Evaluations endpoint wrapper for the TrustModel SDK.
4
4
 
5
5
  from __future__ import annotations
6
6
 
7
- from typing import TYPE_CHECKING, Any, Dict, List, Optional
7
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, TypeVar
8
8
 
9
+ from ..exceptions import ResponseParsingError
9
10
  from ..models.evaluation import Evaluation, EvaluationResult
10
11
  from ..utils.validation import validate_categories
11
12
 
@@ -13,6 +14,68 @@ if TYPE_CHECKING:
13
14
  from ..client import TrustModelClient
14
15
 
15
16
 
17
+ # `_parse` is generic so a call site returning it keeps the model type it
18
+ # asked for. Typed as `Any` it satisfied mypy at the definition and then
19
+ # failed at every caller with `no-any-return`.
20
+ T = TypeVar("T")
21
+
22
+
23
+ def _describe_parse_error(error: Exception) -> str:
24
+ """Summarize a parse failure by field and error type, never by value.
25
+
26
+ pydantic's own string form embeds the offending input, which would put
27
+ response content into any log line or traceback that renders the exception.
28
+ The field location and the kind of mismatch are what actually diagnose a
29
+ shape drift.
30
+ """
31
+ errors = getattr(error, "errors", None)
32
+ if not callable(errors):
33
+ return type(error).__name__
34
+ try:
35
+ details = errors()
36
+ except Exception:
37
+ return type(error).__name__
38
+ described = []
39
+ for detail in details:
40
+ location = ".".join(str(part) for part in detail.get("loc", ())) or "<root>"
41
+ described.append(f"{location} ({detail.get('type', 'unknown')})")
42
+ return ", ".join(described) or type(error).__name__
43
+
44
+
45
+ def _parse(model_cls: Type[T], payload: Dict[str, Any]) -> T:
46
+ """Build a response model, converting a parse failure into a TrustModelError.
47
+
48
+ pydantic raises ``ValidationError``, which is not a ``TrustModelError``, so
49
+ it escapes every consumer's ``except TrustModelError`` and lands as a raw
50
+ traceback. That has already cost us once: the server grew four run statuses
51
+ ``EvaluationStatus`` did not carry, and ``get_result()`` died on them
52
+ mid-poll. Converting here closes the hole for any future response-shape
53
+ drift rather than just that one enum gap.
54
+
55
+ ``from None``, not ``from error``: ``__cause__`` puts the pydantic message —
56
+ which embeds the offending response values — into every traceback, so
57
+ ``logger.exception()`` would print exactly what ``_describe_parse_error``
58
+ strips out. The full detail stays reachable on ``.original_error`` for a
59
+ caller who asks for it.
60
+
61
+ ``(TypeError, ValueError)`` rather than bare ``Exception``: pydantic's
62
+ ``ValidationError`` subclasses ``ValueError``, so response-shape drift is
63
+ still caught, while a genuine SDK-side bug is not answered with "this SDK
64
+ may be out of date - try pip install -U", which sends the user after an
65
+ upgrade that cannot help.
66
+ """
67
+ try:
68
+ return model_cls(**payload)
69
+ except (TypeError, ValueError) as error:
70
+ raise ResponseParsingError(
71
+ f"Could not parse the API response into {model_cls.__name__}: "
72
+ f"{_describe_parse_error(error)}. This SDK may be out of date - "
73
+ "try 'pip install -U trustmodel'.",
74
+ model_name=model_cls.__name__,
75
+ original_error=error,
76
+ ) from None
77
+
78
+
16
79
  class EvaluationsEndpoint:
17
80
  """
18
81
  Interface for evaluation-related API endpoints.
@@ -117,7 +180,7 @@ class EvaluationsEndpoint:
117
180
  request_data[key] = value
118
181
 
119
182
  response = self._client.post("/sdk/v1/evaluate/", data=request_data)
120
- return Evaluation(**response)
183
+ return _parse(Evaluation, response)
121
184
 
122
185
  def create_from_template(
123
186
  self,
@@ -176,14 +239,14 @@ class EvaluationsEndpoint:
176
239
  request_data[key] = value
177
240
 
178
241
  response = self._client.post("/sdk/v1/evaluate/", data=request_data)
179
- return Evaluation(**response)
242
+ return _parse(Evaluation, response)
180
243
 
181
244
  def create_custom_endpoint(
182
245
  self,
183
246
  api_endpoint: str,
184
247
  api_key: str,
185
248
  model_identifier: str,
186
- vendor_identifier: str = "openai",
249
+ vendor_identifier: Optional[str] = None,
187
250
  model_name: Optional[str] = None,
188
251
  model_config_name: Optional[str] = None,
189
252
  system_prompt: Optional[str] = None,
@@ -202,14 +265,21 @@ class EvaluationsEndpoint:
202
265
  api_endpoint: Your OpenAI-compatible API endpoint URL
203
266
  api_key: API key for your endpoint
204
267
  model_identifier: Model identifier to use in API calls
205
- vendor_identifier: Vendor identifier for the custom endpoint. Determines
206
- which validator is used. Defaults to "openai".
207
- Available options:
208
- - "openai": Others/OpenAI-compatible (default, works for Ollama, vLLM, etc.)
268
+ vendor_identifier: Optional vendor identifier, selecting which
269
+ connection validator the API runs against your endpoint. Omit it
270
+ (the default) unless you need a specific validator: the value is
271
+ what the gateway dispatches on, and several identifiers are
272
+ shared with public catalog vendors, which sends the request down
273
+ the public-model path and drops your api_endpoint. Omitting it
274
+ routes on api_endpoint instead, which is unambiguous.
275
+ Known-good options:
209
276
  - "huggingface": Hugging Face endpoints
210
277
  - "azure_ai": Azure AI endpoints
278
+ - "ollama": Ollama endpoints
279
+ Ambiguous, pending a gateway fix - passing either currently
280
+ resolves to the public vendor of the same name:
281
+ - "openai": OpenAI-compatible (the default up to and including 3.7.0)
211
282
  - "xai": Google Vertex AI endpoints
212
- - "bedrock": AWS Bedrock endpoints
213
283
  model_name: Human-readable model name (optional)
214
284
  model_config_name: Custom name for this evaluation (optional)
215
285
  system_prompt: The agent's system prompt text (optional). When provided,
@@ -249,11 +319,18 @@ class EvaluationsEndpoint:
249
319
  "api_endpoint": api_endpoint,
250
320
  "api_key": api_key,
251
321
  "model_identifier": model_identifier,
252
- "vendor_identifier": vendor_identifier,
253
322
  "evaluation_type": "custom",
254
323
  "trigger_source": trigger_source,
255
324
  }
256
325
 
326
+ # Sent only when asked for. An unconditional default made the gateway
327
+ # dispatch on the vendor identifier rather than on api_endpoint, and
328
+ # vendor identifiers are not unique - "openai", "xai" and "bedrock" each
329
+ # resolve to a public catalog vendor first, so a custom-endpoint request
330
+ # was served as a public-model evaluation with api_endpoint dropped.
331
+ if vendor_identifier:
332
+ request_data["vendor_identifier"] = vendor_identifier
333
+
257
334
  if model_name:
258
335
  request_data["model_name"] = model_name
259
336
 
@@ -269,7 +346,7 @@ class EvaluationsEndpoint:
269
346
  request_data[key] = value
270
347
 
271
348
  response = self._client.post("/sdk/v1/evaluate/", data=request_data)
272
- return Evaluation(**response)
349
+ return _parse(Evaluation, response)
273
350
 
274
351
  def list(self, status: Optional[str] = None) -> List[Evaluation]:
275
352
  """
@@ -302,7 +379,7 @@ class EvaluationsEndpoint:
302
379
  # Development format or fallback: try "evaluations" key, then empty list
303
380
  eval_data = response.get("evaluations", [])
304
381
 
305
- return [Evaluation(**eval) for eval in eval_data]
382
+ return [_parse(Evaluation, eval) for eval in eval_data]
306
383
 
307
384
  def get(self, evaluation_id: int) -> Evaluation:
308
385
  """
@@ -322,7 +399,7 @@ class EvaluationsEndpoint:
322
399
  ... print(f"{score.category}: {score.score}")
323
400
  """
324
401
  response = self._client.get(f"/sdk/v1/evaluations/{evaluation_id}/")
325
- return Evaluation(**response)
402
+ return _parse(Evaluation, response)
326
403
 
327
404
  def get_result(self, evaluation_id: int) -> EvaluationResult:
328
405
  """
@@ -342,7 +419,7 @@ class EvaluationsEndpoint:
342
419
  ... print(f"{cs['category']}: {cs['score']}")
343
420
  """
344
421
  response = self._client.get(f"/sdk/v1/evaluations/{evaluation_id}/result/")
345
- return EvaluationResult(**response)
422
+ return _parse(EvaluationResult, response)
346
423
 
347
424
  def get_status(self, evaluation_id: int) -> Dict:
348
425
  """
@@ -209,8 +209,21 @@ class GuardrailsEndpoint:
209
209
  Raises:
210
210
  ValidationError: tool is empty / agent_id missing when
211
211
  Aurora is the only path.
212
- EdgeUnreachableError: Edge failed AND no Aurora fallback
213
- available AND ``fail_mode == "closed"``.
212
+ EdgeUnreachableError: no transport could produce a decision
213
+ AND ``fail_mode == "closed"``. Since TRUS-2159 this covers
214
+ an Aurora *availability* failure (connect, timeout, 5xx,
215
+ unparseable body) as well as an Edge one — previously an
216
+ Aurora failure escaped as an internal transport error and
217
+ ``fail_mode`` never applied to it.
218
+
219
+ Note:
220
+ ``fail_mode`` governs availability only. A 4xx from Aurora —
221
+ 400/404/422 (bad request), 401/403 (bad credentials) or 429
222
+ (rate limited) — always propagates, even under
223
+ ``fail_mode="open"``. Absorbing those would turn a caller's
224
+ bug or a misconfigured key into a silent allow. They surface
225
+ as an internal transport error, which is not currently part
226
+ of the public exception surface.
214
227
  """
215
228
  if not tool:
216
229
  raise ValidationError("guardrails.decide(): `tool` is required")
@@ -251,6 +264,7 @@ class GuardrailsEndpoint:
251
264
 
252
265
  # ── Edge primary ────────────────────────────────────────────
253
266
  last_edge_error: Optional[BaseException] = None
267
+ last_aurora_error: Optional[TransportError] = None
254
268
  if edge is not None:
255
269
  try:
256
270
  body = _build_edge_body(
@@ -293,31 +307,65 @@ class GuardrailsEndpoint:
293
307
  agent_id=agent_id,
294
308
  policy_name=resolved_policy_name,
295
309
  )
296
- raw = aurora.post("/api/v1/guardrails/check", body, timeout=self._client._timeout)
297
- return _decision_from_aurora(raw)
310
+ try:
311
+ raw = aurora.post("/api/v1/guardrails/check", body, timeout=self._client._timeout)
312
+ except TransportError as exc:
313
+ # TRUS-2159: before this, the Aurora call was unguarded, so a
314
+ # TransportError propagated and the fail_mode block below was
315
+ # unreachable whenever Aurora was configured — which is always,
316
+ # for a Direct HTTP agent with no edge_url. A caller who asked
317
+ # for fail_open got an exception instead of the documented allow.
318
+ #
319
+ # Only availability failures are absorbed. A 4xx/401/403/429 is
320
+ # re-raised: turning a malformed request or a bad credential into
321
+ # an allow would be a far worse bug than the one being fixed.
322
+ if not exc.is_availability_failure:
323
+ raise
324
+ logger.info(
325
+ "trustmodel.guardrails.aurora_failed",
326
+ extra={"reason": str(exc), "status_code": exc.status_code},
327
+ )
328
+ last_aurora_error = exc
329
+ else:
330
+ return _decision_from_aurora(raw)
298
331
 
299
332
  # ── Neither succeeded: fail_mode decides ────────────────────
333
+ # TRUS-2159: reachable now for an Aurora availability failure too, not
334
+ # only when Aurora was never configured.
335
+ last_error = last_aurora_error or last_edge_error
336
+ # Which transport we got furthest with — the fail-open Decision reports
337
+ # it so a ``stale=True`` allow stays diagnosable.
338
+ attempted = "aurora" if last_aurora_error is not None else "edge"
339
+ if last_edge_error is not None and last_aurora_error is not None:
340
+ unreachable = "Edge and Aurora unreachable"
341
+ elif last_aurora_error is not None:
342
+ unreachable = "Aurora unreachable"
343
+ elif aurora is None:
344
+ # Preserved wording: pinned by test_fail_closed_edge_down_no_aurora_raises.
345
+ unreachable = "Edge unreachable and no Aurora fallback configured"
346
+ else:
347
+ unreachable = "Edge unreachable"
348
+
300
349
  if self._client.fail_mode == "open":
301
350
  logger.warning(
302
351
  "trustmodel.guardrails.fail_open",
303
- extra={"last_error": str(last_edge_error) if last_edge_error else None},
352
+ extra={
353
+ "last_error": str(last_error) if last_error else None,
354
+ "transport": attempted,
355
+ },
304
356
  )
305
357
  return Decision(
306
358
  verdict="allow",
307
359
  rule_id="fail_open",
308
360
  reason=(
309
- "Edge unreachable and fail_mode=open"
310
- + (f": {last_edge_error}" if last_edge_error else "")
361
+ f"{unreachable} and fail_mode=open" + (f": {last_error}" if last_error else "")
311
362
  ),
312
- source="edge",
363
+ source=attempted,
313
364
  stale=True,
314
365
  )
315
366
  raise EdgeUnreachableError(
316
- (
317
- "Edge unreachable and no Aurora fallback configured "
318
- "(fail_mode=closed)" + (f": {last_edge_error}" if last_edge_error else "")
319
- ),
320
- last_error=last_edge_error if isinstance(last_edge_error, Exception) else None,
367
+ (f"{unreachable} (fail_mode=closed)" + (f": {last_error}" if last_error else "")),
368
+ last_error=last_error if isinstance(last_error, Exception) else None,
321
369
  )
322
370
 
323
371
 
@@ -371,6 +419,14 @@ def _build_aurora_body(
371
419
  # ── response normalizers ──────────────────────────────────────────────
372
420
 
373
421
 
422
+ # TRUS-2158: an ``audit`` rule permits the call and records it. Edge sends it
423
+ # as ``verdict: "audit"``; Aurora sends ``decision: "allow"`` plus
424
+ # ``policy_action: "audit"`` (older Aurora: only ``evidence.rails_action``).
425
+ # Both normalize to ``verdict="allow", policy_action="audit"`` so ``verdict``
426
+ # stays in its documented allow/deny/redact vocabulary.
427
+ _AUDIT = "audit"
428
+
429
+
374
430
  def _decision_from_edge(raw: Dict[str, Any]) -> Decision:
375
431
  redactions = raw.get("redactions") or []
376
432
  if not isinstance(redactions, list):
@@ -378,8 +434,13 @@ def _decision_from_edge(raw: Dict[str, Any]) -> Decision:
378
434
  framework_tags = raw.get("matched_framework_tags") or []
379
435
  if not isinstance(framework_tags, list):
380
436
  framework_tags = []
437
+ verdict = str(raw.get("verdict", ""))
438
+ policy_action = verdict
439
+ if verdict == _AUDIT:
440
+ verdict = "allow"
381
441
  return Decision(
382
- verdict=str(raw.get("verdict", "")),
442
+ verdict=verdict,
443
+ policy_action=policy_action,
383
444
  rule_id=str(raw.get("rule_id", "") or ""),
384
445
  reason=str(raw.get("reason", "") or ""),
385
446
  redactions=[str(p) for p in redactions],
@@ -406,8 +467,14 @@ def _decision_from_aurora(raw: Dict[str, Any]) -> Decision:
406
467
  policy_id = None
407
468
  trust_score = raw.get("trust_score")
408
469
  trust_score_int = int(trust_score) if isinstance(trust_score, (int, float)) else None
470
+ verdict = str(raw.get("decision", ""))
471
+ policy_action = str(raw.get("policy_action", "") or "")
472
+ if not policy_action:
473
+ audited = verdict == "allow" and evidence.get("rails_action") == _AUDIT
474
+ policy_action = _AUDIT if audited else verdict
409
475
  return Decision(
410
- verdict=str(raw.get("decision", "")),
476
+ verdict=verdict,
477
+ policy_action=policy_action,
411
478
  rule_id=str(evidence.get("rule_id", "") or ""),
412
479
  reason=str(raw.get("reason", "") or ""),
413
480
  redactions=redactions,
@@ -160,3 +160,40 @@ class EdgeUnreachableError(TrustModelError):
160
160
  def __init__(self, message: str, last_error: Optional[Exception] = None) -> None:
161
161
  self.last_error = last_error
162
162
  super().__init__(message)
163
+
164
+
165
+ class ResponseParsingError(APIError):
166
+ """Raised when a successful response cannot be parsed into its model.
167
+
168
+ The HTTP call succeeded; the body did not match the model - most often a
169
+ run status this SDK's ``EvaluationStatus`` enum predates, or a field the
170
+ server reshaped. pydantic signals that with a ``ValidationError``, which is
171
+ not a ``TrustModelError``, so it escapes every consumer's existing
172
+ ``except TrustModelError`` and surfaces as a raw traceback. Raising this
173
+ instead means a shape drift is handled by the error path callers already
174
+ have.
175
+
176
+ Attributes:
177
+ model_name: Name of the model class that could not be built.
178
+ original_error: The underlying parse error, kept for callers that want
179
+ the full pydantic detail. Note that its string form embeds the
180
+ offending response values, so ``str(self)`` deliberately reports
181
+ only the field locations and error types - log this exception, not
182
+ ``original_error``.
183
+ """
184
+
185
+ def __init__(
186
+ self,
187
+ message: str,
188
+ model_name: str,
189
+ original_error: Optional[Exception] = None,
190
+ status_code: int = 200,
191
+ ) -> None:
192
+ self.model_name = model_name
193
+ self.original_error = original_error
194
+ # `200` is a placeholder meaning "some 2xx we did not record", not a
195
+ # measurement — `create` returns 201. Reporting the real status needs the
196
+ # client to thread it through to `_parse`, which returns parsed JSON and
197
+ # not the response object, so it is a wider change than this one. Prefer
198
+ # `error_code` over `status_code` when branching on this exception.
199
+ super().__init__(message, status_code, None, "response_parsing_failed")
@@ -12,13 +12,27 @@ from trustmodel.compat import BaseModel, ConfigDict, Field
12
12
 
13
13
 
14
14
  class EvaluationStatus(str, Enum):
15
- """Status of an evaluation run."""
15
+ """Status of an evaluation run.
16
+
17
+ Mirrors ``ReportEvaluationRunStatusChoices`` in aurora-gateway
18
+ (``report/choices.py``). Keep the two in step: this enum is a strict
19
+ pydantic field on ``EvaluationResult``, so a status the server emits and
20
+ this enum lacks makes ``get_result()`` raise on a perfectly valid run.
21
+ ``COMPLETED``, ``FAILED`` and ``CANCELLED`` are the terminal states
22
+ (``TERMINAL_RUN_STATUSES`` server-side); the rest may still move.
23
+ """
16
24
 
17
25
  PROCESSING = "processing"
18
26
  RUNNING = "running"
19
27
  COMPLETED = "completed"
20
28
  FAILED = "failed"
21
29
  PAYMENT_PENDING = "payment_pending"
30
+ # The server has emitted all four since well before they were added here;
31
+ # the enum simply did not carry them.
32
+ PAYMENT_FAILED = "payment_failed"
33
+ DATA_PULL_PENDING = "data_pull_pending"
34
+ CANCELLED = "cancelled"
35
+ RETRYABLE_FAILURE = "retryable_failure"
22
36
 
23
37
 
24
38
  class ApplicationType(str, Enum):
@@ -43,6 +43,13 @@ class Decision:
43
43
  stale: ``True`` only when Edge returned a stale-policy fallback
44
44
  verdict (Aurora is always ``False``).
45
45
  source: ``"edge"`` or ``"aurora"`` — which transport answered.
46
+ policy_action: The governance action the matched rule asked for:
47
+ ``"allow"``, ``"deny"``, ``"redact"``, or ``"audit"``. Equal to
48
+ ``verdict`` except for an ``audit`` rule, where ``verdict`` is
49
+ ``"allow"`` (the call is permitted) and ``policy_action`` is
50
+ ``"audit"`` (it was recorded as a governance event). Enforce on
51
+ ``verdict``; read this to know the call was audited. Defaults
52
+ to ``verdict`` when not supplied.
46
53
  """
47
54
 
48
55
  verdict: str
@@ -56,6 +63,11 @@ class Decision:
56
63
  trust_score: int | None = None
57
64
  stale: bool = False
58
65
  source: str = "edge"
66
+ policy_action: str = ""
67
+
68
+ def __post_init__(self) -> None:
69
+ if not self.policy_action:
70
+ object.__setattr__(self, "policy_action", self.verdict)
59
71
 
60
72
  def applied_args(self, args: Mapping[str, Any]) -> dict[str, Any]:
61
73
  """Return a deep copy of ``args`` with redacted JSON paths nulled.
File without changes
File without changes