{"record":{"id":"8529b13f4315c98d","repo":"BoundaryML/baml","slug":"failed-coercing-baml-value-to-ruby-value-e","errorCode":null,"errorMessage":"failed coercing BAML value to Ruby value: {e:?}","messagePattern":"failed coercing BAML value to Ruby value: (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"engine/language_client_ruby/ext/ruby_ffi/src/lib.rs","lineNumber":296,"sourceCode":"                type_registry.map(|t| &t.inner),\n                client_registry.map(|c| c.inner.borrow_mut()).as_deref(),\n                env_vars,\n            )\n            .map_err(|e| {\n                Error::new(\n                    ruby.exception_runtime_error(),\n                    format!(\n                        \"{:?}\",\n                        e.context(format!(\n                            \"error while parsing LLM response for function {function_name}\"\n                        ))\n                    ),\n                )\n            })?;\n\n        ruby_to_json::RubyToJson::serialize_baml(ruby, types, partial_types, allow_partials, parsed)\n            .map_err(|e| {\n                magnus::Error::new(\n                    ruby.exception_type_error(),\n                    format!(\"failed coercing BAML value to Ruby value: {e:?}\"),\n                )\n            })\n    }\n}\n\nfn invoke_runtime_cli(ruby: &Ruby, argv0: String, argv: Vec<String>) -> Result<u32> {\n    match baml_cli::run_cli(\n        std::iter::once(argv0).chain(argv).collect(),\n        baml_runtime::RuntimeCliDefaults {\n            output_type: baml_types::GeneratorOutputType::RubySorbet,\n        },\n    ) {\n        Ok(exit_code) => Ok(exit_code.into()),\n        Err(e) => Err(Error::new(\n            ruby.exception_runtime_error(),\n            format!(","sourceCodeStart":278,"sourceCodeEnd":314,"githubUrl":"https://github.com/BoundaryML/baml/blob/bd85ce9dee1463ff04d27efd20531013a4ff46c1/engine/language_client_ruby/ext/ruby_ffi/src/lib.rs#L278-L314","documentation":"This magnus::Error (Ruby TypeError) is raised by the BAML Ruby FFI's parse_llm_response after the LLM response has been parsed into a BAML value but the conversion of that BAML value back into a native Ruby value (via RubyToJson::serialize_baml) failed. It wraps the underlying serde/magnus conversion error, so the detailed cause is inside the {e:?} debug payload. It indicates the BAML runtime produced a value that could not be coerced into the Ruby object model.","triggerScenarios":"Calling a BAML-generated function from Ruby (parse_llm_response) where the parsed response contains a BAML value type that RubyToJson::serialize_baml cannot represent, e.g. unexpected partial/streaming state, a mismatch between the declared return type and the actual parsed value, or a serde-level serialization failure inside serialize_baml.","commonSituations":"Streaming/partial responses whose completion state carries types the Ruby bridge does not support; schema drift after editing .baml return types without regenerating the client; deeply nested or unusual return types (unions, maps with non-string keys) hitting an unimplemented coercion path in the FFI.","solutions":["Inspect the wrapped {e:?} detail in the message to find the exact BAML value that failed coercion.","Regenerate the BAML client (bundle baml-cli generate / baml-cli generate) so Ruby types match the current .baml schemas.","Simplify the BAML function return type (avoid exotic nested/unions unsupported by the Ruby bridge) and re-test.","Update the baml gem / ruby_ffi extension to the latest version, as coercion coverage improves between releases.","Capture the full LLM response with a BAML collector and check whether the model returned malformed output that parsed into an unexpected value."],"exampleFix":"// before (retrying blindly on every call)\nbegin\n  result = b.MyFunc(input)\nrescue StandardError => e\n  retry\nend\n\n// after (log detail, regenerate client, narrow the return type)\nbegin\n  result = b.MyFunc(input)\nrescue TypeError => e\n  Baml.logger.error(\"baml coercion failed: #{e.message}\")\n  # run: bundle exec baml-cli generate, then retry once\nend","handlingStrategy":"try-catch","validationCode":"return unless defined?(Baml::Ffi)\nraise unless Gem::Specification.find_by_name('baml')&.version\n# ensure client is regenerated:\nraise 'run baml-cli generate' unless File.exist?(File.join(BAML_SRC_DIR, 'baml_client'))","typeGuard":"def baml_result_ok?(result)\n  result.is_a?(String) || result.is_a?(Hash) || result.respond_to?(:to_h)\nrescue StandardError\n  false\nend","tryCatchPattern":"begin\n  result = b.MyFunc(input)\nrescue TypeError => e\n  logger.error(\"BAML coercion failed: #{e.message}\")\n  raise BamlCoercionError, e.message\nend","preventionTips":["Regenerate the baml_client after every .baml schema change.","Pin and keep the baml gem version in sync across environments.","Prefer simple JSON-safe return types in BAML functions.","Log the raw LLM output with a collector to diagnose unexpected parses."],"tags":["ruby","ffi","serialization","baml"],"backgroundTag":"type-mismatch","analyzedSha":"bd85ce9dee1463ff04d27efd20531013a4ff46c1","analyzedAt":"2026-09-12T03:38:25.718Z","contentChangedAt":"2026-09-12T03:38:25.718Z","schemaVersion":2},"datasetVersion":"2026-09-14T11:17:12.474Z"}