Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Fix a bug with generics

Thomas D Ahlebf011b8c82c1
diff --git a/dspy/signatures/signature.py b/dspy/signatures/signature.py
index 8c1f16164..62626c8e1 100644
--- a/dspy/signatures/signature.py
+++ b/dspy/signatures/signature.py
@@ -1,9 +1,10 @@
import ast
from copy import deepcopy
-import typing
import dsp
from pydantic import BaseModel, Field, create_model
from pydantic.fields import FieldInfo
+import typing
+import types
from typing import Any, Type, Union, Dict, Tuple # noqa: UP035
import re
@@ -62,7 +63,7 @@ class SignatureMeta(type(BaseModel)):
field_type = extra.get("__dspy_field_type")
if field_type not in ["input", "output"]:
raise TypeError(
- f"Field '{name}' in '{cls.__name__}' must be declared with InputField or OutputField.",
+ f"Field '{name}' in '{cls.__name__}' must be declared with InputField or OutputField. {field.json_schema_extra=}",
)
@property
@@ -232,7 +233,8 @@ def make_signature(
# program of thought and teleprompters, so we just silently default to string.
if type_ is None:
type_ = str
- if not isinstance(type_, type) and not isinstance(typing.get_origin(type_), type):
+ # if not isinstance(type_, type) and not isinstance(typing.get_origin(type_), type):
+ if not isinstance(type_, (type, typing._GenericAlias, types.GenericAlias)):
raise ValueError(f"Field types must be types, not {type(type_)}")
if not isinstance(field, FieldInfo):
raise ValueError(f"Field values must be Field instances, not {type(field)}")
diff --git a/tests/functional/test_functional.py b/tests/functional/test_functional.py
index 600e35b63..ebca99223 100644
--- a/tests/functional/test_functional.py
+++ b/tests/functional/test_functional.py
@@ -2,7 +2,7 @@ import datetime
import textwrap
import pydantic
from pydantic import Field, BaseModel, field_validator
-from typing import Annotated
+from typing import Annotated, Literal
from typing import List
import pytest
@@ -495,6 +495,28 @@ def test_parse_type_string():
assert output == [0, 1, 2]
+def test_literal():
+ lm = DummyLM([f'{{"value": "{i}"}}' for i in range(100)])
+ dspy.settings.configure(lm=lm)
+
+ @predictor
+ def f() -> Literal["2", "3"]:
+ pass
+
+ assert f() == "2"
+
+
+def test_literal_int():
+ lm = DummyLM([f'{{"value": {i}}}' for i in range(100)])
+ dspy.settings.configure(lm=lm)
+
+ @predictor
+ def f() -> Literal[2, 3]:
+ pass
+
+ assert f() == 2
+
+
def test_fields_on_base_signature():
class SimpleOutput(dspy.Signature):
output: float = dspy.OutputField(gt=0, lt=1)