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.
Separate blueprint validation code
Louis Choquel6bd13cbf5b4e
diff --git a/pipelex/cli/commands/validate_cmd.py b/pipelex/cli/commands/validate_cmd.pyindex 6b4a2a528..50cadb08b 100644--- a/pipelex/cli/commands/validate_cmd.py+++ b/pipelex/cli/commands/validate_cmd.py@@ -1,20 +1,31 @@from __future__ import annotationsimport asyncio-from typing import Annotated+from pathlib import Path+from typing import Annotated, Any, Dict, Optional, castimport typer--from pipelex import log-from pipelex.create.build_blueprint import validate_blueprint as do_validate_blueprint-from pipelex.hub import get_pipeline_tracker-from pipelex.pipe_works.pipe_dry import dry_run_all_pipes, dry_run_single_pipe+from pydantic import ValidationError++from pipelex import log, pretty_print+from pipelex.cli.commands.common import is_pipelex_libraries_folder+from pipelex.create.helpers import get_support_file+from pipelex.create.pipeline_toml import save_pipeline_blueprint_toml_to_path+from pipelex.create.validate_blueprint import validate_blueprint+from pipelex.exceptions import PipeDefinitionError, PipelexCLIError+from pipelex.hub import get_library_manager, get_pipeline_tracker+from pipelex.libraries.library_manager import LibraryManager+from pipelex.libraries.pipeline_blueprint import PipelineBlueprint+from pipelex.pipe_works.pipe_dry import dry_run_all_pipes, dry_run_pipe_codes, dry_run_single_pipefrom pipelex.pipelex import Pipelex--from .common import is_pipelex_libraries_folder+from pipelex.pipeline.execute import execute_pipeline+from pipelex.tools.misc.file_utils import save_text_to_path+from pipelex.tools.misc.json_utils import save_as_json_to_path+from pipelex.tools.misc.toml_utils import load_toml_from_path+from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error-def do_validate(relative_config_folder_path: str = "./pipelex_libraries") -> None:+def do_validate_all_libraries_and_dry_run(relative_config_folder_path: str = "./pipelex_libraries") -> None:"""Validate libraries and dry-run all pipes."""if not is_pipelex_libraries_folder(relative_config_folder_path):typer.echo(f"❌ No pipelex libraries folder found at '{relative_config_folder_path}'")@@ -44,6 +55,32 @@ def do_dry_run_pipe(pipe_code: str, relative_config_folder_path: str = "./pipeleraise typer.Exit(1)+async def do_validate_blueprint_toml_file(blueprint_path: str) -> None:+ """Validate an already generated pipeline blueprint from a TOML file.++ Args:+ blueprint_path: Path to the blueprint TOML file to validate++ Raises:+ PipelexCLIError: If validation fails+ ValidationError: If the TOML structure doesn't match PipelineBlueprint+ """+ # Load the TOML file+ log.info(f"Loading blueprint from '{blueprint_path}'...")+ blueprint_dict = load_toml_from_path(path=blueprint_path)++ # Validate and create PipelineBlueprint model+ try:+ blueprint = PipelineBlueprint.model_validate(blueprint_dict)+ except ValidationError as exc:+ error_msg = format_pydantic_validation_error(exc=exc)+ raise PipelexCLIError(f"Invalid blueprint structure in '{blueprint_path}': {error_msg}") from exc++ log.info(f"Blueprint loaded successfully: domain='{blueprint.domain}'")++ await validate_blueprint(blueprint=blueprint)++# Typer group for validation commandsvalidate_app = typer.Typer(help="Validation and dry-run commands")@@ -54,7 +91,7 @@ def validate_all_cmd(str, typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path")] = "./pipelex_libraries",) -> None:- do_validate(relative_config_folder_path=relative_config_folder_path)+ do_validate_all_libraries_and_dry_run(relative_config_folder_path=relative_config_folder_path)@validate_app.command("pipe")@@ -88,5 +125,5 @@ def validate_blueprint_cmd(Pipelex.make(relative_config_folder_path=relative_config_folder_path, from_file=False)# Run validation- asyncio.run(do_validate_blueprint(blueprint_path=blueprint_path))+ asyncio.run(do_validate_blueprint_toml_file(blueprint_path=blueprint_path))log.info("Blueprint validation completed successfully.")diff --git a/pipelex/create/build_blueprint.py b/pipelex/create/build_blueprint.pyindex 6e8498e15..4e64d0a14 100644--- a/pipelex/create/build_blueprint.py+++ b/pipelex/create/build_blueprint.py@@ -1,25 +1,18 @@from __future__ import annotations-import asynciofrom pathlib import Path-from typing import Any, Dict, Optional, cast+from typing import Optionalimport typer-from pydantic import ValidationError-from pipelex import log, pretty_print+from pipelex import pretty_printfrom pipelex.create.helpers import get_support_filefrom pipelex.create.pipeline_toml import save_pipeline_blueprint_toml_to_path-from pipelex.exceptions import PipeDefinitionError, PipelexCLIError-from pipelex.hub import get_library_manager-from pipelex.libraries.library_manager import LibraryManager+from pipelex.create.validate_blueprint import validate_blueprintfrom pipelex.libraries.pipeline_blueprint import PipelineBlueprint-from pipelex.pipe_works.pipe_dry import dry_run_pipe_codesfrom pipelex.pipeline.execute import execute_pipelinefrom pipelex.tools.misc.file_utils import save_text_to_pathfrom pipelex.tools.misc.json_utils import save_as_json_to_path-from pipelex.tools.misc.toml_utils import load_toml_from_path-from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_errorasync def do_build_blueprint(@@ -56,95 +49,4 @@ async def do_build_blueprint(typer.echo(f"✅ Blueprint saved to '{output_path}'")if validate:- try:- _load_pipes_from_generated_blueprint(blueprint=blueprint)- except PipeDefinitionError as exc:- raise PipelexCLIError(f"Failed to load pipes from generated blueprint at '{output_path}': {exc}") from exc-- generated_pipe_codes = list(blueprint.pipe.keys())- if not generated_pipe_codes:- raise PipelexCLIError("No pipe found in generated blueprint to validate")- log.info(f"Loaded pipes: {generated_pipe_codes}")-- log.info("Validating pipes...")- asyncio.run(dry_run_pipe_codes(pipe_codes=generated_pipe_codes))- log.info(f"Pipes validated: {generated_pipe_codes}")---def _load_pipes_from_generated_blueprint(blueprint: PipelineBlueprint) -> None:- """Instantiate and register all pipes from a generated PipelineBlueprint.-- This constructs the appropriate typed PipeBlueprint for each pipe entry and- uses LibraryManager.load_pipe_from_blueprint to create the Pipe, then adds it- to the in-memory PipeLibrary so that validation can run against them.- """- library_manager = cast(LibraryManager, get_library_manager())- domain_code = blueprint.domain-- for pipe_code, details in blueprint.pipe.items():- details_dict: Dict[str, Any] = details.copy()-- # Build the concrete PipeBlueprint via LibraryManager helper- # try:- # pipe_blueprint = LibraryManager.make_pipe_blueprint_from_details(- # domain_code=domain_code,- # details_dict=details_dict,- # )- # except ValidationError as exc:- # error_msg = format_pydantic_validation_error(exc=exc)- # raise PipeDefinitionError(f"Failed to build pipe blueprint for pipe '{pipe_code}': {error_msg}\n{exc}") from exc-- pipe_blueprint = LibraryManager.make_pipe_blueprint_from_details(- domain_code=domain_code,- details_dict=details_dict,- )- # Create pipe and register in library- pipe = LibraryManager.load_pipe_from_blueprint(- pipe_code=pipe_code,- pipe_blueprint=pipe_blueprint,- )- library_manager.pipe_library.add_new_pipe(pipe=pipe)---async def validate_blueprint(blueprint_path: str) -> None:- """Validate an already generated pipeline blueprint from a TOML file.-- Args:- blueprint_path: Path to the blueprint TOML file to validate-- Raises:- PipelexCLIError: If validation fails- ValidationError: If the TOML structure doesn't match PipelineBlueprint- """- # Load the TOML file- log.info(f"Loading blueprint from '{blueprint_path}'...")- blueprint_dict = load_toml_from_path(path=blueprint_path)-- # Validate and create PipelineBlueprint model- try:- blueprint = PipelineBlueprint.model_validate(blueprint_dict)- except ValidationError as exc:- error_msg = format_pydantic_validation_error(exc=exc)- raise PipelexCLIError(f"Invalid blueprint structure in '{blueprint_path}': {error_msg}") from exc-- log.info(f"Blueprint loaded successfully: domain='{blueprint.domain}'")-- # Load pipes from the blueprint- try:- _load_pipes_from_generated_blueprint(blueprint=blueprint)- except PipeDefinitionError as exc:- raise PipelexCLIError(f"Failed to load pipes from blueprint at '{blueprint_path}': {exc}") from exc-- # Get pipe codes and validate them- generated_pipe_codes = list(blueprint.pipe.keys())- if not generated_pipe_codes:- raise PipelexCLIError("No pipe found in blueprint to validate")- log.info(f"Loaded pipes: {generated_pipe_codes}")-- # Run validation- log.info("Validating pipes ----------------------")- log.info("Validating libraries ----------------------")- get_library_manager().validate_libraries()- log.info("Dry running pipes...")- await dry_run_pipe_codes(pipe_codes=generated_pipe_codes)- log.info(f"✅ All pipes validated successfully: {generated_pipe_codes}")+ await validate_blueprint(blueprint=blueprint)diff --git a/pipelex/create/validate_blueprint.py b/pipelex/create/validate_blueprint.pynew file mode 100644index 000000000..d9247d51d--- /dev/null+++ b/pipelex/create/validate_blueprint.py@@ -0,0 +1,64 @@+from __future__ import annotations++from typing import Any, Dict, cast++from pipelex import log+from pipelex.exceptions import PipeDefinitionError, PipelexCLIError+from pipelex.hub import get_library_manager+from pipelex.libraries.library_manager import LibraryManager+from pipelex.libraries.pipeline_blueprint import PipelineBlueprint+from pipelex.pipe_works.pipe_dry import dry_run_pipe_codes+++async def validate_blueprint(blueprint: PipelineBlueprint) -> None:+ # Load pipes from the blueprint+ try:+ _load_pipes_from_generated_blueprint(blueprint=blueprint)+ except PipeDefinitionError as exc:+ raise PipelexCLIError(f"Failed to load pipes from blueprint for domain '{blueprint.desc}': {exc}") from exc++ # Run validation+ log.info("Validating pipes ----------------------")+ log.info("Validating libraries ----------------------")+ get_library_manager().validate_libraries()+ generated_pipe_codes = list(blueprint.pipe.keys())+ if not generated_pipe_codes:+ raise PipelexCLIError("No pipe found in blueprint to validate")+ log.info(f"Dry running pipes: {generated_pipe_codes}")+ await dry_run_pipe_codes(pipe_codes=generated_pipe_codes)+ log.info(f"✅ All pipes validated successfully: {generated_pipe_codes}")+++def _load_pipes_from_generated_blueprint(blueprint: PipelineBlueprint) -> None:+ """Instantiate and register all pipes from a generated PipelineBlueprint.++ This constructs the appropriate typed PipeBlueprint for each pipe entry and+ uses LibraryManager.load_pipe_from_blueprint to create the Pipe, then adds it+ to the in-memory PipeLibrary so that validation can run against them.+ """+ library_manager = cast(LibraryManager, get_library_manager())+ domain_code = blueprint.domain++ for pipe_code, details in blueprint.pipe.items():+ details_dict: Dict[str, Any] = details.copy()++ # Build the concrete PipeBlueprint via LibraryManager helper+ # try:+ # pipe_blueprint = LibraryManager.make_pipe_blueprint_from_details(+ # domain_code=domain_code,+ # details_dict=details_dict,+ # )+ # except ValidationError as exc:+ # error_msg = format_pydantic_validation_error(exc=exc)+ # raise PipeDefinitionError(f"Failed to build pipe blueprint for pipe '{pipe_code}': {error_msg}\n{exc}") from exc++ pipe_blueprint = LibraryManager.make_pipe_blueprint_from_details(+ domain_code=domain_code,+ details_dict=details_dict,+ )+ # Create pipe and register in library+ pipe = LibraryManager.load_pipe_from_blueprint(+ pipe_code=pipe_code,+ pipe_blueprint=pipe_blueprint,+ )+ library_manager.pipe_library.add_new_pipe(pipe=pipe)diff --git a/pipelex/libraries/pipeline_blueprint.py b/pipelex/libraries/pipeline_blueprint.pyindex 54ebb0331..9d485045c 100644--- a/pipelex/libraries/pipeline_blueprint.py+++ b/pipelex/libraries/pipeline_blueprint.py@@ -49,3 +49,10 @@ class PipelineBlueprint(StructuredContent):# Pipes section - pipe_name -> blueprint dictpipe: Dict[str, Dict[str, Any]] = Field(default_factory=dict)++ @property+ def desc(self) -> str:+ if self.definition:+ return f"{self.domain} • {self.definition[:100]}"+ else:+ return self.domain