liyaengine 0.22.0__tar.gz → 0.23.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 (44) hide show
  1. {liyaengine-0.22.0 → liyaengine-0.23.0}/PKG-INFO +25 -1
  2. {liyaengine-0.22.0 → liyaengine-0.23.0}/README.md +24 -0
  3. {liyaengine-0.22.0 → liyaengine-0.23.0}/pyproject.toml +1 -1
  4. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/__init__.py +4 -1
  5. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/client.py +2 -0
  6. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/agents.py +15 -4
  7. liyaengine-0.23.0/src/liyaengine/resources/guardrail_templates.py +77 -0
  8. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_agents.py +30 -0
  9. liyaengine-0.23.0/tests/test_guardrail_templates.py +70 -0
  10. {liyaengine-0.22.0 → liyaengine-0.23.0}/.github/workflows/ci.yml +0 -0
  11. {liyaengine-0.22.0 → liyaengine-0.23.0}/.gitignore +0 -0
  12. {liyaengine-0.22.0 → liyaengine-0.23.0}/LICENSE +0 -0
  13. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/_http.py +0 -0
  14. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/errors.py +0 -0
  15. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/py.typed +0 -0
  16. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/__init__.py +0 -0
  17. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/collections.py +0 -0
  18. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/corrections.py +0 -0
  19. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/documents.py +0 -0
  20. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/domain_tools.py +0 -0
  21. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/domains.py +0 -0
  22. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/evaluations.py +0 -0
  23. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/files.py +0 -0
  24. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/gaps.py +0 -0
  25. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/guardrail_policies.py +0 -0
  26. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/healing.py +0 -0
  27. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/memory.py +0 -0
  28. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/prompts.py +0 -0
  29. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/run.py +0 -0
  30. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/traces.py +0 -0
  31. {liyaengine-0.22.0 → liyaengine-0.23.0}/src/liyaengine/resources/workflows.py +0 -0
  32. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_access.py +0 -0
  33. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_collections.py +0 -0
  34. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_corrections.py +0 -0
  35. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_documents.py +0 -0
  36. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_domains.py +0 -0
  37. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_evaluations.py +0 -0
  38. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_files.py +0 -0
  39. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_gaps.py +0 -0
  40. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_guardrail_policies.py +0 -0
  41. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_healing.py +0 -0
  42. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_prompts.py +0 -0
  43. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_traces.py +0 -0
  44. {liyaengine-0.22.0 → liyaengine-0.23.0}/tests/test_workflows.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: liyaengine
3
- Version: 0.22.0
3
+ Version: 0.23.0
4
4
  Summary: Official Python client for the Liya Engine public API
5
5
  Project-URL: Homepage, https://liyaengine.ai
6
6
  Project-URL: Documentation, https://liyaengine.ai/docs/sdks/python
