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.
PipeSignature's pipe_category is a AllowedPipeCategories (#373)
Louis Choquel4048f935b6ce
diff --git a/.vscode/launch.json b/.vscode/launch.jsonindex a9da599ad..5b57e620c 100644--- a/.vscode/launch.json+++ b/.vscode/launch.json@@ -16,7 +16,7 @@"justMyCode": false},{- "name": "Debug test boot without inference",+ "name": "Debug test without inference","type": "debugpy","request": "launch","module": "pytest",diff --git a/pipelex/builder/flow.py b/pipelex/builder/flow.pyindex ee5b67dfe..688217492 100644--- a/pipelex/builder/flow.py+++ b/pipelex/builder/flow.py@@ -1,15 +1,31 @@-from pydantic import ConfigDict, Field+from pydantic import ConfigDict, Field, model_validatorfrom pipelex.builder.pipe.pipe_signature import PipeSignaturefrom pipelex.core.stuffs.structured_content import StructuredContent+from pipelex.exceptions import PipelexExceptionfrom pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprintfrom pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprintfrom pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprintfrom pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint+from pipelex.tools.typing.validation_utils import has_exactly_one_among_attributes_from_list+from pipelex.types import Self-# Union of possible pipe representations in flow view-# Controllers keep their full blueprint, operators are converted to signatures-FlowElementUnion = PipeSignature | PipeBatchBlueprint | PipeConditionBlueprint | PipeParallelBlueprint | PipeSequenceBlueprint++class FlowElementError(PipelexException):+ """Exception raised by FlowElement."""+++# FlowElement as all possible pipe representations in a flow+class FlowElement(StructuredContent):+ operator_signature: PipeSignature | None = None+ controller_blueprint: PipeBatchBlueprint | PipeConditionBlueprint | PipeParallelBlueprint | PipeSequenceBlueprint | None = None++ @model_validator(mode="after")+ def validate_flow_element(self) -> Self:+ if not has_exactly_one_among_attributes_from_list(self, attributes_list=["operator_signature", "controller_blueprint"]):+ msg = "FlowElement must have exactly one of operator_signature or controller_blueprint"+ raise FlowElementError(msg)+ return selfclass Flow(StructuredContent):@@ -35,4 +51,4 @@ class Flow(StructuredContent):domain: strdescription: str | None = None- flow_elements: dict[str, FlowElementUnion] = Field(default_factory=dict)+ flow_elements: dict[str, FlowElement] = Field(default_factory=dict)diff --git a/pipelex/builder/flow_factory.py b/pipelex/builder/flow_factory.pyindex 32752c54e..5625dfb73 100644--- a/pipelex/builder/flow_factory.py+++ b/pipelex/builder/flow_factory.py@@ -1,18 +1,24 @@from pathlib import Pathfrom typing import Any+from pipelex import logfrom pipelex.builder.builder import PipelexBundleSpec-from pipelex.builder.flow import Flow, FlowElementUnion+from pipelex.builder.flow import Flow, FlowElementfrom pipelex.builder.pipe.pipe_signature import PipeSignaturefrom pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprintfrom pipelex.core.interpreter import PipelexInterpreterfrom pipelex.core.pipes.pipe_blueprint import AllowedPipeCategories+from pipelex.exceptions import PipelexExceptionfrom pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprintfrom pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprintfrom pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprintfrom pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint+class FlowFactoryError(PipelexException):+ """Exception raised by FlowFactory."""++class FlowFactory:"""Factory for creating Flow from PipelexBundleSpec or PLX files.@@ -44,7 +50,7 @@ class FlowFactory:Returns:Flow with controllers preserved and operators as signatures."""- flow_elements: dict[str, FlowElementUnion] = {}+ flow_elements: dict[str, FlowElement] = {}if bundle_blueprint.pipe:for pipe_code, pipe_blueprint in bundle_blueprint.pipe.items():@@ -55,11 +61,21 @@ class FlowFactory:pipe_blueprint,PipeBatchBlueprint | PipeConditionBlueprint | PipeParallelBlueprint | PipeSequenceBlueprint,): # pyright: ignore[reportUnnecessaryIsInstance]- flow_elements[pipe_code] = pipe_blueprint+ flow_elements[pipe_code] = FlowElement(controller_blueprint=pipe_blueprint)+ log.debug(+ f"Adding controller {pipe_code} to flow: category is '{pipe_blueprint.pipe_category}' and type is '{pipe_blueprint.type}'"+ )+ else:+ msg = f"Pipe {pipe_code} is not a controller"+ raise FlowFactoryError(message=msg)else:# Convert operators to signatures- flow_elements[pipe_code] = FlowFactory._convert_blueprint_to_signature(pipe_code, pipe_blueprint)-+ signature_from_blueprint = FlowFactory._convert_blueprint_to_signature(pipe_code=pipe_code, pipe_blueprint=pipe_blueprint)+ flow_elements[pipe_code] = FlowElement(operator_signature=signature_from_blueprint)+ log.debug(+ f"Adding operator {pipe_code} to flow: category is '{pipe_blueprint.pipe_category}' and type is '{pipe_blueprint.type}'"+ )+ log.debug(signature_from_blueprint, title="Signature from blueprint")return Flow(domain=bundle_blueprint.domain,description=bundle_blueprint.description,@@ -77,21 +93,12 @@ class FlowFactory:Returns:PipeSignature containing the contract information."""- # Extract inputs as strings from InputRequirementBlueprint- inputs: dict[str, str] = {}- if pipe_blueprint.inputs:- for input_name, input_requirement in pipe_blueprint.inputs.items():- if hasattr(input_requirement, "concept"):- inputs[input_name] = input_requirement.concept- else:- inputs[input_name] = str(input_requirement)-return PipeSignature(code=pipe_code,- pipe_category="PipeSignature",+ pipe_category=pipe_blueprint.pipe_category,type=pipe_blueprint.type,description=pipe_blueprint.description or "",- inputs=inputs,+ inputs=pipe_blueprint.inputs,result=pipe_code,output=pipe_blueprint.output,pipe_dependencies=[],diff --git a/pipelex/builder/pipe/pipe_signature.py b/pipelex/builder/pipe/pipe_signature.pyindex 50c13d88c..7a19bccbf 100644--- a/pipelex/builder/pipe/pipe_signature.py+++ b/pipelex/builder/pipe/pipe_signature.py@@ -1,6 +1,7 @@-from typing import Any, Literal+from typing import Any-from pydantic import Field, field_validator+from pydantic import Field, field_validator, model_validator+from pydantic.json_schema import SkipJsonSchemafrom pipelex import logfrom pipelex.builder.concept.concept_spec import ConceptSpec@@ -19,7 +20,7 @@ class PipeSignature(StructuredContent):code: str = Field(description="Pipe code identifying the pipe. Must be snake_case.")type: AllowedPipeTypes = Field(description="Pipe type.")- pipe_category: Literal["PipeSignature"] = "PipeSignature"+ pipe_category: SkipJsonSchema[AllowedPipeCategories] = Field(description="Pipe category set according to its type.")description: str = Field(description="What the pipe does")inputs: dict[str, str] = Field(description="Pipe inputs: keys are the input variable_names in snake_case, values are the ConceptCodes in PascalCase."@@ -30,6 +31,19 @@ class PipeSignature(StructuredContent):output: str = Field(description="Just the output ConceptCode in PascalCase")pipe_dependencies: list[str] = Field(description="List of pipe codes that this pipe depends on. This is for the PipeControllers")+ @model_validator(mode="before")+ @classmethod+ def set_pipe_category(cls, values: dict[str, Any]) -> dict[str, Any]:+ try:+ type_str = values["type"]+ except TypeError as exc:+ msg = f"Invalid type for '{values}': could not get subscript, required for 'type'"+ raise PipeBlueprintError(msg) from exc+ # we need to convert the type string to the AllowedPipeTypes enum because it arrives as a str implictly converted to enum but not yet+ the_type = AllowedPipeTypes(type_str)+ values["pipe_category"] = the_type.category+ return values+class PipeSpec(StructuredContent):"""Spec defining a pipe: an executable component with a clear contract defined by its inputs and output.diff --git a/pipelex/core/pipes/pipe_blueprint.py b/pipelex/core/pipes/pipe_blueprint.pyindex 2e803dafb..68652ec6c 100644--- a/pipelex/core/pipes/pipe_blueprint.py+++ b/pipelex/core/pipes/pipe_blueprint.py@@ -40,7 +40,7 @@ class AllowedPipeTypes(StrEnum):PIPE_IMG_GEN = "PipeImgGen"PIPE_COMPOSE = "PipeCompose"PIPE_LLM = "PipeLLM"- PIPE_OCR = "PipeExtract"+ PIPE_EXTRACT = "PipeExtract"# Pipe ControllerPIPE_BATCH = "PipeBatch"PIPE_CONDITION = "PipeCondition"@@ -51,6 +51,28 @@ class AllowedPipeTypes(StrEnum):def value_list(cls) -> list[str]:return list(cls)+ @property+ def category(self) -> AllowedPipeCategories:+ match self:+ case AllowedPipeTypes.PIPE_FUNC:+ return AllowedPipeCategories.PIPE_OPERATOR+ case AllowedPipeTypes.PIPE_IMG_GEN:+ return AllowedPipeCategories.PIPE_OPERATOR+ case AllowedPipeTypes.PIPE_COMPOSE:+ return AllowedPipeCategories.PIPE_OPERATOR+ case AllowedPipeTypes.PIPE_LLM:+ return AllowedPipeCategories.PIPE_OPERATOR+ case AllowedPipeTypes.PIPE_EXTRACT:+ return AllowedPipeCategories.PIPE_OPERATOR+ case AllowedPipeTypes.PIPE_BATCH:+ return AllowedPipeCategories.PIPE_CONTROLLER+ case AllowedPipeTypes.PIPE_CONDITION:+ return AllowedPipeCategories.PIPE_CONTROLLER+ case AllowedPipeTypes.PIPE_PARALLEL:+ return AllowedPipeCategories.PIPE_CONTROLLER+ case AllowedPipeTypes.PIPE_SEQUENCE:+ return AllowedPipeCategories.PIPE_CONTROLLER+class PipeBlueprint(BaseModel):model_config = ConfigDict(extra="forbid")diff --git a/tests/integration/pipelex/pipes/test_flow_factory.py b/tests/integration/pipelex/pipes/test_flow_factory.pyindex 3710bd27e..81e6b5449 100644--- a/tests/integration/pipelex/pipes/test_flow_factory.py+++ b/tests/integration/pipelex/pipes/test_flow_factory.py@@ -5,6 +5,8 @@ import pytestfrom pipelex import log, pretty_printfrom pipelex.builder.flow_factory import FlowFactory+from pipelex.builder.pipe.pipe_signature import PipeSignature+from pipelex.core.pipes.pipe_blueprint import AllowedPipeTypesfrom pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprintfrom pipelex.tools.misc.file_utils import get_incremental_directory_path, remove_folderfrom pipelex.tools.misc.json_utils import save_as_json_to_path@@ -70,8 +72,8 @@ class TestFlowFactory:assert len(flow.flow_elements) > 0# Log some details about what we found- controller_count = sum(1 for pipe in flow.flow_elements.values() if pipe.pipe_category == "PipeController")- operator_count = sum(1 for pipe in flow.flow_elements.values() if pipe.pipe_category == "PipeSignature")+ controller_count = sum(1 for element in flow.flow_elements.values() if element.controller_blueprint is not None)+ operator_count = sum(1 for element in flow.flow_elements.values() if element.operator_signature is not None)log.info(f"flow contains {len(flow.flow_elements)} pipes: {controller_count} controllers, {operator_count} operators (as signatures)")@@ -87,18 +89,19 @@ class TestFlowFactory:flow = FlowFactory.make_from_plx_file(plx_file_path)# Find the sequence pipe- sequence_pipe = flow.flow_elements.get("write_discord_newsletter")- assert sequence_pipe is not None- assert sequence_pipe.type == "PipeSequence"+ sequence_element = flow.flow_elements.get("write_discord_newsletter")+ assert sequence_element is not None+ assert sequence_element.controller_blueprint is not None+ assert sequence_element.controller_blueprint.type == "PipeSequence"# Type narrow to PipeSequenceBlueprint for type safety- assert isinstance(sequence_pipe, PipeSequenceBlueprint)+ assert isinstance(sequence_element.controller_blueprint, PipeSequenceBlueprint)# Verify steps are preserved- assert len(sequence_pipe.steps) > 0+ assert len(sequence_element.controller_blueprint.steps) > 0- log.info(f"Sequence pipe has {len(sequence_pipe.steps)} steps:")- for step in sequence_pipe.steps:+ log.info(f"Sequence pipe has {len(sequence_element.controller_blueprint.steps)} steps:")+ for step in sequence_element.controller_blueprint.steps:log.info(f" - {step.pipe} -> {step.result}")async def test_flow_converts_operators_to_signatures(self):@@ -109,20 +112,21 @@ class TestFlowFactory:flow = FlowFactory.make_from_plx_file(plx_file_path)# Find an operator pipe (LLM pipe) - converted to signature- operator_pipe = flow.flow_elements.get("summarize_discord_channel_update_for_new_members")- assert operator_pipe is not None- assert operator_pipe.pipe_category == "PipeSignature"- assert operator_pipe.type == "PipeLLM"+ operator_element = flow.flow_elements.get("summarize_discord_channel_update_for_new_members")+ assert operator_element is not None+ assert operator_element.operator_signature is not None+ assert isinstance(operator_element.operator_signature, PipeSignature)+ assert operator_element.operator_signature.type == AllowedPipeTypes.PIPE_LLM# Verify it has the signature properties- assert hasattr(operator_pipe, "code")- assert hasattr(operator_pipe, "inputs")- assert hasattr(operator_pipe, "output")- assert hasattr(operator_pipe, "description")+ assert hasattr(operator_element.operator_signature, "code")+ assert hasattr(operator_element.operator_signature, "inputs")+ assert hasattr(operator_element.operator_signature, "output")+ assert hasattr(operator_element.operator_signature, "description")- # Verify it doesn't have implementation details (like prompt_template)- assert not hasattr(operator_pipe, "prompt_template")+ # Verify it doesn't have implementation details (like prompt)+ assert not hasattr(operator_element, "prompt")- log.info(f"Operator pipe '{operator_pipe.code}' converted to signature:")- log.info(f" Inputs: {operator_pipe.inputs}")- log.info(f" Output: {operator_pipe.output}")+ log.info(f"Operator pipe '{operator_element.operator_signature.code}' converted to signature:")+ log.info(f" Inputs: {operator_element.operator_signature.inputs}")+ log.info(f" Output: {operator_element.operator_signature.output}")