liyaengine 0.6.0__tar.gz → 0.8.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.
- {liyaengine-0.6.0 → liyaengine-0.8.0}/PKG-INFO +89 -4
- {liyaengine-0.6.0 → liyaengine-0.8.0}/README.md +88 -3
- {liyaengine-0.6.0 → liyaengine-0.8.0}/pyproject.toml +1 -1
- {liyaengine-0.6.0 → liyaengine-0.8.0}/src/liyaengine/__init__.py +13 -2
- liyaengine-0.8.0/src/liyaengine/_http.py +153 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/src/liyaengine/client.py +2 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/src/liyaengine/resources/collections.py +71 -1
- liyaengine-0.8.0/src/liyaengine/resources/documents.py +239 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/src/liyaengine/resources/domains.py +68 -3
- liyaengine-0.8.0/src/liyaengine/resources/run.py +77 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/tests/test_collections.py +86 -0
- liyaengine-0.8.0/tests/test_documents.py +143 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/tests/test_domains.py +54 -1
- liyaengine-0.6.0/src/liyaengine/_http.py +0 -96
- {liyaengine-0.6.0 → liyaengine-0.8.0}/.github/workflows/ci.yml +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/.gitignore +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/LICENSE +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/src/liyaengine/errors.py +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/src/liyaengine/py.typed +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/src/liyaengine/resources/__init__.py +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/src/liyaengine/resources/agents.py +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/src/liyaengine/resources/evaluations.py +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/src/liyaengine/resources/workflows.py +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/tests/test_agents.py +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/tests/test_evaluations.py +0 -0
- {liyaengine-0.6.0 → liyaengine-0.8.0}/tests/test_workflows.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: liyaengine
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.8.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
|
|
@@ -91,6 +91,36 @@ result = client.domains.query("billing", query="refund timeline")
|
|
|
91
91
|
|
|
92
92
|
> `domains.update()`/`domains.intents.update()` return `{"updated": 1}`, not the updated object — call `get()`/`list()` again for the fresh state. Guardrail policy attachment is still dashboard-only (a separate resource with no `/v1` route yet). To bind an intent's prompt to a Prompt Studio library version instead of inline text, pass `prompt_binding={"kind": "library_version", "prompt_id": ..., "version_id": ..., "content_hash": ...}` in place of `prompt_template` — editing `prompt_template` directly afterward without also passing `prompt_binding` silently detaches the binding.
|
|
93
93
|
|
|
94
|
+
## Run
|
|
95
|
+
|
|
96
|
+
The primary way to actually invoke an intent — built-in pack or custom domain — and get a real, LLM-generated response back. `agents.run()` and a domain's public `/v1/{domain}/{intent}` route both reach this same endpoint under the hood; call it directly when you don't need an Agent's multi-turn orchestration on top.
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
result = client.intents.run(
|
|
100
|
+
domain="billing",
|
|
101
|
+
intent="refund-status",
|
|
102
|
+
message="How long do refunds take?",
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
print(result.data) # shape depends on domain — see docstring
|
|
106
|
+
print(result.metadata) # {"model_used": ..., "tokens_used": ..., "cost_usd": ..., "latency_ms": ..., "cached": ..., ...}
|
|
107
|
+
print(result.usage) # {"requests_remaining": ..., "tokens_remaining": ..., ...}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Or stream it token by token:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
for event in client.intents.stream(domain="billing", intent="refund-status", message="How long do refunds take?"):
|
|
114
|
+
if event["type"] == "token":
|
|
115
|
+
print(event["delta"], end="", flush=True)
|
|
116
|
+
if event["type"] == "done":
|
|
117
|
+
print("\n", event["session_id"], event["cost_usd"])
|
|
118
|
+
if event["type"] == "error":
|
|
119
|
+
raise RuntimeError(event["message"])
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
> **Streaming is built-in-packs only** (`chat`, `hiring`, `fintech`, `healthcare`, `ehs`, `compliance`) — a custom-domain intent raises a `LiyaEngineAPIError` (`STREAMING_NOT_SUPPORTED`) immediately, before the stream opens; use `run()` instead for those. Once a stream *has* opened, every other failure (quota exceeded, provider error) arrives as an in-band `{"type": "error"}` event, not a raised error — always check `event["type"]` in your loop, not just try/except. Neither method defaults `domain` sensibly if you omit both `domain` and `pack` — it falls back to `"hiring"`, a historical default carried over from the API itself — pass one explicitly.
|
|
123
|
+
|
|
94
124
|
## Collections
|
|
95
125
|
|
|
96
126
|
```python
|
|
@@ -99,9 +129,63 @@ client.collections.get(id)
|
|
|
99
129
|
client.collections.create(slug=..., label=..., domain_keys=[...])
|
|
100
130
|
client.collections.update(id, label=..., tags=[...], visibility=...)
|
|
101
131
|
client.collections.delete(id)
|
|
132
|
+
|
|
133
|
+
# Reference documents into a collection — never copies them, never touches embeddings.
|
|
134
|
+
client.collections.documents.attach(collection_id, document_id)
|
|
135
|
+
client.collections.documents.list(collection_id) # returns CollectionDocumentSummary, a narrower shape than Document — see below
|
|
136
|
+
client.collections.documents.detach(collection_id, document_id)
|
|
137
|
+
|
|
138
|
+
# Scope a collection's knowledge to a domain.
|
|
139
|
+
client.collections.domains.attach(collection_id, "legal-ops")
|
|
140
|
+
client.collections.domains.detach(collection_id, "legal-ops")
|
|
141
|
+
|
|
142
|
+
# Live aggregation — no rollup table, always reflects current state.
|
|
143
|
+
stats = client.collections.analytics(collection_id)
|
|
144
|
+
|
|
145
|
+
# What references this collection — domains, intents, agents (indirect via
|
|
146
|
+
# domain). "workflows" is always None: no workflow-to-collection link exists.
|
|
147
|
+
refs = client.collections.connections(collection_id)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Full field reference: [Collections API](/docs/api-reference/collections).
|
|
151
|
+
|
|
152
|
+
## Documents
|
|
153
|
+
|
|
154
|
+
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).
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
client.documents.list()
|
|
158
|
+
doc = client.documents.get(id) # includes the full chunk_list
|
|
159
|
+
client.documents.delete(id)
|
|
160
|
+
|
|
161
|
+
# Synchronous — blocks until extraction/chunking/embedding finishes. If
|
|
162
|
+
# collection_ids names exactly one collection, that collection's own
|
|
163
|
+
# chunking/embedding defaults pre-fill the upload.
|
|
164
|
+
uploaded = client.documents.upload(
|
|
165
|
+
file_base64="...",
|
|
166
|
+
file_name="refund-policy.pdf",
|
|
167
|
+
category="policy",
|
|
168
|
+
collection_ids=[collection_id],
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
# Push a URL or inline content — upserts by a deterministic source_id.
|
|
172
|
+
client.documents.push(url="https://example.com/faq", title="FAQ")
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
> 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.
|
|
176
|
+
|
|
177
|
+
For large files or a multi-page crawl, use the async job queue instead — it returns immediately and you poll for completion:
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
job = client.documents.jobs.create_url_job(url="https://example.com", depth=2)
|
|
181
|
+
# ...or: client.documents.jobs.create_file_job(file_base64=..., file_name=...)
|
|
182
|
+
|
|
183
|
+
status = client.documents.jobs.get(job["jobId"]) # pending | running | completed | failed | cancelled
|
|
184
|
+
client.documents.jobs.list(status="running")
|
|
185
|
+
client.documents.jobs.cancel(job["jobId"])
|
|
102
186
|
```
|
|
103
187
|
|
|
104
|
-
|
|
188
|
+
> 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
189
|
|
|
106
190
|
## Agents
|
|
107
191
|
|
|
@@ -216,8 +300,9 @@ LiyaEngine(
|
|
|
216
300
|
- [x] Agents (full CRUD, deploy, run, run/session history)
|
|
217
301
|
- [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
|
|
218
302
|
- [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
|
|
219
|
-
- [
|
|
220
|
-
- [
|
|
303
|
+
- [x] Full KBaaS (document list/get/delete/upload/push, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics/connections)
|
|
304
|
+
- [x] Run / Run (streaming) — built-in packs only for streaming; custom domains use non-streaming `run()`
|
|
305
|
+
- [ ] Flagged-chunk review
|
|
221
306
|
- [ ] Guardrail Policies
|
|
222
307
|
- [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
|
|
223
308
|
- [ ] Async client
|
|
@@ -62,6 +62,36 @@ result = client.domains.query("billing", query="refund timeline")
|
|
|
62
62
|
|
|
63
63
|
> `domains.update()`/`domains.intents.update()` return `{"updated": 1}`, not the updated object — call `get()`/`list()` again for the fresh state. Guardrail policy attachment is still dashboard-only (a separate resource with no `/v1` route yet). To bind an intent's prompt to a Prompt Studio library version instead of inline text, pass `prompt_binding={"kind": "library_version", "prompt_id": ..., "version_id": ..., "content_hash": ...}` in place of `prompt_template` — editing `prompt_template` directly afterward without also passing `prompt_binding` silently detaches the binding.
|
|
64
64
|
|
|
65
|
+
## Run
|
|
66
|
+
|
|
67
|
+
The primary way to actually invoke an intent — built-in pack or custom domain — and get a real, LLM-generated response back. `agents.run()` and a domain's public `/v1/{domain}/{intent}` route both reach this same endpoint under the hood; call it directly when you don't need an Agent's multi-turn orchestration on top.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
result = client.intents.run(
|
|
71
|
+
domain="billing",
|
|
72
|
+
intent="refund-status",
|
|
73
|
+
message="How long do refunds take?",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
print(result.data) # shape depends on domain — see docstring
|
|
77
|
+
print(result.metadata) # {"model_used": ..., "tokens_used": ..., "cost_usd": ..., "latency_ms": ..., "cached": ..., ...}
|
|
78
|
+
print(result.usage) # {"requests_remaining": ..., "tokens_remaining": ..., ...}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Or stream it token by token:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
for event in client.intents.stream(domain="billing", intent="refund-status", message="How long do refunds take?"):
|
|
85
|
+
if event["type"] == "token":
|
|
86
|
+
print(event["delta"], end="", flush=True)
|
|
87
|
+
if event["type"] == "done":
|
|
88
|
+
print("\n", event["session_id"], event["cost_usd"])
|
|
89
|
+
if event["type"] == "error":
|
|
90
|
+
raise RuntimeError(event["message"])
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
> **Streaming is built-in-packs only** (`chat`, `hiring`, `fintech`, `healthcare`, `ehs`, `compliance`) — a custom-domain intent raises a `LiyaEngineAPIError` (`STREAMING_NOT_SUPPORTED`) immediately, before the stream opens; use `run()` instead for those. Once a stream *has* opened, every other failure (quota exceeded, provider error) arrives as an in-band `{"type": "error"}` event, not a raised error — always check `event["type"]` in your loop, not just try/except. Neither method defaults `domain` sensibly if you omit both `domain` and `pack` — it falls back to `"hiring"`, a historical default carried over from the API itself — pass one explicitly.
|
|
94
|
+
|
|
65
95
|
## Collections
|
|
66
96
|
|
|
67
97
|
```python
|
|
@@ -70,9 +100,63 @@ client.collections.get(id)
|
|
|
70
100
|
client.collections.create(slug=..., label=..., domain_keys=[...])
|
|
71
101
|
client.collections.update(id, label=..., tags=[...], visibility=...)
|
|
72
102
|
client.collections.delete(id)
|
|
103
|
+
|
|
104
|
+
# Reference documents into a collection — never copies them, never touches embeddings.
|
|
105
|
+
client.collections.documents.attach(collection_id, document_id)
|
|
106
|
+
client.collections.documents.list(collection_id) # returns CollectionDocumentSummary, a narrower shape than Document — see below
|
|
107
|
+
client.collections.documents.detach(collection_id, document_id)
|
|
108
|
+
|
|
109
|
+
# Scope a collection's knowledge to a domain.
|
|
110
|
+
client.collections.domains.attach(collection_id, "legal-ops")
|
|
111
|
+
client.collections.domains.detach(collection_id, "legal-ops")
|
|
112
|
+
|
|
113
|
+
# Live aggregation — no rollup table, always reflects current state.
|
|
114
|
+
stats = client.collections.analytics(collection_id)
|
|
115
|
+
|
|
116
|
+
# What references this collection — domains, intents, agents (indirect via
|
|
117
|
+
# domain). "workflows" is always None: no workflow-to-collection link exists.
|
|
118
|
+
refs = client.collections.connections(collection_id)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Full field reference: [Collections API](/docs/api-reference/collections).
|
|
122
|
+
|
|
123
|
+
## Documents
|
|
124
|
+
|
|
125
|
+
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).
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
client.documents.list()
|
|
129
|
+
doc = client.documents.get(id) # includes the full chunk_list
|
|
130
|
+
client.documents.delete(id)
|
|
131
|
+
|
|
132
|
+
# Synchronous — blocks until extraction/chunking/embedding finishes. If
|
|
133
|
+
# collection_ids names exactly one collection, that collection's own
|
|
134
|
+
# chunking/embedding defaults pre-fill the upload.
|
|
135
|
+
uploaded = client.documents.upload(
|
|
136
|
+
file_base64="...",
|
|
137
|
+
file_name="refund-policy.pdf",
|
|
138
|
+
category="policy",
|
|
139
|
+
collection_ids=[collection_id],
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
# Push a URL or inline content — upserts by a deterministic source_id.
|
|
143
|
+
client.documents.push(url="https://example.com/faq", title="FAQ")
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
> 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.
|
|
147
|
+
|
|
148
|
+
For large files or a multi-page crawl, use the async job queue instead — it returns immediately and you poll for completion:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
job = client.documents.jobs.create_url_job(url="https://example.com", depth=2)
|
|
152
|
+
# ...or: client.documents.jobs.create_file_job(file_base64=..., file_name=...)
|
|
153
|
+
|
|
154
|
+
status = client.documents.jobs.get(job["jobId"]) # pending | running | completed | failed | cancelled
|
|
155
|
+
client.documents.jobs.list(status="running")
|
|
156
|
+
client.documents.jobs.cancel(job["jobId"])
|
|
73
157
|
```
|
|
74
158
|
|
|
75
|
-
|
|
159
|
+
> 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
160
|
|
|
77
161
|
## Agents
|
|
78
162
|
|
|
@@ -187,8 +271,9 @@ LiyaEngine(
|
|
|
187
271
|
- [x] Agents (full CRUD, deploy, run, run/session history)
|
|
188
272
|
- [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
|
|
189
273
|
- [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
|
|
190
|
-
- [
|
|
191
|
-
- [
|
|
274
|
+
- [x] Full KBaaS (document list/get/delete/upload/push, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics/connections)
|
|
275
|
+
- [x] Run / Run (streaming) — built-in packs only for streaming; custom domains use non-streaming `run()`
|
|
276
|
+
- [ ] Flagged-chunk review
|
|
192
277
|
- [ ] Guardrail Policies
|
|
193
278
|
- [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
|
|
194
279
|
- [ ] Async client
|
|
@@ -1,16 +1,19 @@
|
|
|
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
|
|
9
|
+
from .resources.run import RunIntentResult, RunStreamEvent, RunTokenEvent, RunDoneEvent, RunErrorEvent
|
|
8
10
|
|
|
9
11
|
__all__ = [
|
|
10
12
|
"LiyaEngine",
|
|
11
13
|
"LiyaEngineAPIError",
|
|
12
14
|
"LiyaEngineNetworkError",
|
|
13
15
|
"Collection",
|
|
16
|
+
"CollectionDocumentSummary",
|
|
14
17
|
"Agent",
|
|
15
18
|
"Workflow",
|
|
16
19
|
"EvalDataset",
|
|
@@ -22,6 +25,14 @@ __all__ = [
|
|
|
22
25
|
"Intent",
|
|
23
26
|
"DomainSource",
|
|
24
27
|
"IntentVersionSummary",
|
|
28
|
+
"Document",
|
|
29
|
+
"DocumentChunk",
|
|
30
|
+
"IngestionJob",
|
|
31
|
+
"RunIntentResult",
|
|
32
|
+
"RunStreamEvent",
|
|
33
|
+
"RunTokenEvent",
|
|
34
|
+
"RunDoneEvent",
|
|
35
|
+
"RunErrorEvent",
|
|
25
36
|
]
|
|
26
37
|
|
|
27
|
-
__version__ = "0.
|
|
38
|
+
__version__ = "0.8.0"
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Thin httpx wrapper: bearer auth, JSON in/out, the {success,data} /
|
|
2
|
+
{success,error} envelope unwrapped into a return value or a raised
|
|
3
|
+
LiyaEngineAPIError, and retry-with-backoff on 429/5xx (not on 4xx, which
|
|
4
|
+
are the caller's own mistake and won't succeed on retry).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import time
|
|
10
|
+
from typing import Any, Dict, Iterator, Optional
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from .errors import LiyaEngineAPIError, LiyaEngineNetworkError
|
|
15
|
+
|
|
16
|
+
_DEFAULT_TIMEOUT_S = 30.0
|
|
17
|
+
_DEFAULT_MAX_RETRIES = 2
|
|
18
|
+
_RETRYABLE_STATUS = {429, 500, 502, 503, 504}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class HttpClient:
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
api_key: str,
|
|
25
|
+
base_url: str,
|
|
26
|
+
timeout_s: float = _DEFAULT_TIMEOUT_S,
|
|
27
|
+
max_retries: int = _DEFAULT_MAX_RETRIES,
|
|
28
|
+
client: Optional[httpx.Client] = None,
|
|
29
|
+
) -> None:
|
|
30
|
+
self._max_retries = max_retries
|
|
31
|
+
self._client = client or httpx.Client(
|
|
32
|
+
base_url=base_url.rstrip("/"),
|
|
33
|
+
timeout=timeout_s,
|
|
34
|
+
headers={
|
|
35
|
+
"Authorization": f"Bearer {api_key}",
|
|
36
|
+
"Content-Type": "application/json",
|
|
37
|
+
},
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
def _request_envelope(self, method: str, path: str, json_body: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
41
|
+
"""Shared fetch/retry/error-envelope core — returns the parsed body
|
|
42
|
+
as-is (past the success check), not unwrapped to just `data`. Almost
|
|
43
|
+
every endpoint wants `request()` below instead."""
|
|
44
|
+
last_error: Optional[BaseException] = None
|
|
45
|
+
|
|
46
|
+
for attempt in range(self._max_retries + 1):
|
|
47
|
+
try:
|
|
48
|
+
response = self._client.request(method, path, json=json_body)
|
|
49
|
+
except httpx.TimeoutException as exc:
|
|
50
|
+
last_error = LiyaEngineNetworkError(f"Request timed out: {exc}", exc)
|
|
51
|
+
if attempt >= self._max_retries:
|
|
52
|
+
raise last_error from exc
|
|
53
|
+
time.sleep(2**attempt * 0.25)
|
|
54
|
+
continue
|
|
55
|
+
except httpx.RequestError as exc:
|
|
56
|
+
last_error = LiyaEngineNetworkError(f"Network request failed: {exc}", exc)
|
|
57
|
+
if attempt >= self._max_retries:
|
|
58
|
+
raise last_error from exc
|
|
59
|
+
time.sleep(2**attempt * 0.25)
|
|
60
|
+
continue
|
|
61
|
+
|
|
62
|
+
if response.status_code in _RETRYABLE_STATUS and attempt < self._max_retries:
|
|
63
|
+
time.sleep(2**attempt * 0.25)
|
|
64
|
+
continue
|
|
65
|
+
|
|
66
|
+
try:
|
|
67
|
+
payload: Dict[str, Any] = response.json()
|
|
68
|
+
except ValueError as exc:
|
|
69
|
+
raise LiyaEngineNetworkError(
|
|
70
|
+
f"Invalid JSON response (status {response.status_code})", exc
|
|
71
|
+
) from exc
|
|
72
|
+
|
|
73
|
+
if not payload.get("success"):
|
|
74
|
+
error = payload.get("error", {})
|
|
75
|
+
raise LiyaEngineAPIError(
|
|
76
|
+
response.status_code,
|
|
77
|
+
error.get("code", "UNKNOWN_ERROR"),
|
|
78
|
+
error.get("message", "Unknown error"),
|
|
79
|
+
error.get("details"),
|
|
80
|
+
)
|
|
81
|
+
return payload
|
|
82
|
+
|
|
83
|
+
if last_error is not None:
|
|
84
|
+
raise last_error
|
|
85
|
+
raise LiyaEngineNetworkError("Request failed")
|
|
86
|
+
|
|
87
|
+
def request(self, method: str, path: str, json_body: Optional[Dict[str, Any]] = None) -> Any:
|
|
88
|
+
return self._request_envelope(method, path, json_body).get("data")
|
|
89
|
+
|
|
90
|
+
def get(self, path: str) -> Any:
|
|
91
|
+
return self.request("GET", path)
|
|
92
|
+
|
|
93
|
+
def post(self, path: str, json_body: Optional[Dict[str, Any]] = None) -> Any:
|
|
94
|
+
return self.request("POST", path, json_body)
|
|
95
|
+
|
|
96
|
+
def patch(self, path: str, json_body: Optional[Dict[str, Any]] = None) -> Any:
|
|
97
|
+
return self.request("PATCH", path, json_body)
|
|
98
|
+
|
|
99
|
+
def delete(self, path: str) -> Any:
|
|
100
|
+
return self.request("DELETE", path)
|
|
101
|
+
|
|
102
|
+
def post_envelope(self, path: str, json_body: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
103
|
+
"""For the rare endpoint whose envelope has extra top-level sibling
|
|
104
|
+
fields beyond {success, data} (today: only POST /v1/run, which also
|
|
105
|
+
returns sibling metadata/usage) — returns the parsed body as-is,
|
|
106
|
+
past the standard success/error check, instead of unwrapping to
|
|
107
|
+
just `data`."""
|
|
108
|
+
return self._request_envelope("POST", path, json_body)
|
|
109
|
+
|
|
110
|
+
def stream(self, path: str, json_body: Optional[Dict[str, Any]] = None) -> Iterator[Dict[str, Any]]:
|
|
111
|
+
"""Streams POST {path} as server-sent events, yielding each parsed
|
|
112
|
+
`data: {...}` frame in order. No retries — a stream is a single
|
|
113
|
+
long-lived attempt, not a single request with a bounded response the
|
|
114
|
+
usual retry-with-backoff logic can safely redo. No timeout override
|
|
115
|
+
either: this is a token-by-token stream of unbounded duration, not a
|
|
116
|
+
single request racing a fixed deadline (the client's configured
|
|
117
|
+
timeout_s still applies to the initial connection).
|
|
118
|
+
|
|
119
|
+
A rejection *before* the stream opens (missing field, plan gate)
|
|
120
|
+
arrives as a normal {success:false,error} JSON body over a non-2xx
|
|
121
|
+
status — raised as a LiyaEngineAPIError, exactly like request().
|
|
122
|
+
Once the stream has opened, every subsequent failure arrives in-band
|
|
123
|
+
as a frame with the caller's own `type` field (e.g. "error") — this
|
|
124
|
+
method has no opinion on frame shape; callers discriminate by
|
|
125
|
+
whatever `type` values that specific endpoint documents.
|
|
126
|
+
"""
|
|
127
|
+
with self._client.stream("POST", path, json=json_body) as response:
|
|
128
|
+
content_type = response.headers.get("content-type", "")
|
|
129
|
+
if "text/event-stream" not in content_type:
|
|
130
|
+
response.read()
|
|
131
|
+
try:
|
|
132
|
+
payload = response.json()
|
|
133
|
+
except ValueError as exc:
|
|
134
|
+
raise LiyaEngineNetworkError(
|
|
135
|
+
f"Invalid JSON response (status {response.status_code})", exc
|
|
136
|
+
) from exc
|
|
137
|
+
if payload.get("success") is False:
|
|
138
|
+
error = payload.get("error", {})
|
|
139
|
+
raise LiyaEngineAPIError(
|
|
140
|
+
response.status_code,
|
|
141
|
+
error.get("code", "UNKNOWN_ERROR"),
|
|
142
|
+
error.get("message", "Unknown error"),
|
|
143
|
+
error.get("details"),
|
|
144
|
+
)
|
|
145
|
+
raise LiyaEngineNetworkError(f"Unexpected non-streaming response (status {response.status_code})")
|
|
146
|
+
|
|
147
|
+
for line in response.iter_lines():
|
|
148
|
+
if not line or not line.startswith("data: "):
|
|
149
|
+
continue
|
|
150
|
+
yield json.loads(line[len("data: ") :])
|
|
151
|
+
|
|
152
|
+
def close(self) -> None:
|
|
153
|
+
self._client.close()
|
|
@@ -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"))
|