@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
|
@@ -47,6 +47,8 @@ import { isResponseFormatUnsupportedError, isSchemaComplexityError, isToolsSchem
|
|
|
47
47
|
import { resolveDeferredTool } from "../tools/toolDiscovery.js";
|
|
48
48
|
import { buildAPIError, buildBody, buildToolsForOpenAI, buildWireToolNameMaps, createDeferredAnalytics, ensureJsonWordInBody, estimateWireTokens, mapNeuroLinkToolChoice, mergeUsage, messageBuilderToOpenAI, parseSSEStream, stringifyToolOutput, stripTrailingSlash, v3ResponseFormatToOpenAI, v3ToolChoiceToOpenAI, v3ToolsToOpenAI, } from "./openaiChatCompletionsClient.js";
|
|
49
49
|
import { createStreamChannel } from "../core/streamChannel.js";
|
|
50
|
+
import { getFinishReasonMap, translateFinishReason, } from "./rules/finishReasons.js";
|
|
51
|
+
import { getWireUsage, readWireUsage, splitIncludedCount, splitIncludedPart, } from "./rules/wireUsage.js";
|
|
50
52
|
/**
|
|
51
53
|
* Safety margin (tokens) when fitting `max_tokens` to a runtime-discovered
|
|
52
54
|
* context window: the char-based input estimate and the backend's own prompt
|
|
@@ -108,21 +110,9 @@ const resolveAgainstSchema = (text, schema) => {
|
|
|
108
110
|
* absent value, reads as `stop`. A wire `error` finish never gets here: the SSE
|
|
109
111
|
* parser throws on it, and on a stream that ended with no terminal marker.
|
|
110
112
|
*/
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
return "length";
|
|
115
|
-
case "tool_calls":
|
|
116
|
-
case "function_call":
|
|
117
|
-
case "tool-calls":
|
|
118
|
-
return "tool-calls";
|
|
119
|
-
case "content_filter":
|
|
120
|
-
case "content-filter":
|
|
121
|
-
return "content-filter";
|
|
122
|
-
default:
|
|
123
|
-
return "stop";
|
|
124
|
-
}
|
|
125
|
-
};
|
|
113
|
+
const CHAT_USAGE = getWireUsage("openai-chat");
|
|
114
|
+
const CHAT_FINISH_REASONS = getFinishReasonMap("openai-chat", "chatCompletions");
|
|
115
|
+
const toUnifiedFinishReason = (reason) => translateFinishReason(CHAT_FINISH_REASONS, reason);
|
|
126
116
|
// Pull one native chunk at a time and forward cancellation to its iterator.
|
|
127
117
|
const chunksToV3Stream = (source, completion, cancel) => {
|
|
128
118
|
const iterator = source[Symbol.asyncIterator]();
|
|
@@ -816,40 +806,26 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
816
806
|
}
|
|
817
807
|
const rawFinish = choice?.finish_reason;
|
|
818
808
|
const unified = toUnifiedFinishReason(rawFinish);
|
|
809
|
+
const counts = readWireUsage(CHAT_USAGE, json.usage);
|
|
810
|
+
const cachedSplit = splitIncludedPart(counts.input, counts.cacheRead);
|
|
811
|
+
const reasoningSplit = splitIncludedPart(counts.output, counts.reasoning);
|
|
819
812
|
return {
|
|
820
813
|
content,
|
|
821
814
|
finishReason: { unified, raw: rawFinish ?? "stop" },
|
|
822
815
|
usage: {
|
|
823
816
|
inputTokens: {
|
|
824
|
-
total:
|
|
825
|
-
// cached_tokens is
|
|
826
|
-
//
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
// reasoning_tokens clamp on the output side below).
|
|
830
|
-
noCache: json.usage?.prompt_tokens !== undefined &&
|
|
831
|
-
json.usage?.prompt_tokens_details?.cached_tokens !== undefined
|
|
832
|
-
? Math.max(0, json.usage.prompt_tokens -
|
|
833
|
-
json.usage.prompt_tokens_details.cached_tokens)
|
|
834
|
-
: json.usage?.prompt_tokens,
|
|
835
|
-
cacheRead: json.usage?.prompt_tokens !== undefined &&
|
|
836
|
-
json.usage?.prompt_tokens_details?.cached_tokens !== undefined
|
|
837
|
-
? Math.min(json.usage.prompt_tokens_details.cached_tokens, json.usage.prompt_tokens)
|
|
838
|
-
: json.usage?.prompt_tokens_details?.cached_tokens,
|
|
817
|
+
total: counts.input,
|
|
818
|
+
// cached_tokens is a subset of prompt_tokens: noCache is the
|
|
819
|
+
// remainder, and cacheRead is clamped to the prompt total.
|
|
820
|
+
noCache: cachedSplit.rest,
|
|
821
|
+
cacheRead: cachedSplit.part,
|
|
839
822
|
// OpenAI-style APIs do not report cache writes.
|
|
840
823
|
cacheWrite: undefined,
|
|
841
824
|
},
|
|
842
825
|
outputTokens: {
|
|
843
|
-
total:
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
text: json.usage?.completion_tokens !== undefined &&
|
|
847
|
-
json.usage?.completion_tokens_details?.reasoning_tokens !==
|
|
848
|
-
undefined
|
|
849
|
-
? Math.max(0, json.usage.completion_tokens -
|
|
850
|
-
json.usage.completion_tokens_details.reasoning_tokens)
|
|
851
|
-
: json.usage?.completion_tokens,
|
|
852
|
-
reasoning: json.usage?.completion_tokens_details?.reasoning_tokens,
|
|
826
|
+
total: counts.output,
|
|
827
|
+
text: reasoningSplit.rest,
|
|
828
|
+
reasoning: counts.reasoning,
|
|
853
829
|
},
|
|
854
830
|
},
|
|
855
831
|
warnings: [],
|
|
@@ -1020,6 +996,12 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1020
996
|
...(options.temperature !== undefined
|
|
1021
997
|
? { temperature: options.temperature }
|
|
1022
998
|
: {}),
|
|
999
|
+
...(options.topP !== undefined && options.topP !== null
|
|
1000
|
+
? { topP: options.topP }
|
|
1001
|
+
: {}),
|
|
1002
|
+
...(options.stopSequences && options.stopSequences.length > 0
|
|
1003
|
+
? { stopSequences: options.stopSequences }
|
|
1004
|
+
: {}),
|
|
1023
1005
|
...(options.abortSignal ? { abortSignal: options.abortSignal } : {}),
|
|
1024
1006
|
...(options.toolTimeoutMs !== undefined
|
|
1025
1007
|
? { toolTimeoutMs: options.toolTimeoutMs }
|
|
@@ -1674,10 +1656,11 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1674
1656
|
// `transformParams` can rewrite the prompt before a byte is sent, and
|
|
1675
1657
|
// `wrapStream` can observe, filter, or replace the stream outright.
|
|
1676
1658
|
//
|
|
1677
|
-
// Honoured on the way back in: `prompt`, `maxOutputTokens`, `temperature
|
|
1678
|
-
// and `
|
|
1679
|
-
// gets a WARN rather than a silent drop,
|
|
1680
|
-
// list here would diverge from
|
|
1659
|
+
// Honoured on the way back in: `prompt`, `maxOutputTokens`, `temperature`,
|
|
1660
|
+
// `topP` and `stopSequences`. `tools` is offered read-only — a
|
|
1661
|
+
// middleware that rewrites it gets a WARN rather than a silent drop,
|
|
1662
|
+
// because re-deriving the wire tool list here would diverge from
|
|
1663
|
+
// `buildToolsForOpenAI`.
|
|
1681
1664
|
const v3Tools = openAITools?.map((t) => ({
|
|
1682
1665
|
type: "function",
|
|
1683
1666
|
name: t.function.name,
|
|
@@ -1694,6 +1677,9 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1694
1677
|
? { temperature: options.temperature }
|
|
1695
1678
|
: {}),
|
|
1696
1679
|
...(options.topP !== undefined ? { topP: options.topP } : {}),
|
|
1680
|
+
...(options.stopSequences && options.stopSequences.length > 0
|
|
1681
|
+
? { stopSequences: options.stopSequences }
|
|
1682
|
+
: {}),
|
|
1697
1683
|
};
|
|
1698
1684
|
let loopPromise;
|
|
1699
1685
|
// The wire conversation only exists once `doStream` actually runs, and it
|
|
@@ -1741,6 +1727,11 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1741
1727
|
? { temperature: params.temperature }
|
|
1742
1728
|
: {}),
|
|
1743
1729
|
...(typeof params?.topP === "number" ? { topP: params.topP } : {}),
|
|
1730
|
+
// An empty list is kept, so a middleware can clear the caller's stop
|
|
1731
|
+
// sequences as well as replace them.
|
|
1732
|
+
...(Array.isArray(params?.stopSequences)
|
|
1733
|
+
? { stopSequences: params.stopSequences }
|
|
1734
|
+
: {}),
|
|
1744
1735
|
};
|
|
1745
1736
|
loopPromise = this.runStreamLoop({
|
|
1746
1737
|
maxSteps,
|
|
@@ -1818,9 +1809,9 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1818
1809
|
// cached tokens at the full input rate instead of the cheaper
|
|
1819
1810
|
// cacheRead rate. Clamped like the other call sites in this file
|
|
1820
1811
|
// in case a gateway reports cacheRead > total.
|
|
1821
|
-
const cacheRead =
|
|
1812
|
+
const { rest: uncachedInput, part: cacheRead } = splitIncludedCount(input, part.usage.inputTokens.cacheRead ?? 0);
|
|
1822
1813
|
resolveUsage({
|
|
1823
|
-
promptTokens:
|
|
1814
|
+
promptTokens: uncachedInput,
|
|
1824
1815
|
completionTokens: output,
|
|
1825
1816
|
totalTokens: input + output,
|
|
1826
1817
|
...(cacheRead > 0 ? { cacheReadTokens: cacheRead } : {}),
|
|
@@ -2082,17 +2073,17 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
2082
2073
|
// and calculateCost expect. reasoning_tokens stays a subset of
|
|
2083
2074
|
// completionTokens (informational).
|
|
2084
2075
|
const toDeferredUsage = () => {
|
|
2085
|
-
const
|
|
2086
|
-
const
|
|
2087
|
-
const
|
|
2088
|
-
|
|
2089
|
-
// completion_tokens
|
|
2090
|
-
const reasoningTokens =
|
|
2076
|
+
const counts = readWireUsage(CHAT_USAGE, stepUsage);
|
|
2077
|
+
const promptTokens = counts.input ?? 0;
|
|
2078
|
+
const completionTokens = counts.output ?? 0;
|
|
2079
|
+
const { rest: uncachedPromptTokens, part: cachedTokens } = splitIncludedCount(promptTokens, counts.cacheRead ?? 0);
|
|
2080
|
+
// Reasoning is a subset of completion_tokens; a negative count reads as 0.
|
|
2081
|
+
const reasoningTokens = splitIncludedCount(completionTokens, Math.max(0, counts.reasoning ?? 0)).part;
|
|
2091
2082
|
return {
|
|
2092
|
-
promptTokens:
|
|
2083
|
+
promptTokens: uncachedPromptTokens,
|
|
2093
2084
|
completionTokens,
|
|
2094
2085
|
// Gateways that omit total_tokens must not collapse to 0.
|
|
2095
|
-
totalTokens:
|
|
2086
|
+
totalTokens: counts.total || promptTokens + completionTokens,
|
|
2096
2087
|
...(cachedTokens > 0 ? { cacheReadTokens: cachedTokens } : {}),
|
|
2097
2088
|
...(reasoningTokens > 0 ? { reasoningTokens } : {}),
|
|
2098
2089
|
};
|
|
@@ -2208,6 +2199,10 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
2208
2199
|
abortSignal,
|
|
2209
2200
|
}));
|
|
2210
2201
|
const executed = toolExecutionSummaries.slice(-stepResult.toolCalls.size);
|
|
2202
|
+
// prompt_tokens includes cached_tokens; report the disjoint figures so
|
|
2203
|
+
// a prepareStep hook sees the same numbers from stream() and generate().
|
|
2204
|
+
const stepCounts = readWireUsage(CHAT_USAGE, stepResult.usage);
|
|
2205
|
+
const stepCachedSplit = splitIncludedCount(stepCounts.input ?? 0, stepCounts.cacheRead ?? 0);
|
|
2211
2206
|
stepRecords.push(toPrepareStepRecord({
|
|
2212
2207
|
stepNumber: step,
|
|
2213
2208
|
content: [
|
|
@@ -2240,14 +2235,10 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
2240
2235
|
// here, once in cacheReadTokens) and a prepareStep hook that
|
|
2241
2236
|
// budgets on steps[].usage sees different numbers from
|
|
2242
2237
|
// stream() and generate() for the same step.
|
|
2243
|
-
inputTokens:
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
undefined
|
|
2248
|
-
? {
|
|
2249
|
-
cacheReadTokens: Math.min(stepResult.usage.prompt_tokens_details.cached_tokens, stepResult.usage.prompt_tokens ?? 0),
|
|
2250
|
-
}
|
|
2238
|
+
inputTokens: stepCachedSplit.rest,
|
|
2239
|
+
outputTokens: stepCounts.output ?? 0,
|
|
2240
|
+
...(stepCounts.cacheRead !== undefined
|
|
2241
|
+
? { cacheReadTokens: stepCachedSplit.part }
|
|
2251
2242
|
: {}),
|
|
2252
2243
|
}));
|
|
2253
2244
|
}
|
|
@@ -16,19 +16,19 @@
|
|
|
16
16
|
import { createParser } from "eventsource-parser";
|
|
17
17
|
import { ErrorCategory, ErrorSeverity } from "../constants/enums.js";
|
|
18
18
|
import { NeuroLinkError } from "../utils/errorHandling.js";
|
|
19
|
-
import {
|
|
19
|
+
import { compileToolNameRules, getToolChoiceMap, getToolNameRules, translateToolChoice, } from "./rules/toolRules.js";
|
|
20
20
|
import { resolveSamplingParams } from "../models/modelRegistry.js";
|
|
21
21
|
import { convertZodToJsonSchema, normalizeWireToolSchema, } from "../utils/schemaConversion.js";
|
|
22
22
|
import { estimateTokens, IMAGE_TOKEN_ESTIMATE, TOKENS_PER_MESSAGE, } from "../utils/tokenEstimation.js";
|
|
23
|
+
import { inModelFamily } from "./rules/modelFamilies.js";
|
|
23
24
|
export const stripTrailingSlash = (s) => s.replace(/\/+$/, "");
|
|
24
|
-
// OpenAI-compatible wire tool names
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
// pattern below, which mirrors sanitizeToolName's output alphabet. MCP
|
|
28
|
-
// servers can register names outside it (dots, colons, spaces); sent
|
|
29
|
-
// verbatim they make backends reject the tools block or emit tool_calls
|
|
25
|
+
// OpenAI-compatible wire tool names (openai-chat.json `toolNames`). MCP
|
|
26
|
+
// servers can register names outside that alphabet (dots, colons, spaces);
|
|
27
|
+
// sent verbatim they make backends reject the tools block or emit tool_calls
|
|
30
28
|
// that no longer match the registry.
|
|
31
|
-
const
|
|
29
|
+
const WIRE_TOOL_NAMES = compileToolNameRules(getToolNameRules("openai-chat"));
|
|
30
|
+
const CHAT_TOOL_CHOICE = getToolChoiceMap("openai-chat", "neurolink");
|
|
31
|
+
const V3_TOOL_CHOICE = getToolChoiceMap("openai-chat", "v3");
|
|
32
32
|
/**
|
|
33
33
|
* Build a bijective original ↔ wire tool-name map. Returns undefined when
|
|
34
34
|
* every name is already wire-valid and unreserved (the common case — the
|
|
@@ -43,23 +43,13 @@ const WIRE_TOOL_NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/;
|
|
|
43
43
|
* making the reverse mapping ambiguous.
|
|
44
44
|
*/
|
|
45
45
|
export const buildWireToolNameMaps = (names, reservedWireNames) => {
|
|
46
|
-
if (names.every((name) =>
|
|
46
|
+
if (names.every((name) => WIRE_TOOL_NAMES.isValid(name) && !reservedWireNames?.has(name))) {
|
|
47
47
|
return undefined;
|
|
48
48
|
}
|
|
49
49
|
const toWire = new Map();
|
|
50
50
|
const fromWire = new Map();
|
|
51
51
|
for (const name of names) {
|
|
52
|
-
|
|
53
|
-
if (fromWire.has(wire) || reservedWireNames?.has(wire)) {
|
|
54
|
-
let suffix = 2;
|
|
55
|
-
let candidate;
|
|
56
|
-
do {
|
|
57
|
-
const tail = `_${suffix}`;
|
|
58
|
-
candidate = `${wire.slice(0, 64 - tail.length)}${tail}`;
|
|
59
|
-
suffix++;
|
|
60
|
-
} while (fromWire.has(candidate) || reservedWireNames?.has(candidate));
|
|
61
|
-
wire = candidate;
|
|
62
|
-
}
|
|
52
|
+
const wire = WIRE_TOOL_NAMES.unique(WIRE_TOOL_NAMES.sanitize(name), (candidate) => fromWire.has(candidate) || !!reservedWireNames?.has(candidate));
|
|
63
53
|
toWire.set(name, wire);
|
|
64
54
|
fromWire.set(wire, name);
|
|
65
55
|
}
|
|
@@ -407,21 +397,7 @@ export const v3ToolsToOpenAI = (tools, toolNameToWire) => {
|
|
|
407
397
|
}
|
|
408
398
|
return out.length > 0 ? out : undefined;
|
|
409
399
|
};
|
|
410
|
-
export const v3ToolChoiceToOpenAI = (choice, toolNameToWire) =>
|
|
411
|
-
switch (choice.type) {
|
|
412
|
-
case "auto":
|
|
413
|
-
case "none":
|
|
414
|
-
case "required":
|
|
415
|
-
return choice.type;
|
|
416
|
-
case "tool":
|
|
417
|
-
return {
|
|
418
|
-
type: "function",
|
|
419
|
-
function: {
|
|
420
|
-
name: toolNameToWire?.get(choice.toolName) ?? choice.toolName,
|
|
421
|
-
},
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
};
|
|
400
|
+
export const v3ToolChoiceToOpenAI = (choice, toolNameToWire) => translateToolChoice(V3_TOOL_CHOICE, choice, (name) => toolNameToWire?.get(name) ?? name);
|
|
425
401
|
/**
|
|
426
402
|
* OpenAI's strict structured-output mode rejects a schema unless every object
|
|
427
403
|
* node carries `additionalProperties: false` AND lists every one of its
|
|
@@ -594,24 +570,7 @@ export const v3ResponseFormatToOpenAI = (rf) => {
|
|
|
594
570
|
},
|
|
595
571
|
};
|
|
596
572
|
};
|
|
597
|
-
export const mapNeuroLinkToolChoice = (choice, toolNameToWire) =>
|
|
598
|
-
if (!choice) {
|
|
599
|
-
return undefined;
|
|
600
|
-
}
|
|
601
|
-
if (choice === "auto" || choice === "none" || choice === "required") {
|
|
602
|
-
return choice;
|
|
603
|
-
}
|
|
604
|
-
if (typeof choice === "object" && choice !== null) {
|
|
605
|
-
const c = choice;
|
|
606
|
-
if (c.type === "tool" && c.toolName) {
|
|
607
|
-
return {
|
|
608
|
-
type: "function",
|
|
609
|
-
function: { name: toolNameToWire?.get(c.toolName) ?? c.toolName },
|
|
610
|
-
};
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
return undefined;
|
|
614
|
-
};
|
|
573
|
+
export const mapNeuroLinkToolChoice = (choice, toolNameToWire) => translateToolChoice(CHAT_TOOL_CHOICE, choice, (name) => toolNameToWire?.get(name) ?? name);
|
|
615
574
|
// OpenAI-compatible endpoints (OpenAI, DeepSeek, …) reject
|
|
616
575
|
// `response_format: { type: "json_object" }` unless the literal word "json"
|
|
617
576
|
// appears somewhere in the messages. The `@ai-sdk/openai-compatible` wrapper
|
|
@@ -647,10 +606,11 @@ export const ensureJsonWordInBody = (body) => body.response_format?.type === "js
|
|
|
647
606
|
}
|
|
648
607
|
: body;
|
|
649
608
|
// Reasoning-class OpenAI models (o-series, gpt-5+) reject `max_tokens` and
|
|
650
|
-
// require `max_completion_tokens
|
|
651
|
-
// rename the field on the wire body;
|
|
652
|
-
// keep `max_tokens`, so it is opt-in
|
|
653
|
-
|
|
609
|
+
// require `max_completion_tokens` (model-families.json maxCompletionTokens).
|
|
610
|
+
// Only the Azure provider uses this to rename the field on the wire body;
|
|
611
|
+
// third-party OpenAI-compatible endpoints keep `max_tokens`, so it is opt-in
|
|
612
|
+
// per provider, never applied by default.
|
|
613
|
+
export const requiresMaxCompletionTokens = (modelId) => inModelFamily("maxCompletionTokens", modelId.replace(/^.*\//, ""));
|
|
654
614
|
export const buildBody = (args) => {
|
|
655
615
|
const { modelId, messages, options, tools, toolChoice, streaming, responseFormat, } = args;
|
|
656
616
|
const body = {
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { AuthenticationError, InvalidModelError, NetworkError, } from "../../types/index.js";
|
|
2
1
|
import { logger } from "../../utils/logger.js";
|
|
3
2
|
import { redactUrlCredentials } from "../../utils/logSanitize.js";
|
|
4
|
-
import { classifyProviderError, DEFAULT_ERROR_RULES, } from "../../utils/errorClassifier.js";
|
|
5
3
|
import { OpenAIChatCompletionsProvider } from "../openaiChatCompletionsBase.js";
|
|
6
4
|
import { FALLBACK_OPENAI_COMPATIBLE_MODEL } from "./constants.js";
|
|
7
5
|
import { getDefaultOpenAICompatibleModel, getOpenAICompatibleConfig, } from "./utils.js";
|
|
6
|
+
import { classifyWithProviderRules } from "../rules/errorRules.js";
|
|
7
|
+
import { getProviderErrorRules } from "../rules/registry.js";
|
|
8
|
+
const OPENAI_COMPATIBLE_ERROR_RULES = getProviderErrorRules("openai-compatible");
|
|
8
9
|
/**
|
|
9
10
|
* OpenAI Compatible Provider — direct HTTP, no AI SDK.
|
|
10
11
|
*
|
|
@@ -52,39 +53,11 @@ export class OpenAICompatibleProvider extends OpenAIChatCompletionsProvider {
|
|
|
52
53
|
];
|
|
53
54
|
}
|
|
54
55
|
formatProviderError(error) {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
match: (ctx) => ctx.errorName === "TimeoutError" || /Timeout/.test(ctx.message),
|
|
62
|
-
errorClass: NetworkError,
|
|
63
|
-
message: (ctx) => `Request timed out: ${ctx.message}`,
|
|
64
|
-
},
|
|
65
|
-
{
|
|
66
|
-
match: (ctx) => /ECONNREFUSED|Failed to fetch/i.test(ctx.message),
|
|
67
|
-
errorClass: NetworkError,
|
|
68
|
-
message: () => `OpenAI Compatible endpoint not available. Please check your OPENAI_COMPATIBLE_BASE_URL: ${redactUrlCredentials(this.config.baseURL)}`,
|
|
69
|
-
},
|
|
70
|
-
{
|
|
71
|
-
match: (ctx) => ctx.statusCode === 401 ||
|
|
72
|
-
/API_KEY_INVALID|Invalid API key|Unauthorized/i.test(ctx.message),
|
|
73
|
-
errorClass: AuthenticationError,
|
|
74
|
-
message: "Invalid OpenAI Compatible API key. Please check your OPENAI_COMPATIBLE_API_KEY environment variable.",
|
|
75
|
-
},
|
|
76
|
-
// "does not exist" isn't covered by DEFAULT_ERROR_RULES's
|
|
77
|
-
// model_not_found/"model not found" pattern — preserved verbatim.
|
|
78
|
-
{
|
|
79
|
-
match: (ctx) => /model/i.test(ctx.message) &&
|
|
80
|
-
(/not found/i.test(ctx.message) ||
|
|
81
|
-
/does not exist/i.test(ctx.message)),
|
|
82
|
-
errorClass: InvalidModelError,
|
|
83
|
-
message: (ctx) => `Model '${ctx.modelName}' not available on OpenAI Compatible endpoint. ` +
|
|
84
|
-
"Please check available models or use getAvailableModels() to see supported models.",
|
|
85
|
-
},
|
|
86
|
-
...DEFAULT_ERROR_RULES,
|
|
87
|
-
];
|
|
88
|
-
return classifyProviderError(error, rules, this.providerName, this.modelName);
|
|
56
|
+
return classifyWithProviderRules(error, OPENAI_COMPATIBLE_ERROR_RULES, this.providerName, this.modelName, {
|
|
57
|
+
vars: () => ({
|
|
58
|
+
model: `${this.modelName}`,
|
|
59
|
+
baseURL: redactUrlCredentials(this.config.baseURL),
|
|
60
|
+
}),
|
|
61
|
+
});
|
|
89
62
|
}
|
|
90
63
|
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# Provider rules
|
|
2
|
+
|
|
3
|
+
Provider-specific behaviour, written as data. Each `<provider-id>.json` file is
|
|
4
|
+
read by the shared rule engines in this folder instead of being hard-coded in
|
|
5
|
+
the provider class.
|
|
6
|
+
|
|
7
|
+
A file can hold these blocks today. `schema.ts` defines each one; the
|
|
8
|
+
types are in `src/lib/types/providerRules.ts`.
|
|
9
|
+
|
|
10
|
+
- `errors`: error classification, which `errorRules.ts` compiles into the
|
|
11
|
+
matchers `classifyProviderError` runs. The catalog providers in
|
|
12
|
+
`../catalog/` use the same engine.
|
|
13
|
+
- `finishReasons`: named tables that translate a wire's finish (stop) reason,
|
|
14
|
+
read through `finishReasons.ts`. A wire shared by several providers has its
|
|
15
|
+
own file: `openai-chat.json` (every OpenAI Chat Completions provider),
|
|
16
|
+
`gemini.json` (Vertex and AI Studio), `sagemaker.json`, and `proxy.json`
|
|
17
|
+
(the proxy's translations into the OpenAI, Claude and Gemini vocabularies).
|
|
18
|
+
- `usage`: where a wire reports each token count (dotted paths), read through
|
|
19
|
+
`wireUsage.ts`. `splitIncludedPart` is the one formula wires share: a count
|
|
20
|
+
reported inside another (cache reads inside `prompt_tokens`, reasoning
|
|
21
|
+
inside `completion_tokens`) is split out and clamped to its total.
|
|
22
|
+
`openai-chat.json` carries the OpenAI Chat Completions field names and
|
|
23
|
+
`gemini.json` the Gemini ones; `reasoningInOutput` says whether a wire's
|
|
24
|
+
output count already includes its reasoning tokens (OpenAI) or not (Gemini).
|
|
25
|
+
- `usageDialects` (in `sagemaker.json`): named prompt/completion/total
|
|
26
|
+
layouts for wires that have several, read through `readUsageCounts`.
|
|
27
|
+
- `contextWindows`, `contextWindowNotes` and `providerAliases` (only in
|
|
28
|
+
`limits.json`): each provider's context window per model, the reasons
|
|
29
|
+
behind specific values, and the provider spellings that map onto a table
|
|
30
|
+
key. `src/lib/constants/contextWindows.ts` reads them and adds the catalog
|
|
31
|
+
providers' windows after them. Key order matters: the lookup takes the
|
|
32
|
+
first matching prefix. A model manifest, when one exists, wins over this
|
|
33
|
+
table; `test:provider-rules` names the entries where that happens.
|
|
34
|
+
- `usageFields` and `usageRebase` (only in `usage.json`): the field names the
|
|
35
|
+
shared normalizer `extractTokenUsage` (src/lib/utils/tokenUtils.ts) tries,
|
|
36
|
+
in priority order, and when a cache-inclusive input count is rebased.
|
|
37
|
+
- `toolChoices`: named tables that spell a NeuroLink tool choice for one wire
|
|
38
|
+
(`"auto"` / `"none"` / `"required"` or `{ type: "tool", toolName }`), read
|
|
39
|
+
through `translateToolChoice` in `toolRules.ts`. `null` sends nothing, and
|
|
40
|
+
`"{toolName}"` in the `tool` template becomes the wire's tool name. Tables
|
|
41
|
+
live in `openai-chat.json`, `anthropic.json` and `sagemaker.json`.
|
|
42
|
+
- `toolNames`: the tool names a wire accepts (first characters, allowed
|
|
43
|
+
characters, maximum length), compiled by `compileToolNameRules` into a
|
|
44
|
+
check, a sanitizer and a `_2`, `_3`, … de-duplicator. In
|
|
45
|
+
`openai-chat.json` (64 characters) and `gemini.json` (128).
|
|
46
|
+
- `modelFamilies` and `modelFamilyNotes` (only in `model-families.json`):
|
|
47
|
+
named lists of case-insensitive model-id patterns, read through
|
|
48
|
+
`getModelFamilyPatterns` and `inModelFamily`: models that reject sampling
|
|
49
|
+
parameters or a forced tool choice, Claude models with vision, Gemini 3 and
|
|
50
|
+
2.5, and the models that take a thinking config, prompt caching or a capped
|
|
51
|
+
output.
|
|
52
|
+
- `modelFamilyLabels`, `modelLists` and `modelListNotes` (only in
|
|
53
|
+
`model-families.json`): the family label per model (first match wins), and
|
|
54
|
+
exact model-id lists read through `getModelList`: image-generation models,
|
|
55
|
+
PDF image-generation models, and the Gemini text models Vertex serves only
|
|
56
|
+
on the global endpoint.
|
|
57
|
+
- `reasoning` and `reasoningNotes` (in `gemini.json`): the default thinking
|
|
58
|
+
level and budget, the budget fraction per level, each model's maximum
|
|
59
|
+
budget and accepted `thinkingBudget` range (first match wins), and the
|
|
60
|
+
restricted output-token cap.
|
|
61
|
+
- `apiKeyFormats`, `apiKeyLengths`, `oauthTokenFormats` and `credentialFormatNotes` (only in
|
|
62
|
+
`credentials.json`): the regex each provider's API key or OAuth token must
|
|
63
|
+
match, and the key lengths quoted in configuration hints (`apiKeyLengths`),
|
|
64
|
+
read by `src/lib/utils/providerConfig.ts`.
|
|
65
|
+
- `thinkingLimits` and `thinkingLimitNotes` (in `anthropic.json`): the
|
|
66
|
+
smallest extended-thinking `budget_tokens` Anthropic accepts and the tokens
|
|
67
|
+
kept free for the answer. The direct Anthropic and Vertex Claude paths clamp
|
|
68
|
+
the budget with them, read through `getThinkingLimits` in
|
|
69
|
+
`thinkingLimits.ts`.
|
|
70
|
+
- `defaultModel` and `defaultModelNote` (in `ollama.json`): the model a
|
|
71
|
+
provider uses when neither the call nor the environment names one, read
|
|
72
|
+
through `getDefaultModel` in `fallbackModel.ts`.
|
|
73
|
+
- `fallbackModel` and `fallbackModelNote` (in `ollama.json`): the model a
|
|
74
|
+
provider suggests when the requested one is not installed, read through
|
|
75
|
+
`getFallbackModel` in `fallbackModel.ts`.
|
|
76
|
+
- `errorSignals` and `errorSignalNotes` (only in `structured-output.json`):
|
|
77
|
+
case-insensitive patterns that recognise a structured-output rejection from
|
|
78
|
+
its message, whichever vendor sent it (tools and JSON schema cannot be
|
|
79
|
+
combined, a schema too complex to enforce, `response_format` unsupported by
|
|
80
|
+
the model). `src/lib/core/modules/structuredOutputPolicy.ts` reads them
|
|
81
|
+
through `matchesErrorSignal` in `errorSignals.ts`.
|
|
82
|
+
- `requestDefaults` and `requestDefaultNotes` (in `anthropic.json` and
|
|
83
|
+
`bedrock.json`): values a provider fills in when the caller leaves them
|
|
84
|
+
out, such as Bedrock's default temperature and the longer generate timeout
|
|
85
|
+
Anthropic uses above a large `max_tokens`. Read through `getRequestDefault`
|
|
86
|
+
in `requestDefaults.ts`.
|
|
87
|
+
- `imageLimits`, `imageLimitDefault`, `proxyProviders`, `providerAliases`,
|
|
88
|
+
`visionModels` and `visionFamilies` (only in `vision.json`): images per
|
|
89
|
+
request, the providers that route to arbitrary models, provider spellings,
|
|
90
|
+
vision-capable model ids (substring match) and which model family counts
|
|
91
|
+
as vision-capable. `src/lib/adapters/providerImageAdapter.ts` reads them
|
|
92
|
+
and puts the catalog's vision models first.
|
|
93
|
+
|
|
94
|
+
To change how a provider classifies an error, edit its JSON file. Then run
|
|
95
|
+
`pnpm run test:provider-rules`: it validates every file against `schema.ts`
|
|
96
|
+
and checks, against the built package, that each rule a real HTTP response can
|
|
97
|
+
reach produces the class and message its file states.
|
|
98
|
+
|
|
99
|
+
A rule whose message needs logic names a `messageHook`; the provider passes
|
|
100
|
+
that function when it calls `classifyWithProviderRules`.
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "./provider-rules.schema.json",
|
|
3
|
+
"id": "anthropic",
|
|
4
|
+
"errors": {
|
|
5
|
+
"useDefaults": false,
|
|
6
|
+
"rules": [
|
|
7
|
+
{
|
|
8
|
+
"status": 401,
|
|
9
|
+
"pattern": "API_KEY_INVALID|Invalid API key",
|
|
10
|
+
"class": "authentication",
|
|
11
|
+
"message": "Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
"status": 429,
|
|
15
|
+
"messageStatus": 429,
|
|
16
|
+
"pattern": "rate limit|too_many_requests",
|
|
17
|
+
"class": "rate-limit",
|
|
18
|
+
"message": "Anthropic rate limit exceeded. Please try again later."
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"pattern": "ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection",
|
|
22
|
+
"class": "network",
|
|
23
|
+
"message": "Connection error: {message}"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"statusRange": [500, 599],
|
|
27
|
+
"pattern": "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",
|
|
28
|
+
"class": "provider",
|
|
29
|
+
"message": "Server error: {message}"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"always": true,
|
|
33
|
+
"class": "provider",
|
|
34
|
+
"message": "Anthropic error: {message}"
|
|
35
|
+
}
|
|
36
|
+
]
|
|
37
|
+
},
|
|
38
|
+
"finishReasons": {
|
|
39
|
+
"messages": {
|
|
40
|
+
"map": {
|
|
41
|
+
"max_tokens": "length",
|
|
42
|
+
"tool_use": "tool-calls",
|
|
43
|
+
"refusal": "content-filter"
|
|
44
|
+
},
|
|
45
|
+
"default": "stop",
|
|
46
|
+
"defaultAtToolCap": "tool-calls"
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
"toolChoices": {
|
|
50
|
+
"messages": {
|
|
51
|
+
"modes": {
|
|
52
|
+
"auto": null,
|
|
53
|
+
"none": {
|
|
54
|
+
"type": "none"
|
|
55
|
+
},
|
|
56
|
+
"required": {
|
|
57
|
+
"type": "any"
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
"acceptStrings": true,
|
|
61
|
+
"acceptModeObjects": false,
|
|
62
|
+
"tool": {
|
|
63
|
+
"type": "tool",
|
|
64
|
+
"name": "{toolName}"
|
|
65
|
+
},
|
|
66
|
+
"toolRequiresName": true,
|
|
67
|
+
"fallback": null
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
"thinkingLimits": {
|
|
71
|
+
"minBudgetTokens": 1024,
|
|
72
|
+
"answerReserveTokens": 1024
|
|
73
|
+
},
|
|
74
|
+
"thinkingLimitNotes": {
|
|
75
|
+
"minBudgetTokens": "Anthropic rejects a budget_tokens below 1024 with a 400. When no budget of at least this size fits, thinking is omitted rather than coerced.",
|
|
76
|
+
"answerReserveTokens": "budget_tokens must stay below max_tokens (a 400 otherwise), so the budget is clamped to max_tokens minus this reserve, leaving room for the answer. Used by the direct Anthropic and Vertex Claude paths."
|
|
77
|
+
},
|
|
78
|
+
"requestDefaults": {
|
|
79
|
+
"largeOutputThresholdTokens": 8192,
|
|
80
|
+
"largeOutputTimeoutFloorMs": 300000,
|
|
81
|
+
"clientTimeoutMs": 600000
|
|
82
|
+
},
|
|
83
|
+
"requestDefaultNotes": {
|
|
84
|
+
"largeOutputThresholdTokens": "Above 8192 max_tokens a non-streaming call can run for minutes, so the generate timeout is raised (unless the caller forwarded one).",
|
|
85
|
+
"largeOutputTimeoutFloorMs": "Five minutes: the floor the raised timeout never goes below.",
|
|
86
|
+
"clientTimeoutMs": "An explicit SDK client timeout. With one set, the SDK skips its 'streaming is required for long requests' pre-flight, which would otherwise reject a large max_tokens on a non-streaming call."
|
|
87
|
+
},
|
|
88
|
+
"requestFields": {
|
|
89
|
+
"maxTokens": "max_tokens",
|
|
90
|
+
"temperature": "temperature",
|
|
91
|
+
"topP": "top_p",
|
|
92
|
+
"stopSequences": "stop_sequences"
|
|
93
|
+
},
|
|
94
|
+
"requestFieldNotes": {
|
|
95
|
+
"scope": "The Anthropic Messages wire, used by direct Anthropic and by Claude on Vertex. toWireParams() writes a request from neutral names; unset values and empty lists are left out.",
|
|
96
|
+
"omitWhileThinking": "Extended thinking fixes sampling: Anthropic rejects any temperature but 1 while thinking is on, and does not honour top_p there, so both are left out of a thinking request."
|
|
97
|
+
},
|
|
98
|
+
"toolResults": {
|
|
99
|
+
"errorTemplate": "Error executing tool {name}: {error}",
|
|
100
|
+
"errorFlag": "is_error"
|
|
101
|
+
},
|
|
102
|
+
"contextTexts": {
|
|
103
|
+
"elisionNote": "[Earlier tool exchanges were removed to fit the context window.]"
|
|
104
|
+
},
|
|
105
|
+
"requestFieldRules": {
|
|
106
|
+
"omitWhileThinking": ["temperature", "topP"]
|
|
107
|
+
}
|
|
108
|
+
}
|