Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Improve Adapters (parse_value) and fix bugs & typos (#7817)

Omar Khattab1be3594dac33
diff --git a/dspy/adapters/chat_adapter.py b/dspy/adapters/chat_adapter.py
index e35461dbc..1f4543fcd 100644
--- a/dspy/adapters/chat_adapter.py
+++ b/dspy/adapters/chat_adapter.py
@@ -1,4 +1,3 @@
-import ast
import enum
import inspect
import json
@@ -10,11 +9,10 @@ from itertools import chain
from typing import Any, Dict, Literal, NamedTuple
import pydantic
-from pydantic import TypeAdapter
from pydantic.fields import FieldInfo
from dspy.adapters.base import Adapter
-from dspy.adapters.utils import find_enum_member, format_field_value, get_annotation_name
+from dspy.adapters.utils import parse_value, format_field_value, get_annotation_name
from dspy.signatures.field import OutputField
from dspy.signatures.signature import Signature, SignatureMeta
from dspy.signatures.utils import get_dspy_field_type
@@ -135,26 +133,6 @@ def format_fields(fields_with_values: Dict[FieldInfoWithName, Any]) -> str:
return "\n\n".join(output).strip()
-def parse_value(value, annotation):
- if annotation is str:
- return str(value)
-
- parsed_value = value
-
- if isinstance(annotation, enum.EnumMeta):
- return find_enum_member(annotation, value)
- elif isinstance(value, str):
- try:
- parsed_value = json.loads(value)
- except json.JSONDecodeError:
- try:
- parsed_value = ast.literal_eval(value)
- except (ValueError, SyntaxError):
- parsed_value = value
-
- return TypeAdapter(annotation).validate_python(parsed_value)
-
-
def format_turn(signature, values, role, incomplete=False):
"""
Constructs a new message ("turn") to append to a chat thread. The message is carefully formatted
@@ -259,7 +237,8 @@ def prepare_instructions(signature: SignatureMeta):
f"must exactly match (no extra characters) one of: {'; '.join([str(x) for x in field_type.__args__])}"
)
else:
- desc = "must be pareseable according to the following JSON schema: "
+ # desc = "must be pareseable according to the following JSON schema: "
+ desc = "must adhere to the JSON schema: "
desc += json.dumps(prepare_schema(field_type), ensure_ascii=False)
desc = (" " * 8) + f"# note: the value you produce {desc}" if desc else ""
diff --git a/dspy/adapters/json_adapter.py b/dspy/adapters/json_adapter.py
index eda982eae..c318ab59e 100644
--- a/dspy/adapters/json_adapter.py
+++ b/dspy/adapters/json_adapter.py
@@ -1,4 +1,3 @@
-import ast
import enum
import inspect
import json
@@ -10,12 +9,12 @@ from typing import Any, Dict, KeysView, Literal, NamedTuple
import json_repair
import litellm
import pydantic
-from pydantic import TypeAdapter, create_model
+from pydantic import create_model
from pydantic.fields import FieldInfo
from dspy.adapters.base import Adapter
from dspy.adapters.image_utils import Image
-from dspy.adapters.utils import find_enum_member, format_field_value, get_annotation_name, serialize_for_json
+from dspy.adapters.utils import parse_value, format_field_value, get_annotation_name, serialize_for_json
from dspy.signatures.signature import SignatureMeta
from dspy.signatures.utils import get_dspy_field_type
@@ -119,26 +118,6 @@ class JSONAdapter(Adapter):
return format_fields(role=role, fields_with_values=fields_with_values)
-def parse_value(value, annotation):
- if annotation is str:
- return str(value)
-
- parsed_value = value
-
- if isinstance(annotation, enum.EnumMeta):
- parsed_value = find_enum_member(annotation, value)
- elif isinstance(value, str):
- try:
- parsed_value = json_repair.loads(value)
- except json.JSONDecodeError:
- try:
- parsed_value = ast.literal_eval(value)
- except (ValueError, SyntaxError):
- parsed_value = value
-
- return TypeAdapter(annotation).validate_python(parsed_value)
-
-
def _format_field_value(field_info: FieldInfo, value: Any) -> str:
"""
Formats the value of the specified field according to the field's DSPy type (input or output),
@@ -274,7 +253,7 @@ def prepare_instructions(signature: SignatureMeta):
elif hasattr(type_, "__origin__") and type_.__origin__ is Literal:
desc = f"must be one of: {'; '.join([str(x) for x in type_.__args__])}"
else:
- desc = "must be pareseable according to the following JSON schema: "
+ desc = "must adhere to the JSON schema: "
desc += json.dumps(pydantic.TypeAdapter(type_).json_schema())
desc = (" " * 8) + f"# note: the value you produce {desc}" if desc else ""
diff --git a/dspy/adapters/utils.py b/dspy/adapters/utils.py
index a2438a94c..199fc1056 100644
--- a/dspy/adapters/utils.py
+++ b/dspy/adapters/utils.py
@@ -1,9 +1,11 @@
+import ast
+import enum
import json
-from typing import Any, List, Literal, Union, get_args, get_origin
+import json_repair
from pydantic import TypeAdapter
from pydantic.fields import FieldInfo
-
+from typing import Any, List, Literal, Union, get_args, get_origin
def serialize_for_json(value: Any) -> Any:
@@ -84,6 +86,27 @@ def find_enum_member(enum, identifier):
raise ValueError(f"{identifier} is not a valid name or value for the enum {enum.__name__}")
+
+def parse_value(value, annotation):
+ if annotation is str:
+ return str(value)
+
+ if isinstance(annotation, enum.EnumMeta):
+ return find_enum_member(annotation, value)
+
+ if not isinstance(value, str):
+ return TypeAdapter(annotation).validate_python(value)
+
+ candidate = json_repair.loads(value) # json_repair.loads returns "" on failure.
+ if candidate == "" and value != "":
+ try:
+ candidate = ast.literal_eval(value)
+ except (ValueError, SyntaxError):
+ candidate = value
+
+ return TypeAdapter(annotation).validate_python(candidate)
+
+
def get_annotation_name(annotation):
origin = get_origin(annotation)
args = get_args(annotation)
diff --git a/dspy/evaluate/metrics.py b/dspy/evaluate/metrics.py
index 4cce6adfd..c67dbf82d 100644
--- a/dspy/evaluate/metrics.py
+++ b/dspy/evaluate/metrics.py
@@ -3,14 +3,20 @@
def _passage_match(passages: list[str], answers: list[str]) -> bool:
"""Returns True if any of the passages contains the answer."""
+ from dspy.dsp.utils import DPR_normalize, has_answer, normalize_text
+
+ def passage_has_answers(passage: str, answers: list[str]) -> bool:
+ """Returns True if the passage contains the answer."""
+ return has_answer(
+ tokenized_answers=[DPR_normalize(normalize_text(ans)) for ans in answers],
+ text=normalize_text(passage),
+ )
- from dspy.dsp.utils import passage_has_answers
return any(passage_has_answers(psg, answers) for psg in passages)
def _answer_match(prediction, answers, frac=1.0):
"""Returns True if the prediction matches any of the answers."""
-
from dspy.dsp.utils import EM, F1
if frac >= 1.0: