spring-ai icon indicating copy to clipboard operation
spring-ai copied to clipboard

GH-3884: Throw clear exception when tool parameter receives blank or empty string from model

Open suryateja-g13 opened this issue 6 months ago • 2 comments

What

When a model returns a blank or empty string for a numeric tool parameter (Byte, Short, Integer, Long, Float, Double), JsonParser.toTypedObject() previously threw a cryptic NumberFormatException with no context about what went wrong.

Why

The fix adds an early blank-string guard via a private isStrictNumericType() helper that fires before any type-specific branch. Boolean and enum are intentionally excluded: Boolean.parseBoolean("") returns false by contract, and Enum.valueOf already throws IllegalArgumentException with a descriptive message. Primitive types (int, long, etc.) are covered automatically via ClassUtils.resolvePrimitiveIfNecessary.

Changes

  • JsonParser — added isStrictNumericType() helper and blank-string guard in toTypedObject(); updated @throws Javadoc
  • JsonParserTests — 9 new tests covering all 6 numeric types (empty and blank string), primitive type pass-through, Boolean returning false, and enum throwing its own exception

Fixes GH-3884 (https://github.com/spring-projects/spring-ai/issues/3884)

suryateja-g13 avatar May 13 '26 02:05 suryateja-g13

Fix works. I verified it locally and the unit tests in JsonParserTests all pass. However, one suggestion would be to add a test at the MethodToolCallback level too. Something like this:

@Test
  void emptyStringForLongParamThrowsClearException() {
      var callback = MethodToolCallbackProvider.builder()
          .toolObjects(new IdTool())
          .build()
          .getToolCallbacks()[0];

      String toolInput = """
              { "id": "" }
              """;

      assertThatThrownBy(() -> callback.call(toolInput))
          .isInstanceOf(ToolExecutionException.class)
          .hasRootCauseInstanceOf(IllegalArgumentException.class)
          .hasMessageContaining("Cannot convert blank or empty string to numeric type 'Long'");
  }

  static class IdTool {
      @Tool(description = "Lookup by id")
      public String lookup(Long id) { return "id=" + id; }
  }

@sdeleuze can you take a look on this PR?

stohirov avatar May 20 '26 16:05 stohirov

Thanks for the suggestion! Added a MethodToolCallbackProvider-level test (emptyStringForLongParamThrowsClearException) in MethodToolCallbackProviderTests that exercises the full call path — provider → callback → JsonParser — and asserts that a ToolExecutionException wrapping an IllegalArgumentException with the expected message is thrown when an empty string is passed for a Long parameter.

suryateja-g13 avatar May 21 '26 21:05 suryateja-g13