DSPy: The framework for programming—not prompting—language models
Python
Support `dspy.Tool` as input field type and `dspy.ToolCall` as output field type (#8242)
Chen Qian99a07e9d2347
diff --git a/dspy/__init__.py b/dspy/__init__.pyindex 68f906528..b61d9d2b6 100644--- a/dspy/__init__.py+++ b/dspy/__init__.py@@ -8,7 +8,7 @@ import dspy.retrieversfrom dspy.evaluate import Evaluate # isort: skipfrom dspy.clients import * # isort: skip-from dspy.adapters import Adapter, ChatAdapter, JSONAdapter, TwoStepAdapter, Image, Audio, History, BaseType # isort: skip+from dspy.adapters import Adapter, ChatAdapter, JSONAdapter, TwoStepAdapter, Image, Audio, History, BaseType, Tool, ToolCalls # isort: skipfrom dspy.utils.logging_utils import configure_dspy_loggers, disable_logging, enable_loggingfrom dspy.utils.asyncify import asyncifyfrom dspy.utils.saving import loaddiff --git a/dspy/adapters/__init__.py b/dspy/adapters/__init__.pyindex 4ae8c4e26..15fc74a8a 100644--- a/dspy/adapters/__init__.py+++ b/dspy/adapters/__init__.py@@ -2,7 +2,7 @@ from dspy.adapters.base import Adapterfrom dspy.adapters.chat_adapter import ChatAdapterfrom dspy.adapters.json_adapter import JSONAdapterfrom dspy.adapters.two_step_adapter import TwoStepAdapter-from dspy.adapters.types import History, Image, Audio, BaseType+from dspy.adapters.types import History, Image, Audio, BaseType, Tool, ToolCalls__all__ = ["Adapter",@@ -13,4 +13,6 @@ __all__ = ["Audio","JSONAdapter","TwoStepAdapter",+ "Tool",+ "ToolCalls",]diff --git a/dspy/adapters/base.py b/dspy/adapters/base.pyindex 9ad6d1256..a8cced882 100644--- a/dspy/adapters/base.py+++ b/dspy/adapters/base.py@@ -1,10 +1,17 @@-from typing import TYPE_CHECKING, Any, Optional, Type+import logging+from typing import TYPE_CHECKING, Any, Optional, Type, get_origin++import json_repair+import litellmfrom dspy.adapters.types import Historyfrom dspy.adapters.types.base_type import split_message_content_for_custom_types+from dspy.adapters.types.tool import Tool, ToolCallsfrom dspy.signatures.signature import Signaturefrom dspy.utils.callback import BaseCallback, with_callbacks+logger = logging.getLogger(__name__)+if TYPE_CHECKING:from dspy.clients.lm import LM@@ -20,18 +27,78 @@ class Adapter:cls.format = with_callbacks(cls.format)cls.parse = with_callbacks(cls.parse)- def _call_post_process(self, outputs: list[dict[str, Any]], signature: Type[Signature]) -> list[dict[str, Any]]:+ def _call_preprocess(+ self,+ lm: "LM",+ lm_kwargs: dict[str, Any],+ signature: Type[Signature],+ inputs: dict[str, Any],+ use_native_function_calling: bool = False,+ ) -> dict[str, Any]:+ if use_native_function_calling:+ tool_call_input_field_name = self._get_tool_call_input_field_name(signature)+ tool_call_output_field_name = self._get_tool_call_output_field_name(signature)++ if tool_call_output_field_name and tool_call_input_field_name is None:+ raise ValueError(+ f"You provided an output field {tool_call_output_field_name} to receive the tool calls information, "+ "but did not provide any tools as the input. Please provide a list of tools as the input by adding an "+ "input field with type `list[dspy.Tool]`."+ )++ if tool_call_output_field_name and litellm.supports_function_calling(model=lm.model):+ tools = inputs[tool_call_input_field_name]+ tools = tools if isinstance(tools, list) else [tools]++ litellm_tools = []+ for tool in tools:+ litellm_tools.append(tool.format_as_litellm_function_call())++ lm_kwargs["tools"] = litellm_tools++ signature_for_native_function_calling = signature.delete(tool_call_output_field_name)++ return signature_for_native_function_calling++ return signature++ def _call_postprocess(+ self,+ signature: Type[Signature],+ outputs: list[dict[str, Any]],+ ) -> list[dict[str, Any]]:values = []+ tool_call_output_field_name = self._get_tool_call_output_field_name(signature)+for output in outputs:output_logprobs = None+ tool_calls = None+ text = outputif isinstance(output, dict):- output, output_logprobs = output["text"], output["logprobs"]-- value = self.parse(signature, output)-- if output_logprobs is not None:+ text = output["text"]+ output_logprobs = output.get("logprobs")+ tool_calls = output.get("tool_calls")++ if text:+ value = self.parse(signature, text)+ else:+ value = {}+ for field_name in signature.output_fields.keys():+ value[field_name] = None++ if tool_calls and tool_call_output_field_name:+ tool_calls = [+ {+ "name": v["function"]["name"],+ "args": json_repair.loads(v["function"]["arguments"]),+ }+ for v in tool_calls+ ]+ value[tool_call_output_field_name] = ToolCalls.from_dict_list(tool_calls)++ if output_logprobs:value["logprobs"] = output_logprobsvalues.append(value)@@ -46,10 +113,11 @@ class Adapter:demos: list[dict[str, Any]],inputs: dict[str, Any],) -> list[dict[str, Any]]:- inputs = self.format(signature, demos, inputs)+ processed_signature = self._call_preprocess(lm, lm_kwargs, signature, inputs)+ inputs = self.format(processed_signature, demos, inputs)outputs = lm(messages=inputs, **lm_kwargs)- return self._call_post_process(outputs, signature)+ return self._call_postprocess(signature, outputs)async def acall(self,@@ -59,10 +127,11 @@ class Adapter:demos: list[dict[str, Any]],inputs: dict[str, Any],) -> list[dict[str, Any]]:- inputs = self.format(signature, demos, inputs)+ processed_signature = self._call_preprocess(lm, lm_kwargs, signature, inputs)+ inputs = self.format(processed_signature, demos, inputs)outputs = await lm.acall(messages=inputs, **lm_kwargs)- return self._call_post_process(outputs, signature)+ return self._call_postprocess(signature, outputs)def format(self,@@ -297,6 +366,22 @@ class Adapter:return namereturn None+ def _get_tool_call_input_field_name(self, signature: Type[Signature]) -> bool:+ for name, field in signature.input_fields.items():+ # Look for annotation `list[dspy.Tool]` or `dspy.Tool`+ origin = get_origin(field.annotation)+ if origin is list and field.annotation.__args__[0] == Tool:+ return name+ if field.annotation == Tool:+ return name+ return None++ def _get_tool_call_output_field_name(self, signature: Type[Signature]) -> bool:+ for name, field in signature.output_fields.items():+ if field.annotation == ToolCalls:+ return name+ return None+def format_conversation_history(self,signature: Type[Signature],@@ -352,4 +437,4 @@ class Adapter:Returns:A dictionary of the output fields."""- raise NotImplementedError\ No newline at end of file+ raise NotImplementedErrordiff --git a/dspy/adapters/json_adapter.py b/dspy/adapters/json_adapter.pyindex 018bd5f41..e507c66e0 100644--- a/dspy/adapters/json_adapter.py+++ b/dspy/adapters/json_adapter.py@@ -77,6 +77,16 @@ class JSONAdapter(ChatAdapter):f"`response_format` argument. Original error: {e}") from e+ def _call_preprocess(+ self,+ lm: "LM",+ lm_kwargs: dict[str, Any],+ signature: Type[Signature],+ inputs: dict[str, Any],+ use_native_function_calling: bool = True,+ ) -> dict[str, Any]:+ return super()._call_preprocess(lm, lm_kwargs, signature, inputs, use_native_function_calling)+def format_field_structure(self, signature: Type[Signature]) -> str:parts = []parts.append("All interactions will be structured in the following way, with the appropriate values filled in.")diff --git a/dspy/adapters/two_step_adapter.py b/dspy/adapters/two_step_adapter.pyindex 9ee91458f..64f1b80ed 100644--- a/dspy/adapters/two_step_adapter.py+++ b/dspy/adapters/two_step_adapter.py@@ -1,7 +1,10 @@from typing import Any, Optional, Type+import json_repair+from dspy.adapters.base import Adapterfrom dspy.adapters.chat_adapter import ChatAdapter+from dspy.adapters.types import ToolCallsfrom dspy.adapters.utils import get_field_description_stringfrom dspy.clients import LMfrom dspy.signatures.field import InputField@@ -115,11 +118,16 @@ class TwoStepAdapter(Adapter):values = []+ tool_call_output_field_name = self._get_tool_call_output_field_name(signature)for output in outputs:output_logprobs = None+ tool_calls = None+ text = outputif isinstance(output, dict):- output, output_logprobs = output["text"], output["logprobs"]+ text = output["text"]+ output_logprobs = output.get("logprobs")+ tool_calls = output.get("tool_calls")try:# Call the smaller LM to extract structured data from the raw completion text with ChatAdapter@@ -128,13 +136,23 @@ class TwoStepAdapter(Adapter):lm_kwargs={},signature=extractor_signature,demos=[],- inputs={"text": output},+ inputs={"text": text},)value = value[0]except Exception as e:raise ValueError(f"Failed to parse response from the original completion: {output}") from e+ if tool_calls and tool_call_output_field_name:+ tool_calls = [+ {+ "name": v["function"]["name"],+ "args": json_repair.loads(v["function"]["arguments"]),+ }+ for v in tool_calls+ ]+ value[tool_call_output_field_name] = ToolCalls.from_dict_list(tool_calls)+if output_logprobs is not None:value["logprobs"] = output_logprobsdiff --git a/dspy/adapters/types/__init__.py b/dspy/adapters/types/__init__.pyindex c690a8553..11d09227c 100644--- a/dspy/adapters/types/__init__.py+++ b/dspy/adapters/types/__init__.py@@ -2,5 +2,6 @@ from dspy.adapters.types.history import Historyfrom dspy.adapters.types.image import Imagefrom dspy.adapters.types.audio import Audiofrom dspy.adapters.types.base_type import BaseType+from dspy.adapters.types.tool import Tool, ToolCalls-__all__ = ["History", "Image", "Audio", "BaseType"]+__all__ = ["History", "Image", "Audio", "BaseType", "Tool", "ToolCalls"]diff --git a/dspy/adapters/types/base_type.py b/dspy/adapters/types/base_type.pyindex f2983ef46..b57c75cb1 100644--- a/dspy/adapters/types/base_type.py+++ b/dspy/adapters/types/base_type.py@@ -1,6 +1,6 @@import jsonimport re-from typing import Any+from typing import Any, Union, get_args, get_originimport json_repairimport pydantic@@ -26,12 +26,42 @@ class BaseType(pydantic.BaseModel):```"""- def format(self) -> list[dict[str, Any]]:+ def format(self) -> Union[list[dict[str, Any]], str]:raise NotImplementedError+ @classmethod+ def description(cls) -> str:+ """Description of the custom type"""+ return ""++ @classmethod+ def extract_custom_type_from_annotation(cls, annotation):+ """Extract all custom types from the annotation.++ This is used to extract all custom types from the annotation of a field, while the annotation can+ have arbitrary level of nesting. For example, we detect `Tool` is in `list[dict[str, Tool]]`.+ """+ # Direct match+ if isinstance(annotation, type) and issubclass(annotation, cls):+ return [annotation]++ origin = get_origin(annotation)+ if origin is None:+ return []++ result = []+ # Recurse into all type args+ for arg in get_args(annotation):+ result.extend(cls.extract_custom_type_from_annotation(arg))++ return result+@pydantic.model_serializer()def serialize_model(self):- return f"{CUSTOM_TYPE_START_IDENTIFIER}{self.format()}{CUSTOM_TYPE_END_IDENTIFIER}"+ formatted = self.format()+ if isinstance(formatted, list):+ return f"{CUSTOM_TYPE_START_IDENTIFIER}{self.format()}{CUSTOM_TYPE_END_IDENTIFIER}"+ return formatteddef split_message_content_for_custom_types(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:diff --git a/dspy/primitives/tool.py b/dspy/adapters/types/tool.pysimilarity index 83%rename from dspy/primitives/tool.pyrename to dspy/adapters/types/tool.pyindex 0dd0ccecd..07b980515 100644--- a/dspy/primitives/tool.py+++ b/dspy/adapters/types/tool.py@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Any, Callable, Optional, Tuple, Type, get_origfrom jsonschema import ValidationError, validatefrom pydantic import BaseModel, TypeAdapter, create_model+from dspy.adapters.types.base_type import BaseTypefrom dspy.utils.callback import with_callbacksif TYPE_CHECKING:@@ -13,13 +14,22 @@ if TYPE_CHECKING:_TYPE_MAPPING = {"string": str, "integer": int, "number": float, "boolean": bool, "array": list, "object": dict}-class Tool:++class Tool(BaseType):"""Tool class.This class is used to simplify the creation of tools for tool calling (function calling) in LLMs. Only supportsfunctions for now."""+ func: Callable+ name: Optional[str] = None+ desc: Optional[str] = None+ args: Optional[dict[str, Any]] = None+ arg_types: Optional[dict[str, Any]] = None+ arg_desc: Optional[dict[str, str]] = None+ has_kwargs: bool = False+def __init__(self,func: Callable,@@ -57,14 +67,7 @@ class Tool:# Expected output: {'x': {'type': 'integer'}, 'y': {'type': 'string', 'default': 'hello'}}```"""- self.func = func- self.name = name- self.desc = desc- self.args = args- self.arg_types = arg_types- self.arg_desc = arg_desc- self.has_kwargs = False-+ super().__init__(func=func, name=name, desc=desc, args=args, arg_types=arg_types, arg_desc=arg_desc)self._parse_function(func, arg_desc)def _parse_function(self, func: Callable, arg_desc: Optional[dict[str, str]] = None):@@ -140,6 +143,23 @@ class Tool:parsed_kwargs[k] = vreturn parsed_kwargs+ def format(self):+ return str(self)++ def format_as_litellm_function_call(self):+ return {+ "type": "function",+ "function": {+ "name": self.name,+ "description": self.desc,+ "parameters": {+ "type": "object",+ "properties": self.args,+ "required": list(self.args.keys()),+ },+ },+ }+@with_callbacksdef __call__(self, **kwargs):parsed_kwargs = self._validate_and_parse_args(**kwargs)@@ -188,7 +208,7 @@ class Tool:from dspy.utils.langchain_tool import convert_langchain_toolreturn convert_langchain_tool(tool)-+def __repr__(self):return f"Tool(name={self.name}, desc={self.desc}, args={self.args})"@@ -198,6 +218,44 @@ class Tool:return f"{self.name}{desc} {arg_desc}"+class ToolCalls(BaseType):+ class ToolCall(BaseModel):+ name: str+ args: dict[str, Any]++ tool_calls: list[ToolCall]++ @classmethod+ def from_dict_list(cls, tool_calls_dicts: list[dict[str, Any]]) -> "ToolCalls":+ """Convert a list of dictionaries to a ToolCalls instance.++ Args:+ dict_list: A list of dictionaries, where each dictionary should have 'name' and 'args' keys.++ Returns:+ A ToolCalls instance.++ Example:++ ```python+ tool_calls_dict = [+ {"name": "search", "args": {"query": "hello"}},+ {"name": "translate", "args": {"text": "world"}}+ ]+ tool_calls = ToolCalls.from_dict_list(tool_calls_dict)+ ```+ """+ tool_calls = [cls.ToolCall(**item) for item in tool_calls_dicts]+ return cls(tool_calls=tool_calls)++ @classmethod+ def description(cls) -> str:+ return (+ "Tool calls information, including the name of the tools and the arguments to be passed to it. "+ "Arguments must be provided in JSON format."+ )++def _resolve_json_schema_reference(schema: dict) -> dict:"""Recursively resolve json model schema, expanding all references."""diff --git a/dspy/adapters/utils.py b/dspy/adapters/utils.pyindex 21540bd32..2c27fec94 100644--- a/dspy/adapters/utils.py+++ b/dspy/adapters/utils.py@@ -10,6 +10,7 @@ import pydanticfrom pydantic import TypeAdapterfrom pydantic.fields import FieldInfo+from dspy.adapters.types.base_type import BaseTypefrom dspy.signatures.utils import get_dspy_field_type@@ -200,7 +201,14 @@ def get_field_description_string(fields: dict) -> str:for idx, (k, v) in enumerate(fields.items()):field_message = f"{idx + 1}. `{k}`"field_message += f" ({get_annotation_name(v.annotation)})"- field_message += f": {v.json_schema_extra['desc']}" if v.json_schema_extra["desc"] != f"${{{k}}}" else ""+ desc = v.json_schema_extra["desc"] if v.json_schema_extra["desc"] != f"${{{k}}}" else ""++ custom_types = BaseType.extract_custom_type_from_annotation(v.annotation)+ for custom_type in custom_types:+ if len(custom_type.description()) > 0:+ desc += f"\n Type description of {get_annotation_name(custom_type)}: {custom_type.description()}"++ field_message += f": {desc}"field_message += (f"\nConstraints: {v.json_schema_extra['constraints']}" if v.json_schema_extra.get("constraints") else "")diff --git a/dspy/clients/base_lm.py b/dspy/clients/base_lm.pyindex 0c3ae2ee7..1def8bb83 100644--- a/dspy/clients/base_lm.py+++ b/dspy/clients/base_lm.py@@ -50,16 +50,20 @@ class BaseLM:def _process_lm_response(self, response, prompt, messages, **kwargs):merged_kwargs = {**self.kwargs, **kwargs}- if merged_kwargs.get("logprobs"):- outputs = [- {- "text": c.message.content if hasattr(c, "message") else c["text"],- "logprobs": c.logprobs if hasattr(c, "logprobs") else c["logprobs"],- }- for c in response.choices- ]- else:- outputs = [c.message.content if hasattr(c, "message") else c["text"] for c in response.choices]++ outputs = []+ for c in response.choices:+ output = {}+ output["text"] = c.message.content if hasattr(c, "message") else c["text"]+ if merged_kwargs.get("logprobs"):+ output["logprobs"] = c.logprobs if hasattr(c, "logprobs") else c["logprobs"]+ if hasattr(c, "message") and getattr(c.message, "tool_calls", None):+ output["tool_calls"] = c.message.tool_calls+ outputs.append(output)++ if all(len(output) == 1 for output in outputs):+ # Return a list if every output only has "text" key+ outputs = [output["text"] for output in outputs]if settings.disable_history:return outputsdiff --git a/dspy/predict/code_act.py b/dspy/predict/code_act.pyindex b136171d5..1633e3395 100644--- a/dspy/predict/code_act.py+++ b/dspy/predict/code_act.py@@ -1,15 +1,14 @@-import loggingimport inspect--from typing import Callable, Union, Type+import loggingfrom inspect import Signature+from typing import Callable, Type, Unionimport dspy+from dspy.adapters.types.tool import Tool+from dspy.predict.program_of_thought import ProgramOfThought+from dspy.predict.react import ReActfrom dspy.primitives.python_interpreter import PythonInterpreter-from dspy.primitives.tool import Toolfrom dspy.signatures.signature import ensure_signature-from dspy.predict.react import ReAct-from dspy.predict.program_of_thought import ProgramOfThoughtlogger = logging.getLogger(__name__)diff --git a/dspy/predict/react.py b/dspy/predict/react.pyindex eb04a1695..cc2a8a027 100644--- a/dspy/predict/react.py+++ b/dspy/predict/react.py@@ -4,8 +4,8 @@ from typing import Any, Callable, Literalfrom litellm import ContextWindowExceededErrorimport dspy+from dspy.adapters.types.tool import Toolfrom dspy.primitives.program import Module-from dspy.primitives.tool import Toolfrom dspy.signatures.signature import ensure_signaturelogger = logging.getLogger(__name__)diff --git a/dspy/primitives/__init__.py b/dspy/primitives/__init__.pyindex 0fa160d26..00d3f47de 100644--- a/dspy/primitives/__init__.py+++ b/dspy/primitives/__init__.py@@ -4,7 +4,6 @@ from dspy.primitives.module import BaseModulefrom dspy.primitives.prediction import Completions, Predictionfrom dspy.primitives.program import Module, Programfrom dspy.primitives.python_interpreter import PythonInterpreter-from dspy.primitives.tool import Tool__all__ = ["assertions",@@ -15,5 +14,4 @@ __all__ = ["Program","Module","PythonInterpreter",- "Tool",]diff --git a/dspy/utils/inspect_history.py b/dspy/utils/inspect_history.pyindex 16baefd30..10333c4eb 100644--- a/dspy/utils/inspect_history.py+++ b/dspy/utils/inspect_history.py@@ -43,8 +43,18 @@ def pretty_print_history(history, n: int = 1):print(_blue(image_str.strip()))print("\n")- print(_red("Response:"))- print(_green(outputs[0].strip()))+ if isinstance(outputs[0], dict):+ if outputs[0]["text"]:+ print(_red("Response:"))+ print(_green(outputs[0]["text"].strip()))++ if outputs[0].get("tool_calls"):+ print(_red("Tool calls:"))+ for tool_call in outputs[0]["tool_calls"]:+ print(_green(f"{tool_call['function']['name']}: {tool_call['function']['arguments']}"))+ else:+ print(_red("Response:"))+ print(_green(outputs[0].strip()))if len(outputs) > 1:choices_text = f" \t (and {len(outputs) - 1} other completions)"diff --git a/dspy/utils/langchain_tool.py b/dspy/utils/langchain_tool.pyindex 3417b1f0f..cce44660a 100644--- a/dspy/utils/langchain_tool.py+++ b/dspy/utils/langchain_tool.py@@ -1,5 +1,6 @@from typing import TYPE_CHECKING, Any-from dspy.primitives.tool import Tool, convert_input_schema_to_tool_args++from dspy.adapters.types.tool import Tool, convert_input_schema_to_tool_argsif TYPE_CHECKING:from langchain.tools import BaseTooldiff --git a/dspy/utils/mcp.py b/dspy/utils/mcp.pyindex 6f0a00656..de7e08b06 100644--- a/dspy/utils/mcp.py+++ b/dspy/utils/mcp.py@@ -1,6 +1,6 @@from typing import TYPE_CHECKING, Any, Union-from dspy.primitives.tool import Tool, convert_input_schema_to_tool_args+from dspy.adapters.types.tool import Tool, convert_input_schema_to_tool_argsif TYPE_CHECKING:import mcpdiff --git a/tests/adapters/test_chat_adapter.py b/tests/adapters/test_chat_adapter.pyindex d25000e4e..816c04a31 100644--- a/tests/adapters/test_chat_adapter.py+++ b/tests/adapters/test_chat_adapter.py@@ -6,6 +6,7 @@ import pytestimport dspyimport pydantic+import json@pytest.mark.parametrize(@@ -314,3 +315,40 @@ def test_chat_adapter_formats_image_with_few_shot_examples_with_nested_images():# The query image is formatted in the last user messageassert {"type": "image_url", "image_url": {"url": "https://example.com/image4.jpg"}} in messages[-1]["content"]+++def test_chat_adapter_with_tool():+ class MySignature(dspy.Signature):+ """Answer question with the help of the tools"""++ question: str = dspy.InputField()+ tools: list[dspy.Tool] = dspy.InputField()+ answer: str = dspy.OutputField()+ tool_calls: dspy.ToolCalls = dspy.OutputField()++ def get_weather(city: str) -> str:+ """Get the weather for a city"""+ return f"The weather in {city} is sunny"++ def get_population(country: str, year: int) -> str:+ """Get the population for a country"""+ return f"The population of {country} in {year} is 1000000"++ tools = [dspy.Tool(get_weather), dspy.Tool(get_population)]++ adapter = dspy.ChatAdapter()+ messages = adapter.format(MySignature, [], {"question": "What is the weather in Tokyo?", "tools": tools})++ assert len(messages) == 2++ # The output field type description should be included in the system message even if the output field is nested+ assert dspy.ToolCalls.description() in messages[0]["content"]++ # The user message should include the question and the tools+ assert "What is the weather in Tokyo?" in messages[1]["content"]+ assert "get_weather" in messages[1]["content"]+ assert "get_population" in messages[1]["content"]++ # Tool arguments format should be included in the user message+ assert "{'city': {'type': 'string'}}" in messages[1]["content"]+ assert "{'country': {'type': 'string'}, 'year': {'type': 'integer'}}" in messages[1]["content"]diff --git a/tests/adapters/test_json_adapter.py b/tests/adapters/test_json_adapter.pyindex 6cd185203..622458114 100644--- a/tests/adapters/test_json_adapter.py+++ b/tests/adapters/test_json_adapter.py@@ -5,6 +5,7 @@ import pytestfrom litellm.utils import Choices, Message, ModelResponseimport dspy+import jsondef test_json_adapter_passes_structured_output_when_supported_by_model():@@ -337,3 +338,85 @@ def test_json_adapter_formats_image_with_few_shot_examples_with_nested_images():# The query image is formatted in the last user messageassert {"type": "image_url", "image_url": {"url": "https://example.com/image4.jpg"}} in messages[-1]["content"]+++def test_json_adapter_with_tool():+ class MySignature(dspy.Signature):+ """Answer question with the help of the tools"""++ question: str = dspy.InputField()+ tools: list[dspy.Tool] = dspy.InputField()+ answer: str = dspy.OutputField()+ tool_calls: dspy.ToolCalls = dspy.OutputField()++ def get_weather(city: str) -> str:+ """Get the weather for a city"""+ return f"The weather in {city} is sunny"++ def get_population(country: str, year: int) -> str:+ """Get the population for a country"""+ return f"The population of {country} in {year} is 1000000"++ tools = [dspy.Tool(get_weather), dspy.Tool(get_population)]++ adapter = dspy.JSONAdapter()+ messages = adapter.format(MySignature, [], {"question": "What is the weather in Tokyo?", "tools": tools})++ assert len(messages) == 2++ # The output field type description should be included in the system message even if the output field is nested+ assert dspy.ToolCalls.description() in messages[0]["content"]++ # The user message should include the question and the tools+ assert "What is the weather in Tokyo?" in messages[1]["content"]+ assert "get_weather" in messages[1]["content"]+ assert "get_population" in messages[1]["content"]++ # Tool arguments format should be included in the user message+ assert "{'city': {'type': 'string'}}" in messages[1]["content"]+ assert "{'country': {'type': 'string'}, 'year': {'type': 'integer'}}" in messages[1]["content"]++ with mock.patch("litellm.completion") as mock_completion:+ lm = dspy.LM(model="openai/gpt-4o-mini")+ adapter(lm, {}, MySignature, [], {"question": "What is the weather in Tokyo?", "tools": tools})++ mock_completion.assert_called_once()+ _, call_kwargs = mock_completion.call_args++ # Assert tool calls are included in the `tools` arg+ assert len(call_kwargs["tools"]) > 0+ assert call_kwargs["tools"][0] == {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Get the weather for a city",+ "parameters": {+ "type": "object",+ "properties": {+ "city": {+ "type": "string",+ },+ },+ "required": ["city"],+ },+ },+ }+ assert call_kwargs["tools"][1] == {+ "type": "function",+ "function": {+ "name": "get_population",+ "description": "Get the population for a country",+ "parameters": {+ "type": "object",+ "properties": {+ "country": {+ "type": "string",+ },+ "year": {+ "type": "integer",+ },+ },+ "required": ["country", "year"],+ },+ },+ }diff --git a/tests/primitives/test_tool.py b/tests/adapters/test_tool.pysimilarity index 99%rename from tests/primitives/test_tool.pyrename to tests/adapters/test_tool.pyindex dfee495c6..925e9b9d4 100644--- a/tests/primitives/test_tool.py+++ b/tests/adapters/test_tool.py@@ -1,10 +1,12 @@import asynciofrom typing import Any, Optional+import dspyimport pytestfrom pydantic import BaseModel-from dspy.primitives.tool import Tool+from dspy.adapters.types.tool import Tool+from unittest import mock# Test fixtures