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.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/core/errors.ts
|
|
2
|
-
var SegmindError = class
|
|
2
|
+
var SegmindError = class extends Error {
|
|
3
3
|
/** HTTP status, when the error came from a response. */
|
|
4
4
|
status;
|
|
5
5
|
/** The server's error text (`error` in the response body), when it sent one. */
|
|
@@ -17,20 +17,21 @@ var SegmindError = class _SegmindError extends Error {
|
|
|
17
17
|
this.body = options.body;
|
|
18
18
|
}
|
|
19
19
|
/** Reads the response body and builds the error. Consumes the body. */
|
|
20
|
-
static
|
|
21
|
-
|
|
22
|
-
let body = text;
|
|
23
|
-
try {
|
|
24
|
-
body = text ? JSON.parse(text) : void 0;
|
|
25
|
-
} catch {
|
|
26
|
-
}
|
|
27
|
-
const detail = errorDetail(body) ?? (typeof body === "string" && body ? body.slice(0, 500) : void 0);
|
|
28
|
-
const message = detail ? `${response.status} ${detail}` : `${response.status} ${response.statusText || "request failed"}`;
|
|
29
|
-
return new _SegmindError(message, { status: response.status, detail, requestId, body });
|
|
20
|
+
static fromResponse(response, requestId) {
|
|
21
|
+
return errorFromResponse(response, requestId);
|
|
30
22
|
}
|
|
31
23
|
};
|
|
32
24
|
var APIConnectionError = class extends SegmindError {
|
|
33
25
|
};
|
|
26
|
+
var InsufficientCredits = class extends SegmindError {
|
|
27
|
+
};
|
|
28
|
+
var RateLimited = class extends SegmindError {
|
|
29
|
+
retryAfterMs;
|
|
30
|
+
constructor(message, options = {}) {
|
|
31
|
+
super(message, options);
|
|
32
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
34
35
|
var InferenceFailed = class extends SegmindError {
|
|
35
36
|
/** The status body that reported the failure. */
|
|
36
37
|
statusBody;
|
|
@@ -51,6 +52,43 @@ var InferenceTimeout = class extends SegmindError {
|
|
|
51
52
|
this.elapsedMs = elapsedMs;
|
|
52
53
|
}
|
|
53
54
|
};
|
|
55
|
+
async function errorFromResponse(response, requestId) {
|
|
56
|
+
const text = await response.text().catch(() => "");
|
|
57
|
+
let body = text;
|
|
58
|
+
try {
|
|
59
|
+
body = text ? JSON.parse(text) : void 0;
|
|
60
|
+
} catch {
|
|
61
|
+
}
|
|
62
|
+
const detail = errorDetail(body) ?? plainText(body);
|
|
63
|
+
const message = detail ? `${response.status} ${detail}` : `${response.status} ${response.statusText || "request failed"}`;
|
|
64
|
+
const options = { status: response.status, detail, requestId, body };
|
|
65
|
+
if (response.status === 429) {
|
|
66
|
+
return new RateLimited(message, { ...options, retryAfterMs: parseRetryAfter(response.headers.get("retry-after")) });
|
|
67
|
+
}
|
|
68
|
+
if (response.status === 402 || isOutOfCredits(detail)) return new InsufficientCredits(message, options);
|
|
69
|
+
return new SegmindError(message, options);
|
|
70
|
+
}
|
|
71
|
+
function requestFailure(requestId, statusBody, detail) {
|
|
72
|
+
detail ??= typeof statusBody.error === "string" ? statusBody.error : void 0;
|
|
73
|
+
if (isOutOfCredits(detail)) {
|
|
74
|
+
return new InsufficientCredits(`request ${requestId} failed: ${detail}`, { detail, requestId, body: statusBody });
|
|
75
|
+
}
|
|
76
|
+
return new InferenceFailed(requestId, statusBody, detail);
|
|
77
|
+
}
|
|
78
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
79
|
+
if (!value) return void 0;
|
|
80
|
+
const seconds = Number(value);
|
|
81
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
|
|
82
|
+
const date = Date.parse(value);
|
|
83
|
+
return Number.isNaN(date) ? void 0 : Math.max(date - now, 0);
|
|
84
|
+
}
|
|
85
|
+
function isOutOfCredits(detail) {
|
|
86
|
+
return detail?.startsWith("Insufficient credits.") ?? false;
|
|
87
|
+
}
|
|
88
|
+
function plainText(body) {
|
|
89
|
+
if (typeof body !== "string" || !body || body.trimStart().startsWith("<")) return void 0;
|
|
90
|
+
return body.slice(0, 500);
|
|
91
|
+
}
|
|
54
92
|
function errorDetail(body) {
|
|
55
93
|
if (!body || typeof body !== "object") return void 0;
|
|
56
94
|
const record2 = body;
|
|
@@ -168,6 +206,12 @@ function detectRuntime() {
|
|
|
168
206
|
if (g.process?.versions?.node) return "node";
|
|
169
207
|
return "other";
|
|
170
208
|
}
|
|
209
|
+
function initiatorHeaders(options) {
|
|
210
|
+
return {
|
|
211
|
+
...options.initiator ? { "X-Initiator": options.initiator } : {},
|
|
212
|
+
...options.initiatorId ? { "X-Initiator-ID": options.initiatorId } : {}
|
|
213
|
+
};
|
|
214
|
+
}
|
|
171
215
|
function readEnv(name) {
|
|
172
216
|
try {
|
|
173
217
|
const value = g.process?.env?.[name];
|
|
@@ -200,15 +244,15 @@ function toBase64(bytes) {
|
|
|
200
244
|
var RETRYABLE_STATUS = /* @__PURE__ */ new Set([408, 429, 502, 503, 504]);
|
|
201
245
|
var MAX_RETRY_DELAY_MS = 6e4;
|
|
202
246
|
function retryDelay(attempt, retryAfter, now = Date.now()) {
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1e3, MAX_RETRY_DELAY_MS);
|
|
206
|
-
const date = Date.parse(retryAfter);
|
|
207
|
-
if (!Number.isNaN(date)) return Math.min(Math.max(date - now, 0), MAX_RETRY_DELAY_MS);
|
|
208
|
-
}
|
|
247
|
+
const asked = parseRetryAfter(retryAfter, now);
|
|
248
|
+
if (asked !== void 0) return Math.min(asked, MAX_RETRY_DELAY_MS);
|
|
209
249
|
const base = Math.min(500 * 2 ** attempt, 8e3);
|
|
210
250
|
return base * (0.75 + Math.random() * 0.25);
|
|
211
251
|
}
|
|
252
|
+
function pollDelay(interval, elapsedMs, fallback) {
|
|
253
|
+
const delay = typeof interval === "function" ? interval(elapsedMs) : interval ?? fallback;
|
|
254
|
+
return Number.isFinite(delay) && delay >= 0 ? delay : fallback;
|
|
255
|
+
}
|
|
212
256
|
function sleep(ms, signal) {
|
|
213
257
|
return new Promise((resolve, reject) => {
|
|
214
258
|
if (signal?.aborted) return reject(signal.reason);
|
|
@@ -228,23 +272,35 @@ var HttpClient = class {
|
|
|
228
272
|
this.config = config;
|
|
229
273
|
}
|
|
230
274
|
config;
|
|
275
|
+
/** The hook call in flight, so that requests failing together share one refresh. */
|
|
276
|
+
unauthorized;
|
|
231
277
|
/** The response whatever its status, after retries when `retry` is set. */
|
|
232
278
|
async fetchRaw(req) {
|
|
233
|
-
|
|
279
|
+
let attempt = 0;
|
|
280
|
+
let reauthenticated = false;
|
|
281
|
+
for (; ; ) {
|
|
234
282
|
const canRetry = req.retry === true && attempt < this.config.maxRetries;
|
|
283
|
+
const token = await this.sessionToken(req);
|
|
235
284
|
let response;
|
|
236
285
|
try {
|
|
237
|
-
response = await this.attempt(req);
|
|
286
|
+
response = await this.attempt(req, token);
|
|
238
287
|
} catch (err) {
|
|
239
288
|
if (canRetry && err instanceof APIConnectionError) {
|
|
240
289
|
await sleep(retryDelay(attempt, null), req.signal);
|
|
290
|
+
attempt++;
|
|
241
291
|
continue;
|
|
242
292
|
}
|
|
243
293
|
throw err;
|
|
244
294
|
}
|
|
295
|
+
if (response.status === 401 && !reauthenticated && await this.reauthenticate(req, token)) {
|
|
296
|
+
reauthenticated = true;
|
|
297
|
+
await response.body?.cancel().catch(() => void 0);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
245
300
|
if (canRetry && RETRYABLE_STATUS.has(response.status)) {
|
|
246
301
|
await response.body?.cancel().catch(() => void 0);
|
|
247
302
|
await sleep(retryDelay(attempt, response.headers.get("retry-after")), req.signal);
|
|
303
|
+
attempt++;
|
|
248
304
|
continue;
|
|
249
305
|
}
|
|
250
306
|
return response;
|
|
@@ -260,7 +316,31 @@ var HttpClient = class {
|
|
|
260
316
|
async json(req) {
|
|
261
317
|
return readJson(await this.request(req));
|
|
262
318
|
}
|
|
263
|
-
async
|
|
319
|
+
async sessionToken(req) {
|
|
320
|
+
if (!this.config.tokenProvider || req.bare) return void 0;
|
|
321
|
+
try {
|
|
322
|
+
return await this.config.tokenProvider() ?? void 0;
|
|
323
|
+
} catch (err) {
|
|
324
|
+
throw new SegmindError(`tokenProvider failed: ${describe(err)}`, { cause: err });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/** Tells the app its token was refused. True when it now has a different one to try. */
|
|
328
|
+
async reauthenticate(req, refused) {
|
|
329
|
+
if (!this.config.tokenProvider || req.bare) return false;
|
|
330
|
+
try {
|
|
331
|
+
if (this.config.onUnauthorized) {
|
|
332
|
+
this.unauthorized ??= Promise.resolve(this.config.onUnauthorized()).finally(() => {
|
|
333
|
+
this.unauthorized = void 0;
|
|
334
|
+
});
|
|
335
|
+
await this.unauthorized;
|
|
336
|
+
}
|
|
337
|
+
const next = await this.config.tokenProvider();
|
|
338
|
+
return Boolean(next) && next !== refused;
|
|
339
|
+
} catch {
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
async attempt(req, token) {
|
|
264
344
|
const { signal } = req;
|
|
265
345
|
if (signal?.aborted) throw signal.reason;
|
|
266
346
|
const timeout = req.timeout ?? this.config.timeout;
|
|
@@ -274,6 +354,7 @@ var HttpClient = class {
|
|
|
274
354
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
275
355
|
const headers = req.bare ? { ...req.headers } : { ...this.config.headers, ...req.headers };
|
|
276
356
|
if (this.config.apiKey && !req.bare) headers["x-api-key"] = this.config.apiKey;
|
|
357
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
277
358
|
if (req.body !== void 0) headers["content-type"] = "application/json";
|
|
278
359
|
const body = req.rawBody ?? (req.body === void 0 ? void 0 : JSON.stringify(req.body));
|
|
279
360
|
try {
|
|
@@ -368,7 +449,12 @@ async function readFileInput(input, options) {
|
|
|
368
449
|
if (detectRuntime() !== "node") {
|
|
369
450
|
throw new SegmindError(`${options.caller}: file paths work in Node only; pass a Blob or bytes`);
|
|
370
451
|
}
|
|
371
|
-
const { readFile } = await import(
|
|
452
|
+
const { readFile } = await import(
|
|
453
|
+
/* webpackIgnore: true */
|
|
454
|
+
/* turbopackIgnore: true */
|
|
455
|
+
/* @vite-ignore */
|
|
456
|
+
"node:fs/promises"
|
|
457
|
+
);
|
|
372
458
|
try {
|
|
373
459
|
bytes = new Uint8Array(await readFile(input));
|
|
374
460
|
} catch (err) {
|
|
@@ -512,6 +598,8 @@ var Generations = class {
|
|
|
512
598
|
to_date: options.toDate,
|
|
513
599
|
model_name: options.modelName,
|
|
514
600
|
status: options.status,
|
|
601
|
+
initiator: [options.initiator ?? []].flat().join(",") || void 0,
|
|
602
|
+
key_suffix: options.keySuffix,
|
|
515
603
|
user_id: options.userId,
|
|
516
604
|
user_email: options.userEmail,
|
|
517
605
|
sort_by: options.sortBy,
|
|
@@ -551,12 +639,12 @@ var Job = class {
|
|
|
551
639
|
return await this.read(this.statusUrl, options.signal);
|
|
552
640
|
}
|
|
553
641
|
/**
|
|
554
|
-
* The finished result. Throws `InferenceFailed` when the request failed
|
|
555
|
-
* a `SegmindError` when it has not finished yet (use `wait()` for that).
|
|
642
|
+
* The finished result. Throws `InferenceFailed` when the request failed
|
|
643
|
+
* (`InsufficientCredits` when that was for lack of credits), and a `SegmindError` when it has not finished yet (use `wait()` for that).
|
|
556
644
|
*/
|
|
557
645
|
async result(options = {}) {
|
|
558
646
|
const body = await this.read(this.responseUrl, options.signal);
|
|
559
|
-
if (body.status === "FAILED") throw
|
|
647
|
+
if (body.status === "FAILED") throw requestFailure(this.requestId, body);
|
|
560
648
|
if (body.status !== void 0 && body.status !== "COMPLETED") {
|
|
561
649
|
throw new SegmindError(`request ${this.requestId} is still ${String(body.status)}; use wait()`, {
|
|
562
650
|
requestId: this.requestId,
|
|
@@ -568,15 +656,16 @@ var Job = class {
|
|
|
568
656
|
/** Polls until the request finishes, then returns its result. */
|
|
569
657
|
async wait(options = {}) {
|
|
570
658
|
const timeout = options.timeout ?? DEFAULT_WAIT_TIMEOUT_MS;
|
|
571
|
-
const interval = options.interval ?? DEFAULT_WAIT_INTERVAL_MS;
|
|
572
659
|
const started = Date.now();
|
|
573
660
|
for (; ; ) {
|
|
574
661
|
const status = await this.status({ signal: options.signal });
|
|
662
|
+
options.onStatus?.(status);
|
|
575
663
|
if (status.status === "COMPLETED") return this.result({ signal: options.signal });
|
|
576
|
-
if (status.status === "FAILED") throw
|
|
664
|
+
if (status.status === "FAILED") throw requestFailure(this.requestId, status);
|
|
577
665
|
const elapsed = Date.now() - started;
|
|
578
666
|
if (elapsed >= timeout) throw new InferenceTimeout(this.requestId, elapsed);
|
|
579
|
-
|
|
667
|
+
const delay = pollDelay(options.interval, elapsed, DEFAULT_WAIT_INTERVAL_MS);
|
|
668
|
+
await sleep(Math.min(delay, timeout - elapsed), options.signal);
|
|
580
669
|
}
|
|
581
670
|
}
|
|
582
671
|
/**
|
|
@@ -608,8 +697,8 @@ var PixelFlows = class {
|
|
|
608
697
|
client;
|
|
609
698
|
/** Runs a workflow and waits for its outputs. */
|
|
610
699
|
async run(slug, inputs = {}, options = {}) {
|
|
611
|
-
const
|
|
612
|
-
return
|
|
700
|
+
const job2 = await this.submit(slug, inputs, options);
|
|
701
|
+
return job2.wait(options);
|
|
613
702
|
}
|
|
614
703
|
/** Starts a workflow and returns a job to wait on. Never retried: a run bills. */
|
|
615
704
|
async submit(slug, inputs = {}, options = {}) {
|
|
@@ -620,6 +709,7 @@ var PixelFlows = class {
|
|
|
620
709
|
method: "POST",
|
|
621
710
|
url: `${this.client.baseURL}${route}${clean}`,
|
|
622
711
|
body: inputs,
|
|
712
|
+
headers: initiatorHeaders(options),
|
|
623
713
|
signal: options.signal
|
|
624
714
|
});
|
|
625
715
|
const requestId = body.request_id;
|
|
@@ -655,20 +745,21 @@ var PixelflowJob = class {
|
|
|
655
745
|
}
|
|
656
746
|
/**
|
|
657
747
|
* Polls until the run finishes. Throws `InferenceFailed` (its `detail` names
|
|
658
|
-
* the failing node) or `InferenceTimeout`; the run may still finish after a
|
|
748
|
+
* the failing node), `InsufficientCredits` or `InferenceTimeout`; the run may still finish after a
|
|
659
749
|
* timeout, so `wait()` can be called again.
|
|
660
750
|
*/
|
|
661
751
|
async wait(options = {}) {
|
|
662
752
|
const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
663
|
-
const interval = options.interval ?? DEFAULT_INTERVAL_MS;
|
|
664
753
|
const started = Date.now();
|
|
665
754
|
for (; ; ) {
|
|
666
755
|
const state = await this.status({ signal: options.signal });
|
|
756
|
+
options.onStatus?.(state);
|
|
667
757
|
if (DONE.has(state.status)) return state;
|
|
668
|
-
if (FAILED.has(state.status)) throw
|
|
758
|
+
if (FAILED.has(state.status)) throw requestFailure(this.requestId, state.raw, failureDetail(state.raw));
|
|
669
759
|
const elapsed = Date.now() - started;
|
|
670
|
-
|
|
671
|
-
|
|
760
|
+
const delay = pollDelay(options.interval, elapsed, DEFAULT_INTERVAL_MS);
|
|
761
|
+
if (elapsed + delay > timeout) throw new InferenceTimeout(this.requestId, elapsed);
|
|
762
|
+
await sleep(delay, options.signal);
|
|
672
763
|
}
|
|
673
764
|
}
|
|
674
765
|
};
|
|
@@ -713,7 +804,7 @@ function failureDetail(body) {
|
|
|
713
804
|
}
|
|
714
805
|
|
|
715
806
|
// src/version.ts
|
|
716
|
-
var VERSION = "0.
|
|
807
|
+
var VERSION = "0.4.0";
|
|
717
808
|
|
|
718
809
|
// src/webhooks.ts
|
|
719
810
|
var Webhooks = class {
|
|
@@ -753,10 +844,26 @@ var Webhooks = class {
|
|
|
753
844
|
async delete(webhookId, options = {}) {
|
|
754
845
|
return this.call("DELETE", "/inactive", { query: { webhook_id: webhookId }, signal: options.signal });
|
|
755
846
|
}
|
|
756
|
-
/**
|
|
847
|
+
/** Every delivery made to one registration. */
|
|
757
848
|
async logs(webhookId, options = {}) {
|
|
758
849
|
return this.call("GET", "/dispatch-logs", { query: { webhook_id: webhookId }, signal: options.signal, retry: true });
|
|
759
850
|
}
|
|
851
|
+
/**
|
|
852
|
+
* Sends a `WEBHOOK_TEST` delivery to an active registration. It goes out in
|
|
853
|
+
* the background after this returns, so read `logs` to see how your endpoint
|
|
854
|
+
* answered. Not retried: each attempt is another delivery.
|
|
855
|
+
*/
|
|
856
|
+
async test(webhookId, options = {}) {
|
|
857
|
+
return this.call("POST", "/test", { body: { webhook_id: webhookId }, signal: options.signal });
|
|
858
|
+
}
|
|
859
|
+
/**
|
|
860
|
+
* Sends a past delivery's payload again, by its `id` from `logs`. Refused
|
|
861
|
+
* (406) when the registration is no longer active. Not retried: each
|
|
862
|
+
* attempt is another delivery.
|
|
863
|
+
*/
|
|
864
|
+
async resend(deliveryId, options = {}) {
|
|
865
|
+
return this.call("POST", "/resend", { body: { webhook_dispatch_id: deliveryId }, signal: options.signal });
|
|
866
|
+
}
|
|
760
867
|
call(method, path2, req) {
|
|
761
868
|
return this.client.http.json({ method, url: `${this.client.spotURL}/webhook${path2}`, ...req });
|
|
762
869
|
}
|
|
@@ -791,14 +898,17 @@ var Segmind = class {
|
|
|
791
898
|
/** @internal */
|
|
792
899
|
http;
|
|
793
900
|
constructor(options = {}) {
|
|
794
|
-
|
|
901
|
+
if (options.apiKey && options.tokenProvider) {
|
|
902
|
+
throw new SegmindError("Pass either apiKey or tokenProvider, not both.");
|
|
903
|
+
}
|
|
904
|
+
const apiKey = options.apiKey ?? (options.tokenProvider ? void 0 : readEnv("SEGMIND_API_KEY"));
|
|
795
905
|
const runtime = detectRuntime();
|
|
796
906
|
if (apiKey && (runtime === "browser" || runtime === "react-native") && !options.dangerouslyAllowBrowser) {
|
|
797
907
|
throw new SegmindError(
|
|
798
908
|
"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."
|
|
799
909
|
);
|
|
800
910
|
}
|
|
801
|
-
if (!apiKey) {
|
|
911
|
+
if (!apiKey && !options.tokenProvider) {
|
|
802
912
|
throw new SegmindError("Missing API key: pass { apiKey } or set the SEGMIND_API_KEY environment variable.");
|
|
803
913
|
}
|
|
804
914
|
const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
|
|
@@ -807,11 +917,17 @@ var Segmind = class {
|
|
|
807
917
|
this.spotURL = trimSlash(options.spotURL ?? DEFAULT_SPOT_URL);
|
|
808
918
|
this.consoleURL = trimSlash(options.consoleURL ?? DEFAULT_CONSOLE_URL);
|
|
809
919
|
this.assetsURL = trimSlash(options.assetsURL ?? DEFAULT_ASSETS_URL);
|
|
810
|
-
const headers = {
|
|
920
|
+
const headers = {
|
|
921
|
+
"X-Initiator": "SDK-JS",
|
|
922
|
+
...initiatorHeaders(options),
|
|
923
|
+
...options.defaultHeaders
|
|
924
|
+
};
|
|
811
925
|
const node = nodeVersion();
|
|
812
926
|
if (runtime === "node" && node) headers["User-Agent"] = `segmind-js/${VERSION} node/${node}`;
|
|
813
927
|
this.http = new HttpClient({
|
|
814
928
|
apiKey,
|
|
929
|
+
tokenProvider: options.tokenProvider,
|
|
930
|
+
onUnauthorized: options.onUnauthorized,
|
|
815
931
|
fetch: fetchImpl,
|
|
816
932
|
timeout: options.timeout ?? 6e5,
|
|
817
933
|
maxRetries: options.maxRetries ?? 2,
|
|
@@ -829,8 +945,8 @@ var Segmind = class {
|
|
|
829
945
|
* until it finishes. `params` go to the model unchanged.
|
|
830
946
|
*/
|
|
831
947
|
async run(slug, params = {}, options = {}) {
|
|
832
|
-
const
|
|
833
|
-
return
|
|
948
|
+
const job2 = await this.submit(slug, params, options);
|
|
949
|
+
return job2.wait(options);
|
|
834
950
|
}
|
|
835
951
|
/**
|
|
836
952
|
* One blocking `POST /v1/{slug}`. Returns the fetch `Response`: call
|
|
@@ -842,6 +958,7 @@ var Segmind = class {
|
|
|
842
958
|
method: "POST",
|
|
843
959
|
url: `${this.baseURL}/v1/${path(slug)}`,
|
|
844
960
|
body: params,
|
|
961
|
+
headers: initiatorHeaders(options),
|
|
845
962
|
signal: options.signal,
|
|
846
963
|
timeout: options.timeout
|
|
847
964
|
});
|
|
@@ -854,10 +971,27 @@ var Segmind = class {
|
|
|
854
971
|
async submit(slug, params = {}, options = {}) {
|
|
855
972
|
return this.submitJob(slug, params, options, (body) => body);
|
|
856
973
|
}
|
|
974
|
+
/**
|
|
975
|
+
* A job submitted earlier, from its id alone, for picking one up after a
|
|
976
|
+
* reload or in another process. Makes no request. The result is kept for about
|
|
977
|
+
* an hour, and only for the user who submitted it: anything else reads as a
|
|
978
|
+
* `SegmindError` with status 404.
|
|
979
|
+
*/
|
|
980
|
+
job(requestId) {
|
|
981
|
+
const clean = requestId.trim();
|
|
982
|
+
if (!clean) throw new SegmindError("A request id is required.");
|
|
983
|
+
const url = `${this.baseURL}/v2/requests/${encodeURIComponent(clean)}`;
|
|
984
|
+
return new Job(this.http, {
|
|
985
|
+
request_id: clean,
|
|
986
|
+
status: "UNKNOWN",
|
|
987
|
+
status_url: `${url}/status`,
|
|
988
|
+
response_url: url
|
|
989
|
+
});
|
|
990
|
+
}
|
|
857
991
|
/** Chat with an LLM through the v2 queue. Returns a provider-neutral reply. */
|
|
858
992
|
async chat(slug, params, options = {}) {
|
|
859
|
-
const
|
|
860
|
-
return
|
|
993
|
+
const job2 = await this.submitChat(slug, params, options);
|
|
994
|
+
return job2.wait(options);
|
|
861
995
|
}
|
|
862
996
|
/** Chat with one blocking `POST /v1/{slug}`. */
|
|
863
997
|
async chatSync(slug, params, options = {}) {
|
|
@@ -880,7 +1014,7 @@ var Segmind = class {
|
|
|
880
1014
|
method: "POST",
|
|
881
1015
|
url,
|
|
882
1016
|
body: params,
|
|
883
|
-
headers: { "X-Request-ID": requestId },
|
|
1017
|
+
headers: { "X-Request-ID": requestId, ...initiatorHeaders(options) },
|
|
884
1018
|
signal: options.signal
|
|
885
1019
|
});
|
|
886
1020
|
} catch (err) {
|
|
@@ -916,21 +1050,62 @@ var Segmind = class {
|
|
|
916
1050
|
}
|
|
917
1051
|
}
|
|
918
1052
|
};
|
|
1053
|
+
var MODELS_PAGE_LIMIT = 100;
|
|
919
1054
|
var Models = class {
|
|
920
1055
|
constructor(client2) {
|
|
921
1056
|
this.client = client2;
|
|
922
1057
|
}
|
|
923
1058
|
client;
|
|
924
|
-
/**
|
|
925
|
-
async list(options = {}) {
|
|
1059
|
+
/** One page of the catalog. Pass `offset` from the previous page while `has_more` is true. */
|
|
1060
|
+
async list(params = {}, options = {}) {
|
|
926
1061
|
return this.client.http.json({
|
|
927
1062
|
method: "GET",
|
|
928
|
-
url: `${this.client.
|
|
1063
|
+
url: `${this.client.baseURL}/models`,
|
|
1064
|
+
query: modelsQuery(params),
|
|
929
1065
|
signal: options.signal,
|
|
930
1066
|
retry: true
|
|
931
1067
|
});
|
|
932
1068
|
}
|
|
1069
|
+
/** Every model matching `params`, reading page after page. */
|
|
1070
|
+
async listAll(params = {}, options = {}) {
|
|
1071
|
+
const models2 = [];
|
|
1072
|
+
for (let offset = 0; ; ) {
|
|
1073
|
+
const page = await this.list({ ...params, limit: MODELS_PAGE_LIMIT, offset }, options);
|
|
1074
|
+
models2.push(...page.models);
|
|
1075
|
+
offset += page.models.length;
|
|
1076
|
+
if (!page.has_more || !page.models.length || offset >= page.total) return models2;
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
933
1079
|
};
|
|
1080
|
+
function modelsQuery(p) {
|
|
1081
|
+
return {
|
|
1082
|
+
q: p.q,
|
|
1083
|
+
sort: p.sort,
|
|
1084
|
+
category: p.category,
|
|
1085
|
+
modality: p.modality,
|
|
1086
|
+
input: joinList(p.input),
|
|
1087
|
+
output: joinList(p.output),
|
|
1088
|
+
provider: p.provider,
|
|
1089
|
+
slugs: joinList(p.slugs),
|
|
1090
|
+
operations: joinList(p.operations),
|
|
1091
|
+
features: joinList(p.features),
|
|
1092
|
+
min_popularity: p.minPopularity,
|
|
1093
|
+
min_category_percentile: p.minCategoryPercentile,
|
|
1094
|
+
min_cost: p.minCost,
|
|
1095
|
+
max_cost: p.maxCost,
|
|
1096
|
+
max_latency: p.maxLatency,
|
|
1097
|
+
is_new: p.isNew,
|
|
1098
|
+
created_after: p.createdAfter,
|
|
1099
|
+
include_coming_soon: p.includeComingSoon,
|
|
1100
|
+
facets: p.facets,
|
|
1101
|
+
limit: p.limit,
|
|
1102
|
+
offset: p.offset
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
function joinList(value) {
|
|
1106
|
+
if (value === void 0) return void 0;
|
|
1107
|
+
return Array.isArray(value) ? value.join(",") : value;
|
|
1108
|
+
}
|
|
934
1109
|
var Accounts = class {
|
|
935
1110
|
constructor(client2) {
|
|
936
1111
|
this.client = client2;
|
|
@@ -945,6 +1120,16 @@ var Accounts = class {
|
|
|
945
1120
|
retry: true
|
|
946
1121
|
});
|
|
947
1122
|
}
|
|
1123
|
+
/** The current credit balance. */
|
|
1124
|
+
async credits(options = {}) {
|
|
1125
|
+
const { "free-credits": freeCredits, ...rest } = await this.client.http.json({
|
|
1126
|
+
method: "GET",
|
|
1127
|
+
url: `${this.client.baseURL}/v1/get-user-credits`,
|
|
1128
|
+
signal: options.signal,
|
|
1129
|
+
retry: true
|
|
1130
|
+
});
|
|
1131
|
+
return { ...rest, credits: Number(rest.credits), freeCredits: Number(freeCredits) };
|
|
1132
|
+
}
|
|
948
1133
|
};
|
|
949
1134
|
function validateSubmit(body, status) {
|
|
950
1135
|
if (!body.request_id || !body.status_url || !body.response_url) {
|
|
@@ -993,14 +1178,17 @@ function client() {
|
|
|
993
1178
|
var run = (slug, params, options) => client().run(slug, params, options);
|
|
994
1179
|
var runSync = (slug, params, options) => client().runSync(slug, params, options);
|
|
995
1180
|
var submit = (slug, params, options) => client().submit(slug, params, options);
|
|
1181
|
+
var job = (requestId) => client().job(requestId);
|
|
996
1182
|
var chat = (slug, params, options) => client().chat(slug, params, options);
|
|
997
1183
|
var chatSync = (slug, params, options) => client().chatSync(slug, params, options);
|
|
998
1184
|
var submitChat = (slug, params, options) => client().submitChat(slug, params, options);
|
|
999
1185
|
var models = {
|
|
1000
|
-
list: (options) => client().models.list(options)
|
|
1186
|
+
list: (params, options) => client().models.list(params, options),
|
|
1187
|
+
listAll: (params, options) => client().models.listAll(params, options)
|
|
1001
1188
|
};
|
|
1002
1189
|
var accounts = {
|
|
1003
|
-
current: (options) => client().accounts.current(options)
|
|
1190
|
+
current: (options) => client().accounts.current(options),
|
|
1191
|
+
credits: (options) => client().accounts.credits(options)
|
|
1004
1192
|
};
|
|
1005
1193
|
var files = {
|
|
1006
1194
|
upload: ((input, options) => client().files.upload(input, options))
|
|
@@ -1016,7 +1204,9 @@ var webhooks = {
|
|
|
1016
1204
|
add: (webhookUrl, eventTypes, options) => client().webhooks.add(webhookUrl, eventTypes, options),
|
|
1017
1205
|
update: (webhookId, webhookUrl, eventTypes, options) => client().webhooks.update(webhookId, webhookUrl, eventTypes, options),
|
|
1018
1206
|
delete: (webhookId, options) => client().webhooks.delete(webhookId, options),
|
|
1019
|
-
logs: (webhookId, options) => client().webhooks.logs(webhookId, options)
|
|
1207
|
+
logs: (webhookId, options) => client().webhooks.logs(webhookId, options),
|
|
1208
|
+
test: (webhookId, options) => client().webhooks.test(webhookId, options),
|
|
1209
|
+
resend: (deliveryId, options) => client().webhooks.resend(deliveryId, options)
|
|
1020
1210
|
};
|
|
1021
1211
|
var pixelflows = {
|
|
1022
1212
|
run: (slug, inputs, options) => client().pixelflows.run(slug, inputs, options),
|
|
@@ -1037,10 +1227,12 @@ export {
|
|
|
1037
1227
|
Generations,
|
|
1038
1228
|
InferenceFailed,
|
|
1039
1229
|
InferenceTimeout,
|
|
1230
|
+
InsufficientCredits,
|
|
1040
1231
|
Job,
|
|
1041
1232
|
Models,
|
|
1042
1233
|
PixelFlows,
|
|
1043
1234
|
PixelflowJob,
|
|
1235
|
+
RateLimited,
|
|
1044
1236
|
Segmind,
|
|
1045
1237
|
SegmindError,
|
|
1046
1238
|
VERSION,
|
|
@@ -1051,6 +1243,7 @@ export {
|
|
|
1051
1243
|
files,
|
|
1052
1244
|
generations,
|
|
1053
1245
|
imageUrl,
|
|
1246
|
+
job,
|
|
1054
1247
|
models,
|
|
1055
1248
|
pixelflows,
|
|
1056
1249
|
run,
|