@ai-sdk/provider-utils 4.0.48 → 4.0.50

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 4.0.50
4
+
5
+ ### Patch Changes
6
+
7
+ - cc23556: Mark transient network errors that occur while reading successful response bodies as retryable.
8
+
9
+ ## 4.0.49
10
+
11
+ ### Patch Changes
12
+
13
+ - 9a521b9: Split OpenAI and Azure OpenAI embedding requests by a conservative UTF-8 byte budget derived from their aggregate token limit, in addition to input count limits.
14
+
3
15
  ## 4.0.48
4
16
 
5
17
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -203,6 +203,14 @@ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
203
203
  maxBytes?: number;
204
204
  }): Promise<Uint8Array>;
205
205
 
206
+ /**
207
+ * Symbol for exposing the UTF-8 input byte budget of an embedding model.
208
+ *
209
+ * This capability is experimental and intentionally lives outside the versioned
210
+ * embedding model specification.
211
+ */
212
+ declare const EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL: unique symbol;
213
+
206
214
  /**
207
215
  * Fetches a URL while enforcing the SSRF download guard on every hop.
208
216
  *
@@ -1555,4 +1563,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1555
1563
  */
1556
1564
  type ToolCallOptions = ToolExecutionOptions;
1557
1565
 
1558
- export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1566
+ export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.d.ts CHANGED
@@ -203,6 +203,14 @@ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
203
203
  maxBytes?: number;
204
204
  }): Promise<Uint8Array>;
205
205
 
206
+ /**
207
+ * Symbol for exposing the UTF-8 input byte budget of an embedding model.
208
+ *
209
+ * This capability is experimental and intentionally lives outside the versioned
210
+ * embedding model specification.
211
+ */
212
+ declare const EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL: unique symbol;
213
+
206
214
  /**
207
215
  * Fetches a URL while enforcing the SSRF download guard on every hop.
208
216
  *
@@ -1555,4 +1563,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1555
1563
  */
1556
1564
  type ToolCallOptions = ToolExecutionOptions;
1557
1565
 
