@juspay/neurolink 13.12.3 → 13.12.5
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 +4 -2
- package/dist/browser/neurolink.min.js +407 -407
- package/dist/context/budgetChecker.js +1 -2
- package/dist/evaluation/scorers/rule/formatScorer.d.ts +8 -0
- package/dist/evaluation/scorers/rule/formatScorer.js +75 -6
- package/dist/neurolink.js +39 -7
- package/dist/providers/anthropic/client.js +96 -8
- package/dist/routing/classifierRouter.d.ts +2 -3
- package/dist/routing/classifierRouter.js +5 -6
- package/dist/routing/classifierStrategies.js +3 -6
- package/dist/routing/modelCatalog.js +3 -4
- package/dist/routing/modelPool.d.ts +2 -6
- package/dist/routing/modelPool.js +9 -35
- package/dist/types/classifierRouter.d.ts +2 -5
- package/dist/types/generate.d.ts +1 -2
- package/dist/types/modelPool.d.ts +2 -3
- package/dist/types/modelPool.js +1 -2
- package/dist/types/providers.d.ts +10 -0
- package/dist/types/stream.d.ts +1 -2
- package/dist/types/stt.d.ts +6 -0
- package/dist/types/transcribe.d.ts +2 -0
- package/dist/utils/sttProcessor.d.ts +6 -0
- package/dist/utils/sttProcessor.js +39 -5
- package/docs-site/static/search-index.json +8 -7
- package/package.json +3 -2
|
@@ -94,8 +94,7 @@ export function resolveHistoryBudget(result, compactionThreshold) {
|
|
|
94
94
|
// so the default reproduces the previous number EXACTLY (0.8/0.8 = 1) and
|
|
95
95
|
// anything lower shrinks the target. Clamped to at most 1 because this is
|
|
96
96
|
// the "give the model less context" lever, never the "give it more" one —
|
|
97
|
-
// over-filling a window
|
|
98
|
-
// a permanent cooldown.
|
|
97
|
+
// over-filling a window fails the current request.
|
|
99
98
|
const scale = compactionThreshold === undefined
|
|
100
99
|
? 1
|
|
101
100
|
: Math.max(0, Math.min(1, compactionThreshold / DEFAULT_COMPACTION_THRESHOLD));
|
|
@@ -73,6 +73,14 @@ export declare class FormatScorer extends BaseRuleScorer {
|
|
|
73
73
|
* Check list-specific requirements
|
|
74
74
|
*/
|
|
75
75
|
private _checkListRequirements;
|
|
76
|
+
/**
|
|
77
|
+
* Resolves the JSON Schema draft version from the schema's `$schema` declaration,
|
|
78
|
+
* or defaults to draft '2019-09' when omitted.
|
|
79
|
+
*
|
|
80
|
+
* @param schema - The JSON Schema object to inspect
|
|
81
|
+
* @returns The resolved SchemaDraft or an error message if unsupported
|
|
82
|
+
*/
|
|
83
|
+
private _resolveSchemaDraft;
|
|
76
84
|
/**
|
|
77
85
|
* Validate JSON against schema (basic validation)
|
|
78
86
|
*/
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* @file Format Scorer
|
|
3
3
|
* Evaluates response format compliance (JSON, markdown, code, etc.)
|
|
4
4
|
*/
|
|
5
|
+
import { Validator } from "@cfworker/json-schema";
|
|
5
6
|
import { logger } from "../../../utils/logger.js";
|
|
6
7
|
import { BaseRuleScorer, DEFAULT_RULE_SCORER_CONFIG, } from "./baseRuleScorer.js";
|
|
7
8
|
/**
|
|
@@ -389,20 +390,88 @@ export class FormatScorer extends BaseRuleScorer {
|
|
|
389
390
|
const score = passedChecks / totalChecks;
|
|
390
391
|
return { passed: score >= 0.8, score };
|
|
391
392
|
}
|
|
393
|
+
/**
|
|
394
|
+
* Resolves the JSON Schema draft version from the schema's `$schema` declaration,
|
|
395
|
+
* or defaults to draft '2019-09' when omitted.
|
|
396
|
+
*
|
|
397
|
+
* @param schema - The JSON Schema object to inspect
|
|
398
|
+
* @returns The resolved SchemaDraft or an error message if unsupported
|
|
399
|
+
*/
|
|
400
|
+
_resolveSchemaDraft(schema) {
|
|
401
|
+
if (!("$schema" in schema)) {
|
|
402
|
+
// Documented library default is 2019-09 when $schema is omitted
|
|
403
|
+
return { draft: "2019-09" };
|
|
404
|
+
}
|
|
405
|
+
const declared = schema.$schema;
|
|
406
|
+
// A present-but-non-string $schema (7, null, ...) is malformed, not absent.
|
|
407
|
+
if (typeof declared !== "string") {
|
|
408
|
+
return {
|
|
409
|
+
error: `Unsupported or invalid JSON Schema draft: ${JSON.stringify(declared)}`,
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
const raw = declared.trim().toLowerCase();
|
|
413
|
+
// The unversioned meta-schema URL names no draft; use the default.
|
|
414
|
+
if (/^https?:\/\/json-schema\.org\/schema#?$/.test(raw)) {
|
|
415
|
+
return { draft: "2019-09" };
|
|
416
|
+
}
|
|
417
|
+
// The library has no draft-06; draft-07 is a near-superset, so validate
|
|
418
|
+
// draft-06 schemas as draft-07 rather than rejecting them.
|
|
419
|
+
if (/(?:^|\/|#)draft-0?6(?:[/#]|$)/.test(raw) || raw === "6") {
|
|
420
|
+
return { draft: "7" };
|
|
421
|
+
}
|
|
422
|
+
// Match draft-04 / 4
|
|
423
|
+
if (/(?:^|\/|#)draft-0?4(?:[/#]|$)/.test(raw) || raw === "4") {
|
|
424
|
+
return { draft: "4" };
|
|
425
|
+
}
|
|
426
|
+
// Match draft-07 / 7
|
|
427
|
+
if (/(?:^|\/|#)draft-0?7(?:[/#]|$)/.test(raw) || raw === "7") {
|
|
428
|
+
return { draft: "7" };
|
|
429
|
+
}
|
|
430
|
+
// Match draft-2019-09 / 2019-09
|
|
431
|
+
if (/(?:^|\/|#)(?:draft[/-])?2019-09(?:[/#]|$)/.test(raw) ||
|
|
432
|
+
raw === "2019-09") {
|
|
433
|
+
return { draft: "2019-09" };
|
|
434
|
+
}
|
|
435
|
+
// Match draft-2020-12 / 2020-12
|
|
436
|
+
if (/(?:^|\/|#)(?:draft[/-])?2020-12(?:[/#]|$)/.test(raw) ||
|
|
437
|
+
raw === "2020-12") {
|
|
438
|
+
return { draft: "2020-12" };
|
|
439
|
+
}
|
|
440
|
+
// Fail closed: a genuinely unknown draft (e.g. draft-03) cannot be
|
|
441
|
+
// validated faithfully, and passing it unchecked would reintroduce the
|
|
442
|
+
// "any parseable JSON passes" bug this scorer exists to prevent.
|
|
443
|
+
return {
|
|
444
|
+
error: `Unsupported or invalid JSON Schema draft: "${declared}"`,
|
|
445
|
+
};
|
|
446
|
+
}
|
|
392
447
|
/**
|
|
393
448
|
* Validate JSON against schema (basic validation)
|
|
394
449
|
*/
|
|
395
|
-
_validateJsonSchema(text,
|
|
396
|
-
|
|
450
|
+
_validateJsonSchema(text, schema) {
|
|
451
|
+
let parsed;
|
|
397
452
|
try {
|
|
398
|
-
JSON.parse(text);
|
|
399
|
-
// TODO(#1955): Implement full JSON Schema validation
|
|
400
|
-
// For now, just check it's valid JSON
|
|
401
|
-
return { passed: true, score: 1.0 };
|
|
453
|
+
parsed = JSON.parse(text);
|
|
402
454
|
}
|
|
403
455
|
catch {
|
|
404
456
|
return { passed: false, score: 0.0 };
|
|
405
457
|
}
|
|
458
|
+
const { draft, error: draftError } = this._resolveSchemaDraft(schema);
|
|
459
|
+
if (draftError || !draft) {
|
|
460
|
+
logger.warn(`[FormatScorer] ${draftError ?? "Unsupported JSON Schema draft"}`);
|
|
461
|
+
return { passed: false, score: 0.0 };
|
|
462
|
+
}
|
|
463
|
+
try {
|
|
464
|
+
const validator = new Validator(schema, draft, false);
|
|
465
|
+
const result = validator.validate(parsed);
|
|
466
|
+
return {
|
|
467
|
+
passed: result.valid,
|
|
468
|
+
score: result.valid ? 1.0 : 0.0,
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
catch (err) {
|
|
472
|
+
logger.warn("[FormatScorer] JSON Schema validation error:", err);
|
|
473
|
+
return { passed: false, score: 0.0 };
|
|
474
|
+
}
|
|
406
475
|
}
|
|
407
476
|
/**
|
|
408
477
|
* Override score to add detailed format analysis
|
package/dist/neurolink.js
CHANGED
|
@@ -9960,7 +9960,9 @@ Current user's request: ${currentInput}`;
|
|
|
9960
9960
|
streamPool.recordSuccess(capturedMember);
|
|
9961
9961
|
}
|
|
9962
9962
|
catch (streamConsumeErr) {
|
|
9963
|
-
|
|
9963
|
+
if (!isAbortError(streamConsumeErr)) {
|
|
9964
|
+
streamPool.recordFailure(capturedMember, classifyProviderError(streamConsumeErr));
|
|
9965
|
+
}
|
|
9964
9966
|
throw streamConsumeErr;
|
|
9965
9967
|
}
|
|
9966
9968
|
})();
|
|
@@ -15093,7 +15095,12 @@ Current user's request: ${currentInput}`;
|
|
|
15093
15095
|
this.buildTranscribeDeps(options.credentials?.stt),
|
|
15094
15096
|
import("./voice/transcribe.js"),
|
|
15095
15097
|
]);
|
|
15096
|
-
|
|
15098
|
+
try {
|
|
15099
|
+
return await runTranscribe(options, deps);
|
|
15100
|
+
}
|
|
15101
|
+
finally {
|
|
15102
|
+
await deps.release?.();
|
|
15103
|
+
}
|
|
15097
15104
|
}
|
|
15098
15105
|
/**
|
|
15099
15106
|
* Transcribe a live stream of PCM16LE frames. Engines with a native stream
|
|
@@ -15115,7 +15122,12 @@ Current user's request: ${currentInput}`;
|
|
|
15115
15122
|
this.buildTranscribeDeps(options.credentials?.stt),
|
|
15116
15123
|
import("./voice/transcribeStream.js"),
|
|
15117
15124
|
]);
|
|
15118
|
-
|
|
15125
|
+
try {
|
|
15126
|
+
yield* runTranscribeStream(options, deps);
|
|
15127
|
+
}
|
|
15128
|
+
finally {
|
|
15129
|
+
await deps.release?.();
|
|
15130
|
+
}
|
|
15119
15131
|
}
|
|
15120
15132
|
/**
|
|
15121
15133
|
* Instance `credentials.stt` with a per-call `stt` slice merged on top,
|
|
@@ -15177,19 +15189,38 @@ Current user's request: ${currentInput}`;
|
|
|
15177
15189
|
// Same precedence as STTProcessor.resolveHandler, synchronously: a
|
|
15178
15190
|
// credentials slice for the provider builds a handler from it; else the
|
|
15179
15191
|
// registered handler; else, for a shipped provider, one from the env.
|
|
15192
|
+
// Handlers built here are not the registry's: they are collected and
|
|
15193
|
+
// disposed by `release()` once the request is done.
|
|
15194
|
+
const created = [];
|
|
15195
|
+
const build = (...args) => {
|
|
15196
|
+
const handler = createSTTHandler(...args);
|
|
15197
|
+
created.push(handler);
|
|
15198
|
+
return handler;
|
|
15199
|
+
};
|
|
15180
15200
|
const getHandler = (name) => {
|
|
15181
15201
|
if (resolveCallSTTEndpoints(credentials)[name.trim().toLowerCase()]) {
|
|
15182
|
-
return
|
|
15202
|
+
return build(name, credentials);
|
|
15183
15203
|
}
|
|
15184
15204
|
const descriptor = getSTTProviderDescriptor(name);
|
|
15185
15205
|
if (!descriptor) {
|
|
15186
15206
|
return STTProcessor.getHandler(name);
|
|
15187
15207
|
}
|
|
15188
15208
|
if (credentials?.[descriptor.credentialsKey] !== undefined) {
|
|
15189
|
-
return
|
|
15209
|
+
return build(descriptor.name, credentials);
|
|
15210
|
+
}
|
|
15211
|
+
return STTProcessor.getHandler(descriptor.name) ?? build(descriptor.name);
|
|
15212
|
+
};
|
|
15213
|
+
const release = async () => {
|
|
15214
|
+
const results = await Promise.allSettled(created.splice(0).map(async (handler) => handler.dispose?.()));
|
|
15215
|
+
// One failed disposal must not stop the others, but it stays visible.
|
|
15216
|
+
// Only the error message is logged: the handlers hold the credentials.
|
|
15217
|
+
for (const result of results) {
|
|
15218
|
+
if (result.status === "rejected") {
|
|
15219
|
+
logger.warn(`[NeuroLink] Failed to dispose an STT handler: ${result.reason instanceof Error
|
|
15220
|
+
? result.reason.message
|
|
15221
|
+
: String(result.reason)}`);
|
|
15222
|
+
}
|
|
15190
15223
|
}
|
|
15191
|
-
return (STTProcessor.getHandler(descriptor.name) ??
|
|
15192
|
-
createSTTHandler(descriptor.name));
|
|
15193
15224
|
};
|
|
15194
15225
|
return {
|
|
15195
15226
|
...this.buildSTTCorrectionDeps(),
|
|
@@ -15197,6 +15228,7 @@ Current user's request: ${currentInput}`;
|
|
|
15197
15228
|
resolveProvider,
|
|
15198
15229
|
getHandler,
|
|
15199
15230
|
attachmentPolicy: this.attachmentPolicy,
|
|
15231
|
+
release,
|
|
15200
15232
|
};
|
|
15201
15233
|
}
|
|
15202
15234
|
/**
|
|
@@ -465,6 +465,89 @@ const relaxForcedToolChoice = (modelId, choice) => {
|
|
|
465
465
|
: {}),
|
|
466
466
|
};
|
|
467
467
|
};
|
|
468
|
+
/**
|
|
469
|
+
* Whether the request continues a tool turn whose tool call was made without
|
|
470
|
+
* thinking: the final assistant message calls a tool (`tool_use`) and does not
|
|
471
|
+
* open with a thinking block.
|
|
472
|
+
*
|
|
473
|
+
* Only user messages follow the final assistant message, and Anthropic merges
|
|
474
|
+
* consecutive user messages into one turn, so that turn still answers the
|
|
475
|
+
* tool call however it is split: one tool-result message per tool (as
|
|
476
|
+
* `messagesToAnthropic` emits them), or tool results followed by a new user
|
|
477
|
+
* prompt when a tool turn was interrupted. Anthropic requires the final
|
|
478
|
+
* assistant message to open with a thinking block whenever thinking is on
|
|
479
|
+
* and that message calls a tool.
|
|
480
|
+
*/
|
|
481
|
+
const continuesToolTurnWithoutThinking = (messages) => {
|
|
482
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
483
|
+
const message = messages[index];
|
|
484
|
+
if (message.role !== "assistant") {
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
if (!Array.isArray(message.content) ||
|
|
488
|
+
!message.content.some((block) => block.type === "tool_use")) {
|
|
489
|
+
return false;
|
|
490
|
+
}
|
|
491
|
+
const first = message.content[0];
|
|
492
|
+
return first?.type !== "thinking" && first?.type !== "redacted_thinking";
|
|
493
|
+
}
|
|
494
|
+
return false;
|
|
495
|
+
};
|
|
496
|
+
/**
|
|
497
|
+
* Make an extended-thinking block fit the request it rides on.
|
|
498
|
+
*
|
|
499
|
+
* - A `tool_choice` that forces tool use (`any`, or a named `tool`) cannot be
|
|
500
|
+
* sent with thinking on: Anthropic answers "Thinking may not be enabled when
|
|
501
|
+
* tool_choice forces tool use." with a 400. The forced choice wins and
|
|
502
|
+
* thinking is omitted, as on the Vertex schema path and in oauthFetch.ts.
|
|
503
|
+
* `none` and `auto` do not force tool use and leave thinking alone.
|
|
504
|
+
* - `budget_tokens` must be at least 1024 and below `max_tokens`. As on the
|
|
505
|
+
* Vertex path, it is clamped to leave 1024 tokens for the answer, and
|
|
506
|
+
* thinking is omitted when no budget of at least 1024 fits.
|
|
507
|
+
*
|
|
508
|
+
* - Thinking cannot be switched on partway through a tool-use turn: when the
|
|
509
|
+
* final assistant message calls a tool and does not start with a thinking
|
|
510
|
+
* block, Anthropic requires one and rejects the request. That is what
|
|
511
|
+
* follows a forced first step, where thinking was omitted, so it stays
|
|
512
|
+
* omitted until the turn ends with an assistant message that calls no tool.
|
|
513
|
+
* - A `budget_tokens` that is not a finite number cannot be sent, so thinking
|
|
514
|
+
* is omitted. A fractional budget is rounded down.
|
|
515
|
+
*
|
|
516
|
+
* `{ type: "disabled" }` and an absent block pass through unchanged. Every
|
|
517
|
+
* omission is logged, since the caller asked for thinking.
|
|
518
|
+
*/
|
|
519
|
+
const fitThinkingToRequest = (thinking, toolChoice, maxTokens, messages) => {
|
|
520
|
+
if (thinking?.type !== "enabled") {
|
|
521
|
+
return thinking;
|
|
522
|
+
}
|
|
523
|
+
if (toolChoice?.type === "any" || toolChoice?.type === "tool") {
|
|
524
|
+
logger.warn(`[anthropic] Omitting extended thinking: tool_choice "${toolChoice.type}" forces tool use, which Anthropic rejects alongside thinking`);
|
|
525
|
+
return undefined;
|
|
526
|
+
}
|
|
527
|
+
if (continuesToolTurnWithoutThinking(messages)) {
|
|
528
|
+
logger.warn("[anthropic] Omitting extended thinking: this request continues a tool call made without thinking, and Anthropic does not allow thinking to start mid-turn");
|
|
529
|
+
return undefined;
|
|
530
|
+
}
|
|
531
|
+
// A budget that is not a finite number would survive the comparisons below
|
|
532
|
+
// (NaN compares false against everything) and reach the API as invalid JSON
|
|
533
|
+
// (NaN and Infinity serialize to null), so it is treated as unusable.
|
|
534
|
+
if (typeof thinking.budget_tokens !== "number" ||
|
|
535
|
+
!Number.isFinite(thinking.budget_tokens) ||
|
|
536
|
+
!Number.isFinite(maxTokens)) {
|
|
537
|
+
logger.warn(`[anthropic] Omitting extended thinking: budget_tokens ${String(thinking.budget_tokens)} (max_tokens ${String(maxTokens)}) is not a finite number`);
|
|
538
|
+
return undefined;
|
|
539
|
+
}
|
|
540
|
+
const budget = Math.floor(Math.min(thinking.budget_tokens, maxTokens - 1024));
|
|
541
|
+
if (budget < 1024) {
|
|
542
|
+
logger.warn(`[anthropic] Omitting extended thinking: max_tokens ${maxTokens} leaves no room for a thinking budget of at least 1024 tokens plus an answer`);
|
|
543
|
+
return undefined;
|
|
544
|
+
}
|
|
545
|
+
if (budget !== thinking.budget_tokens) {
|
|
546
|
+
logger.debug(`[anthropic] Clamping thinking budget_tokens ${thinking.budget_tokens} to ${budget} so it stays below max_tokens ${maxTokens}`);
|
|
547
|
+
return { type: "enabled", budget_tokens: budget };
|
|
548
|
+
}
|
|
549
|
+
return thinking;
|
|
550
|
+
};
|
|
468
551
|
/** Map Anthropic stop_reason onto the V3 unified finish reason. */
|
|
469
552
|
const mapAnthropicStopReason = (raw) => {
|
|
470
553
|
switch (raw) {
|
|
@@ -1273,8 +1356,10 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1273
1356
|
system = appendFinalResultInstruction(system);
|
|
1274
1357
|
}
|
|
1275
1358
|
}
|
|
1276
|
-
// Extended thinking passthrough (providerOptions.anthropic.thinking)
|
|
1277
|
-
|
|
1359
|
+
// Extended thinking passthrough (providerOptions.anthropic.thinking),
|
|
1360
|
+
// fitted to the forced tool_choice and max_tokens above.
|
|
1361
|
+
const maxTokens = resolveClaudeMaxTokens(modelId, options.maxOutputTokens);
|
|
1362
|
+
const thinking = fitThinkingToRequest(options.providerOptions?.anthropic?.thinking, toolChoice, maxTokens, messages);
|
|
1278
1363
|
// `disabled` is sent so a model that thinks by default (claude-sonnet-5
|
|
1279
1364
|
// does, unasked) is told not to, but it fixes nothing about sampling: only a
|
|
1280
1365
|
// block that turns thinking ON makes Anthropic reject temperature.
|
|
@@ -1318,7 +1403,7 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1318
1403
|
const params = {
|
|
1319
1404
|
model: modelId,
|
|
1320
1405
|
messages: cachedMessages,
|
|
1321
|
-
max_tokens:
|
|
1406
|
+
max_tokens: maxTokens,
|
|
1322
1407
|
...(system ? { system } : {}),
|
|
1323
1408
|
// Extended thinking fixes sampling: Anthropic rejects any
|
|
1324
1409
|
// temperature but 1 while `thinking` is set, and does not honour
|
|
@@ -1940,8 +2025,9 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1940
2025
|
const stepRecords = [];
|
|
1941
2026
|
// Extended thinking: enabled when the caller supplies an explicit token
|
|
1942
2027
|
// budget (mirrors the previous experimental_thinking gating). Thinking
|
|
1943
|
-
// deltas stream out on the `reasoning` chunk channel.
|
|
1944
|
-
|
|
2028
|
+
// deltas stream out on the `reasoning` chunk channel. Fitted per step in
|
|
2029
|
+
// buildParams, since the step's tool_choice decides whether it may be sent.
|
|
2030
|
+
const requestedThinking = options.thinkingConfig?.enabled && options.thinkingConfig.budgetTokens
|
|
1945
2031
|
? {
|
|
1946
2032
|
type: "enabled",
|
|
1947
2033
|
budget_tokens: options.thinkingConfig.budgetTokens,
|
|
@@ -1949,8 +2035,6 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1949
2035
|
: options.thinkingConfig?.type === "disabled"
|
|
1950
2036
|
? { type: "disabled" }
|
|
1951
2037
|
: undefined;
|
|
1952
|
-
// See the generate path: `disabled` is sent, but only ON constrains sampling.
|
|
1953
|
-
const thinkingOn = thinking?.type === "enabled";
|
|
1954
2038
|
const maxSteps = options.maxSteps || DEFAULT_MAX_STEPS;
|
|
1955
2039
|
const channel = createStreamChannel();
|
|
1956
2040
|
const { push: pushChunk } = channel;
|
|
@@ -2142,13 +2226,17 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2142
2226
|
const streamSamplingParams = resolveSamplingParams("anthropic", modelId, options.temperature !== undefined && options.temperature !== null
|
|
2143
2227
|
? { temperature: options.temperature }
|
|
2144
2228
|
: {}, "anthropic.executeStream");
|
|
2229
|
+
const maxTokens = resolveClaudeMaxTokens(modelId, options.maxTokens);
|
|
2230
|
+
const thinking = fitThinkingToRequest(requestedThinking, anthropicToolChoice, maxTokens, conversation);
|
|
2231
|
+
// See the generate path: `disabled` is sent, but only ON constrains sampling.
|
|
2232
|
+
const thinkingOn = thinking?.type === "enabled";
|
|
2145
2233
|
if (thinkingOn && streamSamplingParams.temperature !== undefined) {
|
|
2146
2234
|
logger.debug("[anthropic] extended thinking is enabled, so temperature is omitted on the stream path — Anthropic rejects any temperature but 1 while thinking is set");
|
|
2147
2235
|
}
|
|
2148
2236
|
return {
|
|
2149
2237
|
model: modelId,
|
|
2150
2238
|
messages: cachedConversation,
|
|
2151
|
-
max_tokens:
|
|
2239
|
+
max_tokens: maxTokens,
|
|
2152
2240
|
// No `stream: true` here: executeStep sets it when it calls
|
|
2153
2241
|
// messages.create, so declaring it made the caller assert a literal
|
|
2154
2242
|
// the adapter immediately overwrites — and forced this whole params
|
|
@@ -108,9 +108,8 @@ export declare class ClassifierRouter {
|
|
|
108
108
|
* Returns undefined — meaning "leave the 0.8 default alone" — whenever the
|
|
109
109
|
* feature is off, no scope was read, or the scope is the widest one. The
|
|
110
110
|
* mapping can only ever LOWER the threshold, which is enforced in
|
|
111
|
-
* `contextScopeToThreshold` rather than here,
|
|
112
|
-
*
|
|
113
|
-
* `context_window` error puts the model into ModelPool's 10-year cooldown.
|
|
111
|
+
* `contextScopeToThreshold` rather than here, to avoid sending requests
|
|
112
|
+
* that exceed the selected model's context window.
|
|
114
113
|
*/
|
|
115
114
|
private selectContextBudget;
|
|
116
115
|
/** Tool narrowing: per-difficulty directive, then classifier hints. */
|
|
@@ -219,9 +219,9 @@ export class ClassifierRouter {
|
|
|
219
219
|
? byId.get(decision.selectedModelId)
|
|
220
220
|
: undefined;
|
|
221
221
|
if (picked) {
|
|
222
|
-
// A pick that cannot hold
|
|
223
|
-
// confidence.
|
|
224
|
-
//
|
|
222
|
+
// A pick that cannot hold this request is vetoed outright, whatever the
|
|
223
|
+
// confidence. It would fail this request even though the member remains
|
|
224
|
+
// healthy for shorter requests.
|
|
225
225
|
if (!this.fitsRequest(picked, input)) {
|
|
226
226
|
this.deps.logger?.debug?.("[ClassifierRouter] classifier pick dropped — window too small", {
|
|
227
227
|
id: decision.selectedModelId,
|
|
@@ -385,9 +385,8 @@ export class ClassifierRouter {
|
|
|
385
385
|
* Returns undefined — meaning "leave the 0.8 default alone" — whenever the
|
|
386
386
|
* feature is off, no scope was read, or the scope is the widest one. The
|
|
387
387
|
* mapping can only ever LOWER the threshold, which is enforced in
|
|
388
|
-
* `contextScopeToThreshold` rather than here,
|
|
389
|
-
*
|
|
390
|
-
* `context_window` error puts the model into ModelPool's 10-year cooldown.
|
|
388
|
+
* `contextScopeToThreshold` rather than here, to avoid sending requests
|
|
389
|
+
* that exceed the selected model's context window.
|
|
391
390
|
*/
|
|
392
391
|
selectContextBudget(decision) {
|
|
393
392
|
if (this.config.contextBudget === false || !decision.contextScope) {
|
|
@@ -205,12 +205,9 @@ const JEV_CONTEXT_CRITERIA = [
|
|
|
205
205
|
* Compaction thresholds per context scope, indexed to match
|
|
206
206
|
* {@link CLASSIFIER_CONTEXT_SCOPES}.
|
|
207
207
|
*
|
|
208
|
-
* Every one is at or below the 0.8 default
|
|
209
|
-
*
|
|
210
|
-
*
|
|
211
|
-
* `context_window` error as a PERMANENT cooldown (10 years), so one
|
|
212
|
-
* optimistic guess retires that model for the life of the process. Shrinking
|
|
213
|
-
* a budget merely compacts a little earlier than it had to.
|
|
208
|
+
* Every one is at or below the 0.8 default. Raising a budget could let a
|
|
209
|
+
* request through that the model rejects for exceeding its window; shrinking
|
|
210
|
+
* a budget compacts a little earlier instead.
|
|
214
211
|
*/
|
|
215
212
|
const CONTEXT_SCOPE_THRESHOLD = [0.45, 0.6, 0.75, 0.8];
|
|
216
213
|
/** Below this calibrated confidence the scope reading is ignored entirely. */
|
|
@@ -184,10 +184,9 @@ export function rankCatalogue(candidates, difficulty, input, requiredCapabilitie
|
|
|
184
184
|
return needed.every((cap) => c.capabilities?.includes(cap));
|
|
185
185
|
});
|
|
186
186
|
const pool = capable.length > 0 ? capable : [...candidates];
|
|
187
|
-
// A model that cannot hold
|
|
188
|
-
//
|
|
189
|
-
//
|
|
190
|
-
// an optimisation. Applied only when it leaves something behind.
|
|
187
|
+
// A model that cannot hold this request would fail it. Keep it out of this
|
|
188
|
+
// request's candidates when another model fits. Applied only when it leaves
|
|
189
|
+
// something behind.
|
|
191
190
|
const needTokens = input?.estimatedInputTokens ?? 0;
|
|
192
191
|
const fits = needTokens > 0
|
|
193
192
|
? pool.filter((c) => c.contextWindow === undefined || c.contextWindow >= needTokens)
|
|
@@ -67,12 +67,8 @@ export declare class ModelPool {
|
|
|
67
67
|
/**
|
|
68
68
|
* Records a provider failure, setting a cooldown appropriate for the error class.
|
|
69
69
|
*
|
|
70
|
-
* -
|
|
71
|
-
*
|
|
72
|
-
* - Non-retryable classes (auth, context_window): permanent cooldown for the
|
|
73
|
-
* lifetime of this ModelPool instance, because these errors are structural
|
|
74
|
-
* and will not resolve between calls (wrong credentials, model not available
|
|
75
|
-
* in team whitelist, payload exceeds the model's context window).
|
|
70
|
+
* A context-window error belongs to the request, so it does not change member
|
|
71
|
+
* health. Other classes, including auth, use the configured timed cooldown.
|
|
76
72
|
*/
|
|
77
73
|
recordFailure(member: ModelPoolMember, errorClass: ProviderErrorClass): void;
|
|
78
74
|
/**
|
|
@@ -91,30 +91,7 @@ export function classifyProviderError(error) {
|
|
|
91
91
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
92
92
|
// Cooldown constants
|
|
93
93
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
94
|
-
const DEFAULT_COOLDOWN_MS = 60_000; // 1 minute for
|
|
95
|
-
// Non-retryable errors use a permanent-for-the-instance cooldown: 10 years.
|
|
96
|
-
// NOTE: Because ModelPool is stored as a long-lived field on the NeuroLink
|
|
97
|
-
// instance (neurolink.ts constructor), a "permanent" cooldown blocks the
|
|
98
|
-
// member for the entire lifetime of the NeuroLink instance, not just the
|
|
99
|
-
// current call. Only use PERMANENT_COOLDOWN_MS for error classes where the
|
|
100
|
-
// root cause is structural and will not resolve between calls (e.g. wrong API
|
|
101
|
-
// key, model not whitelisted for the team). Transient or unclassified errors
|
|
102
|
-
// must use the timed cooldown so a momentary failure doesn't permanently
|
|
103
|
-
// retire a healthy member.
|
|
104
|
-
const PERMANENT_COOLDOWN_MS = 10 * 365 * 24 * 60 * 60 * 1000;
|
|
105
|
-
/**
|
|
106
|
-
* Error classes that should receive a timed cooldown rather than a permanent
|
|
107
|
-
* ban. "unknown" is deliberately included: because the classification is
|
|
108
|
-
* uncertain, treating an unrecognised error as permanent could retire a
|
|
109
|
-
* healthy member due to a one-off network blip or a non-standard error
|
|
110
|
-
* message. A timed cooldown lets the member recover automatically.
|
|
111
|
-
*/
|
|
112
|
-
const RETRYABLE_ERROR_CLASSES = new Set([
|
|
113
|
-
"rate_limit",
|
|
114
|
-
"server",
|
|
115
|
-
"network",
|
|
116
|
-
"unknown",
|
|
117
|
-
]);
|
|
94
|
+
const DEFAULT_COOLDOWN_MS = 60_000; // 1 minute for member health failures
|
|
118
95
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
119
96
|
// ModelPool
|
|
120
97
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -218,19 +195,16 @@ export class ModelPool {
|
|
|
218
195
|
/**
|
|
219
196
|
* Records a provider failure, setting a cooldown appropriate for the error class.
|
|
220
197
|
*
|
|
221
|
-
* -
|
|
222
|
-
*
|
|
223
|
-
* - Non-retryable classes (auth, context_window): permanent cooldown for the
|
|
224
|
-
* lifetime of this ModelPool instance, because these errors are structural
|
|
225
|
-
* and will not resolve between calls (wrong credentials, model not available
|
|
226
|
-
* in team whitelist, payload exceeds the model's context window).
|
|
198
|
+
* A context-window error belongs to the request, so it does not change member
|
|
199
|
+
* health. Other classes, including auth, use the configured timed cooldown.
|
|
227
200
|
*/
|
|
228
201
|
recordFailure(member, errorClass) {
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
202
|
+
if (errorClass === "context_window") {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
this.state.set(this.memberKey(member), {
|
|
206
|
+
cooldownUntil: this.now() + this.cooldownMs,
|
|
207
|
+
});
|
|
234
208
|
}
|
|
235
209
|
/**
|
|
236
210
|
* Records a successful response, clearing any existing cooldown for this member
|
|
@@ -294,12 +294,9 @@ export type ClassifierRouterDecision = {
|
|
|
294
294
|
* Fraction of the model's window at which compaction should trigger for
|
|
295
295
|
* THIS request, replacing the fixed 0.8 default.
|
|
296
296
|
*
|
|
297
|
-
* **Only ever lower than the default, never higher.** Raising it
|
|
297
|
+
* **Only ever lower than the default, never higher.** Raising it could let
|
|
298
298
|
* a request through that the model then rejects with a context-window
|
|
299
|
-
* error
|
|
300
|
-
* so a single optimistic guess retires the model for the life of the
|
|
301
|
-
* process. Shrinking a budget wastes a little context; growing one is
|
|
302
|
-
* unrecoverable.
|
|
299
|
+
* error. Shrinking the budget compacts a little earlier instead.
|
|
303
300
|
*/
|
|
304
301
|
compactionThreshold?: number;
|
|
305
302
|
/** The scope reading `compactionThreshold` was derived from. */
|
package/dist/types/generate.d.ts
CHANGED
|
@@ -1248,8 +1248,7 @@ export type TextGenerationOptions = {
|
|
|
1248
1248
|
* depends on the entire conversation should compact as late as possible.
|
|
1249
1249
|
* When the classifier router runs with a decision model it fills this in
|
|
1250
1250
|
* per request — always at or below the default, never above, because a
|
|
1251
|
-
* request that overflows the window fails
|
|
1252
|
-
* failure as a permanent cooldown.
|
|
1251
|
+
* request that overflows the window fails.
|
|
1253
1252
|
*/
|
|
1254
1253
|
compactionThreshold?: number;
|
|
1255
1254
|
/**
|
|
@@ -4,8 +4,7 @@
|
|
|
4
4
|
* A ModelPool holds an ordered list of (provider, model, region) members and
|
|
5
5
|
* selects among them per-turn using a configurable strategy. On provider
|
|
6
6
|
* failure, the pool cools down the failed member and retries with the next
|
|
7
|
-
* available one
|
|
8
|
-
* permanent failures.
|
|
7
|
+
* available one. Request-scoped context-window errors do not cool members.
|
|
9
8
|
*/
|
|
10
9
|
/** One candidate provider/model/region tuple in a pool. */
|
|
11
10
|
export type ModelPoolMember = {
|
|
@@ -35,7 +34,7 @@ export type ModelPoolConfig = {
|
|
|
35
34
|
strategy?: ModelPoolStrategy;
|
|
36
35
|
/**
|
|
37
36
|
* How long (ms) a failed member stays in cooldown before it is eligible
|
|
38
|
-
* again. Applies to
|
|
37
|
+
* again. Applies to all error classes except context_window.
|
|
39
38
|
* Default: 60_000 (1 minute).
|
|
40
39
|
*/
|
|
41
40
|
cooldownMs?: number;
|
package/dist/types/modelPool.js
CHANGED
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
* A ModelPool holds an ordered list of (provider, model, region) members and
|
|
5
5
|
* selects among them per-turn using a configurable strategy. On provider
|
|
6
6
|
* failure, the pool cools down the failed member and retries with the next
|
|
7
|
-
* available one
|
|
8
|
-
* permanent failures.
|
|
7
|
+
* available one. Request-scoped context-window errors do not cool members.
|
|
9
8
|
*/
|
|
10
9
|
export {};
|
|
@@ -915,6 +915,16 @@ export type IndividualProviderConfig = {
|
|
|
915
915
|
enableBetaFeatures?: boolean;
|
|
916
916
|
[key: string]: unknown;
|
|
917
917
|
};
|
|
918
|
+
/**
|
|
919
|
+
* The `thinking` block of an Anthropic Messages request, as the direct
|
|
920
|
+
* Anthropic provider builds it from `thinkingConfig`.
|
|
921
|
+
*/
|
|
922
|
+
export type AnthropicThinkingParam = {
|
|
923
|
+
type: "enabled";
|
|
924
|
+
budget_tokens: number;
|
|
925
|
+
} | {
|
|
926
|
+
type: "disabled";
|
|
927
|
+
};
|
|
918
928
|
/**
|
|
919
929
|
* Anthropic-specific provider configuration
|
|
920
930
|
*
|
package/dist/types/stream.d.ts
CHANGED
|
@@ -304,8 +304,7 @@ export type StreamOptions = {
|
|
|
304
304
|
* depends on the entire conversation should compact as late as possible.
|
|
305
305
|
* When the classifier router runs with a decision model it fills this in
|
|
306
306
|
* per request — always at or below the default, never above, because a
|
|
307
|
-
* request that overflows the window fails
|
|
308
|
-
* failure as a permanent cooldown.
|
|
307
|
+
* request that overflows the window fails.
|
|
309
308
|
*/
|
|
310
309
|
compactionThreshold?: number;
|
|
311
310
|
/**
|
package/dist/types/stt.d.ts
CHANGED
|
@@ -195,6 +195,12 @@ export type STTHandler = {
|
|
|
195
195
|
* before deciding which engine transcribes.
|
|
196
196
|
*/
|
|
197
197
|
languageProbeModel?(): string | undefined;
|
|
198
|
+
/**
|
|
199
|
+
* Releases what the handler holds (a worker thread, a loaded model). The
|
|
200
|
+
* SDK calls it on handlers it builds for a single call; handlers registered
|
|
201
|
+
* with `STTProcessor.registerHandler` are shared and never disposed by it.
|
|
202
|
+
*/
|
|
203
|
+
dispose?(): Promise<void> | void;
|
|
198
204
|
maxAudioDuration?: number;
|
|
199
205
|
supportsStreaming?: boolean;
|
|
200
206
|
};
|
|
@@ -787,6 +787,8 @@ export type TranscribeDeps = STTCorrectionDeps & {
|
|
|
787
787
|
* environment-derived default applies when absent.
|
|
788
788
|
*/
|
|
789
789
|
attachmentPolicy?: AttachmentPolicy;
|
|
790
|
+
/** Disposes the handlers `getHandler` built for this request. */
|
|
791
|
+
release?: () => Promise<void>;
|
|
790
792
|
};
|
|
791
793
|
/** Resolved endpointer tuning: `STTStreamingOptions` with every default applied, plus the input rate. */
|
|
792
794
|
export type STTEndpointerConfig = {
|