@prompt-helm/sdk 0.2.0 → 1.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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 PromptHelm
3
+ Copyright (c) 2026 Runivox Ltd
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,194 +1,124 @@
1
1
  # @prompt-helm/sdk
2
2
 
3
- Official Node.js SDK for [PromptHelm](https://prompthelm.app) — call your managed prompts from any application.
3
+ Prompt management for LLM apps: fetch your [PromptHelm](https://prompthelm.app) prompts at
4
+ runtime, so changing a prompt needs no rebuild and no redeploy.
4
5
 
5
- PromptHelm is an enterprise LLMOps control plane: versioned prompts, encrypted provider keys, a multi-provider gateway (OpenAI, Anthropic, Gemini, DeepSeek), and first-class cost / latency / cache analytics. This SDK gives you a typed, ergonomic client for the PromptHelm gateway.
6
+ You edit and publish a prompt in the PromptHelm dashboard. Your app asks for it by name, fills
7
+ in its variables and passes the text to whichever model it already calls. Every publish is a
8
+ version that never changes, and rolling back is one click; your app follows either on its next
9
+ refresh, 60 seconds by default.
6
10
 
7
- ## Features
11
+ - **Never takes your app down.** With a `fallback`, every failure (timeout, network, bad key,
12
+ missing prompt, missing variable) returns your fallback and reports through `onError`.
13
+ - **Fast after the first call.** Prompts are served from memory and refreshed in the background;
14
+ a refresh that finds nothing new is an empty `304`.
15
+ - **Your data stays with you.** Variables are filled in on your server. PromptHelm never sees
16
+ their values, your provider keys or your LLM traffic.
17
+ - **Small.** No dependencies, under 2 kB gzipped, ESM and CommonJS, Node.js 18 and later.
8
18
 
9
- - Typed `execute` and `stream` methods backed by the PromptHelm gateway
10
- - Native `fetch` and `AbortController` — no runtime dependencies
11
- - Typed error hierarchy for auth, rate limit, and server failures
12
- - Async iterable streaming with structured SSE events
13
- - Configurable timeout and exponential-backoff retry for transient failures
14
- - ESM and CJS builds, full TypeScript declarations, Node 18+
19
+ ## Install
15
20
 
16
- ## Installation
17
-
18
- ```bash
21
+ ```sh
19
22
  npm install @prompt-helm/sdk
20
23
  ```
21
24
 
22
- ## Quickstart
23
-
24
- ```ts
25
- import { PromptHelm } from "@prompt-helm/sdk";
26
-
27
- const ph = new PromptHelm({
28
- apiKey: process.env.PROMPTHELM_API_KEY ?? "<your-api-token>",
29
- });
30
-
31
- const result = await ph.execute({
32
- promptSlug: "welcome-email",
33
- variables: { name: "World" },
34
- });
25
+ Create an API key in the dashboard and put it in your server's environment:
35
26
 
36
- console.log(result.output);
37
- console.log(`Tokens: ${result.totalTokens}, cost: $${result.cost.toFixed(6)}`);
27
+ ```sh
28
+ PROMPTHELM_API_KEY=ph_…
38
29
  ```
39
30
 
40
- ## Streaming
41
-
42
- `stream` returns an async iterable of typed events. The iterator terminates after a `done` event and throws a typed error if the server emits an `error` event.
31
+ ## Use
43
32
 
44
33
  ```ts
45
34
  import { PromptHelm } from "@prompt-helm/sdk";
46
35
 
47
- const ph = new PromptHelm({
48
- apiKey: process.env.PROMPTHELM_API_KEY ?? "<your-api-token>",
36
+ // One client for the whole app: it holds the cache.
37
+ export const ph = new PromptHelm();
38
+
39
+ const system = await ph.get("support-reply", {
40
+ vars: { company: "Acme", customer_name: user.name },
41
+ fallback: SUPPORT_REPLY, // the prompt you had hard-coded
49
42
  });
50
43
 
51
- for await (const event of ph.stream({
52
- promptSlug: "release-notes",
53
- variables: { version: "1.4.0" },
54
- })) {
55
- if (event.type === "chunk") {
56
- process.stdout.write(event.content);
57
- } else if (event.type === "done") {
58
- console.log(`\n[done] tokens=${event.totalTokens} cost=${event.cost}`);
59
- }
60
- }
44
+ // Pass `system` to your model exactly as you did before.
61
45
  ```
62
46
 
63
- You can stop a stream early with an `AbortSignal`:
47
+ The stored prompt marks each variable in double braces, such as `{{customer_name}}`. If the live
48
+ version uses a variable the call doesn't pass, `get` doesn't send a half-filled prompt: it
49
+ returns the fallback (or, without one, throws `missing_variables`).
64
50
 
65
- ```ts
66
- const controller = new AbortController();
67
- setTimeout(() => controller.abort(), 5_000);
68
-
69
- for await (const event of ph.stream(
70
- { promptSlug: "long-form" },
71
- { signal: controller.signal },
72
- )) {
73
- if (event.type === "chunk") {
74
- process.stdout.write(event.content);
75
- }
76
- }
77
- ```
51
+ ## Options
78
52
 
79
- ## Configuration
80
-
81
- | Option | Type | Default | Description |
82
- | ------------ | ----------------------- | ------------------------------ | -------------------------------------------------------------------- |
83
- | `apiKey` | `string` | required | PromptHelm API key in the form `phk_<32 hex>`. |
84
- | `baseURL` | `string` | `https://api.prompthelm.app` | Override the API host for self-hosted or non-production deployments. |
85
- | `timeout` | `number` (ms) | `60000` | Per-request timeout. Aborts the underlying fetch on expiry. |
86
- | `maxRetries` | `number` | `2` | Retries on network and 5xx errors. 4xx responses are never retried. |
87
- | `userAgent` | `string` | `—` | Prefix appended to the SDK's User-Agent. Use it to identify the calling app (e.g. `"checkout-service/1.4.2"`). |
88
- | `headers` | `Record<string,string>` | `{}` | Extra headers merged into every request. |
89
- | `fetch` | `typeof fetch` | `globalThis.fetch` | Inject a custom `fetch` implementation (used in tests). |
90
-
91
- ## Retries, timeouts & streaming
92
-
93
- This is the reference SDK that the other-language clients mirror, so its
94
- transport behavior is deliberately precise:
95
-
96
- - **Retries** apply to `execute` only. The client retries network failures and
97
- `5xx` responses with exponential backoff plus jitter, up to `maxRetries`
98
- (default `2`). `4xx` responses (`400`/`401`/`403`/`404`/`429`) are **never**
99
- retried, nor are timeouts or caller-initiated aborts. `stream` is not retried
100
- automatically — re-issue the call yourself if a stream fails.
101
- - **Timeouts** are enforced per request via an internal `AbortController`. When
102
- `timeout` (default `60000` ms) elapses the underlying `fetch` is aborted and a
103
- `TimeoutError` is thrown. For streaming, the timeout covers establishing the
104
- response; long-lived streams that keep emitting events are not cut off by it.
105
- - **Cancellation**: pass `options.signal` (an `AbortSignal`) to either method.
106
- Aborting cancels the in-flight HTTP request; for `stream` the iterator stops
107
- cleanly and the connection is released.
108
- - **Streaming protocol**: `stream` consumes Server-Sent Events from
109
- `POST /api/v1/gateway/stream`. Each `data:` frame is a JSON `StreamEvent`
110
- (`chunk` | `done` | `error`). The iterator yields `chunk` and `done` events;
111
- an `error` event is thrown as an `ApiError` carrying `errorCode`, `message`,
112
- and `requestId`. The stream always ends after a `done` or `error` event.
113
-
114
- ## Error handling
115
-
116
- Every non-2xx response is translated into a typed error so consumers can branch on failure modes:
53
+ All optional when the environment variables are set.
117
54
 
118
- ```ts
119
- import {
120
- PromptHelm,
121
- AuthenticationError,
122
- AuthorizationError,
123
- NotFoundError,
124
- RateLimitError,
125
- ApiError,
126
- TimeoutError,
127
- } from "@prompt-helm/sdk";
128
-
129
- const ph = new PromptHelm({
130
- apiKey: process.env.PROMPTHELM_API_KEY ?? "<your-api-token>",
131
- });
55
+ | Option | Default | What it does |
56
+ | --------- | ------------------------------------------------- | -------------------------------------------------------------------- |
57
+ | `apiKey` | `PROMPTHELM_API_KEY` | Your project's API key. Keep it on the server. |
58
+ | `baseUrl` | `PROMPTHELM_BASE_URL`, then `https://prompthelm.app` | Where prompts are fetched from. |
59
+ | `ttl` | `60000` | How long, in ms, a prompt is served before checking for a newer one. |
60
+ | `timeout` | `3000` | How long, in ms, one request may take. |
61
+ | `onError` | `console.warn` | Called with the error and the slug when a fallback or a cached prompt was served instead of failing. |
62
+ | `fetch` | global `fetch` | Your own fetch, for tests or a proxy. |
132
63
 
133
- try {
134
- const result = await ph.execute({ promptSlug: "welcome-email" });
135
- return result.output;
136
- } catch (err) {
137
- if (err instanceof AuthenticationError) {
138
- // Rotate or refresh the API key.
139
- } else if (err instanceof RateLimitError) {
140
- // Back off and retry later.
141
- } else if (err instanceof NotFoundError) {
142
- // The slug does not exist in this environment.
143
- } else if (err instanceof AuthorizationError) {
144
- // The key cannot access this prompt.
145
- } else if (err instanceof TimeoutError) {
146
- // The request exceeded the configured timeout.
147
- } else if (err instanceof ApiError) {
148
- // 5xx or unknown server error. Safe to retry with backoff.
149
- }
150
- throw err;
151
- }
152
- ```
64
+ ## Errors
153
65
 
154
- Every `PromptHelmError` exposes `statusCode`, `errorCode`, and `requestId` so failures can be filed against PromptHelm support with full traceability. Quote the `requestId` when contacting support — it correlates your call to the server-side execution log.
66
+ Failures are `PromptHelmError`s with a `code`, a `message` and, for HTTP errors, a `status`.
67
+ Without a `fallback`, `get` throws them; with one, `onError` receives them.
155
68
 
156
- ## API reference
69
+ | Code | When |
70
+ | ------------------- | ---------------------------------------------------------- |
71
+ | `unauthorized` | The API key is missing, wrong or revoked. |
72
+ | `not_found` | The project has no published prompt with that slug. |
73
+ | `missing_variables` | The live version uses a variable the call doesn't pass. |
74
+ | `timeout` | No response within the timeout. |
75
+ | `network` | PromptHelm couldn't be reached. |
76
+ | `server` | Anything else, such as a 5xx response. |
157
77
 
158
- ### `new PromptHelm(config: PromptHelmConfig)`
78
+ After the first successful fetch, a failed background refresh keeps serving the cached prompt
79
+ and tries again after one ttl.
159
80
 
160
- Construct a client. Throws synchronously if `apiKey` is missing or malformed, if `baseURL` is invalid, or if `timeout` / `maxRetries` are out of range.
81
+ ## Keep fallbacks current
161
82
 
162
- ### `execute(request, options?): Promise<ExecuteResponse>`
83
+ A fallback is only as good as its text, and a copy kept in your code drifts from what you
84
+ publish. `pull` writes every published prompt of the project to one file, keyed by slug:
163
85
 
164
- Performs a single non-streaming gateway call.
86
+ ```sh
87
+ npx @prompt-helm/sdk pull --out src/prompthelm.fallbacks.ts
88
+ ```
165
89
 
166
- `request` accepts:
90
+ ```ts
91
+ import { fallbacks } from "./prompthelm.fallbacks";
167
92
 
168
- - `promptSlug?: string` — managed prompt slug.
169
- - `promptId?: string` — managed prompt id (alternative to `promptSlug`).
170
- - `variables?: Record<string, string>` — template variables.
171
- - `system?: string`, `user?: string` — ad-hoc messages.
172
- - `model?: string` — override the prompt's default model.
173
- - `temperature?`, `maxTokens?`, `topP?`, `stopSequences?` — provider parameters.
174
- - `environment?: "production" | "development"` — which prompt branch to resolve.
175
- - `timeoutMs?: number` — server-side execution deadline.
93
+ const system = await ph.get("support-reply", {
94
+ vars: { company: "Acme", customer_name: user.name },
95
+ fallback: fallbacks["support-reply"],
96
+ });
97
+ ```
176
98
 
177
- `options.signal` lets you cancel mid-flight.
99
+ Run it in CI before the build, so every deploy carries the text that was live then. It reads
100
+ `PROMPTHELM_API_KEY` (and `PROMPTHELM_BASE_URL`), and writes JSON for a `.json` path or with
101
+ `--format json`. A prompt appears in the file once it's published.
178
102
 
179
- ### `stream(request, options?): AsyncIterable<StreamEvent>`
103
+ ## Other languages
180
104
 
181
- Same request shape as `execute`. Yields:
105
+ Any language can fetch the live version with one request:
182
106
 
183
- - `{ type: "chunk", content: string }` — incremental output.
184
- - `{ type: "done", inputTokens, outputTokens, totalTokens, cost, model, latencyMs }` — final usage and pricing.
107
+ ```sh
108
+ curl https://prompthelm.app/v1/prompts/support-reply \
109
+ -H "Authorization: Bearer $PROMPTHELM_API_KEY"
110
+ ```
185
111
 
186
- If the server emits `{ type: "error", errorCode, message, requestId }`, the iterator throws an `ApiError` exposing those fields. If the external `AbortSignal` fires, the iterator stops and the underlying HTTP request is cancelled.
112
+ `GET /v1/prompts` returns every published prompt of the key's project at once, as
113
+ `{ "prompts": [ … ] }`.
187
114
 
188
- ## Versioning
115
+ ## Links
189
116
 
190
- `@prompt-helm/sdk` follows [Semantic Versioning](https://semver.org). Breaking changes will only ship on a major version bump. See the changelog for details.
117
+ - [Quickstart](https://prompthelm.app/quickstart)
118
+ - [Changing a prompt without a redeploy](https://prompthelm.app/guides/change-prompts-without-redeploying)
119
+ - [Prompt versioning and rollback](https://prompthelm.app/guides/prompt-versioning)
120
+ - [Pricing](https://prompthelm.app/pricing)
191
121
 
192
122
  ## License
193
123
 
194
- MIT — see [LICENSE](./LICENSE).
124
+ MIT
package/dist/cli.js ADDED
@@ -0,0 +1,146 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/pull.ts
4
+ import { mkdir, writeFile } from "fs/promises";
5
+ import { dirname, extname } from "path";
6
+
7
+ // src/errors.ts
8
+ var PromptHelmError = class extends Error {
9
+ constructor(code, message, status) {
10
+ super(message);
11
+ this.code = code;
12
+ this.status = status;
13
+ }
14
+ code;
15
+ status;
16
+ name = "PromptHelmError";
17
+ };
18
+
19
+ // src/client.ts
20
+ var DEFAULT_BASE_URL = "https://prompthelm.app";
21
+ async function errorFromResponse(response) {
22
+ const body = await response.json().catch(() => null);
23
+ const message = body?.error?.message ?? `HTTP ${response.status}`;
24
+ const code = response.status === 401 || response.status === 403 ? "unauthorized" : response.status === 404 ? "not_found" : "server";
25
+ return new PromptHelmError(code, message, response.status);
26
+ }
27
+
28
+ // src/pull.ts
29
+ var DEFAULT_OUT = "prompthelm.fallbacks.json";
30
+ var TIMEOUT_MS = 1e4;
31
+ var USAGE = `Usage: npx @prompt-helm/sdk pull [--out <file>] [--format json|ts]
32
+
33
+ Writes the live text of every published prompt in the project to one file, keyed by slug,
34
+ to pass to get() as its fallback.
35
+
36
+ --out <file> Where to write it. Default: ${DEFAULT_OUT}
37
+ --format <name> json or ts. Default: from the file's extension.
38
+
39
+ Reads PROMPTHELM_API_KEY, and PROMPTHELM_BASE_URL when it's set.`;
40
+ var TS_HEADER = `// Written by \`npx @prompt-helm/sdk pull\`: the live text of each prompt, to pass to get() as
41
+ // its fallback. Run it again to refresh it; edits here are overwritten.
42
+ `;
43
+ function parsePullArgs(args) {
44
+ let out = DEFAULT_OUT;
45
+ let format;
46
+ for (let index = 0; index < args.length; index++) {
47
+ const arg = args[index] ?? "";
48
+ if (arg === "-h" || arg === "--help") return "help";
49
+ const match = /^--(out|format)(?:=(.*))?$/.exec(arg);
50
+ if (!match) return { error: `Unknown argument: ${arg}` };
51
+ const value = match[2] ?? args[++index];
52
+ if (!value) return { error: `--${match[1]} needs a value` };
53
+ if (match[1] === "out") out = value;
54
+ else format = value;
55
+ }
56
+ format ??= formatFromExtension(out);
57
+ if (format === "json" || format === "ts") return { out, format };
58
+ return format === void 0 ? { error: `Can't tell the format from "${out}": pass --format json or --format ts` } : { error: `Unknown format "${format}": use json or ts` };
59
+ }
60
+ function formatFromExtension(path) {
61
+ const extension = extname(path).toLowerCase();
62
+ if (extension === ".json") return "json";
63
+ if (extension === ".ts" || extension === ".mts" || extension === ".cts") return "ts";
64
+ return void 0;
65
+ }
66
+ async function fetchLivePrompts(options) {
67
+ const request = options.fetch ?? globalThis.fetch;
68
+ let response;
69
+ try {
70
+ response = await request(`${options.baseUrl.replace(/\/+$/, "")}/v1/prompts`, {
71
+ headers: { authorization: `Bearer ${options.apiKey}`, accept: "application/json" },
72
+ signal: AbortSignal.timeout(TIMEOUT_MS)
73
+ });
74
+ } catch (error) {
75
+ if (error?.name === "TimeoutError") {
76
+ throw new PromptHelmError("timeout", `No response within ${TIMEOUT_MS} ms`);
77
+ }
78
+ throw new PromptHelmError("network", error instanceof Error ? error.message : String(error));
79
+ }
80
+ if (!response.ok) throw await errorFromResponse(response);
81
+ return (await response.json()).prompts;
82
+ }
83
+ function renderFallbacks(prompts, format) {
84
+ const sorted = [...prompts].sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
85
+ const json = JSON.stringify(Object.fromEntries(sorted.map((p) => [p.slug, p.content])), null, 2);
86
+ return format === "json" ? `${json}
87
+ ` : `${TS_HEADER}export const fallbacks = ${json} as const;
88
+ `;
89
+ }
90
+ var nodeIO = () => ({
91
+ env: process.env,
92
+ log: (message) => console.log(message),
93
+ error: (message) => console.error(message),
94
+ write: async (path, text) => {
95
+ await mkdir(dirname(path), { recursive: true });
96
+ await writeFile(path, text);
97
+ }
98
+ });
99
+ async function runCli(argv, io = nodeIO()) {
100
+ const [command, ...rest] = argv;
101
+ if (command === "-h" || command === "--help") {
102
+ io.log(USAGE);
103
+ return 0;
104
+ }
105
+ if (command !== "pull") {
106
+ io.error(command ? `Unknown command: ${command}
107
+
108
+ ${USAGE}` : USAGE);
109
+ return 1;
110
+ }
111
+ const parsed = parsePullArgs(rest);
112
+ if (parsed === "help") {
113
+ io.log(USAGE);
114
+ return 0;
115
+ }
116
+ if ("error" in parsed) {
117
+ io.error(`${parsed.error}
118
+
119
+ ${USAGE}`);
120
+ return 1;
121
+ }
122
+ const apiKey = io.env.PROMPTHELM_API_KEY;
123
+ if (!apiKey) {
124
+ io.error("Set PROMPTHELM_API_KEY to an API key of the project to pull.");
125
+ return 1;
126
+ }
127
+ try {
128
+ const prompts = await fetchLivePrompts({
129
+ apiKey,
130
+ baseUrl: io.env.PROMPTHELM_BASE_URL || DEFAULT_BASE_URL,
131
+ fetch: io.fetch
132
+ });
133
+ await io.write(parsed.out, renderFallbacks(prompts, parsed.format));
134
+ io.log(
135
+ prompts.length === 0 ? `No published prompts yet; wrote an empty list to ${parsed.out}.` : `Wrote ${prompts.length} ${prompts.length === 1 ? "prompt" : "prompts"} to ${parsed.out}:
136
+ ${prompts.map((p) => ` ${p.slug} v${p.version}`).join("\n")}`
137
+ );
138
+ return 0;
139
+ } catch (error) {
140
+ io.error(`PromptHelm: ${error instanceof Error ? error.message : String(error)}`);
141
+ return 1;
142
+ }
143
+ }
144
+
145
+ // src/cli.ts
146
+ process.exitCode = await runCli(process.argv.slice(2));