@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/src/api.ts ADDED
@@ -0,0 +1,415 @@
1
+ import WebSocket from 'ws';
2
+ import { requestIdOf, type ApiResult } 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
+
8
+ export const DEFAULT_BASE_URL = 'https://sandbox.keln.ai';
9
+ export const DEFAULT_API_URL = 'https://api.keln.ai';
10
+ export const USER_AGENT = `keln-sdk-typescript/${VERSION}`;
11
+
12
+ export type KelnOptions = {
13
+ /** A Keln API key. Defaults to the `KELN_API_KEY` environment variable. */
14
+ apiKey?: string;
15
+ /**
16
+ * The Sandbox API's address, an `http` or `https` URL. Defaults to `KELN_SANDBOX_URL`, then
17
+ * `https://sandbox.keln.ai`.
18
+ */
19
+ baseUrl?: string;
20
+ /**
21
+ * The address of inference (`keln.chat`, `keln.responses`, `keln.embeddings`, `keln.rerank`, `keln.decisions`,
22
+ * `keln.audio`, `keln.images`), `keln.models` and `keln.web`, an `http` or `https` URL. Defaults to `KELN_API_URL`,
23
+ * then `https://api.keln.ai`.
24
+ */
25
+ apiUrl?: string;
26
+ /**
27
+ * A `fetch` to send every HTTP request through (tests, proxies). Terminal sockets connect to `baseUrl` directly.
28
+ * Defaults to the global `fetch`.
29
+ */
30
+ fetch?: typeof globalThis.fetch;
31
+ /**
32
+ * How many times a failed call tries again. On api.keln.ai: after a transport failure, a `408`, `409`, `429` or
33
+ * `5xx`, default 2. For a sandbox call that is safe to repeat: after a transport failure, a `429`, `502` or `503`,
34
+ * default 5. A `409 idempotency_key_in_use` is waited out and does not count.
35
+ */
36
+ maxRetries?: number;
37
+ /**
38
+ * How long a command's event stream may stay silent before it counts as dropped. The API sends a ping while a
39
+ * stream is idle.
40
+ * Default 45000; `0` turns the timer off.
41
+ */
42
+ streamIdleTimeoutMs?: number;
43
+ /** Reattaches in a row that may deliver nothing before a command's stream fails. Default 5. */
44
+ maxReattachAttempts?: number;
45
+ };
46
+
47
+ export type RequestOptions = {
48
+ query?: URLSearchParams | Record<string, string>;
49
+ json?: unknown;
50
+ body?: Uint8Array | ReadableStream<Uint8Array>;
51
+ headers?: Record<string, string>;
52
+ signal?: AbortSignal;
53
+ /** The call can be repeated, whatever its method. */
54
+ safe?: boolean;
55
+ };
56
+
57
+ /** A call on api.keln.ai. */
58
+ export type ApiCallOptions = {
59
+ /** Default `POST`. A `GET` sends no body. */
60
+ method?: 'GET' | 'POST';
61
+ json: unknown;
62
+ /** A multipart body in place of `json` (a file upload). It is buffered, so every try sends it whole. */
63
+ form?: FormData;
64
+ query?: Record<string, string>;
65
+ headers?: Record<string, string>;
66
+ signal?: AbortSignal;
67
+ /** Milliseconds the call may take in all, retries and waits included. Default: no limit. */
68
+ timeout?: number;
69
+ /** When the call began, `Date.now()`, for one that did work before it sent: its `timeout` counts from here. */
70
+ startedAt?: number;
71
+ /** What the call is, for messages: `chat completion`, `rerank`. */
72
+ operation: string;
73
+ };
74
+
75
+ /** The messages of an error and its causes: `fetch failed: connect ECONNREFUSED`, not just `fetch failed`. */
76
+ function describe(error: unknown): string {
77
+ const parts: string[] = [];
78
+ for (let e = error; e !== undefined && e !== null && parts.length < 5; e = (e as Error).cause) {
79
+ parts.push(e instanceof Error ? e.message : String(e));
80
+ }
81
+ return parts.join(': ');
82
+ }
83
+
84
+ /** Headers by lowercase name. A later source's header replaces an earlier one's of the same name, whatever its case. */
85
+ function headersOf(...sources: Array<Record<string, string> | undefined>): Record<string, string> {
86
+ const headers: Record<string, string> = {};
87
+ for (const source of sources) {
88
+ for (const [name, value] of Object.entries(source ?? {})) headers[name.toLowerCase()] = value;
89
+ }
90
+ return headers;
91
+ }
92
+
93
+ /** An address the SDK sends to, without its trailing slashes. Anything but an http or https URL throws `KelnError`. */
94
+ function address(option: string, variable: string, value: string): string {
95
+ let protocol: string | undefined;
96
+ try {
97
+ protocol = new URL(value).protocol;
98
+ } catch {
99
+ protocol = undefined;
100
+ }
101
+ if (protocol !== 'http:' && protocol !== 'https:') {
102
+ throw new KelnError(`${option} (or ${variable}) must be an http or https URL.`);
103
+ }
104
+ return value.replace(/\/+$/, '');
105
+ }
106
+
107
+ /** A call's deadline and signal, made once and shared by every step of the call. */
108
+ type Scope = {
109
+ deadline: number | undefined;
110
+ /** The call's `timeout`, as a signal. */
111
+ timer: AbortSignal | undefined;
112
+ /** Aborts on the caller's signal, the timeout, or the SDK's own signal. */
113
+ signal: AbortSignal | undefined;
114
+ /** Why the call stopped: the caller's reason, or `KelnTimeoutError` for the timeout. */
115
+ reason: () => unknown;
116
+ };
117
+
118
+ function scopeOf(options: ApiCallOptions, own: AbortSignal | undefined): Scope {
119
+ const deadline = options.timeout === undefined ? undefined : (options.startedAt ?? Date.now()) + options.timeout;
120
+ const timer = deadline === undefined ? undefined : AbortSignal.timeout(Math.max(deadline - Date.now(), 0));
121
+ const signals = [options.signal, timer, own].filter((s): s is AbortSignal => s !== undefined);
122
+ const signal = signals.length === 0 ? undefined : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
123
+ const reason = (): unknown => {
124
+ if (options.signal?.aborted === true) return options.signal.reason;
125
+ if (timer?.aborted === true) return new KelnTimeoutError(`Keln ${options.operation} ran past its timeout.`);
126
+ return own?.reason;
127
+ };
128
+ return { deadline, timer, signal, reason };
129
+ }
130
+
131
+ /**
132
+ * Every call to the API. The key lives in a private field here and goes only to `baseUrl` and `apiUrl`, so it cannot
133
+ * reach a log through this object, and any text that comes back passes `redact` on its way into an exception.
134
+ */
135
+ export class Api {
136
+ readonly baseUrl: string;
137
+ readonly apiUrl: string;
138
+ readonly maxRetries: number;
139
+ readonly apiMaxRetries: number;
140
+ readonly streamIdleTimeoutMs: number;
141
+ readonly maxReattachAttempts: number;
142
+ readonly #apiKey: string;
143
+ readonly #fetch: typeof globalThis.fetch;
144
+
145
+ constructor(options: KelnOptions) {
146
+ const apiKey = options.apiKey || process.env.KELN_API_KEY;
147
+ if (!apiKey) throw new KelnError('No Keln API key: pass apiKey, or set KELN_API_KEY.');
148
+ if (options.maxRetries !== undefined && !(Number.isInteger(options.maxRetries) && options.maxRetries >= 0)) {
149
+ throw new KelnError('maxRetries must be a non-negative integer.');
150
+ }
151
+ this.#apiKey = apiKey;
152
+ this.baseUrl = address('baseUrl', 'KELN_SANDBOX_URL', options.baseUrl || process.env.KELN_SANDBOX_URL || DEFAULT_BASE_URL);
153
+ this.apiUrl = address('apiUrl', 'KELN_API_URL', options.apiUrl || process.env.KELN_API_URL || DEFAULT_API_URL);
154
+ this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
155
+ this.maxRetries = options.maxRetries ?? 5;
156
+ this.apiMaxRetries = options.maxRetries ?? DEFAULT_API_MAX_RETRIES;
157
+ this.streamIdleTimeoutMs = options.streamIdleTimeoutMs ?? 45_000;
158
+ this.maxReattachAttempts = options.maxReattachAttempts ?? 5;
159
+ }
160
+
161
+ redact(text: string): string {
162
+ return text.replaceAll(this.#apiKey, '[redacted]');
163
+ }
164
+
165
+ /** A transport failure as a `KelnConnectionError`. A cause whose text holds the key is left out. */
166
+ connectionError(cause: unknown, message = 'Could not reach the Keln Sandbox API'): KelnConnectionError {
167
+ const text = describe(cause);
168
+ const clean = this.redact(text);
169
+ return new KelnConnectionError(`${message}: ${clean}`, cause instanceof Error && clean === text ? { cause } : {});
170
+ }
171
+
172
+ /**
173
+ * Runs `attempt`, trying again by the Sandbox API's retry rules when `safe` is true. An abort ends it at once with the
174
+ * signal's reason, and anything that is not one of this SDK's errors is a transport failure. A `409
175
+ * idempotency_key_in_use` means the first request with the key has not finished: it is waited out, for as long as
176
+ * `Retry-After` says or with the usual backoff, and does not count against `maxRetries`.
177
+ */
178
+ async retrying<T>(safe: boolean, signal: AbortSignal | undefined, attempt: () => Promise<T>): Promise<T> {
179
+ let retries = 0;
180
+ let waits = 0;
181
+ while (true) {
182
+ try {
183
+ return await attempt();
184
+ } catch (error) {
185
+ if (signal?.aborted) throw signal.reason;
186
+ const failure = error instanceof KelnError ? error : this.connectionError(error);
187
+ if (!safe) throw failure;
188
+ const retryAfter = failure instanceof KelnApiError ? failure.retryAfter : undefined;
189
+ if (isKeyInUse(failure)) {
190
+ waits += 1;
191
+ await sleep(backoffMs(waits, retryAfter), signal);
192
+ continue;
193
+ }
194
+ retries += 1;
195
+ if (retries > this.maxRetries || !isRetryable(failure)) throw failure;
196
+ await sleep(backoffMs(retries, retryAfter), signal);
197
+ }
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Sends one call, with its retries. A non-2xx answer throws `KelnApiError` built from the complete body. `read`
203
+ * runs inside the retries, so an answer lost halfway is asked for again; without it the caller gets the response
204
+ * with its body unread.
205
+ */
206
+ async request(method: string, path: string, options?: RequestOptions): Promise<Response>;
207
+ async request<T>(method: string, path: string, options: RequestOptions, read: (response: Response) => Promise<T>): Promise<T>;
208
+ async request<T>(
209
+ method: string,
210
+ path: string,
211
+ options: RequestOptions = {},
212
+ read?: (response: Response) => Promise<T>,
213
+ ): Promise<T | Response> {
214
+ let url = `${path.startsWith('/v1/web/') ? this.apiUrl : this.baseUrl}${path}`;
215
+ if (options.query !== undefined) {
216
+ const query = new URLSearchParams(options.query).toString();
217
+ if (query !== '') url += `?${query}`;
218
+ }
219
+ const headers = headersOf({ authorization: `Bearer ${this.#apiKey}`, 'user-agent': USER_AGENT, ...platformHeaders() }, options.headers);
220
+ let body: Uint8Array | ReadableStream<Uint8Array> | string | undefined = options.body;
221
+ if (options.json !== undefined) {
222
+ headers['content-type'] = 'application/json';
223
+ body = JSON.stringify(options.json);
224
+ }
225
+ // The API never redirects; following one would send the key to another address.
226
+ const init: RequestInit & { duplex?: 'half' } = { method, headers, redirect: 'manual' };
227
+ if (body !== undefined) init.body = body as NonNullable<RequestInit['body']>;
228
+ if (body instanceof ReadableStream) init.duplex = 'half'; // a streamed upload
229
+ if (options.signal !== undefined) init.signal = options.signal;
230
+ const safe = options.safe === true || method === 'GET' || method === 'DELETE' || headers['idempotency-key'] !== undefined;
231
+ return await this.retrying(safe, options.signal, async () => {
232
+ const response = await this.#fetch(url, init);
233
+ if (!response.ok) {
234
+ const text = await response.text().catch(() => '');
235
+ throw apiError(response.status, this.redact(text), response.headers.get('retry-after'), response.headers);
236
+ }
237
+ return read === undefined ? response : await read(response);
238
+ });
239
+ }
240
+
241
+ /** A call whose answer is a JSON object. */
242
+ async json<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {
243
+ return await this.request(method, path, options, async (response) => {
244
+ const text = await response.text();
245
+ let value: unknown;
246
+ try {
247
+ value = JSON.parse(text);
248
+ } catch {
249
+ value = undefined;
250
+ }
251
+ if (value === null || typeof value !== 'object') {
252
+ throw new KelnApiError({
253
+ status: response.status,
254
+ message: 'The response body is not a JSON object.',
255
+ body: this.redact(text),
256
+ });
257
+ }
258
+ return value as T;
259
+ });
260
+ }
261
+
262
+ /**
263
+ * One call on api.keln.ai, with its retries (retry.ts): a transport failure, a `408`, `409`, `429` or `5xx` goes
264
+ * round again, up to `apiMaxRetries` times, the try number in `x-keln-retry-count`. `read` runs inside the retries,
265
+ * so an answer lost halfway is asked for again; without it the caller gets the response with its body unread (a
266
+ * stream, which is not retried once it starts). `options.timeout` bounds the whole call; a wait it cannot cover throws
267
+ * the failure at once. An abort of `options.signal` throws its reason.
268
+ */
269
+ async apiCall(path: string, options: ApiCallOptions): Promise<Response>;
270
+ async apiCall<T>(path: string, options: ApiCallOptions, read: (response: Response) => Promise<T>): Promise<T>;
271
+ async apiCall<T>(path: string, options: ApiCallOptions, read?: (response: Response) => Promise<T>): Promise<T | Response> {
272
+ return (await this.#apiCall(path, options, read, undefined)).value;
273
+ }
274
+
275
+ /** A streamed answer on api.keln.ai. Opening it retries; once it has started, a failure throws. */
276
+ async apiStream<T>(path: string, options: ApiCallOptions): Promise<ApiResult<Stream<T>>> {
277
+ const controller = new AbortController();
278
+ const sent = { ...options, headers: headersOf({ accept: 'text/event-stream' }, options.headers) };
279
+ const { value, timer } = await this.#apiCall<Response>(path, sent, undefined, controller.signal);
280
+ const stream = new Stream<T>(value, controller, options.operation, {
281
+ timeout: timer,
282
+ signal: options.signal,
283
+ redact: (text) => this.redact(text),
284
+ });
285
+ return { data: stream, response: value };
286
+ }
287
+
288
+ /**
289
+ * Work a call does before it sends, such as reading an upload into memory, under the call's `signal` and `timeout`
290
+ * (counted from `options.startedAt`): an abort throws the signal's reason, and the timeout `KelnTimeoutError`, at
291
+ * once. `work` gets a signal that aborts then, to stop what it reads.
292
+ */
293
+ async before<T>(options: ApiCallOptions, work: (signal: AbortSignal | undefined) => Promise<T>): Promise<T> {
294
+ const { signal, reason } = scopeOf(options, undefined);
295
+ if (signal === undefined) return await work(undefined);
296
+ try {
297
+ return await untilAborted(work(signal), signal, () => {});
298
+ } catch (error) {
299
+ if (signal.aborted) throw reason();
300
+ throw error;
301
+ }
302
+ }
303
+
304
+ async #apiCall<T>(
305
+ path: string,
306
+ options: ApiCallOptions,
307
+ read: ((response: Response) => Promise<T>) | undefined,
308
+ own: AbortSignal | undefined,
309
+ ): Promise<{ value: T | Response; timer: AbortSignal | undefined }> {
310
+ let url = `${this.apiUrl}${path}`;
311
+ if (options.query !== undefined) {
312
+ const query = new URLSearchParams(options.query).toString();
313
+ if (query !== '') url += `?${query}`;
314
+ }
315
+ const { deadline, timer, signal, reason } = scopeOf(options, own);
316
+ const method = options.method ?? 'POST';
317
+ // A form sets its own content type, with the boundary, when fetch sends it.
318
+ const body: string | FormData | undefined = method === 'GET' ? undefined : (options.form ?? JSON.stringify(options.json));
319
+ for (let retriesTaken = 0; ; retriesTaken++) {
320
+ const headers = headersOf(
321
+ {
322
+ authorization: `Bearer ${this.#apiKey}`,
323
+ 'user-agent': USER_AGENT,
324
+ ...(typeof body === 'string' && { 'content-type': 'application/json' }),
325
+ ...platformHeaders(),
326
+ 'x-keln-retry-count': String(retriesTaken),
327
+ },
328
+ options.headers,
329
+ );
330
+ // The API never redirects; following one would send the key to another address.
331
+ const init: RequestInit = { method, headers, redirect: 'manual' };
332
+ if (body !== undefined) init.body = body;
333
+ if (signal !== undefined) init.signal = signal;
334
+ let failure: KelnError;
335
+ let wait: number;
336
+ try {
337
+ const response = await this.#fetch(url, init);
338
+ if (response.ok) return { value: read === undefined ? response : await read(response), timer };
339
+ const text = await response.text().catch(() => '');
340
+ failure = apiError(response.status, this.redact(text), response.headers.get('retry-after'), response.headers);
341
+ if (retriesTaken >= this.apiMaxRetries || !shouldRetry(response.status, response.headers)) throw failure;
342
+ wait = retryDelayMs(retriesTaken, response.headers);
343
+ } catch (error) {
344
+ if (signal?.aborted) throw reason();
345
+ if (error instanceof KelnApiError) throw error;
346
+ failure = error instanceof KelnError ? error : this.connectionError(error, `Keln ${options.operation} failed`);
347
+ if (retriesTaken >= this.apiMaxRetries) throw failure;
348
+ wait = retryDelayMs(retriesTaken, undefined);
349
+ }
350
+ if (deadline !== undefined && wait >= deadline - Date.now()) throw failure;
351
+ try {
352
+ await sleep(wait, signal);
353
+ } catch {
354
+ throw reason();
355
+ }
356
+ }
357
+ }
358
+
359
+ /** 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`. */
360
+ async apiJson<T extends object>(path: string, options: ApiCallOptions): Promise<ApiResult<T>> {
361
+ return await this.apiCall(path, options, async (response) => {
362
+ const text = await response.text();
363
+ let value: unknown;
364
+ try {
365
+ value = JSON.parse(text);
366
+ } catch {
367
+ value = undefined;
368
+ }
369
+ const requestId = requestIdOf(response.headers);
370
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
371
+ throw new KelnApiError({
372
+ status: undefined,
373
+ message: `The ${options.operation} response body is not a JSON object.`,
374
+ body: this.redact(text),
375
+ requestId,
376
+ });
377
+ }
378
+ Object.defineProperty(value, '_request_id', { value: requestId, enumerable: false, writable: false });
379
+ return { data: value as T, response };
380
+ });
381
+ }
382
+
383
+ /** A call on api.keln.ai whose answer is plain text (a transcription as `text`, `srt` or `vtt`). */
384
+ async apiText(path: string, options: ApiCallOptions): Promise<ApiResult<string>> {
385
+ return await this.apiCall(path, options, async (response) => ({ data: await response.text(), response }));
386
+ }
387
+
388
+ /** A call on api.keln.ai whose answer is bytes (speech's audio). Read whole inside the retries. */
389
+ async apiBytes(path: string, options: ApiCallOptions): Promise<ApiResult<Uint8Array>> {
390
+ return await this.apiCall(path, options, async (response) => ({
391
+ data: new Uint8Array(await response.arrayBuffer()),
392
+ response,
393
+ }));
394
+ }
395
+
396
+ /** A call whose answer has nothing to read. */
397
+ async send(method: string, path: string, options: RequestOptions = {}): Promise<void> {
398
+ await this.request(method, path, options, async (response) => {
399
+ await response.arrayBuffer();
400
+ });
401
+ }
402
+
403
+ /**
404
+ * A WebSocket to `path`, connecting, straight to `baseUrl`: it does not go through `fetch`. No size limit and no
405
+ * handshake timeout of ours: the caller's signal decides.
406
+ */
407
+ webSocket(path: string): WebSocket {
408
+ return new WebSocket(`${this.baseUrl.replace(/^http/, 'ws')}${path}`, {
409
+ headers: { authorization: `Bearer ${this.#apiKey}`, 'user-agent': USER_AGENT },
410
+ maxPayload: 0,
411
+ followRedirects: false,
412
+ perMessageDeflate: false,
413
+ });
414
+ }
415
+ }
package/src/client.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { Api, 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
+ /**
8
+ * The Keln client. The key comes from `apiKey` or `KELN_API_KEY`; without one the constructor throws `KelnError`. The
9
+ * sandbox address comes from `baseUrl`, `KELN_SANDBOX_URL`, or `https://sandbox.keln.ai`, and the address of inference
10
+ * and `keln.web` from `apiUrl`, `KELN_API_URL`, or `https://api.keln.ai`. An address that is not an `http` or `https`
11
+ * URL throws `KelnError` too.
12
+ */
13
+ export class Keln {
14
+ readonly sandboxes: Sandboxes;
15
+ readonly templates: Templates;
16
+ /** Images saved from sandboxes. `keln.images` is image generation. */
17
+ readonly sandboxImages: SandboxImages;
18
+ readonly web: Web;
19
+ readonly chat: Chat;
20
+ readonly responses: Responses;
21
+ readonly embeddings: Embeddings;
22
+ readonly rerank: Rerank;
23
+ readonly decisions: Decisions;
24
+ readonly audio: Audio;
25
+ readonly images: Images;
26
+ readonly models: Models;
27
+
28
+ constructor(options: KelnOptions = {}) {
29
+ const api = new Api(options);
30
+ this.sandboxes = new Sandboxes(api);
31
+ this.templates = new Templates(api);
32
+ this.sandboxImages = new SandboxImages(api);
33
+ this.web = new Web(api);
34
+ this.chat = new Chat(api);
35
+ this.responses = new Responses(api);
36
+ this.embeddings = new Embeddings(api);
37
+ this.rerank = new Rerank(api);
38
+ this.decisions = new Decisions(api);
39
+ this.audio = new Audio(api);
40
+ this.images = new Images(api);
41
+ this.models = new Models(api);
42
+ }
43
+ }