Socket
Book a DemoSign in
Socket

@ai-sdk/provider-utils

Package Overview
Dependencies
Maintainers
3
Versions
242
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ai-sdk/provider-utils - npm Package Compare versions

Comparing version
5.0.0-beta.5
to
5.0.0-beta.6
+105
src/map-reasoning-to-provider.ts
import { LanguageModelV4CallOptions, SharedV4Warning } from '@ai-sdk/provider';
export type ReasoningLevel = Exclude<
LanguageModelV4CallOptions['reasoning'],
'none' | 'provider-default' | undefined
>;
export function isCustomReasoning(
reasoning: LanguageModelV4CallOptions['reasoning'],
): reasoning is Exclude<
LanguageModelV4CallOptions['reasoning'],
'provider-default' | undefined
> {
return reasoning !== undefined && reasoning !== 'provider-default';
}
/**
* Maps a top-level reasoning level to a provider-specific effort string using
* the given effort map. Pushes a compatibility warning if the reasoning level
* maps to a different string, or an unsupported warning if the level is not
* present in the map.
*
* @returns The mapped effort string, or `undefined` if the level is not
* supported.
*/
export function mapReasoningToProviderEffort<T extends string>({
reasoning,
effortMap,
warnings,
}: {
reasoning: ReasoningLevel;
effortMap: Partial<Record<ReasoningLevel, T>>;
warnings: SharedV4Warning[];
}): T | undefined {
const mapped = effortMap[reasoning];
if (mapped == null) {
warnings.push({
type: 'unsupported',
feature: 'reasoning',
details: `reasoning "${reasoning}" is not supported by this model.`,
});
return undefined;
}
if (mapped !== reasoning) {
warnings.push({
type: 'compatibility',
feature: 'reasoning',
details: `reasoning "${reasoning}" is not directly supported by this model. mapped to effort "${mapped}".`,
});
}
return mapped;
}
const DEFAULT_REASONING_BUDGET_PERCENTAGES: Record<ReasoningLevel, number> = {
minimal: 0.02,
low: 0.1,
medium: 0.3,
high: 0.6,
xhigh: 0.9,
};
/**
* Maps a top-level reasoning level to an absolute token budget by multiplying
* the model's max output tokens by a percentage from the budget percentages
* map. The result is clamped between `minReasoningBudget` (default 1024) and
* `maxReasoningBudget`. Pushes an unsupported warning if the level is not
* present in the budget percentages map.
*
* @returns The computed token budget, or `undefined` if the level is not
* supported.
*/
export function mapReasoningToProviderBudget({
reasoning,
maxOutputTokens,
maxReasoningBudget,
minReasoningBudget = 1024,
budgetPercentages = DEFAULT_REASONING_BUDGET_PERCENTAGES,
warnings,
}: {
reasoning: ReasoningLevel;
maxOutputTokens: number;
maxReasoningBudget: number;
minReasoningBudget?: number;
budgetPercentages?: Partial<Record<ReasoningLevel, number>>;
warnings: SharedV4Warning[];
}): number | undefined {
const pct = budgetPercentages[reasoning];
if (pct == null) {
warnings.push({
type: 'unsupported',
feature: 'reasoning',
details: `reasoning "${reasoning}" is not supported by this model.`,
});
return undefined;
}
return Math.min(
maxReasoningBudget,
Math.max(minReasoningBudget, Math.round(maxOutputTokens * pct)),
);
}
+19
-11
# @ai-sdk/provider-utils
## 5.0.0-beta.6
### Patch Changes
- 3887c70: feat(provider): add new top-level reasoning parameter to spec and support it in `generateText` and `streamText`
- Updated dependencies [3887c70]
- @ai-sdk/provider@4.0.0-beta.4
## 5.0.0-beta.5

@@ -53,14 +61,14 @@

