Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

fix(adapters): drop tool_choice when tools aren't sent to the LM (#10399)

Nithilanb51596e9e652
diff --git a/dspy/adapters/base.py b/dspy/adapters/base.py
index 0da1b46fd..06f762f69 100644
--- a/dspy/adapters/base.py
+++ b/dspy/adapters/base.py
@@ -114,6 +114,9 @@ class Adapter:
signature = signature.delete(tool_call_output_field_name)
signature = signature.delete(tool_call_input_field_name)
+ elif tool_call_output_field_name:
+ for key in ("tools", "tool_choice", "parallel_tool_calls"):
+ lm_kwargs.pop(key, None)
# TODO(adapters-plan): Built-in/native response planning should move out
# of `Type.adapt_to_native_lm_feature()` and into adapter-owned planning
diff --git a/tests/adapters/test_chat_adapter.py b/tests/adapters/test_chat_adapter.py
index 0cbdef49a..a889ebd6c 100644
--- a/tests/adapters/test_chat_adapter.py
+++ b/tests/adapters/test_chat_adapter.py
@@ -1049,6 +1049,73 @@ def test_chat_adapter_nonnative_strips_native_tool_kwargs():
assert "parallel_tool_calls" not in lm_kwargs
+def test_chat_adapter_native_preserves_caller_tools_on_ordinary_signature():
+ """An ordinary signature (no `dspy.ToolCalls` output field) never has its tool
+ wiring managed by the adapter, with or without native function calling - so a
+ caller passing native `tools`/`tool_choice` directly (outside the ToolCalls
+ mechanism, e.g. via `config=`) must keep reaching the LM untouched. Regression
+ test for a #10397 fix that briefly over-stripped this case too."""
+
+ class OrdinarySignature(dspy.Signature):
+ question: str = dspy.InputField()
+ answer: str = dspy.OutputField()
+
+ _, lm_kwargs = format_messages_and_lm_kwargs(
+ dspy.ChatAdapter(use_native_function_calling=True),
+ OrdinarySignature,
+ [],
+ {"question": "Q?"},
+ lm_kwargs={
+ "tools": [{"type": "function", "function": {"name": "search"}}],
+ "tool_choice": "auto",
+ "parallel_tool_calls": True,
+ },
+ # Default DummyLM: supports_function_calling is False - shouldn't matter here,
+ # since this signature never opts into the ToolCalls mechanism at all.
+ )
+
+ assert lm_kwargs["tools"] == [{"type": "function", "function": {"name": "search"}}]
+ assert lm_kwargs["tool_choice"] == "auto"
+ assert lm_kwargs["parallel_tool_calls"] is True
+
+
+def test_chat_adapter_native_strips_tool_choice_when_lm_lacks_function_calling():
+ """Regression test for #10397.
+
+ ReActV2's forced-submit path always sets `tool_choice` (to force a final
+ `submit` call), regardless of whether the LM is marked as supporting
+ native function calling. When it isn't (e.g. a model missing from DSPy's
+ capability catalog), the adapter never adds `tools` - so a `tool_choice`
+ the caller already passed in must be dropped too, or OpenAI and
+ OpenAI-compatible gateways reject the request with a 400.
+ """
+
+ def search(query: str) -> str:
+ return query
+
+ class NativeToolSignature(dspy.Signature):
+ question: str = dspy.InputField()
+ tools: list[dspy.Tool] = dspy.InputField()
+ tool_calls: dspy.ToolCalls = dspy.OutputField()
+
+ _, lm_kwargs = format_messages_and_lm_kwargs(
+ dspy.ChatAdapter(use_native_function_calling=True),
+ NativeToolSignature,
+ [],
+ {"question": "Q?", "tools": [dspy.Tool(search)]},
+ lm_kwargs={
+ "tool_choice": {"type": "function", "function": {"name": "submit"}},
+ "parallel_tool_calls": True,
+ },
+ # Default DummyLM: supports_function_calling is False, matching a model
+ # missing from DSPy's catalog - the exact condition that triggers #10397.
+ )
+
+ assert "tools" not in lm_kwargs
+ assert "tool_choice" not in lm_kwargs
+ assert "parallel_tool_calls" not in lm_kwargs
+
+
def test_chat_adapter_format_exact_messages_with_reasoning_and_code_outputs():
python_code = dspy.Code["python"]
diff --git a/tests/predict/test_react_v2.py b/tests/predict/test_react_v2.py
index d9195cbc7..f37b9dbde 100644
--- a/tests/predict/test_react_v2.py
+++ b/tests/predict/test_react_v2.py
@@ -199,6 +199,31 @@ def test_react_v2_forced_submit_on_empty_tool_calls():
assert lm.history[1]["kwargs"].get("reasoning_effort") is None
+def test_react_v2_forced_submit_with_native_flag_but_unsupported_lm():
+ adapter = dspy.JSONAdapter(use_native_function_calling=True)
+ lm = dspy.utils.DummyLM(
+ [
+ {"next_thought": "No action.", "tool_calls": dspy.ToolCalls(tool_calls=[])},
+ {
+ "next_thought": "Forced final.",
+ "tool_calls": dspy.ToolCalls.from_dict_list(
+ [{"name": "submit", "args": {"answer": "forced"}}]
+ ),
+ },
+ ],
+ adapter=adapter,
+ )
+ assert lm.supports_function_calling is False
+
+ with dspy.context(lm=lm, adapter=adapter):
+ pred = dspy.ReActV2("question -> answer", tools=[])(question="cats")
+
+ assert pred.answer == "forced"
+ assert pred.termination_reason == "forced_submit"
+ assert "tool_choice" not in lm.history[1]["kwargs"]
+ assert "tools" not in lm.history[1]["kwargs"]
+
+
class NativeToolLM(dspy.BaseLM):
def __init__(self):
super().__init__("native-tool-lm", "chat", 0.0, 1000, True)