@nemesis-oss/ollama-sdk 1.15.0 → 1.17.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
@@ -393,6 +393,36 @@ var OllamaGenericClientError = class extends OllamaClientError {
393
393
  function isDomAbortError(error) {
394
394
  return typeof DOMException !== "undefined" && error instanceof DOMException && error.name === "AbortError";
395
395
  }
396
+ var NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
397
+ "ECONNRESET",
398
+ "ECONNREFUSED",
399
+ "EPIPE",
400
+ "ETIMEDOUT",
401
+ "ECONNABORTED",
402
+ "EHOSTUNREACH",
403
+ "ENETUNREACH",
404
+ "ENOTFOUND",
405
+ "EAI_AGAIN",
406
+ "UND_ERR_SOCKET",
407
+ "UND_ERR_CONNECT_TIMEOUT",
408
+ "UND_ERR_HEADERS_TIMEOUT",
409
+ "UND_ERR_BODY_TIMEOUT",
410
+ "UND_ERR_CLOSED"
411
+ ]);
412
+ var MAX_CAUSE_DEPTH = 4;
413
+ function isNetworkLevelError(error) {
414
+ let current = error;
415
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && current !== void 0 && current !== null; depth += 1) {
416
+ if (typeof current === "object" && "code" in current) {
417
+ const code = current.code;
418
+ if (typeof code === "string" && NETWORK_ERROR_CODES.has(code)) {
419
+ return true;
420
+ }
421
+ }
422
+ current = current.cause;
423
+ }
424
+ return false;
425
+ }
396
426
  function statusToError(status, message, options) {
397
427
  if (status === 401 || status === 403) {
398
428
  return new OllamaAuthError(message, { ...options, status });
@@ -424,6 +454,13 @@ function mapError(error, context = {}) {
424
454
  request: context.request
425
455
  });
426
456
  }
