lodestar-ai-sdk 0.0.0-stage → 0.1.0

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.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # `lodestar-ai-sdk` (TypeScript / Edge / Node / Workers)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Zero-dependency TypeScript client for **Lodestar Glass-Box Inference (`api.lodestar.so/v1`)** built on native `fetch` — works in Node 18+, Next.js Edge, Cloudflare Workers, Deno, and Bun.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install lodestar-ai-sdk
9
+ ```
10
+
11
+ ## Quickstart
12
+
13
+ ```ts
14
+ import { Lodestar } from "lodestar-ai-sdk";
15
+
16
+ const lodestar = new Lodestar({ apiKey: process.env.LODESTAR_API_KEY! });
17
+
18
+ // 1. Standalone System-One probe (~20ms, $0.03/1M input, $0 output)
19
+ const check = await lodestar.probes.eval({
20
+ model: "qwen3-32b",
21
+ input: "Who designed the Kessington Bridge in Cleveland?",
22
+ probes: ["hallucination_risk", "prompt_injection"],
23
+ });
24
+
25
+ // 2. Glass-Box Chat Completion with Token-0 abort_if + declarative onAbort remediation
26
+ const res = await lodestar.chat.create({
27
+ model: "qwen3-32b",
28
+ messages: [{ role: "user", content: "Return JSON with keys service, status." }],
29
+ probes: ["hallucination_risk", "prompt_injection"],
30
+ abortIf: { hallucination_risk: 0.75, prompt_injection: 0.7 },
31
+ onAbort: {
32
+ hallucination_risk: {
33
+ action: "refuse",
34
+ message: "I don't have enough verified information to answer that.",
35
+ },
36
+ prompt_injection: {
37
+ action: "refuse",
38
+ message: "I cannot assist with untrusted instructions.",
39
+ webhook: "https://hooks.example.com/lodestar",
40
+ },
41
+ },
42
+ patches: ["strict-json"],
43
+ });
44
+ ```
@@ -0,0 +1,154 @@
1
+ export declare const DEFAULT_BASE_URL = "https://api.lodestar.so/v1";
2
+ export interface LodestarOptions {
3
+ apiKey: string;
4
+ baseUrl?: string;
5
+ fetch?: typeof globalThis.fetch;
6
+ }
7
+ export interface ChatMessage {
8
+ role: "system" | "user" | "assistant" | string;
9
+ content: string;
10
+ }
11
+ export interface ProbeEvalParams {
12
+ model?: string;
13
+ probes: string[];
14
+ input?: string;
15
+ messages?: ChatMessage[];
16
+ system?: string;
17
+ }
18
+ export interface ProbeEvalResponse {
19
+ id: string;
20
+ object: "lodestar.probe_eval";
21
+ model: string;
22
+ scores: Record<string, number>;
23
+ early_exit_layer?: number;
24
+ total_layers?: number;
25
+ probe_ms: number;
26
+ latency_ms: number;
27
+ usage: {
28
+ prompt_tokens: number;
29
+ completion_tokens: 0;
30
+ cost_usd: number;
31
+ };
32
+ }
33
+ export interface ProbeCreateParams {
34
+ model?: string;
35
+ name: string;
36
+ positive: Array<string | {
37
+ text: string;
38
+ group?: string;
39
+ }>;
40
+ negative: Array<string | {
41
+ text: string;
42
+ group?: string;
43
+ }>;
44
+ positiveLabel?: string;
45
+ negativeLabel?: string;
46
+ }
47
+ export interface ProbeCreateResponse {
48
+ id: string;
49
+ object: "lodestar.probe";
50
+ name: string;
51
+ model: string;
52
+ layer: number;
53
+ d_model: number;
54
+ n_examples: number;
55
+ fit_ms: number;
56
+ metrics: Record<string, unknown>;
57
+ export_url: string;
58
+ }
59
+ export type OnAbortAction = "retry_with_patch" | "fallback_model" | "refuse";
60
+ export interface OnAbortRule {
61
+ action: OnAbortAction;
62
+ /** Required when `action` is `"retry_with_patch"`. */
63
+ patches?: string[];
64
+ /** Required when `action` is `"fallback_model"` (e.g. `"qwen3-32b"` or BYOK `"gpt-4o"` / `"claude-sonnet-4-20250514"`). */
65
+ model?: string;
66
+ /** Optional provider override for BYOK fallback: `"lodestar" | "openai" | "anthropic" | "gemini" | "custom"`. */
67
+ provider?: "lodestar" | "openai" | "anthropic" | "gemini" | "custom";
68
+ /** Optional custom `https://` endpoint for BYOK fallback. */
69
+ upstream_url?: string;
70
+ /** Optional BYOK API key for frontier fallback (or pass `X-Lodestar-Fallback-API-Key` header). */
71
+ api_key?: string;
72
+ /** Custom refusal message when `action` is `"refuse"`. */
73
+ message?: string;
74
+ /** Optional `https://` webhook URL notified asynchronously when a guard trips. */
75
+ webhook?: string;
76
+ /** Optional extra HTTP headers sent with the webhook request. */
77
+ webhook_headers?: Record<string, string>;
78
+ }
79
+ /** Either a single remediation rule for all guards or a per-probe map (with optional `"default"` key). */
80
+ export type OnAbortConfig = OnAbortRule | Record<string, OnAbortRule>;
81
+ export interface LodestarRemediationMetadata {
82
+ triggered: boolean;
83
+ action: OnAbortAction;
84
+ trigger_reason: string;
85
+ patches_added?: string[];
86
+ original_model?: string;
87
+ fallback_model?: string;
88
+ provider?: string;
89
+ message?: string;
90
+ webhook_dispatched: boolean;
91
+ }
92
+ export interface ChatCreateParams {
93
+ model?: string;
94
+ messages: ChatMessage[];
95
+ probes?: string[];
96
+ abortIf?: Record<string, number | string>;
97
+ onAbort?: OnAbortConfig;
98
+ patches?: string[];
99
+ max_tokens?: number;
100
+ temperature?: number;
101
+ [extra: string]: unknown;
102
+ }
103
+ export interface LodestarMetadata {
104
+ probes: Record<string, number>;
105
+ aborted: boolean;
106
+ abort_reason: string | null;
107
+ patches_applied: string[];
108
+ probe_ms: number;
109
+ early_exit_layer?: number | null;
110
+ vllm_model?: string;
111
+ remediation?: LodestarRemediationMetadata;
112
+ }
113
+ export interface ChatCompletionResponse {
114
+ id: string;
115
+ object: "chat.completion";
116
+ created: number;
117
+ model: string;
118
+ choices: Array<{
119
+ index: number;
120
+ message: ChatMessage;
121
+ finish_reason: string | null;
122
+ }>;
123
+ usage?: {
124
+ prompt_tokens: number;
125
+ completion_tokens: number;
126
+ total_tokens: number;
127
+ };
128
+ lodestar: LodestarMetadata;
129
+ }
130
+ export declare class LodestarAPIError extends Error {
131
+ statusCode: number;
132
+ body: string;
133
+ constructor(statusCode: number, message: string, body?: string);
134
+ }
135
+ export declare class Lodestar {
136
+ readonly baseUrl: string;
137
+ private readonly apiKey;
138
+ private readonly _fetch;
139
+ constructor(opts: LodestarOptions);
140
+ private headers;
141
+ private request;
142
+ readonly probes: {
143
+ list: (model?: string) => Promise<unknown[]>;
144
+ eval: (params: ProbeEvalParams) => Promise<ProbeEvalResponse>;
145
+ create: (params: ProbeCreateParams) => Promise<ProbeCreateResponse>;
146
+ export: (probeId: string) => Promise<Record<string, unknown>>;
147
+ };
148
+ readonly chat: {
149
+ create: (params: ChatCreateParams) => Promise<ChatCompletionResponse>;
150
+ stream: (params: ChatCreateParams) => AsyncGenerator<Record<string, unknown>, void, void>;
151
+ };
152
+ models: () => Promise<unknown[]>;
153
+ usage: (limit?: number) => Promise<Record<string, unknown>>;
154
+ }
package/dist/index.js ADDED
@@ -0,0 +1,142 @@
1
+ export const DEFAULT_BASE_URL = "https://api.lodestar.so/v1";
2
+ export class LodestarAPIError extends Error {
3
+ statusCode;
4
+ body;
5
+ constructor(statusCode, message, body = "") {
6
+ super(`Lodestar API ${statusCode}: ${message}`);
7
+ this.name = "LodestarAPIError";
8
+ this.statusCode = statusCode;
9
+ this.body = body;
10
+ }
11
+ }
12
+ export class Lodestar {
13
+ baseUrl;
14
+ apiKey;
15
+ _fetch;
16
+ constructor(opts) {
17
+ const key = opts.apiKey?.trim();
18
+ if (!key)
19
+ throw new Error("Missing apiKey (expected 'ld_live_...').");
20
+ this.apiKey = key;
21
+ this.baseUrl = (opts.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
22
+ this._fetch = opts.fetch || globalThis.fetch;
23
+ }
24
+ headers() {
25
+ return {
26
+ Authorization: `Bearer ${this.apiKey}`,
27
+ "Content-Type": "application/json",
28
+ };
29
+ }
30
+ async request(method, path, body) {
31
+ const res = await this._fetch(`${this.baseUrl}${path}`, {
32
+ method,
33
+ headers: this.headers(),
34
+ body: body !== undefined ? JSON.stringify(body) : undefined,
35
+ });
36
+ const text = await res.text();
37
+ if (!res.ok) {
38
+ let msg = text;
39
+ try {
40
+ const parsed = JSON.parse(text);
41
+ if (parsed.detail)
42
+ msg = String(parsed.detail);
43
+ }
44
+ catch {
45
+ // raw text
46
+ }
47
+ throw new LodestarAPIError(res.status, msg, text);
48
+ }
49
+ return JSON.parse(text);
50
+ }
51
+ probes = {
52
+ list: async (model) => {
53
+ const q = model ? `?model=${encodeURIComponent(model)}` : "";
54
+ const out = await this.request("GET", `/probes${q}`);
55
+ return out.data;
56
+ },
57
+ eval: (params) => this.request("POST", "/probes/eval", {
58
+ model: params.model ?? "qwen3-32b",
59
+ probes: params.probes,
60
+ input: params.input,
61
+ messages: params.messages,
62
+ system: params.system,
63
+ }),
64
+ create: (params) => this.request("POST", "/probes/create", {
65
+ model: params.model ?? "qwen3-32b",
66
+ name: params.name,
67
+ positive: params.positive,
68
+ negative: params.negative,
69
+ positive_label: params.positiveLabel ?? "Positive",
70
+ negative_label: params.negativeLabel ?? "Negative",
71
+ }),
72
+ export: (probeId) => this.request("GET", `/probes/${encodeURIComponent(probeId)}/export`),
73
+ };
74
+ chat = {
75
+ create: (params) => {
76
+ const { probes, abortIf, onAbort, patches, model, ...rest } = params;
77
+ const lodestar = {};
78
+ if (probes?.length)
79
+ lodestar.probes = probes;
80
+ if (abortIf && Object.keys(abortIf).length)
81
+ lodestar.abort_if = abortIf;
82
+ if (onAbort && Object.keys(onAbort).length)
83
+ lodestar.on_abort = onAbort;
84
+ if (patches?.length)
85
+ lodestar.patches = patches;
86
+ return this.request("POST", "/chat/completions", {
87
+ ...rest,
88
+ model: model ?? "qwen3-32b",
89
+ stream: false,
90
+ ...(Object.keys(lodestar).length ? { lodestar } : {}),
91
+ });
92
+ },
93
+ stream: async function* (params) {
94
+ const { probes, abortIf, onAbort, patches, model, ...rest } = params;
95
+ const lodestar = {};
96
+ if (probes?.length)
97
+ lodestar.probes = probes;
98
+ if (abortIf && Object.keys(abortIf).length)
99
+ lodestar.abort_if = abortIf;
100
+ if (onAbort && Object.keys(onAbort).length)
101
+ lodestar.on_abort = onAbort;
102
+ if (patches?.length)
103
+ lodestar.patches = patches;
104
+ const res = await this._fetch(`${this.baseUrl}/chat/completions`, {
105
+ method: "POST",
106
+ headers: this.headers(),
107
+ body: JSON.stringify({
108
+ ...rest,
109
+ model: model ?? "qwen3-32b",
110
+ stream: true,
111
+ ...(Object.keys(lodestar).length ? { lodestar } : {}),
112
+ }),
113
+ });
114
+ if (!res.ok || !res.body) {
115
+ const txt = await res.text();
116
+ throw new LodestarAPIError(res.status, txt.slice(0, 300), txt);
117
+ }
118
+ const reader = res.body.getReader();
119
+ const decoder = new TextDecoder();
120
+ let buf = "";
121
+ while (true) {
122
+ const { done, value } = await reader.read();
123
+ if (done)
124
+ break;
125
+ buf += decoder.decode(value, { stream: true });
126
+ const lines = buf.split("\n");
127
+ buf = lines.pop() || "";
128
+ for (const raw of lines) {
129
+ const line = raw.trim();
130
+ if (!line.startsWith("data:"))
131
+ continue;
132
+ const payload = line.slice(5).trim();
133
+ if (!payload || payload === "[DONE]")
134
+ continue;
135
+ yield JSON.parse(payload);
136
+ }
137
+ }
138
+ }.bind(this),
139
+ };
140
+ models = async () => (await this.request("GET", "/models")).data;
141
+ usage = (limit = 25) => this.request("GET", `/usage?limit=${limit}`);
142
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "lodestar-ai-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Zero-dependency TypeScript/JavaScript SDK for Lodestar Glass-Box Inference & Open System-One Probes (api.lodestar.so/v1)",
5
+ "homepage": "https://lodestar.so/docs",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/faizancodes/lodestar.git",
9
+ "directory": "packages/lodestar-js"
10
+ },
11
+ "keywords": ["lodestar", "ai", "llm", "guardrails", "interpretability", "probes", "openai", "anthropic"],
12
+ "type": "module",
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ }
20
+ },
21
+ "files": ["dist", "README.md"],
22
+ "scripts": {
23
+ "build": "tsc",
24
+ "typecheck": "tsc --noEmit"
25
+ },
26
+ "engines": {
27
+ "node": ">=18.0.0"
28
+ },
29
+ "license": "MIT"
30
+ }