1558
- export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1566
+ export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.js CHANGED
@@ -33,6 +33,7 @@ __export(index_exports, {
33
33
  DEFAULT_MAX_DOWNLOAD_SIZE: () => DEFAULT_MAX_DOWNLOAD_SIZE,
34
34
  DelayedPromise: () => DelayedPromise,
35
35
  DownloadError: () => DownloadError,
36
+ EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL: () => EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL,
36
37
  EventSourceParserStream: () => import_stream2.EventSourceParserStream,
37
38
  VERSION: () => VERSION,
38
39
  asSchema: () => asSchema,
@@ -733,6 +734,11 @@ async function downloadBlob(url, options) {
733
734
  }
734
735
  }
735
736
 
737
+ // src/embedding-model-capabilities.ts
738
+ var EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL = /* @__PURE__ */ Symbol.for(
739
+ "vercel.ai.embeddingModel.maxInputBytesPerCall"
740
+ );
741
+
736
742
  // src/generate-id.ts
737
743
  var import_provider2 = require("@ai-sdk/provider");
738
744
  var createIdGenerator = ({
@@ -790,24 +796,31 @@ function isAbortError(error) {
790
796
 
791
797
  // src/handle-fetch-error.ts
792
798
  var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
793
- var BUN_ERROR_CODES = [
799
+ var RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
794
800
  "ConnectionRefused",
795
801
  "ConnectionClosed",
796
802
  "FailedToOpenSocket",
797
803
  "ECONNRESET",
798
804
  "ECONNREFUSED",
799
805
  "ETIMEDOUT",
800
- "EPIPE"
801
- ];
802
- function isBunNetworkError(error) {
803
- if (!(error instanceof Error)) {
804
- return false;
805
- }
806
- const code = error.code;
807
- if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) {
808
- return true;
809
- }
810
- return false;
806
+ "EPIPE",
807
+ "UND_ERR_SOCKET",
808
+ "UND_ERR_HEADERS_TIMEOUT",
809
+ "UND_ERR_BODY_TIMEOUT",
810
+ "UND_ERR_CONNECT_TIMEOUT"
811
+ ]);
812
+ function findNetworkError(error) {
813
+ const visited = /* @__PURE__ */ new Set();
814
+ let current = error;
815
+ while (current instanceof Error && !visited.has(current)) {
816
+ visited.add(current);
817
+ const errorWithCode = current;
818
+ if (typeof errorWithCode.code === "string" && RETRYABLE_NETWORK_ERROR_CODES.has(errorWithCode.code)) {
819
+ return errorWithCode;
820
+ }
821
+ current = current.cause;
822
+ }
823
+ return void 0;
811
824
  }
812
825
  function handleFetchError({
813
826
  error,
@@ -830,9 +843,23 @@ function handleFetchError({
830
843
  });
831
844
  }
832
845
  }
833
- if (isBunNetworkError(error)) {
846
+ const networkError = findNetworkError(error);
847
+ if (networkError != null) {
848
+ if (import_provider3.APICallError.isInstance(error)) {
849
+ return new import_provider3.APICallError({
850
+ message: error.message,
851
+ cause: error.cause,
852
+ url: error.url,
853
+ requestBodyValues: error.requestBodyValues,
854
+ statusCode: error.statusCode,
855
+ responseHeaders: error.responseHeaders,
856
+ responseBody: error.responseBody,
857
+ data: error.data,
858
+ isRetryable: true
859
+ });
860
+ }
834
861
  return new import_provider3.APICallError({
835
- message: `Cannot connect to API: ${error.message}`,
862
+ message: `Cannot connect to API: ${error instanceof Error ? error.message : networkError.message}`,
836
863
  cause: error,
837
864
  url,
838
865
  requestBodyValues,
@@ -895,7 +922,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
895
922
  }
896
923
 
897
924
  // src/version.ts
898
- var VERSION = true ? "4.0.48" : "0.0.0-test";
925
+ var VERSION = true ? "4.0.50" : "0.0.0-test";
899
926
 
900
927
  // src/get-from-api.ts
901
928
  var getOriginalFetch = () => globalThis.fetch;
@@ -2930,6 +2957,62 @@ async function retryWithExponentialBackoffInternal(f, {
2930
2957
  // src/response-handler.ts
2931
2958
  var import_provider12 = require("@ai-sdk/provider");
2932
2959
  var textDecoder = new TextDecoder();
2960
+ function wrapResponseBodyStream({
2961
+ stream,
2962
+ url,
2963
+ requestBodyValues,
2964
+ statusCode,
2965
+ responseHeaders
2966
+ }) {
2967
+ const reader = stream.getReader();
2968
+ let readerReleased = false;
2969
+ const releaseReader = () => {
2970
+ if (!readerReleased) {
2971
+ reader.releaseLock();
2972
+ readerReleased = true;
2973
+ }
2974
+ };
2975
+ return new ReadableStream({
2976
+ async pull(controller) {
2977
+ try {
2978
+ const { done, value } = await reader.read();
2979
+ if (done) {
2980
+ releaseReader();
2981
+ controller.close();
2982
+ } else {
2983
+ controller.enqueue(value);
2984
+ }
2985
+ } catch (error) {
2986
+ releaseReader();
2987
+ if (isAbortError(error)) {
2988
+ controller.error(error);
2989
+ return;
2990
+ }
2991
+ controller.error(
2992
+ handleFetchError({
2993
+ error: new import_provider12.APICallError({
2994
+ message: "Failed to process successful response",
2995
+ cause: error,
2996
+ statusCode,
2997
+ url,
2998
+ responseHeaders,
2999
+ requestBodyValues
3000
+ }),
3001
+ url,
3002
+ requestBodyValues
3003
+ })
3004
+ );
3005
+ }
3006
+ },
3007
+ async cancel(reason) {
3008
+ try {
3009
+ await reader.cancel(reason);
3010
+ } finally {
3011
+ releaseReader();
3012
+ }
3013
+ }
3014
+ });
3015
+ }
2933
3016
  async function readResponseBodyAsText({
2934
3017
  response,
2935
3018
  url
@@ -2995,7 +3078,7 @@ var createJsonErrorResponseHandler = ({
2995
3078
  };
2996
3079
  }
2997
3080
  };
2998
- var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
3081
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response, url, requestBodyValues }) => {
2999
3082
  const responseHeaders = extractResponseHeaders(response);
3000
3083
  if (response.body == null) {
3001
3084
  throw new import_provider12.EmptyResponseBodyError({});
@@ -3003,7 +3086,13 @@ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) =>
3003
3086
  return {
3004
3087
  responseHeaders,
3005
3088
  value: parseJsonEventStream({
3006
- stream: response.body,
3089
+ stream: wrapResponseBodyStream({
3090
+ stream: response.body,
3091
+ url,
3092
+ requestBodyValues,
3093
+ statusCode: response.status,
3094
+ responseHeaders
3095
+ }),
3007
3096
  schema: chunkSchema
3008
3097
  })
3009
3098
  };
@@ -3120,6 +3209,7 @@ var import_stream2 = require("eventsource-parser/stream");
3120
3209
  DEFAULT_MAX_DOWNLOAD_SIZE,
3121
3210
  DelayedPromise,
3122
3211
  DownloadError,
3212
+ EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL,
3123
3213
  EventSourceParserStream,
3124
3214
  VERSION,
3125
3215
  asSchema,