fix: migrate Pydantic v1 validators to Pydantic v2 style (#929)#1783
fix: migrate Pydantic v1 validators to Pydantic v2 style (#929)#1783frankentini wants to merge 1 commit intoNVIDIA-NeMo:developfrom
Conversation
Replace deprecated @root_validator and @validator decorators with the Pydantic v2 equivalents to eliminate PydanticDeprecatedSince20 warnings and prepare for Pydantic v3 compatibility. Changes: - nemoguardrails/eval/models.py: replace root_validator(pre=True) with model_validator(mode='before') and root_validator(pre=False) with model_validator(mode='after'); update validate_policy_ids to use self instead of values dict - nemoguardrails/rails/llm/options.py: replace root_validator with model_validator(mode='before') in GenerationOptions.check_fields - nemoguardrails/rails/llm/config.py: replace all root_validator usages with model_validator(mode='before'); replace @validator('models') with @field_validator('models'); remove root_validator and validator from pydantic imports; add field_validator import Note: nemoguardrails/llm/providers/trtllm/llm.py intentionally uses pydantic.v1 for LangChain compatibility and is left unchanged. Closes NVIDIA-NeMo#929
Greptile SummaryThis PR correctly migrates all
|
| Filename | Overview |
|---|---|
| nemoguardrails/eval/models.py | Correctly migrates root_validator to model_validator(mode='before'/'after') and adds @classmethod; two deprecated cls.parse_obj() calls at lines 163 and 326 are left over and still emit PydanticDeprecatedSince20 warnings. |
| nemoguardrails/rails/llm/config.py | All six @root_validator validators correctly migrated to @model_validator(mode='before') @classmethod; @validator('models') correctly migrated to @field_validator('models') @classmethod; old imports removed. |
| nemoguardrails/rails/llm/options.py | @root_validator(pre=True, allow_reuse=True) correctly migrated to @model_validator(mode='before') @classmethod; import updated; no issues found. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Raw input dict] --> B{model_validator mode=before}
B --> |"InteractionSet.instantiate_expected_output\nTaskPrompt.check_fields\nRailsConfig.check_*\nGenerationOptions.check_fields"| C[Transform / validate raw values]
C --> D[Pydantic field-level validation]
D --> E{Validation errors?}
E -- Yes --> F[ValidationError raised\nmode=after skipped]
E -- No --> G{field_validator}
G --> |"RailsConfig.validate_models_api_key_env_var"| H[Validate specific field]
H --> I{model_validator mode=after}
I --> |"EvalConfig.validate_policy_ids\nself = model instance"| J[Cross-field validation]
J --> K[Return self / ValidationError]
Comments Outside Diff (2)
-
nemoguardrails/eval/models.py, line 163 (link)Deprecated
parse_objnot replacedThe PR's goal is to eliminate
PydanticDeprecatedSince20warnings, but twocls.parse_obj()calls in this file remain — lines 163 and 326.parse_objis deprecated in Pydantic v2 and produces the same class of warning the PR targets; the replacement iscls.model_validate().Prompt To Fix With AI
This is a comment left during a code review. Path: nemoguardrails/eval/models.py Line: 163 Comment: **Deprecated `parse_obj` not replaced** The PR's goal is to eliminate `PydanticDeprecatedSince20` warnings, but two `cls.parse_obj()` calls in this file remain — lines 163 and 326. `parse_obj` is deprecated in Pydantic v2 and produces the same class of warning the PR targets; the replacement is `cls.model_validate()`. How can I resolve this? If you propose a fix, please make it concise.
-
nemoguardrails/eval/models.py, line 326 (link)Deprecated
parse_objnot replaced (second occurrence)Same issue as line 163 —
cls.parse_obj()is a Pydantic v1 deprecated API and will still emitPydanticDeprecatedSince20warnings.Prompt To Fix With AI
This is a comment left during a code review. Path: nemoguardrails/eval/models.py Line: 326 Comment: **Deprecated `parse_obj` not replaced (second occurrence)** Same issue as line 163 — `cls.parse_obj()` is a Pydantic v1 deprecated API and will still emit `PydanticDeprecatedSince20` warnings. How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: nemoguardrails/eval/models.py
Line: 163
Comment:
**Deprecated `parse_obj` not replaced**
The PR's goal is to eliminate `PydanticDeprecatedSince20` warnings, but two `cls.parse_obj()` calls in this file remain — lines 163 and 326. `parse_obj` is deprecated in Pydantic v2 and produces the same class of warning the PR targets; the replacement is `cls.model_validate()`.
```suggestion
return cls.model_validate(config_obj)
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: nemoguardrails/eval/models.py
Line: 326
Comment:
**Deprecated `parse_obj` not replaced (second occurrence)**
Same issue as line 163 — `cls.parse_obj()` is a Pydantic v1 deprecated API and will still emit `PydanticDeprecatedSince20` warnings.
```suggestion
return cls.model_validate(output_obj)
```
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "fix: migrate Pydantic v1 validators to P..." | Re-trigger Greptile
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThe pull request migrates deprecated Pydantic v1-style validators to Pydantic v2-style across three core files. Instances of Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~15 minutes 🚥 Pre-merge checks | ✅ 5 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Summary
Fixes #929.
Replaces all deprecated Pydantic v1
@root_validatorand@validatordecorators with their Pydantic v2 equivalents (@model_validator/@field_validator) across three core modules. This eliminates thePydanticDeprecatedSince20warnings users see when running with Pydantic ≥ 2.0 and ensures forward compatibility with Pydantic v3.Changes
nemoguardrails/eval/models.py@root_validator(pre=True)→@model_validator(mode='before')onInteractionSet.instantiate_expected_output@root_validator(pre=False, skip_on_failure=True)→@model_validator(mode='after')onEvalConfig.validate_policy_ids; updated method signature to takeselfand returnselfper Pydantic v2 conventionroot_validator→model_validatornemoguardrails/rails/llm/options.py@root_validator(pre=True, allow_reuse=True)→@model_validator(mode='before')onGenerationOptions.check_fieldsroot_validator→model_validatornemoguardrails/rails/llm/config.py@root_validatorusages to@model_validator(mode='before'):TaskPrompt.check_fieldsRailsConfig.check_model_exists_for_input_railsRailsConfig.check_model_exists_for_output_railsRailsConfig.check_prompt_exist_for_self_check_railsRailsConfig.check_output_parser_existsRailsConfig.check_jailbreak_detection_configRailsConfig.fill_in_default_values_for_v2_x@validator('models')→@field_validator('models')onRailsConfig.validate_models_api_key_env_varroot_validatorandvalidatorfrom pydantic imports; addedfield_validatorNotes
nemoguardrails/llm/providers/trtllm/llm.pyusespydantic.v1explicitly for LangChain compatibility and is intentionally left unchanged.Summary by CodeRabbit