DSPy: The framework for programming—not prompting—language models
Python
Move string representation of tool to Tool class (#8208)
TomuHirata21ff0dc3ac0b
diff --git a/dspy/predict/react.py b/dspy/predict/react.pyindex 6d0b33a90..36d8f654b 100644--- a/dspy/predict/react.py+++ b/dspy/predict/react.py@@ -46,10 +46,7 @@ class ReAct(Module):)for idx, tool in enumerate(tools.values()):- args = getattr(tool, "args")- desc = (f", whose description is <desc>{tool.desc}</desc>." if tool.desc else ".").replace("\n", " ")- desc += f" It takes arguments {args} in JSON format."- instr.append(f"({idx + 1}) {tool.name}{desc}")+ instr.append(f"({idx + 1}) {tool}")react_signature = (dspy.Signature({**signature.input_fields}, "\n".join(instr))@@ -197,7 +194,6 @@ trace of every module repeating the prefix.TOPIC 03: Simplifying ReAct's __init__ by moving modular logic to the Tool class.- * Handling descriptions and casting.* Handling exceptions and error messages.* More cleanly defining the "finish" tool, perhaps as a runtime-defined function?diff --git a/dspy/primitives/tool.py b/dspy/primitives/tool.pyindex 63574a9b7..0bd19d955 100644--- a/dspy/primitives/tool.py+++ b/dspy/primitives/tool.py@@ -173,6 +173,18 @@ class Tool:return convert_mcp_tool(session, tool)+ def __repr__(self):+ return (+ f"Tool(name={self.name}, desc={self.desc}, args={self.args})"+ )+++ def __str__(self):+ desc = f", whose description is <desc>{self.desc}</desc>.".replace("\n", " ") if self.desc else "."+ arg_desc = f"It takes arguments {self.args} in JSON format."+ return f"{self.name}{desc} {arg_desc}"++def resolve_json_schema_reference(schema: dict) -> dict:"""Recursively resolve json model schema, expanding all references."""diff --git a/tests/primitives/test_tool.py b/tests/primitives/test_tool.pyindex 4348d7e26..1d1c203f7 100644--- a/tests/primitives/test_tool.py+++ b/tests/primitives/test_tool.py@@ -251,6 +251,11 @@ def test_tool_call_kwarg():assert tool(x=1, y=2, z=3) == {"y": 2, "z": 3}+def test_tool_str():+ tool = Tool(dummy_function)+ assert str(tool) == "dummy_function, whose description is <desc>A dummy function for testing. Args: x: An integer parameter y: A string parameter </desc>. It takes arguments {'x': {'type': 'integer'}, 'y': {'type': 'string', 'default': 'hello'}} in JSON format."++@pytest.mark.asyncioasync def test_async_tool_from_function():tool = Tool(async_dummy_function)