providerToolNames: {
'openai.code_interpreter': 'code_interpreter',
'openai.file_search': 'file_search',
'openai.image_generation': 'image_generation',
'openai.local_shell': 'local_shell',
'openai.shell': 'shell',
'openai.web_search': 'web_search',
'openai.web_search_preview': 'web_search_preview',
'openai.mcp': 'mcp',
'openai.apply_patch': 'apply_patch',
"openai.code_interpreter": "code_interpreter",
"openai.file_search": "file_search",
"openai.image_generation": "image_generation",
"openai.local_shell": "local_shell",
"openai.shell": "shell",
"openai.web_search": "web_search",
"openai.web_search_preview": "web_search_preview",
"openai.mcp": "mcp",
"openai.apply_patch": "apply_patch",
},
resolveProviderToolName: tool =>
tool.id === 'openai.custom'
resolveProviderToolName: (tool) =>
tool.id === "openai.custom"
? (tool.args as { name?: string }).name

@@ -67,0 +75,0 @@ : undefined,

@@ -1,2 +0,2 @@

import { LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, ImageModelV4File, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV4Prompt, SharedV4ProviderOptions, TypeValidationContext } from '@ai-sdk/provider';
import { LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, ImageModelV4File, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV4Prompt, LanguageModelV4CallOptions, SharedV4Warning, SharedV4ProviderOptions, TypeValidationContext } from '@ai-sdk/provider';
import { StandardSchemaV1, StandardJSONSchemaV1 } from '@standard-schema/spec';

@@ -429,3 +429,38 @@ export * from '@standard-schema/spec';

