{"record":{"id":"f2f981af2de1f0b8","repo":"BoundaryML/baml","slug":"bamlvalidationerror-message","errorCode":null,"errorMessage":"BamlValidationError: {message}","messagePattern":"BamlValidationError: (.+?)","errorType":"exception","errorClass":"BamlValidationError","httpStatus":null,"severity":"error","filePath":"engine/language_client_typescript/src/errors.rs","lineNumber":151,"sourceCode":"    } else {\n        napi::Error::new(napi::Status::GenericFailure, format!(\"BamlError: {err:?}\"))\n    }\n}\n\nfn throw_baml_validation_error(\n    prompt: &str,\n    raw_output: &str,\n    message: &str,\n    detailed_message: Option<&str>,\n) -> napi::Error {\n    let error_json = serde_json::json!({\n        \"type\": \"BamlValidationError\",\n        \"prompt\": prompt,\n        \"raw_output\": raw_output,\n        \"message\": format!(\"BamlValidationError: {}\", message),\n        \"detailed_message\": detailed_message,\n    });\n    napi::Error::new(napi::Status::GenericFailure, error_json.to_string())\n}\n\nfn throw_baml_client_finish_reason_error(\n    prompt: &str,\n    raw_output: &str,\n    message: &str,\n    finish_reason: Option<&str>,\n    detailed_message: Option<&str>,\n) -> napi::Error {\n    let error_json = serde_json::json!({\n        \"type\": \"BamlClientFinishReasonError\",\n        \"prompt\": prompt,\n        \"raw_output\": raw_output,\n        \"message\": format!(\"BamlError: BamlClientError: BamlClientFinishReasonError: {}\", message),\n        \"finish_reason\": finish_reason,\n        \"detailed_message\": detailed_message,\n    });\n    napi::Error::new(napi::Status::GenericFailure, error_json.to_string())","sourceCodeStart":133,"sourceCodeEnd":169,"githubUrl":"https://github.com/BoundaryML/baml/blob/bd85ce9dee1463ff04d27efd20531013a4ff46c1/engine/language_client_typescript/src/errors.rs#L133-L169","documentation":"BamlValidationError is thrown by throw_baml_validation_error when the LLM output does not validate against the function's output schema. The thrown value is a JSON object containing the prompt, raw_output, and message, so callers can inspect what the model actually produced.","triggerScenarios":"A generated BAML function's response fails schema/type validation — the parsed output doesn't match the declared return type — after all retries are exhausted.","commonSituations":"Model returns malformed JSON, omits required fields, emits wrong types, or drifts into prose instead of the requested structure; overly strict output schemas or weak prompts.","solutions":["Inspect raw_output in the error payload to see the actual model response","Tighten the prompt and output schema (add examples, simplify types)","Add retry/retry-exponential policy to the client config so the model can self-correct","Loosen the schema or use a more capable model if outputs are consistently invalid"],"exampleFix":"// before\nclass Answer { answer string }\n// after\nclass Answer {\n  answer string @description(\"The final answer, one sentence\")\n}\n// plus in client config:\nretry_policy ExtraRetries { max_retries 3 }","handlingStrategy":"try-catch","validationCode":"// pre-flight: verify output schema expectations in the prompt include JSON-only instructions\nconst promptHasSchema = prompt.includes('Return JSON matching');","typeGuard":"const isBamlValidationError = (e: unknown): boolean => String(e).includes('BamlValidationError');","tryCatchPattern":"try {\n  return await b.MyFunction(args);\n} catch (e) {\n  if (isBamlValidationError(e)) {\n    const detail = JSON.parse(String(e).replace(/^[^{]*/, ''));\n    console.error('Raw model output:', detail.raw_output);\n    return null; // or retry with a corrective prompt\n  }\n  throw e;\n}","preventionTips":["Add a retry_policy so the model can correct invalid output","Include explicit JSON/format instructions and examples in prompts","Keep output schemas simple; avoid deep nesting and unions where possible","Use @description on fields to guide the model","Test prompts against the weakest model you support"],"tags":["validation","schema","llm","typescript"],"backgroundTag":"schema-validation-failed","analyzedSha":"bd85ce9dee1463ff04d27efd20531013a4ff46c1","analyzedAt":"2026-09-12T03:38:25.718Z","contentChangedAt":"2026-09-12T03:38:25.718Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}