@juspay/neurolink 13.16.2 → 13.17.1
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 +2 -2
- package/dist/adapters/providerImageAdapter.js +29 -495
- package/dist/browser/neurolink.min.js +465 -471
- package/dist/constants/contextWindows.js +13 -328
- package/dist/constants/enums.d.ts +1 -0
- package/dist/constants/enums.js +2 -1
- package/dist/context/anthropicLoopGuard.d.ts +1 -1
- package/dist/context/anthropicLoopGuard.js +2 -1
- package/dist/core/constants.js +6 -53
- package/dist/core/geminiLoopAdapter.js +8 -6
- package/dist/core/modules/structuredOutputPolicy.d.ts +0 -21
- package/dist/core/modules/structuredOutputPolicy.js +4 -54
- package/dist/core/nativeGenerateLoop.js +5 -0
- package/dist/factories/providerDescriptors.js +3 -2
- package/dist/factories/providerRegistry.js +3 -2
- package/dist/models/manifests/anthropic.d.ts +1 -1
- package/dist/models/manifests/anthropic.js +1 -1
- package/dist/models/manifests/azure.js +9 -9
- package/dist/models/manifests/ollama.js +13 -0
- package/dist/models/manifests/openai.d.ts +1 -1
- package/dist/models/manifests/openai.js +1 -1
- package/dist/models/modelRegistry.js +25 -42
- package/dist/neurolink.js +1 -0
- package/dist/providers/amazonBedrock/client.js +9 -37
- package/dist/providers/amazonBedrock/loopAdapter.js +3 -11
- package/dist/providers/amazonSagemaker.js +6 -0
- package/dist/providers/anthropic/client.js +57 -100
- package/dist/providers/anthropic/loopAdapter.js +24 -22
- package/dist/providers/anthropic/structuredOutput.d.ts +0 -2
- package/dist/providers/anthropic/structuredOutput.js +3 -5
- package/dist/providers/azureOpenai.js +4 -22
- package/dist/providers/catalog/loader.js +12 -25
- package/dist/providers/cohere.js +5 -30
- package/dist/providers/googleAiStudio/client.js +12 -61
- package/dist/providers/googleNativeGemini3/utils.js +43 -102
- package/dist/providers/googleVertex/client.d.ts +7 -0
- package/dist/providers/googleVertex/client.js +150 -192
- package/dist/providers/litellm/client.js +10 -50
- package/dist/providers/llamaCpp.js +4 -15
- package/dist/providers/lmStudio.js +9 -14
- package/dist/providers/nvidiaNim/client.js +4 -62
- package/dist/providers/ollama/client.js +14 -54
- package/dist/providers/ollama/constants.d.ts +1 -3
- package/dist/providers/ollama/constants.js +2 -3
- package/dist/providers/openAI/client.js +5 -57
- package/dist/providers/openRouter/client.js +4 -65
- package/dist/providers/openaiChatCompletionsBase.js +53 -62
- package/dist/providers/openaiChatCompletionsClient.js +17 -57
- package/dist/providers/openaiCompatible/client.js +9 -36
- package/dist/providers/rules/README.md +100 -0
- package/dist/providers/rules/anthropic.json +108 -0
- package/dist/providers/rules/azure.json +13 -0
- package/dist/providers/rules/bedrock.json +48 -0
- package/dist/providers/rules/cohere.json +32 -0
- package/dist/providers/rules/credentials.json +34 -0
- package/dist/providers/rules/errorRules.d.ts +17 -0
- package/dist/providers/rules/errorRules.js +197 -0
- package/dist/providers/rules/errorSignals.d.ts +2 -0
- package/dist/providers/rules/errorSignals.js +28 -0
- package/dist/providers/rules/fallbackModel.d.ts +4 -0
- package/dist/providers/rules/fallbackModel.js +21 -0
- package/dist/providers/rules/finalResultTool.d.ts +11 -0
- package/dist/providers/rules/finalResultTool.js +17 -0
- package/dist/providers/rules/finishReasons.d.ts +10 -0
- package/dist/providers/rules/finishReasons.js +28 -0
- package/dist/providers/rules/gemini.json +92 -0
- package/dist/providers/rules/google-ai.json +55 -0
- package/dist/providers/rules/limits.json +338 -0
- package/dist/providers/rules/litellm.json +36 -0
- package/dist/providers/rules/llamacpp.json +23 -0
- package/dist/providers/rules/lm-studio.json +21 -0
- package/dist/providers/rules/model-families.json +115 -0
- package/dist/providers/rules/modelFamilies.d.ts +10 -0
- package/dist/providers/rules/modelFamilies.js +45 -0
- package/dist/providers/rules/nvidia-nim.json +43 -0
- package/dist/providers/rules/ollama.json +37 -0
- package/dist/providers/rules/openai-chat.json +66 -0
- package/dist/providers/rules/openai-compatible.json +31 -0
- package/dist/providers/rules/openai.json +38 -0
- package/dist/providers/rules/openrouter.json +57 -0
- package/dist/providers/rules/proxy.json +44 -0
- package/dist/providers/rules/registry.d.ts +7 -0
- package/dist/providers/rules/registry.js +76 -0
- package/dist/providers/rules/requestDefaults.d.ts +7 -0
- package/dist/providers/rules/requestDefaults.js +9 -0
- package/dist/providers/rules/requestFields.d.ts +21 -0
- package/dist/providers/rules/requestFields.js +42 -0
- package/dist/providers/rules/sagemaker.json +88 -0
- package/dist/providers/rules/schema.d.ts +242 -0
- package/dist/providers/rules/schema.js +359 -0
- package/dist/providers/rules/structured-output.json +36 -0
- package/dist/providers/rules/thinkingLimits.d.ts +7 -0
- package/dist/providers/rules/thinkingLimits.js +9 -0
- package/dist/providers/rules/toolRules.d.ts +16 -0
- package/dist/providers/rules/toolRules.js +95 -0
- package/dist/providers/rules/usage.json +51 -0
- package/dist/providers/rules/vertex.json +65 -0
- package/dist/providers/rules/vision.json +505 -0
- package/dist/providers/rules/wireUsage.d.ts +38 -0
- package/dist/providers/rules/wireUsage.js +82 -0
- package/dist/providers/sagemaker/language-model.js +6 -33
- package/dist/providers/sagemaker/parsers.js +13 -48
- package/dist/providers/sagemaker/streaming.js +9 -16
- package/dist/proxy/claudeFormat.js +3 -16
- package/dist/proxy/geminiFormat.js +3 -9
- package/dist/proxy/openaiFormat.js +3 -16
- package/dist/types/generate.d.ts +2 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +2 -0
- package/dist/types/providerRules.d.ts +414 -0
- package/dist/types/providerRules.js +10 -0
- package/dist/utils/errorClassifier.d.ts +2 -2
- package/dist/utils/errorClassifier.js +3 -2
- package/dist/utils/modelDetection.d.ts +1 -1
- package/dist/utils/modelDetection.js +30 -71
- package/dist/utils/providerConfig.d.ts +10 -9
- package/dist/utils/providerConfig.js +26 -25
- package/dist/utils/providerHealth.js +1 -0
- package/dist/utils/thinkingConfig.d.ts +1 -1
- package/dist/utils/thinkingConfig.js +8 -8
- package/dist/utils/tokenUtils.d.ts +12 -38
- package/dist/utils/tokenUtils.js +44 -127
- package/docs-site/static/search-index.json +5 -5
- package/package.json +2 -1
- package/dist/providers/localRuntimeOpenAICompat.d.ts +0 -16
- package/dist/providers/localRuntimeOpenAICompat.js +0 -26
|
@@ -12,8 +12,7 @@ import { getModelCapabilities, getRecommendedModelForTier, isModelAvailableForTi
|
|
|
12
12
|
import { createOAuthFetch } from "../../proxy/oauthFetch.js";
|
|
13
13
|
import { createProxyFetch, fetchProxyAware } from "../../proxy/proxyFetch.js";
|
|
14
14
|
import { getCapturedLimitSnapshot, getCapturedResponseHeaders, logClaudeLimitSnapshot, runInLimitCaptureScope, setLimitSpanAttributes, withLimitCapture, wrapFetchWithLimitCapture, } from "./rateLimitCapture.js";
|
|
15
|
-
import { AuthenticationError
|
|
16
|
-
import { classifyProviderError, messageNamesStatus, } from "../../utils/errorClassifier.js";
|
|
15
|
+
import { AuthenticationError } from "../../types/index.js";
|
|
17
16
|
import { logger } from "../../utils/logger.js";
|
|
18
17
|
import { drainDetachedPump } from "../../utils/drainDetachedPump.js";
|
|
19
18
|
import { ANTHROPIC_ELISION_NOTE, planAnthropicLoopReclaim, previewAnthropicToolResultText, } from "../../context/anthropicLoopGuard.js";
|
|
@@ -23,6 +22,7 @@ import { redactUrlCredentials } from "../../utils/logSanitize.js";
|
|
|
23
22
|
import { ANTHROPIC_MAX_CACHE_BREAKPOINTS, applyAnthropicHistoryCacheBreakpoints, countAnthropicCacheMarkers, } from "../../utils/anthropicCacheBreakpoints.js";
|
|
24
23
|
import { stringifyAnthropicToolOutput } from "./toolOutput.js";
|
|
25
24
|
import { createAnthropicLoopAdapter } from "./loopAdapter.js";
|
|
25
|
+
import { getToolChoiceMap, translateToolChoice } from "../rules/toolRules.js";
|
|
26
26
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
27
27
|
import { AnthropicThreadStore, createAnthropicThreadSession, settleThread, threadRecovery, } from "./threads.js";
|
|
28
28
|
import { DEFAULT_BEFORE_STEP_TIMEOUT_MS } from "../../utils/parameterValidation.js";
|
|
@@ -48,7 +48,16 @@ import { toNativeToolDeclarations } from "../../core/nativeToolFormat.js";
|
|
|
48
48
|
import { ANTHROPIC_API_VERSION, ANTHROPIC_BETA_HEADERS } from "./constants.js";
|
|
49
49
|
import { cacheControlOf, withLastToolCacheBreakpoint } from "./cacheControl.js";
|
|
50
50
|
import { createNativeGenerateGuard } from "../../context/nativeGenerateGuard.js";
|
|
51
|
-
import { appendFinalResultInstruction, appendFinalResultTool, appendToolAnswerInstruction,
|
|
51
|
+
import { appendFinalResultInstruction, appendFinalResultTool, appendToolAnswerInstruction, } from "./structuredOutput.js";
|
|
52
|
+
import { FINAL_RESULT_TOOL_NAME } from "../rules/finalResultTool.js";
|
|
53
|
+
import { classifyWithProviderRules } from "../rules/errorRules.js";
|
|
54
|
+
import { getProviderErrorRules } from "../rules/registry.js";
|
|
55
|
+
import { getRequestDefault } from "../rules/requestDefaults.js";
|
|
56
|
+
import { toWireParams } from "../rules/requestFields.js";
|
|
57
|
+
import { getThinkingLimits } from "../rules/thinkingLimits.js";
|
|
58
|
+
import { getFinishReasonMap, translateFinishReason, } from "../rules/finishReasons.js";
|
|
59
|
+
const ANTHROPIC_FINISH_REASONS = getFinishReasonMap("anthropic", "messages");
|
|
60
|
+
const ANTHROPIC_ERROR_RULES = getProviderErrorRules("anthropic");
|
|
52
61
|
// AnthropicProviderConfig is imported from types/providers.ts
|
|
53
62
|
// Re-export for backward compatibility
|
|
54
63
|
// Configuration helpers - now using consolidated utility
|
|
@@ -429,25 +438,9 @@ const messagesToAnthropic = (msgs) => {
|
|
|
429
438
|
messages,
|
|
430
439
|
};
|
|
431
440
|
};
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
return undefined; // Anthropic defaults to auto when tools are present
|
|
436
|
-
}
|
|
437
|
-
if (choice === "none") {
|
|
438
|
-
return { type: "none" };
|
|
439
|
-
}
|
|
440
|
-
if (choice === "required") {
|
|
441
|
-
return { type: "any" };
|
|
442
|
-
}
|
|
443
|
-
if (typeof choice === "object") {
|
|
444
|
-
const c = choice;
|
|
445
|
-
if (c.type === "tool" && c.toolName) {
|
|
446
|
-
return { type: "tool", name: c.toolName };
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
return undefined;
|
|
450
|
-
};
|
|
441
|
+
const ANTHROPIC_TOOL_CHOICE = getToolChoiceMap("anthropic", "messages");
|
|
442
|
+
/** Map a NeuroLink tool choice onto Anthropic's tool_choice shape (anthropic.json). */
|
|
443
|
+
const toolChoiceToAnthropic = (choice) => translateToolChoice(ANTHROPIC_TOOL_CHOICE, choice);
|
|
451
444
|
/**
|
|
452
445
|
* Claude 5.5 / 5.1 models answer a forced choice with a 400, so for them it
|
|
453
446
|
* becomes `auto`: the tool stays declared and the model still picks it.
|
|
@@ -501,9 +494,10 @@ const continuesToolTurnWithoutThinking = (messages) => {
|
|
|
501
494
|
* tool_choice forces tool use." with a 400. The forced choice wins and
|
|
502
495
|
* thinking is omitted, as on the Vertex schema path and in oauthFetch.ts.
|
|
503
496
|
* `none` and `auto` do not force tool use and leave thinking alone.
|
|
504
|
-
* - `budget_tokens` must be at least
|
|
505
|
-
*
|
|
506
|
-
*
|
|
497
|
+
* - `budget_tokens` must be at least `minBudgetTokens` and below
|
|
498
|
+
* `max_tokens` (anthropic.json `thinkingLimits`). As on the Vertex path, it
|
|
499
|
+
* is clamped to leave `answerReserveTokens` for the answer, and thinking is
|
|
500
|
+
* omitted when no budget of at least the minimum fits.
|
|
507
501
|
*
|
|
508
502
|
* - Thinking cannot be switched on partway through a tool-use turn: when the
|
|
509
503
|
* final assistant message calls a tool and does not start with a thinking
|
|
@@ -516,6 +510,9 @@ const continuesToolTurnWithoutThinking = (messages) => {
|
|
|
516
510
|
* `{ type: "disabled" }` and an absent block pass through unchanged. Every
|
|
517
511
|
* omission is logged, since the caller asked for thinking.
|
|
518
512
|
*/
|
|
513
|
+
const THINKING_LIMITS = getThinkingLimits("anthropic");
|
|
514
|
+
const LARGE_OUTPUT_THRESHOLD_TOKENS = getRequestDefault("anthropic", "largeOutputThresholdTokens");
|
|
515
|
+
const LARGE_OUTPUT_TIMEOUT_FLOOR_MS = getRequestDefault("anthropic", "largeOutputTimeoutFloorMs");
|
|
519
516
|
const fitThinkingToRequest = (thinking, toolChoice, maxTokens, messages) => {
|
|
520
517
|
if (thinking?.type !== "enabled") {
|
|
521
518
|
return thinking;
|
|
@@ -537,9 +534,9 @@ const fitThinkingToRequest = (thinking, toolChoice, maxTokens, messages) => {
|
|
|
537
534
|
logger.warn(`[anthropic] Omitting extended thinking: budget_tokens ${String(thinking.budget_tokens)} (max_tokens ${String(maxTokens)}) is not a finite number`);
|
|
538
535
|
return undefined;
|
|
539
536
|
}
|
|
540
|
-
const budget = Math.floor(Math.min(thinking.budget_tokens, maxTokens -
|
|
541
|
-
if (budget <
|
|
542
|
-
logger.warn(`[anthropic] Omitting extended thinking: max_tokens ${maxTokens} leaves no room for a thinking budget of at least
|
|
537
|
+
const budget = Math.floor(Math.min(thinking.budget_tokens, maxTokens - THINKING_LIMITS.answerReserveTokens));
|
|
538
|
+
if (budget < THINKING_LIMITS.minBudgetTokens) {
|
|
539
|
+
logger.warn(`[anthropic] Omitting extended thinking: max_tokens ${maxTokens} leaves no room for a thinking budget of at least ${THINKING_LIMITS.minBudgetTokens} tokens plus an answer`);
|
|
543
540
|
return undefined;
|
|
544
541
|
}
|
|
545
542
|
if (budget !== thinking.budget_tokens) {
|
|
@@ -549,18 +546,7 @@ const fitThinkingToRequest = (thinking, toolChoice, maxTokens, messages) => {
|
|
|
549
546
|
return thinking;
|
|
550
547
|
};
|
|
551
548
|
/** Map Anthropic stop_reason onto the V3 unified finish reason. */
|
|
552
|
-
const mapAnthropicStopReason = (raw) =>
|
|
553
|
-
switch (raw) {
|
|
554
|
-
case "max_tokens":
|
|
555
|
-
return "length";
|
|
556
|
-
case "tool_use":
|
|
557
|
-
return "tool-calls";
|
|
558
|
-
case "refusal":
|
|
559
|
-
return "content-filter";
|
|
560
|
-
default:
|
|
561
|
-
return "stop";
|
|
562
|
-
}
|
|
563
|
-
};
|
|
549
|
+
const mapAnthropicStopReason = (raw) => translateFinishReason(ANTHROPIC_FINISH_REASONS, raw);
|
|
564
550
|
// Anthropic's Messages API requires max_tokens on every request. When the
|
|
565
551
|
// caller omits it, default to the model's real output ceiling via
|
|
566
552
|
// resolveClaudeMaxTokens (e.g. 64K for Sonnet 4.x) instead of the legacy 4096,
|
|
@@ -573,7 +559,7 @@ const mapAnthropicStopReason = (raw) => {
|
|
|
573
559
|
// for the non-throwing path — suppresses that pre-flight throw so large
|
|
574
560
|
// max_tokens (our model-ceiling default) works. Per-request duration is still
|
|
575
561
|
// bounded by the abort signal NeuroLink composes for each call.
|
|
576
|
-
const ANTHROPIC_CLIENT_TIMEOUT_MS =
|
|
562
|
+
const ANTHROPIC_CLIENT_TIMEOUT_MS = getRequestDefault("anthropic", "clientTimeoutMs");
|
|
577
563
|
/**
|
|
578
564
|
* Send one non-streaming step of a thread. The SDK's request type does not know
|
|
579
565
|
* the beta `thread` field, so this is the one place it is added to the body,
|
|
@@ -1403,7 +1389,6 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1403
1389
|
const params = {
|
|
1404
1390
|
model: modelId,
|
|
1405
1391
|
messages: cachedMessages,
|
|
1406
|
-
max_tokens: maxTokens,
|
|
1407
1392
|
...(system ? { system } : {}),
|
|
1408
1393
|
// Extended thinking fixes sampling: Anthropic rejects any
|
|
1409
1394
|
// temperature but 1 while `thinking` is set, and does not honour
|
|
@@ -1411,15 +1396,12 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1411
1396
|
// forwarding it alongside thinking turns a call that used to work
|
|
1412
1397
|
// into a 400. Drop the sampling knobs for exactly those turns and
|
|
1413
1398
|
// let Anthropic's thinking defaults stand.
|
|
1414
|
-
...(
|
|
1415
|
-
|
|
1416
|
-
:
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
...(options.stopSequences && options.stopSequences.length > 0
|
|
1421
|
-
? { stop_sequences: options.stopSequences }
|
|
1422
|
-
: {}),
|
|
1399
|
+
...toWireParams("anthropic", {
|
|
1400
|
+
maxTokens,
|
|
1401
|
+
temperature: samplingParams.temperature,
|
|
1402
|
+
topP: samplingParams.topP,
|
|
1403
|
+
stopSequences: options.stopSequences,
|
|
1404
|
+
}, { thinkingOn }),
|
|
1423
1405
|
...(tools ? { tools } : {}),
|
|
1424
1406
|
...(toolChoice ? { tool_choice: toolChoice } : {}),
|
|
1425
1407
|
...(thinking ? { thinking } : {}),
|
|
@@ -1440,8 +1422,8 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1440
1422
|
: undefined;
|
|
1441
1423
|
const generateTimeoutMs = forwardedTimeoutMs !== undefined
|
|
1442
1424
|
? forwardedTimeoutMs
|
|
1443
|
-
:
|
|
1444
|
-
? Math.max(getTimeoutForOptions(options),
|
|
1425
|
+
: maxTokens > LARGE_OUTPUT_THRESHOLD_TOKENS
|
|
1426
|
+
? Math.max(getTimeoutForOptions(options), LARGE_OUTPUT_TIMEOUT_FLOOR_MS)
|
|
1445
1427
|
: getTimeoutForOptions(options);
|
|
1446
1428
|
const timeoutController = createTimeoutController(generateTimeoutMs, providerName, "generate");
|
|
1447
1429
|
const requestSignal = composeAbortSignals(options.abortSignal, timeoutController?.controller.signal);
|
|
@@ -1653,46 +1635,7 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1653
1635
|
return delegatingModel;
|
|
1654
1636
|
}
|
|
1655
1637
|
formatProviderError(error) {
|
|
1656
|
-
|
|
1657
|
-
{
|
|
1658
|
-
// Plan 02's mocked-contract work documented a pre-existing gap: the
|
|
1659
|
-
// Anthropic SDK formats auth failures as a bare "401 <msg>" string,
|
|
1660
|
-
// which the message-text regex alone does not catch — mirrors
|
|
1661
|
-
// Vertex's statusCode === 401 fallback in this same task.
|
|
1662
|
-
match: (ctx) => ctx.statusCode === 401 ||
|
|
1663
|
-
/API_KEY_INVALID|Invalid API key/i.test(ctx.message),
|
|
1664
|
-
errorClass: AuthenticationError,
|
|
1665
|
-
message: "Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable.",
|
|
1666
|
-
},
|
|
1667
|
-
{
|
|
1668
|
-
match: (ctx) => ctx.statusCode === 429 ||
|
|
1669
|
-
/rate limit|too_many_requests/i.test(ctx.message) ||
|
|
1670
|
-
messageNamesStatus(ctx.message, 429),
|
|
1671
|
-
errorClass: RateLimitError,
|
|
1672
|
-
message: "Anthropic rate limit exceeded. Please try again later.",
|
|
1673
|
-
},
|
|
1674
|
-
{
|
|
1675
|
-
match: (ctx) => /ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(ctx.message),
|
|
1676
|
-
errorClass: NetworkError,
|
|
1677
|
-
message: (ctx) => `Connection error: ${ctx.message}`,
|
|
1678
|
-
},
|
|
1679
|
-
{
|
|
1680
|
-
// Match the shared 5xx predicate: HTTP status or a bounded phrase,
|
|
1681
|
-
// rather than digits embedded in an unrelated value.
|
|
1682
|
-
match: (ctx) => (ctx.statusCode !== undefined &&
|
|
1683
|
-
ctx.statusCode >= 500 &&
|
|
1684
|
-
ctx.statusCode <= 599) ||
|
|
1685
|
-
/server error|bad gateway|service unavailable|gateway timeout|\berror\b\D{0,12}\b5\d\d\b|\b5\d\d\b\D{0,12}\berror\b|\bstatus(?:\s*code)?\b\D{0,12}\b5\d\d\b/i.test(ctx.message),
|
|
1686
|
-
errorClass: ProviderError,
|
|
1687
|
-
message: (ctx) => `Server error: ${ctx.message}`,
|
|
1688
|
-
},
|
|
1689
|
-
{
|
|
1690
|
-
match: () => true,
|
|
1691
|
-
errorClass: ProviderError,
|
|
1692
|
-
message: (ctx) => `Anthropic error: ${ctx.message}`,
|
|
1693
|
-
},
|
|
1694
|
-
];
|
|
1695
|
-
return classifyProviderError(error, rules, this.providerName, this.modelName);
|
|
1638
|
+
return classifyWithProviderRules(error, ANTHROPIC_ERROR_RULES, this.providerName, this.modelName);
|
|
1696
1639
|
}
|
|
1697
1640
|
// executeGenerate removed - BaseProvider handles all generation with tools
|
|
1698
1641
|
/**
|
|
@@ -1847,6 +1790,12 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1847
1790
|
...(options.temperature !== undefined
|
|
1848
1791
|
? { temperature: options.temperature }
|
|
1849
1792
|
: {}),
|
|
1793
|
+
...(options.topP !== undefined && options.topP !== null
|
|
1794
|
+
? { topP: options.topP }
|
|
1795
|
+
: {}),
|
|
1796
|
+
...(options.stopSequences && options.stopSequences.length > 0
|
|
1797
|
+
? { stopSequences: options.stopSequences }
|
|
1798
|
+
: {}),
|
|
1850
1799
|
...(options.abortSignal ? { abortSignal: options.abortSignal } : {}),
|
|
1851
1800
|
...(options.toolTimeoutMs !== undefined
|
|
1852
1801
|
? { toolTimeoutMs: options.toolTimeoutMs }
|
|
@@ -2250,9 +2199,15 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2250
2199
|
messages: conversation,
|
|
2251
2200
|
});
|
|
2252
2201
|
const cachedConversation = applyAnthropicHistoryCacheBreakpoints(conversation, ANTHROPIC_MAX_CACHE_BREAKPOINTS - cacheMarkersUsed);
|
|
2253
|
-
const streamSamplingParams = resolveSamplingParams("anthropic", modelId,
|
|
2254
|
-
|
|
2255
|
-
|
|
2202
|
+
const streamSamplingParams = resolveSamplingParams("anthropic", modelId, {
|
|
2203
|
+
...(options.temperature !== undefined &&
|
|
2204
|
+
options.temperature !== null
|
|
2205
|
+
? { temperature: options.temperature }
|
|
2206
|
+
: {}),
|
|
2207
|
+
...(options.topP !== undefined && options.topP !== null
|
|
2208
|
+
? { topP: options.topP }
|
|
2209
|
+
: {}),
|
|
2210
|
+
}, "anthropic.executeStream");
|
|
2256
2211
|
const maxTokens = resolveClaudeMaxTokens(modelId, options.maxTokens);
|
|
2257
2212
|
const thinking = fitThinkingToRequest(requestedThinking, anthropicToolChoice, maxTokens, conversation);
|
|
2258
2213
|
// See the generate path: `disabled` is sent, but only ON constrains sampling.
|
|
@@ -2263,7 +2218,6 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2263
2218
|
return {
|
|
2264
2219
|
model: modelId,
|
|
2265
2220
|
messages: cachedConversation,
|
|
2266
|
-
max_tokens: maxTokens,
|
|
2267
2221
|
// No `stream: true` here: executeStep sets it when it calls
|
|
2268
2222
|
// messages.create, so declaring it made the caller assert a literal
|
|
2269
2223
|
// the adapter immediately overwrites — and forced this whole params
|
|
@@ -2271,9 +2225,12 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2271
2225
|
...(payload.system ? { system: payload.system } : {}),
|
|
2272
2226
|
// Same constraint on the streaming path: a temperature alongside
|
|
2273
2227
|
// `thinking` is rejected outright.
|
|
2274
|
-
...(
|
|
2275
|
-
|
|
2276
|
-
:
|
|
2228
|
+
...toWireParams("anthropic", {
|
|
2229
|
+
maxTokens,
|
|
2230
|
+
temperature: streamSamplingParams.temperature,
|
|
2231
|
+
topP: streamSamplingParams.topP,
|
|
2232
|
+
stopSequences: options.stopSequences,
|
|
2233
|
+
}, { thinkingOn }),
|
|
2277
2234
|
...(cachedTools && cachedTools.length > 0
|
|
2278
2235
|
? { tools: cachedTools }
|
|
2279
2236
|
: {}),
|
|
@@ -28,19 +28,22 @@ import { settleThread, threadRecovery } from "./threads.js";
|
|
|
28
28
|
import { composeAbortSignalsScoped, createTimeoutController, } from "../../utils/timeout.js";
|
|
29
29
|
import { sanitizeAnthropicMessagesForTrace } from "../../utils/anthropicTraceSanitizer.js";
|
|
30
30
|
import { NeuroLinkError } from "../../utils/errorHandling.js";
|
|
31
|
+
import { getRequestFields, getToolResultRules, } from "../rules/requestFields.js";
|
|
31
32
|
import { ErrorCategory, ErrorSeverity } from "../../constants/enums.js";
|
|
33
|
+
import { getFinishReasonMap, translateFinishReason, } from "../rules/finishReasons.js";
|
|
34
|
+
// The Anthropic Messages wire rules, from anthropic.json (shared by direct
|
|
35
|
+
// Anthropic and Claude on Vertex).
|
|
36
|
+
const REQUEST_FIELDS = getRequestFields("anthropic");
|
|
37
|
+
const TOOL_RESULTS = getToolResultRules("anthropic");
|
|
38
|
+
/** A request parameter read back by its neutral name. */
|
|
39
|
+
function readWireParam(params, key) {
|
|
40
|
+
const value = params[REQUEST_FIELDS[key]];
|
|
41
|
+
return typeof value === "number" ? value : undefined;
|
|
42
|
+
}
|
|
43
|
+
const ANTHROPIC_FINISH_REASONS = getFinishReasonMap("anthropic", "messages");
|
|
32
44
|
/** Map Anthropic's stop_reason onto the unified finish reason. */
|
|
33
45
|
function mapAnthropicFinishReason(rawStopReason, hadToolCallsAtCap) {
|
|
34
|
-
|
|
35
|
-
case "max_tokens":
|
|
36
|
-
return "length";
|
|
37
|
-
case "tool_use":
|
|
38
|
-
return "tool-calls";
|
|
39
|
-
case "refusal":
|
|
40
|
-
return "content-filter";
|
|
41
|
-
default:
|
|
42
|
-
return hadToolCallsAtCap ? "tool-calls" : "stop";
|
|
43
|
-
}
|
|
46
|
+
return (translateFinishReason(ANTHROPIC_FINISH_REASONS, rawStopReason, hadToolCallsAtCap) ?? "stop");
|
|
44
47
|
}
|
|
45
48
|
/**
|
|
46
49
|
* Read one streamed Anthropic step off the wire.
|
|
@@ -407,9 +410,9 @@ export function createAnthropicLoopAdapter(config) {
|
|
|
407
410
|
provider: config.provider,
|
|
408
411
|
model: params.model,
|
|
409
412
|
modelParameters: {
|
|
410
|
-
temperature: params
|
|
411
|
-
maxTokens: params
|
|
412
|
-
topP: params
|
|
413
|
+
temperature: readWireParam(params, "temperature"),
|
|
414
|
+
maxTokens: readWireParam(params, "maxTokens"),
|
|
415
|
+
topP: readWireParam(params, "topP"),
|
|
413
416
|
thinkingBudget: params.thinking?.type === "enabled"
|
|
414
417
|
? params.thinking.budget_tokens
|
|
415
418
|
: undefined,
|
|
@@ -524,13 +527,10 @@ export function createAnthropicLoopAdapter(config) {
|
|
|
524
527
|
buildToolResultMessages(conversation, stepResult, toolResults) {
|
|
525
528
|
const assistantMessage = {
|
|
526
529
|
role: "assistant",
|
|
527
|
-
//
|
|
528
|
-
//
|
|
529
|
-
//
|
|
530
|
-
|
|
531
|
-
// it here means a caller cannot forget to. A provider that never emits
|
|
532
|
-
// them sees no change.
|
|
533
|
-
content: stepResult.raw.filter((block) => block.type !== "server_tool_use"),
|
|
530
|
+
// The turn is replayed as rebuilt from the stream: only thinking,
|
|
531
|
+
// redacted_thinking, text and tool_use blocks are collected, so a block
|
|
532
|
+
// the API emits but rejects on input (server_tool_use) never reaches here.
|
|
533
|
+
content: stepResult.raw,
|
|
534
534
|
};
|
|
535
535
|
const resultMessage = {
|
|
536
536
|
role: "user",
|
|
@@ -538,9 +538,11 @@ export function createAnthropicLoopAdapter(config) {
|
|
|
538
538
|
type: "tool_result",
|
|
539
539
|
tool_use_id: result.id,
|
|
540
540
|
content: result.error
|
|
541
|
-
?
|
|
541
|
+
? TOOL_RESULTS.errorTemplate
|
|
542
|
+
.replaceAll("{name}", result.name)
|
|
543
|
+
.replaceAll("{error}", String(result.error))
|
|
542
544
|
: stringifyAnthropicToolOutput(result.output),
|
|
543
|
-
...(result.error ? {
|
|
545
|
+
...(result.error ? { [TOOL_RESULTS.errorFlag]: true } : {}),
|
|
544
546
|
})),
|
|
545
547
|
};
|
|
546
548
|
// The two messages are built in the SDK's own shape and handed back as
|
|
@@ -15,8 +15,6 @@ import type Anthropic from "@anthropic-ai/sdk";
|
|
|
15
15
|
* Claude-on-Vertex loop in `googleVertex/client.ts`, which has used the same
|
|
16
16
|
* tool name, description, and instruction wording since it shipped.
|
|
17
17
|
*/
|
|
18
|
-
/** Internal tool name — filtered out of every returned tool call / execution. */
|
|
19
|
-
export declare const FINAL_RESULT_TOOL_NAME = "final_result";
|
|
20
18
|
/** The system-prompt instruction to answer through the named tool. */
|
|
21
19
|
export declare function toolAnswerInstruction(toolName: string): string;
|
|
22
20
|
/** Appended to the system prompt whenever the final_result tool is in play. */
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { logger } from "../../utils/logger.js";
|
|
2
2
|
import { inlineJsonSchema } from "../../utils/schemaConversion.js";
|
|
3
|
+
import { FINAL_RESULT_TOOL_DESCRIPTION, FINAL_RESULT_TOOL_NAME, finalResultToolInstruction, } from "../rules/finalResultTool.js";
|
|
3
4
|
/**
|
|
4
5
|
* Additive structured output for the native Anthropic Messages API.
|
|
5
6
|
*
|
|
@@ -16,12 +17,9 @@ import { inlineJsonSchema } from "../../utils/schemaConversion.js";
|
|
|
16
17
|
* Claude-on-Vertex loop in `googleVertex/client.ts`, which has used the same
|
|
17
18
|
* tool name, description, and instruction wording since it shipped.
|
|
18
19
|
*/
|
|
19
|
-
/** Internal tool name — filtered out of every returned tool call / execution. */
|
|
20
|
-
export const FINAL_RESULT_TOOL_NAME = "final_result";
|
|
21
|
-
const FINAL_RESULT_TOOL_DESCRIPTION = "Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.";
|
|
22
20
|
/** The system-prompt instruction to answer through the named tool. */
|
|
23
21
|
export function toolAnswerInstruction(toolName) {
|
|
24
|
-
return
|
|
22
|
+
return finalResultToolInstruction("mustCall", toolName);
|
|
25
23
|
}
|
|
26
24
|
/** Appended to the system prompt whenever the final_result tool is in play. */
|
|
27
25
|
export const FINAL_RESULT_INSTRUCTION = toolAnswerInstruction(FINAL_RESULT_TOOL_NAME);
|
|
@@ -61,7 +59,7 @@ export function appendFinalResultTool(tools, jsonSchema) {
|
|
|
61
59
|
return { tools, applied: false };
|
|
62
60
|
}
|
|
63
61
|
if (tools.some((tool) => tool.name === FINAL_RESULT_TOOL_NAME)) {
|
|
64
|
-
logger.warn(
|
|
62
|
+
logger.warn(`[Anthropic] A caller tool is already named '${FINAL_RESULT_TOOL_NAME}'; skipping the additive structured-output tool`);
|
|
65
63
|
return { tools, applied: false };
|
|
66
64
|
}
|
|
67
65
|
// Appended LAST so any cache_control breakpoint an upstream layer placed on
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { APIVersions } from "../constants/enums.js";
|
|
2
|
-
import { AuthenticationError } from "../types/index.js";
|
|
3
2
|
import { logger } from "../utils/logger.js";
|
|
4
|
-
import { classifyProviderError, DEFAULT_ERROR_RULES, messageNamesStatus, } from "../utils/errorClassifier.js";
|
|
5
3
|
import { createAzureAPIKeyConfig, createAzureEndpointConfig, validateApiKey, } from "../utils/providerConfig.js";
|
|
6
4
|
import { transformParamsForLogging } from "../utils/transformationUtils.js";
|
|
7
5
|
import { OpenAIChatCompletionsProvider } from "./openaiChatCompletionsBase.js";
|
|
8
6
|
import { requiresMaxCompletionTokens } from "./openaiChatCompletionsClient.js";
|
|
7
|
+
import { classifyWithProviderRules } from "./rules/errorRules.js";
|
|
8
|
+
import { getProviderErrorRules } from "./rules/registry.js";
|
|
9
|
+
const AZURE_ERROR_RULES = getProviderErrorRules("azure");
|
|
9
10
|
/**
|
|
10
11
|
* Azure OpenAI Provider — direct HTTP, no AI SDK.
|
|
11
12
|
*
|
|
@@ -158,26 +159,7 @@ export class AzureOpenAIProvider extends OpenAIChatCompletionsProvider {
|
|
|
158
159
|
return this.azureDeployment;
|
|
159
160
|
}
|
|
160
161
|
formatProviderError(error) {
|
|
161
|
-
|
|
162
|
-
// special-cased — everything else (429, 404, network errors, 5xx) fell
|
|
163
|
-
// through to one generic ProviderError. The 401 branch below keeps its
|
|
164
|
-
// message text byte-for-byte; DEFAULT_ERROR_RULES now gives
|
|
165
|
-
// 429/404/network/5xx their correct classifications instead of the old
|
|
166
|
-
// undifferentiated catch-all. The branch still reads the text, not the
|
|
167
|
-
// structured status, so a 401 whose message names no status still falls
|
|
168
|
-
// through to DEFAULT_ERROR_RULES as before. What changed is the match: a
|
|
169
|
-
// status-shaped "401" ("status code 401", a leading "401 ...") rather than
|
|
170
|
-
// any three digits, so a request id or token count no longer reads as an
|
|
171
|
-
// auth failure.
|
|
172
|
-
const rules = [
|
|
173
|
-
{
|
|
174
|
-
match: (ctx) => messageNamesStatus(ctx.message, 401),
|
|
175
|
-
errorClass: AuthenticationError,
|
|
176
|
-
message: "Invalid Azure OpenAI API key or endpoint.",
|
|
177
|
-
},
|
|
178
|
-
...DEFAULT_ERROR_RULES,
|
|
179
|
-
];
|
|
180
|
-
return classifyProviderError(error, rules, this.providerName, this.modelName);
|
|
162
|
+
return classifyWithProviderRules(error, AZURE_ERROR_RULES, this.providerName, this.modelName);
|
|
181
163
|
}
|
|
182
164
|
// ===========================================================================
|
|
183
165
|
// New overridable hooks (provided by the base-enhancement branch)
|
|
@@ -6,14 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { CATALOG_JSON_ENTRIES, DECIDE_CATALOG_JSON_ENTRIES, } from "./index.generated.js";
|
|
8
8
|
import { DEFAULT_ERROR_RULES } from "../../utils/errorClassifier.js";
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
authentication: AuthenticationError,
|
|
12
|
-
"rate-limit": RateLimitError,
|
|
13
|
-
"invalid-model": InvalidModelError,
|
|
14
|
-
network: NetworkError,
|
|
15
|
-
provider: ProviderError,
|
|
16
|
-
};
|
|
9
|
+
import { ProviderError } from "../../types/index.js";
|
|
10
|
+
import { compileErrorRules } from "../rules/errorRules.js";
|
|
17
11
|
// Duplicated from tools/codegen-catalog.ts intentionally: src/ must not
|
|
18
12
|
// import from tools/ (build-time tooling depends on runtime source, not the
|
|
19
13
|
// reverse).
|
|
@@ -61,23 +55,16 @@ export function buildCatalogConfigOptions(entry) {
|
|
|
61
55
|
};
|
|
62
56
|
}
|
|
63
57
|
function buildErrorRules(entry) {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
errorClass: ERROR_CLASS_MAP[rule.class],
|
|
75
|
-
message: needsContext
|
|
76
|
-
? (ctx) => interpolate(rule.message, entry, ctx.modelName, ctx.message)
|
|
77
|
-
: interpolate(rule.message, entry),
|
|
78
|
-
};
|
|
79
|
-
});
|
|
80
|
-
return [...bespoke, ...DEFAULT_ERROR_RULES];
|
|
58
|
+
// Catalog rules are a subset of the provider-rules format, so they compile
|
|
59
|
+
// through the same engine as every provider's rules file.
|
|
60
|
+
const vars = {
|
|
61
|
+
apiKeyEnvVar: catalogEnvVar(entry, "apiKey"),
|
|
62
|
+
setupUrl: entry.setup.url,
|
|
63
|
+
};
|
|
64
|
+
return [
|
|
65
|
+
...compileErrorRules(entry.errorRules, { vars: () => vars }),
|
|
66
|
+
...DEFAULT_ERROR_RULES,
|
|
67
|
+
];
|
|
81
68
|
}
|
|
82
69
|
// Recursively freezes a value in place and returns it. Used only on a
|
|
83
70
|
// structuredClone()d graph below — never on CATALOG_JSON_ENTRIES itself —
|
package/dist/providers/cohere.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { CohereModels } from "../constants/enums.js";
|
|
2
|
-
import {
|
|
3
|
-
import { classifyProviderError, DEFAULT_ERROR_RULES, } from "../utils/errorClassifier.js";
|
|
2
|
+
import { ProviderError } from "../types/index.js";
|
|
4
3
|
import { logger } from "../utils/logger.js";
|
|
5
4
|
import { redactUrlCredentials } from "../utils/logSanitize.js";
|
|
6
5
|
import { createProxyFetch } from "../proxy/proxyFetch.js";
|
|
@@ -9,6 +8,9 @@ import { createTimeoutController } from "../utils/timeout.js";
|
|
|
9
8
|
import { stripTrailingSlash } from "./openaiChatCompletionsClient.js";
|
|
10
9
|
import { OpenAIChatCompletionsProvider } from "./openaiChatCompletionsBase.js";
|
|
11
10
|
import { isFiniteEmbeddingVector } from "./embeddingResponseParsing.js";
|
|
11
|
+
import { classifyWithProviderRules } from "./rules/errorRules.js";
|
|
12
|
+
import { getProviderErrorRules } from "./rules/registry.js";
|
|
13
|
+
const COHERE_ERROR_RULES = getProviderErrorRules("cohere");
|
|
12
14
|
const COHERE_DEFAULT_BASE_URL = "https://api.cohere.com/compatibility/v1";
|
|
13
15
|
const getCohereApiKey = () => validateApiKey(createCohereConfig());
|
|
14
16
|
const getDefaultCohereModel = () => getProviderModel("COHERE_MODEL", CohereModels.COMMAND_R_PLUS);
|
|
@@ -61,34 +63,7 @@ export class CohereProvider extends OpenAIChatCompletionsProvider {
|
|
|
61
63
|
];
|
|
62
64
|
}
|
|
63
65
|
formatProviderError(error) {
|
|
64
|
-
|
|
65
|
-
// "invalid api token" is checked lowercase (case-sensitive substring, as
|
|
66
|
-
// in the original) — deliberately NOT normalized to match the family's
|
|
67
|
-
// more common "Invalid API key" capitalization, since Cohere's actual
|
|
68
|
-
// wire message differs.
|
|
69
|
-
{
|
|
70
|
-
match: (ctx) => /invalid api token|Authentication|401|invalid_api_token/.test(ctx.message),
|
|
71
|
-
errorClass: AuthenticationError,
|
|
72
|
-
message: "Invalid Cohere API key. Check COHERE_API_KEY. Get one at https://dashboard.cohere.com/api-keys",
|
|
73
|
-
},
|
|
74
|
-
{
|
|
75
|
-
match: (ctx) => /rate limit|429/.test(ctx.message),
|
|
76
|
-
errorClass: RateLimitError,
|
|
77
|
-
message: "Cohere rate limit exceeded. Back off and retry.",
|
|
78
|
-
},
|
|
79
|
-
{
|
|
80
|
-
match: (ctx) => /model_not_found|404/.test(ctx.message),
|
|
81
|
-
errorClass: InvalidModelError,
|
|
82
|
-
message: () => `Cohere model '${this.modelName}' not found. Use command-r, command-r-plus, or command-r7b-12-2024.`,
|
|
83
|
-
},
|
|
84
|
-
{
|
|
85
|
-
match: (ctx) => /trial limit|trial_limit/.test(ctx.message),
|
|
86
|
-
errorClass: ProviderError,
|
|
87
|
-
message: "Cohere trial usage limit exceeded. Upgrade at https://dashboard.cohere.com/billing.",
|
|
88
|
-
},
|
|
89
|
-
...DEFAULT_ERROR_RULES,
|
|
90
|
-
];
|
|
91
|
-
return classifyProviderError(error, rules, this.providerName, this.modelName);
|
|
66
|
+
return classifyWithProviderRules(error, COHERE_ERROR_RULES, this.providerName, this.modelName, { vars: () => ({ model: `${this.modelName}` }) });
|
|
92
67
|
}
|
|
93
68
|
async validateConfiguration() {
|
|
94
69
|
return (typeof this.config.apiKey === "string" &&
|