{"record":{"id":"87280b1df03b1122","repo":"BoundaryML/baml","slug":"baml-json-serialize-failed-e","errorCode":null,"errorMessage":"baml.json.serialize failed: {e:?}","messagePattern":"baml\\.json\\.serialize failed: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"baml_language/crates/baml_exec/src/output.rs","lineNumber":109,"sourceCode":"/// runtime-value dispatch honors user `baml.ToJson` overrides at every depth.\nasync fn serialize_via_baml_json(\n    engine: &Arc<BexEngine>,\n    value: BexExternalValue,\n    return_type: &RuntimeTy,\n    helper_context: &HelperCallContext,\n) -> Result<String> {\n    let result = engine\n        .call_function(\n            \"baml.json.serialize\",\n            vec![value],\n            helper_context.call_context(indexmap::IndexMap::from([(\n                \"T\".to_string(),\n                return_type.clone(),\n            )])),\n            true,\n        )\n        .await\n        .map_err(|e| anyhow!(\"baml.json.serialize failed: {e:?}\"))?;\n    match result {\n        BexExternalValue::String(s) => Ok(s.to_string()),\n        other => Err(anyhow!(\n            \"baml.json.serialize returned non-string value: {other:?}\"\n        )),\n    }\n}\n\n/// Human-readable formatting for `BexExternalValue`.\n///\n/// Thin wrapper over [`BexExternalValue::render_readable`] — the canonical\n/// structural renderer, shared with the engine's uncaught-throw rendering so\n/// `baml run` output and a leaked `throw` render identically.\npub fn format_value(value: &BexExternalValue) -> String {\n    value.render_readable()\n}\n","sourceCodeStart":91,"sourceCodeEnd":126,"githubUrl":"https://github.com/BoundaryML/baml/blob/bd85ce9dee1463ff04d27efd20531013a4ff46c1/baml_language/crates/baml_exec/src/output.rs#L91-L126","documentation":"This error is produced by serialize_via_baml_json in the BAML executor when the `baml.json` external function fails while serializing a value (typically a class/object) to a JSON string. The call to the baml.json function is awaited and any failure from it is wrapped with anyhow! with the underlying error debug-formatted. It exists to carry the nested evaluation error into the output-writing pipeline (write_output_with_context) with a clear origin prefix.","triggerScenarios":"Calling write_output_with_context with a return type that routes through serialize_via_baml_json when the `baml.json` builtin/function evaluation fails — e.g. the runtime value cannot be converted by baml.json, the baml.json function itself errors, or the runtime/engine call rejects the arguments (type + `true` flag) passed in.","commonSituations":"Serializing a BAML class value whose fields contain types baml.json cannot handle; runtime engine errors during function invocation; mismatches between the return_type passed to baml.json and the actual value produced by the LLM function; partial or malformed results from an LLM response that fails conversion.","solutions":["Read the wrapped `{e:?}` payload to identify the underlying baml.json evaluation failure and fix the value/type it complains about","Verify the value being serialized matches the declared return_type (e.g. class field types) before calling the output writer","Check that the LLM response is valid and the function's output schema compiles/evaluates correctly (run `baml test` / inspect intermediate result)","Upgrade baml_language / the runtime engine if the failing serialization is a known bug"],"exampleFix":"// before\nreturn_type.clone(),\n// after\n// ensure declared return type matches the actual value schema\n// e.g. change fn return type or the value so baml.json receives a compatible class","handlingStrategy":"try-catch","validationCode":"// before calling write_output_with_context, confirm the value matches the declared return type schema\nif !matches_return_type(value, expected_return_type) {\n    return Err(\"value does not match declared return type; baml.json.serialize would fail\");\n}","typeGuard":"fn is_serializable_string_result(v: &BexExternalValue) -> bool {\n    matches!(v, BexExternalValue::String(_))\n}","tryCatchPattern":"match serialize_via_baml_json(...).await {\n    Ok(json) => use(json),\n    Err(e) if e.to_string().contains(\"baml.json.serialize failed\") => {\n        log::error!(\"serialization failed: {e:#}\"); // inspect wrapped {e:?} cause\n        fallback_render(value)\n    }\n    Err(e) => return Err(e),\n}","preventionTips":["Validate the runtime value against the declared return type before output serialization","Keep the runtime engine and baml_language versions aligned","Run `baml test` on functions whose output feeds baml.json serialization","Log the wrapped cause ({e:#}) to pinpoint the underlying failure quickly"],"tags":["serialization","runtime","json","baml"],"backgroundTag":"json-marshal-failed","analyzedSha":"bd85ce9dee1463ff04d27efd20531013a4ff46c1","analyzedAt":"2026-09-12T03:38:25.718Z","contentChangedAt":"2026-09-12T03:38:25.718Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}