457
+ if (isNetworkLevelError(error)) {
458
+ const message2 = error instanceof Error && error.message ? error.message : "Network request failed";
459
+ return new OllamaNetworkError(message2, {
460
+ cause: error,
461
+ request: context.request
462
+ });
463
+ }
427
464
  if (error instanceof TypeError) {
428
465
  return new OllamaNetworkError(error.message || "Network request failed", {
429
466
  cause: error,
@@ -1076,6 +1113,18 @@ function createRequestId() {
1076
1113
  requestSequence += 1;
1077
1114
  return `ollama-http-${requestSequence}`;
1078
1115
  }
1116
+ function isWebReadableStreamBody(body) {
1117
+ return typeof body === "object" && body !== null && typeof body.getReader === "function";
1118
+ }
1119
+ function buildFetchInit(req) {
1120
+ return {
1121
+ method: req.method,
1122
+ headers: req.headers,
1123
+ ...req.body !== void 0 ? { body: req.body } : {},
1124
+ ...req.signal !== void 0 ? { signal: req.signal } : {},
1125
+ ...isWebReadableStreamBody(req.body) ? { duplex: "half" } : {}
1126
+ };
1127
+ }
1079
1128
  function sameHeaders(actual, expected) {
1080
1129
  const actualEntries = Object.fromEntries(
1081
1130
  Object.entries(actual).map(([key, value]) => [key.toLowerCase(), value])
@@ -1125,13 +1174,7 @@ var HttpClient = class {
1125
1174
  timestamp: startedAt
1126
1175
  });
1127
1176
  const finalHandler = async (req) => {
1128
- const init = {
1129
- method: req.method,
1130
- headers: req.headers,
1131
- ...req.body !== void 0 ? { body: req.body } : {},
1132
- ...req.signal !== void 0 ? { signal: req.signal } : {}
1133
- };
1134
- const response = await this.fetchImpl(req.url, init);
1177
+ const response = await this.fetchImpl(req.url, buildFetchInit(req));
1135
1178
  rawResponse = response;
1136
1179
  const responseHeaders = response.headers && typeof response.headers.entries === "function" ? Object.fromEntries(response.headers.entries()) : {};
1137
1180
  return {
@@ -1142,12 +1185,7 @@ var HttpClient = class {
1142
1185
  };
1143
1186
  try {
1144
1187
  if (this.middleware.length === 0) {
1145
- const response2 = await this.fetchImpl(request.url, {
1146
- method: request.method,
1147
- headers: request.headers,
1148
- ...request.body !== void 0 ? { body: request.body } : {},
1149
- ...request.signal !== void 0 ? { signal: request.signal } : {}
1150
- });
1188
+ const response2 = await this.fetchImpl(request.url, buildFetchInit(request));
1151
1189
  if (response2.status >= 200 && response2.status < 300) {
1152
1190
  this.onLifecycleEvent?.({
1153
1191
  type: "success",
@@ -1649,6 +1687,13 @@ function estimateGenerateRequestTokens(req) {
1649
1687
  if (req.images !== void 0) total += req.images.length * IMAGE_TOKEN_ESTIMATE;
1650
1688
  return total;
1651
1689
  }
1690
+ function recommendContextWindow(estimatedTokens) {
1691
+ if (!Number.isFinite(estimatedTokens) || estimatedTokens <= 0) return 4096;
1692
+ const target = estimatedTokens * 1.3;
1693
+ let window = 4096;
1694
+ while (window < target) window *= 2;
1695
+ return window;
1696
+ }
1652
1697
  function checkChatContext(req, options = {}) {
1653
1698
  return check(estimateChatRequestTokens(req), req.options?.num_ctx, options);
1654
1699
  }
@@ -1658,39 +1703,46 @@ function checkGenerateContext(req, options = {}) {
1658
1703
  function check(estimatedPromptTokens, requestNumCtx, options) {
1659
1704
  const threshold = options.threshold ?? DEFAULT_CONTEXT_WARNING_THRESHOLD;
1660
1705
  if (requestNumCtx !== void 0) {
1706
+ const exceeds2 = estimatedPromptTokens > requestNumCtx * threshold;
1661
1707
  return {
1662
1708
  estimatedPromptTokens,
1663
1709
  effectiveContextLength: requestNumCtx,
1664
1710
  windowSource: "request",
1665
- exceedsThreshold: estimatedPromptTokens > requestNumCtx * threshold
1711
+ exceedsThreshold: exceeds2,
1712
+ ...exceeds2 ? { recommendedNumCtx: recommendContextWindow(estimatedPromptTokens) } : {}
1666
1713
  };
1667
1714
  }
1668
1715
  if (options.defaultContextLength !== void 0) {
1716
+ const exceeds2 = estimatedPromptTokens > options.defaultContextLength * threshold;
1669
1717
  return {
1670
1718
  estimatedPromptTokens,
1671
1719
  effectiveContextLength: options.defaultContextLength,
1672
1720
  windowSource: "client-default",
1673
- exceedsThreshold: estimatedPromptTokens > options.defaultContextLength * threshold
1721
+ exceedsThreshold: exceeds2,
1722
+ ...exceeds2 ? { recommendedNumCtx: recommendContextWindow(estimatedPromptTokens) } : {}
1674
1723
  };
1675
1724
  }
1725
+ const exceeds = estimatedPromptTokens > OLLAMA_FALLBACK_CONTEXT_LENGTH;
1676
1726
  return {
1677
1727
  estimatedPromptTokens,
1678
1728
  effectiveContextLength: OLLAMA_FALLBACK_CONTEXT_LENGTH,
1679
1729
  windowSource: "server-fallback",
1680
- exceedsThreshold: estimatedPromptTokens > OLLAMA_FALLBACK_CONTEXT_LENGTH
1730
+ exceedsThreshold: exceeds,
1731
+ ...exceeds ? { recommendedNumCtx: recommendContextWindow(estimatedPromptTokens) } : {}
1681
1732
  };
1682
1733
  }
1683
1734
  var OLLAMA_FALLBACK_CONTEXT_LENGTH = 2048;
1684
1735
  function contextWarningMessage(check2, kind) {
1685
1736
  const where = `OllamaClient.${kind}()`;
1686
1737
  const estimate = `~${check2.estimatedPromptTokens} tokens`;
1738
+ const suggestion = check2.recommendedNumCtx !== void 0 ? ` A window of at least ${check2.recommendedNumCtx} tokens would fit this prompt with ~30% headroom (see \`recommendContextWindow\`) \u2014 verify the model's native maximum via \`client.models.getContextLength()\` before adopting it.` : "";
1687
1739
  if (check2.windowSource === "request") {
1688
- return `${where}: estimated prompt size ${estimate} is close to or beyond the request's context window (num_ctx=${check2.effectiveContextLength}). The server will likely silently truncate the top of the conversation \u2014 the model loses earlier turns with no error. Raise \`options.num_ctx\` or shorten the conversation. Estimates are heuristic (\xB120\u201330%); see \`estimateTokens\`.`;
1740
+ return `${where}: estimated prompt size ${estimate} is close to or beyond the request's context window (num_ctx=${check2.effectiveContextLength}). The server will likely silently truncate the top of the conversation \u2014 the model loses earlier turns with no error. Raise \`options.num_ctx\` or shorten the conversation.${suggestion} Estimates are heuristic (\xB120\u201330%); see \`estimateTokens\`.`;
1689
1741
  }
1690
1742
  if (check2.windowSource === "client-default") {
1691
- return `${where}: estimated prompt size ${estimate} is close to or beyond the client's \`defaultContextLength\` (${check2.effectiveContextLength}, injected as \`num_ctx\`). The server will likely silently truncate the top of the conversation \u2014 the model loses earlier turns with no error. Raise \`defaultContextLength\`, set \`options.num_ctx\` per request, or shorten the conversation. Estimates are heuristic (\xB120\u201330%); see \`estimateTokens\`.`;
1743
+ return `${where}: estimated prompt size ${estimate} is close to or beyond the client's \`defaultContextLength\` (${check2.effectiveContextLength}, injected as \`num_ctx\`). The server will likely silently truncate the top of the conversation \u2014 the model loses earlier turns with no error. Raise \`defaultContextLength\`, set \`options.num_ctx\` per request, or shorten the conversation.${suggestion} Estimates are heuristic (\xB120\u201330%); see \`estimateTokens\`.`;
1692
1744
  }
1693
- return `${where}: estimated prompt size ${estimate} outright exceeds Ollama's conservative server-default context window (${OLLAMA_FALLBACK_CONTEXT_LENGTH}\u20134096 tokens when \`num_ctx\` is unset \u2014 model-dependent). Unless the model's default is larger, the server will silently truncate the top of the conversation \u2014 the model loses earlier turns with no error. Set \`options.num_ctx\` (or the client's \`defaultContextLength\`) to an explicit window to make truncation visible and controllable. Estimates are heuristic (\xB120\u201330%); see \`estimateTokens\`.`;
1745
+ return `${where}: estimated prompt size ${estimate} outright exceeds Ollama's conservative server-default context window (${OLLAMA_FALLBACK_CONTEXT_LENGTH}\u20134096 tokens when \`num_ctx\` is unset \u2014 model-dependent). Unless the model's default is larger, the server will silently truncate the top of the conversation \u2014 the model loses earlier turns with no error. Set \`options.num_ctx\` (or the client's \`defaultContextLength\`) to an explicit window to make truncation visible and controllable.${suggestion} Estimates are heuristic (\xB120\u201330%); see \`estimateTokens\`.`;
1694
1746
  }
1695
1747
 
1696
1748
  // src/context-discovery.ts
@@ -2724,7 +2776,7 @@ var ModelsClient = class {
2724
2776
  { model, singleEndpoint: true }
2725
2777
  );
2726
2778
  }
2727
- async createBlob(digest, data) {
2779
+ async createBlob(digest, data, request) {
2728
2780
  await this.runner(
2729
2781
  (http, signal) => http.request({
2730
2782
  path: `/api/blobs/${encodeURIComponent(digest)}`,
@@ -2732,10 +2784,10 @@ var ModelsClient = class {
2732
2784
  rawBody: data,
2733
2785
  signal
2734
2786
  }),
2735
- { singleEndpoint: true }
2787
+ { ...request, singleEndpoint: true }
2736
2788
  );
2737
2789
  }
2738
- async checkBlob(digest) {
2790
+ async checkBlob(digest, request) {
2739
2791
  try {
2740
2792
  await this.runner(
2741
2793
  (http, signal) => http.request({
@@ -2743,7 +2795,7 @@ var ModelsClient = class {
2743
2795
  method: "HEAD",
2744
2796
  signal
2745
2797
  }),
2746
- { singleEndpoint: true }
2798
+ { ...request, singleEndpoint: true }
2747
2799
  );
2748
2800
  return true;
2749
2801
  } catch (err) {
@@ -2785,9 +2837,32 @@ var ModelsClient = class {
2785
2837
  */
2786
2838
  async createBlobFromData(data, opts) {
2787
2839
  const digest = opts?.digest ?? await this.computeBlobDigest(data);
2788
- const alreadyExisted = await this.checkBlob(digest);
2840
+ const alreadyExisted = await this.checkBlob(digest, opts);
2841
+ if (!alreadyExisted) {
2842
+ await this.createBlob(digest, data, opts);
2843
+ }
2844
+ return { digest, alreadyExisted };
2845
+ }
2846
+ /**
2847
+ * Streams a blob upload straight from a web `ReadableStream` — the
2848
+ * multi-gigabyte-safe counterpart of {@link createBlobFromData}. The body
2849
+ * is never materialized in memory: the transport hands the stream to
2850
+ * `fetch` directly (setting `duplex: 'half'`, which Node 18+ requires for
2851
+ * stream bodies), so peak heap usage is a transport-level chunk, not the
2852
+ * blob size.
2853
+ *
2854
+ * The digest must be known up front — it *is* the upload URL
2855
+ * (`/api/blobs/<digest>`), the same content-addressed protocol
2856
+ * `curl -T` performs. Hash first when you don't have it: in-memory bytes
2857
+ * via {@link computeBlobDigest}, files via {@link createBlobFromFile}
2858
+ * (which hashes in a streaming pass). The server verifies the streamed
2859
+ * bytes against the digest and rejects mismatches, so a corrupted or
2860
+ * truncated stream fails the upload instead of poisoning the store.
2861
+ */
2862
+ async createBlobFromStream(digest, stream, request) {
2863
+ const alreadyExisted = await this.checkBlob(digest, request);
2789
2864
  if (!alreadyExisted) {
2790
- await this.createBlob(digest, data);
2865
+ await this.createBlob(digest, stream, request);
2791
2866
  }
2792
2867
  return { digest, alreadyExisted };
2793
2868
  }
@@ -2796,16 +2871,61 @@ var ModelsClient = class {
2796
2871
  * `node:fs` import, so browser bundles never pull it in). The file name
2797
2872
  * (basename) is what `/api/create`'s `files` map expects as the key, so
2798
2873
  * this returns it alongside the digest.
2874
+ *
2875
+ * Streams both passes in fixed-size chunks — peak heap is O(chunk), not
2876
+ * O(file), so multi-gigabyte GGUFs never enter the Node heap:
2877
+ *
2878
+ * 1. **Hash pass** (skipped when `opts.digest` is provided): the file is
2879
+ * streamed through `node:crypto`'s incremental SHA-256.
2880
+ * 2. **Upload pass**: `node:fs` createReadStream → web ReadableStream →
2881
+ * `fetch` body with `duplex: 'half'` (see {@link createBlobFromStream}).
2882
+ *
2883
+ * A pre-existing blob (HEAD 200) skips the upload pass entirely, same as
2884
+ * {@link createBlobFromData}.
2799
2885
  */
2800
2886
  async createBlobFromFile(path, opts) {
2801
2887
  const nodeFsModule = "node:fs";
2802
- const { promises: fs } = await import(nodeFsModule);
2803
- const data = await fs.readFile(path);
2804
- const result = await this.createBlobFromData(new Uint8Array(data), {
2805
- ...opts
2806
- });
2888
+ const { createReadStream } = await import(nodeFsModule);
2889
+ const nodeCryptoModule = "node:crypto";
2890
+ const { createHash } = await import(nodeCryptoModule);
2891
+ const nodeStreamModule = "node:stream";
2892
+ const { Readable } = await import(nodeStreamModule);
2893
+ const CHUNK_BYTES = 256 * 1024;
2894
+ let digest = opts?.digest;
2895
+ if (digest === void 0) {
2896
+ const hash = createHash("sha256");
2897
+ const hashStream = createReadStream(path, { highWaterMark: CHUNK_BYTES });
2898
+ try {
2899
+ for await (const chunk of hashStream) {
2900
+ if (opts?.signal?.aborted) {
2901
+ throw new OllamaAbortError("createBlobFromFile: aborted while hashing", {});
2902
+ }
2903
+ hash.update(chunk);
2904
+ }
2905
+ } finally {
2906
+ hashStream.destroy();
2907
+ }
2908
+ digest = `sha256:${hash.digest("hex")}`;
2909
+ }
2910
+ const alreadyExisted = await this.checkBlob(digest, opts);
2911
+ if (!alreadyExisted) {
2912
+ const uploadStream = createReadStream(path, { highWaterMark: CHUNK_BYTES });
2913
+ const onAbort = () => {
2914
+ uploadStream.destroy();
2915
+ };
2916
+ opts?.signal?.addEventListener("abort", onAbort, { once: true });
2917
+ try {
2918
+ await this.createBlob(
2919
+ digest,
2920
+ Readable.toWeb(uploadStream),
2921
+ opts
2922
+ );
2923
+ } finally {
2924
+ opts?.signal?.removeEventListener("abort", onAbort);
2925
+ }
2926
+ }
2807
2927
  const fileName = path.split(/[\\/]/).pop() ?? path;
2808
- return { ...result, fileName };
2928
+ return { digest, alreadyExisted, fileName };
2809
2929
  }
2810
2930
  /**
2811
2931
  * One-shot custom-model publishing from raw GGUF weights, following the
@@ -6145,8 +6265,8 @@ var OllamaClient = class _OllamaClient {
6145
6265
  */
6146
6266
  getContextLength = (request) => this.models.getContextLength(request);
6147
6267
  version = () => this.models.version();
6148
- createBlob = (digest, data) => this.models.createBlob(digest, data);
6149
- checkBlob = (digest) => this.models.checkBlob(digest);
6268
+ createBlob = (digest, data, request) => this.models.createBlob(digest, data, request);
6269
+ checkBlob = (digest, request) => this.models.checkBlob(digest, request);
6150
6270
  /**
6151
6271
  * Immediately unloads `model` from VRAM. Convenience alias for
6152
6272
  * {@link ModelsClient.unload} — see that method for the full
@@ -6666,6 +6786,56 @@ function toResponse(stream, init = {}) {
6666
6786
  return new Response(body, { ...init, headers });
6667
6787
  }
6668
6788
 
6789
+ // src/streaming/observe.ts
6790
+ async function* observeStream(source, callbacks = {}) {
6791
+ const { onChunk, onError, onDone, onAbandon, onListenerError } = callbacks;
6792
+ const reportListenerFailure = (error, phase) => {
6793
+ try {
6794
+ onListenerError?.(error, phase);
6795
+ } catch {
6796
+ }
6797
+ };
6798
+ let observerChain = Promise.resolve();
6799
+ const dispatch2 = (phase, task) => {
6800
+ observerChain = observerChain.then(task).then(
6801
+ () => void 0,
6802
+ (error) => {
6803
+ reportListenerFailure(error, phase);
6804
+ }
6805
+ );
6806
+ };
6807
+ let state = "running";
6808
+ try {
6809
+ for await (const chunk of source) {
6810
+ if (onChunk !== void 0) {
6811
+ dispatch2("chunk", () => onChunk(chunk));
6812
+ }
6813
+ yield chunk;
6814
+ }
6815
+ state = "done";
6816
+ if (onDone !== void 0) {
6817
+ dispatch2("done", () => onDone());
6818
+ }
6819
+ } catch (error) {
6820
+ state = "error";
6821
+ try {
6822
+ onError?.(error);
6823
+ } catch (listenerError) {
6824
+ reportListenerFailure(listenerError, "error");
6825
+ }
6826
+ throw error;
6827
+ } finally {
6828
+ if (state === "running") {
6829
+ state = "abandoned";
6830
+ try {
6831
+ onAbandon?.();
6832
+ } catch (listenerError) {
6833
+ reportListenerFailure(listenerError, "abandoned");
6834
+ }
6835
+ }
6836
+ }
6837
+ }
6838
+
6669
6839
  // src/quota.ts
6670
6840
  var QuotaManager = class {
6671
6841
  now;
@@ -8062,6 +8232,7 @@ exports.ModelAffinityScheduler = ModelAffinityScheduler;
8062
8232
  exports.ModelsClient = ModelsClient;
8063
8233
  exports.NANOS_PER_MS = NANOS_PER_MS;
8064
8234
  exports.NANOS_PER_SECOND = NANOS_PER_SECOND;
8235
+ exports.NETWORK_ERROR_CODES = NETWORK_ERROR_CODES;
8065
8236
  exports.NOOP_LOGGER = NOOP_LOGGER;
8066
8237
  exports.OLLAMA_CLOUD_BASE_URL = OLLAMA_CLOUD_BASE_URL;
8067
8238
  exports.OLLAMA_FALLBACK_CONTEXT_LENGTH = OLLAMA_FALLBACK_CONTEXT_LENGTH;
@@ -8150,6 +8321,7 @@ exports.inferRuntimeMode = inferRuntimeMode;
8150
8321
  exports.isKeepAliveSugar = isKeepAliveSugar;
8151
8322
  exports.isKnownDoneReason = isKnownDoneReason;
8152
8323
  exports.isModelResident = isModelResident;
8324
+ exports.isNetworkLevelError = isNetworkLevelError;
8153
8325
  exports.isSameToolCall = isSameToolCall;
8154
8326
  exports.listAllMcpTools = listAllMcpTools;
8155
8327
  exports.listAvailableModels = listAvailableModels;
@@ -8162,10 +8334,12 @@ exports.normalizeChatStream = normalizeChatStream;
8162
8334
  exports.normalizeGenerateStream = normalizeGenerateStream;
8163
8335
  exports.normalizeKeepAlive = normalizeKeepAlive;
8164
8336
  exports.normalizeProgressStream = normalizeProgressStream;
8337
+ exports.observeStream = observeStream;
8165
8338
  exports.parseFrontmatter = parseFrontmatter;
8166
8339
  exports.parseNdjsonStream = parseNdjsonStream;
8167
8340
  exports.parseSseStream = parseSseStream;
8168
8341
  exports.parseStructuredOutput = parseStructuredOutput;
8342
+ exports.recommendContextWindow = recommendContextWindow;
8169
8343
  exports.registerMcpTools = registerMcpTools;
8170
8344
  exports.resolveContextLength = resolveContextLength;
8171
8345
  exports.resolveCredentialEndpoints = resolveCredentialEndpoints;