🤖 feat: Claude Opus 4.6 - 1M Context, Premium Pricing, Adaptive Thinking (#11670)
Some checks are pending
Docker Dev Branch Images Build / build (Dockerfile, lc-dev, node) (push) Waiting to run
Docker Dev Branch Images Build / build (Dockerfile.multi, lc-dev-api, api-build) (push) Waiting to run
Docker Dev Images Build / build (Dockerfile, librechat-dev, node) (push) Waiting to run
Docker Dev Images Build / build (Dockerfile.multi, librechat-dev-api, api-build) (push) Waiting to run
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions

* feat: Implement new features for Claude Opus 4.6 model

- Added support for tiered pricing based on input token count for the Claude Opus 4.6 model.
- Updated token value calculations to include inputTokenCount for accurate pricing.
- Enhanced transaction handling to apply premium rates when input tokens exceed defined thresholds.
- Introduced comprehensive tests to validate pricing logic for both standard and premium rates across various scenarios.
- Updated related utility functions and models to accommodate new pricing structure.

This change improves the flexibility and accuracy of token pricing for the Claude Opus 4.6 model, ensuring users are charged appropriately based on their usage.

* feat: Add effort field to conversation and preset schemas

- Introduced a new optional `effort` field of type `String` in both the `IPreset` and `IConversation` interfaces.
- Updated the `conversationPreset` schema to include the `effort` field, enhancing the data structure for better context management.

* chore: Clean up unused variable and comments in initialize function

* chore: update dependencies and SDK versions

- Updated @anthropic-ai/sdk to version 0.73.0 in package.json and overrides.
- Updated @anthropic-ai/vertex-sdk to version 0.14.3 in packages/api/package.json.
- Updated @librechat/agents to version 3.1.34 in packages/api/package.json.
- Refactored imports in packages/api/src/endpoints/anthropic/vertex.ts for consistency.

* chore: remove postcss-loader from dependencies

* feat: Bedrock model support for adaptive thinking configuration

- Updated .env.example to include new Bedrock model IDs for Claude Opus 4.6.
- Refactored bedrockInputParser to support adaptive thinking for Opus models, allowing for dynamic thinking configurations.
- Introduced a new function to check model compatibility with adaptive thinking.
- Added an optional `effort` field to the input schemas and updated related configurations.
- Enhanced tests to validate the new adaptive thinking logic and model configurations.

* feat: Add tests for Opus 4.6 adaptive thinking configuration

* feat: Update model references for Opus 4.6 by removing version suffix

* feat: Update @librechat/agents to version 3.1.35 in package.json and package-lock.json

* chore: @librechat/agents to version 3.1.36 in package.json and package-lock.json

* feat: Normalize inputTokenCount for spendTokens and enhance transaction handling

- Introduced normalization for promptTokens to ensure inputTokenCount does not go negative.
- Updated transaction logic to reflect normalized inputTokenCount in pricing calculations.
- Added comprehensive tests to validate the new normalization logic and its impact on transaction rates for both standard and premium models.
- Refactored related functions to improve clarity and maintainability of token value calculations.

* chore: Simplify adaptive thinking configuration in helpers.ts

- Removed unnecessary type casting for the thinking property in updatedOptions.
- Ensured that adaptive thinking is directly assigned when conditions are met, improving code clarity.

* refactor: Replace hard-coded token values with dynamic retrieval from maxTokensMap in model tests

* fix: Ensure non-negative token values in spendTokens calculations

- Updated token value retrieval to use Math.max for prompt and completion tokens, preventing negative values.
- Enhanced clarity in token calculations for both prompt and completion transactions.

* test: Add test for normalization of negative structured token values in spendStructuredTokens

- Implemented a test to ensure that negative structured token values are normalized to zero during token spending.
- Verified that the transaction rates remain consistent with the expected standard values after normalization.

* refactor: Bedrock model support for adaptive thinking and context handling

- Added tests for various alternate naming conventions of Claude models to validate adaptive thinking and context support.
- Refactored `supportsAdaptiveThinking` and `supportsContext1m` functions to utilize new parsing methods for model version extraction.
- Updated `bedrockInputParser` to handle effort configurations more effectively and strip unnecessary fields for non-adaptive models.
- Improved handling of anthropic model configurations in the input parser.

* fix: Improve token value retrieval in getMultiplier function

- Updated the token value retrieval logic to use optional chaining for better safety against undefined values.
- Added a test case to ensure that the function returns the default rate when the provided valueKey does not exist in tokenValues.
This commit is contained in:
Danny Avila 2026-02-06 18:35:36 -05:00 committed by GitHub
parent 1d5f2eb04b
commit 41e2348d47
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
32 changed files with 2902 additions and 1087 deletions

View file

@ -78,7 +78,7 @@
"registry": "https://registry.npmjs.org/"
},
"peerDependencies": {
"@anthropic-ai/vertex-sdk": "^0.14.0",
"@anthropic-ai/vertex-sdk": "^0.14.3",
"@aws-sdk/client-bedrock-runtime": "^3.970.0",
"@aws-sdk/client-s3": "^3.980.0",
"@azure/identity": "^4.7.0",
@ -87,7 +87,7 @@
"@google/genai": "^1.19.0",
"@keyv/redis": "^4.3.3",
"@langchain/core": "^0.3.80",
"@librechat/agents": "^3.1.33",
"@librechat/agents": "^3.1.36",
"@librechat/data-schemas": "*",
"@modelcontextprotocol/sdk": "^1.26.0",
"@smithy/node-http-handler": "^4.4.5",

View file

@ -1,6 +1,12 @@
import { logger } from '@librechat/data-schemas';
import { AnthropicClientOptions } from '@librechat/agents';
import { EModelEndpoint, anthropicSettings } from 'librechat-data-provider';
import {
EModelEndpoint,
AnthropicEffort,
anthropicSettings,
supportsContext1m,
supportsAdaptiveThinking,
} from 'librechat-data-provider';
import { matchModelName } from '~/utils/tokens';
/**
@ -48,7 +54,7 @@ function getClaudeHeaders(
return {
'anthropic-beta': 'token-efficient-tools-2025-02-19,output-128k-2025-02-19',
};
} else if (/claude-sonnet-4/.test(model)) {
} else if (supportsContext1m(model)) {
return {
'anthropic-beta': 'context-1m-2025-08-07',
};
@ -58,25 +64,43 @@ function getClaudeHeaders(
}
/**
* Configures reasoning-related options for Claude models
* @param {AnthropicClientOptions & { max_tokens?: number }} anthropicInput The request options object
* @param {Object} extendedOptions Additional client configuration options
* @param {boolean} extendedOptions.thinking Whether thinking is enabled in client config
* @param {number|null} extendedOptions.thinkingBudget The token budget for thinking
* @returns {Object} Updated request options
* Configures reasoning-related options for Claude models.
* Models supporting adaptive thinking (Opus 4.6+, Sonnet 5+) use effort control instead of manual budget_tokens.
*/
function configureReasoning(
anthropicInput: AnthropicClientOptions & { max_tokens?: number },
extendedOptions: { thinking?: boolean; thinkingBudget?: number | null } = {},
extendedOptions: {
thinking?: boolean;
thinkingBudget?: number | null;
effort?: AnthropicEffort | string | null;
} = {},
): AnthropicClientOptions & { max_tokens?: number } {
const updatedOptions = { ...anthropicInput };
const currentMaxTokens = updatedOptions.max_tokens ?? updatedOptions.maxTokens;
const modelName = updatedOptions.model ?? '';
if (extendedOptions.thinking && modelName && supportsAdaptiveThinking(modelName)) {
updatedOptions.thinking = { type: 'adaptive' };
const effort = extendedOptions.effort;
if (effort && effort !== AnthropicEffort.unset) {
updatedOptions.invocationKwargs = {
...updatedOptions.invocationKwargs,
output_config: { effort },
};
}
if (currentMaxTokens == null) {
updatedOptions.max_tokens = anthropicSettings.maxOutputTokens.reset(modelName);
}
return updatedOptions;
}
if (
extendedOptions.thinking &&
updatedOptions?.model &&
(/claude-3[-.]7/.test(updatedOptions.model) ||
/claude-(?:sonnet|opus|haiku)-[4-9]/.test(updatedOptions.model))
modelName &&
(/claude-3[-.]7/.test(modelName) || /claude-(?:sonnet|opus|haiku)-[4-9]/.test(modelName))
) {
updatedOptions.thinking = {
...updatedOptions.thinking,
@ -100,7 +124,7 @@ function configureReasoning(
updatedOptions.thinking.type === 'enabled' &&
(currentMaxTokens == null || updatedOptions.thinking.budget_tokens > currentMaxTokens)
) {
const maxTokens = anthropicSettings.maxOutputTokens.reset(updatedOptions.model ?? '');
const maxTokens = anthropicSettings.maxOutputTokens.reset(modelName);
updatedOptions.max_tokens = currentMaxTokens ?? maxTokens;
logger.warn(
@ -111,11 +135,11 @@ function configureReasoning(
updatedOptions.thinking.budget_tokens = Math.min(
updatedOptions.thinking.budget_tokens,
Math.floor(updatedOptions.max_tokens * 0.9),
Math.floor((updatedOptions.max_tokens ?? 0) * 0.9),
);
}
return updatedOptions;
}
export { checkPromptCacheSupport, getClaudeHeaders, configureReasoning };
export { checkPromptCacheSupport, getClaudeHeaders, configureReasoning, supportsAdaptiveThinking };

View file

@ -77,13 +77,11 @@ export async function initializeAnthropic({
...(vertexConfig && { vertexConfig }),
};
/** @type {undefined | TBaseEndpoint} */
const anthropicConfig = appConfig?.endpoints?.[EModelEndpoint.anthropic];
const allConfig = appConfig?.endpoints?.all;
const result = getLLMConfig(credentials, clientOptions);
// Apply stream rate delay
if (anthropicConfig?.streamRate) {
(result.llmConfig as Record<string, unknown>)._lc_stream_delay = anthropicConfig.streamRate;
}

View file

@ -1,5 +1,6 @@
import { getLLMConfig } from './llm';
import { AnthropicEffort } from 'librechat-data-provider';
import type * as t from '~/types';
import { getLLMConfig } from './llm';
jest.mock('https-proxy-agent', () => ({
HttpsProxyAgent: jest.fn().mockImplementation((proxy) => ({ proxy })),
@ -835,13 +836,19 @@ describe('getLLMConfig', () => {
expect(result.llmConfig.maxTokens).toBe(32000);
});
// opus-4-5+ get 64K
const opus64kModels = ['claude-opus-4-5', 'claude-opus-4-7', 'claude-opus-4-10'];
opus64kModels.forEach((model) => {
// opus-4-5 gets 64K
const opus64kResult = getLLMConfig('test-key', {
modelOptions: { model: 'claude-opus-4-5' },
});
expect(opus64kResult.llmConfig.maxTokens).toBe(64000);
// opus-4-6+ get 128K
const opus128kModels = ['claude-opus-4-7', 'claude-opus-4-10'];
opus128kModels.forEach((model) => {
const result = getLLMConfig('test-key', {
modelOptions: { model },
});
expect(result.llmConfig.maxTokens).toBe(64000);
expect(result.llmConfig.maxTokens).toBe(128000);
});
});
@ -910,6 +917,126 @@ describe('getLLMConfig', () => {
expect(result.llmConfig.maxTokens).toBe(32000);
});
it('should use adaptive thinking for Opus 4.6 instead of enabled + budget_tokens', () => {
const result = getLLMConfig('test-key', {
modelOptions: {
model: 'claude-opus-4-6',
thinking: true,
thinkingBudget: 10000,
},
});
expect((result.llmConfig.thinking as unknown as { type: string }).type).toBe('adaptive');
expect(result.llmConfig.thinking).not.toHaveProperty('budget_tokens');
expect(result.llmConfig.maxTokens).toBe(128000);
});
it('should set effort via output_config for adaptive thinking models', () => {
const result = getLLMConfig('test-key', {
modelOptions: {
model: 'claude-opus-4-6',
thinking: true,
effort: AnthropicEffort.medium,
},
});
expect((result.llmConfig.thinking as unknown as { type: string }).type).toBe('adaptive');
expect(result.llmConfig.invocationKwargs).toHaveProperty('output_config');
expect(result.llmConfig.invocationKwargs?.output_config).toEqual({
effort: AnthropicEffort.medium,
});
});
it('should set effort via output_config even without thinking for adaptive models', () => {
const result = getLLMConfig('test-key', {
modelOptions: {
model: 'claude-opus-4-6',
thinking: false,
effort: AnthropicEffort.low,
},
});
expect(result.llmConfig.thinking).toBeUndefined();
expect(result.llmConfig.invocationKwargs).toHaveProperty('output_config');
expect(result.llmConfig.invocationKwargs?.output_config).toEqual({
effort: AnthropicEffort.low,
});
});
it('should NOT set adaptive thinking or effort for non-adaptive models', () => {
const nonAdaptiveModels = [
'claude-opus-4-5',
'claude-opus-4-1',
'claude-sonnet-4-5',
'claude-sonnet-4',
'claude-haiku-4-5',
];
nonAdaptiveModels.forEach((model) => {
const result = getLLMConfig('test-key', {
modelOptions: {
model,
thinking: true,
thinkingBudget: 10000,
effort: AnthropicEffort.medium,
},
});
if (result.llmConfig.thinking != null) {
expect((result.llmConfig.thinking as unknown as { type: string }).type).not.toBe(
'adaptive',
);
}
expect(result.llmConfig.invocationKwargs?.output_config).toBeUndefined();
});
});
it('should strip adaptive thinking if it somehow reaches a non-adaptive model', () => {
const result = getLLMConfig('test-key', {
modelOptions: {
model: 'claude-sonnet-4-5',
thinking: true,
thinkingBudget: 5000,
},
});
expect(result.llmConfig.thinking).toMatchObject({
type: 'enabled',
budget_tokens: 5000,
});
expect(result.llmConfig.invocationKwargs?.output_config).toBeUndefined();
});
it('should exclude topP/topK for Opus 4.6 with adaptive thinking', () => {
const result = getLLMConfig('test-key', {
modelOptions: {
model: 'claude-opus-4-6',
thinking: true,
topP: 0.9,
topK: 40,
},
});
expect((result.llmConfig.thinking as unknown as { type: string }).type).toBe('adaptive');
expect(result.llmConfig).not.toHaveProperty('topP');
expect(result.llmConfig).not.toHaveProperty('topK');
});
it('should include topP/topK for Opus 4.6 when thinking is disabled', () => {
const result = getLLMConfig('test-key', {
modelOptions: {
model: 'claude-opus-4-6',
thinking: false,
topP: 0.9,
topK: 40,
},
});
expect(result.llmConfig.thinking).toBeUndefined();
expect(result.llmConfig).toHaveProperty('topP', 0.9);
expect(result.llmConfig).toHaveProperty('topK', 40);
});
it('should respect model-specific maxOutputTokens for Claude 4.x models', () => {
const testCases = [
{ model: 'claude-sonnet-4-5', maxOutputTokens: 50000, expected: 50000 },
@ -960,7 +1087,7 @@ describe('getLLMConfig', () => {
});
});
it('should future-proof Claude 5.x Opus models with 64K default', () => {
it('should future-proof Claude 5.x Opus models with 128K default', () => {
const testCases = [
'claude-opus-5',
'claude-opus-5-0',
@ -972,28 +1099,28 @@ describe('getLLMConfig', () => {
const result = getLLMConfig('test-key', {
modelOptions: { model },
});
expect(result.llmConfig.maxTokens).toBe(64000);
expect(result.llmConfig.maxTokens).toBe(128000);
});
});
it('should future-proof Claude 6-9.x models with correct defaults', () => {
const testCases = [
// Claude 6.x - All get 64K since they're version 5+
// Claude 6.x - Sonnet/Haiku get 64K, Opus gets 128K
{ model: 'claude-sonnet-6', expected: 64000 },
{ model: 'claude-haiku-6-0', expected: 64000 },
{ model: 'claude-opus-6-1', expected: 64000 }, // opus 6+ gets 64K
{ model: 'claude-opus-6-1', expected: 128000 },
// Claude 7.x
{ model: 'claude-sonnet-7-20270101', expected: 64000 },
{ model: 'claude-haiku-7.5', expected: 64000 },
{ model: 'claude-opus-7', expected: 64000 }, // opus 7+ gets 64K
{ model: 'claude-opus-7', expected: 128000 },
// Claude 8.x
{ model: 'claude-sonnet-8', expected: 64000 },
{ model: 'claude-haiku-8-2', expected: 64000 },
{ model: 'claude-opus-8-latest', expected: 64000 }, // opus 8+ gets 64K
{ model: 'claude-opus-8-latest', expected: 128000 },
// Claude 9.x
{ model: 'claude-sonnet-9', expected: 64000 },
{ model: 'claude-haiku-9', expected: 64000 },
{ model: 'claude-opus-9', expected: 64000 }, // opus 9+ gets 64K
{ model: 'claude-opus-9', expected: 128000 },
];
testCases.forEach(({ model, expected }) => {

View file

@ -7,7 +7,12 @@ import type {
AnthropicConfigOptions,
AnthropicCredentials,
} from '~/types/anthropic';
import { checkPromptCacheSupport, getClaudeHeaders, configureReasoning } from './helpers';
import {
supportsAdaptiveThinking,
checkPromptCacheSupport,
configureReasoning,
getClaudeHeaders,
} from './helpers';
import {
createAnthropicVertexClient,
isAnthropicVertexCredentials,
@ -83,15 +88,14 @@ function getLLMConfig(
promptCache: options.modelOptions?.promptCache ?? anthropicSettings.promptCache.default,
thinkingBudget:
options.modelOptions?.thinkingBudget ?? anthropicSettings.thinkingBudget.default,
effort: options.modelOptions?.effort ?? anthropicSettings.effort.default,
};
/** Couldn't figure out a way to still loop through the object while deleting the overlapping keys when porting this
* over from javascript, so for now they are being deleted manually until a better way presents itself.
*/
if (options.modelOptions) {
delete options.modelOptions.thinking;
delete options.modelOptions.promptCache;
delete options.modelOptions.thinkingBudget;
delete options.modelOptions.effort;
} else {
throw new Error('No modelOptions provided');
}
@ -145,10 +149,33 @@ function getLLMConfig(
requestOptions = configureReasoning(requestOptions, systemOptions);
if (!/claude-3[-.]7/.test(mergedOptions.model)) {
requestOptions.topP = mergedOptions.topP;
requestOptions.topK = mergedOptions.topK;
} else if (requestOptions.thinking == null) {
if (supportsAdaptiveThinking(mergedOptions.model)) {
if (
systemOptions.effort &&
(systemOptions.effort as string) !== '' &&
!requestOptions.invocationKwargs?.output_config
) {
requestOptions.invocationKwargs = {
...requestOptions.invocationKwargs,
output_config: { effort: systemOptions.effort },
};
}
} else {
if (
requestOptions.thinking != null &&
(requestOptions.thinking as unknown as { type: string }).type === 'adaptive'
) {
delete requestOptions.thinking;
}
if (requestOptions.invocationKwargs?.output_config) {
delete requestOptions.invocationKwargs.output_config;
}
}
const hasActiveThinking = requestOptions.thinking != null;
const isThinkingModel =
/claude-3[-.]7/.test(mergedOptions.model) || supportsAdaptiveThinking(mergedOptions.model);
if (!isThinkingModel || !hasActiveThinking) {
requestOptions.topP = mergedOptions.topP;
requestOptions.topK = mergedOptions.topK;
}

View file

@ -1,10 +1,10 @@
import path from 'path';
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
import { GoogleAuth } from 'google-auth-library';
import { ClientOptions } from '@anthropic-ai/sdk';
import { AuthKeys } from 'librechat-data-provider';
import { loadServiceKey } from '~/utils/key';
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
import type { ClientOptions } from '@anthropic-ai/sdk';
import type { AnthropicCredentials, VertexAIClientOptions } from '~/types/anthropic';
import { loadServiceKey } from '~/utils/key';
/**
* Options for loading Vertex AI credentials

View file

@ -613,4 +613,113 @@ describe('initializeBedrock', () => {
expect(result.llmConfig).toHaveProperty('applicationInferenceProfile', inferenceProfileArn);
});
});
describe('Opus 4.6 Adaptive Thinking', () => {
it('should configure adaptive thinking with default maxTokens for Opus 4.6', async () => {
const params = createMockParams({
model_parameters: {
model: 'anthropic.claude-opus-4-6-v1',
},
});
const result = (await initializeBedrock(params)) as BedrockLLMConfigResult;
const amrf = result.llmConfig.additionalModelRequestFields as Record<string, unknown>;
expect(amrf.thinking).toEqual({ type: 'adaptive' });
expect(result.llmConfig.maxTokens).toBe(16000);
expect(amrf.anthropic_beta).toEqual(
expect.arrayContaining(['output-128k-2025-02-19', 'context-1m-2025-08-07']),
);
});
it('should pass effort via output_config for Opus 4.6', async () => {
const params = createMockParams({
model_parameters: {
model: 'anthropic.claude-opus-4-6-v1',
effort: 'medium',
},
});
const result = (await initializeBedrock(params)) as BedrockLLMConfigResult;
const amrf = result.llmConfig.additionalModelRequestFields as Record<string, unknown>;
expect(amrf.thinking).toEqual({ type: 'adaptive' });
expect(amrf.output_config).toEqual({ effort: 'medium' });
});
it('should respect user-provided maxTokens for Opus 4.6', async () => {
const params = createMockParams({
model_parameters: {
model: 'anthropic.claude-opus-4-6-v1',
maxTokens: 32000,
},
});
const result = (await initializeBedrock(params)) as BedrockLLMConfigResult;
expect(result.llmConfig.maxTokens).toBe(32000);
});
it('should handle cross-region Opus 4.6 model IDs', async () => {
const params = createMockParams({
model_parameters: {
model: 'us.anthropic.claude-opus-4-6-v1',
effort: 'low',
},
});
const result = (await initializeBedrock(params)) as BedrockLLMConfigResult;
const amrf = result.llmConfig.additionalModelRequestFields as Record<string, unknown>;
expect(result.llmConfig).toHaveProperty('model', 'us.anthropic.claude-opus-4-6-v1');
expect(amrf.thinking).toEqual({ type: 'adaptive' });
expect(amrf.output_config).toEqual({ effort: 'low' });
});
it('should use enabled thinking for non-adaptive models (Sonnet 4.5)', async () => {
const params = createMockParams({
model_parameters: {
model: 'anthropic.claude-sonnet-4-5-20250929-v1:0',
},
});
const result = (await initializeBedrock(params)) as BedrockLLMConfigResult;
const amrf = result.llmConfig.additionalModelRequestFields as Record<string, unknown>;
expect(amrf.thinking).toEqual({ type: 'enabled', budget_tokens: 2000 });
expect(amrf.output_config).toBeUndefined();
expect(result.llmConfig.maxTokens).toBe(8192);
});
it('should not include output_config when effort is empty', async () => {
const params = createMockParams({
model_parameters: {
model: 'anthropic.claude-opus-4-6-v1',
effort: '',
},
});
const result = (await initializeBedrock(params)) as BedrockLLMConfigResult;
const amrf = result.llmConfig.additionalModelRequestFields as Record<string, unknown>;
expect(amrf.thinking).toEqual({ type: 'adaptive' });
expect(amrf.output_config).toBeUndefined();
});
it('should strip effort for non-adaptive models', async () => {
const params = createMockParams({
model_parameters: {
model: 'anthropic.claude-opus-4-1-20250805-v1:0',
effort: 'high',
},
});
const result = (await initializeBedrock(params)) as BedrockLLMConfigResult;
const amrf = result.llmConfig.additionalModelRequestFields as Record<string, unknown>;
expect(amrf.thinking).toEqual({ type: 'enabled', budget_tokens: 2000 });
expect(amrf.output_config).toBeUndefined();
expect(amrf.effort).toBeUndefined();
});
});
});

View file

@ -44,6 +44,10 @@ export interface ThinkingConfigEnabled {
type: 'enabled';
}
export interface ThinkingConfigAdaptive {
type: 'adaptive';
}
/**
* Configuration for enabling Claude's extended thinking.
*
@ -55,7 +59,10 @@ export interface ThinkingConfigEnabled {
* [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)
* for details.
*/
export type ThinkingConfigParam = ThinkingConfigEnabled | ThinkingConfigDisabled;
export type ThinkingConfigParam =
| ThinkingConfigEnabled
| ThinkingConfigDisabled
| ThinkingConfigAdaptive;
export type AnthropicModelOptions = Partial<Omit<AnthropicParameters, 'thinking'>> & {
thinking?: AnthropicParameters['thinking'] | null;

View file

@ -151,6 +151,7 @@ const anthropicModels = {
'claude-4': 200000,
'claude-opus-4': 200000,
'claude-opus-4-5': 200000,
'claude-opus-4-6': 1000000,
};
const deepseekModels = {
@ -394,6 +395,7 @@ const anthropicMaxOutputs = {
'claude-sonnet-4': 64000,
'claude-opus-4': 32000,
'claude-opus-4-5': 64000,
'claude-opus-4-6': 128000,
'claude-3.5-sonnet': 8192,
'claude-3-5-sonnet': 8192,
'claude-3.7-sonnet': 128000,

View file

@ -1,5 +1,161 @@
import { bedrockInputParser } from '../src/bedrock';
import type { BedrockConverseInput } from '../src/bedrock';
import {
supportsAdaptiveThinking,
bedrockOutputParser,
bedrockInputParser,
supportsContext1m,
} from '../src/bedrock';
describe('supportsAdaptiveThinking', () => {
test('should return true for claude-opus-4-6', () => {
expect(supportsAdaptiveThinking('claude-opus-4-6')).toBe(true);
});
test('should return true for claude-opus-4.6', () => {
expect(supportsAdaptiveThinking('claude-opus-4.6')).toBe(true);
});
test('should return true for claude-opus-4-7 (future)', () => {
expect(supportsAdaptiveThinking('claude-opus-4-7')).toBe(true);
});
test('should return true for claude-opus-5 (future)', () => {
expect(supportsAdaptiveThinking('claude-opus-5')).toBe(true);
});
test('should return true for claude-opus-9 (future)', () => {
expect(supportsAdaptiveThinking('claude-opus-9')).toBe(true);
});
test('should return true for claude-sonnet-5 (future)', () => {
expect(supportsAdaptiveThinking('claude-sonnet-5')).toBe(true);
});
test('should return true for claude-sonnet-6 (future)', () => {
expect(supportsAdaptiveThinking('claude-sonnet-6')).toBe(true);
});
test('should return false for claude-opus-4-5', () => {
expect(supportsAdaptiveThinking('claude-opus-4-5')).toBe(false);
});
test('should return false for claude-opus-4', () => {
expect(supportsAdaptiveThinking('claude-opus-4')).toBe(false);
});
test('should return false for claude-opus-4-0', () => {
expect(supportsAdaptiveThinking('claude-opus-4-0')).toBe(false);
});
test('should return false for claude-sonnet-4-5', () => {
expect(supportsAdaptiveThinking('claude-sonnet-4-5')).toBe(false);
});
test('should return false for claude-sonnet-4', () => {
expect(supportsAdaptiveThinking('claude-sonnet-4')).toBe(false);
});
test('should return false for claude-3-7-sonnet', () => {
expect(supportsAdaptiveThinking('claude-3-7-sonnet')).toBe(false);
});
test('should return false for unrelated model', () => {
expect(supportsAdaptiveThinking('gpt-4o')).toBe(false);
});
test('should handle Bedrock model ID with prefix stripping', () => {
expect(supportsAdaptiveThinking('anthropic.claude-opus-4-6-v1:0')).toBe(true);
});
test('should handle cross-region Bedrock model ID', () => {
expect(supportsAdaptiveThinking('us.anthropic.claude-opus-4-6-v1')).toBe(true);
});
test('should return true for claude-4-6-opus (alternate naming)', () => {
expect(supportsAdaptiveThinking('claude-4-6-opus')).toBe(true);
});
test('should return true for anthropic.claude-4-6-opus (alternate naming)', () => {
expect(supportsAdaptiveThinking('anthropic.claude-4-6-opus')).toBe(true);
});
test('should return true for claude-5-sonnet (alternate naming)', () => {
expect(supportsAdaptiveThinking('claude-5-sonnet')).toBe(true);
});
test('should return true for anthropic.claude-5-sonnet (alternate naming)', () => {
expect(supportsAdaptiveThinking('anthropic.claude-5-sonnet')).toBe(true);
});
test('should return false for claude-4-5-opus (alternate naming, below threshold)', () => {
expect(supportsAdaptiveThinking('claude-4-5-opus')).toBe(false);
});
test('should return false for claude-4-sonnet (alternate naming, below threshold)', () => {
expect(supportsAdaptiveThinking('claude-4-sonnet')).toBe(false);
});
});
describe('supportsContext1m', () => {
test('should return true for claude-sonnet-4', () => {
expect(supportsContext1m('claude-sonnet-4')).toBe(true);
});
test('should return true for claude-sonnet-4-5', () => {
expect(supportsContext1m('claude-sonnet-4-5')).toBe(true);
});
test('should return true for claude-sonnet-5 (future)', () => {
expect(supportsContext1m('claude-sonnet-5')).toBe(true);
});
test('should return true for claude-opus-4-6', () => {
expect(supportsContext1m('claude-opus-4-6')).toBe(true);
});
test('should return true for claude-opus-5 (future)', () => {
expect(supportsContext1m('claude-opus-5')).toBe(true);
});
test('should return false for claude-opus-4-5', () => {
expect(supportsContext1m('claude-opus-4-5')).toBe(false);
});
test('should return false for claude-opus-4', () => {
expect(supportsContext1m('claude-opus-4')).toBe(false);
});
test('should return false for claude-3-7-sonnet', () => {
expect(supportsContext1m('claude-3-7-sonnet')).toBe(false);
});
test('should return false for claude-sonnet-3', () => {
expect(supportsContext1m('claude-sonnet-3')).toBe(false);
});
test('should return false for unrelated model', () => {
expect(supportsContext1m('gpt-4o')).toBe(false);
});
test('should return true for claude-4-sonnet (alternate naming)', () => {
expect(supportsContext1m('claude-4-sonnet')).toBe(true);
});
test('should return true for claude-5-sonnet (alternate naming)', () => {
expect(supportsContext1m('claude-5-sonnet')).toBe(true);
});
test('should return true for claude-4-6-opus (alternate naming)', () => {
expect(supportsContext1m('claude-4-6-opus')).toBe(true);
});
test('should return false for claude-3-sonnet (alternate naming, below threshold)', () => {
expect(supportsContext1m('claude-3-sonnet')).toBe(false);
});
test('should return false for claude-4-5-opus (alternate naming, below threshold)', () => {
expect(supportsContext1m('claude-4-5-opus')).toBe(false);
});
});
describe('bedrockInputParser', () => {
describe('Model Matching for Reasoning Configuration', () => {
@ -7,7 +163,7 @@ describe('bedrockInputParser', () => {
const input = {
model: 'anthropic.claude-3-7-sonnet',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.thinkingBudget).toBe(2000);
@ -18,7 +174,7 @@ describe('bedrockInputParser', () => {
const input = {
model: 'anthropic.claude-sonnet-4',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.thinkingBudget).toBe(2000);
@ -28,22 +184,25 @@ describe('bedrockInputParser', () => {
]);
});
test('should match anthropic.claude-opus-5 model without 1M context header', () => {
test('should match anthropic.claude-opus-5 model with adaptive thinking and 1M context', () => {
const input = {
model: 'anthropic.claude-opus-5',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.thinkingBudget).toBe(2000);
expect(additionalFields.anthropic_beta).toEqual(['output-128k-2025-02-19']);
expect(additionalFields.thinking).toEqual({ type: 'adaptive' });
expect(additionalFields.thinkingBudget).toBeUndefined();
expect(additionalFields.anthropic_beta).toEqual([
'output-128k-2025-02-19',
'context-1m-2025-08-07',
]);
});
test('should match anthropic.claude-haiku-6 model without 1M context header', () => {
const input = {
model: 'anthropic.claude-haiku-6',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.thinkingBudget).toBe(2000);
@ -54,7 +213,7 @@ describe('bedrockInputParser', () => {
const input = {
model: 'anthropic.claude-4-sonnet',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.thinkingBudget).toBe(2000);
@ -68,7 +227,7 @@ describe('bedrockInputParser', () => {
const input = {
model: 'anthropic.claude-4.5-sonnet',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.thinkingBudget).toBe(2000);
@ -82,7 +241,7 @@ describe('bedrockInputParser', () => {
const input = {
model: 'anthropic.claude-4-7-sonnet',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.thinkingBudget).toBe(2000);
@ -96,7 +255,7 @@ describe('bedrockInputParser', () => {
const input = {
model: 'anthropic.claude-sonnet-4-20250514-v1:0',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.thinkingBudget).toBe(2000);
@ -110,7 +269,7 @@ describe('bedrockInputParser', () => {
const input = {
model: 'some-other-model',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
expect(result.additionalModelRequestFields).toBeUndefined();
});
@ -118,7 +277,7 @@ describe('bedrockInputParser', () => {
const input = {
model: 'moonshot.kimi-k2-0711-thinking',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as
| Record<string, unknown>
| undefined;
@ -129,7 +288,7 @@ describe('bedrockInputParser', () => {
const input = {
model: 'deepseek.deepseek-r1',
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as
| Record<string, unknown>
| undefined;
@ -141,7 +300,7 @@ describe('bedrockInputParser', () => {
model: 'anthropic.claude-sonnet-4',
thinking: false,
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBeUndefined();
expect(additionalFields.thinkingBudget).toBeUndefined();
@ -157,10 +316,307 @@ describe('bedrockInputParser', () => {
thinking: true,
thinkingBudget: 3000,
};
const result = bedrockInputParser.parse(input) as BedrockConverseInput;
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.thinkingBudget).toBe(3000);
});
});
describe('Opus 4.6 Adaptive Thinking', () => {
test('should default to adaptive thinking for anthropic.claude-opus-4-6-v1', () => {
const input = {
model: 'anthropic.claude-opus-4-6-v1',
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toEqual({ type: 'adaptive' });
expect(additionalFields.thinkingBudget).toBeUndefined();
expect(additionalFields.anthropic_beta).toEqual([
'output-128k-2025-02-19',
'context-1m-2025-08-07',
]);
});
test('should handle cross-region model ID us.anthropic.claude-opus-4-6-v1', () => {
const input = {
model: 'us.anthropic.claude-opus-4-6-v1',
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toEqual({ type: 'adaptive' });
expect(additionalFields.thinkingBudget).toBeUndefined();
expect(additionalFields.anthropic_beta).toEqual([
'output-128k-2025-02-19',
'context-1m-2025-08-07',
]);
});
test('should handle cross-region model ID global.anthropic.claude-opus-4-6-v1', () => {
const input = {
model: 'global.anthropic.claude-opus-4-6-v1',
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toEqual({ type: 'adaptive' });
expect(additionalFields.anthropic_beta).toEqual([
'output-128k-2025-02-19',
'context-1m-2025-08-07',
]);
});
test('should pass effort parameter via output_config for adaptive models', () => {
const input = {
model: 'anthropic.claude-opus-4-6-v1',
effort: 'medium',
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toEqual({ type: 'adaptive' });
expect(additionalFields.output_config).toEqual({ effort: 'medium' });
expect(additionalFields.effort).toBeUndefined();
});
test('should not include output_config when effort is unset (empty string)', () => {
const input = {
model: 'anthropic.claude-opus-4-6-v1',
effort: '',
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toEqual({ type: 'adaptive' });
expect(additionalFields.output_config).toBeUndefined();
});
test('should respect thinking=false for adaptive models', () => {
const input = {
model: 'anthropic.claude-opus-4-6-v1',
thinking: false,
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBeUndefined();
expect(additionalFields.thinkingBudget).toBeUndefined();
expect(additionalFields.anthropic_beta).toEqual([
'output-128k-2025-02-19',
'context-1m-2025-08-07',
]);
});
test('should preserve effort when thinking=false for adaptive models', () => {
const input = {
model: 'anthropic.claude-opus-4-6-v1',
thinking: false,
effort: 'high',
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBeUndefined();
expect(additionalFields.thinkingBudget).toBeUndefined();
expect(additionalFields.output_config).toEqual({ effort: 'high' });
expect(additionalFields.effort).toBeUndefined();
});
test('should strip effort for non-adaptive thinking models', () => {
const input = {
model: 'anthropic.claude-sonnet-4-5-20250929-v1:0',
effort: 'high',
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.thinkingBudget).toBe(2000);
expect(additionalFields.effort).toBeUndefined();
expect(additionalFields.output_config).toBeUndefined();
});
test('should not include effort for Opus 4.5 (non-adaptive)', () => {
const input = {
model: 'anthropic.claude-opus-4-5-v1:0',
effort: 'low',
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toBe(true);
expect(additionalFields.effort).toBeUndefined();
expect(additionalFields.output_config).toBeUndefined();
});
test('should support max effort for Opus 4.6', () => {
const input = {
model: 'anthropic.claude-opus-4-6-v1',
effort: 'max',
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const additionalFields = result.additionalModelRequestFields as Record<string, unknown>;
expect(additionalFields.thinking).toEqual({ type: 'adaptive' });
expect(additionalFields.output_config).toEqual({ effort: 'max' });
});
});
describe('bedrockOutputParser with configureThinking', () => {
test('should preserve adaptive thinking config and set default maxTokens', () => {
const parsed = bedrockInputParser.parse({
model: 'anthropic.claude-opus-4-6-v1',
}) as Record<string, unknown>;
const output = bedrockOutputParser(parsed as Record<string, unknown>);
const amrf = output.additionalModelRequestFields as Record<string, unknown>;
expect(amrf.thinking).toEqual({ type: 'adaptive' });
expect(output.maxTokens).toBe(16000);
expect(output.maxOutputTokens).toBeUndefined();
});
test('should respect user-provided maxTokens for adaptive model', () => {
const parsed = bedrockInputParser.parse({
model: 'anthropic.claude-opus-4-6-v1',
maxTokens: 32000,
}) as Record<string, unknown>;
const output = bedrockOutputParser(parsed as Record<string, unknown>);
expect(output.maxTokens).toBe(32000);
});
test('should convert thinking=true to enabled config for non-adaptive models', () => {
const parsed = bedrockInputParser.parse({
model: 'anthropic.claude-sonnet-4-5-20250929-v1:0',
}) as Record<string, unknown>;
const output = bedrockOutputParser(parsed as Record<string, unknown>);
const amrf = output.additionalModelRequestFields as Record<string, unknown>;
expect(amrf.thinking).toEqual({ type: 'enabled', budget_tokens: 2000 });
expect(output.maxTokens).toBe(8192);
});
test('should pass output_config through for adaptive model with effort', () => {
const parsed = bedrockInputParser.parse({
model: 'anthropic.claude-opus-4-6-v1',
effort: 'low',
}) as Record<string, unknown>;
const output = bedrockOutputParser(parsed as Record<string, unknown>);
const amrf = output.additionalModelRequestFields as Record<string, unknown>;
expect(amrf.thinking).toEqual({ type: 'adaptive' });
expect(amrf.output_config).toEqual({ effort: 'low' });
});
test('should use adaptive default maxTokens (16000) over maxOutputTokens for adaptive models', () => {
const parsed = bedrockInputParser.parse({
model: 'anthropic.claude-opus-4-6-v1',
}) as Record<string, unknown>;
parsed.maxOutputTokens = undefined;
(parsed as Record<string, unknown>).maxTokens = undefined;
const output = bedrockOutputParser(parsed as Record<string, unknown>);
expect(output.maxTokens).toBe(16000);
});
test('should use enabled default maxTokens (8192) for non-adaptive thinking models', () => {
const parsed = bedrockInputParser.parse({
model: 'anthropic.claude-sonnet-4-5-20250929-v1:0',
}) as Record<string, unknown>;
parsed.maxOutputTokens = undefined;
(parsed as Record<string, unknown>).maxTokens = undefined;
const output = bedrockOutputParser(parsed as Record<string, unknown>);
expect(output.maxTokens).toBe(8192);
});
test('should use default thinking budget (2000) when no custom budget is set', () => {
const parsed = bedrockInputParser.parse({
model: 'anthropic.claude-3-7-sonnet',
}) as Record<string, unknown>;
const output = bedrockOutputParser(parsed as Record<string, unknown>);
const amrf = output.additionalModelRequestFields as Record<string, unknown>;
const thinking = amrf.thinking as { type: string; budget_tokens: number };
expect(thinking.budget_tokens).toBe(2000);
});
test('should override default thinking budget with custom value', () => {
const parsed = bedrockInputParser.parse({
model: 'anthropic.claude-3-7-sonnet',
thinkingBudget: 5000,
maxTokens: 8192,
}) as Record<string, unknown>;
const output = bedrockOutputParser(parsed as Record<string, unknown>);
const amrf = output.additionalModelRequestFields as Record<string, unknown>;
const thinking = amrf.thinking as { type: string; budget_tokens: number };
expect(thinking.budget_tokens).toBe(5000);
});
test('should remove additionalModelRequestFields when thinking disabled and no other fields', () => {
const parsed = bedrockInputParser.parse({
model: 'some-other-model',
}) as Record<string, unknown>;
const output = bedrockOutputParser(parsed as Record<string, unknown>);
expect(output.additionalModelRequestFields).toBeUndefined();
});
});
describe('Model switching cleanup', () => {
test('should strip anthropic_beta when switching from Anthropic to non-Anthropic model', () => {
const staleConversationData = {
model: 'openai.gpt-oss-120b-1:0',
promptCache: true,
additionalModelRequestFields: {
anthropic_beta: ['output-128k-2025-02-19', 'context-1m-2025-08-07'],
thinking: { type: 'adaptive' },
output_config: { effort: 'high' },
},
};
const result = bedrockInputParser.parse(staleConversationData) as Record<string, unknown>;
const amrf = result.additionalModelRequestFields as Record<string, unknown> | undefined;
expect(amrf?.anthropic_beta).toBeUndefined();
expect(amrf?.thinking).toBeUndefined();
expect(amrf?.output_config).toBeUndefined();
expect(result.promptCache).toBeUndefined();
});
test('should strip promptCache when switching from Claude to non-Claude/Nova model', () => {
const staleConversationData = {
model: 'deepseek.deepseek-r1',
promptCache: true,
};
const result = bedrockInputParser.parse(staleConversationData) as Record<string, unknown>;
expect(result.promptCache).toBeUndefined();
});
test('should preserve promptCache for Claude models', () => {
const input = {
model: 'anthropic.claude-sonnet-4-20250514-v1:0',
promptCache: true,
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
expect(result.promptCache).toBe(true);
});
test('should preserve promptCache for Nova models', () => {
const input = {
model: 'amazon.nova-pro-v1:0',
promptCache: true,
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
expect(result.promptCache).toBe(true);
});
test('should strip stale thinking config from additionalModelRequestFields for non-Anthropic models', () => {
const staleConversationData = {
model: 'moonshot.kimi-k2-0711-thinking',
additionalModelRequestFields: {
thinking: { type: 'enabled', budget_tokens: 2000 },
thinkingBudget: 2000,
anthropic_beta: ['output-128k-2025-02-19'],
},
};
const result = bedrockInputParser.parse(staleConversationData) as Record<string, unknown>;
const amrf = result.additionalModelRequestFields as Record<string, unknown> | undefined;
expect(amrf?.anthropic_beta).toBeUndefined();
expect(amrf?.thinking).toBeUndefined();
expect(amrf?.thinkingBudget).toBeUndefined();
});
test('should not strip anthropic_beta when staying on an Anthropic model', () => {
const input = {
model: 'anthropic.claude-opus-4-6-v1',
};
const result = bedrockInputParser.parse(input) as Record<string, unknown>;
const amrf = result.additionalModelRequestFields as Record<string, unknown>;
expect(amrf.anthropic_beta).toBeDefined();
expect(Array.isArray(amrf.anthropic_beta)).toBe(true);
});
});
});

View file

@ -1,10 +1,12 @@
import { z } from 'zod';
import * as s from './schemas';
type ThinkingConfig = {
type: 'enabled';
budget_tokens: number;
};
const DEFAULT_ENABLED_MAX_TOKENS = 8192;
const DEFAULT_ADAPTIVE_MAX_TOKENS = 16000;
const DEFAULT_THINKING_BUDGET = 2000;
type ThinkingConfig = { type: 'enabled'; budget_tokens: number } | { type: 'adaptive' };
type AnthropicReasoning = {
thinking?: ThinkingConfig | boolean;
thinkingBudget?: number;
@ -15,6 +17,64 @@ type AnthropicInput = BedrockConverseInput & {
AnthropicReasoning;
};
/** Extracts opus major/minor version from both naming formats */
function parseOpusVersion(model: string): { major: number; minor: number } | null {
const nameFirst = model.match(/claude-opus[-.]?(\d+)(?:[-.](\d+))?/);
if (nameFirst) {
return {
major: parseInt(nameFirst[1], 10),
minor: nameFirst[2] != null ? parseInt(nameFirst[2], 10) : 0,
};
}
const numFirst = model.match(/claude-(\d+)(?:[-.](\d+))?-opus/);
if (numFirst) {
return {
major: parseInt(numFirst[1], 10),
minor: numFirst[2] != null ? parseInt(numFirst[2], 10) : 0,
};
}
return null;
}
/** Extracts sonnet major version from both naming formats */
function parseSonnetVersion(model: string): number | null {
const nameFirst = model.match(/claude-sonnet[-.]?(\d+)/);
if (nameFirst) {
return parseInt(nameFirst[1], 10);
}
const numFirst = model.match(/claude-(\d+)(?:[-.]?\d+)?-sonnet/);
if (numFirst) {
return parseInt(numFirst[1], 10);
}
return null;
}
/** Checks if a model supports adaptive thinking (Opus 4.6+, Sonnet 5+) */
export function supportsAdaptiveThinking(model: string): boolean {
const opus = parseOpusVersion(model);
if (opus && (opus.major > 4 || (opus.major === 4 && opus.minor >= 6))) {
return true;
}
const sonnet = parseSonnetVersion(model);
if (sonnet != null && sonnet >= 5) {
return true;
}
return false;
}
/** Checks if a model qualifies for the context-1m beta header (Sonnet 4+, Opus 4.6+, Opus 5+) */
export function supportsContext1m(model: string): boolean {
const sonnet = parseSonnetVersion(model);
if (sonnet != null && sonnet >= 4) {
return true;
}
const opus = parseOpusVersion(model);
if (opus && (opus.major > 4 || (opus.major === 4 && opus.minor >= 6))) {
return true;
}
return false;
}
/**
* Gets the appropriate anthropic_beta headers for Bedrock Anthropic models.
* Bedrock uses `anthropic_beta` (with underscore) in additionalModelRequestFields.
@ -38,7 +98,7 @@ function getBedrockAnthropicBetaHeaders(model: string): string[] {
betaHeaders.push('output-128k-2025-02-19');
}
if (isSonnet4PlusModel) {
if (isSonnet4PlusModel || supportsAdaptiveThinking(model)) {
betaHeaders.push('context-1m-2025-08-07');
}
@ -67,6 +127,7 @@ export const bedrockInputSchema = s.tConversationSchema
stop: true,
thinking: true,
thinkingBudget: true,
effort: true,
promptCache: true,
/* Catch-all fields */
topK: true,
@ -75,10 +136,11 @@ export const bedrockInputSchema = s.tConversationSchema
.transform((obj) => {
if ((obj as AnthropicInput).additionalModelRequestFields?.thinking != null) {
const _obj = obj as AnthropicInput;
obj.thinking = !!_obj.additionalModelRequestFields.thinking;
const thinking = _obj.additionalModelRequestFields.thinking;
obj.thinking = !!thinking;
obj.thinkingBudget =
typeof _obj.additionalModelRequestFields.thinking === 'object'
? (_obj.additionalModelRequestFields.thinking as ThinkingConfig)?.budget_tokens
typeof thinking === 'object' && 'budget_tokens' in thinking
? thinking.budget_tokens
: undefined;
delete obj.additionalModelRequestFields;
}
@ -109,6 +171,7 @@ export const bedrockInputParser = s.tConversationSchema
stop: true,
thinking: true,
thinkingBudget: true,
effort: true,
promptCache: true,
/* Catch-all fields */
topK: true,
@ -157,34 +220,77 @@ export const bedrockInputParser = s.tConversationSchema
typedData.model,
))
) {
if (additionalFields.thinking === undefined) {
additionalFields.thinking = true;
} else if (additionalFields.thinking === false) {
delete additionalFields.thinking;
delete additionalFields.thinkingBudget;
const isAdaptive = supportsAdaptiveThinking(typedData.model as string);
if (isAdaptive) {
const effort = additionalFields.effort;
if (effort && typeof effort === 'string' && effort !== '') {
additionalFields.output_config = { effort };
}
delete additionalFields.effort;
if (additionalFields.thinking === false) {
delete additionalFields.thinking;
delete additionalFields.thinkingBudget;
} else {
additionalFields.thinking = { type: 'adaptive' };
delete additionalFields.thinkingBudget;
}
} else {
if (additionalFields.thinking === undefined) {
additionalFields.thinking = true;
} else if (additionalFields.thinking === false) {
delete additionalFields.thinking;
delete additionalFields.thinkingBudget;
}
if (additionalFields.thinking === true && additionalFields.thinkingBudget === undefined) {
additionalFields.thinkingBudget = DEFAULT_THINKING_BUDGET;
}
delete additionalFields.effort;
}
if (additionalFields.thinking === true && additionalFields.thinkingBudget === undefined) {
additionalFields.thinkingBudget = 2000;
}
if (typedData.model.includes('anthropic.')) {
const betaHeaders = getBedrockAnthropicBetaHeaders(typedData.model);
if ((typedData.model as string).includes('anthropic.')) {
const betaHeaders = getBedrockAnthropicBetaHeaders(typedData.model as string);
if (betaHeaders.length > 0) {
additionalFields.anthropic_beta = betaHeaders;
}
}
} else if (additionalFields.thinking != null || additionalFields.thinkingBudget != null) {
} else {
delete additionalFields.thinking;
delete additionalFields.thinkingBudget;
delete additionalFields.effort;
delete additionalFields.output_config;
delete additionalFields.anthropic_beta;
}
const isAnthropicModel =
typeof typedData.model === 'string' && typedData.model.includes('anthropic.');
/** Strip stale anthropic_beta from previously-persisted additionalModelRequestFields */
if (
!isAnthropicModel &&
typeof typedData.additionalModelRequestFields === 'object' &&
typedData.additionalModelRequestFields != null
) {
const amrf = typedData.additionalModelRequestFields as Record<string, unknown>;
delete amrf.anthropic_beta;
delete amrf.thinking;
delete amrf.thinkingBudget;
delete amrf.effort;
delete amrf.output_config;
}
/** Default promptCache for claude and nova models, if not defined */
if (
typeof typedData.model === 'string' &&
(typedData.model.includes('claude') || typedData.model.includes('nova')) &&
typedData.promptCache === undefined
(typedData.model.includes('claude') || typedData.model.includes('nova'))
) {
typedData.promptCache = true;
if (typedData.promptCache === undefined) {
typedData.promptCache = true;
}
} else if (typedData.promptCache === true) {
typedData.promptCache = undefined;
}
if (Object.keys(additionalFields).length > 0) {
@ -212,20 +318,34 @@ export const bedrockInputParser = s.tConversationSchema
*/
function configureThinking(data: AnthropicInput): AnthropicInput {
const updatedData = { ...data };
if (updatedData.additionalModelRequestFields?.thinking === true) {
updatedData.maxTokens = updatedData.maxTokens ?? updatedData.maxOutputTokens ?? 8192;
const thinking = updatedData.additionalModelRequestFields?.thinking;
if (thinking === true) {
updatedData.maxTokens =
updatedData.maxTokens ?? updatedData.maxOutputTokens ?? DEFAULT_ENABLED_MAX_TOKENS;
delete updatedData.maxOutputTokens;
const thinkingConfig: AnthropicReasoning['thinking'] = {
const thinkingConfig: ThinkingConfig = {
type: 'enabled',
budget_tokens: updatedData.additionalModelRequestFields.thinkingBudget ?? 2000,
budget_tokens:
updatedData.additionalModelRequestFields?.thinkingBudget ?? DEFAULT_THINKING_BUDGET,
};
if (thinkingConfig.budget_tokens > updatedData.maxTokens) {
thinkingConfig.budget_tokens = Math.floor(updatedData.maxTokens * 0.9);
}
updatedData.additionalModelRequestFields.thinking = thinkingConfig;
delete updatedData.additionalModelRequestFields.thinkingBudget;
updatedData.additionalModelRequestFields!.thinking = thinkingConfig;
delete updatedData.additionalModelRequestFields!.thinkingBudget;
} else if (
typeof thinking === 'object' &&
thinking != null &&
(thinking as { type: string }).type === 'adaptive'
) {
updatedData.maxTokens =
updatedData.maxTokens ?? updatedData.maxOutputTokens ?? DEFAULT_ADAPTIVE_MAX_TOKENS;
delete updatedData.maxOutputTokens;
delete updatedData.additionalModelRequestFields!.thinkingBudget;
}
return updatedData;
}
@ -268,8 +388,8 @@ export const bedrockOutputParser = (data: Record<string, unknown>) => {
}
result = configureThinking(result as AnthropicInput);
// Remove additionalModelRequestFields from the result if it doesn't thinking config
if ((result as AnthropicInput).additionalModelRequestFields?.thinking == null) {
const amrf = result.additionalModelRequestFields as Record<string, unknown> | undefined;
if (!amrf || Object.keys(amrf).length === 0) {
delete result.additionalModelRequestFields;
}

View file

@ -1133,6 +1133,7 @@ const sharedOpenAIModels = [
];
const sharedAnthropicModels = [
'claude-opus-4-6',
'claude-sonnet-4-5',
'claude-sonnet-4-5-20250929',
'claude-haiku-4-5',
@ -1153,6 +1154,7 @@ const sharedAnthropicModels = [
];
export const bedrockModels = [
'anthropic.claude-opus-4-6-v1',
'anthropic.claude-sonnet-4-5-20250929-v1:0',
'anthropic.claude-haiku-4-5-20251001-v1:0',
'anthropic.claude-opus-4-1-20250805-v1:0',

View file

@ -5,6 +5,7 @@ import {
openAISettings,
googleSettings,
ReasoningEffort,
AnthropicEffort,
ReasoningSummary,
BedrockProviders,
anthropicSettings,
@ -445,6 +446,26 @@ const anthropic: Record<string, SettingDefinition> = {
showDefault: false,
columnSpan: 2,
},
effort: {
key: 'effort',
label: 'com_endpoint_effort',
labelCode: true,
description: 'com_endpoint_anthropic_effort',
descriptionCode: true,
type: 'enum',
default: anthropicSettings.effort.default,
component: 'slider',
options: anthropicSettings.effort.options,
enumMappings: {
[AnthropicEffort.unset]: 'com_ui_auto',
[AnthropicEffort.low]: 'com_ui_low',
[AnthropicEffort.medium]: 'com_ui_medium',
[AnthropicEffort.high]: 'com_ui_high',
[AnthropicEffort.max]: 'com_ui_max',
},
optionType: 'model',
columnSpan: 4,
},
};
const bedrock: Record<string, SettingDefinition> = {
@ -734,6 +755,7 @@ const anthropicConfig: SettingsConfiguration = [
anthropic.promptCache,
anthropic.thinking,
anthropic.thinkingBudget,
anthropic.effort,
anthropic.web_search,
librechat.fileTokenLimit,
];
@ -754,6 +776,7 @@ const anthropicCol2: SettingsConfiguration = [
anthropic.promptCache,
anthropic.thinking,
anthropic.thinkingBudget,
anthropic.effort,
anthropic.web_search,
librechat.fileTokenLimit,
];
@ -772,6 +795,7 @@ const bedrockAnthropic: SettingsConfiguration = [
bedrock.promptCache,
anthropic.thinking,
anthropic.thinkingBudget,
anthropic.effort,
librechat.fileTokenLimit,
];
@ -829,6 +853,7 @@ const bedrockAnthropicCol2: SettingsConfiguration = [
bedrock.promptCache,
anthropic.thinking,
anthropic.thinkingBudget,
anthropic.effort,
librechat.fileTokenLimit,
];

View file

@ -74,81 +74,83 @@ describe('anthropicSettings', () => {
});
});
describe('Claude Opus 4.5+ models (64K limit - future-proof)', () => {
describe('Claude Opus 4.5 models (64K limit)', () => {
it('should return 64K for claude-opus-4-5', () => {
expect(reset('claude-opus-4-5')).toBe(64000);
});
it('should return 64K for claude-opus-4-6', () => {
expect(reset('claude-opus-4-6')).toBe(64000);
});
it('should return 64K for claude-opus-4-7', () => {
expect(reset('claude-opus-4-7')).toBe(64000);
});
it('should return 64K for claude-opus-4-8', () => {
expect(reset('claude-opus-4-8')).toBe(64000);
});
it('should return 64K for claude-opus-4-9', () => {
expect(reset('claude-opus-4-9')).toBe(64000);
});
it('should return 64K for claude-opus-4.5', () => {
expect(reset('claude-opus-4.5')).toBe(64000);
});
});
it('should return 64K for claude-opus-4.6', () => {
expect(reset('claude-opus-4.6')).toBe(64000);
describe('Claude Opus 4.6+ models (128K limit - future-proof)', () => {
it('should return 128K for claude-opus-4-6', () => {
expect(reset('claude-opus-4-6')).toBe(128000);
});
it('should return 128K for claude-opus-4.6', () => {
expect(reset('claude-opus-4.6')).toBe(128000);
});
it('should return 128K for claude-opus-4-7', () => {
expect(reset('claude-opus-4-7')).toBe(128000);
});
it('should return 128K for claude-opus-4-8', () => {
expect(reset('claude-opus-4-8')).toBe(128000);
});
it('should return 128K for claude-opus-4-9', () => {
expect(reset('claude-opus-4-9')).toBe(128000);
});
});
describe('Claude Opus 4.10+ models (double-digit minor versions)', () => {
it('should return 64K for claude-opus-4-10', () => {
expect(reset('claude-opus-4-10')).toBe(64000);
it('should return 128K for claude-opus-4-10', () => {
expect(reset('claude-opus-4-10')).toBe(128000);
});
it('should return 64K for claude-opus-4-11', () => {
expect(reset('claude-opus-4-11')).toBe(64000);
it('should return 128K for claude-opus-4-11', () => {
expect(reset('claude-opus-4-11')).toBe(128000);
});
it('should return 64K for claude-opus-4-15', () => {
expect(reset('claude-opus-4-15')).toBe(64000);
it('should return 128K for claude-opus-4-15', () => {
expect(reset('claude-opus-4-15')).toBe(128000);
});
it('should return 64K for claude-opus-4-20', () => {
expect(reset('claude-opus-4-20')).toBe(64000);
it('should return 128K for claude-opus-4-20', () => {
expect(reset('claude-opus-4-20')).toBe(128000);
});
it('should return 64K for claude-opus-4.10', () => {
expect(reset('claude-opus-4.10')).toBe(64000);
it('should return 128K for claude-opus-4.10', () => {
expect(reset('claude-opus-4.10')).toBe(128000);
});
});
describe('Claude Opus 5+ models (future major versions)', () => {
it('should return 64K for claude-opus-5', () => {
expect(reset('claude-opus-5')).toBe(64000);
it('should return 128K for claude-opus-5', () => {
expect(reset('claude-opus-5')).toBe(128000);
});
it('should return 64K for claude-opus-6', () => {
expect(reset('claude-opus-6')).toBe(64000);
it('should return 128K for claude-opus-6', () => {
expect(reset('claude-opus-6')).toBe(128000);
});
it('should return 64K for claude-opus-7', () => {
expect(reset('claude-opus-7')).toBe(64000);
it('should return 128K for claude-opus-7', () => {
expect(reset('claude-opus-7')).toBe(128000);
});
it('should return 64K for claude-opus-9', () => {
expect(reset('claude-opus-9')).toBe(64000);
it('should return 128K for claude-opus-9', () => {
expect(reset('claude-opus-9')).toBe(128000);
});
it('should return 64K for claude-opus-5-0', () => {
expect(reset('claude-opus-5-0')).toBe(64000);
it('should return 128K for claude-opus-5-0', () => {
expect(reset('claude-opus-5-0')).toBe(128000);
});
it('should return 64K for claude-opus-5.0', () => {
expect(reset('claude-opus-5.0')).toBe(64000);
it('should return 128K for claude-opus-5.0', () => {
expect(reset('claude-opus-5.0')).toBe(128000);
});
});
@ -157,8 +159,8 @@ describe('anthropicSettings', () => {
expect(reset('claude-opus-4-5-20250420')).toBe(64000);
});
it('should return 64K for claude-opus-4-6-20260101', () => {
expect(reset('claude-opus-4-6-20260101')).toBe(64000);
it('should return 128K for claude-opus-4-6-20260101', () => {
expect(reset('claude-opus-4-6-20260101')).toBe(128000);
});
it('should return 32K for claude-opus-4-1-20250805', () => {
@ -234,8 +236,8 @@ describe('anthropicSettings', () => {
it('should match claude-opus45 (no separator after opus)', () => {
// The regex allows optional separators, so "45" can follow directly
// In practice, Anthropic uses separators, but regex is permissive
expect(reset('claude-opus45')).toBe(64000);
// "45" is treated as major version 45 (>= 5), so it gets 128K
expect(reset('claude-opus45')).toBe(128000);
});
});
});
@ -278,16 +280,28 @@ describe('anthropicSettings', () => {
expect(set(50000, 'claude-opus-4-5')).toBe(50000);
});
it('should cap at 64K for claude-opus-4-6', () => {
expect(set(80000, 'claude-opus-4-6')).toBe(64000);
it('should allow 80K for claude-opus-4-6 (128K cap)', () => {
expect(set(80000, 'claude-opus-4-6')).toBe(80000);
});
it('should cap at 64K for claude-opus-5', () => {
expect(set(100000, 'claude-opus-5')).toBe(64000);
it('should cap at 128K for claude-opus-4-6', () => {
expect(set(150000, 'claude-opus-4-6')).toBe(128000);
});
it('should cap at 64K for claude-opus-4-10', () => {
expect(set(100000, 'claude-opus-4-10')).toBe(64000);
it('should cap at 128K for claude-opus-5', () => {
expect(set(150000, 'claude-opus-5')).toBe(128000);
});
it('should allow 100K for claude-opus-5', () => {
expect(set(100000, 'claude-opus-5')).toBe(100000);
});
it('should cap at 128K for claude-opus-4-10', () => {
expect(set(150000, 'claude-opus-4-10')).toBe(128000);
});
it('should allow 100K for claude-opus-4-10', () => {
expect(set(100000, 'claude-opus-4-10')).toBe(100000);
});
});

View file

@ -173,6 +173,14 @@ export enum ReasoningEffort {
xhigh = 'xhigh',
}
export enum AnthropicEffort {
unset = '',
low = 'low',
medium = 'medium',
high = 'high',
max = 'max',
}
export enum ReasoningSummary {
none = '',
auto = 'auto',
@ -201,6 +209,7 @@ export const imageDetailValue = {
export const eImageDetailSchema = z.nativeEnum(ImageDetail);
export const eReasoningEffortSchema = z.nativeEnum(ReasoningEffort);
export const eAnthropicEffortSchema = z.nativeEnum(AnthropicEffort);
export const eReasoningSummarySchema = z.nativeEnum(ReasoningSummary);
export const eVerbositySchema = z.nativeEnum(Verbosity);
@ -382,6 +391,10 @@ export const anthropicSettings = {
step: 1 as const,
default: DEFAULT_MAX_OUTPUT,
reset: (modelName: string) => {
if (/claude-opus[-.]?(?:4[-.]?(?:[6-9]|\d{2,})|[5-9]|\d{2,})/.test(modelName)) {
return ANTHROPIC_MAX_OUTPUT;
}
if (/claude-(?:sonnet|haiku)[-.]?[4-9]/.test(modelName)) {
return CLAUDE_4_64K_MAX_OUTPUT;
}
@ -397,6 +410,13 @@ export const anthropicSettings = {
return DEFAULT_MAX_OUTPUT;
},
set: (value: number, modelName: string) => {
if (/claude-opus[-.]?(?:4[-.]?(?:[6-9]|\d{2,})|[5-9]|\d{2,})/.test(modelName)) {
if (value > ANTHROPIC_MAX_OUTPUT) {
return ANTHROPIC_MAX_OUTPUT;
}
return value;
}
if (/claude-(?:sonnet|haiku)[-.]?[4-9]/.test(modelName) && value > CLAUDE_4_64K_MAX_OUTPUT) {
return CLAUDE_4_64K_MAX_OUTPUT;
}
@ -445,6 +465,16 @@ export const anthropicSettings = {
default: LEGACY_ANTHROPIC_MAX_OUTPUT,
},
},
effort: {
default: AnthropicEffort.unset,
options: [
AnthropicEffort.unset,
AnthropicEffort.low,
AnthropicEffort.medium,
AnthropicEffort.high,
AnthropicEffort.max,
],
},
web_search: {
default: false as const,
},
@ -703,6 +733,8 @@ export const tConversationSchema = z.object({
verbosity: eVerbositySchema.optional().nullable(),
/* OpenAI: use Responses API */
useResponsesApi: z.boolean().optional(),
/* Anthropic: Effort control */
effort: eAnthropicEffortSchema.optional().nullable(),
/* OpenAI Responses API / Anthropic API / Google API */
web_search: z.boolean().optional(),
/* disable streaming */
@ -825,6 +857,7 @@ export const tQueryParamsSchema = tConversationSchema
promptCache: true,
thinking: true,
thinkingBudget: true,
effort: true,
/** @endpoints bedrock */
region: true,
/** @endpoints bedrock */
@ -1122,6 +1155,7 @@ export const anthropicBaseSchema = tConversationSchema.pick({
promptCache: true,
thinking: true,
thinkingBudget: true,
effort: true,
artifacts: true,
iconURL: true,
greeting: true,

View file

@ -52,6 +52,7 @@ export type TEndpointOption = Pick<
| 'promptCache'
| 'thinking'
| 'thinkingBudget'
| 'effort'
// Assistant/Agent fields
| 'assistant_id'
| 'agent_id'

View file

@ -83,6 +83,9 @@ export const conversationPreset = {
thinkingBudget: {
type: Number,
},
effort: {
type: String,
},
system: {
type: String,
},

View file

@ -30,6 +30,7 @@ export interface IPreset extends Document {
promptCache?: boolean;
thinking?: boolean;
thinkingBudget?: number;
effort?: string;
system?: string;
resendFiles?: boolean;
imageDetail?: string;

View file

@ -28,6 +28,7 @@ export interface IConversation extends Document {
promptCache?: boolean;
thinking?: boolean;
thinkingBudget?: number;
effort?: string;
system?: string;
resendFiles?: boolean;
imageDetail?: string;