liyaengine 0.5.0__tar.gz → 0.7.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 (24) hide show
  1. {liyaengine-0.5.0 → liyaengine-0.7.0}/PKG-INFO +69 -6
  2. {liyaengine-0.5.0 → liyaengine-0.7.0}/README.md +68 -5
  3. {liyaengine-0.5.0 → liyaengine-0.7.0}/pyproject.toml +1 -1
  4. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/__init__.py +9 -3
  5. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/client.py +2 -0
  6. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/resources/collections.py +71 -1
  7. liyaengine-0.7.0/src/liyaengine/resources/documents.py +239 -0
  8. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/resources/domains.py +124 -27
  9. {liyaengine-0.5.0 → liyaengine-0.7.0}/tests/test_collections.py +86 -0
  10. liyaengine-0.7.0/tests/test_documents.py +143 -0
  11. {liyaengine-0.5.0 → liyaengine-0.7.0}/tests/test_domains.py +67 -4
  12. {liyaengine-0.5.0 → liyaengine-0.7.0}/.github/workflows/ci.yml +0 -0
  13. {liyaengine-0.5.0 → liyaengine-0.7.0}/.gitignore +0 -0
  14. {liyaengine-0.5.0 → liyaengine-0.7.0}/LICENSE +0 -0
  15. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/_http.py +0 -0
  16. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/errors.py +0 -0
  17. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/py.typed +0 -0
  18. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/resources/__init__.py +0 -0
  19. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/resources/agents.py +0 -0
  20. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/resources/evaluations.py +0 -0
  21. {liyaengine-0.5.0 → liyaengine-0.7.0}/src/liyaengine/resources/workflows.py +0 -0
  22. {liyaengine-0.5.0 → liyaengine-0.7.0}/tests/test_agents.py +0 -0
  23. {liyaengine-0.5.0 → liyaengine-0.7.0}/tests/test_evaluations.py +0 -0
  24. {liyaengine-0.5.0 → liyaengine-0.7.0}/tests/test_workflows.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: liyaengine
3
- Version: 0.5.0
3
+ Version: 0.7.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
@@ -73,14 +73,23 @@ domain = client.domains.create(domain_key="billing", display_name="Billing")
73
73
 
74
74
  intent = client.domains.intents.create(
75
75
  "billing", intent_key="refund-status", display_name="Refund Status",
76
+ description="Answer refund-status questions.",
76
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},
77
80
  )
78
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
+
79
88
  # Direct retrieval — no LLM call, useful for testing knowledge scoping.
80
89
  result = client.domains.query("billing", query="refund timeline")
81
90
  ```
82
91
 
83
- > Basic CRUD only today — richer config (agent mode, retrieval tuning, guardrail policy attachment, prompt versioning) is still dashboard-only. `domains.update()`/`domains.intents.update()` return `{"updated": 1}`, not the updated object — call `get()`/`list()` again for the fresh state. There's also no get-one-intent route; use `intents.list(domain_key)`.
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.
84
93
 
85
94
  ## Collections
86
95
 
@@ -90,9 +99,63 @@ client.collections.get(id)
90
99
  client.collections.create(slug=..., label=..., domain_keys=[...])
91
100
  client.collections.update(id, label=..., tags=[...], visibility=...)
92
101
  client.collections.delete(id)
102
+
103
+ # Reference documents into a collection — never copies them, never touches embeddings.
104
+ client.collections.documents.attach(collection_id, document_id)
105
+ client.collections.documents.list(collection_id) # returns CollectionDocumentSummary, a narrower shape than Document — see below
106
+ client.collections.documents.detach(collection_id, document_id)
107
+
108
+ # Scope a collection's knowledge to a domain.
109
+ client.collections.domains.attach(collection_id, "legal-ops")
110
+ client.collections.domains.detach(collection_id, "legal-ops")
111
+
112
+ # Live aggregation — no rollup table, always reflects current state.
113
+ stats = client.collections.analytics(collection_id)
114
+
115
+ # What references this collection — domains, intents, agents (indirect via
116
+ # domain). "workflows" is always None: no workflow-to-collection link exists.
117
+ refs = client.collections.connections(collection_id)
118
+ ```
119
+
120
+ Full field reference: [Collections API](/docs/api-reference/collections).
121
+
122
+ ## Documents
123
+
124
+ The tenant-wide knowledge pool collections reference (a document can belong to zero, one, or many collections — attaching never copies it or touches its embeddings).
125
+
126
+ ```python
127
+ client.documents.list()
128
+ doc = client.documents.get(id) # includes the full chunk_list
129
+ client.documents.delete(id)
130
+
131
+ # Synchronous — blocks until extraction/chunking/embedding finishes. If
132
+ # collection_ids names exactly one collection, that collection's own
133
+ # chunking/embedding defaults pre-fill the upload.
134
+ uploaded = client.documents.upload(
135
+ file_base64="...",
136
+ file_name="refund-policy.pdf",
137
+ category="policy",
138
+ collection_ids=[collection_id],
139
+ )
140
+
141
+ # Push a URL or inline content — upserts by a deterministic source_id.
142
+ client.documents.push(url="https://example.com/faq", title="FAQ")
143
+ ```
144
+
145
+ > Unlike `list()`/`get()`, `upload()`'s response has no `uploaded_by` — a real, pre-existing API asymmetry, not an SDK gap. Call `get(id)` afterward if you need it. Similarly, `collections.documents.list()` returns `CollectionDocumentSummary` (`id`/`name`/`chunks`/`size_kb`/`embedding_model`/`uploaded_at` only) rather than a full `Document` — no `category`, `uploaded_by`, or `collections` field; call `documents.get(id)` for the complete record.
146
+
147
+ For large files or a multi-page crawl, use the async job queue instead — it returns immediately and you poll for completion:
148
+
149
+ ```python
150
+ job = client.documents.jobs.create_url_job(url="https://example.com", depth=2)
151
+ # ...or: client.documents.jobs.create_file_job(file_base64=..., file_name=...)
152
+
153
+ status = client.documents.jobs.get(job["jobId"]) # pending | running | completed | failed | cancelled
154
+ client.documents.jobs.list(status="running")
155
+ client.documents.jobs.cancel(job["jobId"])
93
156
  ```
94
157
 
95
- Full field reference: [Collections API](/docs/api-reference/collections). Document ingestion beyond a quick file drop (`domains.upload_document()`) is still dashboard-only.
158
+ > Cancellation is cooperative (checked between page fetches / chunk embeds), not instant, and there is no crash-recovery sweep — if the process running a job restarts mid-run, the job is left "running" indefinitely rather than auto-retried. Poll `get(job_id)` for terminal status; don't assume `cancel()` stops it immediately.
96
159
 
97
160
  ## Agents