type ReasoningLevel = Exclude<LanguageModelV4CallOptions['reasoning'], 'none' | 'provider-default' | undefined>;
declare function isCustomReasoning(reasoning: LanguageModelV4CallOptions['reasoning']): reasoning is Exclude<LanguageModelV4CallOptions['reasoning'], 'provider-default' | undefined>;
/**
* Maps a top-level reasoning level to a provider-specific effort string using
* the given effort map. Pushes a compatibility warning if the reasoning level
* maps to a different string, or an unsupported warning if the level is not
* present in the map.
*
* @returns The mapped effort string, or `undefined` if the level is not
* supported.
*/
declare function mapReasoningToProviderEffort<T extends string>({ reasoning, effortMap, warnings, }: {
reasoning: ReasoningLevel;
effortMap: Partial<Record<ReasoningLevel, T>>;
warnings: SharedV4Warning[];
}): T | undefined;
/**
* Maps a top-level reasoning level to an absolute token budget by multiplying
* the model's max output tokens by a percentage from the budget percentages
* map. The result is clamped between `minReasoningBudget` (default 1024) and
* `maxReasoningBudget`. Pushes an unsupported warning if the level is not
* present in the budget percentages map.
*
* @returns The computed token budget, or `undefined` if the level is not
* supported.
*/
declare function mapReasoningToProviderBudget({ reasoning, maxOutputTokens, maxReasoningBudget, minReasoningBudget, budgetPercentages, warnings, }: {
reasoning: ReasoningLevel;
maxOutputTokens: number;
maxReasoningBudget: number;
minReasoningBudget?: number;
budgetPercentages?: Partial<Record<ReasoningLevel, number>>;
warnings: SharedV4Warning[];
}): number | undefined;
/**
* Loads an optional `string` setting from the environment or a parameter.

@@ -1473,2 +1508,2 @@ *

export { type AssistantContent, type AssistantModelMessage, type CustomPart, 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 ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, 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, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isNonNullable, isParsableJson, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
export { type AssistantContent, type AssistantModelMessage, type CustomPart, 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 ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, 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, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isCustomReasoning, isNonNullable, isParsableJson, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };

@@ -1,2 +0,2 @@

import { LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, ImageModelV4File, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV4Prompt, SharedV4ProviderOptions, TypeValidationContext } from '@ai-sdk/provider';
import { LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, ImageModelV4File, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV4Prompt, LanguageModelV4CallOptions, SharedV4Warning, SharedV4ProviderOptions, TypeValidationContext } from '@ai-sdk/provider';
import { StandardSchemaV1, StandardJSONSchemaV1 } from '@standard-schema/spec';

@@ -429,3 +429,38 @@ export * from '@standard-schema/spec';

type ReasoningLevel = Exclude<LanguageModelV4CallOptions['reasoning'], 'none' | 'provider-default' | undefined>;
declare function isCustomReasoning(reasoning: LanguageModelV4CallOptions['reasoning']): reasoning is Exclude<LanguageModelV4CallOptions['reasoning'], 'provider-default' | undefined>;
/**
* Maps a top-level reasoning level to a provider-specific effort string using
* the given effort map. Pushes a compatibility warning if the reasoning level
* maps to a different string, or an unsupported warning if the level is not
* present in the map.
*
* @returns The mapped effort string, or `undefined` if the level is not
* supported.
*/
declare function mapReasoningToProviderEffort<T extends string>({ reasoning, effortMap, warnings, }: {
reasoning: ReasoningLevel;
effortMap: Partial<Record<ReasoningLevel, T>>;
warnings: SharedV4Warning[];
}): T | undefined;
/**
* Maps a top-level reasoning level to an absolute token budget by multiplying
* the model's max output tokens by a percentage from the budget percentages
* map. The result is clamped between `minReasoningBudget` (default 1024) and
* `maxReasoningBudget`. Pushes an unsupported warning if the level is not
* present in the budget percentages map.
*
* @returns The computed token budget, or `undefined` if the level is not
* supported.
*/
declare function mapReasoningToProviderBudget({ reasoning, maxOutputTokens, maxReasoningBudget, minReasoningBudget, budgetPercentages, warnings, }: {
reasoning: ReasoningLevel;
maxOutputTokens: number;
maxReasoningBudget: number;
minReasoningBudget?: number;
budgetPercentages?: Partial<Record<ReasoningLevel, number>>;
warnings: SharedV4Warning[];
}): number | undefined;
/**
* Loads an optional `string` setting from the environment or a parameter.

@@ -1473,2 +1508,2 @@ *

export { type AssistantContent, type AssistantModelMessage, type CustomPart, 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 ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, 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, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isNonNullable, isParsableJson, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
export { type AssistantContent, type AssistantModelMessage, type CustomPart, 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 ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, 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, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isCustomReasoning, isNonNullable, isParsableJson, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
{
"name": "@ai-sdk/provider-utils",
"version": "5.0.0-beta.5",
"version": "5.0.0-beta.6",
"license": "Apache-2.0",

@@ -38,3 +38,3 @@ "sideEffects": false,

"eventsource-parser": "^3.0.6",
"@ai-sdk/provider": "4.0.0-beta.3"
"@ai-sdk/provider": "4.0.0-beta.4"
},

@@ -73,5 +73,3 @@ "devDependencies": {

"clean": "del-cli dist *.tsbuildinfo",
"lint": "eslint \"./**/*.ts*\"",
"type-check": "tsc --build",
"prettier-check": "prettier --check \"./**/*.ts*\"",
"test": "pnpm test:node && pnpm test:edge",

@@ -78,0 +76,0 @@ "test:update": "pnpm test:node -u",

@@ -28,2 +28,7 @@ export * from './combine-headers';

export * from './load-api-key';
export {
isCustomReasoning,
mapReasoningToProviderBudget,
mapReasoningToProviderEffort,
} from './map-reasoning-to-provider';
export { loadOptionalSetting } from './load-optional-setting';

@@ -30,0 +35,0 @@ export { loadSetting } from './load-setting';

@@ -21,7 +21,12 @@ import { DownloadError } from './download-error';

// Only allow http and https protocols
// data: URLs are inline content, so they do not trigger a network fetch or SSRF risk.
if (parsed.protocol === 'data:') {
return;
}
// Only allow http and https network protocols
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
throw new DownloadError({
url,
message: `URL scheme must be http or https, got ${parsed.protocol}`,
message: `URL scheme must be http, https, or data, got ${parsed.protocol}`,
});

@@ -28,0 +33,0 @@ }

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display