@juspay/neurolink 13.12.4 → 13.12.6
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/browser/neurolink.min.js +440 -440
- package/dist/evaluation/scorers/rule/formatScorer.d.ts +8 -0
- package/dist/evaluation/scorers/rule/formatScorer.js +75 -6
- package/dist/neurolink.js +36 -6
- package/dist/providers/anthropic/client.js +96 -8
- package/dist/providers/openaiChatCompletionsBase.js +3 -2
- package/dist/providers/openaiChatCompletionsClient.js +53 -1
- package/dist/types/openaiCompatible.d.ts +6 -1
- package/dist/types/providers.d.ts +10 -0
- 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 +3 -2
- package/package.json +4 -1
|
@@ -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
|
@@ -15095,7 +15095,12 @@ Current user's request: ${currentInput}`;
|
|
|
15095
15095
|
this.buildTranscribeDeps(options.credentials?.stt),
|
|
15096
15096
|
import("./voice/transcribe.js"),
|
|
15097
15097
|
]);
|
|
15098
|
-
|
|
15098
|
+
try {
|
|
15099
|
+
return await runTranscribe(options, deps);
|
|
15100
|
+
}
|
|
15101
|
+
finally {
|
|
15102
|
+
await deps.release?.();
|
|
15103
|
+
}
|
|
15099
15104
|
}
|
|
15100
15105
|
/**
|
|
15101
15106
|
* Transcribe a live stream of PCM16LE frames. Engines with a native stream
|
|
@@ -15117,7 +15122,12 @@ Current user's request: ${currentInput}`;
|
|
|
15117
15122
|
this.buildTranscribeDeps(options.credentials?.stt),
|
|
15118
15123
|
import("./voice/transcribeStream.js"),
|
|
15119
15124
|
]);
|
|
15120
|
-
|
|
15125
|
+
try {
|
|
15126
|
+
yield* runTranscribeStream(options, deps);
|
|
15127
|
+
}
|
|
15128
|
+
finally {
|
|
15129
|
+
await deps.release?.();
|
|
15130
|
+
}
|
|
15121
15131
|
}
|
|
15122
15132
|
/**
|
|
15123
15133
|
* Instance `credentials.stt` with a per-call `stt` slice merged on top,
|
|
@@ -15179,19 +15189,38 @@ Current user's request: ${currentInput}`;
|
|
|
15179
15189
|
// Same precedence as STTProcessor.resolveHandler, synchronously: a
|
|
15180
15190
|
// credentials slice for the provider builds a handler from it; else the
|
|
15181
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
|
+
};
|
|
15182
15200
|
const getHandler = (name) => {
|
|
15183
15201
|
if (resolveCallSTTEndpoints(credentials)[name.trim().toLowerCase()]) {
|
|
15184
|
-
return
|
|
15202
|
+
return build(name, credentials);
|
|
15185
15203
|
}
|
|
15186
15204
|
const descriptor = getSTTProviderDescriptor(name);
|
|
15187
15205
|
if (!descriptor) {
|
|
15188
15206
|
return STTProcessor.getHandler(name);
|
|
15189
15207
|
}
|
|
15190
15208
|
if (credentials?.[descriptor.credentialsKey] !== undefined) {
|
|
15191
|
-
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
|
+
}
|
|
15192
15223
|
}
|
|
15193
|
-
return (STTProcessor.getHandler(descriptor.name) ??
|
|
15194
|
-
createSTTHandler(descriptor.name));
|
|
15195
15224
|
};
|
|
15196
15225
|
return {
|
|
15197
15226
|
...this.buildSTTCorrectionDeps(),
|
|
@@ -15199,6 +15228,7 @@ Current user's request: ${currentInput}`;
|
|
|
15199
15228
|
resolveProvider,
|
|
15200
15229
|
getHandler,
|
|
15201
15230
|
attachmentPolicy: this.attachmentPolicy,
|
|
15231
|
+
release,
|
|
15202
15232
|
};
|
|
15203
15233
|
}
|
|
15204
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
|
|
@@ -104,8 +104,9 @@ const resolveAgainstSchema = (text, schema) => {
|
|
|
104
104
|
* The one place a finish reason becomes the unified spelling. Accepts the wire's
|
|
105
105
|
* `finish_reason` (`tool_calls`, `content_filter`) and the unified spelling a
|
|
106
106
|
* middleware's own finish part already carries (`tool-calls`, `content-filter`),
|
|
107
|
-
* since both reach the stream path. Anything else, including `stop
|
|
108
|
-
*
|
|
107
|
+
* since both reach the stream path. Anything else, including `stop` and an
|
|
108
|
+
* absent value, reads as `stop`. A wire `error` finish never gets here: the SSE
|
|
109
|
+
* parser throws on it, and on a stream that ended with no terminal marker.
|
|
109
110
|
*/
|
|
110
111
|
const toUnifiedFinishReason = (reason) => {
|
|
111
112
|
switch (reason) {
|
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
* module is to be the native replacement for the AI SDK's OpenAI wrapper.
|
|
15
15
|
*/
|
|
16
16
|
import { createParser } from "eventsource-parser";
|
|
17
|
+
import { ErrorCategory, ErrorSeverity } from "../constants/enums.js";
|
|
18
|
+
import { NeuroLinkError } from "../utils/errorHandling.js";
|
|
17
19
|
import { sanitizeToolName } from "../mcp/toolConverter.js";
|
|
18
20
|
import { resolveSamplingParams } from "../models/modelRegistry.js";
|
|
19
21
|
import { convertZodToJsonSchema, normalizeWireToolSchema, } from "../utils/schemaConversion.js";
|
|
@@ -725,13 +727,24 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
|
|
|
725
727
|
};
|
|
726
728
|
const decoder = new TextDecoder();
|
|
727
729
|
let parseErr;
|
|
730
|
+
// An upstream error frame or `finish_reason: "error"`.
|
|
731
|
+
let streamErr;
|
|
732
|
+
// True once the upstream said it was done: `[DONE]` or any finish_reason.
|
|
733
|
+
let sawTerminal = false;
|
|
728
734
|
// Key of the tool call the previous delta wrote to (for unindexed deltas).
|
|
729
735
|
let lastToolCallKey;
|
|
730
736
|
let nextToolCallKey = 0;
|
|
731
737
|
const toolCallKeysById = new Map();
|
|
732
738
|
const handleEvent = (msg) => {
|
|
739
|
+
if (streamErr) {
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
733
742
|
const data = msg.data;
|
|
734
|
-
if (
|
|
743
|
+
if (data === "[DONE]") {
|
|
744
|
+
sawTerminal = true;
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
if (!data) {
|
|
735
748
|
return;
|
|
736
749
|
}
|
|
737
750
|
let chunk;
|
|
@@ -742,6 +755,13 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
|
|
|
742
755
|
parseErr = err instanceof Error ? err : new Error(String(err));
|
|
743
756
|
return;
|
|
744
757
|
}
|
|
758
|
+
if (chunk.error) {
|
|
759
|
+
streamErr ??= streamFailure("OPENAI_COMPAT_STREAM_ERROR_FRAME", `Upstream sent an error frame mid-stream: ${String(chunk.error.message ?? JSON.stringify(chunk.error)).slice(0, 500)}`, {
|
|
760
|
+
upstreamError: JSON.stringify(chunk.error).slice(0, 500),
|
|
761
|
+
partialTextLength: result.text.length,
|
|
762
|
+
});
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
745
765
|
if (chunk.usage) {
|
|
746
766
|
result.usage = chunk.usage;
|
|
747
767
|
}
|
|
@@ -828,7 +848,12 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
|
|
|
828
848
|
}
|
|
829
849
|
}
|
|
830
850
|
}
|
|
851
|
+
if (choice.finish_reason === "error") {
|
|
852
|
+
streamErr ??= streamFailure("OPENAI_COMPAT_STREAM_FINISH_ERROR", 'Upstream ended the stream with finish_reason "error".', { partialTextLength: result.text.length });
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
831
855
|
if (choice.finish_reason) {
|
|
856
|
+
sawTerminal = true;
|
|
832
857
|
result.finishReason = choice.finish_reason;
|
|
833
858
|
}
|
|
834
859
|
};
|
|
@@ -841,6 +866,15 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
|
|
|
841
866
|
break;
|
|
842
867
|
}
|
|
843
868
|
parser.feed(decoder.decode(value, { stream: true }));
|
|
869
|
+
if (streamErr) {
|
|
870
|
+
try {
|
|
871
|
+
await reader.cancel();
|
|
872
|
+
}
|
|
873
|
+
catch {
|
|
874
|
+
// Keep the original upstream error when reader cleanup fails.
|
|
875
|
+
}
|
|
876
|
+
break;
|
|
877
|
+
}
|
|
844
878
|
}
|
|
845
879
|
parser.feed(decoder.decode());
|
|
846
880
|
}
|
|
@@ -850,8 +884,26 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
|
|
|
850
884
|
if (parseErr) {
|
|
851
885
|
throw parseErr;
|
|
852
886
|
}
|
|
887
|
+
if (streamErr) {
|
|
888
|
+
throw streamErr;
|
|
889
|
+
}
|
|
890
|
+
// The body closed without `[DONE]` or a finish_reason: truncated stream.
|
|
891
|
+
// Not retriable (same as ANTHROPIC_STREAM_TRUNCATED).
|
|
892
|
+
if (!sawTerminal) {
|
|
893
|
+
throw streamFailure("OPENAI_COMPAT_STREAM_TRUNCATED", "Stream ended before [DONE] or a finish_reason; the response is incomplete.", { partialTextLength: result.text.length });
|
|
894
|
+
}
|
|
853
895
|
return result;
|
|
854
896
|
};
|
|
897
|
+
function streamFailure(code, message, context) {
|
|
898
|
+
return new NeuroLinkError({
|
|
899
|
+
code,
|
|
900
|
+
message,
|
|
901
|
+
category: ErrorCategory.NETWORK,
|
|
902
|
+
severity: ErrorSeverity.HIGH,
|
|
903
|
+
retriable: false,
|
|
904
|
+
context,
|
|
905
|
+
});
|
|
906
|
+
}
|
|
855
907
|
function extractOpenAICompatErrorMessage(parsed) {
|
|
856
908
|
const message = parsed?.error?.message;
|
|
857
909
|
if (typeof message === "string" && message.trim().length > 0) {
|
|
@@ -144,7 +144,7 @@ export type OpenAICompatStreamDelta = {
|
|
|
144
144
|
export type OpenAICompatStreamChunkChoice = {
|
|
145
145
|
index: number;
|
|
146
146
|
delta: OpenAICompatStreamDelta;
|
|
147
|
-
finish_reason: "stop" | "length" | "tool_calls" | "function_call" | "content_filter" | null;
|
|
147
|
+
finish_reason: "stop" | "length" | "tool_calls" | "function_call" | "content_filter" | "error" | null;
|
|
148
148
|
};
|
|
149
149
|
export type OpenAICompatChatStreamChunk = {
|
|
150
150
|
id?: string;
|
|
@@ -152,6 +152,11 @@ export type OpenAICompatChatStreamChunk = {
|
|
|
152
152
|
created?: number;
|
|
153
153
|
model?: string;
|
|
154
154
|
choices: OpenAICompatStreamChunkChoice[];
|
|
155
|
+
error?: {
|
|
156
|
+
message?: string;
|
|
157
|
+
type?: string;
|
|
158
|
+
code?: string | number;
|
|
159
|
+
};
|
|
155
160
|
usage?: OpenAICompatUsage;
|
|
156
161
|
};
|
|
157
162
|
export type OpenAICompatErrorMessage = string | ReadonlyArray<{
|
|
@@ -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/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 = {
|
|
@@ -84,6 +84,12 @@ export declare class STTProcessor {
|
|
|
84
84
|
* module, so a static import back would be a cycle.
|
|
85
85
|
*/
|
|
86
86
|
static resolveHandler(provider: string, credentials?: STTCredentials): Promise<STTHandler | undefined>;
|
|
87
|
+
/**
|
|
88
|
+
* {@link resolveHandler} that also says whether the handler was built for
|
|
89
|
+
* this call (`owned`) rather than taken from the registry. The caller of an
|
|
90
|
+
* owned handler is the only one holding it, so it must dispose it.
|
|
91
|
+
*/
|
|
92
|
+
private static resolveOwnedHandler;
|
|
87
93
|
/**
|
|
88
94
|
* List the names of all registered providers.
|
|
89
95
|
*/
|
|
@@ -99,11 +99,19 @@ export class STTProcessor {
|
|
|
99
99
|
* module, so a static import back would be a cycle.
|
|
100
100
|
*/
|
|
101
101
|
static async resolveHandler(provider, credentials) {
|
|
102
|
+
return (await this.resolveOwnedHandler(provider, credentials)).handler;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* {@link resolveHandler} that also says whether the handler was built for
|
|
106
|
+
* this call (`owned`) rather than taken from the registry. The caller of an
|
|
107
|
+
* owned handler is the only one holding it, so it must dispose it.
|
|
108
|
+
*/
|
|
109
|
+
static async resolveOwnedHandler(provider, credentials) {
|
|
102
110
|
const endpoint = resolveCallSTTEndpoints(credentials)[provider.trim().toLowerCase()];
|
|
103
111
|
if (endpoint) {
|
|
104
112
|
// A per-call named endpoint: a fresh handler, never the registry's.
|
|
105
113
|
const { createSTTHandler } = await import("../voice/index.js");
|
|
106
|
-
return createSTTHandler(provider, credentials);
|
|
114
|
+
return { handler: createSTTHandler(provider, credentials), owned: true };
|
|
107
115
|
}
|
|
108
116
|
const descriptor = getSTTProviderDescriptor(provider);
|
|
109
117
|
const slice = descriptor
|
|
@@ -111,14 +119,20 @@ export class STTProcessor {
|
|
|
111
119
|
: undefined;
|
|
112
120
|
if (descriptor && slice !== undefined) {
|
|
113
121
|
const { createSTTHandler } = await import("../voice/index.js");
|
|
114
|
-
return
|
|
122
|
+
return {
|
|
123
|
+
handler: createSTTHandler(descriptor.name, credentials),
|
|
124
|
+
owned: true,
|
|
125
|
+
};
|
|
115
126
|
}
|
|
116
127
|
const registered = this.getHandler(provider);
|
|
117
128
|
if (registered || !descriptor) {
|
|
118
|
-
return registered;
|
|
129
|
+
return { handler: registered, owned: false };
|
|
119
130
|
}
|
|
120
131
|
const { createSTTHandler } = await import("../voice/index.js");
|
|
121
|
-
return
|
|
132
|
+
return {
|
|
133
|
+
handler: createSTTHandler(descriptor.name, credentials),
|
|
134
|
+
owned: true,
|
|
135
|
+
};
|
|
122
136
|
}
|
|
123
137
|
/**
|
|
124
138
|
* List the names of all registered providers.
|
|
@@ -197,6 +211,7 @@ export class STTProcessor {
|
|
|
197
211
|
"stt.language": options.language,
|
|
198
212
|
"stt.format": options.format,
|
|
199
213
|
});
|
|
214
|
+
let ownedHandler;
|
|
200
215
|
try {
|
|
201
216
|
// 1. Audio validation: reject empty + oversized audio
|
|
202
217
|
const byteLength = audio instanceof ArrayBuffer ? audio.byteLength : audio.length;
|
|
@@ -227,7 +242,14 @@ export class STTProcessor {
|
|
|
227
242
|
});
|
|
228
243
|
}
|
|
229
244
|
// 2. Handler lookup and error if provider not supported
|
|
230
|
-
const
|
|
245
|
+
const resolved = await this.resolveOwnedHandler(provider, credentials);
|
|
246
|
+
const handler = resolved.handler;
|
|
247
|
+
// A handler built for this call has no other holder: dispose it when
|
|
248
|
+
// the call ends, or each credentials slice leaks an engine (WhistleSTT
|
|
249
|
+
// starts a worker thread per instance).
|
|
250
|
+
if (handler && resolved.owned) {
|
|
251
|
+
ownedHandler = handler;
|
|
252
|
+
}
|
|
231
253
|
if (!handler) {
|
|
232
254
|
logger.error(`[STTProcessor] Provider "${provider}" is not registered`);
|
|
233
255
|
throw new STTError({
|
|
@@ -364,5 +386,17 @@ export class STTProcessor {
|
|
|
364
386
|
originalError: err instanceof Error ? err : undefined,
|
|
365
387
|
});
|
|
366
388
|
}
|
|
389
|
+
finally {
|
|
390
|
+
if (ownedHandler?.dispose) {
|
|
391
|
+
try {
|
|
392
|
+
await ownedHandler.dispose();
|
|
393
|
+
}
|
|
394
|
+
catch (disposeErr) {
|
|
395
|
+
logger.warn(`[STTProcessor] Failed to dispose the "${provider}" handler: ${disposeErr instanceof Error
|
|
396
|
+
? disposeErr.message
|
|
397
|
+
: String(disposeErr)}`);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
367
401
|
}
|
|
368
402
|
}
|