@juspay/neurolink 10.12.8 → 10.12.9
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 +6 -0
- package/dist/browser/neurolink.min.js +401 -401
- package/dist/core/modules/GenerationHandler.js +36 -14
- package/dist/lib/core/modules/GenerationHandler.js +36 -14
- package/dist/lib/neurolink.d.ts +15 -0
- package/dist/lib/neurolink.js +77 -44
- package/dist/lib/providers/anthropic/client.js +17 -1
- package/dist/lib/types/utilities.d.ts +29 -0
- package/dist/lib/utils/json/coerce.d.ts +21 -1
- package/dist/lib/utils/json/coerce.js +148 -11
- package/dist/neurolink.d.ts +15 -0
- package/dist/neurolink.js +77 -44
- package/dist/providers/anthropic/client.js +17 -1
- package/dist/types/utilities.d.ts +29 -0
- package/dist/utils/json/coerce.d.ts +21 -1
- package/dist/utils/json/coerce.js +148 -11
- package/package.json +2 -1
|
@@ -23,6 +23,48 @@ import { nextBalancedJsonSpan } from "./extract.js";
|
|
|
23
23
|
function hasSafeParse(schema) {
|
|
24
24
|
return typeof schema.safeParse === "function";
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* Does `value` satisfy `schema`? A schema we cannot validate with (absent, or
|
|
28
|
+
* without a Zod-style `safeParse`) accepts everything — callers use this as a
|
|
29
|
+
* gate, not as proof, so an unknown schema must never block a value.
|
|
30
|
+
*
|
|
31
|
+
* Exists so the consumers of coerceJsonToSchema can refuse to publish a
|
|
32
|
+
* recovered value as `structuredData` when the caller's schema rejects it —
|
|
33
|
+
* e.g. a raw *string* under an object schema, which is the shape a truncated
|
|
34
|
+
* response degrades to.
|
|
35
|
+
*/
|
|
36
|
+
export function schemaAccepts(schema, value) {
|
|
37
|
+
if (!schema || !hasSafeParse(schema)) {
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
return schema.safeParse(value).success;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Recover a JSON *scalar* root (string/number/boolean) from model text. The
|
|
44
|
+
* object/array case is handled by `coerceJsonToSchema`; this covers the
|
|
45
|
+
* residual scalar root after that path returns null. Encapsulates the JSON
|
|
46
|
+
* parsing, the empty-string normalization, and the `schemaAccepts` gate so the
|
|
47
|
+
* same policy cannot drift between consumers (`neurolink.recoverStructuredData`
|
|
48
|
+
* and `GenerationHandler.coerceTextMode`).
|
|
49
|
+
*/
|
|
50
|
+
export function recoverScalarRoot(text, schema) {
|
|
51
|
+
try {
|
|
52
|
+
const scalar = JSON.parse(text);
|
|
53
|
+
if (scalar === "") {
|
|
54
|
+
return { kind: "empty" };
|
|
55
|
+
}
|
|
56
|
+
if (scalar === null || scalar === undefined) {
|
|
57
|
+
return { kind: "nullish" };
|
|
58
|
+
}
|
|
59
|
+
if (schemaAccepts(schema, scalar)) {
|
|
60
|
+
return { kind: "accepted", value: scalar };
|
|
61
|
+
}
|
|
62
|
+
return { kind: "rejected", value: scalar };
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return { kind: "not-json" };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
26
68
|
/**
|
|
27
69
|
* Parse `candidate` as JSON, repairing common escaping mistakes on failure.
|
|
28
70
|
* Returns the parsed value plus whether jsonrepair had to alter the text.
|
|
@@ -51,6 +93,34 @@ function parseOrRepair(candidate) {
|
|
|
51
93
|
}
|
|
52
94
|
/** Bounds the recursive nested-string unwrap against pathological inputs. */
|
|
53
95
|
const MAX_NESTED_UNWRAP_DEPTH = 6;
|
|
96
|
+
/** Bounds the structural back-off when salvaging a truncated root object. */
|
|
97
|
+
const MAX_SALVAGE_TRIMS = 8;
|
|
98
|
+
/**
|
|
99
|
+
* Last-resort recovery for output cut off mid-JSON: walk the unclosed root span
|
|
100
|
+
* backwards to successively earlier structural boundaries (`,` / `}` / `]`) and
|
|
101
|
+
* re-attempt parse+repair at each one. Truncation can land somewhere jsonrepair
|
|
102
|
+
* cannot close on its own (inside an escape, a half-written key, a dangling
|
|
103
|
+
* separator); dropping back to the last completed field gives it a repairable
|
|
104
|
+
* prefix. Returns a PARTIAL object — the fields the model did finish — so a
|
|
105
|
+
* truncated response degrades to an incomplete object rather than to raw text.
|
|
106
|
+
*/
|
|
107
|
+
function salvageTruncatedRoot(span) {
|
|
108
|
+
let candidate = span;
|
|
109
|
+
for (let i = 0; i < MAX_SALVAGE_TRIMS && candidate.length > 1; i++) {
|
|
110
|
+
const cut = Math.max(candidate.lastIndexOf(","), candidate.lastIndexOf("}"), candidate.lastIndexOf("]"));
|
|
111
|
+
if (cut <= 0) {
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
candidate = candidate.slice(0, cut);
|
|
115
|
+
const outcome = parseOrRepair(candidate);
|
|
116
|
+
if (outcome !== undefined &&
|
|
117
|
+
outcome.value !== null &&
|
|
118
|
+
typeof outcome.value === "object") {
|
|
119
|
+
return outcome.value;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
54
124
|
/**
|
|
55
125
|
* Recursively replace any string-valued field whose content is itself a JSON
|
|
56
126
|
* object/array with the parsed value. Models sometimes double-encode a NESTED
|
|
@@ -135,30 +205,54 @@ export function coerceJsonToSchema(text, schema) {
|
|
|
135
205
|
// 3. first "{" or "[" to end of text (TRUNCATED output —
|
|
136
206
|
// finishReason=length — where the closing bracket was cut off;
|
|
137
207
|
// jsonrepair closes it)
|
|
138
|
-
// `truncated` marks
|
|
139
|
-
//
|
|
140
|
-
//
|
|
208
|
+
// `truncated` marks a candidate that could only come from output cut short:
|
|
209
|
+
// the first-open-to-end span, and — when the ROOT bracket never closes —
|
|
210
|
+
// every other candidate too, since all of them are then partial views of an
|
|
211
|
+
// unfinished document.
|
|
212
|
+
//
|
|
213
|
+
// `rootAligned` marks candidates that start at the document's first opening
|
|
214
|
+
// bracket, i.e. at the real root. Candidates are ordered root-aligned FIRST.
|
|
215
|
+
// On truncated output the root brace never balances, so the balanced scan
|
|
216
|
+
// walks on and matches brackets that live INSIDE a string value (`[step 1]`
|
|
217
|
+
// in a shell script, say) — a syntactically fine but semantically bogus
|
|
218
|
+
// array. Preferring the root keeps the partial real object ahead of that.
|
|
141
219
|
const candidates = [];
|
|
220
|
+
const openIndexes = [text.indexOf("{"), text.indexOf("[")].filter((i) => i >= 0);
|
|
221
|
+
const firstOpen = openIndexes.length > 0 ? Math.min(...openIndexes) : -1;
|
|
222
|
+
let rootClosed = false;
|
|
142
223
|
let searchFrom = 0;
|
|
143
224
|
for (;;) {
|
|
144
225
|
const found = nextBalancedJsonSpan(text, searchFrom);
|
|
145
226
|
if (!found) {
|
|
146
227
|
break;
|
|
147
228
|
}
|
|
148
|
-
|
|
229
|
+
const start = found.end - found.span.length;
|
|
230
|
+
if (start === firstOpen) {
|
|
231
|
+
rootClosed = true;
|
|
232
|
+
}
|
|
233
|
+
candidates.push({
|
|
234
|
+
text: found.span,
|
|
235
|
+
truncated: false,
|
|
236
|
+
rootAligned: start === firstOpen,
|
|
237
|
+
});
|
|
149
238
|
searchFrom = found.end;
|
|
150
239
|
}
|
|
151
|
-
|
|
152
|
-
const
|
|
240
|
+
// No balanced span starts at the root bracket → the document is unclosed.
|
|
241
|
+
const rootUnclosed = firstOpen >= 0 && !rootClosed;
|
|
153
242
|
const lastClose = Math.max(text.lastIndexOf("}"), text.lastIndexOf("]"));
|
|
154
243
|
if (firstOpen >= 0 && lastClose > firstOpen) {
|
|
155
244
|
candidates.push({
|
|
156
245
|
text: text.slice(firstOpen, lastClose + 1),
|
|
157
|
-
truncated:
|
|
246
|
+
truncated: rootUnclosed,
|
|
247
|
+
rootAligned: true,
|
|
158
248
|
});
|
|
159
249
|
}
|
|
160
250
|
if (firstOpen >= 0) {
|
|
161
|
-
candidates.push({
|
|
251
|
+
candidates.push({
|
|
252
|
+
text: text.slice(firstOpen),
|
|
253
|
+
truncated: true,
|
|
254
|
+
rootAligned: true,
|
|
255
|
+
});
|
|
162
256
|
}
|
|
163
257
|
// JSON-string-literal wrapper: some providers double-encode and return the
|
|
164
258
|
// object as a JSON *string* (e.g. `"{\"k\":1}"`). Unwrap one layer and add
|
|
@@ -174,7 +268,11 @@ export function coerceJsonToSchema(text, schema) {
|
|
|
174
268
|
if (!innerSpan) {
|
|
175
269
|
break;
|
|
176
270
|
}
|
|
177
|
-
candidates.push({
|
|
271
|
+
candidates.push({
|
|
272
|
+
text: innerSpan.span,
|
|
273
|
+
truncated: false,
|
|
274
|
+
rootAligned: false,
|
|
275
|
+
});
|
|
178
276
|
innerFrom = innerSpan.end;
|
|
179
277
|
}
|
|
180
278
|
}
|
|
@@ -183,11 +281,20 @@ export function coerceJsonToSchema(text, schema) {
|
|
|
183
281
|
// not a string literal — ignore
|
|
184
282
|
}
|
|
185
283
|
}
|
|
284
|
+
// Stable partition: root-aligned candidates first. Only the ORDER changes —
|
|
285
|
+
// no candidate is dropped — so the multi-object "prefer the most complete
|
|
286
|
+
// schema-valid candidate" selection below is unaffected (it is order
|
|
287
|
+
// independent), while the unschema'd first-parseable-wins path and the
|
|
288
|
+
// `firstValid` fallback now favour the document's real root.
|
|
289
|
+
const ordered = [
|
|
290
|
+
...candidates.filter((c) => c.rootAligned),
|
|
291
|
+
...candidates.filter((c) => !c.rootAligned),
|
|
292
|
+
];
|
|
186
293
|
let firstValid;
|
|
187
294
|
const schemaValid = [];
|
|
188
295
|
const hasSchema = !!(schema && hasSafeParse(schema));
|
|
189
296
|
const seen = new Set();
|
|
190
|
-
for (const candidate of
|
|
297
|
+
for (const candidate of ordered) {
|
|
191
298
|
if (seen.has(candidate.text)) {
|
|
192
299
|
continue;
|
|
193
300
|
}
|
|
@@ -202,6 +309,7 @@ export function coerceJsonToSchema(text, schema) {
|
|
|
202
309
|
value: outcome.value,
|
|
203
310
|
repaired: outcome.repaired,
|
|
204
311
|
truncated: candidate.truncated,
|
|
312
|
+
rootAligned: candidate.rootAligned,
|
|
205
313
|
};
|
|
206
314
|
if (firstValid === undefined) {
|
|
207
315
|
firstValid = record;
|
|
@@ -229,6 +337,7 @@ export function coerceJsonToSchema(text, schema) {
|
|
|
229
337
|
value: unwrapped.value,
|
|
230
338
|
repaired: true,
|
|
231
339
|
truncated: candidate.truncated,
|
|
340
|
+
rootAligned: candidate.rootAligned,
|
|
232
341
|
});
|
|
233
342
|
}
|
|
234
343
|
else if (
|
|
@@ -247,6 +356,7 @@ export function coerceJsonToSchema(text, schema) {
|
|
|
247
356
|
value: outcome.value[0],
|
|
248
357
|
repaired: true,
|
|
249
358
|
truncated: candidate.truncated,
|
|
359
|
+
rootAligned: candidate.rootAligned,
|
|
250
360
|
});
|
|
251
361
|
}
|
|
252
362
|
}
|
|
@@ -261,7 +371,34 @@ export function coerceJsonToSchema(text, schema) {
|
|
|
261
371
|
? cur
|
|
262
372
|
: best)
|
|
263
373
|
: undefined;
|
|
264
|
-
|
|
374
|
+
let chosen = schemaMatch ?? firstValid;
|
|
375
|
+
// Salvage the root when the document is unclosed AND nothing trustworthy came
|
|
376
|
+
// out of it: either nothing parsed at all, or the only parseable candidate is
|
|
377
|
+
// a bracket pair scraped from INSIDE a string value (not root-aligned, not
|
|
378
|
+
// schema-valid) — the `["step 1"]`-from-a-shell-script case. Backing off to
|
|
379
|
+
// the last completed field yields a PARTIAL OBJECT flagged `truncated`,
|
|
380
|
+
// instead of a bogus value or raw text degrading to a string.
|
|
381
|
+
if (rootUnclosed &&
|
|
382
|
+
schemaMatch === undefined &&
|
|
383
|
+
(chosen === undefined || !chosen.rootAligned)) {
|
|
384
|
+
const salvaged = salvageTruncatedRoot(text.slice(firstOpen));
|
|
385
|
+
if (salvaged !== undefined) {
|
|
386
|
+
logger.debug("[coerceJsonToSchema] salvaged a partial truncated object", {
|
|
387
|
+
textLength: text.length,
|
|
388
|
+
});
|
|
389
|
+
chosen = {
|
|
390
|
+
value: salvaged,
|
|
391
|
+
repaired: true,
|
|
392
|
+
truncated: true,
|
|
393
|
+
rootAligned: true,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
else if (chosen !== undefined) {
|
|
397
|
+
// Nothing salvageable, but we still know the output was truncated —
|
|
398
|
+
// never report a candidate scraped from a truncated document as complete.
|
|
399
|
+
chosen = { ...chosen, truncated: true };
|
|
400
|
+
}
|
|
401
|
+
}
|
|
265
402
|
if (chosen === undefined) {
|
|
266
403
|
return null;
|
|
267
404
|
}
|
package/dist/neurolink.d.ts
CHANGED
|
@@ -775,6 +775,21 @@ export declare class NeuroLink {
|
|
|
775
775
|
private applyClassifierRouting;
|
|
776
776
|
private prepareGenerateAugmentations;
|
|
777
777
|
private buildGenerateTextOptions;
|
|
778
|
+
/**
|
|
779
|
+
* Provider-agnostic JSON recovery for schema requests. Structured-output
|
|
780
|
+
* enforcement makes valid JSON the overwhelming case; for every other
|
|
781
|
+
* provider path — including generate() overrides (Vertex, Anthropic,
|
|
782
|
+
* Bedrock, Google AI Studio) — object/array roots are recovered here via
|
|
783
|
+
* balanced-scan + jsonrepair and scalar JSON roots via plain JSON.parse,
|
|
784
|
+
* with the parsed value exposed as `structuredData`. If nothing JSON-shaped
|
|
785
|
+
* is recoverable (pure prose), the raw text is returned, `structuredData`
|
|
786
|
+
* stays undefined, and a WARN makes the case observable.
|
|
787
|
+
*
|
|
788
|
+
* Mutates `textResult` in place, and must run BEFORE the end-of-generation
|
|
789
|
+
* emits so event consumers see the same content/structuredData the caller
|
|
790
|
+
* receives.
|
|
791
|
+
*/
|
|
792
|
+
private recoverStructuredData;
|
|
778
793
|
private finalizeGenerateRequestResult;
|
|
779
794
|
private emitGenerateErrorEvent;
|
|
780
795
|
/**
|
package/dist/neurolink.js
CHANGED
|
@@ -74,7 +74,7 @@ import { CircuitBreaker, ERROR_CODES, ErrorFactory, isAbortError, isRetriableErr
|
|
|
74
74
|
import { hasLifecycleErrorFired, markLifecycleErrorFired, } from "./utils/lifecycleCallbacks.js";
|
|
75
75
|
import { resolveLifecycleTimeoutMs } from "./utils/lifecycleTimeout.js";
|
|
76
76
|
import { cloneOptionsForCallIsolation } from "./utils/cloneOptions.js";
|
|
77
|
-
import { coerceJsonToSchema } from "./utils/json/coerce.js";
|
|
77
|
+
import { coerceJsonToSchema, recoverScalarRoot, schemaAccepts, } from "./utils/json/coerce.js";
|
|
78
78
|
// Factory processing imports
|
|
79
79
|
import { createCleanStreamOptions, enhanceTextGenerationOptions, processFactoryOptions, processStreamingFactoryOptions, validateFactoryConfig, } from "./utils/factoryProcessing.js";
|
|
80
80
|
import { logger, mcpLogger } from "./utils/logger.js";
|
|
@@ -4058,52 +4058,85 @@ Current user's request: ${currentInput}`;
|
|
|
4058
4058
|
}
|
|
4059
4059
|
return textOptions;
|
|
4060
4060
|
}
|
|
4061
|
-
|
|
4062
|
-
|
|
4063
|
-
|
|
4064
|
-
|
|
4065
|
-
|
|
4066
|
-
|
|
4067
|
-
|
|
4068
|
-
|
|
4069
|
-
|
|
4070
|
-
|
|
4071
|
-
|
|
4072
|
-
|
|
4073
|
-
|
|
4074
|
-
|
|
4075
|
-
|
|
4076
|
-
|
|
4077
|
-
|
|
4078
|
-
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
4082
|
-
|
|
4083
|
-
|
|
4084
|
-
|
|
4085
|
-
|
|
4061
|
+
/**
|
|
4062
|
+
* Provider-agnostic JSON recovery for schema requests. Structured-output
|
|
4063
|
+
* enforcement makes valid JSON the overwhelming case; for every other
|
|
4064
|
+
* provider path — including generate() overrides (Vertex, Anthropic,
|
|
4065
|
+
* Bedrock, Google AI Studio) — object/array roots are recovered here via
|
|
4066
|
+
* balanced-scan + jsonrepair and scalar JSON roots via plain JSON.parse,
|
|
4067
|
+
* with the parsed value exposed as `structuredData`. If nothing JSON-shaped
|
|
4068
|
+
* is recoverable (pure prose), the raw text is returned, `structuredData`
|
|
4069
|
+
* stays undefined, and a WARN makes the case observable.
|
|
4070
|
+
*
|
|
4071
|
+
* Mutates `textResult` in place, and must run BEFORE the end-of-generation
|
|
4072
|
+
* emits so event consumers see the same content/structuredData the caller
|
|
4073
|
+
* receives.
|
|
4074
|
+
*/
|
|
4075
|
+
recoverStructuredData(textResult, schema) {
|
|
4076
|
+
// A provider path that produced its own `structuredData` normally owns it.
|
|
4077
|
+
// The one exception is a STRING the caller's schema rejects: that is the
|
|
4078
|
+
// raw completion leaking through as structured output (the shape a
|
|
4079
|
+
// truncated response degrades to), so re-run recovery over the text rather
|
|
4080
|
+
// than handing back a value the declared schema forbids.
|
|
4081
|
+
const structuredIsRejectedString = typeof textResult.structuredData === "string" &&
|
|
4082
|
+
!schemaAccepts(schema, textResult.structuredData);
|
|
4083
|
+
if (!schema ||
|
|
4084
|
+
(textResult.structuredData !== undefined &&
|
|
4085
|
+
!structuredIsRejectedString) ||
|
|
4086
|
+
typeof textResult.content !== "string") {
|
|
4087
|
+
return;
|
|
4088
|
+
}
|
|
4089
|
+
if (structuredIsRejectedString) {
|
|
4090
|
+
textResult.structuredData = undefined;
|
|
4091
|
+
}
|
|
4092
|
+
const coerced = coerceJsonToSchema(textResult.content, schema);
|
|
4093
|
+
if (coerced) {
|
|
4094
|
+
textResult.content = coerced.content;
|
|
4095
|
+
textResult.structuredData = coerced.structuredData;
|
|
4096
|
+
if (coerced.repaired) {
|
|
4097
|
+
textResult.jsonRepaired = true;
|
|
4086
4098
|
}
|
|
4087
|
-
|
|
4088
|
-
|
|
4089
|
-
const scalar = JSON.parse(textResult.content);
|
|
4090
|
-
if (scalar === "") {
|
|
4091
|
-
// A JSON-encoded empty string is an EMPTY completion, not a
|
|
4092
|
-
// recovered scalar — normalize to a true empty so callers'
|
|
4093
|
-
// empty-response handling fires instead of a literal '""'
|
|
4094
|
-
// reaching the user. `structuredData` stays undefined.
|
|
4095
|
-
textResult.content = "";
|
|
4096
|
-
logger.warn("[NeuroLink] schema requested but the model returned an empty JSON string; normalizing to empty content", { provider: textResult.provider, model: textResult.model });
|
|
4097
|
-
}
|
|
4098
|
-
else if (scalar !== null && scalar !== undefined) {
|
|
4099
|
-
textResult.structuredData = scalar;
|
|
4100
|
-
}
|
|
4101
|
-
}
|
|
4102
|
-
catch {
|
|
4103
|
-
logger.warn("[NeuroLink] schema requested but no JSON could be recovered from model output; returning raw text", { provider: textResult.provider, model: textResult.model });
|
|
4104
|
-
}
|
|
4099
|
+
if (coerced.truncated) {
|
|
4100
|
+
textResult.jsonTruncated = true;
|
|
4105
4101
|
}
|
|
4102
|
+
return;
|
|
4106
4103
|
}
|
|
4104
|
+
const scalar = recoverScalarRoot(textResult.content, schema);
|
|
4105
|
+
switch (scalar.kind) {
|
|
4106
|
+
case "empty":
|
|
4107
|
+
// A JSON-encoded empty string is an EMPTY completion, not a recovered
|
|
4108
|
+
// scalar — normalize to a true empty so callers' empty-response
|
|
4109
|
+
// handling fires instead of a literal '""' reaching the user.
|
|
4110
|
+
// `structuredData` stays undefined.
|
|
4111
|
+
textResult.content = "";
|
|
4112
|
+
logger.warn("[NeuroLink] schema requested but the model returned an empty JSON string; normalizing to empty content", { provider: textResult.provider, model: textResult.model });
|
|
4113
|
+
break;
|
|
4114
|
+
case "accepted":
|
|
4115
|
+
// Only publish a scalar root the caller's schema actually accepts.
|
|
4116
|
+
// Under an OBJECT schema a recovered string is the raw completion in
|
|
4117
|
+
// disguise — the shape a truncated response degrades to — and exposing
|
|
4118
|
+
// it hands the caller a `structuredData` that violates the schema they
|
|
4119
|
+
// passed.
|
|
4120
|
+
textResult.structuredData = scalar.value;
|
|
4121
|
+
break;
|
|
4122
|
+
case "rejected":
|
|
4123
|
+
logger.warn("[NeuroLink] recovered a JSON scalar the requested schema rejects; leaving structuredData unset", {
|
|
4124
|
+
provider: textResult.provider,
|
|
4125
|
+
model: textResult.model,
|
|
4126
|
+
scalarType: typeof scalar.value,
|
|
4127
|
+
});
|
|
4128
|
+
break;
|
|
4129
|
+
case "nullish":
|
|
4130
|
+
// JSON null/undefined — no structured value to publish.
|
|
4131
|
+
break;
|
|
4132
|
+
case "not-json":
|
|
4133
|
+
logger.warn("[NeuroLink] schema requested but no JSON could be recovered from model output; returning raw text", { provider: textResult.provider, model: textResult.model });
|
|
4134
|
+
break;
|
|
4135
|
+
}
|
|
4136
|
+
}
|
|
4137
|
+
finalizeGenerateRequestResult(params) {
|
|
4138
|
+
const { generateSpan, options, textOptions, textResult, factoryResult, originalPrompt, startTime, } = params;
|
|
4139
|
+
this.recoverStructuredData(textResult, textOptions.schema);
|
|
4107
4140
|
// Surface truncation when a schema was requested: either the provider
|
|
4108
4141
|
// reported finishReason="length" or the recovered JSON came from an
|
|
4109
4142
|
// unclosed span. Either way `structuredData` may be incomplete — warn at
|
|
@@ -1206,6 +1206,9 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1206
1206
|
}
|
|
1207
1207
|
const content = [];
|
|
1208
1208
|
let finalResultText;
|
|
1209
|
+
// Text emitted in forced-json mode, kept only as a fallback (see below).
|
|
1210
|
+
const jsonModeText = [];
|
|
1211
|
+
let jsonToolAnswered = false;
|
|
1209
1212
|
for (const block of response.content) {
|
|
1210
1213
|
if (block.type === "thinking") {
|
|
1211
1214
|
content.push({ type: "reasoning", text: block.thinking });
|
|
@@ -1213,13 +1216,17 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1213
1216
|
else if (block.type === "text") {
|
|
1214
1217
|
// In forced-json mode the payload arrives via the tool input, not
|
|
1215
1218
|
// text — pass text through only in normal mode.
|
|
1216
|
-
if (
|
|
1219
|
+
if (jsonTool) {
|
|
1220
|
+
jsonModeText.push(block.text);
|
|
1221
|
+
}
|
|
1222
|
+
else {
|
|
1217
1223
|
content.push({ type: "text", text: block.text });
|
|
1218
1224
|
}
|
|
1219
1225
|
}
|
|
1220
1226
|
else if (block.type === "tool_use") {
|
|
1221
1227
|
if (jsonTool && block.name === jsonTool) {
|
|
1222
1228
|
// Unwrap the synthetic tool call back into text JSON.
|
|
1229
|
+
jsonToolAnswered = true;
|
|
1223
1230
|
content.push({
|
|
1224
1231
|
type: "text",
|
|
1225
1232
|
text: stringifyToolInput(block.input),
|
|
@@ -1241,6 +1248,15 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1241
1248
|
}
|
|
1242
1249
|
}
|
|
1243
1250
|
}
|
|
1251
|
+
// Forced-json mode normally drops text blocks because the payload rides
|
|
1252
|
+
// in the synthetic tool's input. But when the response is cut short
|
|
1253
|
+
// (stop_reason "max_tokens") the tool call can be missing entirely, and
|
|
1254
|
+
// dropping the text would leave an EMPTY completion with nothing for
|
|
1255
|
+
// coerceJsonToSchema to recover. Fall back to the text so a partial
|
|
1256
|
+
// object can still be salvaged and flagged truncated.
|
|
1257
|
+
if (jsonTool && !jsonToolAnswered && jsonModeText.length > 0) {
|
|
1258
|
+
content.push({ type: "text", text: jsonModeText.join("") });
|
|
1259
|
+
}
|
|
1244
1260
|
// final_result is terminal — parity with the native Claude-on-Vertex
|
|
1245
1261
|
// and Gemini loops, which break out of the tool loop the moment it
|
|
1246
1262
|
// arrives. Reasoning blocks are kept; any prose preamble and any tool
|
|
@@ -279,3 +279,32 @@ export type JsonCoercionResult = {
|
|
|
279
279
|
*/
|
|
280
280
|
truncated: boolean;
|
|
281
281
|
};
|
|
282
|
+
/**
|
|
283
|
+
* Decision returned by `recoverScalarRoot`. Each caller applies it to its own
|
|
284
|
+
* result shape and logger prefix, preserving its existing warning behaviour:
|
|
285
|
+
*
|
|
286
|
+
* - `empty` — the text is a JSON-encoded empty string (an EMPTY
|
|
287
|
+
* completion, not a recovered scalar). Callers normalize to a
|
|
288
|
+
* true empty.
|
|
289
|
+
* - `accepted` — a scalar root the caller's schema accepts; safe to publish
|
|
290
|
+
* as `structuredData`.
|
|
291
|
+
* - `rejected` — a scalar root the caller's schema rejects (e.g. a raw
|
|
292
|
+
* string under an object schema — the shape a truncated
|
|
293
|
+
* response degrades to). Do NOT publish it.
|
|
294
|
+
* - `nullish` — the text is the JSON literals `null`/`undefined`; there is
|
|
295
|
+
* no structured value to publish.
|
|
296
|
+
* - `not-json` — the text is not JSON at all.
|
|
297
|
+
*/
|
|
298
|
+
export type ScalarRecoveryDecision = {
|
|
299
|
+
kind: "empty";
|
|
300
|
+
} | {
|
|
301
|
+
kind: "accepted";
|
|
302
|
+
value: unknown;
|
|
303
|
+
} | {
|
|
304
|
+
kind: "rejected";
|
|
305
|
+
value: unknown;
|
|
306
|
+
} | {
|
|
307
|
+
kind: "nullish";
|
|
308
|
+
} | {
|
|
309
|
+
kind: "not-json";
|
|
310
|
+
};
|
|
@@ -1,4 +1,24 @@
|
|
|
1
|
-
import type { JsonCoercionResult, ValidationSchema } from "../../types/index.js";
|
|
1
|
+
import type { JsonCoercionResult, ScalarRecoveryDecision, ValidationSchema } from "../../types/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Does `value` satisfy `schema`? A schema we cannot validate with (absent, or
|
|
4
|
+
* without a Zod-style `safeParse`) accepts everything — callers use this as a
|
|
5
|
+
* gate, not as proof, so an unknown schema must never block a value.
|
|
6
|
+
*
|
|
7
|
+
* Exists so the consumers of coerceJsonToSchema can refuse to publish a
|
|
8
|
+
* recovered value as `structuredData` when the caller's schema rejects it —
|
|
9
|
+
* e.g. a raw *string* under an object schema, which is the shape a truncated
|
|
10
|
+
* response degrades to.
|
|
11
|
+
*/
|
|
12
|
+
export declare function schemaAccepts(schema: ValidationSchema | undefined, value: unknown): boolean;
|
|
13
|
+
/**
|
|
14
|
+
* Recover a JSON *scalar* root (string/number/boolean) from model text. The
|
|
15
|
+
* object/array case is handled by `coerceJsonToSchema`; this covers the
|
|
16
|
+
* residual scalar root after that path returns null. Encapsulates the JSON
|
|
17
|
+
* parsing, the empty-string normalization, and the `schemaAccepts` gate so the
|
|
18
|
+
* same policy cannot drift between consumers (`neurolink.recoverStructuredData`
|
|
19
|
+
* and `GenerationHandler.coerceTextMode`).
|
|
20
|
+
*/
|
|
21
|
+
export declare function recoverScalarRoot(text: string, schema: ValidationSchema | undefined): ScalarRecoveryDecision;
|
|
2
22
|
/**
|
|
3
23
|
* Try to produce canonical JSON from `text`. Returns null when no JSON object
|
|
4
24
|
* could be recovered (caller should then keep the raw text).
|