liyaengine 0.6.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.6.0 → liyaengine-0.7.0}/PKG-INFO +58 -3
  2. {liyaengine-0.6.0 → liyaengine-0.7.0}/README.md +57 -2
  3. {liyaengine-0.6.0 → liyaengine-0.7.0}/pyproject.toml +1 -1
  4. {liyaengine-0.6.0 → liyaengine-0.7.0}/src/liyaengine/__init__.py +7 -2
  5. {liyaengine-0.6.0 → liyaengine-0.7.0}/src/liyaengine/client.py +2 -0
  6. {liyaengine-0.6.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.6.0 → liyaengine-0.7.0}/tests/test_collections.py +86 -0
  9. liyaengine-0.7.0/tests/test_documents.py +143 -0
  10. {liyaengine-0.6.0 → liyaengine-0.7.0}/.github/workflows/ci.yml +0 -0
  11. {liyaengine-0.6.0 → liyaengine-0.7.0}/.gitignore +0 -0
  12. {liyaengine-0.6.0 → liyaengine-0.7.0}/LICENSE +0 -0
  13. {liyaengine-0.6.0 → liyaengine-0.7.0}/src/liyaengine/_http.py +0 -0
  14. {liyaengine-0.6.0 → liyaengine-0.7.0}/src/liyaengine/errors.py +0 -0
  15. {liyaengine-0.6.0 → liyaengine-0.7.0}/src/liyaengine/py.typed +0 -0
  16. {liyaengine-0.6.0 → liyaengine-0.7.0}/src/liyaengine/resources/__init__.py +0 -0
  17. {liyaengine-0.6.0 → liyaengine-0.7.0}/src/liyaengine/resources/agents.py +0 -0
  18. {liyaengine-0.6.0 → liyaengine-0.7.0}/src/liyaengine/resources/domains.py +0 -0
  19. {liyaengine-0.6.0 → liyaengine-0.7.0}/src/liyaengine/resources/evaluations.py +0 -0
  20. {liyaengine-0.6.0 → liyaengine-0.7.0}/src/liyaengine/resources/workflows.py +0 -0
  21. {liyaengine-0.6.0 → liyaengine-0.7.0}/tests/test_agents.py +0 -0
  22. {liyaengine-0.6.0 → liyaengine-0.7.0}/tests/test_domains.py +0 -0
  23. {liyaengine-0.6.0 → liyaengine-0.7.0}/tests/test_evaluations.py +0 -0
  24. {liyaengine-0.6.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.6.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
@@ -99,9 +99,63 @@ client.collections.get(id)
99
99
  client.collections.create(slug=..., label=..., domain_keys=[...])
100
100
  client.collections.update(id, label=..., tags=[...], visibility=...)
101
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"])
102
156
  ```
103
157
 
104
- 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.
105
159
 
106
160
  ## Agents
107
161
 
@@ -216,7 +270,8 @@ LiyaEngine(
216
270
  - [x] Agents (full CRUD, deploy, run, run/session history)
217
271
  - [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
218
272
  - [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
219
- - [ ] Full KBaaS (document list/get/delete, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics)
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
220
275
  - [ ] Run / Run (streaming)
221
276
  - [ ] Guardrail Policies
222
277
  - [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
@@ -70,9 +70,63 @@ client.collections.get(id)
70
70
  client.collections.create(slug=..., label=..., domain_keys=[...])
71
71
  client.collections.update(id, label=..., tags=[...], visibility=...)
72
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"])
73
127
  ```
74
128
 
75
- 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.
76
130
 
77
131
  ## Agents
78
132
 
@@ -187,7 +241,8 @@ LiyaEngine(
187
241
  - [x] Agents (full CRUD, deploy, run, run/session history)
188
242
  - [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
189
243
  - [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
190
- - [ ] Full KBaaS (document list/get/delete, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics)
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
191
246
  - [ ] Run / Run (streaming)
192
247
  - [ ] Guardrail Policies
193
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.6.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
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",
@@ -22,6 +24,9 @@ __all__ = [
22
24
  "Intent",
23
25
  "DomainSource",
24
26
  "IntentVersionSummary",
27
+ "Document",
28
+ "DocumentChunk",
29
+ "IngestionJob",
25
30
  ]
26
31
 
27
- __version__ = "0.6.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))
@@ -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"
File without changes
File without changes