liyaengine 0.4.0__tar.gz → 0.6.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 (22) hide show
  1. {liyaengine-0.4.0 → liyaengine-0.6.0}/PKG-INFO +44 -3
  2. {liyaengine-0.4.0 → liyaengine-0.6.0}/README.md +43 -2
  3. {liyaengine-0.4.0 → liyaengine-0.6.0}/pyproject.toml +1 -1
  4. {liyaengine-0.4.0 → liyaengine-0.6.0}/src/liyaengine/__init__.py +6 -1
  5. {liyaengine-0.4.0 → liyaengine-0.6.0}/src/liyaengine/client.py +3 -0
  6. liyaengine-0.6.0/src/liyaengine/resources/domains.py +386 -0
  7. liyaengine-0.6.0/tests/test_domains.py +222 -0
  8. {liyaengine-0.4.0 → liyaengine-0.6.0}/.github/workflows/ci.yml +0 -0
  9. {liyaengine-0.4.0 → liyaengine-0.6.0}/.gitignore +0 -0
  10. {liyaengine-0.4.0 → liyaengine-0.6.0}/LICENSE +0 -0
  11. {liyaengine-0.4.0 → liyaengine-0.6.0}/src/liyaengine/_http.py +0 -0
  12. {liyaengine-0.4.0 → liyaengine-0.6.0}/src/liyaengine/errors.py +0 -0
  13. {liyaengine-0.4.0 → liyaengine-0.6.0}/src/liyaengine/py.typed +0 -0
  14. {liyaengine-0.4.0 → liyaengine-0.6.0}/src/liyaengine/resources/__init__.py +0 -0
  15. {liyaengine-0.4.0 → liyaengine-0.6.0}/src/liyaengine/resources/agents.py +0 -0
  16. {liyaengine-0.4.0 → liyaengine-0.6.0}/src/liyaengine/resources/collections.py +0 -0
  17. {liyaengine-0.4.0 → liyaengine-0.6.0}/src/liyaengine/resources/evaluations.py +0 -0
  18. {liyaengine-0.4.0 → liyaengine-0.6.0}/src/liyaengine/resources/workflows.py +0 -0
  19. {liyaengine-0.4.0 → liyaengine-0.6.0}/tests/test_agents.py +0 -0
  20. {liyaengine-0.4.0 → liyaengine-0.6.0}/tests/test_collections.py +0 -0
  21. {liyaengine-0.4.0 → liyaengine-0.6.0}/tests/test_evaluations.py +0 -0
  22. {liyaengine-0.4.0 → liyaengine-0.6.0}/tests/test_workflows.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: liyaengine
3
- Version: 0.4.0
3
+ Version: 0.6.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
@@ -31,7 +31,7 @@ Description-Content-Type: text/markdown
31
31
 
