Skip to content

[feat(json_adapter): Enhance parsing for single-field outputs & Pydantic v1/v2 compat #8239

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 31 additions & 21 deletions dspy/adapters/json_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,9 @@
from pydantic.fields import FieldInfo

from dspy.adapters.chat_adapter import ChatAdapter, FieldInfoWithName
from dspy.adapters.utils import (
format_field_value,
get_annotation_name,
parse_value,
serialize_for_json,
translate_field_type,
)
from dspy.adapters.utils import (format_field_value, get_annotation_name,
parse_value, serialize_for_json,
translate_field_type)
from dspy.clients.lm import LM
from dspy.signatures.signature import Signature, SignatureMeta
from dspy.utils.exceptions import AdapterParseError
Expand Down Expand Up @@ -122,19 +118,22 @@ def format_assistant_message_content(
return self.format_field_with_value(fields_with_values, role="assistant")

def parse(self, signature: Type[Signature], completion: str) -> dict[str, Any]:
pattern = r"\{(?:[^{}]|(?R))*\}"
pattern = r"(\{(?:[^{}]|(?R))*\}|\[(?:[^\[\]]|(?R))*\])"
match = regex.search(pattern, completion, regex.DOTALL)
if match:
completion = match.group(0)
fields = json_repair.loads(completion)

if not isinstance(fields, dict):
raise AdapterParseError(
adapter_name="JSONAdapter",
signature=signature,
lm_response=completion,
message="LM response cannot be serialized to a JSON object.",
)
if isinstance(fields, list) and len(signature.output_fields) == 1:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this only applicable if the (single) output field has type list ?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or are you saying basically let's just rely on the validation below to check anyway?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think so, maybe it would be better to run the check on output fields directly instead of on the "fields" variable.

field_name = next(iter(signature.output_fields.keys()))
fields = {field_name: fields}
else:
raise AdapterParseError(
adapter_name="JSONAdapter",
signature=signature,
lm_response=completion,
message="LM response cannot be serialized to a JSON object.",
)

fields = {k: v for k, v in fields.items() if k in signature.output_fields}

Expand Down Expand Up @@ -206,12 +205,23 @@ def _get_structured_outputs_response_format(signature: SignatureMeta) -> type[py
default = field.default if hasattr(field, "default") else ...
fields[name] = (annotation, default)

# Build the model with extra fields forbidden.
pydantic_model = pydantic.create_model(
"DSPyProgramOutputs",
**fields,
__config__=type("Config", (), {"extra": "forbid"}),
)
# Build the model with extra fields forbidden. Pydantic v1 expects a Config
# class while v2 expects a ConfigDict, so we detect the version and pass the
# appropriate object.
if pydantic.version.VERSION.startswith("2"):
config = pydantic.ConfigDict(extra="forbid") # pragma: no cover - v2 only
pydantic_model = pydantic.create_model(
"DSPyProgramOutputs",
**fields,
__config__=config,
)
else:
config_cls = type("Config", (pydantic.BaseConfig,), {"extra": "forbid"})
pydantic_model = pydantic.create_model(
"DSPyProgramOutputs",
**fields,
__config__=config_cls,
)

# Generate the initial schema.
schema = pydantic_model.model_json_schema()
Expand Down