|
| 1 | +import type { ZodType } from 'zod'; |
| 2 | +import { StructuredOutputError } from './errors.js'; |
| 3 | + |
| 4 | +const FENCE = '```'; |
| 5 | + |
| 6 | +/** True if `text` is a short run of ASCII letters (a code-fence language tag like "json"). */ |
| 7 | +function isLanguageTag(text: string): boolean { |
| 8 | + if (text.length === 0 || text.length > 16) { |
| 9 | + return false; |
| 10 | + } |
| 11 | + for (const char of text) { |
| 12 | + const isLetter = (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z'); |
| 13 | + if (!isLetter) { |
| 14 | + return false; |
| 15 | + } |
| 16 | + } |
| 17 | + return true; |
| 18 | +} |
| 19 | + |
| 20 | +/** Index of the first `{` or `[` in `raw`, or -1. Linear scan (no regex, no backtracking). */ |
| 21 | +function firstBracket(raw: string): number { |
| 22 | + for (let i = 0; i < raw.length; i += 1) { |
| 23 | + const char = raw[i]; |
| 24 | + if (char === '{' || char === '[') { |
| 25 | + return i; |
| 26 | + } |
| 27 | + } |
| 28 | + return -1; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Pull the first JSON value out of a model reply that may wrap it in prose or a |
| 33 | + * ```json fence. Uses index scans only (no regex) so it cannot backtrack on |
| 34 | + * adversarial input. Best-effort: returns the most plausible JSON substring, |
| 35 | + * which `parseStructured` then validates. |
| 36 | + */ |
| 37 | +export function extractJson(raw: string): string { |
| 38 | + const fenceStart = raw.indexOf(FENCE); |
| 39 | + if (fenceStart !== -1) { |
| 40 | + const afterOpen = fenceStart + FENCE.length; |
| 41 | + const fenceEnd = raw.indexOf(FENCE, afterOpen); |
| 42 | + if (fenceEnd !== -1) { |
| 43 | + let body = raw.slice(afterOpen, fenceEnd); |
| 44 | + const newline = body.indexOf('\n'); |
| 45 | + if (newline !== -1 && isLanguageTag(body.slice(0, newline).trim())) { |
| 46 | + body = body.slice(newline + 1); |
| 47 | + } |
| 48 | + return body.trim(); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + const start = firstBracket(raw); |
| 53 | + if (start === -1) { |
| 54 | + return raw.trim(); |
| 55 | + } |
| 56 | + |
| 57 | + const opener = raw[start]; |
| 58 | + const closer = opener === '[' ? ']' : '}'; |
| 59 | + const end = raw.lastIndexOf(closer); |
| 60 | + if (end > start) { |
| 61 | + return raw.slice(start, end + 1).trim(); |
| 62 | + } |
| 63 | + return raw.slice(start).trim(); |
| 64 | +} |
| 65 | + |
| 66 | +/** Extract + JSON.parse + schema-validate. Throws {@link StructuredOutputError} on any failure. */ |
| 67 | +export function parseStructured<T>(raw: string, schema: ZodType<T>): T { |
| 68 | + const json = extractJson(raw); |
| 69 | + |
| 70 | + let parsed: unknown; |
| 71 | + try { |
| 72 | + parsed = JSON.parse(json) as unknown; |
| 73 | + } catch (cause) { |
| 74 | + throw new StructuredOutputError('model output was not valid JSON', raw, { cause }); |
| 75 | + } |
| 76 | + |
| 77 | + const result = schema.safeParse(parsed); |
| 78 | + if (!result.success) { |
| 79 | + throw new StructuredOutputError( |
| 80 | + `model output failed schema validation: ${result.error.message}`, |
| 81 | + raw, |
| 82 | + { |
| 83 | + cause: result.error, |
| 84 | + } |
| 85 | + ); |
| 86 | + } |
| 87 | + return result.data; |
| 88 | +} |
0 commit comments