98
161
 
@@ -202,13 +265,13 @@ LiyaEngine(
202
265
 
203
266
  ## Roadmap
204
267
 
205
- - [x] Domains & Intents (basic CRUD, direct retrieval query, narrow document upload — richer config still dashboard-only)
268
+ - [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)
206
269
  - [x] Collections
207
270
  - [x] Agents (full CRUD, deploy, run, run/session history)
208
271
  - [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
209
272
  - [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
210
- - [ ] Full KBaaS (document list/get/delete, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics)
211
- - [ ] Domain/Intent config parity (agent/execution/retrieval/cache config, guardrail policy attachment, versioning)
273
+ - [x] Full KBaaS (document list/get/delete/upload/push, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics/connections)
274
+ - [ ] Flagged-chunk review
212
275
  - [ ] Run / Run (streaming)
213
276
  - [ ] Guardrail Policies
214
277
  - [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
@@ -44,14 +44,23 @@ domain = client.domains.create(domain_key="billing", display_name="Billing")
44
44
 
45
45
  intent = client.domains.intents.create(
46
46
  "billing", intent_key="refund-status", display_name="Refund Status",
47
+ description="Answer refund-status questions.",
47
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},
48
51
  )
49
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
+
50
59
  # Direct retrieval — no LLM call, useful for testing knowledge scoping.
51
60
  result = client.domains.query("billing", query="refund timeline")
52
61
  ```
53
62
 
54
- > Basic CRUD only today — richer config (agent mode, retrieval tuning, guardrail policy attachment, prompt versioning) is still dashboard-only. `domains.update()`/`domains.intents.update()` return `{"updated": 1}`, not the updated object — call `get()`/`list()` again for the fresh state. There's also no get-one-intent route; use `intents.list(domain_key)`.
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.
55
64
 
56
65
  ## Collections
57
66
 
@@ -61,9 +70,63 @@ client.collections.get(id)
61
70
  client.collections.create(slug=..., label=..., domain_keys=[...])
62
71
  client.collections.update(id, label=..., tags=[...], visibility=...)
63
72
  client.collections.delete(id)
73
+
74
+ # Reference documents into a collection — never copies them, never touches embeddings.
75
+ client.collections.documents.attach(collection_id, document_id)
76
+ client.collections.documents.list(collection_id) # returns CollectionDocumentSummary, a narrower shape than Document — see below
77
+ client.collections.documents.detach(collection_id, document_id)
78
+
79
+ # Scope a collection's knowledge to a domain.
80
+ client.collections.domains.attach(collection_id, "legal-ops")
81
+ client.collections.domains.detach(collection_id, "legal-ops")
82
+
83
+ # Live aggregation — no rollup table, always reflects current state.
84
+ stats = client.collections.analytics(collection_id)
85
+
86
+ # What references this collection — domains, intents, agents (indirect via
87
+ # domain). "workflows" is always None: no workflow-to-collection link exists.
88
+ refs = client.collections.connections(collection_id)
89
+ ```
90
+
91
+ Full field reference: [Collections API](/docs/api-reference/collections).
92
+
93
+ ## Documents
94
+
95
+ The tenant-wide knowledge pool collections reference (a document can belong to zero, one, or many collections — attaching never copies it or touches its embeddings).
96
+
97
+ ```python
98
+ client.documents.list()
99
+ doc = client.documents.get(id) # includes the full chunk_list
100
+ client.documents.delete(id)
101
+
102
+ # Synchronous — blocks until extraction/chunking/embedding finishes. If
103
+ # collection_ids names exactly one collection, that collection's own
104
+ # chunking/embedding defaults pre-fill the upload.
105
+ uploaded = client.documents.upload(
106
+ file_base64="...",
107
+ file_name="refund-policy.pdf",
108
+ category="policy",
109
+ collection_ids=[collection_id],
110
+ )
111
+
112
+ # Push a URL or inline content — upserts by a deterministic source_id.
113
+ client.documents.push(url="https://example.com/faq", title="FAQ")
114
+ ```
115
+
116
+ > Unlike `list()`/`get()`, `upload()`'s response has no `uploaded_by` — a real, pre-existing API asymmetry, not an SDK gap. Call `get(id)` afterward if you need it. Similarly, `collections.documents.list()` returns `CollectionDocumentSummary` (`id`/`name`/`chunks`/`size_kb`/`embedding_model`/`uploaded_at` only) rather than a full `Document` — no `category`, `uploaded_by`, or `collections` field; call `documents.get(id)` for the complete record.
117
+
118
+ For large files or a multi-page crawl, use the async job queue instead — it returns immediately and you poll for completion:
119
+
120
+ ```python
121
+ job = client.documents.jobs.create_url_job(url="https://example.com", depth=2)
122
+ # ...or: client.documents.jobs.create_file_job(file_base64=..., file_name=...)
123
+
124
+ status = client.documents.jobs.get(job["jobId"]) # pending | running | completed | failed | cancelled
125
+ client.documents.jobs.list(status="running")
126
+ client.documents.jobs.cancel(job["jobId"])
64
127
  ```
65
128
 
66
- Full field reference: [Collections API](/docs/api-reference/collections). Document ingestion beyond a quick file drop (`domains.upload_document()`) is still dashboard-only.
129
+ > Cancellation is cooperative (checked between page fetches / chunk embeds), not instant, and there is no crash-recovery sweep — if the process running a job restarts mid-run, the job is left "running" indefinitely rather than auto-retried. Poll `get(job_id)` for terminal status; don't assume `cancel()` stops it immediately.
67
130
 
68
131
  ## Agents
69
132
 
@@ -173,13 +236,13 @@ LiyaEngine(
173
236
 
174
237
  ## Roadmap
175
238
 
176
- - [x] Domains & Intents (basic CRUD, direct retrieval query, narrow document upload — richer config still dashboard-only)
239
+ - [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)
177
240
  - [x] Collections
178
241
  - [x] Agents (full CRUD, deploy, run, run/session history)
179
242
  - [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
180
243
  - [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
181
- - [ ] Full KBaaS (document list/get/delete, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics)
182
- - [ ] Domain/Intent config parity (agent/execution/retrieval/cache config, guardrail policy attachment, versioning)
244
+ - [x] Full KBaaS (document list/get/delete/upload/push, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics/connections)
245
+ - [ ] Flagged-chunk review
183
246
  - [ ] Run / Run (streaming)
184
247
  - [ ] Guardrail Policies
185
248
  - [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "liyaengine"
7
- version = "0.5.0"
7
+ version = "0.7.0"
8
8
  description = "Official Python client for the Liya Engine public API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,16 +1,18 @@
1
1
  from .client import LiyaEngine
2
2
  from .errors import LiyaEngineAPIError, LiyaEngineNetworkError
3
3
  from .resources.agents import Agent
4
- from .resources.collections import Collection
4
+ from .resources.collections import Collection, CollectionDocumentSummary
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
7
+ from .resources.domains import Domain, Intent, DomainSource, IntentVersionSummary
8
+ from .resources.documents import Document, DocumentChunk, IngestionJob
8
9
 
9
10
  __all__ = [
10
11
  "LiyaEngine",
11
12
  "LiyaEngineAPIError",
12
13
  "LiyaEngineNetworkError",
13
14
  "Collection",
15
+ "CollectionDocumentSummary",
14
16
  "Agent",
15
17
  "Workflow",
16
18
  "EvalDataset",
@@ -21,6 +23,10 @@ __all__ = [
21
23
  "Domain",
22
24
  "Intent",
23
25
  "DomainSource",
26
+ "IntentVersionSummary",
27
+ "Document",
28
+ "DocumentChunk",
29
+ "IngestionJob",
24
30
  ]
25
31
 
26
- __version__ = "0.5.0"
32
+ __version__ = "0.7.0"
@@ -10,6 +10,7 @@ from .resources.collections import CollectionsResource
10
10
  from .resources.workflows import WorkflowsResource
11
11
  from .resources.evaluations import EvaluationsResource
12
12
  from .resources.domains import DomainsResource, IntentsResource
13
+ from .resources.documents import DocumentsResource
13
14
 
14
15
  _DEFAULT_BASE_URL = "https://api.liyaengine.ai"
15
16
 
@@ -48,6 +49,7 @@ class LiyaEngine:
48
49
  self.evaluations = EvaluationsResource(self._http)
49
50
  self.domains = DomainsResource(self._http)
50
51
  self.intents = IntentsResource(self._http)
52
+ self.documents = DocumentsResource(self._http)
51
53
 
52
54
  def close(self) -> None:
53
55
  self._http.close()
@@ -1,7 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from dataclasses import dataclass
4
- from typing import Any, Dict, List, Optional
4
+ from typing import Any, Dict, List, Optional, cast
5
+ from urllib.parse import quote
5
6
 
6
7
  from .._http import HttpClient
7
8
 
@@ -43,6 +44,62 @@ class Collection:
43
44
  )
44
45
 
45
46
 
47
+ class CollectionDomainsResource:
48
+ def __init__(self, http: HttpClient) -> None:
49
+ self._http = http
50
+
51
+ def attach(self, collection_id: str, domain_key: str) -> None:
52
+ self._http.post(f"/v1/collections/{quote(collection_id)}/domains/{quote(domain_key)}")
53
+
54
+ def detach(self, collection_id: str, domain_key: str) -> None:
55
+ """Detach only — never deletes the collection, even if this was its last attachment. Idempotent."""
56
+ self._http.delete(f"/v1/collections/{quote(collection_id)}/domains/{quote(domain_key)}")
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class CollectionDocumentSummary:
61
+ """The shape GET /v1/collections/{id}/documents actually returns — a
62
+ real, pre-existing backend asymmetry, not the full Document type. No
63
+ category, uploaded_by, or collections field; confirmed against
64
+ collectionAttachmentService.ts's listCollectionDocuments().
65
+ """
66
+
67
+ id: str
68
+ name: str
69
+ chunks: int
70
+ size_kb: int
71
+ embedding_model: Optional[str]
72
+ uploaded_at: str
73
+
74
+ @classmethod
75
+ def _from_dict(cls, data: Dict[str, Any]) -> "CollectionDocumentSummary":
76
+ return cls(
77
+ id=data["id"],
78
+ name=data["name"],
79
+ chunks=data["chunks"],
80
+ size_kb=data["sizeKb"],
81
+ embedding_model=data.get("embeddingModel"),
82
+ uploaded_at=data["uploadedAt"],
83
+ )
84
+
85
+
86
+ class CollectionDocumentsResource:
87
+ def __init__(self, http: HttpClient) -> None:
88
+ self._http = http
89
+
90
+ def list(self, collection_id: str) -> List[CollectionDocumentSummary]:
91
+ data = self._http.get(f"/v1/collections/{quote(collection_id)}/documents")
92
+ return [CollectionDocumentSummary._from_dict(d) for d in data["documents"]]
93
+
94
+ def attach(self, collection_id: str, document_id: str) -> None:
95
+ """Reference only — a collection never owns/copies a document; embeddings are never touched."""
96
+ self._http.post(f"/v1/collections/{quote(collection_id)}/documents/{quote(document_id)}")
97
+
98
+ def detach(self, collection_id: str, document_id: str) -> None:
99
+ """Detach only; the document itself and its embeddings are untouched. Idempotent."""
100
+ self._http.delete(f"/v1/collections/{quote(collection_id)}/documents/{quote(document_id)}")
101
+
102
+
46
103
  class CollectionsResource:
47
104
  """Tenant-wide knowledge collections — organize documents, scope
48
105
  retrieval, attach to one or many domains. Mirrors GET/POST
@@ -52,6 +109,8 @@ class CollectionsResource:
52
109
 
53
110
  def __init__(self, http: HttpClient) -> None:
54
111
  self._http = http
112
+ self.domains = CollectionDomainsResource(http)
113
+ self.documents = CollectionDocumentsResource(http)
55
114
 
56
115
  def list(self) -> List[Collection]:
57
116
  data = self._http.get("/v1/collections")
@@ -127,3 +186,14 @@ class CollectionsResource:
127
186
 
128
187
  def delete(self, id: str) -> None:
129
188
  self._http.delete(f"/v1/collections/{id}")
189
+
190
+ def analytics(self, id: str) -> Dict[str, Any]:
191
+ """On-the-fly aggregation — no dedicated rollup table, so this reflects live state exactly."""
192
+ return cast(Dict[str, Any], self._http.get(f"/v1/collections/{quote(id)}/analytics"))
193
+
194
+ def connections(self, id: str) -> Dict[str, Any]:
195
+ """What references this collection — domains, intents, agents (indirect
196
+ via domain), and workflows (always None — no workflow-to-collection
197
+ link, direct or indirect, exists in the schema; a real answer, not a stub).
198
+ """
199
+ return cast(Dict[str, Any], self._http.get(f"/v1/collections/{quote(id)}/connections"))
@@ -0,0 +1,239 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List, Optional, cast
5
+ from urllib.parse import quote, urlencode
6
+
7
+ from .._http import HttpClient
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class DocumentChunk:
12
+ id: str
13
+ index: int
14
+ text: str
15
+ metadata: Optional[Dict[str, Any]]
16
+
17
+ @classmethod
18
+ def _from_dict(cls, data: Dict[str, Any]) -> "DocumentChunk":
19
+ return cls(
20
+ id=data["id"],
21
+ index=data["index"],
22
+ text=data["text"],
23
+ metadata=data.get("metadata"),
24
+ )
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Document:
29
+ """Tenant-wide knowledge document — the pool collections REFERENCE
30
+ rather than own (a document can be attached to zero, one, or many
31
+ collections). Mirrors /v1/documents (see openapi.yaml).
32
+ """
33
+
34
+ id: str
35
+ name: str
36
+ category: str
37
+ chunks: int
38
+ size_kb: int
39
+ embedding_model: Optional[str]
40
+ # None on upload()'s response — a real, pre-existing API asymmetry, not
41
+ # an SDK gap. list()/get() always include it. Call get(id) afterward if
42
+ # you need it right after an upload.
43
+ uploaded_by: Optional[str]
44
+ uploaded_at: str
45
+ collections: List[Dict[str, Any]]
46
+ # Present only on get() — the single-document fetch.
47
+ chunk_list: Optional[List[DocumentChunk]] = None
48
+
49
+ @classmethod
50
+ def _from_dict(cls, data: Dict[str, Any]) -> "Document":
51
+ chunk_list = data.get("chunkList")
52
+ return cls(
53
+ id=data["id"],
54
+ name=data["name"],
55
+ category=data["category"],
56
+ chunks=data["chunks"],
57
+ size_kb=data["sizeKb"],
58
+ embedding_model=data.get("embeddingModel"),
59
+ uploaded_by=data.get("uploadedBy"),
60
+ uploaded_at=data["uploadedAt"],
61
+ collections=data.get("collections", []),
62
+ chunk_list=[DocumentChunk._from_dict(c) for c in chunk_list] if chunk_list is not None else None,
63
+ )
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class IngestionJob:
68
+ id: str
69
+ source_type: str
70
+ name: str
71
+ status: str
72
+ stage: Optional[str]
73
+ progress: int
74
+ result: Optional[Dict[str, Any]]
75
+ error_message: Optional[str]
76
+ created_at: str
77
+ started_at: Optional[str]
78
+ completed_at: Optional[str]
79
+
80
+ @classmethod
81
+ def _from_dict(cls, data: Dict[str, Any]) -> "IngestionJob":
82
+ return cls(
83
+ id=data["id"],
84
+ source_type=data["source_type"],
85
+ name=data["name"],
86
+ status=data["status"],
87
+ stage=data.get("stage"),
88
+ progress=data["progress"],
89
+ result=data.get("result"),
90
+ error_message=data.get("error_message"),
91
+ created_at=data["created_at"],
92
+ started_at=data.get("started_at"),
93
+ completed_at=data.get("completed_at"),
94
+ )
95
+
96
+
97
+ def _query(**params: Any) -> str:
98
+ pairs = {k: v for k, v in params.items() if v is not None}
99
+ return f"?{urlencode(pairs)}" if pairs else ""
100
+
101
+
102
+ class IngestionJobsResource:
103
+ """Async ingestion jobs (URL crawl, file upload) — a non-blocking
104
+ alternative to documents.upload()/push() for large files or deep
105
+ crawls. Poll get() for status; a completed job's "entry" is the
106
+ resulting document's summary.
107
+
108
+ Cancellation is cooperative (checked between page fetches / chunk
109
+ embeds), not instant — and there is no crash-recovery sweep: if the
110
+ process running a job restarts mid-run, the job is left "running"
111
+ indefinitely rather than automatically retried or failed. A known
112
+ limitation, not silently promised away.
113
+ """
114
+
115
+ def __init__(self, http: HttpClient) -> None:
116
+ self._http = http
117
+
118
+ def create_url_job(
119
+ self,
120
+ *,
121
+ url: str,
122
+ depth: Optional[int] = None,
123
+ category: Optional[str] = None,
124
+ collection_ids: Optional[List[str]] = None,
125
+ ) -> Dict[str, Any]:
126
+ body: Dict[str, Any] = {"url": url}
127
+ if depth is not None:
128
+ body["depth"] = depth
129
+ if category is not None:
130
+ body["category"] = category
131
+ if collection_ids is not None:
132
+ body["collectionIds"] = collection_ids
133
+ return cast(Dict[str, Any], self._http.post("/v1/documents/jobs/url", body))
134
+
135
+ def create_file_job(
136
+ self,
137
+ *,
138
+ file_base64: str,
139
+ file_name: str,
140
+ category: Optional[str] = None,
141
+ collection_ids: Optional[List[str]] = None,
142
+ ) -> Dict[str, Any]:
143
+ body: Dict[str, Any] = {"fileBase64": file_base64, "fileName": file_name}
144
+ if category is not None:
145
+ body["category"] = category
146
+ if collection_ids is not None:
147
+ body["collectionIds"] = collection_ids
148
+ return cast(Dict[str, Any], self._http.post("/v1/documents/jobs/file", body))
149
+
150
+ def list(
151
+ self, *, page: Optional[int] = None, page_size: Optional[int] = None, status: Optional[str] = None
152
+ ) -> Dict[str, Any]:
153
+ qs = _query(page=page, pageSize=page_size, status=status)
154
+ data = cast(Dict[str, Any], self._http.get(f"/v1/documents/jobs{qs}"))
155
+ return {
156
+ "jobs": [IngestionJob._from_dict(j) for j in data["jobs"]],
157
+ "pagination": data["pagination"],
158
+ }
159
+
160
+ def get(self, job_id: str) -> Dict[str, Any]:
161
+ return cast(Dict[str, Any], self._http.get(f"/v1/documents/jobs/{quote(job_id)}"))
162
+
163
+ def cancel(self, job_id: str) -> Dict[str, Any]:
164
+ """Cooperative — the worker notices and stops at its next checkpoint, not instantly."""
165
+ data = cast(Dict[str, Any], self._http.post(f"/v1/documents/jobs/{quote(job_id)}/cancel"))
166
+ return {"job": IngestionJob._from_dict(data["job"])}
167
+
168
+
169
+ class DocumentsResource:
170
+ def __init__(self, http: HttpClient) -> None:
171
+ self._http = http
172
+ self.jobs = IngestionJobsResource(http)
173
+
174
+ def list(self) -> List[Document]:
175
+ data = self._http.get("/v1/documents")
176
+ return [Document._from_dict(d) for d in data["documents"]]
177
+
178
+ def get(self, id: str) -> Document:
179
+ """Includes the document's full chunk_list."""
180
+ data = self._http.get(f"/v1/documents/{quote(id)}")
181
+ return Document._from_dict(data)
182
+
183
+ def delete(self, id: str) -> None:
184
+ """Removes the document and its embeddings. Cascades collection attachments via FK."""
185
+ self._http.delete(f"/v1/documents/{quote(id)}")
186
+
187
+ def upload(
188
+ self,
189
+ *,
190
+ file_base64: str,
191
+ file_name: str,
192
+ category: Optional[str] = None,
193
+ collection_ids: Optional[List[str]] = None,
194
+ ) -> Document:
195
+ """Synchronous — the request blocks until extraction/chunking/embedding
196
+ completes. For large files, prefer jobs.create_file_job() instead. If
197
+ collection_ids names exactly one collection, that collection's own
198
+ chunking/embedding defaults pre-fill this upload.
199
+
200
+ Unlike list()/get(), the response here has no uploaded_by — a real,
201
+ pre-existing asymmetry in the underlying API, not an SDK gap. Call
202
+ get(id) afterward if you need it.
203
+ """
204
+ body: Dict[str, Any] = {"fileBase64": file_base64, "fileName": file_name}
205
+ if category is not None:
206
+ body["category"] = category
207
+ if collection_ids is not None:
208
+ body["collectionIds"] = collection_ids
209
+ data = self._http.post("/v1/documents", body)
210
+ return Document._from_dict(data)
211
+
212
+ def push(
213
+ self,
214
+ *,
215
+ url: Optional[str] = None,
216
+ content: Optional[str] = None,
217
+ title: Optional[str] = None,
218
+ source_id: Optional[str] = None,
219
+ category: Optional[str] = None,
220
+ collection_ids: Optional[List[str]] = None,
221
+ ) -> Dict[str, Any]:
222
+ """Synchronous — pushes a URL or inline content, upserting by a
223
+ deterministic source_id. Prefer jobs.create_url_job() for a deep
224
+ crawl (this only fetches the one URL given, no link-following).
225
+ """
226
+ body: Dict[str, Any] = {}
227
+ if url is not None:
228
+ body["url"] = url
229
+ if content is not None:
230
+ body["content"] = content
231
+ if title is not None:
232
+ body["title"] = title
233
+ if source_id is not None:
234
+ body["sourceId"] = source_id
235
+ if category is not None:
236
+ body["category"] = category
237
+ if collection_ids is not None:
238
+ body["collectionIds"] = collection_ids
239
+ return cast(Dict[str, Any], self._http.post("/v1/documents/push", body))
@@ -1,17 +1,34 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from dataclasses import dataclass
4
- from typing import Any, Dict, List, Optional, cast
4
+ from typing import Any, Dict, List, Literal, Optional, TypedDict, Union, cast
5
5
  from urllib.parse import quote
6
6
 
7
7
  from .._http import HttpClient
8
8
 
9
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
+
10
28
  @dataclass(frozen=True)
11
29
  class Intent:
12
- """Real columns also include agent_config/execution_config/retrieval_config/
13
- cache_config/prompt_binding/guardrail_policy_id — dashboard-only to write today,
14
- not on create()/update()'s keyword args below."""
30
+ """Real column also includes guardrail_policy_id — dashboard-only to write
31
+ today, not on create()/update()'s keyword args below."""
15
32
 
16
33
  id: str
17
34
  tenant_id: str
@@ -20,9 +37,14 @@ class Intent:
20
37
  display_name: str
21
38
  description: Optional[str]
22
39
  prompt_template: str
40
+ prompt_binding: Optional[PromptBinding]
23
41
  output_schema: Optional[Dict[str, Any]]
24
42
  input_schema: Optional[Dict[str, Any]]
25
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]]
26
48
  is_active: bool
27
49
  sort_order: int
28
50
  created_at: str
@@ -33,17 +55,40 @@ class Intent:
33
55
  return cls(
34
56
  id=data["id"], tenant_id=data["tenant_id"], domain_key=data["domain_key"], intent_key=data["intent_key"],
35
57
  display_name=data["display_name"], description=data.get("description"),
36
- prompt_template=data["prompt_template"], output_schema=data.get("output_schema"),
37
- input_schema=data.get("input_schema"), guardrails_config=data.get("guardrails_config"),
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"),
38
63
  is_active=data["is_active"], sort_order=data["sort_order"],
39
64
  created_at=data["created_at"], updated_at=data["updated_at"],
40
65
  )
41
66
 
42
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
+
43
88
  @dataclass(frozen=True)
44
89
  class Domain:
45
- """Real columns also include status/guardrail_policy_id/prompt_binding/tools_config/
46
- default_top_k/default_similarity_threshold — dashboard-only to write today."""
90
+ """Real columns also include guardrail_policy_id/tools_config/default_top_k/
91
+ default_similarity_threshold — dashboard-only to write today."""
47
92
 
48
93
  id: str
49
94
  tenant_id: str
@@ -53,8 +98,10 @@ class Domain:
53
98
  icon: str
54
99
  color: str
55
100
  system_prompt: Optional[str]
101
+ prompt_binding: Optional[PromptBinding]
56
102
  context_enrichment_webhook_url: Optional[str]
57
103
  retrieval_scope: Optional[str]
104
+ status: Literal["draft", "active", "archived"]
58
105
  is_active: bool
59
106
  created_at: str
60
107
  updated_at: str
@@ -69,8 +116,10 @@ class Domain:
69
116
  id=data["id"], tenant_id=data["tenant_id"], domain_key=data["domain_key"],
70
117
  display_name=data["display_name"], description=data.get("description"),
71
118
  icon=data["icon"], color=data["color"], system_prompt=data.get("system_prompt"),
119
+ prompt_binding=data.get("prompt_binding"),
72
120
  context_enrichment_webhook_url=data.get("context_enrichment_webhook_url"),
73
- retrieval_scope=data.get("retrieval_scope"), is_active=data["is_active"],
121
+ retrieval_scope=data.get("retrieval_scope"), status=data.get("status", "active"),
122
+ is_active=data["is_active"],
74
123
  created_at=data["created_at"], updated_at=data["updated_at"],
75
124
  intents=[Intent._from_dict(i) for i in intents] if intents is not None else None,
76
125
  source_types=data.get("source_types"),
@@ -125,14 +174,39 @@ class IntentCatalogEntry:
125
174
  )
126
175
 
127
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
+
128
196
  class DomainIntentsResource:
129
197
  def __init__(self, http: HttpClient) -> None:
130
198
  self._http = http
199
+ self.versions = DomainIntentVersionsResource(http)
131
200
 
132
201
  def list(self, domain_key: str) -> List[Intent]:
133
202
  data = self._http.get(f"/v1/domains/{quote(domain_key)}/intents")
134
203
  return [Intent._from_dict(i) for i in data["intents"]]
135
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
+
136
210
  # /v1/domains/:key/intents predates the snake_case wire convention every
137
211
  # other /v1 resource in this SDK uses, and has real external consumers
138
212
  # (A3LearningLabs, Qistara, StoryHire per the API's own doc comment) — its
@@ -140,14 +214,21 @@ class DomainIntentsResource:
140
214
  # shape stays consistent with every other resource; changing the wire
141
215
  # format itself would break those existing integrations.
142
216
  def create(
143
- self, domain_key: str, *, intent_key: str, display_name: str, prompt_template: str,
144
- description: Optional[str] = None, output_schema: Optional[Dict[str, Any]] = None,
145
- input_schema: Optional[Dict[str, Any]] = None, guardrails_config: Optional[Dict[str, Any]] = None,
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,
146
223
  ) -> Intent:
147
- body: Dict[str, Any] = {"intentKey": intent_key, "displayName": display_name, "promptTemplate": prompt_template}
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}
148
227
  optional = {
149
- "description": description, "outputSchema": output_schema,
150
- "inputSchema": input_schema, "guardrailsConfig": guardrails_config,
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,
151
232
  }
152
233
  body.update({k: v for k, v in optional.items() if v is not None})
153
234
  data = self._http.post(f"/v1/domains/{quote(domain_key)}/intents", body)
@@ -156,16 +237,24 @@ class DomainIntentsResource:
156
237
  def update(
157
238
  self, domain_key: str, intent_key: str, *, display_name: Optional[str] = None,
158
239
  description: Optional[str] = None, prompt_template: Optional[str] = None,
240
+ prompt_binding: Optional[PromptBinding] = None,
159
241
  output_schema: Optional[Dict[str, Any]] = None, input_schema: Optional[Dict[str, Any]] = None,
160
- guardrails_config: 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,
161
246
  ) -> Dict[str, int]:
162
- """Returns {"updated": 1}, not the updated Intent — this door has no
163
- get-single-intent route to re-fetch from either. Call list() again if
164
- you need the fresh object."""
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."""
165
250
  body: Dict[str, Any] = {}
166
251
  optional = {
167
252
  "displayName": display_name, "description": description, "promptTemplate": prompt_template,
168
- "outputSchema": output_schema, "inputSchema": input_schema, "guardrailsConfig": guardrails_config,
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,
169
258
  }
170
259
  body.update({k: v for k, v in optional.items() if v is not None})
171
260
  return cast(Dict[str, int], self._http.patch(f"/v1/domains/{quote(domain_key)}/intents/{quote(intent_key)}", body))
@@ -197,9 +286,10 @@ class DomainSourcesResource:
197
286
  class DomainsResource:
198
287
  """Custom domains — the top-level container tenants configure first (system
199
288
  prompt, retrieval scope, then intents and knowledge underneath). Mirrors the
200
- full /v1/domains surface. Basic CRUD only today — agent/execution/retrieval/
201
- cache config, guardrail policy attachment, and versioning are still
202
- dashboard-only (no /v1 route yet)."""
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)."""
203
293
 
204
294
  def __init__(self, http: HttpClient) -> None:
205
295
  self._http = http
@@ -223,12 +313,15 @@ class DomainsResource:
223
313
  def create(
224
314
  self, *, domain_key: str, display_name: str, description: Optional[str] = None,
225
315
  icon: Optional[str] = None, color: Optional[str] = None, system_prompt: Optional[str] = None,
316
+ prompt_binding: Optional[PromptBinding] = None,
226
317
  context_enrichment_webhook_url: Optional[str] = None,
318
+ status: Optional[Literal["draft", "active", "archived"]] = None,
227
319
  ) -> Domain:
228
320
  body: Dict[str, Any] = {"domainKey": domain_key, "displayName": display_name}
229
321
  optional = {
230
322
  "description": description, "icon": icon, "color": color, "systemPrompt": system_prompt,
231
- "contextEnrichmentWebhookUrl": context_enrichment_webhook_url,
323
+ "promptBinding": prompt_binding,
324
+ "contextEnrichmentWebhookUrl": context_enrichment_webhook_url, "status": status,
232
325
  }
233
326
  body.update({k: v for k, v in optional.items() if v is not None})
234
327
  data = self._http.post("/v1/domains", body)
@@ -237,14 +330,18 @@ class DomainsResource:
237
330
  def update(
238
331
  self, domain_key: str, *, display_name: Optional[str] = None, description: Optional[str] = None,
239
332
  icon: Optional[str] = None, color: Optional[str] = None, system_prompt: Optional[str] = None,
333
+ prompt_binding: Optional[PromptBinding] = None,
240
334
  retrieval_scope: Optional[str] = None, context_enrichment_webhook_url: Optional[str] = None,
335
+ status: Optional[Literal["draft", "active", "archived"]] = None,
241
336
  ) -> Dict[str, int]:
242
- """Returns {"updated": 1}, not the updated Domain — call get() again for the fresh object."""
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."""
243
340
  body: Dict[str, Any] = {}
244
341
  optional = {
245
342
  "displayName": display_name, "description": description, "icon": icon, "color": color,
246
- "systemPrompt": system_prompt, "retrievalScope": retrieval_scope,
247
- "contextEnrichmentWebhookUrl": context_enrichment_webhook_url,
343
+ "systemPrompt": system_prompt, "promptBinding": prompt_binding, "retrievalScope": retrieval_scope,
344
+ "contextEnrichmentWebhookUrl": context_enrichment_webhook_url, "status": status,
248
345
  }
249
346
  body.update({k: v for k, v in optional.items() if v is not None})
250
347
  return cast(Dict[str, int], self._http.patch(f"/v1/domains/{quote(domain_key)}", body))
@@ -112,3 +112,89 @@ def test_delete_does_not_raise(client):
112
112
  return_value=httpx.Response(200, json={"success": True})
113
113
  )
114
114
  client.collections.delete("col_123") # no exception = pass
115
+
116
+
117
+ @respx.mock
118
+ def test_domains_attach_and_detach(client):
119
+ respx.post(f"{BASE_URL}/v1/collections/col_123/domains/legal-ops").mock(
120
+ return_value=httpx.Response(200, json={"success": True})
121
+ )
122
+ respx.delete(f"{BASE_URL}/v1/collections/col_123/domains/legal-ops").mock(
123
+ return_value=httpx.Response(200, json={"success": True})
124
+ )
125
+ client.collections.domains.attach("col_123", "legal-ops")
126
+ client.collections.domains.detach("col_123", "legal-ops")
127
+
128
+
129
+ @respx.mock
130
+ def test_documents_list_attach_detach(client):
131
+ # Real backend shape — no category/uploadedBy/collections, see
132
+ # CollectionDocumentSummary's docstring.
133
+ fixture_document_summary = {
134
+ "id": "doc_123",
135
+ "name": "faq.txt",
136
+ "chunks": 3,
137
+ "sizeKb": 2,
138
+ "embeddingModel": "text-embedding-3-small",
139
+ "uploadedAt": "2026-01-01T00:00:00.000Z",
140
+ }
141
+ respx.get(f"{BASE_URL}/v1/collections/col_123/documents").mock(
142
+ return_value=httpx.Response(200, json={"success": True, "data": {"documents": [fixture_document_summary], "total": 1}})
143
+ )
144
+ respx.post(f"{BASE_URL}/v1/collections/col_123/documents/doc_123").mock(
145
+ return_value=httpx.Response(200, json={"success": True})
146
+ )
147
+ respx.delete(f"{BASE_URL}/v1/collections/col_123/documents/doc_123").mock(
148
+ return_value=httpx.Response(200, json={"success": True})
149
+ )
150
+ documents = client.collections.documents.list("col_123")
151
+ assert len(documents) == 1
152
+ assert documents[0].id == "doc_123"
153
+ client.collections.documents.attach("col_123", "doc_123")
154
+ client.collections.documents.detach("col_123", "doc_123")
155
+
156
+
157
+ @respx.mock
158
+ def test_analytics_returns_live_aggregated_stats(client):
159
+ respx.get(f"{BASE_URL}/v1/collections/col_123/analytics").mock(
160
+ return_value=httpx.Response(
161
+ 200,
162
+ json={
163
+ "success": True,
164
+ "data": {
165
+ "sources": 4,
166
+ "documents": 4,
167
+ "chunks": 42,
168
+ "storage_kb": 128,
169
+ "embedding_model": "text-embedding-3-small",
170
+ "indexed": True,
171
+ "last_synced_at": "2026-01-01T00:00:00.000Z",
172
+ },
173
+ },
174
+ )
175
+ )
176
+ analytics = client.collections.analytics("col_123")
177
+ assert analytics["sources"] == 4
178
+ assert analytics["indexed"] is True
179
+
180
+
181
+ @respx.mock
182
+ def test_connections_returns_domains_intents_agents_and_null_workflows(client):
183
+ respx.get(f"{BASE_URL}/v1/collections/col_123/connections").mock(
184
+ return_value=httpx.Response(
185
+ 200,
186
+ json={
187
+ "success": True,
188
+ "data": {
189
+ "domains": [{"domain_key": "legal-ops", "display_name": "Legal Ops"}],
190
+ "intents": [{"intent_key": "review-contract", "domain_key": "legal-ops", "display_name": "Review Contract"}],
191
+ "agents": [{"id": "agent_1", "name": "Contract Bot", "via": "legal-ops"}],
192
+ "workflows": None,
193
+ },
194
+ },
195
+ )
196
+ )
197
+ connections = client.collections.connections("col_123")
198
+ assert connections["domains"] == [{"domain_key": "legal-ops", "display_name": "Legal Ops"}]
199
+ assert len(connections["agents"]) == 1
200
+ assert connections["workflows"] is None
@@ -0,0 +1,143 @@
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_DOCUMENT = {
10
+ "id": "doc_123",
11
+ "name": "faq.txt",
12
+ "category": "faq",
13
+ "chunks": 3,
14
+ "sizeKb": 2,
15
+ "embeddingModel": "text-embedding-3-small",
16
+ "uploadedBy": "user_1",
17
+ "uploadedAt": "2026-01-01T00:00:00.000Z",
18
+ "collections": [{"id": "col_123", "slug": "contracts", "label": "Contracts", "color": "#6366f1"}],
19
+ }
20
+
21
+ FIXTURE_DOCUMENT_DETAIL = {
22
+ **FIXTURE_DOCUMENT,
23
+ "chunkList": [{"id": "chk_1", "index": 0, "text": "Refunds take 5-7 days.", "metadata": None}],
24
+ }
25
+
26
+ FIXTURE_JOB = {
27
+ "id": "job_1",
28
+ "source_type": "_unfiled",
29
+ "name": "faq.txt",
30
+ "status": "pending",
31
+ "stage": None,
32
+ "progress": 0,
33
+ "result": None,
34
+ "error_message": None,
35
+ "created_at": "2026-01-01T00:00:00.000Z",
36
+ "started_at": None,
37
+ "completed_at": None,
38
+ }
39
+
40
+
41
+ @pytest.fixture
42
+ def client():
43
+ with LiyaEngine(api_key="liya_test_key", base_url=BASE_URL) as c:
44
+ yield c
45
+
46
+
47
+ @respx.mock
48
+ def test_list_returns_documents(client):
49
+ respx.get(f"{BASE_URL}/v1/documents").mock(
50
+ return_value=httpx.Response(200, json={"success": True, "data": {"documents": [FIXTURE_DOCUMENT], "total": 1}})
51
+ )
52
+ documents = client.documents.list()
53
+ assert len(documents) == 1
54
+ assert documents[0].id == "doc_123"
55
+
56
+
57
+ @respx.mock
58
+ def test_get_includes_chunk_list(client):
59
+ respx.get(f"{BASE_URL}/v1/documents/doc_123").mock(
60
+ return_value=httpx.Response(200, json={"success": True, "data": FIXTURE_DOCUMENT_DETAIL})
61
+ )
62
+ detail = client.documents.get("doc_123")
63
+ assert detail.chunk_list is not None
64
+ assert len(detail.chunk_list) == 1
65
+
66
+
67
+ @respx.mock
68
+ def test_delete_does_not_raise(client):
69
+ respx.delete(f"{BASE_URL}/v1/documents/doc_123").mock(return_value=httpx.Response(200, json={"success": True}))
70
+ client.documents.delete("doc_123") # no exception = pass
71
+
72
+
73
+ @respx.mock
74
+ def test_upload_response_has_no_uploaded_by(client):
75
+ body = {k: v for k, v in FIXTURE_DOCUMENT.items() if k != "uploadedBy"}
76
+ respx.post(f"{BASE_URL}/v1/documents").mock(
77
+ return_value=httpx.Response(201, json={"success": True, "data": body})
78
+ )
79
+ uploaded = client.documents.upload(file_base64="ZmFrZQ==", file_name="faq.txt", category="faq")
80
+ assert uploaded.id == "doc_123"
81
+ assert uploaded.uploaded_by is None
82
+
83
+
84
+ @respx.mock
85
+ def test_push_returns_upserted_source_id(client):
86
+ respx.post(f"{BASE_URL}/v1/documents/push").mock(
87
+ return_value=httpx.Response(200, json={"success": True, "data": {"source_id": "src_1", "chunks": 3, "title": "FAQ"}})
88
+ )
89
+ pushed = client.documents.push(url="https://example.com/faq", title="FAQ")
90
+ assert pushed == {"source_id": "src_1", "chunks": 3, "title": "FAQ"}
91
+
92
+
93
+ @respx.mock
94
+ def test_jobs_create_url_job(client):
95
+ respx.post(f"{BASE_URL}/v1/documents/jobs/url").mock(
96
+ return_value=httpx.Response(202, json={"success": True, "data": {"jobId": "job_1", "status": "pending"}})
97
+ )
98
+ job = client.documents.jobs.create_url_job(url="https://example.com", depth=1)
99
+ assert job == {"jobId": "job_1", "status": "pending"}
100
+
101
+
102
+ @respx.mock
103
+ def test_jobs_create_file_job(client):
104
+ respx.post(f"{BASE_URL}/v1/documents/jobs/file").mock(
105
+ return_value=httpx.Response(202, json={"success": True, "data": {"jobId": "job_2", "status": "pending"}})
106
+ )
107
+ job = client.documents.jobs.create_file_job(file_base64="ZmFrZQ==", file_name="notes.txt")
108
+ assert job == {"jobId": "job_2", "status": "pending"}
109
+
110
+
111
+ @respx.mock
112
+ def test_jobs_list_with_query_params(client):
113
+ route = respx.get(f"{BASE_URL}/v1/documents/jobs").mock(
114
+ return_value=httpx.Response(
115
+ 200,
116
+ json={
117
+ "success": True,
118
+ "data": {"jobs": [FIXTURE_JOB], "pagination": {"page": 1, "pageSize": 20, "total": 1, "totalPages": 1}},
119
+ },
120
+ )
121
+ )
122
+ page = client.documents.jobs.list(status="pending")
123
+ assert route.calls.last.request.url.params["status"] == "pending"
124
+ assert page["jobs"][0].id == "job_1"
125
+ assert page["pagination"]["total"] == 1
126
+
127
+
128
+ @respx.mock
129
+ def test_jobs_get_status(client):
130
+ respx.get(f"{BASE_URL}/v1/documents/jobs/job_1").mock(
131
+ return_value=httpx.Response(200, json={"success": True, "data": {"jobId": "job_1", "status": "pending", "stage": None, "progress": 0}})
132
+ )
133
+ status = client.documents.jobs.get("job_1")
134
+ assert status["status"] == "pending"
135
+
136
+
137
+ @respx.mock
138
+ def test_jobs_cancel(client):
139
+ respx.post(f"{BASE_URL}/v1/documents/jobs/job_1/cancel").mock(
140
+ return_value=httpx.Response(200, json={"success": True, "data": {"job": {**FIXTURE_JOB, "status": "cancelled"}}})
141
+ )
142
+ result = client.documents.jobs.cancel("job_1")
143
+ assert result["job"].status == "cancelled"
@@ -15,8 +15,10 @@ FIXTURE_DOMAIN = {
15
15
  "icon": "◆",
16
16
  "color": "#6366f1",
17
17
  "system_prompt": None,
18
+ "prompt_binding": None,
18
19
  "context_enrichment_webhook_url": None,
19
20
  "retrieval_scope": None,
21
+ "status": "active",
20
22
  "is_active": True,
21
23
  "created_at": "2026-01-01T00:00:00.000Z",
22
24
  "updated_at": "2026-01-01T00:00:00.000Z",
@@ -30,15 +32,31 @@ FIXTURE_INTENT = {
30
32
  "display_name": "Refund Status",
31
33
  "description": "Answer refund status questions.",
32
34
  "prompt_template": "You are a billing assistant...",
35
+ "prompt_binding": None,
33
36
  "output_schema": None,
34
37
  "input_schema": None,
35
38
  "guardrails_config": None,
39
+ "agent_config": None,
40
+ "execution_config": None,
41
+ "retrieval_config": None,
42
+ "cache_config": None,
36
43
  "is_active": True,
37
44
  "sort_order": 0,
38
45
  "created_at": "2026-01-01T00:00:00.000Z",
39
46
  "updated_at": "2026-01-01T00:00:00.000Z",
40
47
  }
41
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
+
42
60
 
43
61
  @pytest.fixture
44
62
  def client():
@@ -57,7 +75,7 @@ def test_domain_crud(client):
57
75
  respx.post(f"{BASE_URL}/v1/domains").mock(
58
76
  return_value=httpx.Response(201, json={"success": True, "data": {"domain": FIXTURE_DOMAIN}})
59
77
  )
60
- created = client.domains.create(domain_key="billing", display_name="Billing")
78
+ created = client.domains.create(domain_key="billing", display_name="Billing", status="draft")
61
79
  assert created.domain_key == "billing"
62
80
 
63
81
  respx.get(f"{BASE_URL}/v1/domains/billing").mock(
@@ -70,7 +88,7 @@ def test_domain_crud(client):
70
88
  respx.patch(f"{BASE_URL}/v1/domains/billing").mock(
71
89
  return_value=httpx.Response(200, json={"success": True, "data": {"updated": 1}})
72
90
  )
73
- updated = client.domains.update("billing", display_name="Billing Support")
91
+ updated = client.domains.update("billing", display_name="Billing Support", status="active")
74
92
  assert updated["updated"] == 1
75
93
 
76
94
  respx.delete(f"{BASE_URL}/v1/domains/billing").mock(
@@ -106,18 +124,28 @@ def test_domain_intents_crud(client):
106
124
  intents = client.domains.intents.list("billing")
107
125
  assert len(intents) == 1
108
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
+
109
133
  respx.post(f"{BASE_URL}/v1/domains/billing/intents").mock(
110
134
  return_value=httpx.Response(201, json={"success": True, "data": {"intent": FIXTURE_INTENT}})
111
135
  )
112
136
  created = client.domains.intents.create(
113
- "billing", intent_key="refund-status", display_name="Refund Status", prompt_template="You are a billing assistant...",
137
+ "billing", intent_key="refund-status", display_name="Refund Status",
138
+ description="Answer refund status questions.", prompt_template="You are a billing assistant...",
114
139
  )
115
140
  assert created.intent_key == "refund-status"
116
141
 
117
142
  respx.patch(f"{BASE_URL}/v1/domains/billing/intents/refund-status").mock(
118
143
  return_value=httpx.Response(200, json={"success": True, "data": {"updated": 1}})
119
144
  )
120
- updated = client.domains.intents.update("billing", "refund-status", display_name="Refund Status v2")
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
+ )
121
149
  assert updated["updated"] == 1
122
150
 
123
151
  respx.delete(f"{BASE_URL}/v1/domains/billing/intents/refund-status").mock(
@@ -126,6 +154,41 @@ def test_domain_intents_crud(client):
126
154
  client.domains.intents.delete("billing", "refund-status")
127
155
 
128
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
+
129
192
  @respx.mock
130
193
  def test_domain_sources_crud(client):
131
194
  respx.get(f"{BASE_URL}/v1/domains/billing/sources").mock(
File without changes
File without changes