@keln.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +6 -0
  4. package/README.md +598 -2
  5. package/dist/api-promise.d.ts +30 -0
  6. package/dist/api-promise.js +38 -0
  7. package/dist/api-promise.js.map +1 -0
  8. package/dist/api.d.ts +130 -0
  9. package/dist/api.js +321 -0
  10. package/dist/api.js.map +1 -0
  11. package/dist/client.d.ts +27 -0
  12. package/dist/client.js +42 -0
  13. package/dist/client.js.map +1 -0
  14. package/dist/commands.d.ts +78 -0
  15. package/dist/commands.js +269 -0
  16. package/dist/commands.js.map +1 -0
  17. package/dist/errors.d.ts +93 -0
  18. package/dist/errors.js +173 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/files.d.ts +33 -0
  21. package/dist/files.js +130 -0
  22. package/dist/files.js.map +1 -0
  23. package/dist/images.d.ts +79 -0
  24. package/dist/images.js +150 -0
  25. package/dist/images.js.map +1 -0
  26. package/dist/index.d.ts +23 -0
  27. package/dist/index.js +14 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/inference.d.ts +672 -0
  30. package/dist/inference.js +244 -0
  31. package/dist/inference.js.map +1 -0
  32. package/dist/retry.d.ts +10 -0
  33. package/dist/retry.js +87 -0
  34. package/dist/retry.js.map +1 -0
  35. package/dist/sandbox.d.ts +132 -0
  36. package/dist/sandbox.js +216 -0
  37. package/dist/sandbox.js.map +1 -0
  38. package/dist/sse.d.ts +20 -0
  39. package/dist/sse.js +119 -0
  40. package/dist/sse.js.map +1 -0
  41. package/dist/streaming.d.ts +20 -0
  42. package/dist/streaming.js +77 -0
  43. package/dist/streaming.js.map +1 -0
  44. package/dist/terminals.d.ts +75 -0
  45. package/dist/terminals.js +239 -0
  46. package/dist/terminals.js.map +1 -0
  47. package/dist/types.d.ts +226 -0
  48. package/dist/types.js +6 -0
  49. package/dist/types.js.map +1 -0
  50. package/dist/uploads.d.ts +35 -0
  51. package/dist/uploads.js +154 -0
  52. package/dist/uploads.js.map +1 -0
  53. package/dist/util.d.ts +19 -0
  54. package/dist/util.js +69 -0
  55. package/dist/util.js.map +1 -0
  56. package/dist/web.d.ts +66 -0
  57. package/dist/web.js +44 -0
  58. package/dist/web.js.map +1 -0
  59. package/package.json +57 -4
  60. package/src/api-promise.ts +50 -0
  61. package/src/api.ts +415 -0
  62. package/src/client.ts +43 -0
  63. package/src/commands.ts +325 -0
  64. package/src/errors.ts +185 -0
  65. package/src/files.ts +149 -0
  66. package/src/images.ts +174 -0
  67. package/src/index.ts +114 -0
  68. package/src/inference.ts +737 -0
  69. package/src/retry.ts +77 -0
  70. package/src/sandbox.ts +281 -0
  71. package/src/sse.ts +124 -0
  72. package/src/streaming.ts +79 -0
  73. package/src/terminals.ts +269 -0
  74. package/src/types.ts +241 -0
  75. package/src/uploads.ts +177 -0
  76. package/src/util.ts +78 -0
  77. package/src/web.ts +94 -0
