DSPy: The framework for programming—not prompting—language models
Python
fix BaseType annotation check (#8318)
Omar Khattabcc78b4649562
diff --git a/dspy/adapters/types/base_type.py b/dspy/adapters/types/base_type.pyindex b57c75cb1..a2b71339f 100644--- a/dspy/adapters/types/base_type.py+++ b/dspy/adapters/types/base_type.py@@ -1,5 +1,6 @@import jsonimport re+import inspectfrom typing import Any, Union, get_args, get_originimport json_repair@@ -41,9 +42,18 @@ class BaseType(pydantic.BaseModel):This is used to extract all custom types from the annotation of a field, while the annotation canhave 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]+ # Direct match. Some typing constructs (like `typing.Any`, `TypeAlias`,+ # or weird internals) may pass `isinstance(..., type)` but are not+ # valid classes for `issubclass`. We defensively guard against this by+ # using `inspect.isclass` and wrapping the call in a try/except block.+ try:+ if inspect.isclass(annotation) and issubclass(annotation, cls):+ return [annotation]+ except TypeError:+ # `issubclass` can raise `TypeError` if the argument is not actually+ # a class (even if `inspect.isclass` thought otherwise). In these+ # cases we just ignore the annotation.+ return []origin = get_origin(annotation)if origin is None: