liyaengine 0.7.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.7.0 → liyaengine-0.8.0}/PKG-INFO +32 -2
- {liyaengine-0.7.0 → liyaengine-0.8.0}/README.md +31 -1
- {liyaengine-0.7.0 → liyaengine-0.8.0}/pyproject.toml +1 -1
- {liyaengine-0.7.0 → liyaengine-0.8.0}/src/liyaengine/__init__.py +7 -1
- liyaengine-0.8.0/src/liyaengine/_http.py +153 -0
- {liyaengine-0.7.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.7.0 → liyaengine-0.8.0}/tests/test_domains.py +54 -1
- liyaengine-0.7.0/src/liyaengine/_http.py +0 -96
- {liyaengine-0.7.0 → liyaengine-0.8.0}/.github/workflows/ci.yml +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/.gitignore +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/LICENSE +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/src/liyaengine/client.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/src/liyaengine/errors.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/src/liyaengine/py.typed +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/src/liyaengine/resources/__init__.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/src/liyaengine/resources/agents.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/src/liyaengine/resources/collections.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/src/liyaengine/resources/documents.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/src/liyaengine/resources/evaluations.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/src/liyaengine/resources/workflows.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/tests/test_agents.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/tests/test_collections.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/tests/test_documents.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.8.0}/tests/test_evaluations.py +0 -0
- {liyaengine-0.7.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
|
|
@@ -271,8 +301,8 @@ LiyaEngine(
|
|
|
271
301
|
- [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
|
|
272
302
|
- [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
|
|
273
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()`
|
|
274
305
|
- [ ] Flagged-chunk review
|
|
275
|
-
- [ ] Run / Run (streaming)
|
|
276
306
|
- [ ] Guardrail Policies
|
|
277
307
|
- [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
|
|
278
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
|
|
@@ -242,8 +272,8 @@ LiyaEngine(
|
|
|
242
272
|
- [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
|
|
243
273
|
- [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
|
|
244
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()`
|
|
245
276
|
- [ ] Flagged-chunk review
|
|
246
|
-
- [ ] Run / Run (streaming)
|
|
247
277
|
- [ ] Guardrail Policies
|
|
248
278
|
- [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
|
|
249
279
|
- [ ] Async client
|
|
@@ -6,6 +6,7 @@ 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
8
|
from .resources.documents import Document, DocumentChunk, IngestionJob
|
|
9
|
+
from .resources.run import RunIntentResult, RunStreamEvent, RunTokenEvent, RunDoneEvent, RunErrorEvent
|
|
9
10
|
|
|
10
11
|
__all__ = [
|
|
11
12
|
"LiyaEngine",
|
|
@@ -27,6 +28,11 @@ __all__ = [
|
|
|
27
28
|
"Document",
|
|
28
29
|
"DocumentChunk",
|
|
29
30
|
"IngestionJob",
|
|
31
|
+
"RunIntentResult",
|
|
32
|
+
"RunStreamEvent",
|
|
33
|
+
"RunTokenEvent",
|
|
34
|
+
"RunDoneEvent",
|
|
35
|
+
"RunErrorEvent",
|
|
30
36
|
]
|
|
31
37
|
|
|
32
|
-
__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()
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
from dataclasses import dataclass
|
|
4
|
-
from typing import Any, Dict, List, Literal, Optional, TypedDict, Union, cast
|
|
4
|
+
from typing import Any, Dict, Iterator, List, Literal, Optional, TypedDict, Union, cast
|
|
5
5
|
from urllib.parse import quote
|
|
6
6
|
|
|
7
7
|
from .._http import HttpClient
|
|
8
|
+
from .run import RunIntentResult, RunStreamEvent, _translate_run_input
|
|
8
9
|
|
|
9
10
|
|
|
10
11
|
class InlinePromptBinding(TypedDict):
|
|
@@ -375,8 +376,10 @@ class DomainsResource:
|
|
|
375
376
|
|
|
376
377
|
class IntentsResource:
|
|
377
378
|
"""Flat intent catalog — cuts across every custom domain, for external
|
|
378
|
-
discovery (mirrors the dashboard's API Explorer page)
|
|
379
|
-
|
|
379
|
+
discovery (mirrors the dashboard's API Explorer page) — plus run()/
|
|
380
|
+
stream(), the primary way to actually invoke LiyaEngine: list what you
|
|
381
|
+
can run here, run it below. Create/update/delete an intent via
|
|
382
|
+
client.domains.intents instead — this resource doesn't own that."""
|
|
380
383
|
|
|
381
384
|
def __init__(self, http: HttpClient) -> None:
|
|
382
385
|
self._http = http
|
|
@@ -384,3 +387,65 @@ class IntentsResource:
|
|
|
384
387
|
def list_all(self) -> List[IntentCatalogEntry]:
|
|
385
388
|
data = self._http.get("/v1/intents")
|
|
386
389
|
return [IntentCatalogEntry._from_dict(i) for i in data["intents"]]
|
|
390
|
+
|
|
391
|
+
def run(
|
|
392
|
+
self,
|
|
393
|
+
*,
|
|
394
|
+
intent: str,
|
|
395
|
+
domain: Optional[str] = None,
|
|
396
|
+
pack: Optional[str] = None,
|
|
397
|
+
input: Optional[Dict[str, Any]] = None,
|
|
398
|
+
message: Optional[str] = None,
|
|
399
|
+
session_id: Optional[str] = None,
|
|
400
|
+
retrieval: Optional[Dict[str, Any]] = None,
|
|
401
|
+
guardrails: Optional[Dict[str, Any]] = None,
|
|
402
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
403
|
+
preferences: Optional[Dict[str, Any]] = None,
|
|
404
|
+
) -> RunIntentResult:
|
|
405
|
+
"""Run any intent — built-in pack or custom domain — and get one
|
|
406
|
+
JSON response back. This is the endpoint every other execution path
|
|
407
|
+
(agents.run(), a domain's public /v1/{domain}/{intent} route)
|
|
408
|
+
ultimately reaches; call this directly when you don't need an
|
|
409
|
+
Agent's multi-turn orchestration on top.
|
|
410
|
+
|
|
411
|
+
`domain` defaults to 'hiring' if neither this nor `pack` is given —
|
|
412
|
+
a historical default carried over from the API itself, not a
|
|
413
|
+
recommendation. Pass one explicitly.
|
|
414
|
+
"""
|
|
415
|
+
body = _translate_run_input(
|
|
416
|
+
intent=intent, domain=domain, pack=pack, input=input, message=message,
|
|
417
|
+
session_id=session_id, retrieval=retrieval, guardrails=guardrails,
|
|
418
|
+
metadata=metadata, preferences=preferences,
|
|
419
|
+
)
|
|
420
|
+
payload = self._http.post_envelope("/v1/run", body)
|
|
421
|
+
return RunIntentResult._from_dict(payload)
|
|
422
|
+
|
|
423
|
+
def stream(
|
|
424
|
+
self,
|
|
425
|
+
*,
|
|
426
|
+
intent: str,
|
|
427
|
+
domain: Optional[str] = None,
|
|
428
|
+
pack: Optional[str] = None,
|
|
429
|
+
input: Optional[Dict[str, Any]] = None,
|
|
430
|
+
message: Optional[str] = None,
|
|
431
|
+
session_id: Optional[str] = None,
|
|
432
|
+
retrieval: Optional[Dict[str, Any]] = None,
|
|
433
|
+
guardrails: Optional[Dict[str, Any]] = None,
|
|
434
|
+
) -> Iterator[RunStreamEvent]:
|
|
435
|
+
"""Same request shape as run(), delivered as a token-by-token stream
|
|
436
|
+
instead of one response — iterate with a for loop.
|
|
437
|
+
|
|
438
|
+
Built-in packs only (chat, hiring, fintech, healthcare, ehs,
|
|
439
|
+
compliance). A custom-domain intent raises a LiyaEngineAPIError
|
|
440
|
+
(STREAMING_NOT_SUPPORTED) immediately, before the stream opens — use
|
|
441
|
+
run() for those. Once the stream *has* opened, every other failure
|
|
442
|
+
(quota, provider error) arrives as an in-band {"type": "error"}
|
|
443
|
+
event, not a raised error — always check event["type"] in your loop.
|
|
444
|
+
"""
|
|
445
|
+
body = _translate_run_input(
|
|
446
|
+
intent=intent, domain=domain, pack=pack, input=input, message=message,
|
|
447
|
+
session_id=session_id, retrieval=retrieval, guardrails=guardrails,
|
|
448
|
+
metadata=None, preferences=None,
|
|
449
|
+
)
|
|
450
|
+
for frame in self._http.stream("/v1/run/stream", body):
|
|
451
|
+
yield cast(RunStreamEvent, frame)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Types for POST /v1/run and POST /v1/run/stream — the primary way to
|
|
2
|
+
invoke LiyaEngine directly (no Domain/Agent/Workflow object to create
|
|
3
|
+
first). Methods live on IntentsResource (client.intents.run/.stream),
|
|
4
|
+
pairing with its list_all() catalog: list what you can run, then run it.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, Dict, Literal, Optional, TypedDict, Union
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class RunTokenEvent(TypedDict):
|
|
13
|
+
type: Literal["token"]
|
|
14
|
+
delta: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class RunDoneEvent(TypedDict):
|
|
18
|
+
type: Literal["done"]
|
|
19
|
+
session_id: str
|
|
20
|
+
latency_ms: int
|
|
21
|
+
input_tokens: int
|
|
22
|
+
output_tokens: int
|
|
23
|
+
cost_usd: float
|
|
24
|
+
served_by: Literal["platform", "byok"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class RunErrorEvent(TypedDict):
|
|
28
|
+
type: Literal["error"]
|
|
29
|
+
message: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
RunStreamEvent = Union[RunTokenEvent, RunDoneEvent, RunErrorEvent]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class RunIntentResult:
|
|
37
|
+
"""`data`'s shape depends on `domain`: for the 'chat' domain it's
|
|
38
|
+
{response, session, execution}; for every other domain (built-in
|
|
39
|
+
non-chat, or a custom domain_key) it's {output, session_id, message_id}.
|
|
40
|
+
|
|
41
|
+
`metadata`/`usage` are absent in exactly one narrow case: a chat session
|
|
42
|
+
that has exhausted its per-session token budget short-circuits to a
|
|
43
|
+
canned escalation message (still success, still chat-shaped `data`)
|
|
44
|
+
with no metadata/usage siblings at all — a real, pre-existing envelope
|
|
45
|
+
inconsistency on this endpoint, not an SDK gap.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
data: Dict[str, Any]
|
|
49
|
+
metadata: Optional[Dict[str, Any]]
|
|
50
|
+
usage: Optional[Dict[str, Any]]
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
def _from_dict(cls, payload: Dict[str, Any]) -> "RunIntentResult":
|
|
54
|
+
return cls(data=payload["data"], metadata=payload.get("metadata"), usage=payload.get("usage"))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _translate_run_input(
|
|
58
|
+
*,
|
|
59
|
+
intent: str,
|
|
60
|
+
domain: Optional[str],
|
|
61
|
+
pack: Optional[str],
|
|
62
|
+
input: Optional[Dict[str, Any]],
|
|
63
|
+
message: Optional[str],
|
|
64
|
+
session_id: Optional[str],
|
|
65
|
+
retrieval: Optional[Dict[str, Any]],
|
|
66
|
+
guardrails: Optional[Dict[str, Any]],
|
|
67
|
+
metadata: Optional[Dict[str, Any]],
|
|
68
|
+
preferences: Optional[Dict[str, Any]],
|
|
69
|
+
) -> Dict[str, Any]:
|
|
70
|
+
body: Dict[str, Any] = {"intent": intent}
|
|
71
|
+
optional = {
|
|
72
|
+
"pack": pack, "domain": domain, "input": input, "message": message,
|
|
73
|
+
"session_id": session_id, "retrieval": retrieval, "guardrails": guardrails,
|
|
74
|
+
"metadata": metadata, "preferences": preferences,
|
|
75
|
+
}
|
|
76
|
+
body.update({k: v for k, v in optional.items() if v is not None})
|
|
77
|
+
return body
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
1
3
|
import httpx
|
|
2
4
|
import pytest
|
|
3
5
|
import respx
|
|
4
6
|
|
|
5
|
-
from liyaengine import LiyaEngine
|
|
7
|
+
from liyaengine import LiyaEngine, LiyaEngineAPIError
|
|
6
8
|
|
|
7
9
|
BASE_URL = "https://api.test.liyaengine.ai"
|
|
8
10
|
|
|
@@ -220,3 +222,54 @@ def test_intents_list_all(client):
|
|
|
220
222
|
catalog = client.intents.list_all()
|
|
221
223
|
assert len(catalog) == 1
|
|
222
224
|
assert catalog[0].domain == "billing"
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@respx.mock
|
|
228
|
+
def test_intents_run(client):
|
|
229
|
+
respx.post(f"{BASE_URL}/v1/run").mock(
|
|
230
|
+
return_value=httpx.Response(200, json={
|
|
231
|
+
"success": True,
|
|
232
|
+
"data": {"output": {"answer": "Refunds take 5-7 days."}, "session_id": "sess_2", "message_id": "msg_1"},
|
|
233
|
+
"metadata": {
|
|
234
|
+
"intent": "refund-status", "domain": "billing", "model_used": "gpt-4o-mini",
|
|
235
|
+
"tokens_used": 88, "cost_usd": 0.0008, "latency_ms": 301, "cached": False,
|
|
236
|
+
},
|
|
237
|
+
"usage": {"requests_used": 12, "tokens_used": 4908, "requests_remaining": 988, "tokens_remaining": 244870},
|
|
238
|
+
})
|
|
239
|
+
)
|
|
240
|
+
result = client.intents.run(domain="billing", intent="refund-status", message="How long do refunds take?")
|
|
241
|
+
assert result.data == {"output": {"answer": "Refunds take 5-7 days."}, "session_id": "sess_2", "message_id": "msg_1"}
|
|
242
|
+
assert result.metadata is not None and result.metadata["model_used"] == "gpt-4o-mini"
|
|
243
|
+
assert result.usage is not None and result.usage["requests_remaining"] == 988
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@respx.mock
|
|
247
|
+
def test_intents_stream_yields_frames_in_order(client):
|
|
248
|
+
frames = [
|
|
249
|
+
{"type": "token", "delta": "Refunds "},
|
|
250
|
+
{"type": "token", "delta": "take 5-7 days."},
|
|
251
|
+
{
|
|
252
|
+
"type": "done", "session_id": "sess_3", "latency_ms": 300,
|
|
253
|
+
"input_tokens": 40, "output_tokens": 12, "cost_usd": 0.0005, "served_by": "platform",
|
|
254
|
+
},
|
|
255
|
+
]
|
|
256
|
+
sse_body = "".join(f"data: {json.dumps(f)}\n\n" for f in frames)
|
|
257
|
+
respx.post(f"{BASE_URL}/v1/run/stream").mock(
|
|
258
|
+
return_value=httpx.Response(200, content=sse_body, headers={"content-type": "text/event-stream"})
|
|
259
|
+
)
|
|
260
|
+
events = list(client.intents.stream(domain="chat", intent="answer_question", message="hi"))
|
|
261
|
+
assert events == frames
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
@respx.mock
|
|
265
|
+
def test_intents_stream_raises_for_custom_domain_pre_flight_rejection(client):
|
|
266
|
+
respx.post(f"{BASE_URL}/v1/run/stream").mock(
|
|
267
|
+
return_value=httpx.Response(400, json={
|
|
268
|
+
"success": False,
|
|
269
|
+
"error": {"code": "STREAMING_NOT_SUPPORTED", "message": "Streaming is only supported for built-in packs today."},
|
|
270
|
+
})
|
|
271
|
+
)
|
|
272
|
+
with pytest.raises(LiyaEngineAPIError) as exc_info:
|
|
273
|
+
list(client.intents.stream(domain="legal-ops", intent="review-contract"))
|
|
274
|
+
assert exc_info.value.code == "STREAMING_NOT_SUPPORTED"
|
|
275
|
+
assert exc_info.value.status == 400
|
|
@@ -1,96 +0,0 @@
|
|
|
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 time
|
|
9
|
-
from typing import Any, Dict, Optional
|
|
10
|
-
|
|
11
|
-
import httpx
|
|
12
|
-
|
|
13
|
-
from .errors import LiyaEngineAPIError, LiyaEngineNetworkError
|
|
14
|
-
|
|
15
|
-
_DEFAULT_TIMEOUT_S = 30.0
|
|
16
|
-
_DEFAULT_MAX_RETRIES = 2
|
|
17
|
-
_RETRYABLE_STATUS = {429, 500, 502, 503, 504}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
class HttpClient:
|
|
21
|
-
def __init__(
|
|
22
|
-
self,
|
|
23
|
-
api_key: str,
|
|
24
|
-
base_url: str,
|
|
25
|
-
timeout_s: float = _DEFAULT_TIMEOUT_S,
|
|
26
|
-
max_retries: int = _DEFAULT_MAX_RETRIES,
|
|
27
|
-
client: Optional[httpx.Client] = None,
|
|
28
|
-
) -> None:
|
|
29
|
-
self._max_retries = max_retries
|
|
30
|
-
self._client = client or httpx.Client(
|
|
31
|
-
base_url=base_url.rstrip("/"),
|
|
32
|
-
timeout=timeout_s,
|
|
33
|
-
headers={
|
|
34
|
-
"Authorization": f"Bearer {api_key}",
|
|
35
|
-
"Content-Type": "application/json",
|
|
36
|
-
},
|
|
37
|
-
)
|
|
38
|
-
|
|
39
|
-
def request(self, method: str, path: str, json_body: Optional[Dict[str, Any]] = None) -> Any:
|
|
40
|
-
last_error: Optional[BaseException] = None
|
|
41
|
-
|
|
42
|
-
for attempt in range(self._max_retries + 1):
|
|
43
|
-
try:
|
|
44
|
-
response = self._client.request(method, path, json=json_body)
|
|
45
|
-
except httpx.TimeoutException as exc:
|
|
46
|
-
last_error = LiyaEngineNetworkError(f"Request timed out: {exc}", exc)
|
|
47
|
-
if attempt >= self._max_retries:
|
|
48
|
-
raise last_error from exc
|
|
49
|
-
time.sleep(2**attempt * 0.25)
|
|
50
|
-
continue
|
|
51
|
-
except httpx.RequestError as exc:
|
|
52
|
-
last_error = LiyaEngineNetworkError(f"Network request failed: {exc}", exc)
|
|
53
|
-
if attempt >= self._max_retries:
|
|
54
|
-
raise last_error from exc
|
|
55
|
-
time.sleep(2**attempt * 0.25)
|
|
56
|
-
continue
|
|
57
|
-
|
|
58
|
-
if response.status_code in _RETRYABLE_STATUS and attempt < self._max_retries:
|
|
59
|
-
time.sleep(2**attempt * 0.25)
|
|
60
|
-
continue
|
|
61
|
-
|
|
62
|
-
try:
|
|
63
|
-
payload = response.json()
|
|
64
|
-
except ValueError as exc:
|
|
65
|
-
raise LiyaEngineNetworkError(
|
|
66
|
-
f"Invalid JSON response (status {response.status_code})", exc
|
|
67
|
-
) from exc
|
|
68
|
-
|
|
69
|
-
if not payload.get("success"):
|
|
70
|
-
error = payload.get("error", {})
|
|
71
|
-
raise LiyaEngineAPIError(
|
|
72
|
-
response.status_code,
|
|
73
|
-
error.get("code", "UNKNOWN_ERROR"),
|
|
74
|
-
error.get("message", "Unknown error"),
|
|
75
|
-
error.get("details"),
|
|
76
|
-
)
|
|
77
|
-
return payload.get("data")
|
|
78
|
-
|
|
79
|
-
if last_error is not None:
|
|
80
|
-
raise last_error
|
|
81
|
-
raise LiyaEngineNetworkError("Request failed")
|
|
82
|
-
|
|
83
|
-
def get(self, path: str) -> Any:
|
|
84
|
-
return self.request("GET", path)
|
|
85
|
-
|
|
86
|
-
def post(self, path: str, json_body: Optional[Dict[str, Any]] = None) -> Any:
|
|
87
|
-
return self.request("POST", path, json_body)
|
|
88
|
-
|
|
89
|
-
def patch(self, path: str, json_body: Optional[Dict[str, Any]] = None) -> Any:
|
|
90
|
-
return self.request("PATCH", path, json_body)
|
|
91
|
-
|
|
92
|
-
def delete(self, path: str) -> Any:
|
|
93
|
-
return self.request("DELETE", path)
|
|
94
|
-
|
|
95
|
-
def close(self) -> None:
|
|
96
|
-
self._client.close()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|