@superlinked/sie-sdk 0.6.20 → 0.6.21

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.js CHANGED
@@ -590,7 +590,11 @@ function parseScoreResult(data) {
590
590
  return {
591
591
  model: wire.model,
592
592
  queryId: wire.query_id,
593
- scores: wire.scores.map(parseScoreEntry)
593
+ scores: wire.scores.map(parseScoreEntry),
594
+ usage: wire.usage ? {
595
+ inputTokens: wire.usage.input_tokens,
596
+ images: wire.usage.images
597
+ } : void 0
594
598
  };
595
599
  }
596
600
  function parseEntity(data) {
@@ -603,6 +607,19 @@ function parseEntity(data) {
603
607
  bbox: data.bbox
604
608
  };
605
609
  }
610
+ function parseExtractItemError(data) {
611
+ if (data === void 0 || data === null) return void 0;
612
+ if (typeof data === "object" && !Array.isArray(data)) {
613
+ const error = data;
614
+ if (typeof error.code === "string" && error.code.trim().length > 0 && typeof error.message === "string" && error.message.trim().length > 0) {
615
+ return { code: error.code, message: error.message };
616
+ }
617
+ }
618
+ return {
619
+ code: "INTERNAL_ERROR",
620
+ message: "Malformed extraction item error"
621
+ };
622
+ }
606
623
  function parseExtractResult(data) {
607
624
  return {
608
625
  id: data.id,
@@ -627,7 +644,9 @@ function parseExtractResult(data) {
627
644
  score: o.score,
628
645
  bbox: o.bbox
629
646
  })
630
- )
647
+ ),
648
+ data: data.data,
649
+ error: parseExtractItemError(data.error)
631
650
  };
632
651
  }
633
652
  function parseExtractResults(data) {
@@ -1170,12 +1189,75 @@ function extractDataPayload(block) {
1170
1189
  }
1171
1190
 
1172
1191
  // src/version.ts
1173
- var SDK_VERSION = "0.6.20";
1192
+ var SDK_VERSION = "0.6.21";
1174
1193
 
1175
1194
  // src/client.ts
1176
1195
  function sleep2(ms) {
1177
1196
  return new Promise((resolve) => setTimeout(resolve, ms));
1178
1197
  }
1198
+ function parseNonnegativeMeterHeader(headers, name) {
1199
+ const raw = headers.get(name);
1200
+ if (raw === null || !/^(0|[1-9]\d*)$/.test(raw)) return void 0;
1201
+ const parsed = Number(raw);
1202
+ return Number.isSafeInteger(parsed) ? parsed : void 0;
1203
+ }
1204
+ function parseRequestMetadata(headers) {
1205
+ const metadata = {};
1206
+ const requestId = headers.get("x-sie-request-id");
1207
+ if (requestId !== null && requestId.length > 0 && requestId.length <= 256 && requestId === requestId.trim() && /^[\x20-\x7e]+$/.test(requestId)) {
1208
+ metadata.id = requestId;
1209
+ }
1210
+ const executionIdentitySha256 = headers.get("x-sie-execution-identity-sha256");
1211
+ if (executionIdentitySha256 !== null && /^[0-9a-f]{64}$/.test(executionIdentitySha256)) {
1212
+ metadata.executionIdentitySha256 = executionIdentitySha256;
1213
+ }
1214
+ const usageHeaders = {
1215
+ inputTokens: "x-sie-units-input-tokens",
1216
+ pairs: "x-sie-units-pairs",
1217
+ images: "x-sie-units-images",
1218
+ pages: "x-sie-units-pages",
1219
+ outputTokens: "x-sie-units-output-tokens",
1220
+ audioMs: "x-sie-units-audio-ms"
1221
+ };
1222
+ const usage = {};
1223
+ for (const [field, header] of Object.entries(usageHeaders)) {
1224
+ const value = parseNonnegativeMeterHeader(headers, header);
1225
+ if (value !== void 0) usage[field] = value;
1226
+ }
1227
+ if (Object.keys(usage).length > 0) metadata.usage = usage;
1228
+ const creditsDebited = parseNonnegativeMeterHeader(headers, "x-sie-credits-debited");
1229
+ if (creditsDebited !== void 0) metadata.creditsDebited = creditsDebited;
1230
+ return Object.keys(metadata).length > 0 ? metadata : void 0;
1231
+ }
1232
+ function attachRequestMetadata(results, headers) {
1233
+ const metadata = parseRequestMetadata(headers);
1234
+ if (metadata === void 0) return;
1235
+ for (const result of results) {
1236
+ result.request = { ...metadata };
1237
+ if (metadata.usage !== void 0) result.request.usage = { ...metadata.usage };
1238
+ }
1239
+ }
1240
+ function validateGenerationSeed(seed) {
1241
+ if (!Number.isSafeInteger(seed)) {
1242
+ throw new RangeError("seed must be a JavaScript safe integer");
1243
+ }
1244
+ return seed;
1245
+ }
1246
+ function applyGenerateOptions(body, options) {
1247
+ if (options.temperature !== void 0) body.temperature = options.temperature;
1248
+ if (options.topP !== void 0) body.top_p = options.topP;
1249
+ if (options.adapterOptions !== void 0) body.options = options.adapterOptions;
1250
+ if (options.stop !== void 0) body.stop = options.stop;
1251
+ if (options.frequencyPenalty !== void 0) body.frequency_penalty = options.frequencyPenalty;
1252
+ if (options.presencePenalty !== void 0) body.presence_penalty = options.presencePenalty;
1253
+ if (options.grammar !== void 0) body.grammar = options.grammar;
1254
+ if (options.seed !== void 0) body.seed = validateGenerationSeed(options.seed);
1255
+ if (options.logitBias !== void 0) body.logit_bias = options.logitBias;
1256
+ if (options.routingKey !== void 0) body.routing_key = options.routingKey;
1257
+ if (options.promptCacheKey !== void 0) body.prompt_cache_key = options.promptCacheKey;
1258
+ if (options.safetyIdentifier !== void 0) body.safety_identifier = options.safetyIdentifier;
1259
+ if (options.loraAdapter !== void 0) body.lora_adapter = options.loraAdapter;
1260
+ }
1179
1261
  function resolveUploadFilename(file, filename) {
1180
1262
  if (filename) return filename;
1181
1263
  const name = file.name;
@@ -1217,6 +1299,32 @@ async function itemImagesForWire(item) {
1217
1299
  async function itemsImagesForWire(items) {
1218
1300
  return Promise.all(items.map(itemImagesForWire));
1219
1301
  }
1302
+ async function extractItemForWire(item) {
1303
+ const { images, audio, ...wireItem } = item;
1304
+ const wireImages = images ? await Promise.all(images.map(imageForWire)) : void 0;
1305
+ if (!audio) {
1306
+ return { ...wireItem, ...wireImages === void 0 ? {} : { images: wireImages } };
1307
+ }
1308
+ if (audio instanceof Uint8Array) {
1309
+ return {
1310
+ ...wireItem,
1311
+ ...wireImages === void 0 ? {} : { images: wireImages },
1312
+ audio: { data: audio }
1313
+ };
1314
+ }
1315
+ const { sampleRate, ...wireAudio } = audio;
1316
+ return {
1317
+ ...wireItem,
1318
+ ...wireImages === void 0 ? {} : { images: wireImages },
1319
+ audio: {
1320
+ ...wireAudio,
1321
+ ...sampleRate === void 0 ? {} : { sample_rate: sampleRate }
1322
+ }
1323
+ };
1324
+ }
1325
+ async function itemsForExtractWire(items) {
1326
+ return Promise.all(items.map(extractItemForWire));
1327
+ }
1220
1328
  function extractChatChunkError(chunk) {
1221
1329
  const err = chunk.error;
1222
1330
  if (!err) return null;
@@ -1341,6 +1449,7 @@ var SIEClient = class {
1341
1449
  );
1342
1450
  const data = unpackMessage(new Uint8Array(await response.arrayBuffer()));
1343
1451
  const results = parseEncodeResults(data.items);
1452
+ attachRequestMetadata(results, response.headers);
1344
1453
  if (isSingleItem) {
1345
1454
  const first = results[0];
1346
1455
  if (!first) {
@@ -1510,13 +1619,9 @@ var SIEClient = class {
1510
1619
  async generate(model, prompt, options) {
1511
1620
  const body = {
1512
1621
  prompt,
1513
- max_new_tokens: options.maxNewTokens,
1514
- temperature: options.temperature ?? 1,
1515
- top_p: options.topP ?? 1
1622
+ max_new_tokens: options.maxNewTokens
1516
1623
  };
1517
- if (options.stop !== void 0) {
1518
- body.stop = options.stop;
1519
- }
1624
+ applyGenerateOptions(body, options);
1520
1625
  const { pool, gpu } = this.parseGpuParam(options.gpu);
1521
1626
  const headers = {
1522
1627
  Accept: "application/json",
@@ -1539,7 +1644,9 @@ var SIEClient = class {
1539
1644
  if (data === null || typeof data !== "object") {
1540
1645
  throw new RequestError("Unexpected generate response shape");
1541
1646
  }
1542
- return parseGenerateResult(data);
1647
+ const result = parseGenerateResult(data);
1648
+ attachRequestMetadata([result], response.headers);
1649
+ return result;
1543
1650
  }
1544
1651
  /**
1545
1652
  * Per-attempt JSON POST used by the non-streaming surfaces
@@ -1617,6 +1724,9 @@ var SIEClient = class {
1617
1724
  400
1618
1725
  );
1619
1726
  }
1727
+ if (req.seed !== void 0) {
1728
+ validateGenerationSeed(req.seed);
1729
+ }
1620
1730
  const body = { ...req, stream: false };
1621
1731
  const url = `${this.baseUrl}/v1/chat/completions`;
1622
1732
  const headers = this.buildChatHeaders("application/json");
@@ -1633,6 +1743,7 @@ var SIEClient = class {
1633
1743
  if (data === null || typeof data !== "object") {
1634
1744
  throw new RequestError("Unexpected chat.completion response shape");
1635
1745
  }
1746
+ attachRequestMetadata([data], response.headers);
1636
1747
  return data;
1637
1748
  }
1638
1749
  /**
@@ -1684,6 +1795,9 @@ var SIEClient = class {
1684
1795
  * ```
1685
1796
  */
1686
1797
  async *streamChatCompletions(req, signal) {
1798
+ if (req.seed !== void 0) {
1799
+ validateGenerationSeed(req.seed);
1800
+ }
1687
1801
  const body = { ...req, stream: true };
1688
1802
  const url = `${this.baseUrl}/v1/chat/completions`;
1689
1803
  yield* this.consumeSseStream(
@@ -1700,10 +1814,10 @@ var SIEClient = class {
1700
1814
  * chunk shape documented in
1701
1815
  * `packages/sie_gateway/src/handlers/sse.rs::build_generate_chunk_event`.
1702
1816
  *
1703
- * The first delta carries `seq: 0` and `text_delta` populated; the
1704
- * terminal chunk has `done: true`, `finish_reason`, and (typically)
1705
- * `usage` + `ttft_ms`. The generator completes on the `data: [DONE]`
1706
- * sentinel.
1817
+ * Delta chunks may carry text, log probabilities, or both; callers must not
1818
+ * assume every non-terminal event has a non-empty `text_delta`. The terminal
1819
+ * chunk has `done: true`, `finish_reason`, and (typically) `usage` +
1820
+ * `ttft_ms`. The generator completes on the `data: [DONE]` sentinel.
1707
1821
  *
1708
1822
  * Error semantics match {@link streamChatCompletions}: pre-stream HTTP
1709
1823
  * errors throw normally, mid-stream `error` chunks throw
@@ -1725,11 +1839,14 @@ var SIEClient = class {
1725
1839
  const body = {
1726
1840
  prompt,
1727
1841
  max_new_tokens: options.maxNewTokens,
1728
- temperature: options.temperature ?? 1,
1729
- top_p: options.topP ?? 1,
1730
1842
  stream: true
1731
1843
  };
1732
- if (options.stop !== void 0) body.stop = options.stop;
1844
+ applyGenerateOptions(body, options);
1845
+ if (options.logprobs !== void 0) body.logprobs = options.logprobs;
1846
+ if (options.topLogprobs !== void 0) {
1847
+ body.top_logprobs = options.topLogprobs;
1848
+ body.logprobs = true;
1849
+ }
1733
1850
  const safeModel = model.replaceAll("/", "__");
1734
1851
  const url = `${this.baseUrl}/v1/generate/${encodeURIComponent(safeModel)}`;
1735
1852
  const { pool, gpu } = this.parseGpuParam(options.gpu);
@@ -1946,7 +2063,9 @@ var SIEClient = class {
1946
2063
  model
1947
2064
  );
1948
2065
  const data = unpackMessage(new Uint8Array(await response.arrayBuffer()));
1949
- return parseScoreResult(data);
2066
+ const result = parseScoreResult(data);
2067
+ attachRequestMetadata([result], response.headers);
2068
+ return result;
1950
2069
  }
1951
2070
  /**
1952
2071
  * Extract entities from one or more items.
@@ -1970,7 +2089,7 @@ var SIEClient = class {
1970
2089
  async extract(model, items, options) {
1971
2090
  const isSingleItem = !Array.isArray(items);
1972
2091
  const itemsArray = isSingleItem ? [items] : items;
1973
- const itemsForWire = await itemsImagesForWire(itemsArray);
2092
+ const itemsForWire = await itemsForExtractWire(itemsArray);
1974
2093
  const body = {
1975
2094
  items: itemsForWire
1976
2095
  };
@@ -1996,6 +2115,7 @@ var SIEClient = class {
1996
2115
  );
1997
2116
  const data = unpackMessage(new Uint8Array(await response.arrayBuffer()));
1998
2117
  const results = parseExtractResults(data.items);
2118
+ attachRequestMetadata(results, response.headers);
1999
2119
  if (isSingleItem) {
2000
2120
  const first = results[0];
2001
2121
  if (!first) {