Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(tools): preserve exponent-form custom API body numbers (#45548)

MindOfqcfe2b8bd3466e
diff --git a/api/core/tools/custom_tool/tool.py b/api/core/tools/custom_tool/tool.py
index 60c277e5ce5..068b578341f 100644
--- a/api/core/tools/custom_tool/tool.py
+++ b/api/core/tools/custom_tool/tool.py
@@ -308,6 +308,12 @@ class ApiTool(Tool):
def _convert_body_property_any_of(
self, property: dict[str, Any], value: Any, any_of: list[dict[str, Any]], max_recursive=10
):
+ """Convert a body value using the first supported anyOf option, without side effects.
+
+ Number options preserve fractional exponent values. Conversions raising ValueError
+ try the remaining options; exhaustion returns the input unchanged. A depleted
+ recursion budget raises before conversion.
+ """
if max_recursive <= 0:
raise Exception("Max recursion depth reached")
for option in any_of or []:
@@ -317,7 +323,7 @@ class ApiTool(Tool):
if option["type"] == "integer" or option["type"] == "int":
return int(value)
elif option["type"] == "number":
- if "." in str(value):
+ if "." in str(value) or "e" in str(value).lower():
return float(value)
else:
return int(value)
@@ -343,13 +349,19 @@ class ApiTool(Tool):
return value # or raise ValueError(f"Cannot convert value '{value}' to any specified type in anyOf")
def _convert_body_property_type(self, property: dict[str, Any], value: Any):
+ """Convert a body value according to its OpenAPI property, without side effects.
+
+ Number properties accept decimal and exponent representations while integer
+ representations keep their exact value. Conversions raising ValueError return
+ the original input; anyOf properties retain their existing option-order behavior.
+ """
try:
if "type" in property:
if property["type"] == "integer" or property["type"] == "int":
return int(value)
elif property["type"] == "number":
- # check if it is a float
- if "." in str(value):
+ # Decimal points and exponents both denote floating-point representations.
+ if "." in str(value) or "e" in str(value).lower():
return float(value)
else:
return int(value)
diff --git a/api/tests/unit_tests/core/tools/custom_tool/test_tool.py b/api/tests/unit_tests/core/tools/custom_tool/test_tool.py
index ae849505138..f30d8784c9d 100644
--- a/api/tests/unit_tests/core/tools/custom_tool/test_tool.py
+++ b/api/tests/unit_tests/core/tools/custom_tool/test_tool.py
@@ -54,6 +54,50 @@ parameters = {
class TestApiToolRequestAssemblyCases:
+ @staticmethod
+ @pytest.mark.parametrize("schema", [{"type": "number"}, {"anyOf": [{"type": "number"}, {"type": "null"}]}])
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (1e-7, 1e-7),
+ (-1e-7, -1e-7),
+ ("1e-7", 1e-7),
+ ("2E3", 2000.0),
+ (12, 12),
+ ("12", 12),
+ ("1.25", 1.25),
+ (9007199254740993, 9007199254740993),
+ ("9007199254740993", 9007199254740993),
+ ],
+ )
+ def test_number_body_preserves_value(
+ monkeypatch: pytest.MonkeyPatch, schema: dict[str, Any], value: int | float | str, expected: int | float
+ ) -> None:
+ tool = _build_tool(
+ openapi={
+ "parameters": [],
+ "requestBody": {"content": {"application/json": {"schema": {"properties": {"amount": schema}}}}},
+ }
+ )
+ sent_bodies: list[dict[str, Any]] = []
+
+ def capture_request(request: httpx.Request) -> httpx.Response:
+ sent_bodies.append(json.loads(request.content))
+ return httpx.Response(200)
+
+ with httpx.Client(transport=httpx.MockTransport(capture_request)) as client:
+ monkeypatch.setattr("core.helper.ssrf_proxy._get_ssrf_client", lambda ssl_verify_enabled: client)
+ tool.do_http_request("https://api.example.com/items", "POST", {}, {"amount": value})
+
+ assert sent_bodies == [{"amount": expected}]
+ assert isinstance(sent_bodies[0]["amount"], (int, float))
+
+ @staticmethod
+ @pytest.mark.parametrize("schema", [{"type": "number"}, {"anyOf": [{"type": "number"}]}])
+ def test_invalid_number_body_keeps_existing_fallback(schema: dict[str, Any]) -> None:
+ tool = _build_tool()
+ assert tool._convert_body_property_type(schema, "not-a-number") == "not-a-number"
+
@staticmethod
@pytest.mark.usefixtures("setup_http_mock")
def test_api_tool() -> None: