Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
fix/main-stuff-as-model-validate (#180)
Thomas Hebrarde52d88d81775
diff --git a/.cursor/rules/pipelex.mdc b/.cursor/rules/pipelex.mdcindex a91840521..92ce9fddb 100644--- a/.cursor/rules/pipelex.mdc+++ b/.cursor/rules/pipelex.mdc@@ -443,4 +443,12 @@ pretty_print(gantt_chart, title="Gantt Chart")get_pipeline_tracker().output_flowchart()```-ALWAYS RUN `pipelex validate` when you are finished writing pipelines: This checks for errors. If there are errors, iterate until it works.\ No newline at end of file+# Error Handling & Validation++## Validation Error Handling++- Use `StuffContentValidationError` for handling content validation failures+- Use `format_pydantic_validation_error` to format validation errors consistently++ALWAYS RUN `pipelex validate` when you are finished writing pipelines: This checks for errors. If there are errors, iterate until it works.+diff --git a/AGENTS.md b/AGENTS.mdindex b2f3ae1cd..50a542992 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -15,6 +15,11 @@ This python >=3.10 code is in the `pipelex` directory.- Add trailing commas to multi-line lists, dicts, function arguments, and tuples with >2 items (helps with cleaner diffs and prevents syntax errors when adding items)- All imports inside this repo's packages must be absolute package paths from the root+## Error Handling & Validation++- Use `format_pydantic_validation_error` for consistent error formatting when catching ValidationError+- Implement `StuffContentValidationError` for content validation failures+## Linting & checking- Run `make lint` -> it runs `ruff check . --fix` to enforce all our linting rulesdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3d4fb2aa0..bcf8725a7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,10 @@# Changelog+## [v0.6.3] - 2025-07-18++### Changed+- Enhanced `Stuff.content_as()` method with improved type validation logic - now attempts model validation when `isinstance` check fails+## [v0.6.2] - 2025-07-18### Addeddiff --git a/CLAUDE.md b/CLAUDE.mdindex 1e1309494..ed571e800 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -15,6 +15,12 @@ This python >=3.10 code is in the `pipelex` directory.- Add trailing commas to multi-line lists, dicts, function arguments, and tuples with >2 items (helps with cleaner diffs and prevents syntax errors when adding items)- All imports inside this repo's packages must be absolute package paths from the root+## Error Handling & Validation++- Use `StuffContentValidationError` for type validation failures+- Apply `format_pydantic_validation_error` for formatting validation errors consistently++## Test file structure- Name test files with `test_` prefixdiff --git a/pipelex/core/stuff.py b/pipelex/core/stuff.pyindex ef1350e2d..df6132fcc 100644--- a/pipelex/core/stuff.py+++ b/pipelex/core/stuff.py@@ -1,6 +1,6 @@from typing import Any, Dict, Optional, Type, Union-from pydantic import ConfigDict+from pydantic import ConfigDict, ValidationErrorfrom typing_extensions import overridefrom pipelex import log@@ -18,9 +18,9 @@ from pipelex.core.stuff_content import (TextAndImagesContent,TextContent,)-from pipelex.exceptions import StuffError+from pipelex.exceptions import StuffContentValidationError, StuffErrorfrom pipelex.tools.misc.string_utils import pascal_case_to_snake_case-from pipelex.tools.typing.pydantic_utils import CustomBaseModel+from pipelex.tools.typing.pydantic_utils import CustomBaseModel, format_pydantic_validation_errorclass Stuff(CustomBaseModel):@@ -106,9 +106,25 @@ class Stuff(CustomBaseModel):def content_as(self, content_type: Type[StuffContentType]) -> StuffContentType:"""Get content with proper typing if it's of the expected type."""- if not isinstance(self.content, content_type):- raise TypeError(f"Content is of type '{type(self.content)}', instead of the expected '{content_type}'")- return self.content+ # First try the direct isinstance check for performance+ if isinstance(self.content, content_type):+ return self.content++ # If isinstance failed, try model validation approach+ try:+ # Check if class names match (quick filter before attempting validation)+ if type(self.content).__name__ == content_type.__name__:+ content_dict = self.content.smart_dump()+ validated_content = content_type.model_validate(content_dict)+ log.debug(f"Model validation passed: converted {type(self.content).__name__} to {content_type.__name__}")+ return validated_content+ except ValidationError as exc:+ formatted_error = format_pydantic_validation_error(exc)+ raise StuffContentValidationError(+ original_type=type(self.content).__name__, target_type=content_type.__name__, validation_error=formatted_error+ ) from exc++ raise TypeError(f"Content is of type '{type(self.content)}', instead of the expected '{content_type}'")def as_list_content(self) -> ListContent: # pyright: ignore[reportMissingTypeArgument, reportUnknownParameterType]"""Get content as ListContent with items of any type."""diff --git a/pipelex/exceptions.py b/pipelex/exceptions.pyindex 986534b85..13bd1e339 100644--- a/pipelex/exceptions.py+++ b/pipelex/exceptions.py@@ -157,6 +157,16 @@ class StuffError(PipelexError):pass+class StuffContentValidationError(StuffError):+ """Raised when content validation fails during type conversion."""++ def __init__(self, original_type: str, target_type: str, validation_error: str):+ self.original_type = original_type+ self.target_type = target_type+ self.validation_error = validation_error+ super().__init__(f"Failed to validate content from {original_type} to {target_type}: {validation_error}")++class PipeExecutionError(PipelexError):pass