package/dist/api.d.ts ADDED
@@ -0,0 +1,130 @@
1
+ import WebSocket from 'ws';
2
+ import { type ApiResult } from './api-promise.js';
3
+ import { KelnConnectionError } from './errors.js';
4
+ import { Stream } from './streaming.js';
5
+ export declare const DEFAULT_BASE_URL = "https://sandbox.keln.ai";
6
+ export declare const DEFAULT_API_URL = "https://api.keln.ai";
7
+ export declare const USER_AGENT = "keln-sdk-typescript/0.1.0";
8
+ export type KelnOptions = {
9
+ /** A Keln API key. Defaults to the `KELN_API_KEY` environment variable. */
10
+ apiKey?: string;
11
+ /**
12
+ * The Sandbox API's address, an `http` or `https` URL. Defaults to `KELN_SANDBOX_URL`, then
13
+ * `https://sandbox.keln.ai`.
14
+ */
15
+ baseUrl?: string;
16
+ /**
17
+ * The address of inference (`keln.chat`, `keln.responses`, `keln.embeddings`, `keln.rerank`, `keln.decisions`,
18
+ * `keln.audio`, `keln.images`), `keln.models` and `keln.web`, an `http` or `https` URL. Defaults to `KELN_API_URL`,
19
+ * then `https://api.keln.ai`.
20
+ */
21
+ apiUrl?: string;
22
+ /**
23
+ * A `fetch` to send every HTTP request through (tests, proxies). Terminal sockets connect to `baseUrl` directly.
24
+ * Defaults to the global `fetch`.
25
+ */
26
+ fetch?: typeof globalThis.fetch;
27
+ /**
28
+ * How many times a failed call tries again. On api.keln.ai: after a transport failure, a `408`, `409`, `429` or
29
+ * `5xx`, default 2. For a sandbox call that is safe to repeat: after a transport failure, a `429`, `502` or `503`,
30
+ * default 5. A `409 idempotency_key_in_use` is waited out and does not count.
31
+ */
32
+ maxRetries?: number;
33
+ /**
34
+ * How long a command's event stream may stay silent before it counts as dropped. The API sends a ping while a
35
+ * stream is idle.
36
+ * Default 45000; `0` turns the timer off.
37
+ */
38
+ streamIdleTimeoutMs?: number;
39
+ /** Reattaches in a row that may deliver nothing before a command's stream fails. Default 5. */
40
+ maxReattachAttempts?: number;
41
+ };
42
+ export type RequestOptions = {
43
+ query?: URLSearchParams | Record<string, string>;
44
+ json?: unknown;
45
+ body?: Uint8Array | ReadableStream<Uint8Array>;
46
+ headers?: Record<string, string>;
47
+ signal?: AbortSignal;
48
+ /** The call can be repeated, whatever its method. */
49
+ safe?: boolean;
50
+ };
51
+ /** A call on api.keln.ai. */
52
+ export type ApiCallOptions = {
53
+ /** Default `POST`. A `GET` sends no body. */
54
+ method?: 'GET' | 'POST';
55
+ json: unknown;
56
+ /** A multipart body in place of `json` (a file upload). It is buffered, so every try sends it whole. */
57
+ form?: FormData;
58
+ query?: Record<string, string>;
59
+ headers?: Record<string, string>;
60
+ signal?: AbortSignal;
61
+ /** Milliseconds the call may take in all, retries and waits included. Default: no limit. */
62
+ timeout?: number;
63
+ /** When the call began, `Date.now()`, for one that did work before it sent: its `timeout` counts from here. */
64
+ startedAt?: number;
65
+ /** What the call is, for messages: `chat completion`, `rerank`. */
66
+ operation: string;
67
+ };
68
+ /**
69
+ * Every call to the API. The key lives in a private field here and goes only to `baseUrl` and `apiUrl`, so it cannot
70
+ * reach a log through this object, and any text that comes back passes `redact` on its way into an exception.
71
+ */
72
+ export declare class Api {
73
+ #private;
74
+ readonly baseUrl: string;
75
+ readonly apiUrl: string;
76
+ readonly maxRetries: number;
77
+ readonly apiMaxRetries: number;
78
+ readonly streamIdleTimeoutMs: number;
79
+ readonly maxReattachAttempts: number;
80
+ constructor(options: KelnOptions);
81
+ redact(text: string): string;
82
+ /** A transport failure as a `KelnConnectionError`. A cause whose text holds the key is left out. */
83
+ connectionError(cause: unknown, message?: string): KelnConnectionError;
84
+ /**
85
+ * Runs `attempt`, trying again by the Sandbox API's retry rules when `safe` is true. An abort ends it at once with the
86
+ * signal's reason, and anything that is not one of this SDK's errors is a transport failure. A `409
87
+ * idempotency_key_in_use` means the first request with the key has not finished: it is waited out, for as long as
88
+ * `Retry-After` says or with the usual backoff, and does not count against `maxRetries`.
89
+ */
90
+ retrying<T>(safe: boolean, signal: AbortSignal | undefined, attempt: () => Promise<T>): Promise<T>;
91
+ /**
92
+ * Sends one call, with its retries. A non-2xx answer throws `KelnApiError` built from the complete body. `read`
93
+ * runs inside the retries, so an answer lost halfway is asked for again; without it the caller gets the response
94
+ * with its body unread.
95
+ */
96
+ request(method: string, path: string, options?: RequestOptions): Promise<Response>;
97
+ request<T>(method: string, path: string, options: RequestOptions, read: (response: Response) => Promise<T>): Promise<T>;
98
+ /** A call whose answer is a JSON object. */
99
+ json<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
100
+ /**
101
+ * One call on api.keln.ai, with its retries (retry.ts): a transport failure, a `408`, `409`, `429` or `5xx` goes
102
+ * round again, up to `apiMaxRetries` times, the try number in `x-keln-retry-count`. `read` runs inside the retries,
103
+ * so an answer lost halfway is asked for again; without it the caller gets the response with its body unread (a
104
+ * stream, which is not retried once it starts). `options.timeout` bounds the whole call; a wait it cannot cover throws
105
+ * the failure at once. An abort of `options.signal` throws its reason.
106
+ */
107
+ apiCall(path: string, options: ApiCallOptions): Promise<Response>;
108
+ apiCall<T>(path: string, options: ApiCallOptions, read: (response: Response) => Promise<T>): Promise<T>;
109
+ /** A streamed answer on api.keln.ai. Opening it retries; once it has started, a failure throws. */
110
+ apiStream<T>(path: string, options: ApiCallOptions): Promise<ApiResult<Stream<T>>>;
111
+ /**
112
+ * Work a call does before it sends, such as reading an upload into memory, under the call's `signal` and `timeout`
113
+ * (counted from `options.startedAt`): an abort throws the signal's reason, and the timeout `KelnTimeoutError`, at
114
+ * once. `work` gets a signal that aborts then, to stop what it reads.
115
+ */
116
+ before<T>(options: ApiCallOptions, work: (signal: AbortSignal | undefined) => Promise<T>): Promise<T>;
117
+ /** A call on api.keln.ai whose answer is a JSON object, with the API's id for the request on it as `_request_id`. */
118
+ apiJson<T extends object>(path: string, options: ApiCallOptions): Promise<ApiResult<T>>;
119
+ /** A call on api.keln.ai whose answer is plain text (a transcription as `text`, `srt` or `vtt`). */
120
+ apiText(path: string, options: ApiCallOptions): Promise<ApiResult<string>>;
121
+ /** A call on api.keln.ai whose answer is bytes (speech's audio). Read whole inside the retries. */
122
+ apiBytes(path: string, options: ApiCallOptions): Promise<ApiResult<Uint8Array>>;
123
+ /** A call whose answer has nothing to read. */
124
+ send(method: string, path: string, options?: RequestOptions): Promise<void>;
125
+ /**
126
+ * A WebSocket to `path`, connecting, straight to `baseUrl`: it does not go through `fetch`. No size limit and no
127
+ * handshake timeout of ours: the caller's signal decides.
128
+ */
129
+ webSocket(path: string): WebSocket;
130
+ }
package/dist/api.js ADDED
@@ -0,0 +1,321 @@
1
+ import WebSocket from 'ws';
2
+ import { requestIdOf } from './api-promise.js';
3
+ import { KelnApiError, KelnConnectionError, KelnError, KelnTimeoutError, apiError, isKeyInUse, isRetryable } from './errors.js';
4
+ import { DEFAULT_API_MAX_RETRIES, platformHeaders, retryDelayMs, shouldRetry } from './retry.js';
5
+ import { Stream } from './streaming.js';
6
+ import { VERSION, backoffMs, sleep, untilAborted } from './util.js';
7
+ export const DEFAULT_BASE_URL = 'https://sandbox.keln.ai';
8
+ export const DEFAULT_API_URL = 'https://api.keln.ai';
9
+ export const USER_AGENT = `keln-sdk-typescript/${VERSION}`;
10
+ /** The messages of an error and its causes: `fetch failed: connect ECONNREFUSED`, not just `fetch failed`. */
11
+ function describe(error) {
12
+ const parts = [];
13
+ for (let e = error; e !== undefined && e !== null && parts.length < 5; e = e.cause) {
14
+ parts.push(e instanceof Error ? e.message : String(e));
15
+ }
16
+ return parts.join(': ');
17
+ }
18
+ /** Headers by lowercase name. A later source's header replaces an earlier one's of the same name, whatever its case. */
19
+ function headersOf(...sources) {
20
+ const headers = {};
21
+ for (const source of sources) {
22
+ for (const [name, value] of Object.entries(source ?? {}))
23
+ headers[name.toLowerCase()] = value;
24
+ }
25
+ return headers;
26
+ }
27
+ /** An address the SDK sends to, without its trailing slashes. Anything but an http or https URL throws `KelnError`. */
28
+ function address(option, variable, value) {
29
+ let protocol;
30
+ try {
31
+ protocol = new URL(value).protocol;
32
+ }
33
+ catch {
34
+ protocol = undefined;
35
+ }
36
+ if (protocol !== 'http:' && protocol !== 'https:') {
37
+ throw new KelnError(`${option} (or ${variable}) must be an http or https URL.`);
38
+ }
39
+ return value.replace(/\/+$/, '');
40
+ }
41
+ function scopeOf(options, own) {
42
+ const deadline = options.timeout === undefined ? undefined : (options.startedAt ?? Date.now()) + options.timeout;
43
+ const timer = deadline === undefined ? undefined : AbortSignal.timeout(Math.max(deadline - Date.now(), 0));
44
+ const signals = [options.signal, timer, own].filter((s) => s !== undefined);
45
+ const signal = signals.length === 0 ? undefined : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
46
+ const reason = () => {
47
+ if (options.signal?.aborted === true)
48
+ return options.signal.reason;
49
+ if (timer?.aborted === true)
50
+ return new KelnTimeoutError(`Keln ${options.operation} ran past its timeout.`);
51
+ return own?.reason;
52
+ };
53
+ return { deadline, timer, signal, reason };
54
+ }
55
+ /**
56
+ * Every call to the API. The key lives in a private field here and goes only to `baseUrl` and `apiUrl`, so it cannot
57
+ * reach a log through this object, and any text that comes back passes `redact` on its way into an exception.
58
+ */
59
+ export class Api {
60
+ baseUrl;
61
+ apiUrl;
62
+ maxRetries;
63
+ apiMaxRetries;
64
+ streamIdleTimeoutMs;
65
+ maxReattachAttempts;
66
+ #apiKey;
67
+ #fetch;
68
+ constructor(options) {
69
+ const apiKey = options.apiKey || process.env.KELN_API_KEY;
70
+ if (!apiKey)
71
+ throw new KelnError('No Keln API key: pass apiKey, or set KELN_API_KEY.');
72
+ if (options.maxRetries !== undefined && !(Number.isInteger(options.maxRetries) && options.maxRetries >= 0)) {
73
+ throw new KelnError('maxRetries must be a non-negative integer.');
74
+ }
75
+ this.#apiKey = apiKey;
76
+ this.baseUrl = address('baseUrl', 'KELN_SANDBOX_URL', options.baseUrl || process.env.KELN_SANDBOX_URL || DEFAULT_BASE_URL);
77
+ this.apiUrl = address('apiUrl', 'KELN_API_URL', options.apiUrl || process.env.KELN_API_URL || DEFAULT_API_URL);
78
+ this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
79
+ this.maxRetries = options.maxRetries ?? 5;
80
+ this.apiMaxRetries = options.maxRetries ?? DEFAULT_API_MAX_RETRIES;
81
+ this.streamIdleTimeoutMs = options.streamIdleTimeoutMs ?? 45_000;
82
+ this.maxReattachAttempts = options.maxReattachAttempts ?? 5;
83
+ }
84
+ redact(text) {
85
+ return text.replaceAll(this.#apiKey, '[redacted]');
86
+ }
87
+ /** A transport failure as a `KelnConnectionError`. A cause whose text holds the key is left out. */
88
+ connectionError(cause, message = 'Could not reach the Keln Sandbox API') {
89
+ const text = describe(cause);
90
+ const clean = this.redact(text);
91
+ return new KelnConnectionError(`${message}: ${clean}`, cause instanceof Error && clean === text ? { cause } : {});
92
+ }
93
+ /**
94
+ * Runs `attempt`, trying again by the Sandbox API's retry rules when `safe` is true. An abort ends it at once with the
95
+ * signal's reason, and anything that is not one of this SDK's errors is a transport failure. A `409
96
+ * idempotency_key_in_use` means the first request with the key has not finished: it is waited out, for as long as
97
+ * `Retry-After` says or with the usual backoff, and does not count against `maxRetries`.
98
+ */
99
+ async retrying(safe, signal, attempt) {
100
+ let retries = 0;
101
+ let waits = 0;
102
+ while (true) {
103
+ try {
104
+ return await attempt();
105
+ }
106
+ catch (error) {
107
+ if (signal?.aborted)
108
+ throw signal.reason;
109
+ const failure = error instanceof KelnError ? error : this.connectionError(error);
110
+ if (!safe)
111
+ throw failure;
112
+ const retryAfter = failure instanceof KelnApiError ? failure.retryAfter : undefined;
113
+ if (isKeyInUse(failure)) {
114
+ waits += 1;
115
+ await sleep(backoffMs(waits, retryAfter), signal);
116
+ continue;
117
+ }
118
+ retries += 1;
119
+ if (retries > this.maxRetries || !isRetryable(failure))
120
+ throw failure;
121
+ await sleep(backoffMs(retries, retryAfter), signal);
122
+ }
123
+ }
124
+ }
125
+ async request(method, path, options = {}, read) {
126
+ let url = `${path.startsWith('/v1/web/') ? this.apiUrl : this.baseUrl}${path}`;
127
+ if (options.query !== undefined) {
128
+ const query = new URLSearchParams(options.query).toString();
129
+ if (query !== '')
130
+ url += `?${query}`;
131
+ }
132
+ const headers = headersOf({ authorization: `Bearer ${this.#apiKey}`, 'user-agent': USER_AGENT, ...platformHeaders() }, options.headers);
133
+ let body = options.body;
134
+ if (options.json !== undefined) {
135
+ headers['content-type'] = 'application/json';
136
+ body = JSON.stringify(options.json);
137
+ }
138
+ // The API never redirects; following one would send the key to another address.
139
+ const init = { method, headers, redirect: 'manual' };
140
+ if (body !== undefined)
141
+ init.body = body;
142
+ if (body instanceof ReadableStream)
143
+ init.duplex = 'half'; // a streamed upload
144
+ if (options.signal !== undefined)
145
+ init.signal = options.signal;
146
+ const safe = options.safe === true || method === 'GET' || method === 'DELETE' || headers['idempotency-key'] !== undefined;
147
+ return await this.retrying(safe, options.signal, async () => {
148
+ const response = await this.#fetch(url, init);
149
+ if (!response.ok) {
150
+ const text = await response.text().catch(() => '');
151
+ throw apiError(response.status, this.redact(text), response.headers.get('retry-after'), response.headers);
152
+ }
153
+ return read === undefined ? response : await read(response);
154
+ });
155
+ }
156
+ /** A call whose answer is a JSON object. */
157
+ async json(method, path, options = {}) {
158
+ return await this.request(method, path, options, async (response) => {
159
+ const text = await response.text();
160
+ let value;
161
+ try {
162
+ value = JSON.parse(text);
163
+ }
164
+ catch {
165
+ value = undefined;
166
+ }
167
+ if (value === null || typeof value !== 'object') {
168
+ throw new KelnApiError({
169
+ status: response.status,
170
+ message: 'The response body is not a JSON object.',
171
+ body: this.redact(text),
172
+ });
173
+ }
174
+ return value;
175
+ });
176
+ }
177
+ async apiCall(path, options, read) {
178
+ return (await this.#apiCall(path, options, read, undefined)).value;
179
+ }
180
+ /** A streamed answer on api.keln.ai. Opening it retries; once it has started, a failure throws. */
181
+ async apiStream(path, options) {
182
+ const controller = new AbortController();
183
+ const sent = { ...options, headers: headersOf({ accept: 'text/event-stream' }, options.headers) };
184
+ const { value, timer } = await this.#apiCall(path, sent, undefined, controller.signal);
185
+ const stream = new Stream(value, controller, options.operation, {
186
+ timeout: timer,
187
+ signal: options.signal,
188
+ redact: (text) => this.redact(text),
189
+ });
190
+ return { data: stream, response: value };
191
+ }
192
+ /**
193
+ * Work a call does before it sends, such as reading an upload into memory, under the call's `signal` and `timeout`
194
+ * (counted from `options.startedAt`): an abort throws the signal's reason, and the timeout `KelnTimeoutError`, at
195
+ * once. `work` gets a signal that aborts then, to stop what it reads.
196
+ */
197
+ async before(options, work) {
198
+ const { signal, reason } = scopeOf(options, undefined);
199
+ if (signal === undefined)
200
+ return await work(undefined);
201
+ try {
202
+ return await untilAborted(work(signal), signal, () => { });
203
+ }
204
+ catch (error) {
205
+ if (signal.aborted)
206
+ throw reason();
207
+ throw error;
208
+ }
209
+ }
210
+ async #apiCall(path, options, read, own) {
211
+ let url = `${this.apiUrl}${path}`;
212
+ if (options.query !== undefined) {
213
+ const query = new URLSearchParams(options.query).toString();
214
+ if (query !== '')
215
+ url += `?${query}`;
216
+ }
217
+ const { deadline, timer, signal, reason } = scopeOf(options, own);
218
+ const method = options.method ?? 'POST';
219
+ // A form sets its own content type, with the boundary, when fetch sends it.
220
+ const body = method === 'GET' ? undefined : (options.form ?? JSON.stringify(options.json));
221
+ for (let retriesTaken = 0;; retriesTaken++) {
222
+ const headers = headersOf({
223
+ authorization: `Bearer ${this.#apiKey}`,
224
+ 'user-agent': USER_AGENT,
225
+ ...(typeof body === 'string' && { 'content-type': 'application/json' }),
226
+ ...platformHeaders(),
227
+ 'x-keln-retry-count': String(retriesTaken),
228
+ }, options.headers);
229
+ // The API never redirects; following one would send the key to another address.
230
+ const init = { method, headers, redirect: 'manual' };
231
+ if (body !== undefined)
232
+ init.body = body;
233
+ if (signal !== undefined)
234
+ init.signal = signal;
235
+ let failure;
236
+ let wait;
237
+ try {
238
+ const response = await this.#fetch(url, init);
239
+ if (response.ok)
240
+ return { value: read === undefined ? response : await read(response), timer };
241
+ const text = await response.text().catch(() => '');
242
+ failure = apiError(response.status, this.redact(text), response.headers.get('retry-after'), response.headers);
243
+ if (retriesTaken >= this.apiMaxRetries || !shouldRetry(response.status, response.headers))
244
+ throw failure;
245
+ wait = retryDelayMs(retriesTaken, response.headers);
246
+ }
247
+ catch (error) {
248
+ if (signal?.aborted)
249
+ throw reason();
250
+ if (error instanceof KelnApiError)
251
+ throw error;
252
+ failure = error instanceof KelnError ? error : this.connectionError(error, `Keln ${options.operation} failed`);
253
+ if (retriesTaken >= this.apiMaxRetries)
254
+ throw failure;
255
+ wait = retryDelayMs(retriesTaken, undefined);
256
+ }
257
+ if (deadline !== undefined && wait >= deadline - Date.now())
258
+ throw failure;
259
+ try {
260
+ await sleep(wait, signal);
261
+ }
262
+ catch {
263
+ throw reason();
264
+ }
265
+ }
266
+ }
267
+ /** A call on api.keln.ai whose answer is a JSON object, with the API's id for the request on it as `_request_id`. */
268
+ async apiJson(path, options) {
269
+ return await this.apiCall(path, options, async (response) => {
270
+ const text = await response.text();
271
+ let value;
272
+ try {
273
+ value = JSON.parse(text);
274
+ }
275
+ catch {
276
+ value = undefined;
277
+ }
278
+ const requestId = requestIdOf(response.headers);
279
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
280
+ throw new KelnApiError({
281
+ status: undefined,
282
+ message: `The ${options.operation} response body is not a JSON object.`,
283
+ body: this.redact(text),
284
+ requestId,
285
+ });
286
+ }
287
+ Object.defineProperty(value, '_request_id', { value: requestId, enumerable: false, writable: false });
288
+ return { data: value, response };
289
+ });
290
+ }
291
+ /** A call on api.keln.ai whose answer is plain text (a transcription as `text`, `srt` or `vtt`). */
292
+ async apiText(path, options) {
293
+ return await this.apiCall(path, options, async (response) => ({ data: await response.text(), response }));
294
+ }
295
+ /** A call on api.keln.ai whose answer is bytes (speech's audio). Read whole inside the retries. */
296
+ async apiBytes(path, options) {
297
+ return await this.apiCall(path, options, async (response) => ({
298
+ data: new Uint8Array(await response.arrayBuffer()),
299
+ response,
300
+ }));
301
+ }
302
+ /** A call whose answer has nothing to read. */
303
+ async send(method, path, options = {}) {
304
+ await this.request(method, path, options, async (response) => {
305
+ await response.arrayBuffer();
306
+ });
307
+ }
308
+ /**
309
+ * A WebSocket to `path`, connecting, straight to `baseUrl`: it does not go through `fetch`. No size limit and no
310
+ * handshake timeout of ours: the caller's signal decides.
311
+ */
312
+ webSocket(path) {
313
+ return new WebSocket(`${this.baseUrl.replace(/^http/, 'ws')}${path}`, {
314
+ headers: { authorization: `Bearer ${this.#apiKey}`, 'user-agent': USER_AGENT },
315
+ maxPayload: 0,
316
+ followRedirects: false,
317
+ perMessageDeflate: false,
318
+ });
319
+ }
320
+ }
321
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,IAAI,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAkB,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,SAAS,EAAE,gBAAgB,EAAE,QAAQ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,EAAE,UAA0B,EAAE;QACnE,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE;YAC3D,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC;QAC/B,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACH,SAAS,CAAC,IAAY;QACpB,OAAO,IAAI,SAAS,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,IAAI,EAAE,EAAE;YACpE,OAAO,EAAE,EAAE,aAAa,EAAE,UAAU,IAAI,CAAC,OAAO,EAAE,EAAE,YAAY,EAAE,UAAU,EAAE;YAC9E,UAAU,EAAE,CAAC;YACb,eAAe,EAAE,KAAK;YACtB,iBAAiB,EAAE,KAAK;SACzB,CAAC,CAAC;IACL,CAAC;CACF"}
@@ -0,0 +1,27 @@
1
+ import { type KelnOptions } from './api.js';
2
+ import { SandboxImages } from './images.js';
3
+ import { Audio, Chat, Decisions, Embeddings, Images, Models, Rerank, Responses } from './inference.js';
4
+ import { Sandboxes, Templates } from './sandbox.js';
5
+ import { Web } from './web.js';
6
+ /**
7
+ * The Keln client. The key comes from `apiKey` or `KELN_API_KEY`; without one the constructor throws `KelnError`. The
8
+ * sandbox address comes from `baseUrl`, `KELN_SANDBOX_URL`, or `https://sandbox.keln.ai`, and the address of inference
9
+ * and `keln.web` from `apiUrl`, `KELN_API_URL`, or `https://api.keln.ai`. An address that is not an `http` or `https`
10
+ * URL throws `KelnError` too.
11
+ */
12
+ export declare class Keln {
13
+ readonly sandboxes: Sandboxes;
14
+ readonly templates: Templates;
15
+ /** Images saved from sandboxes. `keln.images` is image generation. */
16
+ readonly sandboxImages: SandboxImages;
17
+ readonly web: Web;
18
+ readonly chat: Chat;
19
+ readonly responses: Responses;
20
+ readonly embeddings: Embeddings;
21
+ readonly rerank: Rerank;
22
+ readonly decisions: Decisions;
23
+ readonly audio: Audio;
24
+ readonly images: Images;
25
+ readonly models: Models;
26
+ constructor(options?: KelnOptions);
27
+ }
package/dist/client.js ADDED
@@ -0,0 +1,42 @@
1
+ import { Api } from './api.js';
2
+ import { SandboxImages } from './images.js';
3
+ import { Audio, Chat, Decisions, Embeddings, Images, Models, Rerank, Responses } from './inference.js';
4
+ import { Sandboxes, Templates } from './sandbox.js';
5
+ import { Web } from './web.js';
6
+ /**
7
+ * The Keln client. The key comes from `apiKey` or `KELN_API_KEY`; without one the constructor throws `KelnError`. The
8
+ * sandbox address comes from `baseUrl`, `KELN_SANDBOX_URL`, or `https://sandbox.keln.ai`, and the address of inference
9
+ * and `keln.web` from `apiUrl`, `KELN_API_URL`, or `https://api.keln.ai`. An address that is not an `http` or `https`
10
+ * URL throws `KelnError` too.
11
+ */
12
+ export class Keln {
13
+ sandboxes;
14
+ templates;
15
+ /** Images saved from sandboxes. `keln.images` is image generation. */
16
+ sandboxImages;
17
+ web;
18
+ chat;
19
+ responses;
20
+ embeddings;
21
+ rerank;
22
+ decisions;
23
+ audio;
24
+ images;
25
+ models;
26
+ constructor(options = {}) {
27
+ const api = new Api(options);
28
+ this.sandboxes = new Sandboxes(api);
29
+ this.templates = new Templates(api);
30
+ this.sandboxImages = new SandboxImages(api);
31
+ this.web = new Web(api);
32
+ this.chat = new Chat(api);
33
+ this.responses = new Responses(api);
34
+ this.embeddings = new Embeddings(api);
35
+ this.rerank = new Rerank(api);
36
+ this.decisions = new Decisions(api);
37
+ this.audio = new Audio(api);
38
+ this.images = new Images(api);
39
+ this.models = new Models(api);
40
+ }
41
+ }
42
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAoB,MAAM,UAAU,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,IAAI,EA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B,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC;QAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC;IAChC,CAAC;CACF"}
@@ -0,0 +1,78 @@
1
+ import type { Api } from './api.js';
2
+ import type { CallOptions, CommandData, CommandEvent, CommandResult, CommandState } from './types.js';
3
+ /** What to run: a shell line, through `bash -lc`, or a program and its arguments, run directly. */
4
+ export type CommandLine = string | string[];
5
+ export type CommandOptions = CallOptions & {
6
+ /** Working directory (absolute). Defaults to the user's home. */
7
+ cwd?: string;
8
+ /** Environment variables, over the sandbox's own. */
9
+ env?: Record<string, string>;
10
+ /** `user` (the API's default) or `root`. */
11
+ user?: 'user' | 'root';
12
+ /** The API's timeout: it kills the command after this many seconds of running. Unset, the command runs on. */
13
+ timeoutS?: number;
14
+ /** Keep stdin open for `command.write()`. */
15
+ stdin?: boolean;
16
+ /** The `Idempotency-Key`. Defaults to a fresh one per call. A retry with it never runs the command twice. */
17
+ idempotencyKey?: string;
18
+ };
19
+ export type OutputOptions = {
20
+ /** Sees stdout as it arrives. A multi-byte character split across two events arrives whole. */
21
+ onStdout?: (text: string) => void;
22
+ /** Sees stderr as it arrives. */
23
+ onStderr?: (text: string) => void;
24
+ };
25
+ export type RunOptions = CommandOptions & OutputOptions;
26
+ /** One command, started in the background or found by id. Its fields are the API's, as of the last answer. */
27
+ export declare class Command {
28
+ #private;
29
+ id: string;
30
+ object: string;
31
+ sandboxId: string;
32
+ state: CommandState;
33
+ /** What ran (`["bash", "-lc", "<command>"]` for a shell line). */
34
+ argv: string[];
35
+ exitCode: number | null;
36
+ /** The API's `signal`, the signal that ended the command. `signal()` is the call that sends one. */
37
+ exitSignal: number | null;
38
+ oomKilled: boolean;
39
+ /** Whether stdin is open for writing. */
40
+ stdin: boolean;
41
+ startedAt: number;
42
+ endedAt: number | null;
43
+ /** The object as the API sent it. */
44
+ raw: CommandData;
45
+ /** Made by `sandbox.commands`. */
46
+ constructor(api: Api, data: CommandData);
47
+ /** Waits for the exit and returns the command's whole output, from its first event. Aborting leaves it running. */
48
+ wait(options?: CallOptions & OutputOptions): Promise<CommandResult>;
49
+ /** The command's events, from the start or after `lastEventId`, to its `exit` event. It reattaches by itself. */
50
+ events(options?: CallOptions & {
51
+ lastEventId?: string;
52
+ }): AsyncGenerator<CommandEvent>;
53
+ /** Reads the command again and updates this object. */
54
+ refresh(options?: CallOptions): Promise<this>;
55
+ /** Sends SIGKILL. Killing an exited command changes nothing. */
56
+ kill(options?: CallOptions): Promise<this>;
57
+ /** Sends a signal, by name (`SIGTERM`, `TERM`) or number (15). */
58
+ signal(signal: string | number, options?: CallOptions): Promise<this>;
59
+ /** Writes to the command's stdin, which needs `stdin: true` at the start. */
60
+ write(data: Uint8Array | string, options?: CallOptions): Promise<void>;
61
+ /** Sends end-of-file. Closing a closed stdin changes nothing. */
62
+ closeStdin(options?: CallOptions): Promise<void>;
63
+ }
64
+ /** The commands of one sandbox: `sandbox.commands`. */
65
+ export declare class Commands {
66
+ #private;
67
+ /** Made by `Sandbox`. */
68
+ constructor(api: Api, sandboxId: string);
69
+ /** Runs a command, waits for its exit and returns its result. Aborting stops the waiting, not the command. */
70
+ run(cmd: CommandLine, options?: RunOptions): Promise<CommandResult>;
71
+ /** Runs a command and iterates its events: `started`, `stdout`, `stderr`, `exit`. It reattaches by itself. */
72
+ stream(cmd: CommandLine, options?: CommandOptions): AsyncGenerator<CommandEvent>;
73
+ /** Starts a command in the background and returns it at once. */
74
+ start(cmd: CommandLine, options?: CommandOptions): Promise<Command>;
75
+ get(commandId: string, options?: CallOptions): Promise<Command>;
76
+ /** The sandbox's commands, running and exited, newest first. */
77
+ list(options?: CallOptions): Promise<Command[]>;
78
+ }