DSPy: The framework for programming—not prompting—language models
Python
fix(adapter): guard annotation subclass checks for ReAct tool args #9425 (#9433)
Isaac Miller35613ab51c8a
diff --git a/dspy/adapters/base.py b/dspy/adapters/base.pyindex a6cd102f9..751b018f2 100644--- a/dspy/adapters/base.py+++ b/dspy/adapters/base.py@@ -105,8 +105,8 @@ class Adapter:for name, field in signature.output_fields.items():if (isinstance(field.annotation, type)- and issubclass(field.annotation, Type)and field.annotation in self.native_response_types+ and issubclass(field.annotation, Type)):signature = field.annotation.adapt_to_native_lm_feature(signature, name, lm, lm_kwargs)@@ -166,8 +166,8 @@ class Adapter:for name, field in original_signature.output_fields.items():if (isinstance(field.annotation, type)- and issubclass(field.annotation, Type)and field.annotation in self.native_response_types+ and issubclass(field.annotation, Type)):parsed_value = field.annotation.parse_lm_response(output)if parsed_value is not None:diff --git a/dspy/adapters/utils.py b/dspy/adapters/utils.pyindex 4e9866ed2..b45eda559 100644--- a/dspy/adapters/utils.py+++ b/dspy/adapters/utils.py@@ -17,6 +17,13 @@ from dspy.adapters.types.reasoning import Reasoningfrom dspy.signatures.utils import get_dspy_field_type+def _annotation_is_subclass(annotation: Any, expected_base: type) -> bool:+ try:+ return inspect.isclass(annotation) and issubclass(annotation, expected_base)+ except TypeError:+ return False++def serialize_for_json(value: Any) -> Any:"""Formats the specified value so that it can be serialized as a JSON string.@@ -92,7 +99,7 @@ def translate_field_type(field_name, field_info):desc = "must be True or False"elif field_type in (int, float):desc = f"must be a single {field_type.__name__} value"- elif inspect.isclass(field_type) and issubclass(field_type, enum.Enum):+ elif _annotation_is_subclass(field_type, enum.Enum):enum_vals = "; ".join(str(member.value) for member in field_type)desc = f"must be one of: {enum_vals}"elif hasattr(field_type, "__origin__") and field_type.__origin__ is Literal:@@ -101,7 +108,7 @@ def translate_field_type(field_name, field_info):# literal or returning a value of the form 'Literal[<selected_value>]'f"must exactly match (no extra characters) one of: {'; '.join([str(x) for x in field_type.__args__])}")- elif inspect.isclass(field_type) and issubclass(field_type, Code) and field_type.description():+ elif _annotation_is_subclass(field_type, Code) and field_type.description():# Code has a rich type description already; avoid duplicating its large schema block.desc = ""else:@@ -182,7 +189,7 @@ def parse_value(value, annotation):try:return TypeAdapter(annotation).validate_python(candidate)except pydantic.ValidationError as e:- if inspect.isclass(annotation) and issubclass(annotation, DspyType):+ if _annotation_is_subclass(annotation, DspyType):try:# For dspy.Type, try parsing from the original value in case it has a custom parserreturn TypeAdapter(annotation).validate_python(value)diff --git a/tests/predict/test_react.py b/tests/predict/test_react.pyindex bd65515fb..f5a4caabd 100644--- a/tests/predict/test_react.py+++ b/tests/predict/test_react.py@@ -5,6 +5,8 @@ import pytestfrom pydantic import BaseModelimport dspy+import dspy.adapters.base as adapter_base+import dspy.adapters.utils as adapter_utilsfrom dspy.utils.dummies import DummyLM@@ -131,6 +133,52 @@ def test_tool_calling_with_pydantic_args():assert outputs.trajectory == expected_trajectory+def test_react_with_tools_skips_native_response_issubclass_for_generic_alias(monkeypatch):+ def get_user_info(name: str):+ return {"name": name}++ class CustomerService(dspy.Signature):+ user_request: str = dspy.InputField()+ process_result: str = dspy.OutputField()++ react = dspy.ReAct(CustomerService, tools=[get_user_info])+ problem_annotation = react.react.signature.output_fields["next_tool_args"].annotation++ def guarded_issubclass(cls, class_or_tuple):+ if cls == problem_annotation:+ raise TypeError("issubclass() arg 1 must be a class")+ return issubclass(cls, class_or_tuple)++ monkeypatch.setattr(adapter_base, "issubclass", guarded_issubclass, raising=False)+ monkeypatch.setattr(adapter_utils, "issubclass", guarded_issubclass, raising=False)++ lm = DummyLM(+ [+ {+ "next_thought": "I should look up the user first.",+ "next_tool_name": "get_user_info",+ "next_tool_args": {"name": "Adam"},+ },+ {+ "next_thought": "I have the information I need, so I can finish now.",+ "next_tool_name": "finish",+ "next_tool_args": {},+ },+ {+ "reasoning": "I fetched the user profile and can answer the request.",+ "process_result": "Resolved Adam's request.",+ },+ ]+ )++ with dspy.context(lm=lm):+ result = react(user_request="Help me, my name is Adam")++ assert result.process_result == "Resolved Adam's request."+ assert result.trajectory["tool_name_0"] == "get_user_info"+ assert result.trajectory["tool_args_0"] == {"name": "Adam"}++def test_tool_calling_without_typehint():def foo(a, b):"""Add two numbers."""