segmind 0.6.0 → 0.7.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/dist/index.cjs CHANGED
@@ -105,12 +105,78 @@ function str(value) {
105
105
  return typeof value === "string" ? value : void 0;
106
106
  }
107
107
 
108
+ // src/decisions.ts
109
+ var DecisionResponse = class {
110
+ constructor(body) {
111
+ const answers = record2(body.answers);
112
+ if (!answers) throw new (0, _chunk74UKKBOOcjs.SegmindError)("not a decision reply: it has no answers map", { body });
113
+ this.model = typeof body.model === "string" ? body.model : "";
114
+ this.answers = answers;
115
+ this.raw = body.raw;
116
+ this.usage = record2(body.usage);
117
+ this.cost = num(body.cost);
118
+ this.latencyMs = num(body.latency_ms);
119
+ this.warnings = Array.isArray(body.warnings) ? body.warnings.filter((w) => typeof w === "string") : [];
120
+ }
121
+ /** The full answer for `key`, whatever its status. Throws for a key no question used. */
122
+ answer(key) {
123
+ if (!Object.prototype.hasOwnProperty.call(this.answers, key)) throw new (0, _chunk74UKKBOOcjs.SegmindError)(`no answer for "${key}"`);
124
+ return this.answers[key];
125
+ }
126
+ /** `ok`, `refused` or `error`. */
127
+ status(key) {
128
+ return this.answer(key).status;
129
+ }
130
+ /** A yes/no question's probability of yes; undefined unless the model answered. */
131
+ probability(key) {
132
+ return this.read(key, "noul", "probability");
133
+ }
134
+ /** A choice question's picked option; undefined unless the model answered. */
135
+ choice(key) {
136
+ return this.read(key, "choice", "choice");
137
+ }
138
+ /** A score question's expected level index (0 = lowest); undefined unless answered. */
139
+ score(key) {
140
+ return this.read(key, "score", "score");
141
+ }
142
+ /** A box question's edges; undefined unless the model answered. */
143
+ box(key) {
144
+ return this.read(key, "box", "box");
145
+ }
146
+ /** A field of an `ok` answer of `type`. A refused or errored answer has none. */
147
+ read(key, type, field) {
148
+ const a = this.answer(key);
149
+ return a.status === "ok" && a.type === type ? a[field] : void 0;
150
+ }
151
+ };
152
+ function decisionBody(params) {
153
+ const { state, questions } = params;
154
+ if (state == null || typeof state === "string" && !state.trim()) throw new (0, _chunk74UKKBOOcjs.SegmindError)("decide: state is required");
155
+ if (!record2(questions) || !Object.keys(questions).length) {
156
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("decide: questions must map at least one key to a question");
157
+ }
158
+ return params;
159
+ }
160
+ function decisionFromRunResult(body) {
161
+ let output = body.output;
162
+ if (typeof output === "string" && output.trim()) output = JSON.parse(output);
163
+ if (_optionalChain([record2, 'call', _19 => _19(output), 'optionalAccess', _20 => _20.answers])) return new DecisionResponse(output);
164
+ if (record2(body.answers)) return new DecisionResponse(body);
165
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("the v2 result has no decision reply; decideSync makes a blocking /v1 call instead", { body });
166
+ }
167
+ function record2(value) {
168
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
169
+ }
170
+ function num(value) {
171
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
172
+ }
173
+
108
174
  // src/core/env.ts
109
175
  var g = globalThis;
110
176
  function detectRuntime() {
111
- if (_optionalChain([g, 'access', _19 => _19.navigator, 'optionalAccess', _20 => _20.product]) === "ReactNative") return "react-native";
177
+ if (_optionalChain([g, 'access', _21 => _21.navigator, 'optionalAccess', _22 => _22.product]) === "ReactNative") return "react-native";
112
178
  if (typeof g.window !== "undefined" && typeof g.document !== "undefined") return "browser";
113
- if (_optionalChain([g, 'access', _21 => _21.process, 'optionalAccess', _22 => _22.versions, 'optionalAccess', _23 => _23.node])) return "node";
179
+ if (_optionalChain([g, 'access', _23 => _23.process, 'optionalAccess', _24 => _24.versions, 'optionalAccess', _25 => _25.node])) return "node";
114
180
  return "other";
115
181
  }
116
182
  function initiatorHeaders(options) {
@@ -121,17 +187,17 @@ function initiatorHeaders(options) {
121
187
  }
122
188
  function readEnv(name) {
123
189
  try {
124
- const value = _optionalChain([g, 'access', _24 => _24.process, 'optionalAccess', _25 => _25.env, 'optionalAccess', _26 => _26[name]]);
125
- return _optionalChain([value, 'optionalAccess', _27 => _27.trim, 'call', _28 => _28()]) ? value.trim() : void 0;
190
+ const value = _optionalChain([g, 'access', _26 => _26.process, 'optionalAccess', _27 => _27.env, 'optionalAccess', _28 => _28[name]]);
191
+ return _optionalChain([value, 'optionalAccess', _29 => _29.trim, 'call', _30 => _30()]) ? value.trim() : void 0;
126
192
  } catch (e3) {
127
193
  return void 0;
128
194
  }
129
195
  }
130
196
  function nodeVersion() {
131
- return _optionalChain([g, 'access', _29 => _29.process, 'optionalAccess', _30 => _30.versions, 'optionalAccess', _31 => _31.node]) ? g.process.version : void 0;
197
+ return _optionalChain([g, 'access', _31 => _31.process, 'optionalAccess', _32 => _32.versions, 'optionalAccess', _33 => _33.node]) ? g.process.version : void 0;
132
198
  }
133
199
  function randomRequestId() {
134
- const uuid = _optionalChain([g, 'access', _32 => _32.crypto, 'optionalAccess', _33 => _33.randomUUID, 'optionalCall', _34 => _34()]);
200
+ const uuid = _optionalChain([g, 'access', _34 => _34.crypto, 'optionalAccess', _35 => _35.randomUUID, 'optionalCall', _36 => _36()]);
135
201
  if (uuid) return uuid;
136
202
  let id = "";
137
203
  for (let i = 0; i < 32; i++) id += Math.floor(Math.random() * 16).toString(16);
@@ -162,16 +228,16 @@ function pollDelay(interval, elapsedMs, fallback) {
162
228
  }
163
229
  function sleep(ms, signal) {
164
230
  return new Promise((resolve, reject) => {
165
- if (_optionalChain([signal, 'optionalAccess', _35 => _35.aborted])) return reject(signal.reason);
231
+ if (_optionalChain([signal, 'optionalAccess', _37 => _37.aborted])) return reject(signal.reason);
166
232
  const timer = setTimeout(() => {
167
- _optionalChain([signal, 'optionalAccess', _36 => _36.removeEventListener, 'call', _37 => _37("abort", onAbort)]);
233
+ _optionalChain([signal, 'optionalAccess', _38 => _38.removeEventListener, 'call', _39 => _39("abort", onAbort)]);
168
234
  resolve();
169
235
  }, ms);
170
236
  const onAbort = () => {
171
237
  clearTimeout(timer);
172
238
  reject(signal.reason);
173
239
  };
174
- _optionalChain([signal, 'optionalAccess', _38 => _38.addEventListener, 'call', _39 => _39("abort", onAbort, { once: true })]);
240
+ _optionalChain([signal, 'optionalAccess', _40 => _40.addEventListener, 'call', _41 => _41("abort", onAbort, { once: true })]);
175
241
  });
176
242
  }
177
243
  var HttpClient = class {
@@ -201,11 +267,11 @@ var HttpClient = class {
201
267
  }
202
268
  if (response.status === 401 && !reauthenticated && await this.reauthenticate(req, token)) {
203
269
  reauthenticated = true;
204
- await _optionalChain([response, 'access', _40 => _40.body, 'optionalAccess', _41 => _41.cancel, 'call', _42 => _42(), 'access', _43 => _43.catch, 'call', _44 => _44(() => void 0)]);
270
+ await _optionalChain([response, 'access', _42 => _42.body, 'optionalAccess', _43 => _43.cancel, 'call', _44 => _44(), 'access', _45 => _45.catch, 'call', _46 => _46(() => void 0)]);
205
271
  continue;
206
272
  }
207
273
  if (canRetry && RETRYABLE_STATUS.has(response.status)) {
208
- await _optionalChain([response, 'access', _45 => _45.body, 'optionalAccess', _46 => _46.cancel, 'call', _47 => _47(), 'access', _48 => _48.catch, 'call', _49 => _49(() => void 0)]);
274
+ await _optionalChain([response, 'access', _47 => _47.body, 'optionalAccess', _48 => _48.cancel, 'call', _49 => _49(), 'access', _50 => _50.catch, 'call', _51 => _51(() => void 0)]);
209
275
  await sleep(retryDelay(attempt, response.headers.get("retry-after")), req.signal);
210
276
  attempt++;
211
277
  continue;
@@ -249,7 +315,7 @@ var HttpClient = class {
249
315
  }
250
316
  async attempt(req, token) {
251
317
  const { signal } = req;
252
- if (_optionalChain([signal, 'optionalAccess', _50 => _50.aborted])) throw signal.reason;
318
+ if (_optionalChain([signal, 'optionalAccess', _52 => _52.aborted])) throw signal.reason;
253
319
  const timeout = _nullishCoalesce(req.timeout, () => ( this.config.timeout));
254
320
  const controller = new AbortController();
255
321
  let timedOut = false;
@@ -258,7 +324,7 @@ var HttpClient = class {
258
324
  controller.abort();
259
325
  }, timeout);
260
326
  const onAbort = () => controller.abort(signal.reason);
261
- _optionalChain([signal, 'optionalAccess', _51 => _51.addEventListener, 'call', _52 => _52("abort", onAbort, { once: true })]);
327
+ _optionalChain([signal, 'optionalAccess', _53 => _53.addEventListener, 'call', _54 => _54("abort", onAbort, { once: true })]);
262
328
  const headers = req.bare ? { ...req.headers } : { ...this.config.headers, ...req.headers };
263
329
  if (this.config.apiKey && !req.bare) headers["x-api-key"] = this.config.apiKey;
264
330
  if (token) headers.Authorization = `Bearer ${token}`;
@@ -272,12 +338,12 @@ var HttpClient = class {
272
338
  signal: controller.signal
273
339
  });
274
340
  } catch (err) {
275
- if (_optionalChain([signal, 'optionalAccess', _53 => _53.aborted])) throw _nullishCoalesce(signal.reason, () => ( err));
341
+ if (_optionalChain([signal, 'optionalAccess', _55 => _55.aborted])) throw _nullishCoalesce(signal.reason, () => ( err));
276
342
  const reason = timedOut ? `request timed out after ${timeout} ms` : `connection error: ${describe(err)}`;
277
343
  throw new (0, _chunk74UKKBOOcjs.APIConnectionError)(`${req.method} ${req.url}: ${reason}`, { cause: err });
278
344
  } finally {
279
345
  clearTimeout(timer);
280
- _optionalChain([signal, 'optionalAccess', _54 => _54.removeEventListener, 'call', _55 => _55("abort", onAbort)]);
346
+ _optionalChain([signal, 'optionalAccess', _56 => _56.removeEventListener, 'call', _57 => _57("abort", onAbort)]);
281
347
  }
282
348
  }
283
349
  };
