lexio-sdk 1.0.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.
- lexio/__init__.py +46 -0
- lexio/cache.py +71 -0
- lexio/cli.py +251 -0
- lexio/client.py +618 -0
- lexio/errors.py +41 -0
- lexio/models.py +99 -0
- lexio/retry.py +51 -0
- lexio_sdk-1.0.0.dist-info/METADATA +74 -0
- lexio_sdk-1.0.0.dist-info/RECORD +11 -0
- lexio_sdk-1.0.0.dist-info/WHEEL +4 -0
- lexio_sdk-1.0.0.dist-info/entry_points.txt +2 -0
lexio/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from .client import LexioClient, AsyncLexioClient
|
|
2
|
+
from .models import (
|
|
3
|
+
EntitlementStatus,
|
|
4
|
+
PromptResult,
|
|
5
|
+
PromptEntry,
|
|
6
|
+
RunTestsConfig,
|
|
7
|
+
TestRunResult,
|
|
8
|
+
TestResult,
|
|
9
|
+
EvaluatorScore,
|
|
10
|
+
ComparisonResponse,
|
|
11
|
+
PromptMetadata,
|
|
12
|
+
PaginatedList,
|
|
13
|
+
)
|
|
14
|
+
from .errors import (
|
|
15
|
+
LexioError,
|
|
16
|
+
LexioAuthenticationError,
|
|
17
|
+
LexioRateLimitError,
|
|
18
|
+
LexioQuotaExceededError,
|
|
19
|
+
LexioPromptNotFoundError,
|
|
20
|
+
LexioVariableInterpolationError,
|
|
21
|
+
LexioNetworkError,
|
|
22
|
+
LexioEntitlementError,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"LexioClient",
|
|
27
|
+
"AsyncLexioClient",
|
|
28
|
+
"EntitlementStatus",
|
|
29
|
+
"PromptResult",
|
|
30
|
+
"PromptEntry",
|
|
31
|
+
"RunTestsConfig",
|
|
32
|
+
"TestRunResult",
|
|
33
|
+
"TestResult",
|
|
34
|
+
"EvaluatorScore",
|
|
35
|
+
"ComparisonResponse",
|
|
36
|
+
"PromptMetadata",
|
|
37
|
+
"PaginatedList",
|
|
38
|
+
"LexioError",
|
|
39
|
+
"LexioAuthenticationError",
|
|
40
|
+
"LexioRateLimitError",
|
|
41
|
+
"LexioQuotaExceededError",
|
|
42
|
+
"LexioPromptNotFoundError",
|
|
43
|
+
"LexioVariableInterpolationError",
|
|
44
|
+
"LexioNetworkError",
|
|
45
|
+
"LexioEntitlementError",
|
|
46
|
+
]
|
lexio/cache.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import time
|
|
3
|
+
from typing import NamedTuple
|
|
4
|
+
from .models import PromptResult
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class _Entry(NamedTuple):
|
|
8
|
+
value: PromptResult
|
|
9
|
+
stale_at: float
|
|
10
|
+
expires_at: float
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CacheLookupResult(NamedTuple):
|
|
14
|
+
value: PromptResult
|
|
15
|
+
is_stale: bool
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PromptCache:
|
|
19
|
+
def __init__(self, stale_age_seconds: int = 300, max_age_seconds: int = 86400, max_items: int = 1000):
|
|
20
|
+
self._store: dict[str, _Entry] = {}
|
|
21
|
+
self._stale_age = stale_age_seconds
|
|
22
|
+
self._max_age = max_age_seconds
|
|
23
|
+
self._max_items = max_items
|
|
24
|
+
|
|
25
|
+
def _key(self, slug: str, tag: str | None, version: int | None) -> str:
|
|
26
|
+
return f"{slug}:{tag or 'active'}:{version or 0}"
|
|
27
|
+
|
|
28
|
+
def get(self, slug: str, tag: str | None = None, version: int | None = None) -> CacheLookupResult | None:
|
|
29
|
+
k = self._key(slug, tag, version)
|
|
30
|
+
entry = self._store.get(k)
|
|
31
|
+
if entry is None:
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
now = time.monotonic()
|
|
35
|
+
if now > entry.expires_at:
|
|
36
|
+
del self._store[k]
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
# LRU: Move to end
|
|
40
|
+
del self._store[k]
|
|
41
|
+
self._store[k] = entry
|
|
42
|
+
|
|
43
|
+
return CacheLookupResult(
|
|
44
|
+
value=entry.value,
|
|
45
|
+
is_stale=now > entry.stale_at
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def set(self, slug: str, tag: str | None, version: int | None, value: PromptResult) -> None:
|
|
49
|
+
k = self._key(slug, tag, version)
|
|
50
|
+
|
|
51
|
+
if k in self._store:
|
|
52
|
+
del self._store[k]
|
|
53
|
+
elif len(self._store) >= self._max_items:
|
|
54
|
+
first_key = next(iter(self._store))
|
|
55
|
+
del self._store[first_key]
|
|
56
|
+
|
|
57
|
+
now = time.monotonic()
|
|
58
|
+
self._store[k] = _Entry(
|
|
59
|
+
value=value,
|
|
60
|
+
stale_at=now + self._stale_age,
|
|
61
|
+
expires_at=now + self._max_age
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def invalidate(self, slug: str) -> None:
|
|
65
|
+
prefix = f"{slug}:"
|
|
66
|
+
keys = [k for k in self._store if k.startswith(prefix)]
|
|
67
|
+
for k in keys:
|
|
68
|
+
del self._store[k]
|
|
69
|
+
|
|
70
|
+
def clear(self) -> None:
|
|
71
|
+
self._store.clear()
|
lexio/cli.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
|
|
10
|
+
from .client import LexioClient
|
|
11
|
+
from .models import RunTestsConfig, PromptEntry
|
|
12
|
+
|
|
13
|
+
CREDS_DIR = Path.home() / ".lexio"
|
|
14
|
+
CREDS_FILE = CREDS_DIR / "credentials"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _load_api_key() -> str | None:
|
|
18
|
+
if os.environ.get("LEXIO_API_KEY"):
|
|
19
|
+
return os.environ["LEXIO_API_KEY"]
|
|
20
|
+
if CREDS_FILE.exists():
|
|
21
|
+
try:
|
|
22
|
+
return json.loads(CREDS_FILE.read_text())["api_key"]
|
|
23
|
+
except Exception:
|
|
24
|
+
pass
|
|
25
|
+
return None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _save_api_key(key: str) -> None:
|
|
29
|
+
CREDS_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
30
|
+
CREDS_FILE.write_text(json.dumps({"api_key": key}))
|
|
31
|
+
CREDS_FILE.chmod(0o600)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _client() -> LexioClient:
|
|
35
|
+
key = _load_api_key()
|
|
36
|
+
if not key:
|
|
37
|
+
click.echo("No API key found. Run: lexio login", err=True)
|
|
38
|
+
sys.exit(2)
|
|
39
|
+
return LexioClient(api_key=key)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _print_table(rows: list[list[str]]) -> None:
|
|
43
|
+
if not rows:
|
|
44
|
+
return
|
|
45
|
+
widths = [max(len(str(r[i])) for r in rows) for i in range(len(rows[0]))]
|
|
46
|
+
sep = " ".join("-" * w for w in widths)
|
|
47
|
+
for i, row in enumerate(rows):
|
|
48
|
+
click.echo(" ".join(str(cell).ljust(widths[j]) for j, cell in enumerate(row)))
|
|
49
|
+
if i == 0:
|
|
50
|
+
click.echo(sep)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@click.group()
|
|
54
|
+
def cli() -> None:
|
|
55
|
+
"""Lexio CLI — prompt management and multi-model test runner."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@cli.command()
|
|
59
|
+
def login() -> None:
|
|
60
|
+
"""Save API key to ~/.lexio/credentials."""
|
|
61
|
+
key = click.prompt("Paste your Lexio API key", hide_input=True).strip()
|
|
62
|
+
if not key.startswith("lx_"):
|
|
63
|
+
click.echo("Invalid key format. API keys begin with lx_", err=True)
|
|
64
|
+
sys.exit(2)
|
|
65
|
+
_save_api_key(key)
|
|
66
|
+
click.echo(f"Credentials saved to {CREDS_FILE}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@cli.command()
|
|
70
|
+
def status() -> None:
|
|
71
|
+
"""Show plan, quota, and BYOK status."""
|
|
72
|
+
e = _client().check_entitlement()
|
|
73
|
+
click.echo(f"Plan: {e.plan}")
|
|
74
|
+
click.echo(f"Org: {e.org_id}")
|
|
75
|
+
click.echo(f"Team: {e.team_id or 'n/a'}")
|
|
76
|
+
click.echo(f"BYOK: {'enabled' if e.byok_enabled else 'disabled'}")
|
|
77
|
+
click.echo(f"Remaining: {e.remaining_tokens:,} tokens")
|
|
78
|
+
click.echo(f"Resets: {e.reset_at}")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@cli.command("get-prompt")
|
|
82
|
+
@click.argument("slug")
|
|
83
|
+
@click.option("--tag", default=None, help="Fetch by named tag")
|
|
84
|
+
@click.option("--version", "ver", type=int, default=None, help="Fetch by version number")
|
|
85
|
+
@click.option("--var", "variables", multiple=True, metavar="KEY=VALUE", help="Variable substitution")
|
|
86
|
+
@click.option("--json", "json_output", is_flag=True)
|
|
87
|
+
def get_prompt(slug: str, tag: str | None, ver: int | None, variables: tuple[str, ...], json_output: bool) -> None:
|
|
88
|
+
"""Fetch and print a prompt."""
|
|
89
|
+
vars_dict = {}
|
|
90
|
+
for v in variables:
|
|
91
|
+
k, _, val = v.partition("=")
|
|
92
|
+
vars_dict[k] = val
|
|
93
|
+
|
|
94
|
+
result = _client().get_prompt(slug, tag=tag, version=ver, variables=vars_dict or None)
|
|
95
|
+
if json_output:
|
|
96
|
+
click.echo(json.dumps(result.__dict__, indent=2))
|
|
97
|
+
return
|
|
98
|
+
click.echo(f"slug: {result.slug}")
|
|
99
|
+
click.echo(f"version: {result.version}" + (f" tag: {result.tag}" if result.tag else ""))
|
|
100
|
+
click.echo("")
|
|
101
|
+
click.echo(result.text)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@cli.command("list-prompts")
|
|
105
|
+
@click.option("--tag", "tags", multiple=True, help="Filter by tag")
|
|
106
|
+
@click.option("--json", "json_output", is_flag=True)
|
|
107
|
+
def list_prompts(tags: tuple[str, ...], json_output: bool) -> None:
|
|
108
|
+
"""List available prompts."""
|
|
109
|
+
result = _client().list_prompts(tags=list(tags) or None)
|
|
110
|
+
if json_output:
|
|
111
|
+
click.echo(json.dumps([p.__dict__ for p in result.data], indent=2))
|
|
112
|
+
return
|
|
113
|
+
rows = [["SLUG", "LATEST VERSION", "TAGS", "UPDATED"]]
|
|
114
|
+
for p in result.data:
|
|
115
|
+
rows.append([p.slug, str(p.latest_version), ",".join(p.tags) or "-", p.updated_at[:10]])
|
|
116
|
+
_print_table(rows)
|
|
117
|
+
click.echo(f"\n{result.total} prompt(s)")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@cli.command("run-tests")
|
|
121
|
+
@click.option("--config", "config_file", default=None, help="Path to JSON config file")
|
|
122
|
+
@click.option("--prompt", "prompt_slugs", multiple=True, help="Prompt slug (repeatable)")
|
|
123
|
+
@click.option("--tag", default=None, help="Tag for all --prompt entries")
|
|
124
|
+
@click.option("--model", "model_ids", multiple=True, help="Model ID (repeatable)")
|
|
125
|
+
@click.option("--evaluator", is_flag=True)
|
|
126
|
+
@click.option("--reference", default=None)
|
|
127
|
+
@click.option("--async", "async_mode", is_flag=True)
|
|
128
|
+
@click.option("--wait", is_flag=True)
|
|
129
|
+
@click.option("--output", default=None, help="Write results JSON to file")
|
|
130
|
+
@click.option("--format", "fmt", type=click.Choice(["table", "json"]), default="table")
|
|
131
|
+
@click.option("--max-cost", type=float, default=None)
|
|
132
|
+
def run_tests(
|
|
133
|
+
config_file: str | None,
|
|
134
|
+
prompt_slugs: tuple[str, ...],
|
|
135
|
+
tag: str | None,
|
|
136
|
+
model_ids: tuple[str, ...],
|
|
137
|
+
evaluator: bool,
|
|
138
|
+
reference: str | None,
|
|
139
|
+
async_mode: bool,
|
|
140
|
+
wait: bool,
|
|
141
|
+
output: str | None,
|
|
142
|
+
fmt: str,
|
|
143
|
+
max_cost: float | None,
|
|
144
|
+
) -> None:
|
|
145
|
+
"""Run prompts against models."""
|
|
146
|
+
if config_file:
|
|
147
|
+
cfg = json.loads(Path(config_file).read_text())
|
|
148
|
+
prompts = [PromptEntry(slug=p.get("slug"), tag=p.get("tag"), version=p.get("version"), variables=p.get("variables")) for p in cfg["prompts"]]
|
|
149
|
+
models = cfg["models"]
|
|
150
|
+
evaluator = cfg.get("evaluator", evaluator)
|
|
151
|
+
reference = cfg.get("referenceAnswer", reference)
|
|
152
|
+
else:
|
|
153
|
+
if not prompt_slugs:
|
|
154
|
+
click.echo("--prompt or --config required", err=True)
|
|
155
|
+
sys.exit(1)
|
|
156
|
+
if not model_ids:
|
|
157
|
+
click.echo("--model required", err=True)
|
|
158
|
+
sys.exit(1)
|
|
159
|
+
prompts = [PromptEntry(slug=s, tag=tag) for s in prompt_slugs]
|
|
160
|
+
models = list(model_ids)
|
|
161
|
+
|
|
162
|
+
config = RunTestsConfig(
|
|
163
|
+
prompts=prompts,
|
|
164
|
+
models=models,
|
|
165
|
+
evaluator=evaluator,
|
|
166
|
+
reference_answer=reference,
|
|
167
|
+
async_mode=async_mode or wait,
|
|
168
|
+
max_estimated_cost_usd=max_cost,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
c = _client()
|
|
172
|
+
result = c.run_tests(config)
|
|
173
|
+
|
|
174
|
+
if wait and result.status == "queued":
|
|
175
|
+
click.echo(f"Job queued: {result.run_id}. Waiting for completion...")
|
|
176
|
+
result = c.wait_for_result(result.run_id)
|
|
177
|
+
|
|
178
|
+
if output:
|
|
179
|
+
Path(output).write_text(json.dumps(result.__dict__, indent=2, default=str))
|
|
180
|
+
|
|
181
|
+
if fmt == "json":
|
|
182
|
+
click.echo(json.dumps(result.__dict__, indent=2, default=str))
|
|
183
|
+
return
|
|
184
|
+
|
|
185
|
+
if result.status == "queued":
|
|
186
|
+
click.echo(f"Queued. run_id: {result.run_id}")
|
|
187
|
+
click.echo(f"Use: lexio get-result {result.run_id} --wait")
|
|
188
|
+
return
|
|
189
|
+
|
|
190
|
+
rows = [["PROMPT", "TAG", "MODEL", "SCORE", "TOKENS", "COST"]]
|
|
191
|
+
for r in result.results:
|
|
192
|
+
rows.append([
|
|
193
|
+
r.prompt_slug or "-",
|
|
194
|
+
r.prompt_tag or "-",
|
|
195
|
+
r.model_id,
|
|
196
|
+
f"{r.evaluator_score.composite_score:.2f}" if r.evaluator_score else "-",
|
|
197
|
+
str(r.total_tokens),
|
|
198
|
+
f"${r.estimated_cost_usd:.4f}",
|
|
199
|
+
])
|
|
200
|
+
_print_table(rows)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@cli.command("get-result")
|
|
204
|
+
@click.argument("run_id")
|
|
205
|
+
@click.option("--wait", is_flag=True)
|
|
206
|
+
@click.option("--timeout", "timeout_sec", type=int, default=120)
|
|
207
|
+
@click.option("--format", "fmt", type=click.Choice(["table", "json"]), default="table")
|
|
208
|
+
def get_result(run_id: str, wait: bool, timeout_sec: int, fmt: str) -> None:
|
|
209
|
+
"""Fetch result of an async run."""
|
|
210
|
+
c = _client()
|
|
211
|
+
result = c.get_result(run_id)
|
|
212
|
+
|
|
213
|
+
if wait and result.status in ("queued", "running"):
|
|
214
|
+
click.echo(f"Status: {result.status}. Waiting...")
|
|
215
|
+
result = c.wait_for_result(run_id, timeout=float(timeout_sec))
|
|
216
|
+
|
|
217
|
+
if fmt == "json":
|
|
218
|
+
click.echo(json.dumps(result.__dict__, indent=2, default=str))
|
|
219
|
+
return
|
|
220
|
+
|
|
221
|
+
click.echo(f"Status: {result.status}")
|
|
222
|
+
if not result.results:
|
|
223
|
+
return
|
|
224
|
+
|
|
225
|
+
rows = [["MODEL", "SCORE", "TOKENS", "COST", "LATENCY"]]
|
|
226
|
+
for r in result.results:
|
|
227
|
+
rows.append([
|
|
228
|
+
r.model_id,
|
|
229
|
+
f"{r.evaluator_score.composite_score:.2f}" if r.evaluator_score else "-",
|
|
230
|
+
str(r.total_tokens),
|
|
231
|
+
f"${r.estimated_cost_usd:.4f}",
|
|
232
|
+
f"{r.latency_ms}ms",
|
|
233
|
+
])
|
|
234
|
+
_print_table(rows)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@cli.command("list-comparisons")
|
|
238
|
+
@click.option("--prompt", "prompt_slug", default=None)
|
|
239
|
+
@click.option("--limit", type=int, default=20)
|
|
240
|
+
@click.option("--json", "json_output", is_flag=True)
|
|
241
|
+
def list_comparisons(prompt_slug: str | None, limit: int, json_output: bool) -> None:
|
|
242
|
+
"""List recent comparisons."""
|
|
243
|
+
result = _client().list_comparisons(prompt_slug=prompt_slug, limit=limit)
|
|
244
|
+
if json_output:
|
|
245
|
+
click.echo(json.dumps(result, indent=2))
|
|
246
|
+
return
|
|
247
|
+
click.echo(json.dumps(result, indent=2))
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def main() -> None:
|
|
251
|
+
cli()
|
lexio/client.py
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import time
|
|
5
|
+
import json
|
|
6
|
+
import asyncio
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .cache import PromptCache
|
|
12
|
+
from .errors import (
|
|
13
|
+
LexioAuthenticationError,
|
|
14
|
+
LexioEntitlementError,
|
|
15
|
+
LexioNetworkError,
|
|
16
|
+
LexioPromptNotFoundError,
|
|
17
|
+
LexioQuotaExceededError,
|
|
18
|
+
LexioRateLimitError,
|
|
19
|
+
LexioVariableInterpolationError,
|
|
20
|
+
)
|
|
21
|
+
from .models import (
|
|
22
|
+
ComparisonResponse,
|
|
23
|
+
EntitlementStatus,
|
|
24
|
+
EvaluatorScore,
|
|
25
|
+
PaginatedList,
|
|
26
|
+
PromptEntry,
|
|
27
|
+
PromptMetadata,
|
|
28
|
+
PromptResult,
|
|
29
|
+
RunTestsConfig,
|
|
30
|
+
TestResult,
|
|
31
|
+
TestRunResult,
|
|
32
|
+
)
|
|
33
|
+
from .retry import with_retry, async_with_retry
|
|
34
|
+
|
|
35
|
+
DEFAULT_BASE_URL = "https://api.lexio.studio"
|
|
36
|
+
DEFAULT_CACHE_MAX_AGE = 300
|
|
37
|
+
DEFAULT_ENTITLEMENT_TTL = 60.0
|
|
38
|
+
DEFAULT_TIMEOUT = 30.0
|
|
39
|
+
SDK_VERSION = "1.0.0"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _parse_entitlement(raw: dict[str, Any]) -> EntitlementStatus:
|
|
43
|
+
return EntitlementStatus(
|
|
44
|
+
plan=raw.get("plan", "free"),
|
|
45
|
+
org_id=raw.get("org_id", ""),
|
|
46
|
+
team_id=raw.get("team_id"),
|
|
47
|
+
byok_enabled=raw.get("byok_enabled", False),
|
|
48
|
+
remaining_tokens=raw.get("remaining_tokens", 0),
|
|
49
|
+
reset_at=raw.get("reset_at", ""),
|
|
50
|
+
concurrent_comparisons_allowed=raw.get("concurrent_comparisons_allowed", 1),
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _parse_test_result(r: dict[str, Any]) -> TestResult:
|
|
55
|
+
es = r.get("evaluator_score")
|
|
56
|
+
return TestResult(
|
|
57
|
+
prompt_slug=r.get("prompt_slug"),
|
|
58
|
+
prompt_version_id=r.get("prompt_version_id", ""),
|
|
59
|
+
prompt_tag=r.get("prompt_tag"),
|
|
60
|
+
model_id=r["model_id"],
|
|
61
|
+
output=r.get("output", ""),
|
|
62
|
+
input_tokens=r.get("input_tokens", 0),
|
|
63
|
+
output_tokens=r.get("output_tokens", 0),
|
|
64
|
+
total_tokens=r.get("total_tokens", 0),
|
|
65
|
+
estimated_cost_usd=float(r.get("estimated_cost_usd", 0)),
|
|
66
|
+
latency_ms=r.get("latency_ms", 0),
|
|
67
|
+
evaluator_score=EvaluatorScore(
|
|
68
|
+
composite_score=float(es["composite_score"]),
|
|
69
|
+
component_scores=es.get("component_scores", {}),
|
|
70
|
+
) if es else None,
|
|
71
|
+
error_message=r.get("error_message"),
|
|
72
|
+
invocation_source=r.get("invocation_source", "platform"),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _parse_run_result(raw: dict[str, Any]) -> TestRunResult:
|
|
77
|
+
return TestRunResult(
|
|
78
|
+
run_id=raw["run_id"],
|
|
79
|
+
status=raw["status"],
|
|
80
|
+
results=[_parse_test_result(r) for r in raw.get("results", [])],
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _raise_for_response(res: httpx.Response, path: str) -> None:
|
|
85
|
+
if res.status_code == 401:
|
|
86
|
+
raise LexioAuthenticationError()
|
|
87
|
+
if res.status_code == 402:
|
|
88
|
+
data = res.json() if res.content else {}
|
|
89
|
+
raise LexioQuotaExceededError(data.get("error", "Quota exceeded"), data)
|
|
90
|
+
if res.status_code == 403:
|
|
91
|
+
data = res.json() if res.content else {}
|
|
92
|
+
raise LexioEntitlementError(data.get("error", "Forbidden"))
|
|
93
|
+
if res.status_code == 404:
|
|
94
|
+
raise LexioPromptNotFoundError(path)
|
|
95
|
+
if res.status_code == 429:
|
|
96
|
+
retry_after_ms = int(float(res.headers.get("retry-after", "0")) * 1000)
|
|
97
|
+
raise LexioRateLimitError(retry_after_ms)
|
|
98
|
+
if res.is_error:
|
|
99
|
+
raise LexioNetworkError(f"Lexio API error {res.status_code}: {res.text[:500]}")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class LexioClient:
|
|
103
|
+
"""Synchronous Lexio SDK client."""
|
|
104
|
+
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
api_key: str | None = None,
|
|
108
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
109
|
+
cache: bool = False,
|
|
110
|
+
cache_max_age: int = DEFAULT_CACHE_MAX_AGE,
|
|
111
|
+
entitlement_ttl: float = DEFAULT_ENTITLEMENT_TTL,
|
|
112
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
113
|
+
byok_keys: dict[str, str] | None = None,
|
|
114
|
+
):
|
|
115
|
+
key = api_key or os.environ.get("LEXIO_API_KEY")
|
|
116
|
+
if not key:
|
|
117
|
+
raise ValueError("LEXIO_API_KEY is required. Pass api_key or set the LEXIO_API_KEY env var.")
|
|
118
|
+
self._api_key = key
|
|
119
|
+
self._base_url = base_url.rstrip("/")
|
|
120
|
+
self._timeout = timeout
|
|
121
|
+
self._cache: PromptCache | None = PromptCache(cache_max_age) if cache else None
|
|
122
|
+
self._entitlement_ttl = entitlement_ttl
|
|
123
|
+
self._cached_entitlement: EntitlementStatus | None = None
|
|
124
|
+
self._entitlement_cached_at: float = 0.0
|
|
125
|
+
self._byok_keys: dict[str, str] = byok_keys or {}
|
|
126
|
+
self._http = httpx.Client(
|
|
127
|
+
timeout=timeout,
|
|
128
|
+
headers={
|
|
129
|
+
"x-api-key": key,
|
|
130
|
+
"Content-Type": "application/json",
|
|
131
|
+
"X-Lexio-SDK-Version": SDK_VERSION,
|
|
132
|
+
},
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
def close(self) -> None:
|
|
136
|
+
self._http.close()
|
|
137
|
+
|
|
138
|
+
def __enter__(self) -> "LexioClient":
|
|
139
|
+
return self
|
|
140
|
+
|
|
141
|
+
def __exit__(self, *_: Any) -> None:
|
|
142
|
+
self.close()
|
|
143
|
+
|
|
144
|
+
def _request(
|
|
145
|
+
self,
|
|
146
|
+
method: str,
|
|
147
|
+
path: str,
|
|
148
|
+
body: dict[str, Any] | None = None,
|
|
149
|
+
params: dict[str, str] | None = None,
|
|
150
|
+
) -> Any:
|
|
151
|
+
def _do() -> Any:
|
|
152
|
+
url = f"{self._base_url}{path}"
|
|
153
|
+
try:
|
|
154
|
+
res = self._http.request(method, url, json=body, params=params)
|
|
155
|
+
except httpx.TimeoutException as e:
|
|
156
|
+
raise LexioNetworkError(f"Request timed out: {e}") from e
|
|
157
|
+
except httpx.RequestError as e:
|
|
158
|
+
raise LexioNetworkError(str(e)) from e
|
|
159
|
+
_raise_for_response(res, path)
|
|
160
|
+
return res.json()
|
|
161
|
+
|
|
162
|
+
return with_retry(_do)
|
|
163
|
+
|
|
164
|
+
# ── Public methods ───────────────────────────────────────────────────────
|
|
165
|
+
|
|
166
|
+
def check_entitlement(self, force: bool = False) -> EntitlementStatus:
|
|
167
|
+
if (
|
|
168
|
+
not force
|
|
169
|
+
and self._cached_entitlement
|
|
170
|
+
and (time.monotonic() - self._entitlement_cached_at) < self._entitlement_ttl
|
|
171
|
+
):
|
|
172
|
+
return self._cached_entitlement
|
|
173
|
+
raw = self._request("GET", "/sdk/quotas")
|
|
174
|
+
result = _parse_entitlement(raw)
|
|
175
|
+
self._cached_entitlement = result
|
|
176
|
+
self._entitlement_cached_at = time.monotonic()
|
|
177
|
+
return result
|
|
178
|
+
|
|
179
|
+
def invalidate_entitlement(self) -> None:
|
|
180
|
+
self._cached_entitlement = None
|
|
181
|
+
self._entitlement_cached_at = 0.0
|
|
182
|
+
|
|
183
|
+
def get_prompt(
|
|
184
|
+
self,
|
|
185
|
+
slug: str,
|
|
186
|
+
*,
|
|
187
|
+
tag: str | None = None,
|
|
188
|
+
version: int | None = None,
|
|
189
|
+
variables: dict[str, str] | None = None,
|
|
190
|
+
) -> PromptResult:
|
|
191
|
+
if self._cache:
|
|
192
|
+
cached = self._cache.get(slug, tag, version)
|
|
193
|
+
if cached:
|
|
194
|
+
if cached.is_stale:
|
|
195
|
+
# SWR: Trigger background revalidation (best-effort sync)
|
|
196
|
+
try:
|
|
197
|
+
self._fetch_and_cache_prompt(slug, tag=tag, version=version)
|
|
198
|
+
except Exception:
|
|
199
|
+
pass
|
|
200
|
+
return self._interpolate_prompt(cached.value, variables)
|
|
201
|
+
|
|
202
|
+
result = self._fetch_and_cache_prompt(slug, tag=tag, version=version)
|
|
203
|
+
return self._interpolate_prompt(result, variables)
|
|
204
|
+
|
|
205
|
+
def _fetch_and_cache_prompt(
|
|
206
|
+
self,
|
|
207
|
+
slug: str,
|
|
208
|
+
*,
|
|
209
|
+
tag: str | None = None,
|
|
210
|
+
version: int | None = None,
|
|
211
|
+
) -> PromptResult:
|
|
212
|
+
params: dict[str, str] = {"slug": slug}
|
|
213
|
+
if tag:
|
|
214
|
+
params["tag"] = tag
|
|
215
|
+
if version is not None:
|
|
216
|
+
params["version"] = str(version)
|
|
217
|
+
|
|
218
|
+
raw = self._request("GET", "/sdk/prompts", params=params)
|
|
219
|
+
|
|
220
|
+
result = PromptResult(
|
|
221
|
+
slug=raw["slug"],
|
|
222
|
+
version=raw["version_number"],
|
|
223
|
+
tag=raw.get("label"),
|
|
224
|
+
text=raw.get("template", ""),
|
|
225
|
+
model_hints=[],
|
|
226
|
+
cached_at=None,
|
|
227
|
+
_variables_schema=raw.get("variable_schema", {}),
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
if self._cache:
|
|
231
|
+
self._cache.set(slug, raw.get("label"), raw["version_number"], result)
|
|
232
|
+
|
|
233
|
+
return result
|
|
234
|
+
|
|
235
|
+
def _interpolate_prompt(self, prompt: PromptResult, variables: dict[str, str] | None) -> PromptResult:
|
|
236
|
+
var_schema = prompt._variables_schema
|
|
237
|
+
required = [k for k, v in var_schema.items() if isinstance(v, dict) and v.get("required")]
|
|
238
|
+
missing = [k for k in required if not (variables or {}).get(k)]
|
|
239
|
+
if missing:
|
|
240
|
+
raise LexioVariableInterpolationError(missing)
|
|
241
|
+
|
|
242
|
+
text = prompt.text
|
|
243
|
+
for k, v in (variables or {}).items():
|
|
244
|
+
text = text.replace("{{" + k + "}}", v)
|
|
245
|
+
|
|
246
|
+
# Return a copy with interpolated text
|
|
247
|
+
return PromptResult(
|
|
248
|
+
slug=prompt.slug,
|
|
249
|
+
version=prompt.version,
|
|
250
|
+
tag=prompt.tag,
|
|
251
|
+
text=text,
|
|
252
|
+
model_hints=prompt.model_hints,
|
|
253
|
+
cached_at=prompt.cached_at,
|
|
254
|
+
_variables_schema=prompt._variables_schema
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
def run_tests(self, config: RunTestsConfig) -> TestRunResult:
|
|
258
|
+
merged_byok = {**self._byok_keys, **(config.byok_keys or {})}
|
|
259
|
+
body: dict[str, Any] = {
|
|
260
|
+
"prompts": [
|
|
261
|
+
{
|
|
262
|
+
"slug": p.slug,
|
|
263
|
+
"prompt_version_id": p.prompt_version_id,
|
|
264
|
+
"tag": p.tag,
|
|
265
|
+
"version": p.version,
|
|
266
|
+
"variables": p.variables,
|
|
267
|
+
}
|
|
268
|
+
for p in config.prompts
|
|
269
|
+
],
|
|
270
|
+
"models": config.models,
|
|
271
|
+
"evaluator": config.evaluator,
|
|
272
|
+
"reference_answer": config.reference_answer,
|
|
273
|
+
"async": config.async_mode,
|
|
274
|
+
"idempotency_key": config.idempotency_key,
|
|
275
|
+
"max_estimated_cost_usd": config.max_estimated_cost_usd,
|
|
276
|
+
}
|
|
277
|
+
if merged_byok:
|
|
278
|
+
body["byok_keys"] = merged_byok
|
|
279
|
+
raw = self._request("POST", "/sdk/tests", body=body)
|
|
280
|
+
return _parse_run_result(raw)
|
|
281
|
+
|
|
282
|
+
def get_result(self, run_id: str) -> TestRunResult:
|
|
283
|
+
raw = self._request("GET", f"/sdk/comparisons/{run_id}/result")
|
|
284
|
+
return _parse_run_result(raw)
|
|
285
|
+
|
|
286
|
+
def wait_for_result(
|
|
287
|
+
self,
|
|
288
|
+
run_id: str,
|
|
289
|
+
poll_interval: float = 2.0,
|
|
290
|
+
timeout: float = 120.0,
|
|
291
|
+
) -> TestRunResult:
|
|
292
|
+
deadline = time.monotonic() + timeout
|
|
293
|
+
while time.monotonic() < deadline:
|
|
294
|
+
result = self.get_result(run_id)
|
|
295
|
+
if result.status in ("complete", "failed"):
|
|
296
|
+
return result
|
|
297
|
+
time.sleep(poll_interval)
|
|
298
|
+
raise TimeoutError(f"wait_for_result timed out after {timeout}s for run {run_id}")
|
|
299
|
+
|
|
300
|
+
def submit_comparison(
|
|
301
|
+
self,
|
|
302
|
+
prompt_version_id: str,
|
|
303
|
+
variable_values: dict[str, str],
|
|
304
|
+
model_ids: list[str],
|
|
305
|
+
) -> ComparisonResponse:
|
|
306
|
+
raw = self._request("POST", "/sdk/comparisons", body={
|
|
307
|
+
"prompt_version_id": prompt_version_id,
|
|
308
|
+
"variables": variable_values,
|
|
309
|
+
"model_ids": model_ids,
|
|
310
|
+
})
|
|
311
|
+
return ComparisonResponse(comparison_id=raw["comparison_id"], status=raw["status"])
|
|
312
|
+
|
|
313
|
+
def list_prompts(
|
|
314
|
+
self,
|
|
315
|
+
*,
|
|
316
|
+
tags: list[str] | None = None,
|
|
317
|
+
page: int = 1,
|
|
318
|
+
page_size: int = 20,
|
|
319
|
+
) -> PaginatedList:
|
|
320
|
+
params: dict[str, str] = {"page": str(page), "page_size": str(page_size)}
|
|
321
|
+
if tags:
|
|
322
|
+
params["tags"] = ",".join(tags)
|
|
323
|
+
raw = self._request("GET", "/sdk/prompts", params=params)
|
|
324
|
+
|
|
325
|
+
prompts = []
|
|
326
|
+
for p in raw.get("data", []):
|
|
327
|
+
lv = p.get("latest_version")
|
|
328
|
+
v_num = lv.get("version_number") if isinstance(lv, dict) else 0
|
|
329
|
+
prompts.append(PromptMetadata(
|
|
330
|
+
slug=p["slug"],
|
|
331
|
+
latest_version=v_num,
|
|
332
|
+
tags=p.get("tags", []),
|
|
333
|
+
created_at=p["created_at"],
|
|
334
|
+
updated_at=p.get("updated_at", p["created_at"]),
|
|
335
|
+
))
|
|
336
|
+
|
|
337
|
+
return PaginatedList(
|
|
338
|
+
data=prompts,
|
|
339
|
+
total=raw.get("total", 0),
|
|
340
|
+
page=raw.get("page", page),
|
|
341
|
+
page_size=raw.get("page_size", page_size),
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
def list_comparisons(self, prompt_slug: str | None = None, limit: int = 20) -> list[Any]:
|
|
345
|
+
params: dict[str, str] = {"limit": str(limit)}
|
|
346
|
+
if prompt_slug:
|
|
347
|
+
params["prompt_slug"] = prompt_slug
|
|
348
|
+
raw = self._request("GET", "/sdk/comparisons", params=params)
|
|
349
|
+
return raw.get("data", [])
|
|
350
|
+
|
|
351
|
+
def get_quota_status(self) -> EntitlementStatus:
|
|
352
|
+
return self.check_entitlement(force=True)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
class AsyncLexioClient:
|
|
356
|
+
"""Async Lexio SDK client (asyncio)."""
|
|
357
|
+
|
|
358
|
+
def __init__(
|
|
359
|
+
self,
|
|
360
|
+
api_key: str | None = None,
|
|
361
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
362
|
+
cache: bool = False,
|
|
363
|
+
cache_max_age: int = DEFAULT_CACHE_MAX_AGE,
|
|
364
|
+
entitlement_ttl: float = DEFAULT_ENTITLEMENT_TTL,
|
|
365
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
366
|
+
byok_keys: dict[str, str] | None = None,
|
|
367
|
+
):
|
|
368
|
+
key = api_key or os.environ.get("LEXIO_API_KEY")
|
|
369
|
+
if not key:
|
|
370
|
+
raise ValueError("LEXIO_API_KEY is required.")
|
|
371
|
+
self._api_key = key
|
|
372
|
+
self._base_url = base_url.rstrip("/")
|
|
373
|
+
self._timeout = timeout
|
|
374
|
+
self._cache: PromptCache | None = PromptCache(cache_max_age) if cache else None
|
|
375
|
+
self._entitlement_ttl = entitlement_ttl
|
|
376
|
+
self._cached_entitlement: EntitlementStatus | None = None
|
|
377
|
+
self._entitlement_cached_at: float = 0.0
|
|
378
|
+
self._byok_keys: dict[str, str] = byok_keys or {}
|
|
379
|
+
self._pending_requests: dict[str, asyncio.Future] = {}
|
|
380
|
+
self._http = httpx.AsyncClient(
|
|
381
|
+
timeout=timeout,
|
|
382
|
+
headers={
|
|
383
|
+
"x-api-key": key,
|
|
384
|
+
"Content-Type": "application/json",
|
|
385
|
+
"X-Lexio-SDK-Version": SDK_VERSION,
|
|
386
|
+
},
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
async def aclose(self) -> None:
|
|
390
|
+
await self._http.aclose()
|
|
391
|
+
|
|
392
|
+
async def __aenter__(self) -> "AsyncLexioClient":
|
|
393
|
+
return self
|
|
394
|
+
|
|
395
|
+
async def __aexit__(self, *_: Any) -> None:
|
|
396
|
+
await self.aclose()
|
|
397
|
+
|
|
398
|
+
async def _request(
|
|
399
|
+
self,
|
|
400
|
+
method: str,
|
|
401
|
+
path: str,
|
|
402
|
+
body: dict[str, Any] | None = None,
|
|
403
|
+
params: dict[str, str] | None = None,
|
|
404
|
+
) -> Any:
|
|
405
|
+
# Deduplication key
|
|
406
|
+
req_key = f"{method}:{path}:{json.dumps(body, sort_keys=True)}:{json.dumps(params, sort_keys=True)}"
|
|
407
|
+
|
|
408
|
+
if req_key in self._pending_requests:
|
|
409
|
+
return await self._pending_requests[req_key]
|
|
410
|
+
|
|
411
|
+
fut = asyncio.get_running_loop().create_future()
|
|
412
|
+
self._pending_requests[req_key] = fut
|
|
413
|
+
|
|
414
|
+
async def _do() -> Any:
|
|
415
|
+
url = f"{self._base_url}{path}"
|
|
416
|
+
try:
|
|
417
|
+
res = await self._http.request(method, url, json=body, params=params)
|
|
418
|
+
except httpx.TimeoutException as e:
|
|
419
|
+
raise LexioNetworkError(f"Request timed out: {e}") from e
|
|
420
|
+
except httpx.RequestError as e:
|
|
421
|
+
raise LexioNetworkError(str(e)) from e
|
|
422
|
+
_raise_for_response(res, path)
|
|
423
|
+
return res.json()
|
|
424
|
+
|
|
425
|
+
try:
|
|
426
|
+
result = await async_with_retry(_do)
|
|
427
|
+
fut.set_result(result)
|
|
428
|
+
return result
|
|
429
|
+
except Exception as e:
|
|
430
|
+
fut.set_exception(e)
|
|
431
|
+
raise
|
|
432
|
+
finally:
|
|
433
|
+
del self._pending_requests[req_key]
|
|
434
|
+
|
|
435
|
+
async def check_entitlement(self, force: bool = False) -> EntitlementStatus:
|
|
436
|
+
if (
|
|
437
|
+
not force
|
|
438
|
+
and self._cached_entitlement
|
|
439
|
+
and (time.monotonic() - self._entitlement_cached_at) < self._entitlement_ttl
|
|
440
|
+
):
|
|
441
|
+
return self._cached_entitlement
|
|
442
|
+
raw = await self._request("GET", "/sdk/quotas")
|
|
443
|
+
result = _parse_entitlement(raw)
|
|
444
|
+
self._cached_entitlement = result
|
|
445
|
+
self._entitlement_cached_at = time.monotonic()
|
|
446
|
+
return result
|
|
447
|
+
|
|
448
|
+
def invalidate_entitlement(self) -> None:
|
|
449
|
+
self._cached_entitlement = None
|
|
450
|
+
self._entitlement_cached_at = 0.0
|
|
451
|
+
|
|
452
|
+
async def get_prompt(
|
|
453
|
+
self,
|
|
454
|
+
slug: str,
|
|
455
|
+
*,
|
|
456
|
+
tag: str | None = None,
|
|
457
|
+
version: int | None = None,
|
|
458
|
+
variables: dict[str, str] | None = None,
|
|
459
|
+
) -> PromptResult:
|
|
460
|
+
if self._cache:
|
|
461
|
+
cached = self._cache.get(slug, tag, version)
|
|
462
|
+
if cached:
|
|
463
|
+
if cached.is_stale:
|
|
464
|
+
# SWR: Trigger background revalidation
|
|
465
|
+
asyncio.create_task(self._fetch_and_cache_prompt(slug, tag=tag, version=version))
|
|
466
|
+
return self._interpolate_prompt(cached.value, variables)
|
|
467
|
+
|
|
468
|
+
result = await self._fetch_and_cache_prompt(slug, tag=tag, version=version)
|
|
469
|
+
return self._interpolate_prompt(result, variables)
|
|
470
|
+
|
|
471
|
+
async def _fetch_and_cache_prompt(
|
|
472
|
+
self,
|
|
473
|
+
slug: str,
|
|
474
|
+
*,
|
|
475
|
+
tag: str | None = None,
|
|
476
|
+
version: int | None = None,
|
|
477
|
+
) -> PromptResult:
|
|
478
|
+
params: dict[str, str] = {"slug": slug}
|
|
479
|
+
if tag:
|
|
480
|
+
params["tag"] = tag
|
|
481
|
+
if version is not None:
|
|
482
|
+
params["version"] = str(version)
|
|
483
|
+
|
|
484
|
+
raw = await self._request("GET", "/sdk/prompts", params=params)
|
|
485
|
+
|
|
486
|
+
result = PromptResult(
|
|
487
|
+
slug=raw["slug"],
|
|
488
|
+
version=raw["version_number"],
|
|
489
|
+
tag=raw.get("label"),
|
|
490
|
+
text=raw.get("template", ""),
|
|
491
|
+
model_hints=[],
|
|
492
|
+
cached_at=None,
|
|
493
|
+
_variables_schema=raw.get("variable_schema", {}),
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
if self._cache:
|
|
497
|
+
self._cache.set(slug, raw.get("label"), raw["version_number"], result)
|
|
498
|
+
|
|
499
|
+
return result
|
|
500
|
+
|
|
501
|
+
def _interpolate_prompt(self, prompt: PromptResult, variables: dict[str, str] | None) -> PromptResult:
|
|
502
|
+
var_schema = prompt._variables_schema
|
|
503
|
+
required = [k for k, v in var_schema.items() if isinstance(v, dict) and v.get("required")]
|
|
504
|
+
missing = [k for k in required if not (variables or {}).get(k)]
|
|
505
|
+
if missing:
|
|
506
|
+
raise LexioVariableInterpolationError(missing)
|
|
507
|
+
|
|
508
|
+
text = prompt.text
|
|
509
|
+
for k, v in (variables or {}).items():
|
|
510
|
+
text = text.replace("{{" + k + "}}", v)
|
|
511
|
+
|
|
512
|
+
return PromptResult(
|
|
513
|
+
slug=prompt.slug,
|
|
514
|
+
version=prompt.version,
|
|
515
|
+
tag=prompt.tag,
|
|
516
|
+
text=text,
|
|
517
|
+
model_hints=prompt.model_hints,
|
|
518
|
+
cached_at=prompt.cached_at,
|
|
519
|
+
_variables_schema=prompt._variables_schema
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
async def run_tests(self, config: RunTestsConfig) -> TestRunResult:
|
|
523
|
+
merged_byok = {**self._byok_keys, **(config.byok_keys or {})}
|
|
524
|
+
body: dict[str, Any] = {
|
|
525
|
+
"prompts": [
|
|
526
|
+
{
|
|
527
|
+
"slug": p.slug,
|
|
528
|
+
"prompt_version_id": p.prompt_version_id,
|
|
529
|
+
"tag": p.tag,
|
|
530
|
+
"version": p.version,
|
|
531
|
+
"variables": p.variables,
|
|
532
|
+
}
|
|
533
|
+
for p in config.prompts
|
|
534
|
+
],
|
|
535
|
+
"models": config.models,
|
|
536
|
+
"evaluator": config.evaluator,
|
|
537
|
+
"reference_answer": config.reference_answer,
|
|
538
|
+
"async": config.async_mode,
|
|
539
|
+
"idempotency_key": config.idempotency_key,
|
|
540
|
+
"max_estimated_cost_usd": config.max_estimated_cost_usd,
|
|
541
|
+
}
|
|
542
|
+
if merged_byok:
|
|
543
|
+
body["byok_keys"] = merged_byok
|
|
544
|
+
raw = await self._request("POST", "/sdk/tests", body=body)
|
|
545
|
+
return _parse_run_result(raw)
|
|
546
|
+
|
|
547
|
+
async def get_result(self, run_id: str) -> TestRunResult:
|
|
548
|
+
raw = await self._request("GET", f"/sdk/comparisons/{run_id}/result")
|
|
549
|
+
return _parse_run_result(raw)
|
|
550
|
+
|
|
551
|
+
async def wait_for_result(
|
|
552
|
+
self,
|
|
553
|
+
run_id: str,
|
|
554
|
+
poll_interval: float = 2.0,
|
|
555
|
+
timeout: float = 120.0,
|
|
556
|
+
) -> TestRunResult:
|
|
557
|
+
import asyncio
|
|
558
|
+
deadline = time.monotonic() + timeout
|
|
559
|
+
while time.monotonic() < deadline:
|
|
560
|
+
result = await self.get_result(run_id)
|
|
561
|
+
if result.status in ("complete", "failed"):
|
|
562
|
+
return result
|
|
563
|
+
await asyncio.sleep(poll_interval)
|
|
564
|
+
raise TimeoutError(f"wait_for_result timed out after {timeout}s for run {run_id}")
|
|
565
|
+
|
|
566
|
+
async def submit_comparison(
|
|
567
|
+
self,
|
|
568
|
+
prompt_version_id: str,
|
|
569
|
+
variable_values: dict[str, str],
|
|
570
|
+
model_ids: list[str],
|
|
571
|
+
) -> ComparisonResponse:
|
|
572
|
+
raw = await self._request("POST", "/sdk/comparisons", body={
|
|
573
|
+
"prompt_version_id": prompt_version_id,
|
|
574
|
+
"variables": variable_values,
|
|
575
|
+
"model_ids": model_ids,
|
|
576
|
+
})
|
|
577
|
+
return ComparisonResponse(comparison_id=raw["comparison_id"], status=raw["status"])
|
|
578
|
+
|
|
579
|
+
async def list_prompts(
|
|
580
|
+
self,
|
|
581
|
+
*,
|
|
582
|
+
tags: list[str] | None = None,
|
|
583
|
+
page: int = 1,
|
|
584
|
+
page_size: int = 20,
|
|
585
|
+
) -> PaginatedList:
|
|
586
|
+
params: dict[str, str] = {"page": str(page), "page_size": str(page_size)}
|
|
587
|
+
if tags:
|
|
588
|
+
params["tags"] = ",".join(tags)
|
|
589
|
+
raw = await self._request("GET", "/sdk/prompts", params=params)
|
|
590
|
+
|
|
591
|
+
prompts = []
|
|
592
|
+
for p in raw.get("data", []):
|
|
593
|
+
lv = p.get("latest_version")
|
|
594
|
+
v_num = lv.get("version_number") if isinstance(lv, dict) else 0
|
|
595
|
+
prompts.append(PromptMetadata(
|
|
596
|
+
slug=p["slug"],
|
|
597
|
+
latest_version=v_num,
|
|
598
|
+
tags=p.get("tags", []),
|
|
599
|
+
created_at=p["created_at"],
|
|
600
|
+
updated_at=p.get("updated_at", p["created_at"]),
|
|
601
|
+
))
|
|
602
|
+
|
|
603
|
+
return PaginatedList(
|
|
604
|
+
data=prompts,
|
|
605
|
+
total=raw.get("total", 0),
|
|
606
|
+
page=raw.get("page", page),
|
|
607
|
+
page_size=raw.get("page_size", page_size),
|
|
608
|
+
)
|
|
609
|
+
|
|
610
|
+
async def list_comparisons(self, prompt_slug: str | None = None, limit: int = 20) -> list[Any]:
|
|
611
|
+
params: dict[str, str] = {"limit": str(limit)}
|
|
612
|
+
if prompt_slug:
|
|
613
|
+
params["prompt_slug"] = prompt_slug
|
|
614
|
+
raw = await self._request("GET", "/sdk/comparisons", params=params)
|
|
615
|
+
return raw.get("data", [])
|
|
616
|
+
|
|
617
|
+
async def get_quota_status(self) -> EntitlementStatus:
|
|
618
|
+
return await self.check_entitlement(force=True)
|
lexio/errors.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
class LexioError(Exception):
|
|
2
|
+
def __init__(self, message: str, status: int | None = None):
|
|
3
|
+
super().__init__(message)
|
|
4
|
+
self.status = status
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class LexioAuthenticationError(LexioError):
|
|
8
|
+
def __init__(self, message: str = "Invalid or missing API key"):
|
|
9
|
+
super().__init__(message, 401)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LexioRateLimitError(LexioError):
|
|
13
|
+
def __init__(self, retry_after_ms: int = 0, message: str = "Rate limit exceeded after all retries"):
|
|
14
|
+
super().__init__(message, 429)
|
|
15
|
+
self.retry_after_ms = retry_after_ms
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class LexioQuotaExceededError(LexioError):
|
|
19
|
+
def __init__(self, message: str = "Monthly token quota exceeded", entitlement: dict | None = None):
|
|
20
|
+
super().__init__(message, 402)
|
|
21
|
+
self.entitlement = entitlement
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class LexioPromptNotFoundError(LexioError):
|
|
25
|
+
def __init__(self, slug: str):
|
|
26
|
+
super().__init__(f"Prompt not found: {slug}", 404)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class LexioVariableInterpolationError(LexioError):
|
|
30
|
+
def __init__(self, missing: list[str]):
|
|
31
|
+
super().__init__(f"Missing required template variables: {', '.join(missing)}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class LexioNetworkError(LexioError):
|
|
35
|
+
def __init__(self, message: str):
|
|
36
|
+
super().__init__(message)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class LexioEntitlementError(LexioError):
|
|
40
|
+
def __init__(self, message: str):
|
|
41
|
+
super().__init__(message, 403)
|
lexio/models.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class EntitlementStatus:
|
|
8
|
+
plan: str
|
|
9
|
+
org_id: str
|
|
10
|
+
team_id: str | None
|
|
11
|
+
byok_enabled: bool
|
|
12
|
+
remaining_tokens: int
|
|
13
|
+
reset_at: str
|
|
14
|
+
concurrent_comparisons_allowed: int
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class PromptResult:
|
|
19
|
+
slug: str
|
|
20
|
+
version: int
|
|
21
|
+
tag: str | None
|
|
22
|
+
text: str
|
|
23
|
+
model_hints: list[str]
|
|
24
|
+
cached_at: str | None
|
|
25
|
+
_variables_schema: dict[str, Any] = field(default_factory=dict)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class EvaluatorScore:
|
|
30
|
+
composite_score: float
|
|
31
|
+
component_scores: dict[str, float]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class TestResult:
|
|
36
|
+
prompt_slug: str | None
|
|
37
|
+
prompt_version_id: str
|
|
38
|
+
prompt_tag: str | None
|
|
39
|
+
model_id: str
|
|
40
|
+
output: str
|
|
41
|
+
input_tokens: int
|
|
42
|
+
output_tokens: int
|
|
43
|
+
total_tokens: int
|
|
44
|
+
estimated_cost_usd: float
|
|
45
|
+
latency_ms: int
|
|
46
|
+
evaluator_score: EvaluatorScore | None
|
|
47
|
+
error_message: str | None
|
|
48
|
+
invocation_source: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class TestRunResult:
|
|
53
|
+
run_id: str
|
|
54
|
+
status: str
|
|
55
|
+
results: list[TestResult] = field(default_factory=list)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class PromptEntry:
|
|
60
|
+
slug: str | None = None
|
|
61
|
+
prompt_version_id: str | None = None
|
|
62
|
+
tag: str | None = None
|
|
63
|
+
version: int | None = None
|
|
64
|
+
variables: dict[str, str] | None = None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class RunTestsConfig:
|
|
69
|
+
prompts: list[PromptEntry]
|
|
70
|
+
models: list[str]
|
|
71
|
+
evaluator: bool = False
|
|
72
|
+
reference_answer: str | None = None
|
|
73
|
+
async_mode: bool = False
|
|
74
|
+
idempotency_key: str | None = None
|
|
75
|
+
max_estimated_cost_usd: float | None = None
|
|
76
|
+
byok_keys: dict[str, str] | None = None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class ComparisonResponse:
|
|
81
|
+
comparison_id: str
|
|
82
|
+
status: str
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class PromptMetadata:
|
|
87
|
+
slug: str
|
|
88
|
+
latest_version: int
|
|
89
|
+
tags: list[str]
|
|
90
|
+
created_at: str
|
|
91
|
+
updated_at: str
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass
|
|
95
|
+
class PaginatedList:
|
|
96
|
+
data: list[Any]
|
|
97
|
+
total: int
|
|
98
|
+
page: int
|
|
99
|
+
page_size: int
|
lexio/retry.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import time
|
|
3
|
+
from typing import Callable, TypeVar
|
|
4
|
+
from .errors import LexioRateLimitError, LexioNetworkError
|
|
5
|
+
|
|
6
|
+
T = TypeVar("T")
|
|
7
|
+
|
|
8
|
+
BACKOFF_DELAYS_MS = [250, 500, 1000]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def with_retry(fn: Callable[[], T]) -> T:
|
|
12
|
+
last_error: Exception = RuntimeError("unreachable")
|
|
13
|
+
for attempt in range(len(BACKOFF_DELAYS_MS) + 1):
|
|
14
|
+
try:
|
|
15
|
+
return fn()
|
|
16
|
+
except LexioRateLimitError as e:
|
|
17
|
+
last_error = e
|
|
18
|
+
if attempt >= len(BACKOFF_DELAYS_MS):
|
|
19
|
+
break
|
|
20
|
+
delay_ms = max(e.retry_after_ms, BACKOFF_DELAYS_MS[attempt])
|
|
21
|
+
time.sleep(delay_ms / 1000)
|
|
22
|
+
except LexioNetworkError as e:
|
|
23
|
+
last_error = e
|
|
24
|
+
if attempt >= len(BACKOFF_DELAYS_MS):
|
|
25
|
+
break
|
|
26
|
+
time.sleep(BACKOFF_DELAYS_MS[attempt] / 1000)
|
|
27
|
+
except Exception:
|
|
28
|
+
raise
|
|
29
|
+
raise last_error
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
async def async_with_retry(fn: Callable[[], object]) -> object:
|
|
33
|
+
import asyncio
|
|
34
|
+
last_error: Exception = RuntimeError("unreachable")
|
|
35
|
+
for attempt in range(len(BACKOFF_DELAYS_MS) + 1):
|
|
36
|
+
try:
|
|
37
|
+
return await fn() # type: ignore[misc]
|
|
38
|
+
except LexioRateLimitError as e:
|
|
39
|
+
last_error = e
|
|
40
|
+
if attempt >= len(BACKOFF_DELAYS_MS):
|
|
41
|
+
break
|
|
42
|
+
delay_ms = max(e.retry_after_ms, BACKOFF_DELAYS_MS[attempt])
|
|
43
|
+
await asyncio.sleep(delay_ms / 1000)
|
|
44
|
+
except LexioNetworkError as e:
|
|
45
|
+
last_error = e
|
|
46
|
+
if attempt >= len(BACKOFF_DELAYS_MS):
|
|
47
|
+
break
|
|
48
|
+
await asyncio.sleep(BACKOFF_DELAYS_MS[attempt] / 1000)
|
|
49
|
+
except Exception:
|
|
50
|
+
raise
|
|
51
|
+
raise last_error
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lexio-sdk
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Lexio SDK for Python
|
|
5
|
+
License: MIT
|
|
6
|
+
Keywords: ai,lexio,llm,prompt,sdk
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Requires-Dist: click>=8.1.0
|
|
9
|
+
Requires-Dist: httpx>=0.27.0
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
12
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
13
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# Lexio Python SDK
|
|
17
|
+
|
|
18
|
+
Official Python SDK for [Lexio](https://lexio.dev) — LLM prompt management and evaluation.
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install lexio-sdk
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from lexio import LexioClient
|
|
30
|
+
|
|
31
|
+
client = LexioClient(api_key="lx_live_...")
|
|
32
|
+
|
|
33
|
+
# Fetch a prompt
|
|
34
|
+
prompt = client.get_prompt("my-prompt", variables={"topic": "AI"})
|
|
35
|
+
print(prompt.text)
|
|
36
|
+
|
|
37
|
+
# Run tests across models
|
|
38
|
+
from lexio.models import RunTestsConfig, PromptEntry
|
|
39
|
+
|
|
40
|
+
result = client.run_tests(RunTestsConfig(
|
|
41
|
+
prompts=[PromptEntry(slug="my-prompt")],
|
|
42
|
+
models=["openai/gpt-4o-mini", "anthropic/claude-3-haiku"],
|
|
43
|
+
))
|
|
44
|
+
for r in result.results:
|
|
45
|
+
print(r.model_id, r.output)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## BYOK (Bring Your Own Key)
|
|
49
|
+
|
|
50
|
+
Pass your own provider API keys — they are used in-memory and never stored:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
client = LexioClient(api_key="lx_live_...", byok_keys={"openai": "sk-..."})
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Or register keys permanently via the Lexio dashboard (Settings → Provider Keys).
|
|
57
|
+
|
|
58
|
+
## Async client
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from lexio import AsyncLexioClient
|
|
62
|
+
|
|
63
|
+
async with AsyncLexioClient(api_key="lx_live_...") as client:
|
|
64
|
+
result = await client.run_tests(config)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Requirements
|
|
68
|
+
|
|
69
|
+
- Python 3.11+
|
|
70
|
+
- `httpx`
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
lexio/__init__.py,sha256=j01htw4GnhgRJob8W9tXPC6IETpBwEneXU3Cj86Swh4,1018
|
|
2
|
+
lexio/cache.py,sha256=m7rNSXDLaXIJDm9TIpwWltTACOkPp4LsY119Prqvbxw,2096
|
|
3
|
+
lexio/cli.py,sha256=TjSsLtr1999isOedUu2O8yV6Y6SB_czMgmuaLxQkCgU,8668
|
|
4
|
+
lexio/client.py,sha256=zA9sFHMdfTq9VtsKvPdrvn2C26_y64H4F7CX5rc-ZgQ,21815
|
|
5
|
+
lexio/errors.py,sha256=4nZ6Oh5xAcIn6VmdXjE6ykMVnSIlm8G_d4ZhnR7NMRc,1323
|
|
6
|
+
lexio/models.py,sha256=9iqommnDzNxPSPbYe8ZZGh4g89wUij66M1IsEO915OU,1940
|
|
7
|
+
lexio/retry.py,sha256=SlITe0RA4HJlui1JGUCLm2oFDxZDqW7Fo2NaB3e4mDc,1696
|
|
8
|
+
lexio_sdk-1.0.0.dist-info/METADATA,sha256=oXNsD0fEmgphcg0ow4Kpdei92-UWmQCqMl64sy168OE,1603
|
|
9
|
+
lexio_sdk-1.0.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
10
|
+
lexio_sdk-1.0.0.dist-info/entry_points.txt,sha256=CvXQG0V8Qx0Z3PxygBCoPUPb-4lnp34ijPlztdLuPB8,41
|
|
11
|
+
lexio_sdk-1.0.0.dist-info/RECORD,,
|