@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
@@ -0,0 +1,737 @@
1
+ // Portions adapted from openai-node (Apache-2.0, Copyright 2026 OpenAI) and changed by Keln. See NOTICE.
2
+ /**
3
+ * Inference on api.keln.ai: chat completions, responses, embeddings, rerank, decisions, transcriptions, speech and
4
+ * images, and the model list.
5
+ *
6
+ * Each call takes the request body its endpoint documents, and any other field of the body reaches the API unchanged.
7
+ * Every call retries by the rules in retry.ts, and returns an `ApiPromise`: await it for the answer, or call
8
+ * `withResponse()` for its headers too.
9
+ */
10
+ import { ApiPromise, requestIdOf, type ApiResult } from './api-promise.js';
11
+ import type { Api, ApiCallOptions } from './api.js';
12
+ import type { Stream } from './streaming.js';
13
+ import { createForm, isUploadable, toDataUrl, type Uploadable } from './uploads.js';
14
+
15
+ /** Per call. */
16
+ export type InferenceCallOptions = {
17
+ /** Aborting it ends the call with the signal's reason. */
18
+ signal?: AbortSignal;
19
+ /** Milliseconds the call may take in all, an upload's reading, retries and waits included. Default: no limit. */
20
+ timeout?: number;
21
+ /** Extra request headers. One the SDK also sends, in any letter case, replaces the SDK's. */
22
+ headers?: Record<string, string>;
23
+ /** Extra query parameters. */
24
+ query?: Record<string, string>;
25
+ };
26
+
27
+ /** `_request_id`: the API's id for the request (`x-keln-request-id`). */
28
+ export type WithRequestId = { readonly _request_id?: string | undefined };
29
+
30
+ export type ChatMessage = { role: string; content?: unknown; [field: string]: unknown };
31
+
32
+ /**
33
+ * How deeply the model thinks. With `none`, the model answers without thinking. The other values set how deeply it
34
+ * thinks, and `xhigh` means the same as `max`. Without this field, a model that thinks uses its deepest setting.
35
+ * `GET /v1/models` lists the levels each model supports in `reasoning.supported_efforts`.
36
+ */
37
+ export type ReasoningEffort = 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
38
+
39
+ /**
40
+ * The mode the call runs in: `lite` or `standard`. `default` and `standard_only` mean `standard`. `auto`, or no
41
+ * value, uses the mode set on the API key.
42
+ */
43
+ export type ServiceTier = 'lite' | 'standard' | 'auto' | 'default' | 'standard_only';
44
+
45
+ /** Web search on a chat completion. `{}` turns it on with the defaults. */
46
+ export type ChatWebSearchOptions = {
47
+ /** Searches per turn: at most 10, the default. */
48
+ max_uses?: number;
49
+ /**
50
+ * Keep results to `allowed_domains`, remove `blocked_domains`, or both. They apply to the pages the model reads
51
+ * too.
52
+ */
53
+ filters?: { allowed_domains?: string[]; blocked_domains?: string[] };
54
+ /** `false`: the model searches but reads no pages. */
55
+ fetch?: boolean;
56
+ /** `true`: the sources the model used, in `message.web_search_sources`. */
57
+ include_sources?: boolean;
58
+ [field: string]: unknown;
59
+ };
60
+
61
+ /** Code execution on a chat completion, turned on by a `code_interpreter` or `shell` tool in `tools`. */
62
+ export type CodeExecutionOptions = {
63
+ /** `true`: each run in `message.provider_specific_fields.keln_code_execution`, or in the deltas of a stream. */
64
+ include_events?: boolean;
65
+ /** Runs per response. Default 20, at most 30. */
66
+ max_tool_calls?: number;
67
+ /** Milliseconds a run may take before it is stopped. Default 120000, at most 300000. */
68
+ timeout_ms?: number;
69
+ /** Bytes of each run's output the model gets. Default 16384, at most 65536. */
70
+ max_output_length?: number;
71
+ [field: string]: unknown;
72
+ };
73
+
74
+ export type ChatCompletionCreateParams = {
75
+ model: string;
76
+ messages: ChatMessage[];
77
+ stream?: boolean | null;
78
+ reasoning_effort?: ReasoningEffort;
79
+ service_tier?: ServiceTier;
80
+ web_search_options?: ChatWebSearchOptions;
81
+ code_execution?: CodeExecutionOptions;
82
+ [field: string]: unknown;
83
+ };
84
+
85
+ export type Usage = {
86
+ prompt_tokens: number;
87
+ completion_tokens?: number;
88
+ total_tokens: number;
89
+ prompt_tokens_details?: { cached_tokens?: number; [field: string]: unknown };
90
+ completion_tokens_details?: { reasoning_tokens?: number; [field: string]: unknown };
91
+ /** What the call billed, in USD, searches and code execution included. */
92
+ cost?: number;
93
+ /** Searches the model ran, on a call with web search. */
94
+ web_search_requests?: number;
95
+ /** Seconds of code execution billed, on a call that ran code. */
96
+ code_execution_seconds?: number;
97
+ [field: string]: unknown;
98
+ };
99
+
100
+ export type ChatCompletion = WithRequestId & {
101
+ id: string;
102
+ object: 'chat.completion';
103
+ created?: number;
104
+ model: string;
105
+ choices: Array<{
106
+ index: number;
107
+ message: { role: string; content: string | null; reasoning_content?: string | null; tool_calls?: unknown[]; [field: string]: unknown };
108
+ finish_reason: string | null;
109
+ [field: string]: unknown;
110
+ }>;
111
+ usage?: Usage;
112
+ /** The mode that served the call: `standard` or `lite`. */
113
+ service_tier?: string;
114
+ [field: string]: unknown;
115
+ };
116
+
117
+ export type ChatCompletionChunk = {
118
+ id: string;
119
+ object: 'chat.completion.chunk';
120
+ model: string;
121
+ choices: Array<{
122
+ index: number;
123
+ delta: { role?: string; content?: string | null; reasoning_content?: string | null; tool_calls?: unknown[]; [field: string]: unknown };
124
+ finish_reason: string | null;
125
+ [field: string]: unknown;
126
+ }>;
127
+ usage?: Usage | null;
128
+ /** The mode that served the call, on the last chunk. */
129
+ service_tier?: string;
130
+ [field: string]: unknown;
131
+ };
132
+
133
+ export type ResponseCreateParams = {
134
+ model: string;
135
+ input?: string | unknown[];
136
+ stream?: boolean | null;
137
+ /** `effort` works as `reasoning_effort` does on a chat completion. */
138
+ reasoning?: { effort?: ReasoningEffort; summary?: string | null; [field: string]: unknown };
139
+ service_tier?: ServiceTier;
140
+ [field: string]: unknown;
141
+ };
142
+
143
+ /** `usage` on a response. */
144
+ export type ResponseUsage = {
145
+ input_tokens: number;
146
+ output_tokens: number;
147
+ total_tokens: number;
148
+ input_tokens_details?: { cached_tokens?: number; [field: string]: unknown };
149
+ output_tokens_details?: { reasoning_tokens?: number; [field: string]: unknown };
150
+ /** Searches the model ran, on a call with web search. */
151
+ web_search_requests?: number;
152
+ /** Seconds of code execution billed, on a call that ran code. */
153
+ code_execution_seconds?: number;
154
+ [field: string]: unknown;
155
+ };
156
+
157
+ export type Response = WithRequestId & {
158
+ id: string;
159
+ object: 'response';
160
+ status: string;
161
+ output: unknown[];
162
+ usage?: ResponseUsage;
163
+ /** The mode that served the call: `standard` or `lite`. */
164
+ service_tier?: string;
165
+ [field: string]: unknown;
166
+ };
167
+
168
+ /** One event of a streamed response: `type` is `response.created`, `response.output_text.delta`, `error`, .... */
169
+ export type ResponseStreamEvent = { type: string; [field: string]: unknown };
170
+
171
+ export type EmbeddingCreateParams = {
172
+ model: string;
173
+ input: string | string[];
174
+ dimensions?: number;
175
+ /** Unset: the SDK asks for base64 and hands back numbers. Set: the answer comes as sent. */
176
+ encoding_format?: 'float' | 'base64';
177
+ user?: string;
178
+ [field: string]: unknown;
179
+ };
180
+
181
+ export type CreateEmbeddingResponse = WithRequestId & {
182
+ object: 'list';
183
+ model: string;
184
+ data: Array<{ object: 'embedding'; index: number; embedding: number[] | string }>;
185
+ usage: Usage;
186
+ [field: string]: unknown;
187
+ };
188
+
189
+ export type RerankCreateParams = {
190
+ model: string;
191
+ query: string;
192
+ documents: Array<string | { text: string }>;
193
+ /** Only the best `top_n`. */
194
+ top_n?: number;
195
+ /** Attach each document's text to its result. */
196
+ return_documents?: boolean;
197
+ /** What "relevant" means for your task, on a model that takes an instruction. */
198
+ instruction?: string;
199
+ [field: string]: unknown;
200
+ };
201
+
202
+ export type RerankResponse = WithRequestId & {
203
+ object: 'rerank';
204
+ model: string;
205
+ /** Best first. `index` is the document's place in `documents`. */
206
+ results: Array<{ index: number; relevance_score: number; document?: { text: string } }>;
207
+ usage: Usage;
208
+ [field: string]: unknown;
209
+ };
210
+
211
+ export type DecisionCreateParams = {
212
+ model: string;
213
+ /** What the questions are about: text or JSON. */
214
+ state: unknown;
215
+ /** Each name to its question: `type` `noul`, `choice` or `score`, with its `instructions`. */
216
+ questions: Record<string, { type: string; instructions: string; [field: string]: unknown }>;
217
+ [field: string]: unknown;
218
+ };
219
+
220
+ export type DecisionResponse = WithRequestId & {
221
+ model: string;
222
+ /** Under the names `questions` used. */
223
+ answers: Record<string, { [field: string]: unknown }>;
224
+ usage?: Usage;
225
+ [field: string]: unknown;
226
+ };
227
+
228
+ /** The answer formats of a transcription. `text`, `srt` and `vtt` come back as a string. */
229
+ export type AudioResponseFormat = 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt' | 'diarized_json';
230
+
231
+ export type TranscriptionCreateParams = {
232
+ /** The audio: a `File`, `Blob`, `Response` or async iterable of bytes (`fs.createReadStream(path)`); see `toFile`. */
233
+ file: Uploadable;
234
+ model: string;
235
+ response_format?: AudioResponseFormat;
236
+ language?: string;
237
+ languages?: string[];
238
+ /** Spelling hints for names and terms. */
239
+ keywords?: string[];
240
+ prompt?: string;
241
+ temperature?: number;
242
+ /** With `response_format: 'verbose_json'`. */
243
+ timestamp_granularities?: Array<'word' | 'segment'>;
244
+ chunking_strategy?: 'auto' | Record<string, unknown>;
245
+ include?: string[];
246
+ known_speaker_names?: string[];
247
+ known_speaker_references?: string[];
248
+ [field: string]: unknown;
249
+ };
250
+
251
+ /** `usage` on a transcription: the audio's length and what it billed. */
252
+ export type TranscriptionUsage = { type: 'duration'; seconds: number; cost?: number; [field: string]: unknown };
253
+
254
+ export type Transcription = WithRequestId & { text: string; usage?: TranscriptionUsage; [field: string]: unknown };
255
+
256
+ export type TranscriptionVerbose = WithRequestId & {
257
+ task?: string;
258
+ language: string;
259
+ duration: number;
260
+ text: string;
261
+ segments?: Array<{ id: number; start: number; end: number; text: string; speaker?: number; [field: string]: unknown }>;
262
+ words?: Array<{ word: string; start: number; end: number; speaker?: number; [field: string]: unknown }>;
263
+ usage?: TranscriptionUsage;
264
+ [field: string]: unknown;
265
+ };
266
+
267
+ export type TranscriptionDiarized = WithRequestId & {
268
+ task?: string;
269
+ duration: number;
270
+ text: string;
271
+ segments: Array<{ type: 'transcript.text.segment'; id: string; start: number; end: number; text: string; speaker: string; [field: string]: unknown }>;
272
+ usage?: TranscriptionUsage;
273
+ [field: string]: unknown;
274
+ };
275
+
276
+ /** One turn of a conversation: a stretch of text in one voice, with its own style direction. */
277
+ export type SpeechTurn = { text: string; voice?: string; instructions?: string };
278
+
279
+ export type SpeechCreateParams = {
280
+ model: string;
281
+ /** The text, or a list of turns for a conversation (at most two voices). */
282
+ input: string | SpeechTurn[];
283
+ /** One of the model's own voices, which `GET /v1/models` lists as `supported_voices`. */
284
+ voice?: string;
285
+ /** How to say it: a style direction. */
286
+ instructions?: string;
287
+ response_format?: 'mp3' | 'opus' | 'flac' | 'wav' | 'pcm';
288
+ speed?: number;
289
+ stream_format?: 'audio';
290
+ [field: string]: unknown;
291
+ };
292
+
293
+ /** What a speech answer billed, from its headers: text tokens in, audio tokens out, USD, and the audio's seconds. */
294
+ export type SpeechUsage = { prompt_tokens?: number; completion_tokens?: number; cost?: number; seconds?: number };
295
+
296
+ /** A speech answer: the audio and what it cost. `arrayBuffer()` gives the audio as an `ArrayBuffer`. */
297
+ export type SpeechAudio = WithRequestId & {
298
+ readonly content: Uint8Array;
299
+ readonly contentType: string | undefined;
300
+ readonly usage: SpeechUsage;
301
+ arrayBuffer(): Promise<ArrayBuffer>;
302
+ };
303
+
304
+ /**
305
+ * An image an edit starts from: a file (a `File`, `Blob`, `Response` or stream; `toFile` makes one from bytes), a link
306
+ * (an https link or a base64 data URL), or an `{ image_url }` object.
307
+ */
308
+ export type ImageInput = Uploadable | string | { image_url: string | { url: string }; [field: string]: unknown };
309
+
310
+ /** The fields `keln.images.generate` and `keln.images.edit` share, Keln's `aspect_ratio` and `resolution` among them. */
311
+ type ImageRequestBase = {
312
+ model: string;
313
+ prompt: string;
314
+ /** `auto`, `WIDTHxHEIGHT`, or a resolution such as `2K`. `GET /v1/models` lists a model's sizes in `supported_parameters`. */
315
+ size?: string;
316
+ /** Keln's: one of the model's aspect ratios, such as `16:9`. */
317
+ aspect_ratio?: string;
318
+ /** Keln's: one of the model's resolutions, such as `2K`. */
319
+ resolution?: string;
320
+ background?: 'transparent' | 'opaque' | 'auto';
321
+ complexity?: 'low' | 'medium' | 'high';
322
+ frame_count?: number;
323
+ frame_duration_ms?: number;
324
+ n?: number;
325
+ output_compression?: number;
326
+ partial_images?: number;
327
+ response_format?: 'url' | 'b64_json';
328
+ safety_identifier?: string;
329
+ stream?: boolean | null;
330
+ user?: string;
331
+ };
332
+
333
+ export type ImageGenerateParams = ImageRequestBase & {
334
+ moderation?: 'low' | 'auto';
335
+ output_format?: 'png' | 'jpeg' | 'webp' | 'gif' | 'svg';
336
+ quality?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'auto' | 'standard' | 'hd';
337
+ style?: 'vivid' | 'natural';
338
+ svg?: Record<string, unknown>;
339
+ [field: string]: unknown;
340
+ };
341
+
342
+ export type ImageEditParams = ImageRequestBase & {
343
+ /** One image or several. Files alone go as multipart; with a link, the edit goes as JSON. */
344
+ image: ImageInput | ImageInput[];
345
+ input_fidelity?: 'high' | 'low';
346
+ markup?: Uploadable;
347
+ mask?: Uploadable;
348
+ output_format?: 'png' | 'jpeg' | 'webp' | 'gif';
349
+ quality?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'auto' | 'standard';
350
+ [field: string]: unknown;
351
+ };
352
+
353
+ /** `usage` on an image answer: tokens in and out, and what the call billed. */
354
+ export type ImageUsage = {
355
+ input_tokens: number;
356
+ output_tokens: number;
357
+ total_tokens: number;
358
+ /** The prompt's tokens, and the tokens of the pictures sent. */
359
+ input_tokens_details?: { text_tokens: number; image_tokens: number; [field: string]: unknown };
360
+ /** The picture's tokens, and the model's thinking and any words it wrote beside the picture. */
361
+ output_tokens_details?: { image_tokens: number; text_tokens: number; [field: string]: unknown };
362
+ /** What the call billed, in USD. */
363
+ cost?: number;
364
+ [field: string]: unknown;
365
+ };
366
+
367
+ /** An image answer: the picture as base64 in `data[0].b64_json`, its size, format and usage. */
368
+ export type ImagesResponse = WithRequestId & {
369
+ created: number;
370
+ data: Array<{ b64_json: string; media_type?: string; [field: string]: unknown }>;
371
+ size?: string;
372
+ output_format?: string;
373
+ background?: string;
374
+ usage?: ImageUsage;
375
+ [field: string]: unknown;
376
+ };
377
+
378
+ /** The one event of a streamed image answer: `image_generation.completed`, or `image_edit.completed` on an edit. */
379
+ export type ImageStreamEvent = {
380
+ type: 'image_generation.completed' | 'image_edit.completed' | (string & {});
381
+ b64_json: string;
382
+ media_type?: string;
383
+ created_at?: number;
384
+ size?: string;
385
+ output_format?: string;
386
+ usage?: ImageUsage;
387
+ [field: string]: unknown;
388
+ };
389
+
390
+ /** One model of `GET /v1/models`. */
391
+ export type Model = {
392
+ /** The id a request names in `model`. */
393
+ id: string;
394
+ object: 'model';
395
+ owned_by: string;
396
+ /** A constant. It is not a date: `added` is. */
397
+ created: number;
398
+ /** Unix seconds: the date the catalog lists the model under. */
399
+ added?: number;
400
+ /** The context window in tokens, prompt and output together. Absent on transcription, speech and image models. */
401
+ context_length?: number;
402
+ /** What the model takes: `['text']`, `['text', 'image']`, or `['audio']` for a transcription model. */
403
+ input_modalities: string[];
404
+ /**
405
+ * What the model returns, and so the call that serves it: `text` (chat completions and responses), `embeddings`,
406
+ * `rerank`, `decisions`, `transcription`, `speech` or `image`.
407
+ */
408
+ output_modalities: string[];
409
+ /** On a model that thinks: whether thinking can be switched off, the levels it grades, and the one it runs by default. */
410
+ reasoning?: { mandatory: boolean; supported_efforts?: string[]; default_effort?: string; [field: string]: unknown };
411
+ /**
412
+ * USD per unit, as strings. On a chat model, per token: `prompt`, `completion`, `input_cache_read`. A transcription
413
+ * model's `prompt` is per second of audio; a speech model's `completion` per audio token; an image model adds
414
+ * `image_output`, per image token out.
415
+ */
416
+ pricing: { prompt: string; completion: string; input_cache_read?: string; image_output?: string; [field: string]: unknown };
417
+ /** On a speech model: the names its `voice` takes. */
418
+ supported_voices?: string[];
419
+ /** On an image model: what a request may ask of it, each field with its values. */
420
+ supported_parameters?: Record<string, unknown>;
421
+ /** Live speed: `tps_p50` output tokens per second, `ttft_p50_ms` milliseconds to the first token, as of `as_of`. */
422
+ performance?: { tps_p50: number; ttft_p50_ms?: number; as_of: number; [field: string]: unknown };
423
+ [field: string]: unknown;
424
+ };
425
+
426
+ /** `GET /v1/models`: every model a request can name. */
427
+ export type ModelList = WithRequestId & { object: 'list'; data: Model[]; [field: string]: unknown };
428
+
429
+ /** `keln.models.list()`: await it for the list, or loop over it with `for await` for each model. */
430
+ export class ModelListPromise extends ApiPromise<ModelList> implements AsyncIterable<Model> {
431
+ async *[Symbol.asyncIterator](): AsyncIterator<Model> {
432
+ const list = await this;
433
+ yield* list.data;
434
+ }
435
+ }
436
+
437
+ /** A header as a number, absent when it is missing or not one. */
438
+ function headerNumber(headers: Headers, name: string): number | undefined {
439
+ const raw = headers.get(name);
440
+ if (raw === null || raw.trim() === '') return undefined;
441
+ const value = Number(raw);
442
+ return Number.isFinite(value) ? value : undefined;
443
+ }
444
+
445
+ /** `make` started now, its answer as an `ApiPromise`: for a call that has work to do before it sends. */
446
+ function later<T>(make: () => Promise<ApiResult<T>>): ApiPromise<T> {
447
+ return new ApiPromise(make());
448
+ }
449
+
450
+ function callOptions(operation: string, json: unknown, options: InferenceCallOptions): ApiCallOptions {
451
+ return {
452
+ operation,
453
+ json,
454
+ ...(options.signal !== undefined && { signal: options.signal }),
455
+ ...(options.timeout !== undefined && { timeout: options.timeout }),
456
+ ...(options.headers !== undefined && { headers: options.headers }),
457
+ ...(options.query !== undefined && { query: options.query }),
458
+ };
459
+ }
460
+
461
+ /** Little-endian 32-bit floats from base64: an embedding asked for as base64, handed back as numbers. */
462
+ export function toFloat32Array(base64Str: string): number[] {
463
+ const buf = Buffer.from(base64Str, 'base64');
464
+ if (buf.length % Float32Array.BYTES_PER_ELEMENT !== 0) {
465
+ throw new RangeError('Invalid base64-encoded float32 array: byte length must be a multiple of 4');
466
+ }
467
+ return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT));
468
+ }
469
+
470
+ /** `keln.chat.completions`. */
471
+ export class Completions {
472
+ readonly #api: Api;
473
+
474
+ constructor(api: Api) {
475
+ this.#api = api;
476
+ }
477
+
478
+ /**
479
+ * A chat completion, `POST /v1/chat/completions`, with Keln's `reasoning_effort`, `service_tier`,
480
+ * `web_search_options` and `code_execution`. With `stream: true`, a `Stream` of chunks: one that ends early with
481
+ * Keln's `stream_interrupted` chunk throws `KelnApiError` with that `code`.
482
+ */
483
+ create(body: ChatCompletionCreateParams & { stream: true }, options?: InferenceCallOptions): ApiPromise<Stream<ChatCompletionChunk>>;
484
+ create(body: ChatCompletionCreateParams & { stream?: false | null }, options?: InferenceCallOptions): ApiPromise<ChatCompletion>;
485
+ create(body: ChatCompletionCreateParams, options?: InferenceCallOptions): ApiPromise<ChatCompletion | Stream<ChatCompletionChunk>>;
486
+ create(body: ChatCompletionCreateParams, options: InferenceCallOptions = {}): ApiPromise<ChatCompletion> | ApiPromise<Stream<ChatCompletionChunk>> {
487
+ const sent = callOptions('chat completion', body, options);
488
+ if (body.stream === true) return new ApiPromise(this.#api.apiStream<ChatCompletionChunk>('/v1/chat/completions', sent));
489
+ return new ApiPromise(this.#api.apiJson<ChatCompletion>('/v1/chat/completions', sent));
490
+ }
491
+ }
492
+
493
+ /** `keln.chat`. */
494
+ export class Chat {
495
+ readonly completions: Completions;
496
+
497
+ constructor(api: Api) {
498
+ this.completions = new Completions(api);
499
+ }
500
+ }
501
+
502
+ /** `keln.responses`. */
503
+ export class Responses {
504
+ readonly #api: Api;
505
+
506
+ constructor(api: Api) {
507
+ this.#api = api;
508
+ }
509
+
510
+ /**
511
+ * A response, `POST /v1/responses`, with Keln's `service_tier`. With `stream: true`, a `Stream` of its events. A
512
+ * failure after the stream started arrives as an `error` event and `response.failed`, which pass through to be read.
513
+ */
514
+ create(body: ResponseCreateParams & { stream: true }, options?: InferenceCallOptions): ApiPromise<Stream<ResponseStreamEvent>>;
515
+ create(body: ResponseCreateParams & { stream?: false | null }, options?: InferenceCallOptions): ApiPromise<Response>;
516
+ create(body: ResponseCreateParams, options?: InferenceCallOptions): ApiPromise<Response | Stream<ResponseStreamEvent>>;
517
+ create(body: ResponseCreateParams, options: InferenceCallOptions = {}): ApiPromise<Response> | ApiPromise<Stream<ResponseStreamEvent>> {
518
+ const sent = callOptions('response', body, options);
519
+ if (body.stream === true) return new ApiPromise(this.#api.apiStream<ResponseStreamEvent>('/v1/responses', sent));
520
+ return new ApiPromise(this.#api.apiJson<Response>('/v1/responses', sent));
521
+ }
522
+ }
523
+
524
+ /** `keln.embeddings`. */
525
+ export class Embeddings {
526
+ readonly #api: Api;
527
+
528
+ constructor(api: Api) {
529
+ this.#api = api;
530
+ }
531
+
532
+ /**
533
+ * Embeddings, `POST /v1/embeddings`. Without `encoding_format` the SDK asks for base64, a quarter of the bytes, and
534
+ * hands back numbers; with one, the answer comes as the API sent it.
535
+ */
536
+ create(body: EmbeddingCreateParams, options: InferenceCallOptions = {}): ApiPromise<CreateEmbeddingResponse> {
537
+ return later(async () => {
538
+ const asked = body.encoding_format !== undefined;
539
+ const sent = asked ? body : { ...body, encoding_format: 'base64' as const };
540
+ const result = await this.#api.apiJson<CreateEmbeddingResponse>('/v1/embeddings', callOptions('embeddings', sent, options));
541
+ if (!asked) {
542
+ for (const item of result.data.data ?? []) {
543
+ if (typeof item.embedding === 'string') item.embedding = toFloat32Array(item.embedding);
544
+ }
545
+ }
546
+ return result;
547
+ });
548
+ }
549
+ }
550
+
551
+ /** `keln.rerank`. */
552
+ export class Rerank {
553
+ readonly #api: Api;
554
+
555
+ constructor(api: Api) {
556
+ this.#api = api;
557
+ }
558
+
559
+ /** Documents ranked against `query`, `POST /v1/rerank`. */
560
+ create(body: RerankCreateParams, options: InferenceCallOptions = {}): ApiPromise<RerankResponse> {
561
+ return new ApiPromise(this.#api.apiJson<RerankResponse>('/v1/rerank', callOptions('rerank', body, options)));
562
+ }
563
+ }
564
+
565
+ /** `keln.decisions`. */
566
+ export class Decisions {
567
+ readonly #api: Api;
568
+
569
+ constructor(api: Api) {
570
+ this.#api = api;
571
+ }
572
+
573
+ /** Typed answers about one `state`, `POST /v1/decisions`. */
574
+ create(body: DecisionCreateParams, options: InferenceCallOptions = {}): ApiPromise<DecisionResponse> {
575
+ return new ApiPromise(this.#api.apiJson<DecisionResponse>('/v1/decisions', callOptions('decision', body, options)));
576
+ }
577
+ }
578
+
579
+ /** `keln.audio.transcriptions`. */
580
+ export class Transcriptions {
581
+ readonly #api: Api;
582
+
583
+ constructor(api: Api) {
584
+ this.#api = api;
585
+ }
586
+
587
+ /**
588
+ * Audio to text, `POST /v1/audio/transcriptions`, sent multipart, arrays as repeated `name[]` fields. `text`, `srt`
589
+ * and `vtt` answers come back as a string, every other format as an object with `text` and `usage` (`seconds`,
590
+ * `cost`). `diarize: true` in the body puts speakers on a `verbose_json` answer, and `keyterms` adds spelling hints
591
+ * as `keywords` does. The call's `signal` and `timeout` cover reading the file into memory too.
592
+ */
593
+ create(body: TranscriptionCreateParams & { response_format: 'text' | 'srt' | 'vtt' }, options?: InferenceCallOptions): ApiPromise<string>;
594
+ create(body: TranscriptionCreateParams & { response_format: 'verbose_json' }, options?: InferenceCallOptions): ApiPromise<TranscriptionVerbose>;
595
+ create(body: TranscriptionCreateParams & { response_format: 'diarized_json' }, options?: InferenceCallOptions): ApiPromise<TranscriptionDiarized>;
596
+ create(body: TranscriptionCreateParams & { response_format?: 'json' }, options?: InferenceCallOptions): ApiPromise<Transcription>;
597
+ create(
598
+ body: TranscriptionCreateParams,
599
+ options: InferenceCallOptions = {},
600
+ ): ApiPromise<string | Transcription | TranscriptionVerbose | TranscriptionDiarized> {
601
+ const call: ApiCallOptions = { ...callOptions('transcription', undefined, options), startedAt: Date.now() };
602
+ return later<string | Transcription>(async () => {
603
+ const sent = { ...call, form: await this.#api.before(call, (signal) => createForm(body, signal)) };
604
+ const format = body.response_format;
605
+ if (format === 'text' || format === 'srt' || format === 'vtt') {
606
+ return await this.#api.apiText('/v1/audio/transcriptions', sent);
607
+ }
608
+ return await this.#api.apiJson<Transcription>('/v1/audio/transcriptions', sent);
609
+ });
610
+ }
611
+ }
612
+
613
+ /** `keln.audio.speech`. */
614
+ export class Speech {
615
+ readonly #api: Api;
616
+
617
+ constructor(api: Api) {
618
+ this.#api = api;
619
+ }
620
+
621
+ /**
622
+ * Text to audio, `POST /v1/audio/speech`. `input` is the text, or a list of turns for a conversation. The answer is
623
+ * the audio (MP3 unless `response_format` says otherwise) with its usage and cost, read from the answer's headers.
624
+ */
625
+ create(body: SpeechCreateParams, options: InferenceCallOptions = {}): ApiPromise<SpeechAudio> {
626
+ return later(async () => {
627
+ const { data: content, response } = await this.#api.apiBytes('/v1/audio/speech', callOptions('speech', body, options));
628
+ const headers = response.headers;
629
+ const usage: SpeechUsage = {};
630
+ for (const [key, header] of [
631
+ ['prompt_tokens', 'x-keln-usage-prompt-tokens'],
632
+ ['completion_tokens', 'x-keln-usage-completion-tokens'],
633
+ ['cost', 'x-keln-usage-cost'],
634
+ ['seconds', 'x-keln-audio-seconds'],
635
+ ] as const) {
636
+ const value = headerNumber(headers, header);
637
+ if (value !== undefined) usage[key] = value;
638
+ }
639
+ const audio: SpeechAudio = {
640
+ content,
641
+ contentType: headers.get('content-type') ?? undefined,
642
+ usage,
643
+ arrayBuffer: async () => content.slice().buffer,
644
+ };
645
+ Object.defineProperty(audio, '_request_id', { value: requestIdOf(headers), enumerable: false, writable: false });
646
+ return { data: audio, response };
647
+ });
648
+ }
649
+ }
650
+
651
+ /** `keln.audio`. */
652
+ export class Audio {
653
+ readonly transcriptions: Transcriptions;
654
+ readonly speech: Speech;
655
+
656
+ constructor(api: Api) {
657
+ this.transcriptions = new Transcriptions(api);
658
+ this.speech = new Speech(api);
659
+ }
660
+ }
661
+
662
+ /** One image in the JSON form of an edit: a file as a base64 data URL, a link or `{ image_url }` as it is. */
663
+ async function jsonImage(value: ImageInput, signal: AbortSignal | undefined): Promise<unknown> {
664
+ return isUploadable(value) ? await toDataUrl(value, signal) : value;
665
+ }
666
+
667
+ /** `keln.images`. */
668
+ export class Images {
669
+ readonly #api: Api;
670
+
671
+ constructor(api: Api) {
672
+ this.#api = api;
673
+ }
674
+
675
+ /**
676
+ * A picture from a prompt, `POST /v1/images/generations`, with Keln's `aspect_ratio` and `resolution` beside
677
+ * `size`. The picture is `data[0].b64_json`, base64, beside its `media_type`, the answer's `size` and
678
+ * `output_format`, and `usage` (tokens and `cost`). With `stream: true`, a `Stream` of one `image_generation.completed`
679
+ * event with the same fields. A request the model's filter blocks throws `BadRequestError` with the code
680
+ * `moderation_blocked`.
681
+ */
682
+ generate(body: ImageGenerateParams & { stream: true }, options?: InferenceCallOptions): ApiPromise<Stream<ImageStreamEvent>>;
683
+ generate(body: ImageGenerateParams & { stream?: false | null }, options?: InferenceCallOptions): ApiPromise<ImagesResponse>;
684
+ generate(body: ImageGenerateParams, options?: InferenceCallOptions): ApiPromise<ImagesResponse | Stream<ImageStreamEvent>>;
685
+ generate(body: ImageGenerateParams, options: InferenceCallOptions = {}): ApiPromise<ImagesResponse> | ApiPromise<Stream<ImageStreamEvent>> {
686
+ const sent = callOptions('image generation', body, options);
687
+ if (body.stream === true) return new ApiPromise(this.#api.apiStream<ImageStreamEvent>('/v1/images/generations', sent));
688
+ return new ApiPromise(this.#api.apiJson<ImagesResponse>('/v1/images/generations', sent));
689
+ }
690
+
691
+ /**
692
+ * Pictures changed by a prompt, `POST /v1/images/edits`, with the same answer as `generate`. `image` is one image or
693
+ * several: files (`File`, `Blob`, `Response` or a stream) go multipart, one as `image` and several as repeated
694
+ * `image[]`. With a link (an https link or a data URL) among them, the edit goes as JSON in `images`, each file as a
695
+ * data URL. Without a `size`, `aspect_ratio` or `resolution` the model follows the shape of the picture. With
696
+ * `stream: true`, a `Stream` of one `image_edit.completed` event. The call's `signal` and `timeout` cover reading the
697
+ * files into memory too.
698
+ */
699
+ edit(body: ImageEditParams & { stream: true }, options?: InferenceCallOptions): ApiPromise<Stream<ImageStreamEvent>>;
700
+ edit(body: ImageEditParams & { stream?: false | null }, options?: InferenceCallOptions): ApiPromise<ImagesResponse>;
701
+ edit(body: ImageEditParams, options?: InferenceCallOptions): ApiPromise<ImagesResponse | Stream<ImageStreamEvent>>;
702
+ edit(body: ImageEditParams, options: InferenceCallOptions = {}): ApiPromise<ImagesResponse | Stream<ImageStreamEvent>> {
703
+ const call: ApiCallOptions = { ...callOptions('image edit', undefined, options), startedAt: Date.now() };
704
+ return later<ImagesResponse | Stream<ImageStreamEvent>>(async () => {
705
+ const { image, mask, markup, ...fields } = body;
706
+ const images = Array.isArray(image) ? image : [image];
707
+ const sent = await this.#api.before(call, async (signal): Promise<ApiCallOptions> => {
708
+ if ([...images, mask, markup].every((f) => f === undefined || isUploadable(f))) {
709
+ return { ...call, form: await createForm(body, signal) };
710
+ }
711
+ const json: Record<string, unknown> = { images: await Promise.all(images.map((i) => jsonImage(i, signal))), ...fields };
712
+ if (markup !== undefined) json.markup = await jsonImage(markup, signal);
713
+ if (mask !== undefined) json.mask = await jsonImage(mask, signal);
714
+ return { ...call, json };
715
+ });
716
+ if (body.stream === true) return await this.#api.apiStream<ImageStreamEvent>('/v1/images/edits', sent);
717
+ return await this.#api.apiJson<ImagesResponse>('/v1/images/edits', sent);
718
+ });
719
+ }
720
+ }
721
+
722
+ /** `keln.models`. */
723
+ export class Models {
724
+ readonly #api: Api;
725
+
726
+ constructor(api: Api) {
727
+ this.#api = api;
728
+ }
729
+
730
+ /**
731
+ * Every model a request can name, `GET /v1/models`: its context window, prices, what it takes and returns, and for
732
+ * some models their voices, sizes or thinking levels. Await it for the list, or loop over it with `for await`.
733
+ */
734
+ list(options: InferenceCallOptions = {}): ModelListPromise {
735
+ return new ModelListPromise(this.#api.apiJson<ModelList>('/v1/models', { ...callOptions('model list', undefined, options), method: 'GET' }));
736
+ }
737
+ }