DSPy: The framework for programming—not prompting—language models
Python
Flexible handling of `dspy.ToolCalls` parsing (#8563)
Chen Qiana16d23b043dd
diff --git a/dspy/adapters/types/tool.py b/dspy/adapters/types/tool.pyindex 0eb8c90fd..5cde703a4 100644--- a/dspy/adapters/types/tool.py+++ b/dspy/adapters/types/tool.py@@ -2,6 +2,7 @@ import asyncioimport inspectfrom typing import TYPE_CHECKING, Any, Callable, Type, get_origin, get_type_hints+import pydanticfrom jsonschema import ValidationError, validatefrom pydantic import BaseModel, TypeAdapter, create_model@@ -255,10 +256,19 @@ class Tool(Type):class ToolCalls(Type):- class ToolCall(BaseModel):+ class ToolCall(Type):name: strargs: dict[str, Any]+ def format(self):+ return {+ "type": "function",+ "function": {+ "name": self.name,+ "arguments": self.args,+ },+ }+tool_calls: list[ToolCall]@classmethod@@ -293,21 +303,37 @@ class ToolCalls(Type):def format(self) -> list[dict[str, Any]]:# The tool_call field is compatible with OpenAI's tool calls schema.- return [- {- "type": "tool_calls",- "tool_calls": [- {- "type": "function",- "function": {- "name": tool_call.name,- "arguments": tool_call.args,- },+ return {+ "tool_calls": [tool_call.format() for tool_call in self.tool_calls],+ }++ @pydantic.model_validator(mode="before")+ @classmethod+ def validate_input(cls, data: Any):+ if isinstance(data, cls):+ return data++ # Handle case where data is a list of dicts with "name" and "args" keys+ if isinstance(data, list) and all(+ isinstance(item, dict) and "name" in item and "args" in item for item in data+ ):+ return {"tool_calls": [cls.ToolCall(**item) for item in data]}+ # Handle case where data is a dict+ elif isinstance(data, dict):+ if "tool_calls" in data:+ # Handle case where data is a dict with "tool_calls" key+ tool_calls_data = data["tool_calls"]+ if isinstance(tool_calls_data, list):+ return {+ "tool_calls": [+ cls.ToolCall(**item) if isinstance(item, dict) else item for item in tool_calls_data+ ]}- for tool_call in self.tool_calls- ],- }- ]+ elif "name" in data and "args" in data:+ # Handle case where data is a dict with "name" and "args" keys+ return {"tool_calls": [cls.ToolCall(**data)]}++ raise ValueError(f"Received invalid value for `dspy.ToolCalls`: {data}")def _resolve_json_schema_reference(schema: dict) -> dict:diff --git a/tests/adapters/test_chat_adapter.py b/tests/adapters/test_chat_adapter.pyindex 98e892e8d..0d5ee764c 100644--- a/tests/adapters/test_chat_adapter.py+++ b/tests/adapters/test_chat_adapter.py@@ -531,3 +531,63 @@ def test_chat_adapter_toolcalls_native_function_calling():)assert result[0]["answer"] == "Paris"assert result[0]["tool_calls"] is None+++def test_chat_adapter_toolcalls_vague_match():+ class MySignature(dspy.Signature):+ question: str = dspy.InputField()+ tools: list[dspy.Tool] = dspy.InputField()+ tool_calls: dspy.ToolCalls = dspy.OutputField()++ def get_weather(city: str) -> str:+ return f"The weather in {city} is sunny"++ tools = [dspy.Tool(get_weather)]++ adapter = dspy.ChatAdapter()++ with mock.patch("litellm.completion") as mock_completion:+ # Case 1: tool_calls field is a list of dicts+ mock_completion.return_value = ModelResponse(+ choices=[+ Choices(+ message=Message(+ content="[[ ## tool_calls ## ]]\n[{'name': 'get_weather', 'args': {'city': 'Paris'}]"+ )+ )+ ],+ model="openai/gpt-4o-mini",+ )+ result = adapter(+ dspy.LM(model="openai/gpt-4o-mini", cache=False),+ {},+ MySignature,+ [],+ {"question": "What is the weather in Paris?", "tools": tools},+ )+ assert result[0]["tool_calls"] == dspy.ToolCalls(+ tool_calls=[dspy.ToolCalls.ToolCall(name="get_weather", args={"city": "Paris"})]+ )++ with mock.patch("litellm.completion") as mock_completion:+ # Case 2: tool_calls field is a single dict with "name" and "args" keys+ mock_completion.return_value = ModelResponse(+ choices=[+ Choices(+ message=Message(+ content="[[ ## tool_calls ## ]]\n{'name': 'get_weather', 'args': {'city': 'Paris'}}"+ )+ )+ ],+ model="openai/gpt-4o-mini",+ )+ result = adapter(+ dspy.LM(model="openai/gpt-4o-mini", cache=False),+ {},+ MySignature,+ [],+ {"question": "What is the weather in Paris?", "tools": tools},+ )+ assert result[0]["tool_calls"] == dspy.ToolCalls(+ tool_calls=[dspy.ToolCalls.ToolCall(name="get_weather", args={"city": "Paris"})]+ )diff --git a/tests/adapters/test_tool.py b/tests/adapters/test_tool.pyindex 90e23b331..d9c38912f 100644--- a/tests/adapters/test_tool.py+++ b/tests/adapters/test_tool.py@@ -394,42 +394,33 @@ def test_async_tool_call_in_sync_mode():TOOL_CALL_TEST_CASES = [- ([], [{"type": "tool_calls", "tool_calls": []}]),+ ([], {"tool_calls": []}),([{"name": "search", "args": {"query": "hello"}}],- [- {- "type": "tool_calls",- "tool_calls": [{"type": "function", "function": {"name": "search", "arguments": {"query": "hello"}}}],- }- ],+ {+ "tool_calls": [{"type": "function", "function": {"name": "search", "arguments": {"query": "hello"}}}],+ },),([{"name": "search", "args": {"query": "hello"}},{"name": "translate", "args": {"text": "world", "lang": "fr"}},],- [- {- "type": "tool_calls",- "tool_calls": [- {"type": "function", "function": {"name": "search", "arguments": {"query": "hello"}}},- {- "type": "function",- "function": {"name": "translate", "arguments": {"text": "world", "lang": "fr"}},- },- ],- }- ],+ {+ "tool_calls": [+ {"type": "function", "function": {"name": "search", "arguments": {"query": "hello"}}},+ {+ "type": "function",+ "function": {"name": "translate", "arguments": {"text": "world", "lang": "fr"}},+ },+ ],+ },),([{"name": "get_time", "args": {}}],- [- {- "type": "tool_calls",- "tool_calls": [{"type": "function", "function": {"name": "get_time", "arguments": {}}}],- }- ],+ {+ "tool_calls": [{"type": "function", "function": {"name": "get_time", "arguments": {}}}],+ },),]@@ -454,40 +445,89 @@ def test_tool_calls_format_from_dict_list():tool_calls = ToolCalls.from_dict_list(tool_calls_dicts)result = tool_calls.format()- assert len(result[0]["tool_calls"]) == 2- assert result[0]["tool_calls"][0]["function"]["name"] == "search"- assert result[0]["tool_calls"][1]["function"]["name"] == "translate"+ assert len(result["tool_calls"]) == 2+ assert result["tool_calls"][0]["function"]["name"] == "search"+ assert result["tool_calls"][1]["function"]["name"] == "translate"+++def test_toolcalls_vague_match():+ """+ Test that ToolCalls can parse the data with slightly off format:++ - a single dict with "name" and "args"+ - a list of dicts with "name" and "args"+ - invalid input (should raise ValueError)+ """+ # Single dict with "name" and "args" should parse as one ToolCall+ data_single = {"name": "search", "args": {"query": "hello"}}+ tc = ToolCalls.model_validate(data_single)+ assert isinstance(tc, ToolCalls)+ assert len(tc.tool_calls) == 1+ assert tc.tool_calls[0].name == "search"+ assert tc.tool_calls[0].args == {"query": "hello"}++ # List of dicts with "name" and "args" should parse as multiple ToolCalls+ data_list = [+ {"name": "search", "args": {"query": "hello"}},+ {"name": "translate", "args": {"text": "world", "lang": "fr"}},+ ]+ tc = ToolCalls.model_validate(data_list)+ assert isinstance(tc, ToolCalls)+ assert len(tc.tool_calls) == 2+ assert tc.tool_calls[0].name == "search"+ assert tc.tool_calls[1].name == "translate"++ # Dict with "tool_calls" key containing a list of dicts+ data_tool_calls = {+ "tool_calls": [+ {"name": "search", "args": {"query": "hello"}},+ {"name": "get_time", "args": {}},+ ]+ }+ tc = ToolCalls.model_validate(data_tool_calls)+ assert isinstance(tc, ToolCalls)+ assert len(tc.tool_calls) == 2+ assert tc.tool_calls[0].name == "search"+ assert tc.tool_calls[1].name == "get_time"++ # Invalid input should raise ValueError+ with pytest.raises(ValueError):+ ToolCalls.model_validate({"foo": "bar"})+ with pytest.raises(ValueError):+ ToolCalls.model_validate([{"foo": "bar"}])-def test_tool_convert_input_schema_to_tool_args__no_input_params():+def test_tool_convert_input_schema_to_tool_args_no_input_params():args, arg_types, arg_desc = convert_input_schema_to_tool_args(schema={"properties": {}})assert args == {}assert arg_types == {}assert arg_desc == {}-def test_tool_convert_input_schema_to_tool_args__lang_chain():+def test_tool_convert_input_schema_to_tool_args_lang_chain():# Example from langchain docs:# https://web.archive.org/web/20250723101359/https://api.python.langchain.com/en/latest/tools/langchain_core.tools.tool.html- args, arg_types, arg_desc = convert_input_schema_to_tool_args(schema={- "title": "fooSchema",- "description": "The foo.",- "type": "object",- "properties": {- "bar": {- "title": "Bar",- "description": "The bar.",- "type": "string",+ args, arg_types, arg_desc = convert_input_schema_to_tool_args(+ schema={+ "title": "fooSchema",+ "description": "The foo.",+ "type": "object",+ "properties": {+ "bar": {+ "title": "Bar",+ "description": "The bar.",+ "type": "string",+ },+ "baz": {+ "title": "Baz",+ "type": "integer",+ },},- "baz": {- "title": "Baz",- "type": "integer",- }- },- "required": [- "baz",- ],- })+ "required": [+ "baz",+ ],+ }+ )assert args == {"bar": {"title": "Bar", "description": "The bar.", "type": "string"},"baz": {"title": "Baz", "type": "integer"},