liyaengine 0.7.0__tar.gz → 0.9.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.9.0}/PKG-INFO +71 -2
- {liyaengine-0.7.0 → liyaengine-0.9.0}/README.md +70 -1
- {liyaengine-0.7.0 → liyaengine-0.9.0}/pyproject.toml +1 -1
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/__init__.py +13 -1
- liyaengine-0.9.0/src/liyaengine/_http.py +153 -0
- liyaengine-0.9.0/src/liyaengine/resources/domain_tools.py +135 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/resources/domains.py +70 -3
- liyaengine-0.9.0/src/liyaengine/resources/run.py +77 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/tests/test_domains.py +127 -1
- liyaengine-0.7.0/src/liyaengine/_http.py +0 -96
- {liyaengine-0.7.0 → liyaengine-0.9.0}/.github/workflows/ci.yml +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/.gitignore +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/LICENSE +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/client.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/errors.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/py.typed +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/resources/__init__.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/resources/agents.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/resources/collections.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/resources/documents.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/resources/evaluations.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/src/liyaengine/resources/workflows.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/tests/test_agents.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/tests/test_collections.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/tests/test_documents.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.0}/tests/test_evaluations.py +0 -0
- {liyaengine-0.7.0 → liyaengine-0.9.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.9.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,74 @@ 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
|
+
## Domain Tools
|
|
95
|
+
|
|
96
|
+
The custom webhook tools an agent-mode intent (`agent_config={"enabled": True, ...}`) can call mid-conversation — e.g. a real order-status lookup against your own backend. Every custom tool is dispatched by one generic platform tool, `webhook_sender`; the LLM calls `webhook_sender({tool_name, payload})`, and `webhook_sender` looks up `tool_name` in the domain's `custom_tools` to find the real endpoint.
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
# 1. Define the tool on the domain.
|
|
100
|
+
client.domains.tools.update(
|
|
101
|
+
"shipping-support",
|
|
102
|
+
# webhook_sender must be explicitly enabled here — defining custom_tools
|
|
103
|
+
# alone does nothing, since it's webhook_sender that actually dispatches them.
|
|
104
|
+
enabled_platform_tools=["webhook_sender"],
|
|
105
|
+
custom_tools=[{
|
|
106
|
+
"name": "lookup_order",
|
|
107
|
+
"display_name": "Order Lookup",
|
|
108
|
+
"description": 'Looks up a real order by number and returns its current status. Call with {"order_number": "..."}.',
|
|
109
|
+
"endpoint_url": "https://fernbankoutdoor.com/api/liya-tools/lookup-order",
|
|
110
|
+
"auth_type": "api_key",
|
|
111
|
+
"auth_value": os.environ["LIYA_TOOL_SHARED_SECRET"], # write-only — never returned by get()
|
|
112
|
+
}],
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
# 2. Verify the endpoint actually works before wiring it into a live intent.
|
|
116
|
+
test_result = client.domains.tools.test("shipping-support", "lookup_order", {"order_number": "A1092"})
|
|
117
|
+
|
|
118
|
+
# 3. Point the intent at "webhook_sender" — NOT "lookup_order". agent_config["tools"]
|
|
119
|
+
# is a platform-tool allowlist; "lookup_order" is only ever an *argument* the
|
|
120
|
+
# model passes to webhook_sender at call time, never an entry in this array.
|
|
121
|
+
client.domains.intents.update(
|
|
122
|
+
"shipping-support", "track-order",
|
|
123
|
+
agent_config={"enabled": True, "tools": ["webhook_sender"], "max_steps": 3},
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
config = client.domains.tools.get("shipping-support")
|
|
127
|
+
# config.custom_tools[0].auth_configured is True — the real credential is never returned, only whether one is set.
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
> **Two real footguns, easy to hit on the first try:** (1) `enabled_platform_tools` must include `"webhook_sender"` — a domain with only `custom_tools` defined and no platform tool enabled registers *zero* tools, and the model will just apologize that it can't look anything up (or worse, quietly fabricate a plausible-looking answer if your prompt insists it report a result). (2) `agent_config["tools"]` takes platform tool names, so it's `["webhook_sender"]`, never `["lookup_order"]` — the custom tool's own name is an argument, not an allowlist entry. Beyond that: there's no JSON-schema parameter definition for a custom tool today — `description` is the *only* thing the model sees to decide when and how to call it, so be explicit about the fields you expect. `custom_tools` in `update()` REPLACES the entire array, not a per-tool patch. Omit `auth_value` on an update to preserve the existing stored credential; it's encrypted separately and never round-trips back to a reader.
|
|
131
|
+
|
|
132
|
+
## Run
|
|
133
|
+
|
|
134
|
+
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.
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
result = client.intents.run(
|
|
138
|
+
domain="billing",
|
|
139
|
+
intent="refund-status",
|
|
140
|
+
message="How long do refunds take?",
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
print(result.data) # shape depends on domain — see docstring
|
|
144
|
+
print(result.metadata) # {"model_used": ..., "tokens_used": ..., "cost_usd": ..., "latency_ms": ..., "cached": ..., ...}
|
|
145
|
+
print(result.usage) # {"requests_remaining": ..., "tokens_remaining": ..., ...}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Or stream it token by token:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
for event in client.intents.stream(domain="billing", intent="refund-status", message="How long do refunds take?"):
|
|
152
|
+
if event["type"] == "token":
|
|
153
|
+
print(event["delta"], end="", flush=True)
|
|
154
|
+
if event["type"] == "done":
|
|
155
|
+
print("\n", event["session_id"], event["cost_usd"])
|
|
156
|
+
if event["type"] == "error":
|
|
157
|
+
raise RuntimeError(event["message"])
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
> **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.
|
|
161
|
+
|
|
94
162
|
## Collections
|
|
95
163
|
|
|
96
164
|
```python
|
|
@@ -271,8 +339,9 @@ LiyaEngine(
|
|
|
271
339
|
- [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
|
|
272
340
|
- [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
|
|
273
341
|
- [x] Full KBaaS (document list/get/delete/upload/push, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics/connections)
|
|
342
|
+
- [x] Run / Run (streaming) — built-in packs only for streaming; custom domains use non-streaming `run()`
|
|
343
|
+
- [x] Domain agentic tool configuration (previously dashboard-only)
|
|
274
344
|
- [ ] Flagged-chunk review
|
|
275
|
-
- [ ] Run / Run (streaming)
|
|
276
345
|
- [ ] Guardrail Policies
|
|
277
346
|
- [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
|
|
278
347
|
- [ ] Async client
|
|
@@ -62,6 +62,74 @@ 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
|
+
## Domain Tools
|
|
66
|
+
|
|
67
|
+
The custom webhook tools an agent-mode intent (`agent_config={"enabled": True, ...}`) can call mid-conversation — e.g. a real order-status lookup against your own backend. Every custom tool is dispatched by one generic platform tool, `webhook_sender`; the LLM calls `webhook_sender({tool_name, payload})`, and `webhook_sender` looks up `tool_name` in the domain's `custom_tools` to find the real endpoint.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
# 1. Define the tool on the domain.
|
|
71
|
+
client.domains.tools.update(
|
|
72
|
+
"shipping-support",
|
|
73
|
+
# webhook_sender must be explicitly enabled here — defining custom_tools
|
|
74
|
+
# alone does nothing, since it's webhook_sender that actually dispatches them.
|
|
75
|
+
enabled_platform_tools=["webhook_sender"],
|
|
76
|
+
custom_tools=[{
|
|
77
|
+
"name": "lookup_order",
|
|
78
|
+
"display_name": "Order Lookup",
|
|
79
|
+
"description": 'Looks up a real order by number and returns its current status. Call with {"order_number": "..."}.',
|
|
80
|
+
"endpoint_url": "https://fernbankoutdoor.com/api/liya-tools/lookup-order",
|
|
81
|
+
"auth_type": "api_key",
|
|
82
|
+
"auth_value": os.environ["LIYA_TOOL_SHARED_SECRET"], # write-only — never returned by get()
|
|
83
|
+
}],
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# 2. Verify the endpoint actually works before wiring it into a live intent.
|
|
87
|
+
test_result = client.domains.tools.test("shipping-support", "lookup_order", {"order_number": "A1092"})
|
|
88
|
+
|
|
89
|
+
# 3. Point the intent at "webhook_sender" — NOT "lookup_order". agent_config["tools"]
|
|
90
|
+
# is a platform-tool allowlist; "lookup_order" is only ever an *argument* the
|
|
91
|
+
# model passes to webhook_sender at call time, never an entry in this array.
|
|
92
|
+
client.domains.intents.update(
|
|
93
|
+
"shipping-support", "track-order",
|
|
94
|
+
agent_config={"enabled": True, "tools": ["webhook_sender"], "max_steps": 3},
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
config = client.domains.tools.get("shipping-support")
|
|
98
|
+
# config.custom_tools[0].auth_configured is True — the real credential is never returned, only whether one is set.
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
> **Two real footguns, easy to hit on the first try:** (1) `enabled_platform_tools` must include `"webhook_sender"` — a domain with only `custom_tools` defined and no platform tool enabled registers *zero* tools, and the model will just apologize that it can't look anything up (or worse, quietly fabricate a plausible-looking answer if your prompt insists it report a result). (2) `agent_config["tools"]` takes platform tool names, so it's `["webhook_sender"]`, never `["lookup_order"]` — the custom tool's own name is an argument, not an allowlist entry. Beyond that: there's no JSON-schema parameter definition for a custom tool today — `description` is the *only* thing the model sees to decide when and how to call it, so be explicit about the fields you expect. `custom_tools` in `update()` REPLACES the entire array, not a per-tool patch. Omit `auth_value` on an update to preserve the existing stored credential; it's encrypted separately and never round-trips back to a reader.
|
|
102
|
+
|
|
103
|
+
## Run
|
|
104
|
+
|
|
105
|
+
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.
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
result = client.intents.run(
|
|
109
|
+
domain="billing",
|
|
110
|
+
intent="refund-status",
|
|
111
|
+
message="How long do refunds take?",
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
print(result.data) # shape depends on domain — see docstring
|
|
115
|
+
print(result.metadata) # {"model_used": ..., "tokens_used": ..., "cost_usd": ..., "latency_ms": ..., "cached": ..., ...}
|
|
116
|
+
print(result.usage) # {"requests_remaining": ..., "tokens_remaining": ..., ...}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Or stream it token by token:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
for event in client.intents.stream(domain="billing", intent="refund-status", message="How long do refunds take?"):
|
|
123
|
+
if event["type"] == "token":
|
|
124
|
+
print(event["delta"], end="", flush=True)
|
|
125
|
+
if event["type"] == "done":
|
|
126
|
+
print("\n", event["session_id"], event["cost_usd"])
|
|
127
|
+
if event["type"] == "error":
|
|
128
|
+
raise RuntimeError(event["message"])
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
> **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.
|
|
132
|
+
|
|
65
133
|
## Collections
|
|
66
134
|
|
|
67
135
|
```python
|
|
@@ -242,8 +310,9 @@ LiyaEngine(
|
|
|
242
310
|
- [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history)
|
|
243
311
|
- [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring)
|
|
244
312
|
- [x] Full KBaaS (document list/get/delete/upload/push, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics/connections)
|
|
313
|
+
- [x] Run / Run (streaming) — built-in packs only for streaming; custom domains use non-streaming `run()`
|
|
314
|
+
- [x] Domain agentic tool configuration (previously dashboard-only)
|
|
245
315
|
- [ ] Flagged-chunk review
|
|
246
|
-
- [ ] Run / Run (streaming)
|
|
247
316
|
- [ ] Guardrail Policies
|
|
248
317
|
- [ ] Prompt Studio (holding until the feature itself is committed/merged upstream)
|
|
249
318
|
- [ ] Async client
|
|
@@ -6,6 +6,8 @@ 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
|
|
10
|
+
from .resources.domain_tools import PlatformTool, MaskedCustomTool, DomainToolsConfig, TestDomainToolResult, CustomToolInput
|
|
9
11
|
|
|
10
12
|
__all__ = [
|
|
11
13
|
"LiyaEngine",
|
|
@@ -27,6 +29,16 @@ __all__ = [
|
|
|
27
29
|
"Document",
|
|
28
30
|
"DocumentChunk",
|
|
29
31
|
"IngestionJob",
|
|
32
|
+
"RunIntentResult",
|
|
33
|
+
"RunStreamEvent",
|
|
34
|
+
"RunTokenEvent",
|
|
35
|
+
"RunDoneEvent",
|
|
36
|
+
"RunErrorEvent",
|
|
37
|
+
"PlatformTool",
|
|
38
|
+
"MaskedCustomTool",
|
|
39
|
+
"DomainToolsConfig",
|
|
40
|
+
"TestDomainToolResult",
|
|
41
|
+
"CustomToolInput",
|
|
30
42
|
]
|
|
31
43
|
|
|
32
|
-
__version__ = "0.
|
|
44
|
+
__version__ = "0.9.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()
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""A domain's agentic tool configuration — the custom webhook tools (and
|
|
2
|
+
enabled platform tools) an agent-mode intent (agent_config.enabled) can
|
|
3
|
+
call mid-conversation. Was dashboard-only before this; the tool's real
|
|
4
|
+
definition (endpoint, auth) can now be set from here too, not just
|
|
5
|
+
referenced by name in an intent's agent_config.tools[].
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any, Dict, List, Literal, Optional, TypedDict, cast
|
|
11
|
+
from urllib.parse import quote
|
|
12
|
+
|
|
13
|
+
from .._http import HttpClient
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CustomToolInput(TypedDict, total=False):
|
|
17
|
+
"""URL-safe `name` (/^[a-z0-9_-]+$/) is what agent_config.tools[] references,
|
|
18
|
+
and what the model passes as tool_name at run time. `description` is the
|
|
19
|
+
ONLY thing the model sees to decide when/how to call this tool — there's
|
|
20
|
+
no separate JSON-schema parameter definition today, so be explicit about
|
|
21
|
+
expected fields there. `auth_value` is write-only: omit on update to keep
|
|
22
|
+
the existing stored credential; required on first create for any
|
|
23
|
+
auth_type other than "none"."""
|
|
24
|
+
|
|
25
|
+
name: str
|
|
26
|
+
display_name: str
|
|
27
|
+
description: str
|
|
28
|
+
endpoint_url: str
|
|
29
|
+
auth_type: Literal["none", "api_key", "bearer"]
|
|
30
|
+
auth_value: str
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class PlatformTool:
|
|
35
|
+
name: str
|
|
36
|
+
description: str
|
|
37
|
+
enabled: bool
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def _from_dict(cls, data: Dict[str, Any]) -> "PlatformTool":
|
|
41
|
+
return cls(name=data["name"], description=data["description"], enabled=data["enabled"])
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class MaskedCustomTool:
|
|
46
|
+
"""A CustomToolInput as returned by the API — auth_value replaced by
|
|
47
|
+
auth_configured; the real credential is never returned once stored."""
|
|
48
|
+
|
|
49
|
+
name: str
|
|
50
|
+
display_name: str
|
|
51
|
+
description: str
|
|
52
|
+
endpoint_url: str
|
|
53
|
+
auth_type: Literal["none", "api_key", "bearer"]
|
|
54
|
+
auth_configured: bool
|
|
55
|
+
|
|
56
|
+
@classmethod
|
|
57
|
+
def _from_dict(cls, data: Dict[str, Any]) -> "MaskedCustomTool":
|
|
58
|
+
return cls(
|
|
59
|
+
name=data["name"], display_name=data["display_name"], description=data["description"],
|
|
60
|
+
endpoint_url=data["endpoint_url"], auth_type=data["auth_type"], auth_configured=data["auth_configured"],
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class DomainToolsConfig:
|
|
66
|
+
platform_tools: List[PlatformTool]
|
|
67
|
+
custom_tools: List[MaskedCustomTool]
|
|
68
|
+
web_search_configured: bool
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def _from_dict(cls, data: Dict[str, Any]) -> "DomainToolsConfig":
|
|
72
|
+
return cls(
|
|
73
|
+
platform_tools=[PlatformTool._from_dict(t) for t in data["platform_tools"]],
|
|
74
|
+
custom_tools=[MaskedCustomTool._from_dict(t) for t in data["custom_tools"]],
|
|
75
|
+
web_search_configured=data["web_search_configured"],
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class TestDomainToolResult:
|
|
81
|
+
status_code: int
|
|
82
|
+
ok: bool
|
|
83
|
+
body: Any
|
|
84
|
+
latency_ms: int
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def _from_dict(cls, data: Dict[str, Any]) -> "TestDomainToolResult":
|
|
88
|
+
return cls(status_code=data["status_code"], ok=data["ok"], body=data["body"], latency_ms=data["latency_ms"])
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class DomainToolsResource:
|
|
92
|
+
"""Domain-scoped tool configuration. Sits at client.domains.tools rather
|
|
93
|
+
than a top-level resource — a tool only ever exists in the context of
|
|
94
|
+
the one domain it's defined on."""
|
|
95
|
+
|
|
96
|
+
def __init__(self, http: HttpClient) -> None:
|
|
97
|
+
self._http = http
|
|
98
|
+
|
|
99
|
+
def get(self, domain_key: str) -> DomainToolsConfig:
|
|
100
|
+
data = self._http.get(f"/v1/domains/{quote(domain_key)}/tools")
|
|
101
|
+
return DomainToolsConfig._from_dict(data)
|
|
102
|
+
|
|
103
|
+
def update(
|
|
104
|
+
self,
|
|
105
|
+
domain_key: str,
|
|
106
|
+
*,
|
|
107
|
+
enabled_platform_tools: Optional[List[str]] = None,
|
|
108
|
+
custom_tools: Optional[List[CustomToolInput]] = None,
|
|
109
|
+
web_search_api_key: Optional[str] = None,
|
|
110
|
+
) -> DomainToolsConfig:
|
|
111
|
+
"""`custom_tools`, when given, REPLACES the entire array — not a
|
|
112
|
+
per-tool merge/patch. `web_search_api_key=""` clears the stored key;
|
|
113
|
+
omit to leave it unchanged."""
|
|
114
|
+
body: Dict[str, Any] = {}
|
|
115
|
+
if enabled_platform_tools is not None:
|
|
116
|
+
body["enabled_platform_tools"] = enabled_platform_tools
|
|
117
|
+
if custom_tools is not None:
|
|
118
|
+
body["custom_tools"] = custom_tools
|
|
119
|
+
if web_search_api_key is not None:
|
|
120
|
+
body["web_search_api_key"] = web_search_api_key
|
|
121
|
+
data = self._http.patch(f"/v1/domains/{quote(domain_key)}/tools", body)
|
|
122
|
+
return DomainToolsConfig._from_dict(cast(Dict[str, Any], data)["tools_config"])
|
|
123
|
+
|
|
124
|
+
def test(
|
|
125
|
+
self, domain_key: str, tool_name: str, payload: Optional[Dict[str, Any]] = None,
|
|
126
|
+
) -> TestDomainToolResult:
|
|
127
|
+
"""Dispatches a real request to one custom tool's endpoint_url — the
|
|
128
|
+
exact same request shape (headers, auth, `_liya_meta` envelope) an
|
|
129
|
+
agent's real webhook_sender tool call would send — without needing a
|
|
130
|
+
live conversation to trigger it."""
|
|
131
|
+
body: Dict[str, Any] = {"tool_name": tool_name}
|
|
132
|
+
if payload is not None:
|
|
133
|
+
body["payload"] = payload
|
|
134
|
+
data = self._http.post(f"/v1/domains/{quote(domain_key)}/tools/test", body)
|
|
135
|
+
return TestDomainToolResult._from_dict(cast(Dict[str, Any], data))
|
|
@@ -1,10 +1,12 @@
|
|
|
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
|
|
9
|
+
from .domain_tools import DomainToolsResource
|
|
8
10
|
|
|
9
11
|
|
|
10
12
|
class InlinePromptBinding(TypedDict):
|
|
@@ -295,6 +297,7 @@ class DomainsResource:
|
|
|
295
297
|
self._http = http
|
|
296
298
|
self.intents = DomainIntentsResource(http)
|
|
297
299
|
self.sources = DomainSourcesResource(http)
|
|
300
|
+
self.tools = DomainToolsResource(http)
|
|
298
301
|
|
|
299
302
|
def list(self) -> List[Domain]:
|
|
300
303
|
data = self._http.get("/v1/domains")
|
|
@@ -375,8 +378,10 @@ class DomainsResource:
|
|
|
375
378
|
|
|
376
379
|
class IntentsResource:
|
|
377
380
|
"""Flat intent catalog — cuts across every custom domain, for external
|
|
378
|
-
discovery (mirrors the dashboard's API Explorer page)
|
|
379
|
-
|
|
381
|
+
discovery (mirrors the dashboard's API Explorer page) — plus run()/
|
|
382
|
+
stream(), the primary way to actually invoke LiyaEngine: list what you
|
|
383
|
+
can run here, run it below. Create/update/delete an intent via
|
|
384
|
+
client.domains.intents instead — this resource doesn't own that."""
|
|
380
385
|
|
|
381
386
|
def __init__(self, http: HttpClient) -> None:
|
|
382
387
|
self._http = http
|
|
@@ -384,3 +389,65 @@ class IntentsResource:
|
|
|
384
389
|
def list_all(self) -> List[IntentCatalogEntry]:
|
|
385
390
|
data = self._http.get("/v1/intents")
|
|
386
391
|
return [IntentCatalogEntry._from_dict(i) for i in data["intents"]]
|
|
392
|
+
|
|
393
|
+
def run(
|
|
394
|
+
self,
|
|
395
|
+
*,
|
|
396
|
+
intent: str,
|
|
397
|
+
domain: Optional[str] = None,
|
|
398
|
+
pack: Optional[str] = None,
|
|
399
|
+
input: Optional[Dict[str, Any]] = None,
|
|
400
|
+
message: Optional[str] = None,
|
|
401
|
+
session_id: Optional[str] = None,
|
|
402
|
+
retrieval: Optional[Dict[str, Any]] = None,
|
|
403
|
+
guardrails: Optional[Dict[str, Any]] = None,
|
|
404
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
405
|
+
preferences: Optional[Dict[str, Any]] = None,
|
|
406
|
+
) -> RunIntentResult:
|
|
407
|
+
"""Run any intent — built-in pack or custom domain — and get one
|
|
408
|
+
JSON response back. This is the endpoint every other execution path
|
|
409
|
+
(agents.run(), a domain's public /v1/{domain}/{intent} route)
|
|
410
|
+
ultimately reaches; call this directly when you don't need an
|
|
411
|
+
Agent's multi-turn orchestration on top.
|
|
412
|
+
|
|
413
|
+
`domain` defaults to 'hiring' if neither this nor `pack` is given —
|
|
414
|
+
a historical default carried over from the API itself, not a
|
|
415
|
+
recommendation. Pass one explicitly.
|
|
416
|
+
"""
|
|
417
|
+
body = _translate_run_input(
|
|
418
|
+
intent=intent, domain=domain, pack=pack, input=input, message=message,
|
|
419
|
+
session_id=session_id, retrieval=retrieval, guardrails=guardrails,
|
|
420
|
+
metadata=metadata, preferences=preferences,
|
|
421
|
+
)
|
|
422
|
+
payload = self._http.post_envelope("/v1/run", body)
|
|
423
|
+
return RunIntentResult._from_dict(payload)
|
|
424
|
+
|
|
425
|
+
def stream(
|
|
426
|
+
self,
|
|
427
|
+
*,
|
|
428
|
+
intent: str,
|
|
429
|
+
domain: Optional[str] = None,
|
|
430
|
+
pack: Optional[str] = None,
|
|
431
|
+
input: Optional[Dict[str, Any]] = None,
|
|
432
|
+
message: Optional[str] = None,
|
|
433
|
+
session_id: Optional[str] = None,
|
|
434
|
+
retrieval: Optional[Dict[str, Any]] = None,
|
|
435
|
+
guardrails: Optional[Dict[str, Any]] = None,
|
|
436
|
+
) -> Iterator[RunStreamEvent]:
|
|
437
|
+
"""Same request shape as run(), delivered as a token-by-token stream
|
|
438
|
+
instead of one response — iterate with a for loop.
|
|
439
|
+
|
|
440
|
+
Built-in packs only (chat, hiring, fintech, healthcare, ehs,
|
|
441
|
+
compliance). A custom-domain intent raises a LiyaEngineAPIError
|
|
442
|
+
(STREAMING_NOT_SUPPORTED) immediately, before the stream opens — use
|
|
443
|
+
run() for those. Once the stream *has* opened, every other failure
|
|
444
|
+
(quota, provider error) arrives as an in-band {"type": "error"}
|
|
445
|
+
event, not a raised error — always check event["type"] in your loop.
|
|
446
|
+
"""
|
|
447
|
+
body = _translate_run_input(
|
|
448
|
+
intent=intent, domain=domain, pack=pack, input=input, message=message,
|
|
449
|
+
session_id=session_id, retrieval=retrieval, guardrails=guardrails,
|
|
450
|
+
metadata=None, preferences=None,
|
|
451
|
+
)
|
|
452
|
+
for frame in self._http.stream("/v1/run/stream", body):
|
|
453
|
+
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,127 @@ 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
|
+
|
|
276
|
+
|
|
277
|
+
FIXTURE_MASKED_TOOL = {
|
|
278
|
+
"name": "lookup_order", "display_name": "Order Lookup", "description": "Looks up a real order by number",
|
|
279
|
+
"endpoint_url": "https://fernbankoutdoor.com/api/liya-tools/lookup-order", "auth_type": "api_key", "auth_configured": True,
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@respx.mock
|
|
284
|
+
def test_domain_tools_get(client):
|
|
285
|
+
respx.get(f"{BASE_URL}/v1/domains/shipping-support/tools").mock(
|
|
286
|
+
return_value=httpx.Response(200, json={
|
|
287
|
+
"success": True,
|
|
288
|
+
"data": {
|
|
289
|
+
"platform_tools": [{"name": "document_search", "description": "Search the knowledge base", "enabled": True}],
|
|
290
|
+
"custom_tools": [FIXTURE_MASKED_TOOL],
|
|
291
|
+
"web_search_configured": False,
|
|
292
|
+
},
|
|
293
|
+
})
|
|
294
|
+
)
|
|
295
|
+
config = client.domains.tools.get("shipping-support")
|
|
296
|
+
assert config.platform_tools[0].name == "document_search"
|
|
297
|
+
assert config.custom_tools[0].auth_configured is True
|
|
298
|
+
assert not hasattr(config.custom_tools[0], "auth_value")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
@respx.mock
|
|
302
|
+
def test_domain_tools_update_replaces_custom_tools(client):
|
|
303
|
+
respx.patch(f"{BASE_URL}/v1/domains/shipping-support/tools").mock(
|
|
304
|
+
return_value=httpx.Response(200, json={
|
|
305
|
+
"success": True,
|
|
306
|
+
"data": {"tools_config": {
|
|
307
|
+
"platform_tools": [],
|
|
308
|
+
"custom_tools": [FIXTURE_MASKED_TOOL],
|
|
309
|
+
"web_search_configured": False,
|
|
310
|
+
}},
|
|
311
|
+
})
|
|
312
|
+
)
|
|
313
|
+
config = client.domains.tools.update(
|
|
314
|
+
"shipping-support",
|
|
315
|
+
custom_tools=[{
|
|
316
|
+
"name": "lookup_order", "display_name": "Order Lookup", "description": "Looks up a real order by number",
|
|
317
|
+
"endpoint_url": "https://fernbankoutdoor.com/api/liya-tools/lookup-order", "auth_type": "api_key",
|
|
318
|
+
"auth_value": "sk_live_...",
|
|
319
|
+
}],
|
|
320
|
+
)
|
|
321
|
+
assert config.custom_tools[0].name == "lookup_order"
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
@respx.mock
|
|
325
|
+
def test_domain_tools_test_dispatches_and_returns_response(client):
|
|
326
|
+
respx.post(f"{BASE_URL}/v1/domains/shipping-support/tools/test").mock(
|
|
327
|
+
return_value=httpx.Response(200, json={
|
|
328
|
+
"success": True,
|
|
329
|
+
"data": {"status_code": 200, "ok": True, "body": {"order_status": "shipped", "eta_days": 2}, "latency_ms": 42},
|
|
330
|
+
})
|
|
331
|
+
)
|
|
332
|
+
result = client.domains.tools.test("shipping-support", "lookup_order", {"order_number": "A1092"})
|
|
333
|
+
assert result.status_code == 200
|
|
334
|
+
assert result.body == {"order_status": "shipped", "eta_days": 2}
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
@respx.mock
|
|
338
|
+
def test_domain_tools_test_raises_for_unknown_tool(client):
|
|
339
|
+
respx.post(f"{BASE_URL}/v1/domains/shipping-support/tools/test").mock(
|
|
340
|
+
return_value=httpx.Response(404, json={
|
|
341
|
+
"success": False,
|
|
342
|
+
"error": {"code": "TOOL_NOT_FOUND", "message": "Custom tool 'does-not-exist' not found."},
|
|
343
|
+
})
|
|
344
|
+
)
|
|
345
|
+
with pytest.raises(LiyaEngineAPIError) as exc_info:
|
|
346
|
+
client.domains.tools.test("shipping-support", "does-not-exist")
|
|
347
|
+
assert exc_info.value.code == "TOOL_NOT_FOUND"
|
|
348
|
+
assert exc_info.value.status == 404
|
|
@@ -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
|