32
32
  Official Python client for the [Liya Engine](https://liyaengine.ai) public API.
33
33
 
34
- > **Status: early access.** This SDK currently covers Collections, Agents, Workflows, and Evaluations. More resources (Domains, Run, Guardrail Policies) ship incrementally — see [Roadmap](#roadmap).
34
+ > **Status: early access.** This SDK currently covers Domains, Intents, Collections, Agents, Workflows, and Evaluations. More resources (Run, Guardrail Policies) ship incrementally — see [Roadmap](#roadmap).
35
35
 
36
36
  ## Install
37
37
 
@@ -64,6 +64,45 @@ with LiyaEngine(api_key="liya_...") as client:
64
64
 
65
65
  Get an API key from your [Liya Engine dashboard](https://app.liyaengine.ai) under Settings → API Keys.
66
66
 
67
+ ## Domains & Intents
68
+
69
+ A Domain is the top-level container most tenants configure first; Intents live under it.
70
+
71
+ ```python
72
+ domain = client.domains.create(domain_key="billing", display_name="Billing")
73
+
74
+ intent = client.domains.intents.create(
75
+ "billing", intent_key="refund-status", display_name="Refund Status",
76
+ description="Answer refund-status questions.",
77
+ prompt_template="You are a billing assistant. Question: {{message}}",
78
+ # Agent mode, per-intent execution/retrieval/cache overrides — optional:
79
+ agent_config={"enabled": True, "max_steps": 3},
80
+ )
81
+
82
+ one_intent = client.domains.intents.get("billing", "refund-status")
83
+
84
+ # Every update creates a restorable version snapshot automatically.
85
+ versions = client.domains.intents.versions.list("billing", "refund-status")
86
+ client.domains.intents.versions.restore("billing", "refund-status", versions[0].version_number)
87
+
88
+ # Direct retrieval — no LLM call, useful for testing knowledge scoping.
89
+ result = client.domains.query("billing", query="refund timeline")
90
+ ```
91
+
92
+ > `domains.update()`/`domains.intents.update()` return `{"updated": 1}`, not the updated object — call `get()`/`list()` again for the fresh state. Guardrail policy attachment is still dashboard-only (a separate resource with no `/v1` route yet). To bind an intent's prompt to a Prompt Studio library version instead of inline text, pass `prompt_binding={"kind": "library_version", "prompt_id": ..., "version_id": ..., "content_hash": ...}` in place of `prompt_template` — editing `prompt_template` directly afterward without also passing `prompt_binding` silently detaches the binding.
93
+
94
+ ## Collections
95
+
96
+ ```python
97
+ client.collections.list()
98
+ client.collections.get(id)
99
+ client.collections.create(slug=..., label=..., domain_keys=[...])
100
+ client.collections.update(id, label=..., tags=[...], visibility=...)
101
+ client.collections.delete(id)
102
+ ```
103
+
104
+ Full field reference: [Collections API](/docs/api-reference/collections). Document ingestion beyond a quick file drop (`domains.upload_document()`) is still dashboard-only.
105
+
67
106
  ## Agents
68
107
 
69
108
  ```python
@@ -172,13 +211,15 @@ LiyaEngine(
172
211
 
173
212
  ## Roadmap
174
213
 
214
+ - [x] Domains & Intents (full CRUD parity with the dashboard, prompt binding, agent/execution/retrieval/cache config, versioning, direct retrieval query, narrow document upload — guardrail policy attachment still dashboard-only)
175
215
  - [x] Collections
176
216
  - [x] Agents (full CRUD, deploy, run, run/session history)
177
217
  - [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
178
218
  - [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
179
- - [ ] Domains (custom domain + intent CRUD)
219
+ - [ ] Full KBaaS (document list/get/delete, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics)
180
220
  - [ ] Run / Run (streaming)
181
221
  - [ ] Guardrail Policies
222
+ - [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
182
223
  - [ ] Async client
183
224
 
184
225
  Full docs: https://liyaengine.ai/docs/sdks/python
@@ -2,7 +2,7 @@
2
2
 
3
3
  Official Python client for the [Liya Engine](https://liyaengine.ai) public API.
4
4
 
5
- > **Status: early access.** This SDK currently covers Collections, Agents, Workflows, and Evaluations. More resources (Domains, Run, Guardrail Policies) ship incrementally — see [Roadmap](#roadmap).
5
+ > **Status: early access.** This SDK currently covers Domains, Intents, Collections, Agents, Workflows, and Evaluations. More resources (Run, Guardrail Policies) ship incrementally — see [Roadmap](#roadmap).
6
6
 
7
7
  ## Install
8
8
 
@@ -35,6 +35,45 @@ with LiyaEngine(api_key="liya_...") as client:
35
35
 
36
36
  Get an API key from your [Liya Engine dashboard](https://app.liyaengine.ai) under Settings → API Keys.
37
37
 
38
+ ## Domains & Intents
39
+
40
+ A Domain is the top-level container most tenants configure first; Intents live under it.
41
+
42
+ ```python
43
+ domain = client.domains.create(domain_key="billing", display_name="Billing")
44
+
45
+ intent = client.domains.intents.create(
46
+ "billing", intent_key="refund-status", display_name="Refund Status",
47
+ description="Answer refund-status questions.",
48
+ prompt_template="You are a billing assistant. Question: {{message}}",
49
+ # Agent mode, per-intent execution/retrieval/cache overrides — optional:
50
+ agent_config={"enabled": True, "max_steps": 3},
51
+ )
52
+
53
+ one_intent = client.domains.intents.get("billing", "refund-status")
54
+
55
+ # Every update creates a restorable version snapshot automatically.
56
+ versions = client.domains.intents.versions.list("billing", "refund-status")
57
+ client.domains.intents.versions.restore("billing", "refund-status", versions[0].version_number)
58
+
59
+ # Direct retrieval — no LLM call, useful for testing knowledge scoping.
60
+ result = client.domains.query("billing", query="refund timeline")
61
+ ```
62
+
63
+ > `domains.update()`/`domains.intents.update()` return `{"updated": 1}`, not the updated object — call `get()`/`list()` again for the fresh state. Guardrail policy attachment is still dashboard-only (a separate resource with no `/v1` route yet). To bind an intent's prompt to a Prompt Studio library version instead of inline text, pass `prompt_binding={"kind": "library_version", "prompt_id": ..., "version_id": ..., "content_hash": ...}` in place of `prompt_template` — editing `prompt_template` directly afterward without also passing `prompt_binding` silently detaches the binding.
64
+
65
+ ## Collections
66
+
67
+ ```python
68
+ client.collections.list()
69
+ client.collections.get(id)
70
+ client.collections.create(slug=..., label=..., domain_keys=[...])
71
+ client.collections.update(id, label=..., tags=[...], visibility=...)
72
+ client.collections.delete(id)
73
+ ```
74
+
75
+ Full field reference: [Collections API](/docs/api-reference/collections). Document ingestion beyond a quick file drop (`domains.upload_document()`) is still dashboard-only.
76
+
38
77
  ## Agents
39
78
 
40
79
  ```python
@@ -143,13 +182,15 @@ LiyaEngine(
143
182
 
144
183
  ## Roadmap
145
184
 
185
+ - [x] Domains & Intents (full CRUD parity with the dashboard, prompt binding, agent/execution/retrieval/cache config, versioning, direct retrieval query, narrow document upload — guardrail policy attachment still dashboard-only)
146
186
  - [x] Collections
147
187
  - [x] Agents (full CRUD, deploy, run, run/session history)
148
188
  - [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
149
189
  - [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
150
- - [ ] Domains (custom domain + intent CRUD)
190
+ - [ ] Full KBaaS (document list/get/delete, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics)
151
191
  - [ ] Run / Run (streaming)
152
192
  - [ ] Guardrail Policies
193
+ - [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
153
194
  - [ ] Async client
154
195
 
155
196
  Full docs: https://liyaengine.ai/docs/sdks/python
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "liyaengine"
7
- version = "0.4.0"
7
+ version = "0.6.0"
8
8
  description = "Official Python client for the Liya Engine public API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -4,6 +4,7 @@ from .resources.agents import Agent
4
4
  from .resources.collections import Collection
5
5
  from .resources.workflows import Workflow
6
6
  from .resources.evaluations import EvalDataset, EvalCase, EvalSuite, EvalRun, EvalReview
7
+ from .resources.domains import Domain, Intent, DomainSource, IntentVersionSummary
7
8
 
8
9
  __all__ = [
9
10
  "LiyaEngine",
@@ -17,6 +18,10 @@ __all__ = [
17
18
  "EvalSuite",
18
19
  "EvalRun",
19
20
  "EvalReview",
21
+ "Domain",
22
+ "Intent",
23
+ "DomainSource",
24
+ "IntentVersionSummary",
20
25
  ]
21
26
 
22
- __version__ = "0.4.0"
27
+ __version__ = "0.6.0"
@@ -9,6 +9,7 @@ from .resources.agents import AgentsResource
9
9
  from .resources.collections import CollectionsResource
10
10
  from .resources.workflows import WorkflowsResource
11
11
  from .resources.evaluations import EvaluationsResource
12
+ from .resources.domains import DomainsResource, IntentsResource
12
13
 
13
14
  _DEFAULT_BASE_URL = "https://api.liyaengine.ai"
14
15
 
@@ -45,6 +46,8 @@ class LiyaEngine:
45
46
  self.agents = AgentsResource(self._http)
46
47
  self.workflows = WorkflowsResource(self._http)
47
48
  self.evaluations = EvaluationsResource(self._http)
49
+ self.domains = DomainsResource(self._http)
50
+ self.intents = IntentsResource(self._http)
48
51
 
49
52
  def close(self) -> None:
50
53
  self._http.close()
@@ -0,0 +1,386 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List, Literal, Optional, TypedDict, Union, cast
5
+ from urllib.parse import quote
6
+
7
+ from .._http import HttpClient
8
+
9
+
10
+ class InlinePromptBinding(TypedDict):
11
+ kind: Literal["inline"]
12
+ content: str
13
+
14
+
15
+ class LibraryVersionPromptBinding(TypedDict):
16
+ """Pinned to one exact, immutable, content-hashed Prompt Studio version —
17
+ deliberately rejects mutable aliases like "latest" or "production"."""
18
+
19
+ kind: Literal["library_version"]
20
+ prompt_id: str
21
+ version_id: str
22
+ content_hash: str
23
+
24
+
25
+ PromptBinding = Union[InlinePromptBinding, LibraryVersionPromptBinding]
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Intent:
30
+ """Real column also includes guardrail_policy_id — dashboard-only to write
31
+ today, not on create()/update()'s keyword args below."""
32
+
33
+ id: str
34
+ tenant_id: str
35
+ domain_key: str
36
+ intent_key: str
37
+ display_name: str
38
+ description: Optional[str]
39
+ prompt_template: str
40
+ prompt_binding: Optional[PromptBinding]
41
+ output_schema: Optional[Dict[str, Any]]
42
+ input_schema: Optional[Dict[str, Any]]
43
+ guardrails_config: Optional[Dict[str, Any]]
44
+ agent_config: Optional[Dict[str, Any]]
45
+ execution_config: Optional[Dict[str, Any]]
46
+ retrieval_config: Optional[Dict[str, Any]]
47
+ cache_config: Optional[Dict[str, Any]]
48
+ is_active: bool
49
+ sort_order: int
50
+ created_at: str
51
+ updated_at: str
52
+
53
+ @classmethod
54
+ def _from_dict(cls, data: Dict[str, Any]) -> "Intent":
55
+ return cls(
56
+ id=data["id"], tenant_id=data["tenant_id"], domain_key=data["domain_key"], intent_key=data["intent_key"],
57
+ display_name=data["display_name"], description=data.get("description"),
58
+ prompt_template=data["prompt_template"], prompt_binding=data.get("prompt_binding"),
59
+ output_schema=data.get("output_schema"), input_schema=data.get("input_schema"),
60
+ guardrails_config=data.get("guardrails_config"), agent_config=data.get("agent_config"),
61
+ execution_config=data.get("execution_config"), retrieval_config=data.get("retrieval_config"),
62
+ cache_config=data.get("cache_config"),
63
+ is_active=data["is_active"], sort_order=data["sort_order"],
64
+ created_at=data["created_at"], updated_at=data["updated_at"],
65
+ )
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class IntentVersionSummary:
70
+ id: str
71
+ version_number: int
72
+ changed_fields: List[str]
73
+ change_type: Literal["create", "update", "restore"]
74
+ restored_from_version: Optional[int]
75
+ created_by: Optional[str]
76
+ actor_name: Optional[str]
77
+ created_at: str
78
+
79
+ @classmethod
80
+ def _from_dict(cls, data: Dict[str, Any]) -> "IntentVersionSummary":
81
+ return cls(
82
+ id=data["id"], version_number=data["version_number"], changed_fields=data["changed_fields"],
83
+ change_type=data["change_type"], restored_from_version=data.get("restored_from_version"),
84
+ created_by=data.get("created_by"), actor_name=data.get("actorName"), created_at=data["created_at"],
85
+ )
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class Domain:
90
+ """Real columns also include guardrail_policy_id/tools_config/default_top_k/
91
+ default_similarity_threshold — dashboard-only to write today."""
92
+
93
+ id: str
94
+ tenant_id: str
95
+ domain_key: str
96
+ display_name: str
97
+ description: Optional[str]
98
+ icon: str
99
+ color: str
100
+ system_prompt: Optional[str]
101
+ prompt_binding: Optional[PromptBinding]
102
+ context_enrichment_webhook_url: Optional[str]
103
+ retrieval_scope: Optional[str]
104
+ status: Literal["draft", "active", "archived"]
105
+ is_active: bool
106
+ created_at: str
107
+ updated_at: str
108
+ # Present on get()/list() only when a domain has intents/source types — not on create().
109
+ intents: Optional[List[Intent]] = None
110
+ source_types: Optional[List[Dict[str, Any]]] = None
111
+
112
+ @classmethod
113
+ def _from_dict(cls, data: Dict[str, Any]) -> "Domain":
114
+ intents = data.get("intents")
115
+ return cls(
116
+ id=data["id"], tenant_id=data["tenant_id"], domain_key=data["domain_key"],
117
+ display_name=data["display_name"], description=data.get("description"),
118
+ icon=data["icon"], color=data["color"], system_prompt=data.get("system_prompt"),
119
+ prompt_binding=data.get("prompt_binding"),
120
+ context_enrichment_webhook_url=data.get("context_enrichment_webhook_url"),
121
+ retrieval_scope=data.get("retrieval_scope"), status=data.get("status", "active"),
122
+ is_active=data["is_active"],
123
+ created_at=data["created_at"], updated_at=data["updated_at"],
124
+ intents=[Intent._from_dict(i) for i in intents] if intents is not None else None,
125
+ source_types=data.get("source_types"),
126
+ )
127
+
128
+
129
+ @dataclass(frozen=True)
130
+ class DomainSource:
131
+ """A domain-scoped view of a Collection — same underlying resource as
132
+ client.collections. Prefer client.collections for the full config surface;
133
+ this covers only the create/list/delete + attach-a-document routes nested
134
+ under a domain."""
135
+
136
+ id: str
137
+ tenant_id: str
138
+ domain_key: str
139
+ slug: str
140
+ label: str
141
+ color: str
142
+ created_at: str
143
+ # Present on create() only.
144
+ domain_keys: Optional[List[str]] = None
145
+
146
+ @classmethod
147
+ def _from_dict(cls, data: Dict[str, Any]) -> "DomainSource":
148
+ return cls(
149
+ id=data["id"], tenant_id=data["tenant_id"], domain_key=data["domain_key"],
150
+ slug=data["slug"], label=data["label"], color=data["color"],
151
+ created_at=data["created_at"], domain_keys=data.get("domain_keys"),
152
+ )
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class IntentCatalogEntry:
157
+ domain: str
158
+ domain_label: str
159
+ intent: str
160
+ display_name: str
161
+ description: Optional[str]
162
+ endpoint: str
163
+ method: str
164
+ input_schema: Dict[str, Any]
165
+ output_schema: Optional[Dict[str, Any]]
166
+
167
+ @classmethod
168
+ def _from_dict(cls, data: Dict[str, Any]) -> "IntentCatalogEntry":
169
+ return cls(
170
+ domain=data["domain"], domain_label=data["domainLabel"], intent=data["intent"],
171
+ display_name=data["displayName"], description=data.get("description"),
172
+ endpoint=data["endpoint"], method=data["method"],
173
+ input_schema=data.get("inputSchema", {}), output_schema=data.get("outputSchema"),
174
+ )
175
+
176
+
177
+ class DomainIntentVersionsResource:
178
+ def __init__(self, http: HttpClient) -> None:
179
+ self._http = http
180
+
181
+ def list(self, domain_key: str, intent_key: str) -> List[IntentVersionSummary]:
182
+ """Newest first, max 50."""
183
+ data = self._http.get(f"/v1/domains/{quote(domain_key)}/intents/{quote(intent_key)}/versions")
184
+ return [IntentVersionSummary._from_dict(v) for v in data["versions"]]
185
+
186
+ def get(self, domain_key: str, intent_key: str, version_number: int) -> IntentVersionSummary:
187
+ data = self._http.get(f"/v1/domains/{quote(domain_key)}/intents/{quote(intent_key)}/versions/{version_number}")
188
+ return IntentVersionSummary._from_dict(data["version"])
189
+
190
+ def restore(self, domain_key: str, intent_key: str, version_number: int) -> Intent:
191
+ """Writes the version's snapshot back onto the live intent. The restore itself is versioned too."""
192
+ data = self._http.post(f"/v1/domains/{quote(domain_key)}/intents/{quote(intent_key)}/versions/{version_number}/restore", {})
193
+ return Intent._from_dict(data["intent"])
194
+
195
+
196
+ class DomainIntentsResource:
197
+ def __init__(self, http: HttpClient) -> None:
198
+ self._http = http
199
+ self.versions = DomainIntentVersionsResource(http)
200
+
201
+ def list(self, domain_key: str) -> List[Intent]:
202
+ data = self._http.get(f"/v1/domains/{quote(domain_key)}/intents")
203
+ return [Intent._from_dict(i) for i in data["intents"]]
204
+
205
+ def get(self, domain_key: str, intent_key: str) -> Intent:
206
+ """No get-single-intent route existed before this — now it does."""
207
+ data = self._http.get(f"/v1/domains/{quote(domain_key)}/intents/{quote(intent_key)}")
208
+ return Intent._from_dict(data["intent"])
209
+
210
+ # /v1/domains/:key/intents predates the snake_case wire convention every
211
+ # other /v1 resource in this SDK uses, and has real external consumers
212
+ # (A3LearningLabs, Qistara, StoryHire per the API's own doc comment) — its
213
+ # request bodies are camelCase. Translated here so this SDK's own public
214
+ # shape stays consistent with every other resource; changing the wire
215
+ # format itself would break those existing integrations.
216
+ def create(
217
+ self, domain_key: str, *, intent_key: str, display_name: str, description: str,
218
+ prompt_template: Optional[str] = None, prompt_binding: Optional[PromptBinding] = None,
219
+ output_schema: Optional[Dict[str, Any]] = None, input_schema: Optional[Dict[str, Any]] = None,
220
+ guardrails_config: Optional[Dict[str, Any]] = None, agent_config: Optional[Dict[str, Any]] = None,
221
+ execution_config: Optional[Dict[str, Any]] = None, retrieval_config: Optional[Dict[str, Any]] = None,
222
+ cache_config: Optional[Dict[str, Any]] = None,
223
+ ) -> Intent:
224
+ """Either prompt_template or prompt_binding is required — pass prompt_binding
225
+ to pin the intent to a Prompt Studio library version instead of inline text."""
226
+ body: Dict[str, Any] = {"intentKey": intent_key, "displayName": display_name, "description": description}
227
+ optional = {
228
+ "promptTemplate": prompt_template, "promptBinding": prompt_binding,
229
+ "outputSchema": output_schema, "inputSchema": input_schema, "guardrailsConfig": guardrails_config,
230
+ "agentConfig": agent_config, "executionConfig": execution_config,
231
+ "retrievalConfig": retrieval_config, "cacheConfig": cache_config,
232
+ }
233
+ body.update({k: v for k, v in optional.items() if v is not None})
234
+ data = self._http.post(f"/v1/domains/{quote(domain_key)}/intents", body)
235
+ return Intent._from_dict(data["intent"])
236
+
237
+ def update(
238
+ self, domain_key: str, intent_key: str, *, display_name: Optional[str] = None,
239
+ description: Optional[str] = None, prompt_template: Optional[str] = None,
240
+ prompt_binding: Optional[PromptBinding] = None,
241
+ output_schema: Optional[Dict[str, Any]] = None, input_schema: Optional[Dict[str, Any]] = None,
242
+ guardrails_config: Optional[Dict[str, Any]] = None, agent_config: Optional[Dict[str, Any]] = None,
243
+ execution_config: Optional[Dict[str, Any]] = None, retrieval_config: Optional[Dict[str, Any]] = None,
244
+ cache_config: Optional[Dict[str, Any]] = None, sort_order: Optional[int] = None,
245
+ model_override: Optional[str] = None, is_active: Optional[bool] = None,
246
+ ) -> Dict[str, int]:
247
+ """Returns {"updated": 1}, not the updated Intent — call get() again if
248
+ you need the fresh object. Editing prompt_template without also passing
249
+ prompt_binding detaches any existing binding on this intent."""
250
+ body: Dict[str, Any] = {}
251
+ optional = {
252
+ "displayName": display_name, "description": description, "promptTemplate": prompt_template,
253
+ "promptBinding": prompt_binding, "outputSchema": output_schema, "inputSchema": input_schema,
254
+ "guardrailsConfig": guardrails_config, "agentConfig": agent_config,
255
+ "executionConfig": execution_config, "retrievalConfig": retrieval_config,
256
+ "cacheConfig": cache_config, "sortOrder": sort_order, "modelOverride": model_override,
257
+ "isActive": is_active,
258
+ }
259
+ body.update({k: v for k, v in optional.items() if v is not None})
260
+ return cast(Dict[str, int], self._http.patch(f"/v1/domains/{quote(domain_key)}/intents/{quote(intent_key)}", body))
261
+
262
+ def delete(self, domain_key: str, intent_key: str) -> None:
263
+ """Soft delete."""
264
+ self._http.delete(f"/v1/domains/{quote(domain_key)}/intents/{quote(intent_key)}")
265
+
266
+
267
+ class DomainSourcesResource:
268
+ def __init__(self, http: HttpClient) -> None:
269
+ self._http = http
270
+
271
+ def list(self, domain_key: str) -> List[DomainSource]:
272
+ data = self._http.get(f"/v1/domains/{quote(domain_key)}/sources")
273
+ return [DomainSource._from_dict(s) for s in data["sources"]]
274
+
275
+ def create(self, domain_key: str, *, slug: str, label: str, color: Optional[str] = None) -> DomainSource:
276
+ body: Dict[str, Any] = {"slug": slug, "label": label}
277
+ if color is not None:
278
+ body["color"] = color
279
+ data = self._http.post(f"/v1/domains/{quote(domain_key)}/sources", body)
280
+ return DomainSource._from_dict(data["sourceType"])
281
+
282
+ def delete(self, domain_key: str, slug: str) -> None:
283
+ self._http.delete(f"/v1/domains/{quote(domain_key)}/sources/{quote(slug)}")
284
+
285
+
286
+ class DomainsResource:
287
+ """Custom domains — the top-level container tenants configure first (system
288
+ prompt, retrieval scope, then intents and knowledge underneath). Mirrors the
289
+ full /v1/domains surface, including intent versioning (intents.versions) and
290
+ the agent/execution/retrieval/cache config blobs. Guardrail policy attachment
291
+ is still dashboard-only (no /v1 route for that yet — a separate resource
292
+ entirely)."""
293
+
294
+ def __init__(self, http: HttpClient) -> None:
295
+ self._http = http
296
+ self.intents = DomainIntentsResource(http)
297
+ self.sources = DomainSourcesResource(http)
298
+
299
+ def list(self) -> List[Domain]:
300
+ data = self._http.get("/v1/domains")
301
+ return [Domain._from_dict(d) for d in data["domains"]]
302
+
303
+ def get(self, domain_key: str) -> Domain:
304
+ """Includes this domain's intents and source types."""
305
+ data = self._http.get(f"/v1/domains/{quote(domain_key)}")
306
+ return Domain._from_dict(data["domain"])
307
+
308
+ # /v1/domains predates the snake_case wire convention every other /v1
309
+ # resource in this SDK uses, and has real external consumers
310
+ # (A3LearningLabs, Qistara, StoryHire per the API's own doc comment) — its
311
+ # request bodies are camelCase. Translated here so this SDK's own public
312
+ # shape stays consistent with every other resource.
313
+ def create(
314
+ self, *, domain_key: str, display_name: str, description: Optional[str] = None,
315
+ icon: Optional[str] = None, color: Optional[str] = None, system_prompt: Optional[str] = None,
316
+ prompt_binding: Optional[PromptBinding] = None,
317
+ context_enrichment_webhook_url: Optional[str] = None,
318
+ status: Optional[Literal["draft", "active", "archived"]] = None,
319
+ ) -> Domain:
320
+ body: Dict[str, Any] = {"domainKey": domain_key, "displayName": display_name}
321
+ optional = {
322
+ "description": description, "icon": icon, "color": color, "systemPrompt": system_prompt,
323
+ "promptBinding": prompt_binding,
324
+ "contextEnrichmentWebhookUrl": context_enrichment_webhook_url, "status": status,
325
+ }
326
+ body.update({k: v for k, v in optional.items() if v is not None})
327
+ data = self._http.post("/v1/domains", body)
328
+ return Domain._from_dict(data["domain"])
329
+
330
+ def update(
331
+ self, domain_key: str, *, display_name: Optional[str] = None, description: Optional[str] = None,
332
+ icon: Optional[str] = None, color: Optional[str] = None, system_prompt: Optional[str] = None,
333
+ prompt_binding: Optional[PromptBinding] = None,
334
+ retrieval_scope: Optional[str] = None, context_enrichment_webhook_url: Optional[str] = None,
335
+ status: Optional[Literal["draft", "active", "archived"]] = None,
336
+ ) -> Dict[str, int]:
337
+ """Returns {"updated": 1}, not the updated Domain — call get() again for
338
+ the fresh object. Editing system_prompt without also passing
339
+ prompt_binding detaches any existing binding on this domain."""
340
+ body: Dict[str, Any] = {}
341
+ optional = {
342
+ "displayName": display_name, "description": description, "icon": icon, "color": color,
343
+ "systemPrompt": system_prompt, "promptBinding": prompt_binding, "retrievalScope": retrieval_scope,
344
+ "contextEnrichmentWebhookUrl": context_enrichment_webhook_url, "status": status,
345
+ }
346
+ body.update({k: v for k, v in optional.items() if v is not None})
347
+ return cast(Dict[str, int], self._http.patch(f"/v1/domains/{quote(domain_key)}", body))
348
+
349
+ def delete(self, domain_key: str) -> None:
350
+ """Soft delete."""
351
+ self._http.delete(f"/v1/domains/{quote(domain_key)}")
352
+
353
+ def query(self, domain_key: str, *, query: str, top_k: Optional[int] = None) -> Dict[str, Any]:
354
+ """Direct retrieval — runs this domain's knowledge search with no LLM
355
+ call and no intent involved. Useful for testing collection/retrieval-scope
356
+ configuration, or for building your own retrieval-then-generate flow."""
357
+ body: Dict[str, Any] = {"query": query}
358
+ if top_k is not None:
359
+ body["top_k"] = top_k
360
+ return cast(Dict[str, Any], self._http.post(f"/v1/domains/{quote(domain_key)}/query", body))
361
+
362
+ def upload_document(self, domain_key: str, source_slug: str, *, file_base64: str, file_name: str) -> Dict[str, Any]:
363
+ """Uploads a file (base64), extracts text, chunks, embeds, and attaches
364
+ it to the named source (collection) — a real but narrow ingestion path:
365
+ no category, no URL crawl, no async job, and it always uses
366
+ text-embedding-3-small regardless of the collection's own
367
+ default_embedding_model. For anything beyond a quick file drop, use the
368
+ dashboard's Knowledge tab today."""
369
+ data = self._http.post(
370
+ f"/v1/domains/{quote(domain_key)}/sources/{quote(source_slug)}/docs",
371
+ {"fileBase64": file_base64, "fileName": file_name},
372
+ )
373
+ return cast(Dict[str, Any], data["document"])
374
+
375
+
376
+ class IntentsResource:
377
+ """Flat intent catalog — cuts across every custom domain, for external
378
+ discovery (mirrors the dashboard's API Explorer page). Read-only; create/
379
+ update/delete an intent via client.domains.intents."""
380
+
381
+ def __init__(self, http: HttpClient) -> None:
382
+ self._http = http
383
+
384
+ def list_all(self) -> List[IntentCatalogEntry]:
385
+ data = self._http.get("/v1/intents")
386
+ return [IntentCatalogEntry._from_dict(i) for i in data["intents"]]
@@ -0,0 +1,222 @@
1
+ import httpx
2
+ import pytest
3
+ import respx
4
+
5
+ from liyaengine import LiyaEngine
6
+
7
+ BASE_URL = "https://api.test.liyaengine.ai"
8
+
9
+ FIXTURE_DOMAIN = {
10
+ "id": "dom_123",
11
+ "tenant_id": "tenant_1",
12
+ "domain_key": "billing",
13
+ "display_name": "Billing",
14
+ "description": None,
15
+ "icon": "◆",
16
+ "color": "#6366f1",
17
+ "system_prompt": None,
18
+ "prompt_binding": None,
19
+ "context_enrichment_webhook_url": None,
20
+ "retrieval_scope": None,
21
+ "status": "active",
22
+ "is_active": True,
23
+ "created_at": "2026-01-01T00:00:00.000Z",
24
+ "updated_at": "2026-01-01T00:00:00.000Z",
25
+ }
26
+
27
+ FIXTURE_INTENT = {
28
+ "id": "int_123",
29
+ "tenant_id": "tenant_1",
30
+ "domain_key": "billing",
31
+ "intent_key": "refund-status",
32
+ "display_name": "Refund Status",
33
+ "description": "Answer refund status questions.",
34
+ "prompt_template": "You are a billing assistant...",
35
+ "prompt_binding": None,
36
+ "output_schema": None,
37
+ "input_schema": None,
38
+ "guardrails_config": None,
39
+ "agent_config": None,
40
+ "execution_config": None,
41
+ "retrieval_config": None,
42
+ "cache_config": None,
43
+ "is_active": True,
44
+ "sort_order": 0,
45
+ "created_at": "2026-01-01T00:00:00.000Z",
46
+ "updated_at": "2026-01-01T00:00:00.000Z",
47
+ }
48
+
49
+ FIXTURE_VERSION = {
50
+ "id": "ver_1",
51
+ "version_number": 1,
52
+ "changed_fields": ["prompt_template"],
53
+ "change_type": "create",
54
+ "restored_from_version": None,
55
+ "created_by": None,
56
+ "actorName": None,
57
+ "created_at": "2026-01-01T00:00:00.000Z",
58
+ }
59
+
60
+
61
+ @pytest.fixture
62
+ def client():
63
+ with LiyaEngine(api_key="liya_test_key", base_url=BASE_URL) as c:
64
+ yield c
65
+
66
+
67
+ @respx.mock
68
+ def test_domain_crud(client):
69
+ respx.get(f"{BASE_URL}/v1/domains").mock(
70
+ return_value=httpx.Response(200, json={"success": True, "data": {"domains": [FIXTURE_DOMAIN]}})
71
+ )
72
+ domains = client.domains.list()
73
+ assert len(domains) == 1
74
+
75
+ respx.post(f"{BASE_URL}/v1/domains").mock(
76
+ return_value=httpx.Response(201, json={"success": True, "data": {"domain": FIXTURE_DOMAIN}})
77
+ )
78
+ created = client.domains.create(domain_key="billing", display_name="Billing", status="draft")
79
+ assert created.domain_key == "billing"
80
+
81
+ respx.get(f"{BASE_URL}/v1/domains/billing").mock(
82
+ return_value=httpx.Response(200, json={"success": True, "data": {"domain": {**FIXTURE_DOMAIN, "intents": [FIXTURE_INTENT], "source_types": []}}})
83
+ )
84
+ fetched = client.domains.get("billing")
85
+ assert fetched.intents is not None
86
+ assert len(fetched.intents) == 1
87
+
88
+ respx.patch(f"{BASE_URL}/v1/domains/billing").mock(
89
+ return_value=httpx.Response(200, json={"success": True, "data": {"updated": 1}})
90
+ )
91
+ updated = client.domains.update("billing", display_name="Billing Support", status="active")
92
+ assert updated["updated"] == 1
93
+
94
+ respx.delete(f"{BASE_URL}/v1/domains/billing").mock(
95
+ return_value=httpx.Response(200, json={"success": True, "data": {"deleted": "billing"}})
96
+ )
97
+ client.domains.delete("billing")
98
+
99
+
100
+ @respx.mock
101
+ def test_domain_query(client):
102
+ respx.post(f"{BASE_URL}/v1/domains/billing/query").mock(
103
+ return_value=httpx.Response(200, json={"success": True, "data": {"results": [{"content": "Refunds take 5-7 days.", "score": 0.91}], "total": 1}})
104
+ )
105
+ result = client.domains.query("billing", query="refund timeline")
106
+ assert result["total"] == 1
107
+ assert "5-7 days" in result["results"][0]["content"]
108
+
109
+
110
+ @respx.mock
111
+ def test_domain_upload_document(client):
112
+ respx.post(f"{BASE_URL}/v1/domains/billing/sources/billing-faq/docs").mock(
113
+ return_value=httpx.Response(201, json={"success": True, "data": {"document": {"id": "doc_1", "name": "faq.txt", "chunks": 3, "sizeKb": 2, "uploadedAt": "2026-01-01T00:00:00.000Z"}}})
114
+ )
115
+ doc = client.domains.upload_document("billing", "billing-faq", file_base64="aGVsbG8=", file_name="faq.txt")
116
+ assert doc["chunks"] == 3
117
+
118
+
119
+ @respx.mock
120
+ def test_domain_intents_crud(client):
121
+ respx.get(f"{BASE_URL}/v1/domains/billing/intents").mock(
122
+ return_value=httpx.Response(200, json={"success": True, "data": {"intents": [FIXTURE_INTENT]}})
123
+ )
124
+ intents = client.domains.intents.list("billing")
125
+ assert len(intents) == 1
126
+
127
+ respx.get(f"{BASE_URL}/v1/domains/billing/intents/refund-status").mock(
128
+ return_value=httpx.Response(200, json={"success": True, "data": {"intent": FIXTURE_INTENT}})
129
+ )
130
+ fetched = client.domains.intents.get("billing", "refund-status")
131
+ assert fetched.intent_key == "refund-status"
132
+
133
+ respx.post(f"{BASE_URL}/v1/domains/billing/intents").mock(
134
+ return_value=httpx.Response(201, json={"success": True, "data": {"intent": FIXTURE_INTENT}})
135
+ )
136
+ created = client.domains.intents.create(
137
+ "billing", intent_key="refund-status", display_name="Refund Status",
138
+ description="Answer refund status questions.", prompt_template="You are a billing assistant...",
139
+ )
140
+ assert created.intent_key == "refund-status"
141
+
142
+ respx.patch(f"{BASE_URL}/v1/domains/billing/intents/refund-status").mock(
143
+ return_value=httpx.Response(200, json={"success": True, "data": {"updated": 1}})
144
+ )
145
+ updated = client.domains.intents.update(
146
+ "billing", "refund-status", display_name="Refund Status v2",
147
+ agent_config={"enabled": True, "max_steps": 3}, sort_order=2,
148
+ )
149
+ assert updated["updated"] == 1
150
+
151
+ respx.delete(f"{BASE_URL}/v1/domains/billing/intents/refund-status").mock(
152
+ return_value=httpx.Response(200, json={"success": True, "data": {"deleted": "refund-status"}})
153
+ )
154
+ client.domains.intents.delete("billing", "refund-status")
155
+
156
+
157
+ @respx.mock
158
+ def test_domain_intent_create_with_prompt_binding(client):
159
+ respx.post(f"{BASE_URL}/v1/domains/billing/intents").mock(
160
+ return_value=httpx.Response(201, json={"success": True, "data": {"intent": FIXTURE_INTENT}})
161
+ )
162
+ created = client.domains.intents.create(
163
+ "billing", intent_key="refund-status", display_name="Refund Status",
164
+ description="Answer refund status questions.",
165
+ prompt_binding={"kind": "library_version", "prompt_id": "prompt_1", "version_id": "version_2", "content_hash": "sha256:" + "a" * 64},
166
+ )
167
+ assert created.intent_key == "refund-status"
168
+
169
+
170
+ @respx.mock
171
+ def test_domain_intent_versions(client):
172
+ respx.get(f"{BASE_URL}/v1/domains/billing/intents/refund-status/versions").mock(
173
+ return_value=httpx.Response(200, json={"success": True, "data": {"versions": [FIXTURE_VERSION]}})
174
+ )
175
+ versions = client.domains.intents.versions.list("billing", "refund-status")
176
+ assert len(versions) == 1
177
+ assert versions[0].change_type == "create"
178
+
179
+ respx.get(f"{BASE_URL}/v1/domains/billing/intents/refund-status/versions/1").mock(
180
+ return_value=httpx.Response(200, json={"success": True, "data": {"version": FIXTURE_VERSION}})
181
+ )
182
+ version = client.domains.intents.versions.get("billing", "refund-status", 1)
183
+ assert version.version_number == 1
184
+
185
+ respx.post(f"{BASE_URL}/v1/domains/billing/intents/refund-status/versions/1/restore").mock(
186
+ return_value=httpx.Response(200, json={"success": True, "data": {"intent": FIXTURE_INTENT}})
187
+ )
188
+ restored = client.domains.intents.versions.restore("billing", "refund-status", 1)
189
+ assert restored.intent_key == "refund-status"
190
+
191
+
192
+ @respx.mock
193
+ def test_domain_sources_crud(client):
194
+ respx.get(f"{BASE_URL}/v1/domains/billing/sources").mock(
195
+ return_value=httpx.Response(200, json={"success": True, "data": {"sources": [{"id": "src_1", "tenant_id": "tenant_1", "domain_key": "billing", "slug": "billing-faq", "label": "Billing FAQ", "color": "#6366f1", "created_at": "2026-01-01T00:00:00.000Z"}]}})
196
+ )
197
+ sources = client.domains.sources.list("billing")
198
+ assert len(sources) == 1
199
+
200
+ respx.post(f"{BASE_URL}/v1/domains/billing/sources").mock(
201
+ return_value=httpx.Response(201, json={"success": True, "data": {"sourceType": {"id": "src_new", "tenant_id": "tenant_1", "domain_key": "billing", "slug": "billing-faq", "label": "Billing FAQ", "color": "#6366f1", "created_at": "2026-01-01T00:00:00.000Z", "domain_keys": ["billing"]}}})
202
+ )
203
+ created = client.domains.sources.create("billing", slug="billing-faq", label="Billing FAQ")
204
+ assert created.slug == "billing-faq"
205
+
206
+ respx.delete(f"{BASE_URL}/v1/domains/billing/sources/billing-faq").mock(
207
+ return_value=httpx.Response(200, json={"success": True, "data": {"deleted": "billing-faq"}})
208
+ )
209
+ client.domains.sources.delete("billing", "billing-faq")
210
+
211
+
212
+ @respx.mock
213
+ def test_intents_list_all(client):
214
+ respx.get(f"{BASE_URL}/v1/intents").mock(
215
+ return_value=httpx.Response(200, json={"success": True, "data": {"intents": [{
216
+ "domain": "billing", "domainLabel": "Billing", "intent": "refund-status", "displayName": "Refund Status",
217
+ "description": None, "endpoint": "/v1/billing/refund-status", "method": "POST", "inputSchema": {}, "outputSchema": None,
218
+ }], "total": 1}})
219
+ )
220
+ catalog = client.intents.list_all()
221
+ assert len(catalog) == 1
222
+ assert catalog[0].domain == "billing"
File without changes
File without changes