@@ -288,6 +288,12 @@ result = client.agents.run(agent.agent_key, input={"message": "My order hasn't a
288
288
 
289
289
  history = client.agents.list_runs(agent.agent_key)
290
290
 
291
+ # Name your own conversations: no need to store our session_id. The first call
292
+ # with a key starts the conversation, later calls continue it. Needs
293
+ # input["user_id"]; a key belongs to one user.
294
+ client.agents.run(agent.agent_key, session_key="conv_55", input={"user_id": "cust_812", "message": "I can't pay this month."})
295
+ thread = client.agents.list_runs(agent.agent_key, session_key="conv_55", user_id="cust_812")
296
+
291
297
  # run_stream() — real-time step progress instead of one awaited result.
292
298
  # Step-level, not token-level: the agent orchestration loop has no
293
299
  # streaming synthesis call, so there's no token delta to yield. What
@@ -389,6 +395,8 @@ waiting = client.workflows.approvals.list(status="pending")
389
395
 
390
396
  ## Evaluations
391
397
 
398
+ > **New in 0.23.0:** `guardrail_templates`, and `session_key` on `agents.run()`, `agents.run_stream()` and `agents.list_runs()`. Nothing is removed or renamed.
399
+
392
400
  A Suite binds a Dataset to one intent, agent or workflow; `suites.run()` runs it for real and scores what it produces. `runs.submit()`/`evaluations.score()` score a response you already generated yourself — no intent execution involved.
393
401
 
394
402
  > **Upgrading to 0.22.0:** suites can now target an agent or workflow, so `EvalSuite.intent_key` and `domain_key` are `Optional[str]`. Code that reads `suite.intent_key` as a `str` needs a `None` check (use `suite.target_type` to tell the target kinds apart).
@@ -514,6 +522,22 @@ stats = client.guardrail_policies.analytics(strict.id, days=30)
514
522
  versions = client.guardrail_policies.versions.list(strict.id)
515
523
  ```
516
524
 
525
+ ### Templates
526
+
527
+ A template is a starting point for one industry (general, financial services, healthcare) and one audience (customer or staff). Previewing saves nothing: it returns the settings and what they would change. Create a policy from `preview.config` to apply it.
528
+
529
+ ```python
530
+ templates = client.guardrail_templates.list() # ids like "financial-staff", "healthcare-member"
531
+
532
+ preview = client.guardrail_templates.preview("healthcare-member")
533
+ print([f'{c["label"]}: {c["from"]} -> {c["to"]}' for c in preview.changes])
534
+
535
+ policy = client.guardrail_policies.create(name="Member help", config=preview.config)
536
+ client.guardrail_policies.attach(policy.id, "agent", agent.id)
537
+ ```
538
+
539
+ Pass a policy's `config` as `config=` to preview a template against it instead of the defaults.
540
+
517
541
  > The platform's ML classifier (for injection detection and grounding/hallucination checks) isn't a field on `config` — it's an infrastructure capability that activates automatically whenever it's configured tenant-wide, layered on top of `content_policy.injection_detection` and `post_llm.hallucination_check`. There's nothing to toggle for it specifically.
518
542
 
519
543
  ## Prompt Studio
@@ -259,6 +259,12 @@ result = client.agents.run(agent.agent_key, input={"message": "My order hasn't a
259
259
 
260
260
  history = client.agents.list_runs(agent.agent_key)
261
261
 
262
+ # Name your own conversations: no need to store our session_id. The first call
263
+ # with a key starts the conversation, later calls continue it. Needs
264
+ # input["user_id"]; a key belongs to one user.
265
+ client.agents.run(agent.agent_key, session_key="conv_55", input={"user_id": "cust_812", "message": "I can't pay this month."})
266
+ thread = client.agents.list_runs(agent.agent_key, session_key="conv_55", user_id="cust_812")
267
+
262
268
  # run_stream() — real-time step progress instead of one awaited result.
263
269
  # Step-level, not token-level: the agent orchestration loop has no
264
270
  # streaming synthesis call, so there's no token delta to yield. What
@@ -360,6 +366,8 @@ waiting = client.workflows.approvals.list(status="pending")
360
366
 
361
367
  ## Evaluations
362
368
 
369
+ > **New in 0.23.0:** `guardrail_templates`, and `session_key` on `agents.run()`, `agents.run_stream()` and `agents.list_runs()`. Nothing is removed or renamed.
370
+
363
371
  A Suite binds a Dataset to one intent, agent or workflow; `suites.run()` runs it for real and scores what it produces. `runs.submit()`/`evaluations.score()` score a response you already generated yourself — no intent execution involved.
364
372
 
365
373
  > **Upgrading to 0.22.0:** suites can now target an agent or workflow, so `EvalSuite.intent_key` and `domain_key` are `Optional[str]`. Code that reads `suite.intent_key` as a `str` needs a `None` check (use `suite.target_type` to tell the target kinds apart).
@@ -485,6 +493,22 @@ stats = client.guardrail_policies.analytics(strict.id, days=30)
485
493
  versions = client.guardrail_policies.versions.list(strict.id)
486
494
  ```
487
495
 
496
+ ### Templates
497
+
498
+ A template is a starting point for one industry (general, financial services, healthcare) and one audience (customer or staff). Previewing saves nothing: it returns the settings and what they would change. Create a policy from `preview.config` to apply it.
499
+
500
+ ```python
501
+ templates = client.guardrail_templates.list() # ids like "financial-staff", "healthcare-member"
502
+
503
+ preview = client.guardrail_templates.preview("healthcare-member")
504
+ print([f'{c["label"]}: {c["from"]} -> {c["to"]}' for c in preview.changes])
505
+
506
+ policy = client.guardrail_policies.create(name="Member help", config=preview.config)
507
+ client.guardrail_policies.attach(policy.id, "agent", agent.id)
508
+ ```
509
+
510
+ Pass a policy's `config` as `config=` to preview a template against it instead of the defaults.
511
+
488
512
  > The platform's ML classifier (for injection detection and grounding/hallucination checks) isn't a field on `config` — it's an infrastructure capability that activates automatically whenever it's configured tenant-wide, layered on top of `content_policy.injection_detection` and `post_llm.hallucination_check`. There's nothing to toggle for it specifically.
489
513
 
490
514
  ## Prompt Studio
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "liyaengine"
7
- version = "0.22.0"
7
+ version = "0.23.0"
8
8
  description = "Official Python client for the Liya Engine public API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -16,6 +16,7 @@ from .resources.guardrail_policies import (
16
16
  GuardrailPolicy, GuardrailPolicyConnections, GuardrailIssue, TestGuardrailPolicyResult,
17
17
  GuardrailPolicyVersionSummary, GuardrailPolicyAnalytics, ConsumerType as GuardrailConsumerType,
18
18
  )
19
+ from .resources.guardrail_templates import GuardrailTemplate, GuardrailTemplatePreview
19
20
  from .resources.prompts import Prompt, PromptVersion, PromptDeployment, PublishPromptResult
20
21
  from .resources.traces import Trace, TraceCaseDraft, TraceSummary, TracesPage, TraceStats
21
22
  from .resources.gaps import GapArticleDraft, GapCoverage, GapCoverageResult
@@ -85,10 +86,12 @@ __all__ = [
85
86
  "TraceStats",
86
87
  "TraceCaseDraft",
87
88
  "CorrectionResult",
89
+ "GuardrailTemplate",
90
+ "GuardrailTemplatePreview",
88
91
  "ReportedPassage",
89
92
  "GapArticleDraft",
90
93
  "GapCoverage",
91
94
  "GapCoverageResult",
92
95
  ]
93
96
 
94
- __version__ = "0.22.0"
97
+ __version__ = "0.23.0"
@@ -13,6 +13,7 @@ from .resources.domains import DomainsResource, IntentsResource
13
13
  from .resources.documents import DocumentsResource
14
14
  from .resources.files import FilesResource
15
15
  from .resources.guardrail_policies import GuardrailPoliciesResource
16
+ from .resources.guardrail_templates import GuardrailTemplatesResource
16
17
  from .resources.prompts import PromptsResource
17
18
  from .resources.traces import TracesResource
18
19
  from .resources.gaps import GapsResource
@@ -60,6 +61,7 @@ class LiyaEngine:
60
61
  self.documents = DocumentsResource(self._http)
61
62
  self.files = FilesResource(self._http)
62
63
  self.guardrail_policies = GuardrailPoliciesResource(self._http)
64
+ self.guardrail_templates = GuardrailTemplatesResource(self._http)
63
65
  self.prompts = PromptsResource(self._http)
64
66
  self.traces = TracesResource(self._http)
65
67
  self.gaps = GapsResource(self._http)
@@ -282,19 +282,26 @@ class AgentsResource:
282
282
 
283
283
  def run(
284
284
  self, agent_key: str, *, input: Dict[str, Any], session_id: Optional[str] = None,
285
- access: Optional[Dict[str, Any]] = None,
285
+ session_key: Optional[str] = None, access: Optional[Dict[str, Any]] = None,
286
286
  ) -> Dict[str, Any]:
287
- """`access={"groups": [...]}` is the end user's retrieval access context (see intents.run)."""
287
+ """`access={"groups": [...]}` is the end user's retrieval access context (see intents.run).
288
+
289
+ `session_key` is your own conversation id, instead of ours: the first call with a key starts the
290
+ conversation and later calls continue it, so you need not store `session_id`. It needs
291
+ `input["user_id"]`, a key belongs to one user, and it cannot be sent with `session_id`.
292
+ """
288
293
  body: Dict[str, Any] = {"input": input}
289
294
  if session_id is not None:
290
295
  body["session_id"] = session_id
296
+ if session_key is not None:
297
+ body["session_key"] = session_key
291
298
  if access is not None:
292
299
  body["access"] = access
293
300
  return cast(Dict[str, Any], self._http.post(f"/v1/agents/{quote(agent_key)}/run", body))
294
301
 
295
302
  def run_stream(
296
303
  self, agent_key: str, *, input: Dict[str, Any], session_id: Optional[str] = None,
297
- access: Optional[Dict[str, Any]] = None,
304
+ session_key: Optional[str] = None, access: Optional[Dict[str, Any]] = None,
298
305
  ) -> Iterator[AgentRunStreamEvent]:
299
306
  """Same input as run() — real-time step progress instead of one awaited result.
300
307
 
@@ -307,6 +314,8 @@ class AgentsResource:
307
314
  body: Dict[str, Any] = {"input": input}
308
315
  if session_id is not None:
309
316
  body["session_id"] = session_id
317
+ if session_key is not None:
318
+ body["session_key"] = session_key
310
319
  if access is not None:
311
320
  body["access"] = access
312
321
  for frame in self._http.stream(f"/v1/agents/{quote(agent_key)}/run/stream", body):
@@ -315,8 +324,10 @@ class AgentsResource:
315
324
  def list_runs(
316
325
  self, agent_key: str, *, page: Optional[int] = None, page_size: Optional[int] = None,
317
326
  status: Optional[str] = None, session_id: Optional[str] = None,
327
+ session_key: Optional[str] = None, user_id: Optional[str] = None,
318
328
  ) -> Dict[str, Any]:
319
- qs = _query(page=page, pageSize=page_size, status=status, session_id=session_id)
329
+ """Filter to one conversation with `session_id`, or with `session_key` and the `user_id` it belongs to."""
330
+ qs = _query(page=page, pageSize=page_size, status=status, session_id=session_id, session_key=session_key, user_id=user_id)
320
331
  return cast(Dict[str, Any], self._http.get(f"/v1/agents/{quote(agent_key)}/runs{qs}"))
321
332
 
322
333
  def get_run(self, agent_key: str, run_id: str) -> Dict[str, Any]:
@@ -0,0 +1,77 @@
1
+ """Guardrail templates — a starting point for one industry (general, financial
2
+ services, healthcare) and one audience (customer or staff).
3
+
4
+ Previewing a template saves nothing: it returns the settings and what they
5
+ would change. Create a policy from ``preview.config`` to apply it, then
6
+ ``guardrail_policies.attach()`` it.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Any, Dict, List, Optional, cast
12
+ from urllib.parse import quote
13
+
14
+ from .._http import HttpClient
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class GuardrailTemplate:
19
+ id: str
20
+ # "general", "financial_services" or "healthcare".
21
+ industry: str
22
+ # "customer" or "staff". Members and patients are "customer": the person on the other end is the public.
23
+ audience: str
24
+ name: str
25
+ description: str
26
+ # Each setting the template wants, as a person would read it: {"id", "label", "value"}.
27
+ settings: List[Dict[str, str]]
28
+ # Topics the template adds to a policy's blocked list.
29
+ topics: List[str]
30
+ # A suggested reply for blocked requests, when the template has one.
31
+ reply_hint: Optional[str]
32
+ # Workspace-wide settings it recommends but cannot change itself, e.g. "redact_healthcare_identifiers".
33
+ workspace_settings: List[str]
34
+
35
+ @classmethod
36
+ def _from_dict(cls, d: Dict[str, Any]) -> "GuardrailTemplate":
37
+ return cls(
38
+ id=d["id"], industry=d["industry"], audience=d["audience"], name=d["name"], description=d["description"],
39
+ settings=list(d.get("settings") or []), topics=list(d.get("topics") or []), reply_hint=d.get("reply_hint"),
40
+ workspace_settings=list(d.get("workspace_settings") or []),
41
+ )
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class GuardrailTemplatePreview:
46
+ template_id: str
47
+ # The settings with the template applied: pass it as ``config`` to ``guardrail_policies.create()``.
48
+ config: Dict[str, Any]
49
+ # What applying the template changes, setting by setting: {"id", "label", "from", "to"}.
50
+ changes: List[Dict[str, str]]
51
+ # How many of the template's settings the starting config already had.
52
+ already_set: int
53
+ topics_added: List[str]
54
+ topics_already_blocked: List[str]
55
+
56
+ @classmethod
57
+ def _from_dict(cls, d: Dict[str, Any]) -> "GuardrailTemplatePreview":
58
+ return cls(
59
+ template_id=d["template_id"], config=d.get("config") or {}, changes=list(d.get("changes") or []),
60
+ already_set=int(d.get("already_set") or 0), topics_added=list(d.get("topics_added") or []),
61
+ topics_already_blocked=list(d.get("topics_already_blocked") or []),
62
+ )
63
+
64
+
65
+ class GuardrailTemplatesResource:
66
+ def __init__(self, http: HttpClient) -> None:
67
+ self._http = http
68
+
69
+ def list(self) -> List[GuardrailTemplate]:
70
+ data = cast(Dict[str, Any], self._http.get("/v1/guardrail-templates"))
71
+ return [GuardrailTemplate._from_dict(t) for t in data["templates"]]
72
+
73
+ def preview(self, template_id: str, *, config: Optional[Dict[str, Any]] = None) -> GuardrailTemplatePreview:
74
+ """What the template would change. Pass an existing policy's ``config`` to preview against it;
75
+ omit it to preview against the defaults."""
76
+ data = cast(Dict[str, Any], self._http.post(f"/v1/guardrail-templates/{quote(template_id)}/preview", {"config": config or {}}))
77
+ return GuardrailTemplatePreview._from_dict(data["preview"])
@@ -263,3 +263,33 @@ def test_replay_a_proposal_waits_longer_and_is_never_retried(client):
263
263
  with pytest.raises(LiyaEngineAPIError):
264
264
  client.agents.replay_limit_proposal("limit:a1:steps:20")
265
265
  assert boom.call_count == 1
266
+
267
+
268
+ @respx.mock
269
+ def test_run_sends_session_key_and_returns_the_echoed_key(client):
270
+ route = respx.post(f"{BASE_URL}/v1/agents/support-triage/run").mock(
271
+ return_value=httpx.Response(200, json={"success": True, "data": {"run_id": "run_2", "session_id": "sk_1", "session_key": "conv_55", "output": "ok"}})
272
+ )
273
+ result = client.agents.run("support-triage", session_key="conv_55", input={"user_id": "u1", "message": "hello"})
274
+ assert json.loads(route.calls[0].request.content) == {"input": {"user_id": "u1", "message": "hello"}, "session_key": "conv_55"}
275
+ assert result["session_key"] == "conv_55"
276
+
277
+
278
+ @respx.mock
279
+ def test_run_stream_sends_session_key(client):
280
+ sse_body = f"data: {json.dumps({'type': 'done', 'run_id': 'r', 'session_id': 's', 'output': 'x'})}\n\n"
281
+ route = respx.post(f"{BASE_URL}/v1/agents/support-triage/run/stream").mock(
282
+ return_value=httpx.Response(200, content=sse_body, headers={"content-type": "text/event-stream"})
283
+ )
284
+ list(client.agents.run_stream("support-triage", session_key="conv_55", input={"user_id": "u1", "message": "hi"}))
285
+ assert json.loads(route.calls[0].request.content)["session_key"] == "conv_55"
286
+
287
+
288
+ @respx.mock
289
+ def test_list_runs_filters_by_session_key_and_user_id(client):
290
+ route = respx.get(f"{BASE_URL}/v1/agents/support-triage/runs").mock(
291
+ return_value=httpx.Response(200, json={"success": True, "data": {"runs": [], "pagination": {"page": 1}}})
292
+ )
293
+ client.agents.list_runs("support-triage", session_key="conv_55", user_id="u1")
294
+ params = dict(route.calls[0].request.url.params)
295
+ assert params["session_key"] == "conv_55" and params["user_id"] == "u1"
@@ -0,0 +1,70 @@
1
+ import json
2
+
3
+ import httpx
4
+ import pytest
5
+ import respx
6
+
7
+ from liyaengine import LiyaEngine, LiyaEngineAPIError
8
+
9
+ BASE_URL = "https://api.test.liyaengine.ai"
10
+
11
+ TEMPLATE = {
12
+ "id": "healthcare-member", "industry": "healthcare", "audience": "customer", "name": "Healthcare · member facing",
13
+ "description": "For assistants that talk to members and patients.",
14
+ "settings": [{"id": "pii_mode", "label": "PII mode", "value": "Redact"}],
15
+ "topics": ["diagnose my symptoms"], "reply_hint": "Call your doctor.", "workspace_settings": ["redact_healthcare_identifiers"],
16
+ }
17
+ PREVIEW = {
18
+ "template_id": "healthcare-member",
19
+ "config": {"pre_llm": {"content_policy": {"injection_mode": "balanced", "blocked_topics": ["diagnose my symptoms"]}}},
20
+ "changes": [{"id": "injection_mode", "label": "How injection is judged", "from": "Standard", "to": "Balanced"}],
21
+ "already_set": 3, "topics_added": ["diagnose my symptoms"], "topics_already_blocked": [],
22
+ }
23
+
24
+
25
+ @pytest.fixture
26
+ def client():
27
+ with LiyaEngine(api_key="liya_test_key", base_url=BASE_URL, max_retries=0) as c:
28
+ yield c
29
+
30
+
31
+ @respx.mock
32
+ def test_list_returns_templates(client):
33
+ respx.get(f"{BASE_URL}/v1/guardrail-templates").mock(
34
+ return_value=httpx.Response(200, json={"success": True, "data": {"templates": [TEMPLATE]}})
35
+ )
36
+ templates = client.guardrail_templates.list()
37
+ assert templates[0].id == "healthcare-member"
38
+ assert templates[0].workspace_settings == ["redact_healthcare_identifiers"]
39
+ assert templates[0].topics == ["diagnose my symptoms"]
40
+
41
+
42
+ @respx.mock
43
+ def test_preview_against_defaults_sends_an_empty_config_and_returns_a_config_for_create(client):
44
+ route = respx.post(f"{BASE_URL}/v1/guardrail-templates/healthcare-member/preview").mock(
45
+ return_value=httpx.Response(200, json={"success": True, "data": {"preview": PREVIEW}})
46
+ )
47
+ preview = client.guardrail_templates.preview("healthcare-member")
48
+ assert json.loads(route.calls[0].request.content) == {"config": {}}
49
+ assert preview.changes[0]["to"] == "Balanced"
50
+ assert preview.config["pre_llm"]["content_policy"]["injection_mode"] == "balanced"
51
+ assert preview.already_set == 3
52
+
53
+
54
+ @respx.mock
55
+ def test_preview_against_a_policy_config(client):
56
+ route = respx.post(f"{BASE_URL}/v1/guardrail-templates/healthcare-member/preview").mock(
57
+ return_value=httpx.Response(200, json={"success": True, "data": {"preview": PREVIEW}})
58
+ )
59
+ client.guardrail_templates.preview("healthcare-member", config={"pre_llm": {"input_fields": {"scan": False}}})
60
+ assert json.loads(route.calls[0].request.content) == {"config": {"pre_llm": {"input_fields": {"scan": False}}}}
61
+
62
+
63
+ @respx.mock
64
+ def test_unknown_template_raises_the_api_error(client):
65
+ respx.post(f"{BASE_URL}/v1/guardrail-templates/ghost/preview").mock(
66
+ return_value=httpx.Response(404, json={"success": False, "error": {"code": "TEMPLATE_NOT_FOUND", "message": "There is no guardrail template with that id."}})
67
+ )
68
+ with pytest.raises(LiyaEngineAPIError) as err:
69
+ client.guardrail_templates.preview("ghost")
70
+ assert err.value.status == 404 and err.value.code == "TEMPLATE_NOT_FOUND"
File without changes
File without changes