lexio-sdk 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ node_modules/
2
+ dist/
@@ -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,59 @@
1
+ # Lexio Python SDK
2
+
3
+ Official Python SDK for [Lexio](https://lexio.dev) — LLM prompt management and evaluation.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install lexio-sdk
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ```python
14
+ from lexio import LexioClient
15
+
16
+ client = LexioClient(api_key="lx_live_...")
17
+
18
+ # Fetch a prompt
19
+ prompt = client.get_prompt("my-prompt", variables={"topic": "AI"})
20
+ print(prompt.text)
21
+
22
+ # Run tests across models
23
+ from lexio.models import RunTestsConfig, PromptEntry
24
+
25
+ result = client.run_tests(RunTestsConfig(
26
+ prompts=[PromptEntry(slug="my-prompt")],
27
+ models=["openai/gpt-4o-mini", "anthropic/claude-3-haiku"],
28
+ ))
29
+ for r in result.results:
30
+ print(r.model_id, r.output)
31
+ ```
32
+
33
+ ## BYOK (Bring Your Own Key)
34
+
35
+ Pass your own provider API keys — they are used in-memory and never stored:
36
+
37
+ ```python
38
+ client = LexioClient(api_key="lx_live_...", byok_keys={"openai": "sk-..."})
39
+ ```
40
+
41
+ Or register keys permanently via the Lexio dashboard (Settings → Provider Keys).
42
+
43
+ ## Async client
44
+
45
+ ```python
46
+ from lexio import AsyncLexioClient
47
+
48
+ async with AsyncLexioClient(api_key="lx_live_...") as client:
49
+ result = await client.run_tests(config)
50
+ ```
51
+
52
+ ## Requirements
53
+
54
+ - Python 3.11+
55
+ - `httpx`
56
+
57
+ ## License
58
+
59
+ MIT
@@ -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
+ ]
@@ -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()
@@ -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()