Skip to content

Commit bc3648a

Browse files
Support kwargs in dspy Tool (#8102)
* support kwargs in dspy Tool Co-authored-by: ButterflyAtHeart <[email protected]> * improve comment --------- Co-authored-by: ButterflyAtHeart <[email protected]>
1 parent c498de5 commit bc3648a

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

dspy/primitives/tool.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ def foo(x: int, y: str = "hello"):
5757
self.args = args
5858
self.arg_types = arg_types
5959
self.arg_desc = arg_desc
60+
self.has_kwargs = False
6061

6162
self._parse_function(func, arg_desc)
6263

@@ -129,6 +130,7 @@ def _parse_function(self, func: Callable, arg_desc: dict[str, str] = None):
129130
self.desc = self.desc or desc
130131
self.args = self.args or args
131132
self.arg_types = self.arg_types or arg_types
133+
self.has_kwargs = any([param.kind == param.VAR_KEYWORD for param in sig.parameters.values()])
132134

133135
def _parse_args(self, **kwargs):
134136
parsed_kwargs = {}
@@ -147,6 +149,9 @@ def _parse_args(self, **kwargs):
147149
def __call__(self, **kwargs):
148150
for k, v in kwargs.items():
149151
if k not in self.args:
152+
if self.has_kwargs:
153+
# If the tool has kwargs, skip validation for unknown args
154+
continue
150155
raise ValueError(f"Arg {k} is not in the tool's args.")
151156
try:
152157
instance = v.model_dump() if hasattr(v, "model_dump") else v

tests/primitives/test_tool.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,12 @@ def dummy_function(x: list[list[DummyModel]]):
193193

194194
result = tool(**args)
195195
assert result == [[DummyModel(field1="hello", field2=123)]]
196+
197+
198+
def test_tool_call_kwarg():
199+
def fn(x: int, **kwargs):
200+
return kwargs
201+
tool = Tool(fn)
202+
203+
assert tool(x=1, y=2, z=3) == {"y": 2, "z": 3}
204+

0 commit comments

Comments
 (0)