Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

fix(dspy): store tool argument defaults in JSON form (#10574)

Jay Hemnanida9211ae00d2
diff --git a/dspy/adapters/types/tool.py b/dspy/adapters/types/tool.py
index f8124024c..4265626b0 100644
--- a/dspy/adapters/types/tool.py
+++ b/dspy/adapters/types/tool.py
@@ -1,9 +1,11 @@
import asyncio
import inspect
+from decimal import Decimal
from typing import TYPE_CHECKING, Any, Callable, Literal, Protocol, get_origin, get_type_hints
import json_repair
import pydantic
+import pydantic_core
from jsonschema import ValidationError, validate
from pydantic import BaseModel, TypeAdapter, create_model
@@ -111,7 +113,7 @@ class Tool(Type):
else:
args[k] = _resolve_json_schema_reference(TypeAdapter(v).json_schema())
if default_values[k] is not inspect.Parameter.empty:
- args[k]["default"] = default_values[k]
+ args[k]["default"] = _to_json_default(default_values[k])
if arg_desc and k in arg_desc:
args[k]["description"] = arg_desc[k]
@@ -520,6 +522,17 @@ def _normalize_tool_call_dict(data: dict[str, Any]) -> dict[str, Any]:
}
+def _to_json_default(value: Any) -> Any:
+ """Convert a parameter default to its JSON form, e.g. an Enum member to its value."""
+ if isinstance(value, Decimal):
+ # A JSON number fits both float and Decimal arguments; pydantic would give a string.
+ return float(value)
+ try:
+ return pydantic_core.to_jsonable_python(value)
+ except Exception:
+ return value
+
+
def _resolve_json_schema_reference(schema: dict) -> dict:
"""Recursively resolve json model schema, expanding all references."""
diff --git a/tests/adapters/test_tool.py b/tests/adapters/test_tool.py
index 5b357249b..8145db138 100644
--- a/tests/adapters/test_tool.py
+++ b/tests/adapters/test_tool.py
@@ -146,6 +146,42 @@ def test_tool_from_function():
assert tool.args["y"]["default"] == "hello"
+def test_tool_defaults_are_json_serializable():
+ import datetime
+ import enum
+ import json
+ from decimal import Decimal
+
+ class Unit(enum.Enum):
+ CELSIUS = "celsius"
+ FAHRENHEIT = "fahrenheit"
+
+ def forecast(
+ city: str,
+ unit: Unit = Unit.CELSIUS,
+ start: datetime.date = datetime.date(2026, 1, 2),
+ price: Decimal = Decimal("1.5"),
+ factor: float = Decimal("0.1"),
+ ) -> str:
+ return city
+
+ tool = Tool(forecast)
+ assert tool.args["unit"]["default"] == "celsius"
+ assert tool.args["start"]["default"] == "2026-01-02"
+ assert tool.args["price"]["default"] == 1.5
+ assert tool.args["factor"]["default"] == 0.1
+ assert tool(city="x", price=tool.args["price"]["default"], factor=tool.args["factor"]["default"]) == "x"
+ json.dumps(tool.format_as_litellm_function_call())
+
+
+def test_tool_defaults_without_json_form_are_kept():
+ def scale(data: bytes = b"\xff") -> str:
+ return "ok"
+
+ tool = Tool(scale)
+ assert tool.args["data"]["default"] == b"\xff"
+
+
def test_format_as_litellm_function_call_excludes_defaulted_args_from_required():
# `x` has no default and must be required; `y` has a default and must be optional.
tool = Tool(dummy_function)