Your LLM returned almost-valid JSON. Stop hand-patching it.
说明与用途
LLM 通常返回几乎有效的 JSON,但与预期模式不匹配。coerce-json 库自动清理、强制类型、填充默认值并记录更改,将验证成功率从 13.5% 提升至 86.5%(或开启 fuzzy 后为 100%)。
问题
LLMs often output JSON that is syntactically valid but semantically mismatched to the expected schema, causing runtime failures and manual patching.
结果
Coercing almost-valid LLM output with coerce-json increases validation success from 13.5% to 86.5% (or 100% with fuzzy matching) on a representative corpus, eliminating manual patching and providing an auditable change log.
工作流
- 1. Receive raw LLM output (often fenced JSON).
- 2. Pass the raw string to
coercefromcoerce-jsonalong with a Zod schema. - 3.
coerceextracts JSON, removes fences, coerces primitive types, applies defaults, and records each change. - 4. Inspect the
changeslog to audit modifications. - 5. Use the coerced
valuefor downstream processing or further validation.
证据
Every field is *almost* right. id is a string. active is a string. There's a role you never asked for.
coerce is a zero-dependency library that takes almost-valid model output and makes it fit your schema — reporting every fix:
Under plain Zod, 13.5% of them validate. Run them through coerce with defaults, and 86.5% validate. Flip on fuzzy: true and it's 100%.
- 记录日期: 2026-10-08T16:40:58.774Z