DSPy: The framework for programming—not prompting—language models
Python
fix(tool): exclude defaulted args from required in function-calling schema (#9971)
Katherine Ahn67bf5eb48228
diff --git a/dspy/adapters/types/tool.py b/dspy/adapters/types/tool.pyindex 239ad1113..ff2bc37b4 100644--- a/dspy/adapters/types/tool.py+++ b/dspy/adapters/types/tool.py@@ -158,7 +158,7 @@ class Tool(Type):"parameters": {"type": "object","properties": self.args,- "required": list(self.args.keys()),+ "required": [k for k in self.args if "default" not in self.args[k]],},},}diff --git a/tests/adapters/test_chat_adapter.py b/tests/adapters/test_chat_adapter.pyindex 8fcdeb4f9..5b4d4c0d5 100644--- a/tests/adapters/test_chat_adapter.py+++ b/tests/adapters/test_chat_adapter.py@@ -1165,7 +1165,7 @@ def test_chat_adapter_format_exact_messages_and_lm_kwargs_with_native_tool_calli"parameters": {"type": "object","properties": {"query": {"type": "string"},"k": {"type": "integer", "default": 3}},- "required": ["query", "k"]}}}]}+ "required": ["query"]}}}]}assert lm_kwargs == expected_lm_kwargsdiff --git a/tests/adapters/test_json_adapter.py b/tests/adapters/test_json_adapter.pyindex c778537bc..4d5efee0b 100644--- a/tests/adapters/test_json_adapter.py+++ b/tests/adapters/test_json_adapter.py@@ -604,7 +604,7 @@ def test_json_adapter_format_exact_messages_and_lm_kwargs_with_native_tool_calli"parameters": {"type": "object","properties": {"query": {"type": "string"},"k": {"type": "integer", "default": 3}},- "required": ["query", "k"]}}}]}+ "required": ["query"]}}}]}assert lm_kwargs == expected_lm_kwargsdef test_json_adapter_format_exact_messages_with_tool_calls_output_demo():diff --git a/tests/adapters/test_tool.py b/tests/adapters/test_tool.pyindex 4987a6a13..1e717308d 100644--- a/tests/adapters/test_tool.py+++ b/tests/adapters/test_tool.py@@ -146,6 +146,19 @@ def test_tool_from_function():assert tool.args["y"]["default"] == "hello"+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)++ function_call = tool.format_as_litellm_function_call()+ parameters = function_call["function"]["parameters"]++ assert parameters["required"] == ["x"]+ assert "y" not in parameters["required"]+ # The default is still advertised on the property itself.+ assert parameters["properties"]["y"]["default"] == "hello"++def test_tool_from_class():class Foo:def __init__(self, user_id: str):