lodestar-sdk 0.1.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,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: lodestar-sdk
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for Lodestar Glass-Box Inference & Open System-One Probes (api.lodestar.so/v1)
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://lodestar.so
7
+ Project-URL: Documentation, https://lodestar.so/docs
8
+ Project-URL: Repository, https://github.com/faizancodes/lodestar
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ Provides-Extra: async
12
+ Requires-Dist: httpx>=0.27.0; extra == "async"
13
+
14
+ # `lodestar-sdk` (Python)
15
+
16
+ Zero-dependency Python SDK for **Lodestar Glass-Box Inference (`api.lodestar.so/v1`)** — Token-0 mind-reading probes, `abort_if` zero-output-token gating, 3-second custom System-One probe training, and per-request surgical patches.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install lodestar-sdk
22
+ ```
23
+
24
+ ## Quickstart
25
+
26
+ ```python
27
+ from lodestar_sdk import Lodestar
28
+
29
+ client = Lodestar(api_key="ld_live_...")
30
+
31
+ # 1. Standalone System-One probe ($0.03/1M input, $0 output, ~20ms)
32
+ res = client.probes.eval(
33
+ model="qwen3-32b",
34
+ input="Who designed the Kessington Bridge in Cleveland?",
35
+ probes=["hallucination_risk", "prompt_injection"],
36
+ )
37
+ print(res["scores"]) # {'hallucination_risk': 0.999, 'prompt_injection': 0.012}
38
+
39
+ # 2. Glass-Box Chat Completion with Token-0 abort_if + declarative on_abort remediation
40
+ chat = client.chat.create(
41
+ model="qwen3-32b",
42
+ messages=[{"role": "user", "content": "Return JSON with keys service, status."}],
43
+ probes=["hallucination_risk", "prompt_injection"],
44
+ abort_if={"hallucination_risk": 0.75, "prompt_injection": 0.70},
45
+ on_abort={
46
+ "hallucination_risk": {"action": "refuse", "message": "I don't have enough verified information to answer that."},
47
+ "prompt_injection": {
48
+ "action": "refuse",
49
+ "message": "I cannot assist with untrusted instructions.",
50
+ "webhook": "https://hooks.example.com/lodestar",
51
+ },
52
+ },
53
+ patches=["strict-json"],
54
+ )
55
+ print(chat["lodestar"])
56
+
57
+ # 3. Train a custom 20 KB probe in ~3 seconds & export it anytime
58
+ probe = client.probes.create(
59
+ model="qwen3-32b",
60
+ name="churn_intent",
61
+ positive=churn_examples, # 12+ examples
62
+ negative=normal_examples, # 12+ examples
63
+ )
64
+ client.probes.export(probe["id"], out_path="churn_intent.probe.json")
65
+ ```
66
+
67
+ You can also use the stock `openai` Python SDK with a 1-line `base_url` swap:
68
+
69
+ ```python
70
+ from openai import OpenAI
71
+
72
+ client = OpenAI(base_url="https://api.lodestar.so/v1", api_key="ld_live_...")
73
+ res = client.chat.completions.create(
74
+ model="qwen3-32b",
75
+ messages=[{"role": "user", "content": "Who designed the Kessington Bridge?"}],
76
+ extra_body={"lodestar": {"probes": ["hallucination_risk"], "abort_if": {"hallucination_risk": 0.75}}},
77
+ )
78
+ ```
@@ -0,0 +1,65 @@
1
+ # `lodestar-sdk` (Python)
2
+
3
+ Zero-dependency Python SDK for **Lodestar Glass-Box Inference (`api.lodestar.so/v1`)** — Token-0 mind-reading probes, `abort_if` zero-output-token gating, 3-second custom System-One probe training, and per-request surgical patches.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install lodestar-sdk
9
+ ```
10
+
11
+ ## Quickstart
12
+
13
+ ```python
14
+ from lodestar_sdk import Lodestar
15
+
16
+ client = Lodestar(api_key="ld_live_...")
17
+
18
+ # 1. Standalone System-One probe ($0.03/1M input, $0 output, ~20ms)
19
+ res = client.probes.eval(
20
+ model="qwen3-32b",
21
+ input="Who designed the Kessington Bridge in Cleveland?",
22
+ probes=["hallucination_risk", "prompt_injection"],
23
+ )
24
+ print(res["scores"]) # {'hallucination_risk': 0.999, 'prompt_injection': 0.012}
25
+
26
+ # 2. Glass-Box Chat Completion with Token-0 abort_if + declarative on_abort remediation
27
+ chat = client.chat.create(
28
+ model="qwen3-32b",
29
+ messages=[{"role": "user", "content": "Return JSON with keys service, status."}],
30
+ probes=["hallucination_risk", "prompt_injection"],
31
+ abort_if={"hallucination_risk": 0.75, "prompt_injection": 0.70},
32
+ on_abort={
33
+ "hallucination_risk": {"action": "refuse", "message": "I don't have enough verified information to answer that."},
34
+ "prompt_injection": {
35
+ "action": "refuse",
36
+ "message": "I cannot assist with untrusted instructions.",
37
+ "webhook": "https://hooks.example.com/lodestar",
38
+ },
39
+ },
40
+ patches=["strict-json"],
41
+ )
42
+ print(chat["lodestar"])
43
+
44
+ # 3. Train a custom 20 KB probe in ~3 seconds & export it anytime
45
+ probe = client.probes.create(
46
+ model="qwen3-32b",
47
+ name="churn_intent",
48
+ positive=churn_examples, # 12+ examples
49
+ negative=normal_examples, # 12+ examples
50
+ )
51
+ client.probes.export(probe["id"], out_path="churn_intent.probe.json")
52
+ ```
53
+
54
+ You can also use the stock `openai` Python SDK with a 1-line `base_url` swap:
55
+
56
+ ```python
57
+ from openai import OpenAI
58
+
59
+ client = OpenAI(base_url="https://api.lodestar.so/v1", api_key="ld_live_...")
60
+ res = client.chat.completions.create(
61
+ model="qwen3-32b",
62
+ messages=[{"role": "user", "content": "Who designed the Kessington Bridge?"}],
63
+ extra_body={"lodestar": {"probes": ["hallucination_risk"], "abort_if": {"hallucination_risk": 0.75}}},
64
+ )
65
+ ```
@@ -0,0 +1,232 @@
1
+ """Official zero-dependency Python client for Lodestar Glass-Box Inference (`api.lodestar.so/v1`)."""
2
+ from __future__ import annotations
3
+
4
+ import http.client
5
+ import json
6
+ import os
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ from pathlib import Path
11
+ from typing import Any, Iterator
12
+
13
+ DEFAULT_BASE_URL = "https://api.lodestar.so/v1"
14
+
15
+
16
+ class LodestarAPIError(RuntimeError):
17
+ """Raised when `api.lodestar.so/v1` returns a non-2xx status code."""
18
+
19
+ def __init__(self, status_code: int, message: str, body: str = ""):
20
+ super().__init__(f"Lodestar API {status_code}: {message}")
21
+ self.status_code = status_code
22
+ self.body = body
23
+
24
+
25
+ class _ProbesResource:
26
+ def __init__(self, client: Lodestar):
27
+ self._c = client
28
+
29
+ def list(self, *, model: str | None = None) -> list[dict[str, Any]]:
30
+ q = f"?model={urllib.parse.quote(model)}" if model else ""
31
+ return self._c._request("GET", f"/probes{q}")["data"]
32
+
33
+ def eval(
34
+ self,
35
+ *,
36
+ probes: list[str],
37
+ model: str = "qwen3-32b",
38
+ input: str | None = None,
39
+ messages: list[dict[str, Any]] | None = None,
40
+ system: str | None = None,
41
+ ) -> dict[str, Any]:
42
+ payload: dict[str, Any] = {"model": model, "probes": probes}
43
+ if input is not None:
44
+ payload["input"] = input
45
+ if messages is not None:
46
+ payload["messages"] = messages
47
+ if system is not None:
48
+ payload["system"] = system
49
+ return self._c._request("POST", "/probes/eval", payload)
50
+
51
+ def create(
52
+ self,
53
+ *,
54
+ name: str,
55
+ positive: list[Any],
56
+ negative: list[Any],
57
+ model: str = "qwen3-32b",
58
+ positive_label: str = "Positive",
59
+ negative_label: str = "Negative",
60
+ ) -> dict[str, Any]:
61
+ return self._c._request(
62
+ "POST",
63
+ "/probes/create",
64
+ {
65
+ "model": model,
66
+ "name": name,
67
+ "positive": positive,
68
+ "negative": negative,
69
+ "positive_label": positive_label,
70
+ "negative_label": negative_label,
71
+ },
72
+ )
73
+
74
+ def export(self, probe_id: str, *, out_path: str | Path | None = None) -> dict[str, Any]:
75
+ artifact = self._c._request("GET", f"/probes/{urllib.parse.quote(probe_id)}/export")
76
+ if out_path is not None:
77
+ Path(out_path).write_text(json.dumps(artifact, indent=2) + "\n")
78
+ return artifact
79
+
80
+
81
+ class _ChatResource:
82
+ def __init__(self, client: Lodestar):
83
+ self._c = client
84
+
85
+ def _build_payload(
86
+ self,
87
+ *,
88
+ model: str,
89
+ messages: list[dict[str, Any]],
90
+ probes: list[str] | None = None,
91
+ abort_if: dict[str, float | str] | None = None,
92
+ on_abort: dict[str, Any] | None = None,
93
+ patches: list[str] | None = None,
94
+ stream: bool = False,
95
+ **kwargs: Any,
96
+ ) -> dict[str, Any]:
97
+ payload: dict[str, Any] = {"model": model, "messages": messages, "stream": stream, **kwargs}
98
+ ld: dict[str, Any] = {}
99
+ if probes:
100
+ ld["probes"] = probes
101
+ if abort_if:
102
+ ld["abort_if"] = abort_if
103
+ if on_abort:
104
+ ld["on_abort"] = on_abort
105
+ if patches:
106
+ ld["patches"] = patches
107
+ if ld:
108
+ payload["lodestar"] = ld
109
+ return payload
110
+
111
+ def create(
112
+ self,
113
+ *,
114
+ model: str = "qwen3-32b",
115
+ messages: list[dict[str, Any]],
116
+ probes: list[str] | None = None,
117
+ abort_if: dict[str, float | str] | None = None,
118
+ on_abort: dict[str, Any] | None = None,
119
+ patches: list[str] | None = None,
120
+ **kwargs: Any,
121
+ ) -> dict[str, Any]:
122
+ payload = self._build_payload(
123
+ model=model,
124
+ messages=messages,
125
+ probes=probes,
126
+ abort_if=abort_if,
127
+ on_abort=on_abort,
128
+ patches=patches,
129
+ stream=False,
130
+ **kwargs,
131
+ )
132
+ return self._c._request("POST", "/chat/completions", payload)
133
+
134
+ def stream(
135
+ self,
136
+ *,
137
+ model: str = "qwen3-32b",
138
+ messages: list[dict[str, Any]],
139
+ probes: list[str] | None = None,
140
+ abort_if: dict[str, float | str] | None = None,
141
+ on_abort: dict[str, Any] | None = None,
142
+ patches: list[str] | None = None,
143
+ **kwargs: Any,
144
+ ) -> Iterator[dict[str, Any]]:
145
+ payload = self._build_payload(
146
+ model=model,
147
+ messages=messages,
148
+ probes=probes,
149
+ abort_if=abort_if,
150
+ on_abort=on_abort,
151
+ patches=patches,
152
+ stream=True,
153
+ **kwargs,
154
+ )
155
+ yield from self._c._stream_sse("/chat/completions", payload)
156
+
157
+
158
+ class Lodestar:
159
+ """Client for Lodestar Glass-Box Inference & Open System-One API."""
160
+
161
+ def __init__(
162
+ self,
163
+ *,
164
+ api_key: str | None = None,
165
+ base_url: str | None = None,
166
+ timeout: float = 60.0,
167
+ ):
168
+ self.api_key = (api_key or os.environ.get("LODESTAR_API_KEY") or "").strip()
169
+ if not self.api_key:
170
+ raise ValueError("Missing api_key (pass api_key='ld_live_...' or set LODESTAR_API_KEY).")
171
+ self.base_url = (base_url or os.environ.get("LODESTAR_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
172
+ self.timeout = float(timeout)
173
+ self.probes = _ProbesResource(self)
174
+ self.chat = _ChatResource(self)
175
+
176
+ def _headers(self) -> dict[str, str]:
177
+ return {
178
+ "Authorization": f"Bearer {self.api_key}",
179
+ "Content-Type": "application/json",
180
+ "User-Agent": "lodestar-sdk-python/0.1.0",
181
+ }
182
+
183
+ def _request(self, method: str, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
184
+ url = f"{self.base_url}{path}"
185
+ data = json.dumps(body).encode("utf-8") if body is not None else None
186
+ req = urllib.request.Request(url, data=data, headers=self._headers(), method=method)
187
+ try:
188
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
189
+ return json.loads(resp.read().decode("utf-8"))
190
+ except urllib.error.HTTPError as err:
191
+ raw = err.read().decode("utf-8", errors="replace")
192
+ try:
193
+ msg = json.loads(raw).get("detail", raw)
194
+ except Exception:
195
+ msg = raw
196
+ raise LodestarAPIError(err.code, str(msg), raw) from err
197
+
198
+ def _stream_sse(self, path: str, body: dict[str, Any]) -> Iterator[dict[str, Any]]:
199
+ url = f"{self.base_url}{path}"
200
+ parsed = urllib.parse.urlparse(url)
201
+ conn_cls = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
202
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
203
+ conn = conn_cls(parsed.hostname or "127.0.0.1", port, timeout=self.timeout)
204
+ try:
205
+ req_path = parsed.path + (f"?{parsed.query}" if parsed.query else "")
206
+ conn.request("POST", req_path, body=json.dumps(body).encode("utf-8"), headers=self._headers())
207
+ resp = conn.getresponse()
208
+ if resp.status >= 400:
209
+ raw = resp.read().decode("utf-8", errors="replace")
210
+ raise LodestarAPIError(resp.status, raw[:300], raw)
211
+ while True:
212
+ raw_line = resp.readline()
213
+ if not raw_line:
214
+ break
215
+ line = raw_line.decode("utf-8", errors="replace").strip()
216
+ if not line.startswith("data:"):
217
+ continue
218
+ payload = line[5:].strip()
219
+ if not payload or payload == "[DONE]":
220
+ continue
221
+ yield json.loads(payload)
222
+ finally:
223
+ conn.close()
224
+
225
+ def models(self) -> list[dict[str, Any]]:
226
+ return self._request("GET", "/models")["data"]
227
+
228
+ def usage(self, *, limit: int = 25) -> dict[str, Any]:
229
+ return self._request("GET", f"/usage?limit={int(limit)}")
230
+
231
+
232
+ __all__ = ["Lodestar", "LodestarAPIError", "DEFAULT_BASE_URL"]
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: lodestar-sdk
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for Lodestar Glass-Box Inference & Open System-One Probes (api.lodestar.so/v1)
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://lodestar.so
7
+ Project-URL: Documentation, https://lodestar.so/docs
8
+ Project-URL: Repository, https://github.com/faizancodes/lodestar
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ Provides-Extra: async
12
+ Requires-Dist: httpx>=0.27.0; extra == "async"
13
+
14
+ # `lodestar-sdk` (Python)
15
+
16
+ Zero-dependency Python SDK for **Lodestar Glass-Box Inference (`api.lodestar.so/v1`)** — Token-0 mind-reading probes, `abort_if` zero-output-token gating, 3-second custom System-One probe training, and per-request surgical patches.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install lodestar-sdk
22
+ ```
23
+
24
+ ## Quickstart
25
+
26
+ ```python
27
+ from lodestar_sdk import Lodestar
28
+
29
+ client = Lodestar(api_key="ld_live_...")
30
+
31
+ # 1. Standalone System-One probe ($0.03/1M input, $0 output, ~20ms)
32
+ res = client.probes.eval(
33
+ model="qwen3-32b",
34
+ input="Who designed the Kessington Bridge in Cleveland?",
35
+ probes=["hallucination_risk", "prompt_injection"],
36
+ )
37
+ print(res["scores"]) # {'hallucination_risk': 0.999, 'prompt_injection': 0.012}
38
+
39
+ # 2. Glass-Box Chat Completion with Token-0 abort_if + declarative on_abort remediation
40
+ chat = client.chat.create(
41
+ model="qwen3-32b",
42
+ messages=[{"role": "user", "content": "Return JSON with keys service, status."}],
43
+ probes=["hallucination_risk", "prompt_injection"],
44
+ abort_if={"hallucination_risk": 0.75, "prompt_injection": 0.70},
45
+ on_abort={
46
+ "hallucination_risk": {"action": "refuse", "message": "I don't have enough verified information to answer that."},
47
+ "prompt_injection": {
48
+ "action": "refuse",
49
+ "message": "I cannot assist with untrusted instructions.",
50
+ "webhook": "https://hooks.example.com/lodestar",
51
+ },
52
+ },
53
+ patches=["strict-json"],
54
+ )
55
+ print(chat["lodestar"])
56
+
57
+ # 3. Train a custom 20 KB probe in ~3 seconds & export it anytime
58
+ probe = client.probes.create(
59
+ model="qwen3-32b",
60
+ name="churn_intent",
61
+ positive=churn_examples, # 12+ examples
62
+ negative=normal_examples, # 12+ examples
63
+ )
64
+ client.probes.export(probe["id"], out_path="churn_intent.probe.json")
65
+ ```
66
+
67
+ You can also use the stock `openai` Python SDK with a 1-line `base_url` swap:
68
+
69
+ ```python
70
+ from openai import OpenAI
71
+
72
+ client = OpenAI(base_url="https://api.lodestar.so/v1", api_key="ld_live_...")
73
+ res = client.chat.completions.create(
74
+ model="qwen3-32b",
75
+ messages=[{"role": "user", "content": "Who designed the Kessington Bridge?"}],
76
+ extra_body={"lodestar": {"probes": ["hallucination_risk"], "abort_if": {"hallucination_risk": 0.75}}},
77
+ )
78
+ ```
@@ -0,0 +1,8 @@
1
+ README.md
2
+ pyproject.toml
3
+ lodestar_sdk/__init__.py
4
+ lodestar_sdk.egg-info/PKG-INFO
5
+ lodestar_sdk.egg-info/SOURCES.txt
6
+ lodestar_sdk.egg-info/dependency_links.txt
7
+ lodestar_sdk.egg-info/requires.txt
8
+ lodestar_sdk.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+
2
+ [async]
3
+ httpx>=0.27.0
@@ -0,0 +1 @@
1
+ lodestar_sdk
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lodestar-sdk"
7
+ version = "0.1.0"
8
+ description = "Official Python SDK for Lodestar Glass-Box Inference & Open System-One Probes (api.lodestar.so/v1)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ dependencies = []
13
+
14
+ [project.urls]
15
+ Homepage = "https://lodestar.so"
16
+ Documentation = "https://lodestar.so/docs"
17
+ Repository = "https://github.com/faizancodes/lodestar"
18
+
19
+ [project.optional-dependencies]
20
+ async = ["httpx>=0.27.0"]
21
+
22
+ [tool.setuptools.packages.find]
23
+ where = ["."]
24
+ include = ["lodestar_sdk*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+