Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Treat null / empty-dict tool_calls as 'no calls' in ToolCalls validator (#10644)

Jaspere79a1df47b63
diff --git a/dspy/adapters/types/tool.py b/dspy/adapters/types/tool.py
index 4265626b0..901372e2b 100644
--- a/dspy/adapters/types/tool.py
+++ b/dspy/adapters/types/tool.py
@@ -432,9 +432,22 @@ class ToolCalls(Type):
if "tool_call_results" in data:
normalized["tool_call_results"] = data["tool_call_results"]
return normalized
+ # Models in JSON mode write `"tool_calls": null` to mean "no
+ # tool calls this turn"; treat it like an empty list.
+ if tool_calls_data is None:
+ return {"tool_calls": []}
elif _is_tool_call_dict(data):
# Handle case where data is a dict with "name" and "args" keys
return {"tool_calls": [cls.ToolCall(**_normalize_tool_call_dict(data))]}
+ elif not data:
+ # An empty dict is also "no tool calls".
+ return {"tool_calls": []}
+
+ # `None` (models in JSON mode) means "no tool calls this turn" and
+ # normalizes to an empty call list, matching the native-path behavior
+ # where the field stays None when the provider returns no calls.
+ if data is None:
+ return {"tool_calls": []}
raise ValueError(f"Received invalid value for `dspy.ToolCalls`: {data}")
diff --git a/tests/adapters/test_tool.py b/tests/adapters/test_tool.py
index 8145db138..1f7aa15df 100644
--- a/tests/adapters/test_tool.py
+++ b/tests/adapters/test_tool.py
@@ -811,3 +811,29 @@ def test_tool_call_execute_with_local_functions():
globals().pop("local_add", None)
main()
+
+
+def test_tool_calls_none_and_empty_dict_mean_no_calls():
+ """`"tool_calls": null` / `{}` are how JSON-mode models say "no tool calls
+ this turn" -- they must parse like `[]`, not raise AdapterParseError (#10612)."""
+ for empty in (None, {}):
+ calls = dspy.ToolCalls.model_validate(empty)
+ assert calls.tool_calls == []
+ # And through the wrapping form: {"tool_calls": None}
+ calls = dspy.ToolCalls.model_validate({"tool_calls": None})
+ assert calls.tool_calls == []
+
+
+def test_tool_calls_none_reaches_empty_tool_calls_semantics():
+ """End-to-end: ReActV2 with a JSON-mode model writing `"tool_calls": null`
+ must take the usual empty_tool_calls path (like `[]`), not a parse error."""
+ adapter = dspy.JSONAdapter()
+ lm = dspy.utils.DummyLM([{"next_thought": "Nothing to call.", "tool_calls": None}] * 2, adapter=adapter)
+ with dspy.context(lm=lm, adapter=adapter):
+ try:
+ dspy.ReActV2("question -> answer", tools=[])(question="hi")
+ raised = None
+ except Exception as e:
+ raised = e
+ assert raised is not None
+ assert "empty_tool_calls" in str(raised), f"expected empty_tool_calls semantics, got: {raised}"