@superlinked/sie-sdk 0.6.20 → 0.6.22

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