Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

feat(dspy): update mechanism by which paser is applied

JONEMI197e875950b99c
diff --git a/dspy/functional/functional.py b/dspy/functional/functional.py
index 036ddc2ad..7e2997edb 100644
--- a/dspy/functional/functional.py
+++ b/dspy/functional/functional.py
@@ -1,6 +1,7 @@
import inspect
import json
import typing
+from contextlib import suppress
from typing import Annotated, Callable, List, Tuple, Union # noqa: UP035
import pydantic
@@ -405,17 +406,16 @@ def _func_to_signature(func):
return dspy.Signature(fields, instructions)
-def _unwrap_json(output, native_parser: Callable[[str], Union[dict, pydantic.BaseModel]]):
- try:
- return native_parser(output)
- except (ValueError, pydantic.ValidationError):
- output = output.strip()
- if output.startswith("```"):
- if not output.startswith("```json"):
- raise ValueError("json output should start with ```json") from None
- if not output.endswith("```"):
- raise ValueError("Don't write anything after the final json ```") from None
- output = output[7:-3].strip()
- if not output.startswith("{") or not output.endswith("}"):
- raise ValueError("json output should start and end with { and }") from None
- return ujson.dumps(ujson.loads(output)) # ujson is a bit more robust than the standard json
+def _unwrap_json(output, from_json: Callable[[str], Union[pydantic.BaseModel, str]]):
+ with suppress(ValueError, pydantic.ValidationError, AttributeError):
+ output = from_json(output).model_dump_json()
+ output = output.strip()
+ if output.startswith("```"):
+ if not output.startswith("```json"):
+ raise ValueError("json output should start with ```json") from None
+ if not output.endswith("```"):
+ raise ValueError("Don't write anything after the final json ```") from None
+ output = output[7:-3].strip()
+ if not output.startswith("{") or not output.endswith("}"):
+ raise ValueError("json output should start and end with { and }") from None
+ return ujson.dumps(ujson.loads(output)) # ujson is a bit more robust than the standard json