Skip to content
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

Support Pydantic Validators when using .parsed #289

Open
philschmid opened this issue Feb 10, 2025 · 1 comment
Open

Support Pydantic Validators when using .parsed #289

philschmid opened this issue Feb 10, 2025 · 1 comment
Assignees
Labels
priority: p3 Desirable enhancement or fix. May not be included in next release. type: feature request ‘Nice-to-have’ improvement, new feature or different behavior or design.

Comments

@philschmid
Copy link

Currently, when using the .parsed property to access parsed JSON responses, Pydantic validator functions (and by extension, @field_validator and @model_validator decorators) are not executed. Errors like pydantic.ValidationError and json.decoder.JSONDecodeError are silently caught, and the .parsed attribute returns an empty or null value, rather than raising the expected validation error. This makes it difficult to leverage Pydantic's validation capabilities when working with streaming or potentially malformed responses.

Expected Behavior:

When .parsed is accessed, and the underlying response data causes a pydantic.ValidationError (because a validator fails), the exception should be raised, just as it would be if constructing the Pydantic model directly with valid data. The same exception handling applies to JSONDecodeError.

Example (Illustrative):

from pydantic import BaseModel, field_validator
import httpx #or whichever http request lib

class MyModel(BaseModel):
    value: int

    @field_validator("value")
    @classmethod
    def check_positive(cls, v):
        if v <= 0:
            raise ValueError("Value must be positive")
        return v

# Assume 'response' is from a hypothetical API wrapper
# response = ... #  response.text = '{"value": -1}'

# Currently:
# print(response.parsed)  # Might return None or an empty object, silently failing

# Expected (with this feature request):
# try:
#     print(response.parsed)
# except pydantic.ValidationError as e:
#     print(f"Validation failed: {e}")  #  This should be triggered
     # and a valid error message should be produced.

Benefits:

  • Improved developer experience and reduced debugging time.
  • More reliable and robust applications.
  • Full utilization of Pydantic's validation features.
@philschmid philschmid added priority: p3 Desirable enhancement or fix. May not be included in next release. type: feature request ‘Nice-to-have’ improvement, new feature or different behavior or design. labels Feb 10, 2025
@sararob sararob self-assigned this Feb 10, 2025
@pedrurrego
Copy link

wow, this would be really helpful! I am getting the following error, apparently because of parsed: Union[pydantic.BaseModel, dict, Enum], but having a default None value.

    | engine_response.google.content.parsed.BaseModel
    |   Input should be a valid dictionary or instance of BaseModel [type=model_type, input_value=None, input_type=NoneType]
    |     For further information visit https://errors.pydantic.dev/2.10/v/model_type
    | engine_response.google.content.parsed.dict[any,any]
    |   Input should be a valid dictionary [type=dict_type, input_value=None, input_type=NoneType]
    |     For further information visit https://errors.pydantic.dev/2.10/v/dict_type
    | engine_response.google.content.parsed.is-instance[Enum]
    |   Input should be an instance of Enum [type=is_instance_of, input_value=None, input_type=NoneType]
    |     For further information visit https://errors.pydantic.dev/2.10/v/is_instance_of

thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
priority: p3 Desirable enhancement or fix. May not be included in next release. type: feature request ‘Nice-to-have’ improvement, new feature or different behavior or design.
Projects
None yet
Development

No branches or pull requests

3 participants