liyagent 0.2.0__py3-none-any.whl
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.
- liyagent/__init__.py +15 -0
- liyagent/_transport.py +225 -0
- liyagent/_version.py +3 -0
- liyagent/client.py +78 -0
- liyagent/models.py +147 -0
- liyagent/py.typed +0 -0
- liyagent/resources.py +338 -0
- liyagent-0.2.0.dist-info/METADATA +126 -0
- liyagent-0.2.0.dist-info/RECORD +12 -0
- liyagent-0.2.0.dist-info/WHEEL +5 -0
- liyagent-0.2.0.dist-info/licenses/LICENSE +202 -0
- liyagent-0.2.0.dist-info/top_level.txt +1 -0
liyagent/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Liyagent's Python SDK: agents, runs, evals, knowledge, approvals and
|
|
2
|
+
solution templates over the public API.
|
|
3
|
+
|
|
4
|
+
from liyagent import Client
|
|
5
|
+
liya = Client("https://acme.liyagent.com", token="svc/ci:...")
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from . import models
|
|
9
|
+
from ._transport import LiyagentError
|
|
10
|
+
from ._version import __version__
|
|
11
|
+
from .client import Client, missing_operations
|
|
12
|
+
from .resources import OPERATIONS
|
|
13
|
+
|
|
14
|
+
__all__ = ["Client", "LiyagentError", "OPERATIONS", "missing_operations", "models",
|
|
15
|
+
"__version__"]
|
liyagent/_transport.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""The one HTTP path every SDK call takes: credentials, errors, the server's
|
|
2
|
+
OpenAPI document.
|
|
3
|
+
|
|
4
|
+
The behaviour is the `liya` CLI's (ticketiq/cli/client.py and tiq.py), kept
|
|
5
|
+
in step by a test that runs both over the same responses
|
|
6
|
+
(tests/unit/test_sdk_python.py) rather than by importing them: the SDK is
|
|
7
|
+
installed on its own, by people who never install the server.
|
|
8
|
+
|
|
9
|
+
* Credentials, highest first: ``token=`` (or ``LIYA_TOKEN`` /
|
|
10
|
+
``TICKETIQ_TOKEN``), then ``username=``/``password=`` (a console sign-in).
|
|
11
|
+
A service account's client credentials, ``svc/<name>:<secret>``, are
|
|
12
|
+
exchanged for a one-hour session (POST /api/service-accounts/token) on
|
|
13
|
+
first use, and again when that session expires (a 401 on a session the
|
|
14
|
+
SDK minted is retried once on a new one, as is a sign-in's); any other
|
|
15
|
+
token is sent as a bearer as it is.
|
|
16
|
+
* ``api_key=`` is the instance API key or an inbound client's token, sent as
|
|
17
|
+
X-API-Key, for the machine surface (POST /api/answer).
|
|
18
|
+
* A refusal is a LiyagentError carrying the status, the server's reason —
|
|
19
|
+
a bundle's or a template's {message, at} kept whole — and its kind: 401
|
|
20
|
+
and 403 told apart, as the CLI tells them apart.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
from typing import Any
|
|
28
|
+
from urllib.parse import quote
|
|
29
|
+
|
|
30
|
+
from ._version import __version__
|
|
31
|
+
|
|
32
|
+
USER_AGENT = f"liyagent-python/{__version__}"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class LiyagentError(RuntimeError):
|
|
36
|
+
"""A request the server refused, or could not be made.
|
|
37
|
+
|
|
38
|
+
`status` is the HTTP status (0 when the server was not reached), `detail`
|
|
39
|
+
the server's own answer (a string, or an object such as {message, at}),
|
|
40
|
+
and `kind` one of: "auth" (401: sign in again), "forbidden" (403: a
|
|
41
|
+
permission is missing), "not_found", "invalid" (400, 422), "conflict"
|
|
42
|
+
(409, 412), "unreachable" or "error"."""
|
|
43
|
+
|
|
44
|
+
def __init__(self, message: str, *, status: int = 0, detail: Any = None,
|
|
45
|
+
kind: str = "error") -> None:
|
|
46
|
+
super().__init__(message)
|
|
47
|
+
self.status = status
|
|
48
|
+
self.detail = detail
|
|
49
|
+
self.kind = kind
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def detail_of(response: Any) -> str:
|
|
53
|
+
"""The server's reason as one line. A bundle's or a template's refusal
|
|
54
|
+
is {message, at} — where in the document it was — and both halves are
|
|
55
|
+
the point, so neither is dropped (tiq._detail)."""
|
|
56
|
+
try:
|
|
57
|
+
detail = response.json().get("detail", "")
|
|
58
|
+
except Exception:
|
|
59
|
+
return response.text[:200]
|
|
60
|
+
if isinstance(detail, dict):
|
|
61
|
+
msg = str(detail.get("message") or json.dumps(detail, sort_keys=True))
|
|
62
|
+
return msg + (f" (at {detail['at']})" if detail.get("at") else "")
|
|
63
|
+
return str(detail)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _kind(status: int) -> str:
|
|
67
|
+
return {401: "auth", 403: "forbidden", 404: "not_found", 400: "invalid", 422: "invalid",
|
|
68
|
+
409: "conflict", 412: "conflict"}.get(status, "error")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def checked(response: Any, path: str) -> Any:
|
|
72
|
+
"""The JSON of a successful response, or the LiyagentError it is."""
|
|
73
|
+
status = response.status_code
|
|
74
|
+
if status < 400:
|
|
75
|
+
if status == 204 or not response.content:
|
|
76
|
+
return {}
|
|
77
|
+
try:
|
|
78
|
+
return response.json()
|
|
79
|
+
except ValueError:
|
|
80
|
+
return response.text
|
|
81
|
+
try:
|
|
82
|
+
raw = response.json().get("detail")
|
|
83
|
+
except Exception:
|
|
84
|
+
raw = response.text[:200]
|
|
85
|
+
if status == 401:
|
|
86
|
+
msg = (f"{path}: not signed in — the session or token was refused (expired, or its "
|
|
87
|
+
"service account deleted?)")
|
|
88
|
+
elif status == 403:
|
|
89
|
+
why = detail_of(response)
|
|
90
|
+
msg = f"{path}: this account lacks the permission for it" + (f" ({why})" if why else "")
|
|
91
|
+
else:
|
|
92
|
+
msg = f"{path} failed ({status}): {detail_of(response)}"
|
|
93
|
+
raise LiyagentError(msg, status=status, detail=raw, kind=_kind(status))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def segment(value: Any) -> str:
|
|
97
|
+
"""One path segment, quoted whole."""
|
|
98
|
+
return quote(str(value), safe="")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Transport:
|
|
102
|
+
"""An httpx client with the caller's credentials on it, made on first
|
|
103
|
+
use. `http` is the seam: hand in any httpx.Client (or a FastAPI
|
|
104
|
+
TestClient) and the SDK talks through it instead of a socket."""
|
|
105
|
+
|
|
106
|
+
def __init__(self, base_url: str = "", *, token: str = "", username: str = "",
|
|
107
|
+
password: str = "", api_key: str = "", timeout: float = 60.0,
|
|
108
|
+
http: Any = None) -> None:
|
|
109
|
+
self.base_url = (base_url or os.environ.get("LIYA_URL")
|
|
110
|
+
or "http://127.0.0.1:8787").rstrip("/")
|
|
111
|
+
self.token = token or os.environ.get("LIYA_TOKEN") or os.environ.get(
|
|
112
|
+
"TICKETIQ_TOKEN", "")
|
|
113
|
+
self.username, self.password = username, password
|
|
114
|
+
self.api_key = api_key or os.environ.get("LIYA_API_KEY", "")
|
|
115
|
+
self.timeout = timeout
|
|
116
|
+
self._http = http
|
|
117
|
+
self._owned = http is None
|
|
118
|
+
self._bearer: str | None = None
|
|
119
|
+
self._openapi: dict[str, Any] | None = None
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def http(self) -> Any:
|
|
123
|
+
if self._http is None:
|
|
124
|
+
import httpx
|
|
125
|
+
self._http = httpx.Client(base_url=self.base_url, timeout=self.timeout,
|
|
126
|
+
headers={"User-Agent": USER_AGENT})
|
|
127
|
+
return self._http
|
|
128
|
+
|
|
129
|
+
def close(self) -> None:
|
|
130
|
+
if self._http is not None and self._owned:
|
|
131
|
+
self._http.close()
|
|
132
|
+
self._http = None
|
|
133
|
+
|
|
134
|
+
# ---- credentials ----
|
|
135
|
+
|
|
136
|
+
def _exchange(self, token: str) -> str:
|
|
137
|
+
"""A bearer for `token`: a service account's svc/<name>:<secret>
|
|
138
|
+
exchanged for a session, anything else as it is (tiq._bearer)."""
|
|
139
|
+
client_id, sep, secret = token.partition(":")
|
|
140
|
+
if not (sep and client_id.startswith("svc/")):
|
|
141
|
+
return token
|
|
142
|
+
r = self._send("POST", "/api/service-accounts/token", json={
|
|
143
|
+
"grant_type": "client_credentials", "client_id": client_id,
|
|
144
|
+
"client_secret": secret})
|
|
145
|
+
if r.status_code != 200:
|
|
146
|
+
raise LiyagentError(
|
|
147
|
+
f"the service account {client_id!r} was refused ({r.status_code}) — a wrong or "
|
|
148
|
+
"expired secret, a deleted service account, or its account disabled",
|
|
149
|
+
status=r.status_code, kind="auth")
|
|
150
|
+
return r.json()["access_token"]
|
|
151
|
+
|
|
152
|
+
def _login(self) -> str:
|
|
153
|
+
r = self._send("POST", "/api/login",
|
|
154
|
+
json={"username": self.username, "password": self.password})
|
|
155
|
+
if r.status_code != 200:
|
|
156
|
+
raise LiyagentError(f"sign-in failed for {self.username!r} ({r.status_code})",
|
|
157
|
+
status=r.status_code, kind="auth")
|
|
158
|
+
return str((r.json() or {}).get("token") or "")
|
|
159
|
+
|
|
160
|
+
def _minted(self) -> bool:
|
|
161
|
+
"""Whether the bearer is a session the SDK minted itself — from a
|
|
162
|
+
service account's client credentials, or a sign-in — and so one it
|
|
163
|
+
can mint again when it expires. A token given as it is cannot be."""
|
|
164
|
+
if self.token:
|
|
165
|
+
client_id, sep, _ = self.token.partition(":")
|
|
166
|
+
return bool(sep and client_id.startswith("svc/"))
|
|
167
|
+
return bool(self.username and self.password)
|
|
168
|
+
|
|
169
|
+
def bearer(self) -> str:
|
|
170
|
+
if self._bearer is None:
|
|
171
|
+
if self.token:
|
|
172
|
+
self._bearer = self._exchange(self.token)
|
|
173
|
+
elif self.username and self.password:
|
|
174
|
+
self._bearer = self._login()
|
|
175
|
+
else:
|
|
176
|
+
raise LiyagentError("no credentials — pass token= (or set LIYA_TOKEN), or "
|
|
177
|
+
"username= and password=", kind="auth")
|
|
178
|
+
return self._bearer
|
|
179
|
+
|
|
180
|
+
# ---- requests ----
|
|
181
|
+
|
|
182
|
+
def _send(self, method: str, path: str, *, params: dict | None = None, json: Any = None,
|
|
183
|
+
headers: dict | None = None) -> Any:
|
|
184
|
+
try:
|
|
185
|
+
return self.http.request(method, path, params=params or None, json=json,
|
|
186
|
+
headers=headers)
|
|
187
|
+
except LiyagentError:
|
|
188
|
+
raise
|
|
189
|
+
except Exception as e:
|
|
190
|
+
raise LiyagentError(f"cannot reach {self.base_url}: {e.__class__.__name__}: {e}",
|
|
191
|
+
kind="unreachable") from None
|
|
192
|
+
|
|
193
|
+
def request(self, method: str, path: str, *, params: dict | None = None,
|
|
194
|
+
json: Any = None, auth: str = "bearer") -> Any:
|
|
195
|
+
"""`auth` is "bearer" (a person or a service account), "api_key"
|
|
196
|
+
(X-API-Key, the machine surface) or "none"."""
|
|
197
|
+
headers: dict[str, str] = {}
|
|
198
|
+
if auth == "bearer":
|
|
199
|
+
headers["Authorization"] = f"Bearer {self.bearer()}"
|
|
200
|
+
elif auth == "api_key":
|
|
201
|
+
if self.api_key:
|
|
202
|
+
headers["X-API-Key"] = self.api_key
|
|
203
|
+
else:
|
|
204
|
+
headers["Authorization"] = f"Bearer {self.bearer()}"
|
|
205
|
+
# A parameter left unset is left off rather than sent empty.
|
|
206
|
+
query = {k: v for k, v in (params or {}).items() if v not in (None, "", [])}
|
|
207
|
+
response = self._send(method, path, params=query, json=json, headers=headers)
|
|
208
|
+
if response.status_code == 401 and "Authorization" in headers and self._minted():
|
|
209
|
+
# A session the SDK minted lasts an hour (a service account's) or
|
|
210
|
+
# until it is signed out, and a Client may outlive it. A 401 is
|
|
211
|
+
# answered before the route runs, so the request is sent again —
|
|
212
|
+
# once — on a session minted afresh; refused again, it is the
|
|
213
|
+
# caller's 401.
|
|
214
|
+
self._bearer = None
|
|
215
|
+
headers["Authorization"] = f"Bearer {self.bearer()}"
|
|
216
|
+
response = self._send(method, path, params=query, json=json, headers=headers)
|
|
217
|
+
return checked(response, path)
|
|
218
|
+
|
|
219
|
+
# ---- what the server serves ----
|
|
220
|
+
|
|
221
|
+
def openapi(self) -> dict[str, Any]:
|
|
222
|
+
if self._openapi is None:
|
|
223
|
+
r = self._send("GET", "/openapi.json")
|
|
224
|
+
self._openapi = r.json() if r.status_code == 200 else {}
|
|
225
|
+
return self._openapi
|
liyagent/_version.py
ADDED
liyagent/client.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""The Client: one object per Liyagent instance, a namespace per resource.
|
|
2
|
+
|
|
3
|
+
from liyagent import Client
|
|
4
|
+
|
|
5
|
+
with Client("https://acme.liyagent.com", token="svc/ci:...") as liya:
|
|
6
|
+
for t in liya.templates.list(solution="itsm"):
|
|
7
|
+
print(t["key"], t["version"])
|
|
8
|
+
plan = liya.templates.preview("it-ticket-triage", agent_id="desk-triage")
|
|
9
|
+
if plan["valid"]:
|
|
10
|
+
liya.templates.install("it-ticket-triage", agent_id="desk-triage")
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from ._transport import Transport
|
|
19
|
+
from .resources import (OPERATIONS, Agents, Approvals, Evals, Knowledge, Runs, Templates)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _matches(template: str, served: str) -> bool:
|
|
23
|
+
"""Whether two OpenAPI path templates name one route: the same segments,
|
|
24
|
+
a placeholder matching a placeholder whatever its name."""
|
|
25
|
+
a, b = template.strip("/").split("/"), served.strip("/").split("/")
|
|
26
|
+
var = re.compile(r"^\{[^}]+\}$")
|
|
27
|
+
return len(a) == len(b) and all(x == y or (var.match(x) and var.match(y))
|
|
28
|
+
for x, y in zip(a, b))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def missing_operations(spec: dict[str, Any]) -> list[str]:
|
|
32
|
+
"""The SDK operations an OpenAPI document does not serve, as
|
|
33
|
+
"METHOD /path" — empty when the server has every one."""
|
|
34
|
+
paths = spec.get("paths") or {}
|
|
35
|
+
out = []
|
|
36
|
+
for method, template in OPERATIONS:
|
|
37
|
+
if not any(_matches(template, p) and method.lower() in ops
|
|
38
|
+
for p, ops in paths.items()):
|
|
39
|
+
out.append(f"{method} {template}")
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Client:
|
|
44
|
+
"""A Liyagent instance. Credentials as Transport takes them: `token`
|
|
45
|
+
(a session, or a service account's svc/<name>:<secret>), or `username`
|
|
46
|
+
and `password`; `api_key` for the machine surface (knowledge.answer).
|
|
47
|
+
`http` is any httpx.Client to talk through instead of a socket."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, base_url: str = "", *, token: str = "", username: str = "",
|
|
50
|
+
password: str = "", api_key: str = "", timeout: float = 60.0,
|
|
51
|
+
http: Any = None) -> None:
|
|
52
|
+
self.transport = Transport(base_url, token=token, username=username,
|
|
53
|
+
password=password, api_key=api_key, timeout=timeout,
|
|
54
|
+
http=http)
|
|
55
|
+
self.agents = Agents(self.transport)
|
|
56
|
+
self.runs = Runs(self.transport)
|
|
57
|
+
self.evals = Evals(self.transport)
|
|
58
|
+
self.knowledge = Knowledge(self.transport)
|
|
59
|
+
self.approvals = Approvals(self.transport)
|
|
60
|
+
self.templates = Templates(self.transport)
|
|
61
|
+
|
|
62
|
+
def request(self, method: str, path: str, **kw: Any) -> Any:
|
|
63
|
+
"""Any other route, with the same credentials and errors."""
|
|
64
|
+
return self.transport.request(method, path, **kw)
|
|
65
|
+
|
|
66
|
+
def check_server(self) -> list[str]:
|
|
67
|
+
"""The operations this SDK uses that the server does not serve (an
|
|
68
|
+
older release): empty when every call here will find its route."""
|
|
69
|
+
return missing_operations(self.transport.openapi())
|
|
70
|
+
|
|
71
|
+
def close(self) -> None:
|
|
72
|
+
self.transport.close()
|
|
73
|
+
|
|
74
|
+
def __enter__(self) -> "Client":
|
|
75
|
+
return self
|
|
76
|
+
|
|
77
|
+
def __exit__(self, *exc: Any) -> None:
|
|
78
|
+
self.close()
|
liyagent/models.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Typed request bodies for the Liyagent API.
|
|
2
|
+
|
|
3
|
+
Generated by sdk/scripts/generate_models.py from the server's OpenAPI document.
|
|
4
|
+
Do not edit by hand.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any, Literal, TypedDict
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AnswerBody(TypedDict, total=False):
|
|
13
|
+
query: str
|
|
14
|
+
top_k: int | None
|
|
15
|
+
requester: str
|
|
16
|
+
conversation_id: str
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ApprovalDecisionBody(TypedDict, total=False):
|
|
20
|
+
reason: str
|
|
21
|
+
digest: str
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class BundleApplyBody(TypedDict, total=False):
|
|
25
|
+
bundle: dict[str, Any] # required
|
|
26
|
+
dry_run: bool
|
|
27
|
+
reason: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class EvalDatasetBody(TypedDict, total=False):
|
|
31
|
+
name: str # required
|
|
32
|
+
kind: str # required
|
|
33
|
+
items: list[Any] | None
|
|
34
|
+
jsonl: str | None
|
|
35
|
+
description: str | None
|
|
36
|
+
append: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class EvalOfflineRunBody(TypedDict, total=False):
|
|
40
|
+
dataset: str # required
|
|
41
|
+
version: int | None
|
|
42
|
+
agent: str
|
|
43
|
+
split: str
|
|
44
|
+
evaluators: list[Any] | None
|
|
45
|
+
baseline: str
|
|
46
|
+
allowed_drop: float | None
|
|
47
|
+
allowed_drops: dict[str, float] | None
|
|
48
|
+
variant: dict[str, Any] | None
|
|
49
|
+
model: str
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class GatewayAgentBody(TypedDict, total=False):
|
|
53
|
+
label: str | None
|
|
54
|
+
about: str | None
|
|
55
|
+
enabled: bool | None
|
|
56
|
+
tags: list[str] | None
|
|
57
|
+
prompt: str | None
|
|
58
|
+
runtime: str | None
|
|
59
|
+
reason: str | None
|
|
60
|
+
exchange_only: bool | None
|
|
61
|
+
uid: str | None
|
|
62
|
+
display_name: str | None
|
|
63
|
+
description: str | None
|
|
64
|
+
managed: dict[str, Any] | None
|
|
65
|
+
update_mask: list[str] | str | None
|
|
66
|
+
invoke_access: list[str] | None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class KBRejectBody(TypedDict, total=False):
|
|
70
|
+
reason: str
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class PlaygroundBody(TypedDict, total=False):
|
|
74
|
+
message: str
|
|
75
|
+
system: str
|
|
76
|
+
session: str
|
|
77
|
+
ticket: str
|
|
78
|
+
provider: str
|
|
79
|
+
model: str
|
|
80
|
+
effort: str
|
|
81
|
+
files: list[str]
|
|
82
|
+
support_grant: str
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ReasonBody(TypedDict, total=False):
|
|
86
|
+
reason: str
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class RunResumeBody(TypedDict, total=False):
|
|
90
|
+
answer: Any
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class TemplateDocBody(TypedDict, total=False):
|
|
94
|
+
template: dict[str, Any] # required
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class TemplateFromAgentBody(TypedDict, total=False):
|
|
98
|
+
agent: str # required
|
|
99
|
+
workflow: str
|
|
100
|
+
key: str
|
|
101
|
+
title: str
|
|
102
|
+
solution: str
|
|
103
|
+
version: str
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class TemplateInstallBody(TypedDict, total=False):
|
|
107
|
+
agent_id: str
|
|
108
|
+
provider: str
|
|
109
|
+
model: str
|
|
110
|
+
tags: list[str]
|
|
111
|
+
enable_triggers: bool
|
|
112
|
+
reason: str
|
|
113
|
+
params: dict[str, Any]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class TemplateUninstallBody(TypedDict, total=False):
|
|
117
|
+
reason: str
|
|
118
|
+
keep_guardrails: bool
|
|
119
|
+
dry_run: bool
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class WorkflowRunBody(TypedDict, total=False):
|
|
123
|
+
input: dict[str, Any]
|
|
124
|
+
version: int | None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# The body each operation takes, by (method, path) as OPERATIONS lists it.
|
|
128
|
+
REQUEST_BODIES: dict[tuple[str, str], str] = {
|
|
129
|
+
("PUT", "/api/gateway/agents/{agent_id}"): "GatewayAgentBody",
|
|
130
|
+
("DELETE", "/api/gateway/agents/{agent_id}"): "ReasonBody",
|
|
131
|
+
("POST", "/api/agents/apply"): "BundleApplyBody",
|
|
132
|
+
("POST", "/api/agents/{key}/playground"): "PlaygroundBody",
|
|
133
|
+
("POST", "/api/agents/{key}/workflows/{name}/runs"): "WorkflowRunBody",
|
|
134
|
+
("POST", "/api/runs/{run_id}/resume"): "RunResumeBody",
|
|
135
|
+
("POST", "/api/evals/datasets"): "EvalDatasetBody",
|
|
136
|
+
("POST", "/api/evals/runs"): "EvalOfflineRunBody",
|
|
137
|
+
("POST", "/api/answer"): "AnswerBody",
|
|
138
|
+
("POST", "/api/kb/articles/{article_id}/reject"): "KBRejectBody",
|
|
139
|
+
("POST", "/api/approvals/{approval_id}/approve"): "ApprovalDecisionBody",
|
|
140
|
+
("POST", "/api/approvals/{approval_id}/reject"): "ApprovalDecisionBody",
|
|
141
|
+
("POST", "/api/templates/{key}/preview"): "TemplateInstallBody",
|
|
142
|
+
("POST", "/api/templates/{key}/install"): "TemplateInstallBody",
|
|
143
|
+
("DELETE", "/api/template-installs/{agent}"): "TemplateUninstallBody",
|
|
144
|
+
("POST", "/api/template-authoring/validate"): "TemplateDocBody",
|
|
145
|
+
("POST", "/api/template-authoring/from-agent"): "TemplateFromAgentBody",
|
|
146
|
+
("PUT", "/api/template-authoring/{key}/versions/{version}"): "TemplateDocBody",
|
|
147
|
+
}
|
liyagent/py.typed
ADDED
|
File without changes
|
liyagent/resources.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""The resources a Client exposes, one class each, over the public API.
|
|
2
|
+
|
|
3
|
+
Every method is one request (Evals.wait polls one), named for what it does,
|
|
4
|
+
and returns the server's JSON as it is: the SDK adds no model of its own
|
|
5
|
+
that could drift from the server's. The (method, path) each one uses is in
|
|
6
|
+
OPERATIONS, which a test checks against the server's OpenAPI document and
|
|
7
|
+
Client.check_server() checks against a live one.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any, Iterator
|
|
14
|
+
|
|
15
|
+
from ._transport import LiyagentError, Transport, segment as q
|
|
16
|
+
from .models import TemplateFromAgentBody, TemplateInstallBody
|
|
17
|
+
|
|
18
|
+
# Every operation the SDK calls: (method, path template). Kept beside the
|
|
19
|
+
# methods that use them, and checked against the server's OpenAPI document,
|
|
20
|
+
# so a route renamed on the server fails a test rather than a customer.
|
|
21
|
+
OPERATIONS: tuple[tuple[str, str], ...] = (
|
|
22
|
+
("GET", "/api/gateway/agents"),
|
|
23
|
+
("GET", "/api/gateway/agents/{agent_id}"),
|
|
24
|
+
("PUT", "/api/gateway/agents/{agent_id}"),
|
|
25
|
+
("DELETE", "/api/gateway/agents/{agent_id}"),
|
|
26
|
+
("GET", "/api/agents/{key}/export"),
|
|
27
|
+
("POST", "/api/agents/apply"),
|
|
28
|
+
("POST", "/api/agents/{key}/playground"),
|
|
29
|
+
("POST", "/api/agents/{key}/start"),
|
|
30
|
+
("POST", "/api/agents/{key}/stop"),
|
|
31
|
+
("GET", "/api/agents/{key}/workflows"),
|
|
32
|
+
("POST", "/api/agents/{key}/workflows/{name}/runs"),
|
|
33
|
+
("GET", "/api/agents/{key}/workflow-runs/{run_id}"),
|
|
34
|
+
("GET", "/api/runs"),
|
|
35
|
+
("GET", "/api/runs/{run_id}/checkpoint"),
|
|
36
|
+
("POST", "/api/runs/{run_id}/resume"),
|
|
37
|
+
("GET", "/api/evals/datasets"),
|
|
38
|
+
("POST", "/api/evals/datasets"),
|
|
39
|
+
("GET", "/api/evals/datasets/{name}"),
|
|
40
|
+
("POST", "/api/evals/runs"),
|
|
41
|
+
("GET", "/api/evals/runs"),
|
|
42
|
+
("GET", "/api/evals/runs/{run_id}"),
|
|
43
|
+
("GET", "/api/evals/runs/{run_id}/compare"),
|
|
44
|
+
("POST", "/api/answer"),
|
|
45
|
+
("GET", "/api/collections"),
|
|
46
|
+
("GET", "/api/kb/articles"),
|
|
47
|
+
("POST", "/api/kb/articles/{article_id}/approve"),
|
|
48
|
+
("POST", "/api/kb/articles/{article_id}/reject"),
|
|
49
|
+
("GET", "/api/approvals"),
|
|
50
|
+
("GET", "/api/approvals/{approval_id}"),
|
|
51
|
+
("POST", "/api/approvals/{approval_id}/approve"),
|
|
52
|
+
("POST", "/api/approvals/{approval_id}/reject"),
|
|
53
|
+
("GET", "/api/templates"),
|
|
54
|
+
("GET", "/api/templates/{key}"),
|
|
55
|
+
("POST", "/api/templates/{key}/preview"),
|
|
56
|
+
("POST", "/api/templates/{key}/install"),
|
|
57
|
+
("GET", "/api/template-installs"),
|
|
58
|
+
("DELETE", "/api/template-installs/{agent}"),
|
|
59
|
+
("GET", "/api/template-authoring"),
|
|
60
|
+
("GET", "/api/template-authoring/{key}"),
|
|
61
|
+
("POST", "/api/template-authoring/validate"),
|
|
62
|
+
("POST", "/api/template-authoring/from-agent"),
|
|
63
|
+
("PUT", "/api/template-authoring/{key}/versions/{version}"),
|
|
64
|
+
("POST", "/api/template-authoring/{key}/versions/{version}/publish"),
|
|
65
|
+
("DELETE", "/api/template-authoring/{key}/versions/{version}"),
|
|
66
|
+
("DELETE", "/api/template-authoring/{key}"),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class _Resource:
|
|
71
|
+
def __init__(self, t: Transport) -> None:
|
|
72
|
+
self._t = t
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Agents(_Resource):
|
|
76
|
+
"""Agents in the registry: list, read, create or change, delete; their
|
|
77
|
+
bundle (agents as code); ask one a question; run one of its workflows."""
|
|
78
|
+
|
|
79
|
+
def list(self, *, filter: str = "", page_size: int = 100) -> Iterator[dict[str, Any]]:
|
|
80
|
+
"""Every agent the caller may see, following the pages. `filter` is
|
|
81
|
+
the server's AIP-160 filter (e.g. 'runtime = "managed"')."""
|
|
82
|
+
token = ""
|
|
83
|
+
while True:
|
|
84
|
+
page = self._t.request("GET", "/api/gateway/agents", params={
|
|
85
|
+
"filter": filter, "page_size": page_size, "page_token": token})
|
|
86
|
+
yield from page.get("agents") or []
|
|
87
|
+
token = page.get("next_page_token") or ""
|
|
88
|
+
if not token:
|
|
89
|
+
return
|
|
90
|
+
|
|
91
|
+
def get(self, agent_id: str) -> dict[str, Any]:
|
|
92
|
+
return self._t.request("GET", f"/api/gateway/agents/{q(agent_id)}")
|
|
93
|
+
|
|
94
|
+
def put(self, agent_id: str, **fields: Any) -> dict[str, Any]:
|
|
95
|
+
"""Create the agent, or change the fields given (label, about, tags,
|
|
96
|
+
runtime, enabled...)."""
|
|
97
|
+
return self._t.request("PUT", f"/api/gateway/agents/{q(agent_id)}", json=fields)
|
|
98
|
+
|
|
99
|
+
def delete(self, agent_id: str, *, reason: str = "") -> dict[str, Any]:
|
|
100
|
+
return self._t.request("DELETE", f"/api/gateway/agents/{q(agent_id)}",
|
|
101
|
+
json={"reason": reason})
|
|
102
|
+
|
|
103
|
+
def export(self, agent_id: str, *, sections: list[str] | None = None) -> dict[str, Any]:
|
|
104
|
+
"""The agent as a bundle: what POST /agents/apply takes back."""
|
|
105
|
+
return self._t.request("GET", f"/api/agents/{q(agent_id)}/export",
|
|
106
|
+
params={"sections": ",".join(sections or [])})
|
|
107
|
+
|
|
108
|
+
def apply(self, bundle: dict[str, Any], *, dry_run: bool = False,
|
|
109
|
+
reason: str = "") -> dict[str, Any]:
|
|
110
|
+
"""Apply a bundle (or an AgentBundleList): the plan per section, and
|
|
111
|
+
with dry_run nothing written."""
|
|
112
|
+
return self._t.request("POST", "/api/agents/apply",
|
|
113
|
+
json={"bundle": bundle, "dry_run": dry_run, "reason": reason})
|
|
114
|
+
|
|
115
|
+
def ask(self, agent_id: str, message: str, *, session: str = "",
|
|
116
|
+
**options: Any) -> dict[str, Any]:
|
|
117
|
+
"""One prompt through the agent as production runs it — its
|
|
118
|
+
guardrails, tools, approvals and budget — and its answer."""
|
|
119
|
+
return self._t.request("POST", f"/api/agents/{q(agent_id)}/playground",
|
|
120
|
+
json={"message": message, "session": session, **options})
|
|
121
|
+
|
|
122
|
+
def start(self, agent_id: str) -> dict[str, Any]:
|
|
123
|
+
return self._t.request("POST", f"/api/agents/{q(agent_id)}/start")
|
|
124
|
+
|
|
125
|
+
def stop(self, agent_id: str) -> dict[str, Any]:
|
|
126
|
+
return self._t.request("POST", f"/api/agents/{q(agent_id)}/stop")
|
|
127
|
+
|
|
128
|
+
def workflows(self, agent_id: str) -> list[dict[str, Any]]:
|
|
129
|
+
return self._t.request("GET", f"/api/agents/{q(agent_id)}/workflows")["workflows"]
|
|
130
|
+
|
|
131
|
+
def run_workflow(self, agent_id: str, name: str, input: dict[str, Any] | None = None, *,
|
|
132
|
+
version: int | None = None) -> dict[str, Any]:
|
|
133
|
+
"""Run a workflow to its end or its first wait (an approval)."""
|
|
134
|
+
return self._t.request("POST", f"/api/agents/{q(agent_id)}/workflows/{q(name)}/runs",
|
|
135
|
+
json={"input": input or {}, "version": version})
|
|
136
|
+
|
|
137
|
+
def workflow_run(self, agent_id: str, run_id: str) -> dict[str, Any]:
|
|
138
|
+
return self._t.request("GET", f"/api/agents/{q(agent_id)}/workflow-runs/{q(run_id)}")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class Runs(_Resource):
|
|
142
|
+
"""Agent runs: the recent ones, a suspended one's checkpoint, resuming it."""
|
|
143
|
+
|
|
144
|
+
def list(self, *, limit: int = 50) -> list[dict[str, Any]]:
|
|
145
|
+
return self._t.request("GET", "/api/runs", params={"limit": limit})["runs"]
|
|
146
|
+
|
|
147
|
+
def checkpoint(self, run_id: str) -> dict[str, Any]:
|
|
148
|
+
return self._t.request("GET", f"/api/runs/{q(run_id)}/checkpoint")
|
|
149
|
+
|
|
150
|
+
def resume(self, run_id: str, answer: Any = None) -> dict[str, Any]:
|
|
151
|
+
"""Resume a run waiting for input (`answer`) or a connection."""
|
|
152
|
+
return self._t.request("POST", f"/api/runs/{q(run_id)}/resume",
|
|
153
|
+
json={"answer": answer} if answer is not None else {})
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class Evals(_Resource):
|
|
157
|
+
"""Eval datasets (versioned, immutable) and the runs scored on them."""
|
|
158
|
+
|
|
159
|
+
def datasets(self, *, kind: str = "") -> list[dict[str, Any]]:
|
|
160
|
+
return self._t.request("GET", "/api/evals/datasets", params={"kind": kind})["datasets"]
|
|
161
|
+
|
|
162
|
+
def dataset(self, name: str, *, version: int | None = None,
|
|
163
|
+
items: bool = True) -> dict[str, Any]:
|
|
164
|
+
return self._t.request("GET", f"/api/evals/datasets/{q(name)}",
|
|
165
|
+
params={"version": version, "items": str(items).lower()})
|
|
166
|
+
|
|
167
|
+
def create_dataset(self, name: str, kind: str, items: list[dict[str, Any]], *,
|
|
168
|
+
description: str | None = None, append: bool = False) -> dict[str, Any]:
|
|
169
|
+
"""Write the dataset's next version (version 1 of a new one); items
|
|
170
|
+
equal to the latest version's write nothing (`unchanged`)."""
|
|
171
|
+
body: dict[str, Any] = {"name": name, "kind": kind, "items": items, "append": append}
|
|
172
|
+
if description is not None:
|
|
173
|
+
body["description"] = description
|
|
174
|
+
return self._t.request("POST", "/api/evals/datasets", json=body)
|
|
175
|
+
|
|
176
|
+
def start_run(self, dataset: str, agent: str = "", *, version: int | None = None,
|
|
177
|
+
split: str = "", evaluators: list[str] | None = None,
|
|
178
|
+
baseline: str = "", allowed_drop: float | None = None) -> dict[str, Any]:
|
|
179
|
+
"""Score a dataset version, as a background job; poll with run() or
|
|
180
|
+
wait()."""
|
|
181
|
+
body: dict[str, Any] = {"dataset": dataset, "agent": agent, "version": version,
|
|
182
|
+
"split": split, "evaluators": evaluators,
|
|
183
|
+
"baseline": baseline, "allowed_drop": allowed_drop}
|
|
184
|
+
return self._t.request("POST", "/api/evals/runs",
|
|
185
|
+
json={k: v for k, v in body.items() if v not in (None, "")})
|
|
186
|
+
|
|
187
|
+
def runs(self, *, dataset: str = "", agent: str = "", limit: int = 50
|
|
188
|
+
) -> list[dict[str, Any]]:
|
|
189
|
+
return self._t.request("GET", "/api/evals/runs",
|
|
190
|
+
params={"dataset": dataset, "agent": agent, "limit": limit})["runs"]
|
|
191
|
+
|
|
192
|
+
def run(self, run_id: str) -> dict[str, Any]:
|
|
193
|
+
return self._t.request("GET", f"/api/evals/runs/{q(run_id)}")
|
|
194
|
+
|
|
195
|
+
def compare(self, run_id: str, *, baseline: str = "pinned") -> dict[str, Any]:
|
|
196
|
+
return self._t.request("GET", f"/api/evals/runs/{q(run_id)}/compare",
|
|
197
|
+
params={"baseline": baseline})
|
|
198
|
+
|
|
199
|
+
def wait(self, run_id: str, *, timeout: float = 600.0, every: float = 2.0
|
|
200
|
+
) -> dict[str, Any]:
|
|
201
|
+
"""Poll a run until it is no longer queued or running."""
|
|
202
|
+
deadline = time.monotonic() + timeout
|
|
203
|
+
while True:
|
|
204
|
+
got = self.run(run_id)
|
|
205
|
+
if str(got.get("status") or "") not in ("queued", "running", "pending"):
|
|
206
|
+
return got
|
|
207
|
+
if time.monotonic() >= deadline:
|
|
208
|
+
raise LiyagentError(f"eval run {run_id} still {got.get('status')} after "
|
|
209
|
+
f"{timeout:.0f}s", kind="error")
|
|
210
|
+
time.sleep(every)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class Knowledge(_Resource):
|
|
214
|
+
"""The knowledge base: answers from it, its collections, and the
|
|
215
|
+
articles drafted from resolved work that wait for a person."""
|
|
216
|
+
|
|
217
|
+
def answer(self, query: str, *, top_k: int | None = None,
|
|
218
|
+
conversation_id: str = "") -> dict[str, Any]:
|
|
219
|
+
"""The closest known answers to a question, without filing a ticket.
|
|
220
|
+
The machine surface: the API key (api_key=) or a client token."""
|
|
221
|
+
return self._t.request("POST", "/api/answer", auth="api_key", json={
|
|
222
|
+
"query": query, "top_k": top_k, "conversation_id": conversation_id})
|
|
223
|
+
|
|
224
|
+
def collections(self) -> Any:
|
|
225
|
+
return self._t.request("GET", "/api/collections")
|
|
226
|
+
|
|
227
|
+
def articles(self, *, status: str = "", limit: int = 50) -> Any:
|
|
228
|
+
return self._t.request("GET", "/api/kb/articles",
|
|
229
|
+
params={"status": status, "limit": limit})
|
|
230
|
+
|
|
231
|
+
def approve_article(self, article_id: str) -> dict[str, Any]:
|
|
232
|
+
return self._t.request("POST", f"/api/kb/articles/{q(article_id)}/approve")
|
|
233
|
+
|
|
234
|
+
def reject_article(self, article_id: str) -> dict[str, Any]:
|
|
235
|
+
return self._t.request("POST", f"/api/kb/articles/{q(article_id)}/reject")
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class Approvals(_Resource):
|
|
239
|
+
"""The approval queue: agent calls held for a person's decision."""
|
|
240
|
+
|
|
241
|
+
def list(self, *, status: str = "", mine: bool = False, limit: int = 100
|
|
242
|
+
) -> list[dict[str, Any]]:
|
|
243
|
+
return self._t.request("GET", "/api/approvals", params={
|
|
244
|
+
"status": status, "mine": "true" if mine else "", "limit": limit})["approvals"]
|
|
245
|
+
|
|
246
|
+
def get(self, approval_id: str) -> dict[str, Any]:
|
|
247
|
+
return self._t.request("GET", f"/api/approvals/{q(approval_id)}")
|
|
248
|
+
|
|
249
|
+
def approve(self, approval_id: str, *, reason: str = "", digest: str = "") -> dict[str, Any]:
|
|
250
|
+
"""Approve once; the held call runs as it was asked for. `digest`,
|
|
251
|
+
given, refuses the decision if the request was edited since."""
|
|
252
|
+
return self._t.request("POST", f"/api/approvals/{q(approval_id)}/approve",
|
|
253
|
+
json={"reason": reason, "digest": digest})
|
|
254
|
+
|
|
255
|
+
def reject(self, approval_id: str, *, reason: str = "", digest: str = "") -> dict[str, Any]:
|
|
256
|
+
return self._t.request("POST", f"/api/approvals/{q(approval_id)}/reject",
|
|
257
|
+
json={"reason": reason, "digest": digest})
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class Templates(_Resource):
|
|
261
|
+
"""Solution templates: install an agent with its guardrails, workflow,
|
|
262
|
+
triggers, eval set and budget in one step."""
|
|
263
|
+
|
|
264
|
+
def list(self, *, solution: str = "") -> list[dict[str, Any]]:
|
|
265
|
+
return self._t.request("GET", "/api/templates",
|
|
266
|
+
params={"solution": solution})["templates"]
|
|
267
|
+
|
|
268
|
+
def get(self, key: str, *, agent_id: str = "") -> dict[str, Any]:
|
|
269
|
+
"""The template whole, and what installing it as `agent_id` writes."""
|
|
270
|
+
return self._t.request("GET", f"/api/templates/{q(key)}",
|
|
271
|
+
params={"agent_id": agent_id})
|
|
272
|
+
|
|
273
|
+
def preview(self, key: str, **options: Any) -> dict[str, Any]:
|
|
274
|
+
"""Every write of an install made and rolled back: the plan, and
|
|
275
|
+
whether (and where) it would be refused. Options as install()."""
|
|
276
|
+
return self._t.request("POST", f"/api/templates/{q(key)}/preview", json=options)
|
|
277
|
+
|
|
278
|
+
def install(self, key: str, *, agent_id: str = "", provider: str = "", model: str = "",
|
|
279
|
+
tags: list[str] | None = None, enable_triggers: bool = False,
|
|
280
|
+
reason: str = "", params: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
281
|
+
"""Install (or, over the agent it installed, upgrade) a template.
|
|
282
|
+
`params` are values for the template's parameters."""
|
|
283
|
+
body: TemplateInstallBody = {
|
|
284
|
+
"agent_id": agent_id, "provider": provider, "model": model,
|
|
285
|
+
"tags": list(tags or []), "enable_triggers": enable_triggers, "reason": reason,
|
|
286
|
+
"params": dict(params or {})}
|
|
287
|
+
return self._t.request("POST", f"/api/templates/{q(key)}/install", json=body)
|
|
288
|
+
|
|
289
|
+
def installs(self) -> list[dict[str, Any]]:
|
|
290
|
+
return self._t.request("GET", "/api/template-installs")["installs"]
|
|
291
|
+
|
|
292
|
+
def uninstall(self, agent_id: str, *, reason: str = "", keep_guardrails: bool = False,
|
|
293
|
+
dry_run: bool = False) -> dict[str, Any]:
|
|
294
|
+
return self._t.request("DELETE", f"/api/template-installs/{q(agent_id)}", json={
|
|
295
|
+
"reason": reason, "keep_guardrails": keep_guardrails, "dry_run": dry_run})
|
|
296
|
+
|
|
297
|
+
# ---- the tenant's own templates (needs templates.write) ----
|
|
298
|
+
|
|
299
|
+
def authored(self) -> list[dict[str, Any]]:
|
|
300
|
+
"""The tenant's own templates, one row per key with its versions."""
|
|
301
|
+
return self._t.request("GET", "/api/template-authoring")["templates"]
|
|
302
|
+
|
|
303
|
+
def authored_versions(self, key: str) -> list[dict[str, Any]]:
|
|
304
|
+
"""Every version of one, newest first, each with its document."""
|
|
305
|
+
return self._t.request("GET", f"/api/template-authoring/{q(key)}")["versions"]
|
|
306
|
+
|
|
307
|
+
def validate(self, template: dict[str, Any]) -> dict[str, Any]:
|
|
308
|
+
"""{ok, problem} against the template schema; nothing is saved."""
|
|
309
|
+
return self._t.request("POST", "/api/template-authoring/validate",
|
|
310
|
+
json={"template": template})
|
|
311
|
+
|
|
312
|
+
def draft_from_agent(self, agent: str, *, workflow: str = "", key: str = "",
|
|
313
|
+
title: str = "", solution: str = "",
|
|
314
|
+
version: str = "1.0.0") -> dict[str, Any]:
|
|
315
|
+
"""A template document drafted from an agent the tenant runs. Not saved."""
|
|
316
|
+
body: TemplateFromAgentBody = {"agent": agent, "workflow": workflow, "key": key,
|
|
317
|
+
"title": title, "solution": solution,
|
|
318
|
+
"version": version}
|
|
319
|
+
return self._t.request("POST", "/api/template-authoring/from-agent", json=body)
|
|
320
|
+
|
|
321
|
+
def save_draft(self, template: dict[str, Any]) -> dict[str, Any]:
|
|
322
|
+
"""Save (or rewrite) the draft version the document names."""
|
|
323
|
+
return self._t.request(
|
|
324
|
+
"PUT", f"/api/template-authoring/{q(template['key'])}/versions/"
|
|
325
|
+
f"{q(template['version'])}", json={"template": template})
|
|
326
|
+
|
|
327
|
+
def publish(self, key: str, version: str) -> dict[str, Any]:
|
|
328
|
+
"""Publish a draft version to the tenant's gallery (immutable after)."""
|
|
329
|
+
return self._t.request(
|
|
330
|
+
"POST", f"/api/template-authoring/{q(key)}/versions/{q(version)}/publish")
|
|
331
|
+
|
|
332
|
+
def delete_draft(self, key: str, version: str) -> dict[str, Any]:
|
|
333
|
+
return self._t.request(
|
|
334
|
+
"DELETE", f"/api/template-authoring/{q(key)}/versions/{q(version)}")
|
|
335
|
+
|
|
336
|
+
def withdraw(self, key: str) -> dict[str, Any]:
|
|
337
|
+
"""Every version out of the gallery; installed agents keep running."""
|
|
338
|
+
return self._t.request("DELETE", f"/api/template-authoring/{q(key)}")
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: liyagent
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Python SDK for Liyagent: agents, runs, evals, knowledge, approvals and solution templates
|
|
5
|
+
Author: Liyagent
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://liyagent.com
|
|
8
|
+
Keywords: liyagent,ai agents,agent platform,itsm,sdk
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: httpx>=0.25
|
|
24
|
+
Provides-Extra: test
|
|
25
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# Liyagent Python SDK
|
|
29
|
+
|
|
30
|
+
A small client for Liyagent's public API: agents, runs, evals, knowledge,
|
|
31
|
+
approvals and solution templates. It depends only on `httpx` and returns the
|
|
32
|
+
server's JSON as it is.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install liyagent # from PyPI, once released
|
|
36
|
+
pip install ./sdk/python # from this repository
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Python 3.10+. Versioned with the package (`liyagent.__version__`); see
|
|
40
|
+
`CHANGELOG.md`.
|
|
41
|
+
|
|
42
|
+
## Sign in
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from liyagent import Client
|
|
46
|
+
|
|
47
|
+
# A service account (what a pipeline uses): exchanged for a one-hour session,
|
|
48
|
+
# and for a new one when it expires.
|
|
49
|
+
liya = Client("https://acme.liyagent.com", token="svc/ci-deployer:...")
|
|
50
|
+
|
|
51
|
+
# A person, as the console signs in.
|
|
52
|
+
liya = Client("https://acme.liyagent.com", username="ana", password="...")
|
|
53
|
+
|
|
54
|
+
# The machine surface (knowledge.answer): the instance API key or a client token.
|
|
55
|
+
liya = Client("https://acme.liyagent.com", api_key="...")
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`LIYA_URL`, `LIYA_TOKEN` (or `TICKETIQ_TOKEN`) and `LIYA_API_KEY` are read
|
|
59
|
+
when the arguments are left out, as the `liya` CLI reads them.
|
|
60
|
+
|
|
61
|
+
## What it covers
|
|
62
|
+
|
|
63
|
+
| Namespace | Calls |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `liya.agents` | `list`, `get`, `put`, `delete`, `export`, `apply` (agents as code), `ask`, `start`, `stop`, `workflows`, `run_workflow`, `workflow_run` |
|
|
66
|
+
| `liya.runs` | `list`, `checkpoint`, `resume` |
|
|
67
|
+
| `liya.evals` | `datasets`, `dataset`, `create_dataset`, `start_run`, `runs`, `run`, `compare`, `wait` |
|
|
68
|
+
| `liya.knowledge` | `answer`, `collections`, `articles`, `approve_article`, `reject_article` |
|
|
69
|
+
| `liya.approvals` | `list`, `get`, `approve`, `reject` |
|
|
70
|
+
| `liya.templates` | `list`, `get`, `preview`, `install` (with `params`), `installs`, `uninstall` |
|
|
71
|
+
| `liya.templates` (authoring, `templates.write`) | `authored`, `authored_versions`, `validate`, `draft_from_agent`, `save_draft`, `publish`, `delete_draft`, `withdraw` |
|
|
72
|
+
|
|
73
|
+
Anything else: `liya.request("GET", "/api/...")`, with the same credentials
|
|
74
|
+
and errors.
|
|
75
|
+
|
|
76
|
+
## Types
|
|
77
|
+
|
|
78
|
+
Request bodies are typed: `liyagent.models` holds a `TypedDict` per body
|
|
79
|
+
(`TemplateInstallBody`, `BundleApplyBody`, …) and `REQUEST_BODIES` maps each
|
|
80
|
+
operation to its body. They are generated from the server's OpenAPI document
|
|
81
|
+
by `sdk/scripts/generate_models.py`, and the server's test suite fails when
|
|
82
|
+
the committed file differs from what the document says. The package ships
|
|
83
|
+
`py.typed`, so mypy and pyright read them. Responses are the server's JSON
|
|
84
|
+
as it is.
|
|
85
|
+
|
|
86
|
+
## Your own templates
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
doc = liya.templates.draft_from_agent("desk-helper", key="desk-answers")["template"]
|
|
90
|
+
doc["params"] = [{"name": "team", "label": "Escalation team", "required": True}]
|
|
91
|
+
doc["agent"]["instructions"] += "\nEscalate to {{ params.team }}."
|
|
92
|
+
assert liya.templates.validate(doc)["ok"]
|
|
93
|
+
liya.templates.save_draft(doc)
|
|
94
|
+
liya.templates.publish("desk-answers", doc["version"])
|
|
95
|
+
liya.templates.install("desk-answers", agent_id="desk-two", params={"team": "Network"})
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Errors
|
|
99
|
+
|
|
100
|
+
A refusal raises `LiyagentError` with `status`, the server's `detail` (for a
|
|
101
|
+
bundle or template refusal, `{message, at}`: where in the document it was)
|
|
102
|
+
and a `kind`: `auth` (401, sign in again), `forbidden` (403, a permission is
|
|
103
|
+
missing), `not_found`, `invalid` (400, 422), `conflict` (409, 412),
|
|
104
|
+
`unreachable` or `error`.
|
|
105
|
+
|
|
106
|
+
## Check the server
|
|
107
|
+
|
|
108
|
+
`liya.check_server()` lists the operations this SDK uses that the server
|
|
109
|
+
does not serve, so a pipeline can stop before it calls a route an older
|
|
110
|
+
release does not have. The same list (`liyagent.OPERATIONS`) is checked
|
|
111
|
+
against the server's OpenAPI document in the server's test suite
|
|
112
|
+
(`tests/unit/test_sdk_python.py`).
|
|
113
|
+
|
|
114
|
+
## Examples
|
|
115
|
+
|
|
116
|
+
- `examples/install_template.py` — preview a template, stop if any part would
|
|
117
|
+
be refused, install it.
|
|
118
|
+
- `examples/eval_gate.py` — score an agent on its eval set and fail a build
|
|
119
|
+
that is worse than the pinned baseline.
|
|
120
|
+
- `examples/approvals_queue.py` — work the approval queue from a terminal.
|
|
121
|
+
|
|
122
|
+
## Releasing
|
|
123
|
+
|
|
124
|
+
See `sdk/RELEASING.md`: a tag `sdk-py-vX.Y.Z` builds and publishes this
|
|
125
|
+
package to PyPI from GitHub Actions (`.github/workflows/sdk-release.yml`)
|
|
126
|
+
by trusted publishing.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
liyagent/__init__.py,sha256=MLqGWZ9K4GA825A3W_b_fmclp31WNBldcztwGY3Ctvc,502
|
|
2
|
+
liyagent/_transport.py,sha256=C7EmD0naaliNt4wt-xWhte4QQoo84CWiC9eUq7BPzvc,9795
|
|
3
|
+
liyagent/_version.py,sha256=lTSvLyQ7UAUF5D-8qqh4U3TYyN4CSl8S4zOauv1Mn-M,104
|
|
4
|
+
liyagent/client.py,sha256=PH7rB5zYwpKeOkLO8ecGlPo8KONMgA5ibSAPPnSy_bI,3198
|
|
5
|
+
liyagent/models.py,sha256=Z0JABNL71soLUZdqbJ0TwhQ4oQ0PRk8QWzsx4snXmZw,3891
|
|
6
|
+
liyagent/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
liyagent/resources.py,sha256=I5alsX5BSGJNBBeFQKh05_yWSr7AM-1Z1mSqNnE-YJE,17148
|
|
8
|
+
liyagent-0.2.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
9
|
+
liyagent-0.2.0.dist-info/METADATA,sha256=rtUkfSY83rHhEU3uk1jTdurg5_zWsZYgQALvBT911v0,5083
|
|
10
|
+
liyagent-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
liyagent-0.2.0.dist-info/top_level.txt,sha256=FjwpGt3cMCag6lgG3lA6rKNBs0bGM8xzWbbwbvBgPK4,9
|
|
12
|
+
liyagent-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
liyagent
|