segmind 0.2.4 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -4
- package/dist/index.cjs +243 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +284 -84
- package/dist/index.d.ts +284 -84
- package/dist/index.js +243 -50
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -42,10 +42,12 @@ __export(index_exports, {
|
|
|
42
42
|
Generations: () => Generations,
|
|
43
43
|
InferenceFailed: () => InferenceFailed,
|
|
44
44
|
InferenceTimeout: () => InferenceTimeout,
|
|
45
|
+
InsufficientCredits: () => InsufficientCredits,
|
|
45
46
|
Job: () => Job,
|
|
46
47
|
Models: () => Models,
|
|
47
48
|
PixelFlows: () => PixelFlows,
|
|
48
49
|
PixelflowJob: () => PixelflowJob,
|
|
50
|
+
RateLimited: () => RateLimited,
|
|
49
51
|
Segmind: () => Segmind,
|
|
50
52
|
SegmindError: () => SegmindError,
|
|
51
53
|
VERSION: () => VERSION,
|
|
@@ -56,6 +58,7 @@ __export(index_exports, {
|
|
|
56
58
|
files: () => files,
|
|
57
59
|
generations: () => generations,
|
|
58
60
|
imageUrl: () => imageUrl,
|
|
61
|
+
job: () => job,
|
|
59
62
|
models: () => models,
|
|
60
63
|
pixelflows: () => pixelflows,
|
|
61
64
|
run: () => run,
|
|
@@ -67,7 +70,7 @@ __export(index_exports, {
|
|
|
67
70
|
module.exports = __toCommonJS(index_exports);
|
|
68
71
|
|
|
69
72
|
// src/core/errors.ts
|
|
70
|
-
var SegmindError = class
|
|
73
|
+
var SegmindError = class extends Error {
|
|
71
74
|
/** HTTP status, when the error came from a response. */
|
|
72
75
|
status;
|
|
73
76
|
/** The server's error text (`error` in the response body), when it sent one. */
|
|
@@ -85,20 +88,21 @@ var SegmindError = class _SegmindError extends Error {
|
|
|
85
88
|
this.body = options.body;
|
|
86
89
|
}
|
|
87
90
|
/** Reads the response body and builds the error. Consumes the body. */
|
|
88
|
-
static
|
|
89
|
-
|
|
90
|
-
let body = text;
|
|
91
|
-
try {
|
|
92
|
-
body = text ? JSON.parse(text) : void 0;
|
|
93
|
-
} catch {
|
|
94
|
-
}
|
|
95
|
-
const detail = errorDetail(body) ?? (typeof body === "string" && body ? body.slice(0, 500) : void 0);
|
|
96
|
-
const message = detail ? `${response.status} ${detail}` : `${response.status} ${response.statusText || "request failed"}`;
|
|
97
|
-
return new _SegmindError(message, { status: response.status, detail, requestId, body });
|
|
91
|
+
static fromResponse(response, requestId) {
|
|
92
|
+
return errorFromResponse(response, requestId);
|
|
98
93
|
}
|
|
99
94
|
};
|
|
100
95
|
var APIConnectionError = class extends SegmindError {
|
|
101
96
|
};
|
|
97
|
+
var InsufficientCredits = class extends SegmindError {
|
|
98
|
+
};
|
|
99
|
+
var RateLimited = class extends SegmindError {
|
|
100
|
+
retryAfterMs;
|
|
101
|
+
constructor(message, options = {}) {
|
|
102
|
+
super(message, options);
|
|
103
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
104
|
+
}
|
|
105
|
+
};
|
|
102
106
|
var InferenceFailed = class extends SegmindError {
|
|
103
107
|
/** The status body that reported the failure. */
|
|
104
108
|
statusBody;
|
|
@@ -119,6 +123,43 @@ var InferenceTimeout = class extends SegmindError {
|
|
|
119
123
|
this.elapsedMs = elapsedMs;
|
|
120
124
|
}
|
|
121
125
|
};
|
|
126
|
+
async function errorFromResponse(response, requestId) {
|
|
127
|
+
const text = await response.text().catch(() => "");
|
|
128
|
+
let body = text;
|
|
129
|
+
try {
|
|
130
|
+
body = text ? JSON.parse(text) : void 0;
|
|
131
|
+
} catch {
|
|
132
|
+
}
|
|
133
|
+
const detail = errorDetail(body) ?? plainText(body);
|
|
134
|
+
const message = detail ? `${response.status} ${detail}` : `${response.status} ${response.statusText || "request failed"}`;
|
|
135
|
+
const options = { status: response.status, detail, requestId, body };
|
|
136
|
+
if (response.status === 429) {
|
|
137
|
+
return new RateLimited(message, { ...options, retryAfterMs: parseRetryAfter(response.headers.get("retry-after")) });
|
|
138
|
+
}
|
|
139
|
+
if (response.status === 402 || isOutOfCredits(detail)) return new InsufficientCredits(message, options);
|
|
140
|
+
return new SegmindError(message, options);
|
|
141
|
+
}
|
|
142
|
+
function requestFailure(requestId, statusBody, detail) {
|
|
143
|
+
detail ??= typeof statusBody.error === "string" ? statusBody.error : void 0;
|
|
144
|
+
if (isOutOfCredits(detail)) {
|
|
145
|
+
return new InsufficientCredits(`request ${requestId} failed: ${detail}`, { detail, requestId, body: statusBody });
|
|
146
|
+
}
|
|
147
|
+
return new InferenceFailed(requestId, statusBody, detail);
|
|
148
|
+
}
|
|
149
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
150
|
+
if (!value) return void 0;
|
|
151
|
+
const seconds = Number(value);
|
|
152
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
|
|
153
|
+
const date = Date.parse(value);
|
|
154
|
+
return Number.isNaN(date) ? void 0 : Math.max(date - now, 0);
|
|
155
|
+
}
|
|
156
|
+
function isOutOfCredits(detail) {
|
|
157
|
+
return detail?.startsWith("Insufficient credits.") ?? false;
|
|
158
|
+
}
|
|
159
|
+
function plainText(body) {
|
|
160
|
+
if (typeof body !== "string" || !body || body.trimStart().startsWith("<")) return void 0;
|
|
161
|
+
return body.slice(0, 500);
|
|
162
|
+
}
|
|
122
163
|
function errorDetail(body) {
|
|
123
164
|
if (!body || typeof body !== "object") return void 0;
|
|
124
165
|
const record2 = body;
|
|
@@ -236,6 +277,12 @@ function detectRuntime() {
|
|
|
236
277
|
if (g.process?.versions?.node) return "node";
|
|
237
278
|
return "other";
|
|
238
279
|
}
|
|
280
|
+
function initiatorHeaders(options) {
|
|
281
|
+
return {
|
|
282
|
+
...options.initiator ? { "X-Initiator": options.initiator } : {},
|
|
283
|
+
...options.initiatorId ? { "X-Initiator-ID": options.initiatorId } : {}
|
|
284
|
+
};
|
|
285
|
+
}
|
|
239
286
|
function readEnv(name) {
|
|
240
287
|
try {
|
|
241
288
|
const value = g.process?.env?.[name];
|
|
@@ -268,15 +315,15 @@ function toBase64(bytes) {
|
|
|
268
315
|
var RETRYABLE_STATUS = /* @__PURE__ */ new Set([408, 429, 502, 503, 504]);
|
|
269
316
|
var MAX_RETRY_DELAY_MS = 6e4;
|
|
270
317
|
function retryDelay(attempt, retryAfter, now = Date.now()) {
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1e3, MAX_RETRY_DELAY_MS);
|
|
274
|
-
const date = Date.parse(retryAfter);
|
|
275
|
-
if (!Number.isNaN(date)) return Math.min(Math.max(date - now, 0), MAX_RETRY_DELAY_MS);
|
|
276
|
-
}
|
|
318
|
+
const asked = parseRetryAfter(retryAfter, now);
|
|
319
|
+
if (asked !== void 0) return Math.min(asked, MAX_RETRY_DELAY_MS);
|
|
277
320
|
const base = Math.min(500 * 2 ** attempt, 8e3);
|
|
278
321
|
return base * (0.75 + Math.random() * 0.25);
|
|
279
322
|
}
|
|
323
|
+
function pollDelay(interval, elapsedMs, fallback) {
|
|
324
|
+
const delay = typeof interval === "function" ? interval(elapsedMs) : interval ?? fallback;
|
|
325
|
+
return Number.isFinite(delay) && delay >= 0 ? delay : fallback;
|
|
326
|
+
}
|
|
280
327
|
function sleep(ms, signal) {
|
|
281
328
|
return new Promise((resolve, reject) => {
|
|
282
329
|
if (signal?.aborted) return reject(signal.reason);
|
|
@@ -296,23 +343,35 @@ var HttpClient = class {
|
|
|
296
343
|
this.config = config;
|
|
297
344
|
}
|
|
298
345
|
config;
|
|
346
|
+
/** The hook call in flight, so that requests failing together share one refresh. */
|
|
347
|
+
unauthorized;
|
|
299
348
|
/** The response whatever its status, after retries when `retry` is set. */
|
|
300
349
|
async fetchRaw(req) {
|
|
301
|
-
|
|
350
|
+
let attempt = 0;
|
|
351
|
+
let reauthenticated = false;
|
|
352
|
+
for (; ; ) {
|
|
302
353
|
const canRetry = req.retry === true && attempt < this.config.maxRetries;
|
|
354
|
+
const token = await this.sessionToken(req);
|
|
303
355
|
let response;
|
|
304
356
|
try {
|
|
305
|
-
response = await this.attempt(req);
|
|
357
|
+
response = await this.attempt(req, token);
|
|
306
358
|
} catch (err) {
|
|
307
359
|
if (canRetry && err instanceof APIConnectionError) {
|
|
308
360
|
await sleep(retryDelay(attempt, null), req.signal);
|
|
361
|
+
attempt++;
|
|
309
362
|
continue;
|
|
310
363
|
}
|
|
311
364
|
throw err;
|
|
312
365
|
}
|
|
366
|
+
if (response.status === 401 && !reauthenticated && await this.reauthenticate(req, token)) {
|
|
367
|
+
reauthenticated = true;
|
|
368
|
+
await response.body?.cancel().catch(() => void 0);
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
313
371
|
if (canRetry && RETRYABLE_STATUS.has(response.status)) {
|
|
314
372
|
await response.body?.cancel().catch(() => void 0);
|
|
315
373
|
await sleep(retryDelay(attempt, response.headers.get("retry-after")), req.signal);
|
|
374
|
+
attempt++;
|
|
316
375
|
continue;
|
|
317
376
|
}
|
|
318
377
|
return response;
|
|
@@ -328,7 +387,31 @@ var HttpClient = class {
|
|
|
328
387
|
async json(req) {
|
|
329
388
|
return readJson(await this.request(req));
|
|
330
389
|
}
|
|
331
|
-
async
|
|
390
|
+
async sessionToken(req) {
|
|
391
|
+
if (!this.config.tokenProvider || req.bare) return void 0;
|
|
392
|
+
try {
|
|
393
|
+
return await this.config.tokenProvider() ?? void 0;
|
|
394
|
+
} catch (err) {
|
|
395
|
+
throw new SegmindError(`tokenProvider failed: ${describe(err)}`, { cause: err });
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
/** Tells the app its token was refused. True when it now has a different one to try. */
|
|
399
|
+
async reauthenticate(req, refused) {
|
|
400
|
+
if (!this.config.tokenProvider || req.bare) return false;
|
|
401
|
+
try {
|
|
402
|
+
if (this.config.onUnauthorized) {
|
|
403
|
+
this.unauthorized ??= Promise.resolve(this.config.onUnauthorized()).finally(() => {
|
|
404
|
+
this.unauthorized = void 0;
|
|
405
|
+
});
|
|
406
|
+
await this.unauthorized;
|
|
407
|
+
}
|
|
408
|
+
const next = await this.config.tokenProvider();
|
|
409
|
+
return Boolean(next) && next !== refused;
|
|
410
|
+
} catch {
|
|
411
|
+
return false;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
async attempt(req, token) {
|
|
332
415
|
const { signal } = req;
|
|
333
416
|
if (signal?.aborted) throw signal.reason;
|
|
334
417
|
const timeout = req.timeout ?? this.config.timeout;
|
|
@@ -342,6 +425,7 @@ var HttpClient = class {
|
|
|
342
425
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
343
426
|
const headers = req.bare ? { ...req.headers } : { ...this.config.headers, ...req.headers };
|
|
344
427
|
if (this.config.apiKey && !req.bare) headers["x-api-key"] = this.config.apiKey;
|
|
428
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
345
429
|
if (req.body !== void 0) headers["content-type"] = "application/json";
|
|
346
430
|
const body = req.rawBody ?? (req.body === void 0 ? void 0 : JSON.stringify(req.body));
|
|
347
431
|
try {
|
|
@@ -436,7 +520,12 @@ async function readFileInput(input, options) {
|
|
|
436
520
|
if (detectRuntime() !== "node") {
|
|
437
521
|
throw new SegmindError(`${options.caller}: file paths work in Node only; pass a Blob or bytes`);
|
|
438
522
|
}
|
|
439
|
-
const { readFile } = await import(
|
|
523
|
+
const { readFile } = await import(
|
|
524
|
+
/* webpackIgnore: true */
|
|
525
|
+
/* turbopackIgnore: true */
|
|
526
|
+
/* @vite-ignore */
|
|
527
|
+
"node:fs/promises"
|
|
528
|
+
);
|
|
440
529
|
try {
|
|
441
530
|
bytes = new Uint8Array(await readFile(input));
|
|
442
531
|
} catch (err) {
|
|
@@ -580,6 +669,8 @@ var Generations = class {
|
|
|
580
669
|
to_date: options.toDate,
|
|
581
670
|
model_name: options.modelName,
|
|
582
671
|
status: options.status,
|
|
672
|
+
initiator: [options.initiator ?? []].flat().join(",") || void 0,
|
|
673
|
+
key_suffix: options.keySuffix,
|
|
583
674
|
user_id: options.userId,
|
|
584
675
|
user_email: options.userEmail,
|
|
585
676
|
sort_by: options.sortBy,
|
|
@@ -619,12 +710,12 @@ var Job = class {
|
|
|
619
710
|
return await this.read(this.statusUrl, options.signal);
|
|
620
711
|
}
|
|
621
712
|
/**
|
|
622
|
-
* The finished result. Throws `InferenceFailed` when the request failed
|
|
623
|
-
* a `SegmindError` when it has not finished yet (use `wait()` for that).
|
|
713
|
+
* The finished result. Throws `InferenceFailed` when the request failed
|
|
714
|
+
* (`InsufficientCredits` when that was for lack of credits), and a `SegmindError` when it has not finished yet (use `wait()` for that).
|
|
624
715
|
*/
|
|
625
716
|
async result(options = {}) {
|
|
626
717
|
const body = await this.read(this.responseUrl, options.signal);
|
|
627
|
-
if (body.status === "FAILED") throw
|
|
718
|
+
if (body.status === "FAILED") throw requestFailure(this.requestId, body);
|
|
628
719
|
if (body.status !== void 0 && body.status !== "COMPLETED") {
|
|
629
720
|
throw new SegmindError(`request ${this.requestId} is still ${String(body.status)}; use wait()`, {
|
|
630
721
|
requestId: this.requestId,
|
|
@@ -636,15 +727,16 @@ var Job = class {
|
|
|
636
727
|
/** Polls until the request finishes, then returns its result. */
|
|
637
728
|
async wait(options = {}) {
|
|
638
729
|
const timeout = options.timeout ?? DEFAULT_WAIT_TIMEOUT_MS;
|
|
639
|
-
const interval = options.interval ?? DEFAULT_WAIT_INTERVAL_MS;
|
|
640
730
|
const started = Date.now();
|
|
641
731
|
for (; ; ) {
|
|
642
732
|
const status = await this.status({ signal: options.signal });
|
|
733
|
+
options.onStatus?.(status);
|
|
643
734
|
if (status.status === "COMPLETED") return this.result({ signal: options.signal });
|
|
644
|
-
if (status.status === "FAILED") throw
|
|
735
|
+
if (status.status === "FAILED") throw requestFailure(this.requestId, status);
|
|
645
736
|
const elapsed = Date.now() - started;
|
|
646
737
|
if (elapsed >= timeout) throw new InferenceTimeout(this.requestId, elapsed);
|
|
647
|
-
|
|
738
|
+
const delay = pollDelay(options.interval, elapsed, DEFAULT_WAIT_INTERVAL_MS);
|
|
739
|
+
await sleep(Math.min(delay, timeout - elapsed), options.signal);
|
|
648
740
|
}
|
|
649
741
|
}
|
|
650
742
|
/**
|
|
@@ -676,8 +768,8 @@ var PixelFlows = class {
|
|
|
676
768
|
client;
|
|
677
769
|
/** Runs a workflow and waits for its outputs. */
|
|
678
770
|
async run(slug, inputs = {}, options = {}) {
|
|
679
|
-
const
|
|
680
|
-
return
|
|
771
|
+
const job2 = await this.submit(slug, inputs, options);
|
|
772
|
+
return job2.wait(options);
|
|
681
773
|
}
|
|
682
774
|
/** Starts a workflow and returns a job to wait on. Never retried: a run bills. */
|
|
683
775
|
async submit(slug, inputs = {}, options = {}) {
|
|
@@ -688,6 +780,7 @@ var PixelFlows = class {
|
|
|
688
780
|
method: "POST",
|
|
689
781
|
url: `${this.client.baseURL}${route}${clean}`,
|
|
690
782
|
body: inputs,
|
|
783
|
+
headers: initiatorHeaders(options),
|
|
691
784
|
signal: options.signal
|
|
692
785
|
});
|
|
693
786
|
const requestId = body.request_id;
|
|
@@ -723,20 +816,21 @@ var PixelflowJob = class {
|
|
|
723
816
|
}
|
|
724
817
|
/**
|
|
725
818
|
* Polls until the run finishes. Throws `InferenceFailed` (its `detail` names
|
|
726
|
-
* the failing node) or `InferenceTimeout`; the run may still finish after a
|
|
819
|
+
* the failing node), `InsufficientCredits` or `InferenceTimeout`; the run may still finish after a
|
|
727
820
|
* timeout, so `wait()` can be called again.
|
|
728
821
|
*/
|
|
729
822
|
async wait(options = {}) {
|
|
730
823
|
const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
731
|
-
const interval = options.interval ?? DEFAULT_INTERVAL_MS;
|
|
732
824
|
const started = Date.now();
|
|
733
825
|
for (; ; ) {
|
|
734
826
|
const state = await this.status({ signal: options.signal });
|
|
827
|
+
options.onStatus?.(state);
|
|
735
828
|
if (DONE.has(state.status)) return state;
|
|
736
|
-
if (FAILED.has(state.status)) throw
|
|
829
|
+
if (FAILED.has(state.status)) throw requestFailure(this.requestId, state.raw, failureDetail(state.raw));
|
|
737
830
|
const elapsed = Date.now() - started;
|
|
738
|
-
|
|
739
|
-
|
|
831
|
+
const delay = pollDelay(options.interval, elapsed, DEFAULT_INTERVAL_MS);
|
|
832
|
+
if (elapsed + delay > timeout) throw new InferenceTimeout(this.requestId, elapsed);
|
|
833
|
+
await sleep(delay, options.signal);
|
|
740
834
|
}
|
|
741
835
|
}
|
|
742
836
|
};
|
|
@@ -781,7 +875,7 @@ function failureDetail(body) {
|
|
|
781
875
|
}
|
|
782
876
|
|
|
783
877
|
// src/version.ts
|
|
784
|
-
var VERSION = "0.
|
|
878
|
+
var VERSION = "0.4.0";
|
|
785
879
|
|
|
786
880
|
// src/webhooks.ts
|
|
787
881
|
var Webhooks = class {
|
|
@@ -821,10 +915,26 @@ var Webhooks = class {
|
|
|
821
915
|
async delete(webhookId, options = {}) {
|
|
822
916
|
return this.call("DELETE", "/inactive", { query: { webhook_id: webhookId }, signal: options.signal });
|
|
823
917
|
}
|
|
824
|
-
/**
|
|
918
|
+
/** Every delivery made to one registration. */
|
|
825
919
|
async logs(webhookId, options = {}) {
|
|
826
920
|
return this.call("GET", "/dispatch-logs", { query: { webhook_id: webhookId }, signal: options.signal, retry: true });
|
|
827
921
|
}
|
|
922
|
+
/**
|
|
923
|
+
* Sends a `WEBHOOK_TEST` delivery to an active registration. It goes out in
|
|
924
|
+
* the background after this returns, so read `logs` to see how your endpoint
|
|
925
|
+
* answered. Not retried: each attempt is another delivery.
|
|
926
|
+
*/
|
|
927
|
+
async test(webhookId, options = {}) {
|
|
928
|
+
return this.call("POST", "/test", { body: { webhook_id: webhookId }, signal: options.signal });
|
|
929
|
+
}
|
|
930
|
+
/**
|
|
931
|
+
* Sends a past delivery's payload again, by its `id` from `logs`. Refused
|
|
932
|
+
* (406) when the registration is no longer active. Not retried: each
|
|
933
|
+
* attempt is another delivery.
|
|
934
|
+
*/
|
|
935
|
+
async resend(deliveryId, options = {}) {
|
|
936
|
+
return this.call("POST", "/resend", { body: { webhook_dispatch_id: deliveryId }, signal: options.signal });
|
|
937
|
+
}
|
|
828
938
|
call(method, path2, req) {
|
|
829
939
|
return this.client.http.json({ method, url: `${this.client.spotURL}/webhook${path2}`, ...req });
|
|
830
940
|
}
|
|
@@ -859,14 +969,17 @@ var Segmind = class {
|
|
|
859
969
|
/** @internal */
|
|
860
970
|
http;
|
|
861
971
|
constructor(options = {}) {
|
|
862
|
-
|
|
972
|
+
if (options.apiKey && options.tokenProvider) {
|
|
973
|
+
throw new SegmindError("Pass either apiKey or tokenProvider, not both.");
|
|
974
|
+
}
|
|
975
|
+
const apiKey = options.apiKey ?? (options.tokenProvider ? void 0 : readEnv("SEGMIND_API_KEY"));
|
|
863
976
|
const runtime = detectRuntime();
|
|
864
977
|
if (apiKey && (runtime === "browser" || runtime === "react-native") && !options.dangerouslyAllowBrowser) {
|
|
865
978
|
throw new SegmindError(
|
|
866
979
|
"An API key in a browser or mobile app exposes it to every user. Call Segmind from your backend instead, or pass dangerouslyAllowBrowser: true if you accept that risk."
|
|
867
980
|
);
|
|
868
981
|
}
|
|
869
|
-
if (!apiKey) {
|
|
982
|
+
if (!apiKey && !options.tokenProvider) {
|
|
870
983
|
throw new SegmindError("Missing API key: pass { apiKey } or set the SEGMIND_API_KEY environment variable.");
|
|
871
984
|
}
|
|
872
985
|
const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
|
|
@@ -875,11 +988,17 @@ var Segmind = class {
|
|
|
875
988
|
this.spotURL = trimSlash(options.spotURL ?? DEFAULT_SPOT_URL);
|
|
876
989
|
this.consoleURL = trimSlash(options.consoleURL ?? DEFAULT_CONSOLE_URL);
|
|
877
990
|
this.assetsURL = trimSlash(options.assetsURL ?? DEFAULT_ASSETS_URL);
|
|
878
|
-
const headers = {
|
|
991
|
+
const headers = {
|
|
992
|
+
"X-Initiator": "SDK-JS",
|
|
993
|
+
...initiatorHeaders(options),
|
|
994
|
+
...options.defaultHeaders
|
|
995
|
+
};
|
|
879
996
|
const node = nodeVersion();
|
|
880
997
|
if (runtime === "node" && node) headers["User-Agent"] = `segmind-js/${VERSION} node/${node}`;
|
|
881
998
|
this.http = new HttpClient({
|
|
882
999
|
apiKey,
|
|
1000
|
+
tokenProvider: options.tokenProvider,
|
|
1001
|
+
onUnauthorized: options.onUnauthorized,
|
|
883
1002
|
fetch: fetchImpl,
|
|
884
1003
|
timeout: options.timeout ?? 6e5,
|
|
885
1004
|
maxRetries: options.maxRetries ?? 2,
|
|
@@ -897,8 +1016,8 @@ var Segmind = class {
|
|
|
897
1016
|
* until it finishes. `params` go to the model unchanged.
|
|
898
1017
|
*/
|
|
899
1018
|
async run(slug, params = {}, options = {}) {
|
|
900
|
-
const
|
|
901
|
-
return
|
|
1019
|
+
const job2 = await this.submit(slug, params, options);
|
|
1020
|
+
return job2.wait(options);
|
|
902
1021
|
}
|
|
903
1022
|
/**
|
|
904
1023
|
* One blocking `POST /v1/{slug}`. Returns the fetch `Response`: call
|
|
@@ -910,6 +1029,7 @@ var Segmind = class {
|
|
|
910
1029
|
method: "POST",
|
|
911
1030
|
url: `${this.baseURL}/v1/${path(slug)}`,
|
|
912
1031
|
body: params,
|
|
1032
|
+
headers: initiatorHeaders(options),
|
|
913
1033
|
signal: options.signal,
|
|
914
1034
|
timeout: options.timeout
|
|
915
1035
|
});
|
|
@@ -922,10 +1042,27 @@ var Segmind = class {
|
|
|
922
1042
|
async submit(slug, params = {}, options = {}) {
|
|
923
1043
|
return this.submitJob(slug, params, options, (body) => body);
|
|
924
1044
|
}
|
|
1045
|
+
/**
|
|
1046
|
+
* A job submitted earlier, from its id alone, for picking one up after a
|
|
1047
|
+
* reload or in another process. Makes no request. The result is kept for about
|
|
1048
|
+
* an hour, and only for the user who submitted it: anything else reads as a
|
|
1049
|
+
* `SegmindError` with status 404.
|
|
1050
|
+
*/
|
|
1051
|
+
job(requestId) {
|
|
1052
|
+
const clean = requestId.trim();
|
|
1053
|
+
if (!clean) throw new SegmindError("A request id is required.");
|
|
1054
|
+
const url = `${this.baseURL}/v2/requests/${encodeURIComponent(clean)}`;
|
|
1055
|
+
return new Job(this.http, {
|
|
1056
|
+
request_id: clean,
|
|
1057
|
+
status: "UNKNOWN",
|
|
1058
|
+
status_url: `${url}/status`,
|
|
1059
|
+
response_url: url
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
925
1062
|
/** Chat with an LLM through the v2 queue. Returns a provider-neutral reply. */
|
|
926
1063
|
async chat(slug, params, options = {}) {
|
|
927
|
-
const
|
|
928
|
-
return
|
|
1064
|
+
const job2 = await this.submitChat(slug, params, options);
|
|
1065
|
+
return job2.wait(options);
|
|
929
1066
|
}
|
|
930
1067
|
/** Chat with one blocking `POST /v1/{slug}`. */
|
|
931
1068
|
async chatSync(slug, params, options = {}) {
|
|
@@ -948,7 +1085,7 @@ var Segmind = class {
|
|
|
948
1085
|
method: "POST",
|
|
949
1086
|
url,
|
|
950
1087
|
body: params,
|
|
951
|
-
headers: { "X-Request-ID": requestId },
|
|
1088
|
+
headers: { "X-Request-ID": requestId, ...initiatorHeaders(options) },
|
|
952
1089
|
signal: options.signal
|
|
953
1090
|
});
|
|
954
1091
|
} catch (err) {
|
|
@@ -984,21 +1121,62 @@ var Segmind = class {
|
|
|
984
1121
|
}
|
|
985
1122
|
}
|
|
986
1123
|
};
|
|
1124
|
+
var MODELS_PAGE_LIMIT = 100;
|
|
987
1125
|
var Models = class {
|
|
988
1126
|
constructor(client2) {
|
|
989
1127
|
this.client = client2;
|
|
990
1128
|
}
|
|
991
1129
|
client;
|
|
992
|
-
/**
|
|
993
|
-
async list(options = {}) {
|
|
1130
|
+
/** One page of the catalog. Pass `offset` from the previous page while `has_more` is true. */
|
|
1131
|
+
async list(params = {}, options = {}) {
|
|
994
1132
|
return this.client.http.json({
|
|
995
1133
|
method: "GET",
|
|
996
|
-
url: `${this.client.
|
|
1134
|
+
url: `${this.client.baseURL}/models`,
|
|
1135
|
+
query: modelsQuery(params),
|
|
997
1136
|
signal: options.signal,
|
|
998
1137
|
retry: true
|
|
999
1138
|
});
|
|
1000
1139
|
}
|
|
1140
|
+
/** Every model matching `params`, reading page after page. */
|
|
1141
|
+
async listAll(params = {}, options = {}) {
|
|
1142
|
+
const models2 = [];
|
|
1143
|
+
for (let offset = 0; ; ) {
|
|
1144
|
+
const page = await this.list({ ...params, limit: MODELS_PAGE_LIMIT, offset }, options);
|
|
1145
|
+
models2.push(...page.models);
|
|
1146
|
+
offset += page.models.length;
|
|
1147
|
+
if (!page.has_more || !page.models.length || offset >= page.total) return models2;
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1001
1150
|
};
|
|
1151
|
+
function modelsQuery(p) {
|
|
1152
|
+
return {
|
|
1153
|
+
q: p.q,
|
|
1154
|
+
sort: p.sort,
|
|
1155
|
+
category: p.category,
|
|
1156
|
+
modality: p.modality,
|
|
1157
|
+
input: joinList(p.input),
|
|
1158
|
+
output: joinList(p.output),
|
|
1159
|
+
provider: p.provider,
|
|
1160
|
+
slugs: joinList(p.slugs),
|
|
1161
|
+
operations: joinList(p.operations),
|
|
1162
|
+
features: joinList(p.features),
|
|
1163
|
+
min_popularity: p.minPopularity,
|
|
1164
|
+
min_category_percentile: p.minCategoryPercentile,
|
|
1165
|
+
min_cost: p.minCost,
|
|
1166
|
+
max_cost: p.maxCost,
|
|
1167
|
+
max_latency: p.maxLatency,
|
|
1168
|
+
is_new: p.isNew,
|
|
1169
|
+
created_after: p.createdAfter,
|
|
1170
|
+
include_coming_soon: p.includeComingSoon,
|
|
1171
|
+
facets: p.facets,
|
|
1172
|
+
limit: p.limit,
|
|
1173
|
+
offset: p.offset
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
function joinList(value) {
|
|
1177
|
+
if (value === void 0) return void 0;
|
|
1178
|
+
return Array.isArray(value) ? value.join(",") : value;
|
|
1179
|
+
}
|
|
1002
1180
|
var Accounts = class {
|
|
1003
1181
|
constructor(client2) {
|
|
1004
1182
|
this.client = client2;
|
|
@@ -1013,6 +1191,16 @@ var Accounts = class {
|
|
|
1013
1191
|
retry: true
|
|
1014
1192
|
});
|
|
1015
1193
|
}
|
|
1194
|
+
/** The current credit balance. */
|
|
1195
|
+
async credits(options = {}) {
|
|
1196
|
+
const { "free-credits": freeCredits, ...rest } = await this.client.http.json({
|
|
1197
|
+
method: "GET",
|
|
1198
|
+
url: `${this.client.baseURL}/v1/get-user-credits`,
|
|
1199
|
+
signal: options.signal,
|
|
1200
|
+
retry: true
|
|
1201
|
+
});
|
|
1202
|
+
return { ...rest, credits: Number(rest.credits), freeCredits: Number(freeCredits) };
|
|
1203
|
+
}
|
|
1016
1204
|
};
|
|
1017
1205
|
function validateSubmit(body, status) {
|
|
1018
1206
|
if (!body.request_id || !body.status_url || !body.response_url) {
|
|
@@ -1061,14 +1249,17 @@ function client() {
|
|
|
1061
1249
|
var run = (slug, params, options) => client().run(slug, params, options);
|
|
1062
1250
|
var runSync = (slug, params, options) => client().runSync(slug, params, options);
|
|
1063
1251
|
var submit = (slug, params, options) => client().submit(slug, params, options);
|
|
1252
|
+
var job = (requestId) => client().job(requestId);
|
|
1064
1253
|
var chat = (slug, params, options) => client().chat(slug, params, options);
|
|
1065
1254
|
var chatSync = (slug, params, options) => client().chatSync(slug, params, options);
|
|
1066
1255
|
var submitChat = (slug, params, options) => client().submitChat(slug, params, options);
|
|
1067
1256
|
var models = {
|
|
1068
|
-
list: (options) => client().models.list(options)
|
|
1257
|
+
list: (params, options) => client().models.list(params, options),
|
|
1258
|
+
listAll: (params, options) => client().models.listAll(params, options)
|
|
1069
1259
|
};
|
|
1070
1260
|
var accounts = {
|
|
1071
|
-
current: (options) => client().accounts.current(options)
|
|
1261
|
+
current: (options) => client().accounts.current(options),
|
|
1262
|
+
credits: (options) => client().accounts.credits(options)
|
|
1072
1263
|
};
|
|
1073
1264
|
var files = {
|
|
1074
1265
|
upload: ((input, options) => client().files.upload(input, options))
|
|
@@ -1084,7 +1275,9 @@ var webhooks = {
|
|
|
1084
1275
|
add: (webhookUrl, eventTypes, options) => client().webhooks.add(webhookUrl, eventTypes, options),
|
|
1085
1276
|
update: (webhookId, webhookUrl, eventTypes, options) => client().webhooks.update(webhookId, webhookUrl, eventTypes, options),
|
|
1086
1277
|
delete: (webhookId, options) => client().webhooks.delete(webhookId, options),
|
|
1087
|
-
logs: (webhookId, options) => client().webhooks.logs(webhookId, options)
|
|
1278
|
+
logs: (webhookId, options) => client().webhooks.logs(webhookId, options),
|
|
1279
|
+
test: (webhookId, options) => client().webhooks.test(webhookId, options),
|
|
1280
|
+
resend: (deliveryId, options) => client().webhooks.resend(deliveryId, options)
|
|
1088
1281
|
};
|
|
1089
1282
|
var pixelflows = {
|
|
1090
1283
|
run: (slug, inputs, options) => client().pixelflows.run(slug, inputs, options),
|