@@ -474,7 +540,7 @@ var Files = class {
474
540
  signal,
475
541
  retry: true
476
542
  });
477
- return _nullishCoalesce(_optionalChain([confirmed, 'access', _56 => _56.asset, 'optionalAccess', _57 => _57.url]), () => ( ticket.publicUrl));
543
+ return _nullishCoalesce(_optionalChain([confirmed, 'access', _58 => _58.asset, 'optionalAccess', _59 => _59.url]), () => ( ticket.publicUrl));
478
544
  }
479
545
  /**
480
546
  * A PUT to the same key is idempotent, so it retries; a `Blob` body can be
@@ -581,7 +647,7 @@ var Job = class {
581
647
  const started = Date.now();
582
648
  for (; ; ) {
583
649
  const status = await this.status({ signal: options.signal });
584
- _optionalChain([options, 'access', _58 => _58.onStatus, 'optionalCall', _59 => _59(status)]);
650
+ _optionalChain([options, 'access', _60 => _60.onStatus, 'optionalCall', _61 => _61(status)]);
585
651
  if (status.status === "COMPLETED") return this.result({ signal: options.signal });
586
652
  if (status.status === "FAILED") throw _chunk74UKKBOOcjs.requestFailure.call(void 0, this.requestId, status);
587
653
  const elapsed = Date.now() - started;
@@ -675,7 +741,7 @@ var PixelflowJob = class {
675
741
  const started = Date.now();
676
742
  for (; ; ) {
677
743
  const state = await this.status({ signal: options.signal });
678
- _optionalChain([options, 'access', _60 => _60.onStatus, 'optionalCall', _61 => _61(state)]);
744
+ _optionalChain([options, 'access', _62 => _62.onStatus, 'optionalCall', _63 => _63(state)]);
679
745
  if (DONE.has(state.status)) return state;
680
746
  if (FAILED.has(state.status)) throw _chunk74UKKBOOcjs.requestFailure.call(void 0, this.requestId, state.raw, failureDetail(state.raw));
681
747
  const elapsed = Date.now() - started;
@@ -758,7 +824,7 @@ var Realtime = class {
758
824
  };
759
825
 
760
826
  // src/version.ts
761
- var VERSION = "0.6.0";
827
+ var VERSION = "0.7.0";
762
828
 
763
829
  // src/webhooks.ts
764
830
  var Webhooks = class {
@@ -867,7 +933,7 @@ var Segmind = class {
867
933
  if (!apiKey && !options.tokenProvider) {
868
934
  throw new (0, _chunk74UKKBOOcjs.SegmindError)("Missing API key: pass { apiKey } or set the SEGMIND_API_KEY environment variable.");
869
935
  }
870
- const fetchImpl = _nullishCoalesce(options.fetch, () => ( _optionalChain([globalThis, 'access', _62 => _62.fetch, 'optionalAccess', _63 => _63.bind, 'call', _64 => _64(globalThis)])));
936
+ const fetchImpl = _nullishCoalesce(options.fetch, () => ( _optionalChain([globalThis, 'access', _64 => _64.fetch, 'optionalAccess', _65 => _65.bind, 'call', _66 => _66(globalThis)])));
871
937
  if (!fetchImpl) throw new (0, _chunk74UKKBOOcjs.SegmindError)("No fetch implementation available: pass { fetch }.");
872
938
  this.baseURL = trimBase(_nullishCoalesce(_nullishCoalesce(options.baseURL, () => ( readEnv("SEGMIND_BASE_URL"))), () => ( DEFAULT_BASE_URL)));
873
939
  this.spotURL = trimSlash(_nullishCoalesce(options.spotURL, () => ( DEFAULT_SPOT_URL)));
@@ -959,6 +1025,24 @@ var Segmind = class {
959
1025
  async submitChat(slug, params, options = {}) {
960
1026
  return this.submitJob(slug, chatBody(params), options, chatFromRunResult);
961
1027
  }
1028
+ /**
1029
+ * Ask a decision model typed questions through the v2 queue. Pass `state`
1030
+ * and `questions` (see `question` for the builders); the reply carries
1031
+ * probabilities, the amount charged and the model's latency.
1032
+ */
1033
+ async decide(slug, params, options = {}) {
1034
+ const job2 = await this.submitDecision(slug, params, options);
1035
+ return job2.wait(options);
1036
+ }
1037
+ /** Ask a decision model with one blocking `POST /v1/{slug}`, which suits a model that answers in about a second. */
1038
+ async decideSync(slug, params, options = {}) {
1039
+ const response = await this.runSync(slug, decisionBody(params), options);
1040
+ return new DecisionResponse(await readJson(response));
1041
+ }
1042
+ /** Submits a decision to the v2 queue and returns a `Job` whose result is a `DecisionResponse`. */
1043
+ async submitDecision(slug, params, options = {}) {
1044
+ return this.submitJob(slug, decisionBody(params), options, decisionFromRunResult);
1045
+ }
962
1046
  async submitJob(slug, params, options, transform) {
963
1047
  const url = `${this.baseURL}/v2/${path(slug)}`;
964
1048
  const maxRetries = this.http.config.maxRetries;
@@ -993,13 +1077,13 @@ var Segmind = class {
993
1077
  return new Job(this.http, onBase(validateSubmit(body, response.status), this.baseURL), transform);
994
1078
  }
995
1079
  if (canRetry && response.status === 503) {
996
- await _optionalChain([response, 'access', _65 => _65.body, 'optionalAccess', _66 => _66.cancel, 'call', _67 => _67(), 'access', _68 => _68.catch, 'call', _69 => _69(() => void 0)]);
1080
+ await _optionalChain([response, 'access', _67 => _67.body, 'optionalAccess', _68 => _68.cancel, 'call', _69 => _69(), 'access', _70 => _70.catch, 'call', _71 => _71(() => void 0)]);
997
1081
  requestId = randomRequestId();
998
1082
  await sleep(retryDelay(attempt, response.headers.get("retry-after")), options.signal);
999
1083
  continue;
1000
1084
  }
1001
1085
  if (canRetry && (response.status === 429 || response.status === 502 || response.status === 504)) {
1002
- await _optionalChain([response, 'access', _70 => _70.body, 'optionalAccess', _71 => _71.cancel, 'call', _72 => _72(), 'access', _73 => _73.catch, 'call', _74 => _74(() => void 0)]);
1086
+ await _optionalChain([response, 'access', _72 => _72.body, 'optionalAccess', _73 => _73.cancel, 'call', _74 => _74(), 'access', _75 => _75.catch, 'call', _76 => _76(() => void 0)]);
1003
1087
  await sleep(retryDelay(attempt, response.headers.get("retry-after")), options.signal);
1004
1088
  continue;
1005
1089
  }
@@ -1139,6 +1223,9 @@ var job = (requestId) => client().job(requestId);
1139
1223
  var chat = (slug, params, options) => client().chat(slug, params, options);
1140
1224
  var chatSync = (slug, params, options) => client().chatSync(slug, params, options);
1141
1225
  var submitChat = (slug, params, options) => client().submitChat(slug, params, options);
1226
+ var decide = (slug, params, options) => client().decide(slug, params, options);
1227
+ var decideSync = (slug, params, options) => client().decideSync(slug, params, options);
1228
+ var submitDecision = (slug, params, options) => client().submitDecision(slug, params, options);
1142
1229
  var models = {
1143
1230
  list: (params, options) => client().models.list(params, options),
1144
1231
  listAll: (params, options) => client().models.listAll(params, options)
@@ -1209,5 +1296,9 @@ var pixelflows = {
1209
1296
 
1210
1297
 
1211
1298
 
1212
- exports.APIConnectionError = _chunk74UKKBOOcjs.APIConnectionError; exports.Accounts = Accounts; exports.ChatResponse = ChatResponse; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_CONSOLE_URL = DEFAULT_CONSOLE_URL; exports.DEFAULT_SPOT_URL = DEFAULT_SPOT_URL; exports.DEFAULT_WAIT_INTERVAL_MS = DEFAULT_WAIT_INTERVAL_MS; exports.DEFAULT_WAIT_TIMEOUT_MS = DEFAULT_WAIT_TIMEOUT_MS; exports.Files = Files; exports.Generations = Generations; exports.InferenceFailed = _chunk74UKKBOOcjs.InferenceFailed; exports.InferenceTimeout = _chunk74UKKBOOcjs.InferenceTimeout; exports.InsufficientCredits = _chunk74UKKBOOcjs.InsufficientCredits; exports.Job = Job; exports.Models = Models; exports.PixelFlows = PixelFlows; exports.PixelflowJob = PixelflowJob; exports.RateLimited = _chunk74UKKBOOcjs.RateLimited; exports.Realtime = Realtime; exports.Segmind = Segmind; exports.SegmindError = _chunk74UKKBOOcjs.SegmindError; exports.VERSION = VERSION; exports.Webhooks = Webhooks; exports.accounts = accounts; exports.chat = chat; exports.chatSync = chatSync; exports.files = files; exports.generations = generations; exports.imageUrl = imageUrl; exports.job = job; exports.models = models; exports.pixelflows = pixelflows; exports.run = run; exports.runSync = runSync; exports.submit = submit; exports.submitChat = submitChat; exports.webhooks = webhooks;
1299
+
1300
+
1301
+
1302
+
1303
+ exports.APIConnectionError = _chunk74UKKBOOcjs.APIConnectionError; exports.Accounts = Accounts; exports.ChatResponse = ChatResponse; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_CONSOLE_URL = DEFAULT_CONSOLE_URL; exports.DEFAULT_SPOT_URL = DEFAULT_SPOT_URL; exports.DEFAULT_WAIT_INTERVAL_MS = DEFAULT_WAIT_INTERVAL_MS; exports.DEFAULT_WAIT_TIMEOUT_MS = DEFAULT_WAIT_TIMEOUT_MS; exports.DecisionResponse = DecisionResponse; exports.Files = Files; exports.Generations = Generations; exports.InferenceFailed = _chunk74UKKBOOcjs.InferenceFailed; exports.InferenceTimeout = _chunk74UKKBOOcjs.InferenceTimeout; exports.InsufficientCredits = _chunk74UKKBOOcjs.InsufficientCredits; exports.Job = Job; exports.Models = Models; exports.PixelFlows = PixelFlows; exports.PixelflowJob = PixelflowJob; exports.RateLimited = _chunk74UKKBOOcjs.RateLimited; exports.Realtime = Realtime; exports.Segmind = Segmind; exports.SegmindError = _chunk74UKKBOOcjs.SegmindError; exports.VERSION = VERSION; exports.Webhooks = Webhooks; exports.accounts = accounts; exports.chat = chat; exports.chatSync = chatSync; exports.decide = decide; exports.decideSync = decideSync; exports.files = files; exports.generations = generations; exports.imageUrl = imageUrl; exports.job = job; exports.models = models; exports.pixelflows = pixelflows; exports.run = run; exports.runSync = runSync; exports.submit = submit; exports.submitChat = submitChat; exports.submitDecision = submitDecision; exports.webhooks = webhooks;
1213
1304
  //# sourceMappingURL=index.cjs.map