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.
Feature/posthog (#388)
Louis Choqueldf5c02991958
diff --git a/.pipelex/pipelex.toml b/.pipelex/pipelex.tomlindex e246c84bb..5dc8a89b1 100644--- a/.pipelex/pipelex.toml+++ b/.pipelex/pipelex.toml@@ -1,3 +1,45 @@+####################################################################################################+# Pipelex Configuration File+####################################################################################################+#+# This configuration file is copied to your project's .pipelex/ directory when you run:+# pipelex init config+#+# Purpose:+# - This file allows you to override Pipelex's default settings for your specific project+# - Feel free to modify any settings below to suit your needs+# - You can add any configuration sections that exist in the main pipelex.toml+#+# Finding Available Settings:+# - See the full default configuration in: pipelex/pipelex.toml (in the Pipelex package)+# - See the configuration structure classes in: pipelex/config.py and pipelex/cogt/config_cogt.py+#+# Common Customizations:+# - Logging levels and behavior+# - Excluded directories for scanning+# - LLM prompt dumping for debugging+# - Feature flags for tracking and reporting+# - Observer and reporting output directories+#+####################################################################################################++[pipelex.scan_config]+excluded_dirs = [+ ".venv",+ "venv",+ "env",+ ".env",+ "virtualenv",+ ".virtualenv",+ ".git",+ "__pycache__",+ ".pytest_cache",+ ".mypy_cache",+ ".ruff_cache",+ "node_modules",+ "results",+]+[pipelex.log_config]default_log_level = "INFO"@@ -5,10 +47,12 @@ default_log_level = "INFO"pipelex = "INFO"[cogt.llm_config]+# Uncomment any of these to enable dumping the inputs or outputs of text-genration with an LLM# is_dump_text_prompts_enabled = true# is_dump_response_text_enabled = true[cogt.llm_config.instructor_config]+# Uncomment any of these to enable dumping the kwargs, response or errors of the instructor# is_dump_kwargs_enabled = true# is_dump_response_enabled = true# is_dump_error_enabled = true@@ -18,6 +62,13 @@ observer_dir = "results/observer"[pipelex.feature_config]# WIP/Experimental feature flags-# is_pipeline_tracking_enabled = true-# is_activity_tracking_enabled = true+is_pipeline_tracking_enabled = falseis_reporting_enabled = true++[pipelex.reporting_config]+is_log_costs_to_console = false+is_generate_cost_report_file_enabled = true+cost_report_dir_path = "reports"+cost_report_base_name = "cost_report"+cost_report_extension = "csv"+cost_report_unit_scale = 1.0diff --git a/.pipelex/telemetry.toml b/.pipelex/telemetry.tomlnew file mode 100644index 000000000..067123595--- /dev/null+++ b/.pipelex/telemetry.toml@@ -0,0 +1,8 @@+settings_customized = false+telemetry_mode = "off" # Values: "off" | "anonymous" | "identified"+host = "https://eu.i.posthog.com"+project_api_key = "phc_HPJnNKpIXh0SxNDYyTAyUtnq9KxNNZJWQszynsWVx4Y"+respect_dnt = true+redact = ["prompt", "system_prompt", "response", "file_path", "url"]+debug = false+user_id = ""diff --git a/docs/pages/advanced-customization/index.md b/docs/pages/advanced-customization/index.mdindex af83f63f8..f7719ee1b 100644--- a/docs/pages/advanced-customization/index.md+++ b/docs/pages/advanced-customization/index.md@@ -60,7 +60,6 @@ Some components are controlled by feature flags in the configuration:- `is_reporting_enabled`: Controls Reporting system- `is_pipeline_tracking_enabled`: Controls Pipeline Tracking-- `is_activity_tracking_enabled`: Controls Activity TrackingWhen a feature is disabled, the corresponding NoOp implementation is used automatically.diff --git a/docs/pages/configuration/config-advanced/feature-config.md b/docs/pages/configuration/config-advanced/feature-config.mdindex 574e1d46e..9f4b3b594 100644--- a/docs/pages/configuration/config-advanced/feature-config.md+++ b/docs/pages/configuration/config-advanced/feature-config.md@@ -7,14 +7,12 @@ The `FeatureConfig` class controls which features are enabled in Pipelex.```pythonclass FeatureConfig(ConfigModel):is_pipeline_tracking_enabled: bool- is_activity_tracking_enabled: boolis_reporting_enabled: bool```### Fields- `is_pipeline_tracking_enabled`: When true, enables pipeline tracking functionality-- `is_activity_tracking_enabled`: When true, enables activity tracking functionality- `is_reporting_enabled`: When true, enables the reporting system## Impact on Dependency Injection@@ -24,7 +22,6 @@ The feature flags directly affect which implementation is used for certain compo| Feature Flag | When True | When False ||--------------|-----------|------------|| `is_pipeline_tracking_enabled` | `PipelineTracker` | `PipelineTrackerNoOp` |-| `is_activity_tracking_enabled` | `ActivityManager` | `ActivityManagerNoOp` || `is_reporting_enabled` | `ReportingManager` | `ReportingNoOp` |## Feature Details@@ -41,16 +38,6 @@ is_pipeline_tracking_enabled = true- Useful for debugging and monitoring pipeline behavior- Default: `true`-### Activity Tracking--```toml-is_activity_tracking_enabled = true-```--- Controls whether activity tracking is enabled-- When enabled, tracks detailed information about system activities-- Default: `true`-### Reporting```toml@@ -68,9 +55,6 @@ is_reporting_enabled = true# Enable pipeline tracking for debuggingis_pipeline_tracking_enabled = true-# Enable activity tracking-is_activity_tracking_enabled = true-# Enable reporting for cost monitoringis_reporting_enabled = true```diff --git a/pipelex/builder/builder_loop.py b/pipelex/builder/builder_loop.pyindex 3ecaa7b7a..cd090e7eb 100644--- a/pipelex/builder/builder_loop.py+++ b/pipelex/builder/builder_loop.py@@ -13,7 +13,7 @@ from pipelex.builder.builder_errors import (from pipelex.builder.builder_validation import validate_bundle_specfrom pipelex.client.protocol import PipelineInputsfrom pipelex.core.pipes.pipe_blueprint import AllowedPipeCategories-from pipelex.exceptions import StaticValidationErrorType, WorkingMemoryStuffNotFoundError+from pipelex.exceptions import PipelineExecutionError, StaticValidationErrorType, WorkingMemoryStuffNotFoundErrorfrom pipelex.hub import get_required_pipefrom pipelex.language.plx_factory import PlxFactoryfrom pipelex.pipeline.execute import execute_pipeline@@ -29,10 +29,14 @@ class BuilderLoop:is_save_second_iteration_enabled: bool = True,) -> PipelexBundleSpec:pretty_print(f"Building and fixing with {pipe_code}")- pipe_output = await execute_pipeline(- pipe_code=pipe_code,- inputs=input_memory,- )+ try:+ pipe_output = await execute_pipeline(+ pipe_code=pipe_code,+ inputs=input_memory,+ )+ except PipelineExecutionError as exc:+ msg = f"Builder loop: Failed to execute pipeline: {exc}."+ raise PipeBuilderError(message=msg) from excpretty_print(pipe_output, title="Pipe Output")try:diff --git a/pipelex/cli/_cli.py b/pipelex/cli/_cli.pyindex cc7c0cddb..69fab0190 100644--- a/pipelex/cli/_cli.py+++ b/pipelex/cli/_cli.py@@ -1,5 +1,8 @@+import os+import typerfrom click import Command, Context+from rich.console import Consolefrom typer.core import TyperGroupfrom typing_extensions import override@@ -9,6 +12,10 @@ from pipelex.cli.commands.kit_cmd import kit_appfrom pipelex.cli.commands.run_cmd import run_cmdfrom pipelex.cli.commands.show_cmd import show_appfrom pipelex.cli.commands.validate_cmd import validate_cmd+from pipelex.system.configuration.config_loader import config_manager+from pipelex.system.telemetry.telemetry_config import TelemetryMode+from pipelex.tools.misc.file_utils import path_exists+from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_pathclass PipelexCLI(TyperGroup):@@ -27,6 +34,91 @@ class PipelexCLI(TyperGroup):return cmd+def check_telemetry_consent() -> None:+ """Check if user has customized telemetry settings and prompt if not."""+ # Check if .pipelex directory exists - if not, user must run pipelex init first+ pipelex_config_dir = config_manager.pipelex_config_dir+ if not path_exists(pipelex_config_dir):+ typer.echo("Pipelex has not been initialized in this directory.", err=True)+ typer.echo("Please run 'pipelex init' first to set up the configuration.", err=True)+ raise typer.Exit(code=1)++ telemetry_config_path = os.path.join(pipelex_config_dir, "telemetry.toml")+ if not path_exists(telemetry_config_path):+ typer.echo(f"Telemetry configuration file not found at {telemetry_config_path}", err=True)+ typer.echo("Please run 'pipelex init' to restore the configuration.", err=True)+ raise typer.Exit(code=1)++ # Load the TOML file with tomlkit to preserve formatting and comments+ toml_doc = load_toml_with_tomlkit(telemetry_config_path)++ try:+ # Check if settings have already been customized+ if toml_doc["settings_customized"]:+ return++ # Map choice to telemetry mode using enum+ mode_map = {+ 1: TelemetryMode.OFF,+ 2: TelemetryMode.ANONYMOUS,+ 3: TelemetryMode.IDENTIFIED,+ }++ # Prompt user for telemetry preference+ typer.echo("\n" + "=" * 70)+ typer.echo("Telemetry Configuration")+ typer.echo("=" * 70)+ typer.echo("\nPipelex can collect anonymous usage data to help improve the product.")+ typer.echo("\nPlease choose your telemetry preference:")+ typer.echo(f" [1] {mode_map[1]:11} - No telemetry data collected")+ typer.echo(f" [2] {mode_map[2]:11} - Anonymous usage data only (default)")+ typer.echo(f" [3] {mode_map[3]:11} - Usage data with user identification")+ typer.echo(f" [q] {'quit':11} - Exit without configuring")+ typer.echo()++ choice_str = typer.prompt(+ "Enter your choice",+ type=str,+ default="2",+ show_default=True,+ )++ # Handle quit option+ if choice_str.lower() == "q":+ typer.echo("\nExiting without configuring telemetry.")+ raise typer.Exit(code=0)++ # Parse and validate choice+ try:+ choice = int(choice_str)+ except ValueError:+ typer.echo(f"Invalid choice: {choice_str}. Defaulting to anonymous.")+ choice = 2++ if choice not in mode_map:+ typer.echo(f"Invalid choice: {choice}. Defaulting to anonymous.")+ choice = 2++ telemetry_mode = mode_map[choice]++ # Update the settings+ toml_doc["settings_customized"] = True+ toml_doc["telemetry_mode"] = telemetry_mode++ # Save back to file+ save_toml_to_path(toml_doc, telemetry_config_path)++ typer.echo(f"\n✓ Telemetry mode set to: {telemetry_mode}")+ typer.echo("=" * 70 + "\n")++ except typer.Exit:+ # Re-raise Exit exceptions (e.g., when user quits)+ raise+ except Exception as e:+ # Silently fail if there's any issue - don't block CLI usage+ typer.echo(f"Warning: Could not save telemetry preference: {e}", err=True)++def main() -> None:"""Entry point for the pipelex CLI."""app()@@ -40,6 +132,32 @@ app = typer.Typer()[email protected](invoke_without_command=True)+def app_callback(ctx: typer.Context) -> None:+ """Run pre-command checks like printing the logo and checking telemetry consent."""+ console = Console()+ console.print(+ """++░█████████ ░[bold green4]██[/bold green4] ░██+░██ ░██ ░██+░██ ░██ ░██░████████ ░███████ ░██ ░███████ ░██ ░[bold green4]██[/bold green4]+░█████████ ░██░██ ░██ ░██ ░██ ░██ ░██ ░██ ░██ ░██+░██ ░██░██ ░██ ░█████████ ░██ ░█████████ ░█████+░██ ░██░███ ░██ ░██ ░██ ░██ ░██ ░██+░██ ░██░██░█████ ░███████ ░██ ░███████ ░██ ░██+ ░██+ ░██++"""+ )+ # Skip checks if no command is being run (e.g., just --help) or if running init command+ if ctx.invoked_subcommand is None or ctx.invoked_subcommand == "init":+ return++ check_telemetry_consent()++app.add_typer(init_app, name="init", help="Initialize Pipelex configuration in a `.pipelex` directory")app.add_typer(kit_app, name="kit", help="Manage kit assets: agent rules, migration rules")app.add_typer(diff --git a/pipelex/cli/commands/build_cmd.py b/pipelex/cli/commands/build_cmd.pyindex cf712f777..c373ed1f6 100644--- a/pipelex/cli/commands/build_cmd.py+++ b/pipelex/cli/commands/build_cmd.py@@ -10,7 +10,7 @@ from pipelex.builder.builder import PipelexBundleSpec, load_and_validate_bundlefrom pipelex.builder.builder_errors import PipeBuilderError, PipelexBundleErrorfrom pipelex.builder.builder_loop import BuilderLoopfrom pipelex.builder.runner_code import generate_runner_code-from pipelex.exceptions import PipeInputError+from pipelex.exceptions import PipeInputError, PipelineExecutionErrorfrom pipelex.hub import get_report_delegate, get_required_pipefrom pipelex.language.plx_factory import PlxFactoryfrom pipelex.pipelex import Pipelex@@ -286,10 +286,14 @@ def build_one_shot_cmd(else:ensure_directory_for_file_path(file_path=output_path)- pipe_output = await execute_pipeline(- pipe_code=builder_pipe,- inputs={"brief": brief},- )+ try:+ pipe_output = await execute_pipeline(+ pipe_code=builder_pipe,+ inputs={"brief": brief},+ )+ except PipelineExecutionError as exc:+ typer.secho(f"Failed to execute pipeline: {exc}", fg=typer.colors.RED, err=True)+ raise typer.Exit(1) from excpretty_print(pipe_output, title="Pipe Output")# Save to file unless explicitly disabled with --no-output@@ -361,10 +365,14 @@ def build_partial_cmd(input_memory = load_json_dict_from_path(inputs)else:input_memory = {"brief": inputs}- pipe_output = await execute_pipeline(- pipe_code=builder_pipe,- inputs=input_memory,- )+ try:+ pipe_output = await execute_pipeline(+ pipe_code=builder_pipe,+ inputs=input_memory,+ )+ except PipelineExecutionError as exc:+ typer.secho(f"Failed to execute pipeline: {exc}", fg=typer.colors.RED, err=True)+ raise typer.Exit(1) from exc# Save to file unless explicitly disabled with --no-outputif output_path:match extension:diff --git a/pipelex/cli/commands/run_cmd.py b/pipelex/cli/commands/run_cmd.pyindex 878b50bb6..1e8d2b6ab 100644--- a/pipelex/cli/commands/run_cmd.py+++ b/pipelex/cli/commands/run_cmd.py@@ -9,7 +9,7 @@ import typerfrom pipelex import log, pretty_print_mdfrom pipelex.builder.builder import load_and_validate_bundlefrom pipelex.builder.builder_errors import PipelexBundleError-from pipelex.exceptions import PipeInputError+from pipelex.exceptions import PipeInputError, PipelineExecutionErrorfrom pipelex.pipelex import Pipelexfrom pipelex.pipeline.execute import execute_pipelinefrom pipelex.tools.misc.file_utils import get_incremental_file_path@@ -150,10 +150,14 @@ def run_cmd(# Execute pipelinetyper.secho(f"\n🚀 Executing {source_description}...\n", fg=typer.colors.GREEN, bold=True)- pipe_output = await execute_pipeline(- pipe_code=pipe_code,- inputs=input_memory,- )+ try:+ pipe_output = await execute_pipeline(+ pipe_code=pipe_code,+ inputs=input_memory,+ )+ except PipelineExecutionError as exc:+ typer.secho(f"Failed to execute pipeline: {exc}", fg=typer.colors.RED, err=True)+ raise typer.Exit(1) from exc# Pretty print main_stuff unless disabledif not no_pretty_print:diff --git a/pipelex/cogt/llm/llm_worker_internal_abstract.py b/pipelex/cogt/llm/llm_worker_internal_abstract.pyindex 81c26e25a..ec02cd435 100644--- a/pipelex/cogt/llm/llm_worker_internal_abstract.py+++ b/pipelex/cogt/llm/llm_worker_internal_abstract.py@@ -49,7 +49,7 @@ class LLMWorkerInternalAbstract(LLMWorkerAbstract):self,llm_job: LLMJob,):- log.info(f"LLM Worker: {self.desc} --------------------------------")+ log.info(f"{self.desc} --------------------------------")await super()._before_job(llm_job=llm_job)llm_job.llm_job_before_start(inference_model=self.inference_model)if get_config().cogt.llm_config.is_dump_text_prompts_enabled:diff --git a/pipelex/config.py b/pipelex/config.pyindex 2f328d22b..f82415790 100644--- a/pipelex/config.py+++ b/pipelex/config.py@@ -77,7 +77,6 @@ class PromptingConfig(ConfigModel):class FeatureConfig(ConfigModel):is_pipeline_tracking_enabled: bool- is_activity_tracking_enabled: boolis_reporting_enabled: booldiff --git a/pipelex/core/pipes/pipe_abstract.py b/pipelex/core/pipes/pipe_abstract.pyindex f93a60642..ea2497967 100644--- a/pipelex/core/pipes/pipe_abstract.py+++ b/pipelex/core/pipes/pipe_abstract.py@@ -91,7 +91,7 @@ class PipeAbstract(ABC, BaseModel):limit = pipe_run_params.pipe_stack_limitif len(pipe_stack) > limit:msg = f"Exceeded pipe stack limit of {limit}. You can raise that limit in the config. Stack:\n{pipe_stack}"- raise PipeStackOverflowError(msg)+ raise PipeStackOverflowError(message=msg, limit=limit, pipe_stack=pipe_stack)PipeAbstractType = type[PipeAbstract]diff --git a/pipelex/exceptions.py b/pipelex/exceptions.pyindex c584a3ece..140523da1 100644--- a/pipelex/exceptions.py+++ b/pipelex/exceptions.py@@ -1,5 +1,7 @@from __future__ import annotations+from typing import TYPE_CHECKING+from click import ClickExceptionfrom typing_extensions import override@@ -14,6 +16,10 @@ from pipelex.core.validation_errors import ValidationErrorDetailsProtocolfrom pipelex.system.exceptions import RootExceptionfrom pipelex.tools.misc.context_provider_abstract import ContextProviderException+if TYPE_CHECKING:+ from pipelex.cogt.templating.template_category import TemplateCategory+ from pipelex.pipe_run.pipe_run_mode import PipeRunMode+class PipelexException(RootException):pass@@ -270,25 +276,82 @@ class StuffContentValidationError(StuffError):super().__init__(f"Failed to validate content from {original_type} to {target_type}: {validation_error}")-class PipeExecutionError(PipelexException):+class PipeRunError(PipelexException):pass-class PipeRunError(PipeExecutionError):- pass-+class DryRunError(PipeRunError):+ """Raised when a dry run fails due to missing inputs or other validation issues."""-class PipeStackOverflowError(PipeExecutionError):- pass+ def __init__(self, message: str, pipe_type: str, pipe_code: str | None = None):+ self.pipe_type = pipe_type+ self.pipe_code = pipe_code+ super().__init__(message)-# TODO: create variants of DryRunError for each type of Pipe-class DryRunError(PipeExecutionError):+class DryRunMissingInputsError(DryRunError):"""Raised when a dry run fails due to missing inputs or other validation issues."""- def __init__(self, message: str, missing_inputs: list[str] | None = None, pipe_code: str | None = None):+ def __init__(self, message: str, pipe_type: str, pipe_code: str, missing_inputs: list[str] | None = None):self.missing_inputs = missing_inputs or []+ super().__init__(message, pipe_type, pipe_code)+++class DryRunMissingPipesError(DryRunError):+ """Raised when a dry run fails due to missing pipes or other validation issues."""++ def __init__(self, message: str, pipe_type: str, pipe_code: str, missing_pipes: list[str] | None = None):+ self.missing_pipes = missing_pipes or []+ super().__init__(message, pipe_type, pipe_code)+++class DryRunTemplatingError(DryRunError):+ """Raised when a dry run fails due to templating issues."""++ def __init__(self, message: str, pipe_type: str, pipe_code: str, template_category: TemplateCategory, template: str):+ self.template_category = template_category+ self.template = template+ super().__init__(message, pipe_type, pipe_code)+++class PipeStackOverflowError(PipeRunError):+ def __init__(self, message: str, limit: int, pipe_stack: list[str]):+ self.limit = limit+ self.pipe_stack = pipe_stack+ super().__init__(message)+++class PipeRouterError(PipelexException):+ def __init__(+ self,+ message: str,+ run_mode: PipeRunMode,+ pipe_code: str,+ output_name: str | None,+ pipe_stack: list[str],+ missing_inputs: list[str] | None = None,+ ):+ self.run_mode = run_mode+ self.pipe_code = pipe_code+ self.output_name = output_name+ self.pipe_stack = pipe_stack+ self.missing_inputs = missing_inputs+ super().__init__(message)+++class PipelineExecutionError(PipelexException):+ def __init__(+ self,+ message: str,+ run_mode: PipeRunMode,+ pipe_code: str,+ output_name: str | None,+ pipe_stack: list[str],+ ):+ self.run_mode = run_modeself.pipe_code = pipe_code+ self.output_name = output_name+ self.pipe_stack = pipe_stacksuper().__init__(message)diff --git a/pipelex/hub.py b/pipelex/hub.pyindex d8a851d33..3662f9dc9 100644--- a/pipelex/hub.py+++ b/pipelex/hub.py@@ -29,6 +29,8 @@ from pipelex.plugins.plugin_manager import PluginManagerfrom pipelex.reporting.reporting_protocol import ReportingProtocolfrom pipelex.system.configuration.config_loader import config_managerfrom pipelex.system.configuration.config_root import ConfigRoot+from pipelex.system.telemetry.telemetry_config import TelemetryConfig+from pipelex.system.telemetry.telemetry_manager import TelemetryManagerAbstractfrom pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstractfrom pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract@@ -47,6 +49,8 @@ class PipelexHub:self._secrets_provider: SecretsProviderAbstract | None = Noneself._class_registry: ClassRegistryAbstract | None = Noneself._storage_provider: StorageProviderAbstract | None = None+ self._telemetry_manager: TelemetryManagerAbstract | None = None+# cogtself._models_manager: ModelManagerAbstract | None = Noneself._plugin_manager: PluginManager | None = None@@ -116,6 +120,9 @@ class PipelexHub:def set_class_registry(self, class_registry: ClassRegistryAbstract):self._class_registry = class_registry+ def set_telemetry_manager(self, telemetry_manager: TelemetryManagerAbstract):+ self._telemetry_manager = telemetry_manager+# cogtdef set_models_manager(self, models_manager: ModelManagerAbstract):@@ -200,6 +207,12 @@ class PipelexHub:raise RuntimeError(msg)return self._storage_provider+ def get_telemetry_manager(self) -> TelemetryManagerAbstract:+ if self._telemetry_manager is None:+ msg = "TelemetryManager is not initialized"+ raise RuntimeError(msg)+ return self._telemetry_manager+# cogtdef get_required_models_manager(self) -> ModelManagerAbstract:@@ -309,6 +322,14 @@ def get_class_registry() -> ClassRegistryAbstract:return get_pipelex_hub().get_required_class_registry()+def get_telemetry_manager() -> TelemetryManagerAbstract:+ return get_pipelex_hub().get_telemetry_manager()+++def get_telemetry_config() -> TelemetryConfig:+ return get_telemetry_manager().get_telemetry_config()++# cogtdiff --git a/pipelex/kit/configs/pipelex.toml b/pipelex/kit/configs/pipelex.tomlindex 89ff02d75..5dc8a89b1 100644--- a/pipelex/kit/configs/pipelex.toml+++ b/pipelex/kit/configs/pipelex.toml@@ -63,7 +63,6 @@ observer_dir = "results/observer"[pipelex.feature_config]# WIP/Experimental feature flagsis_pipeline_tracking_enabled = false-is_activity_tracking_enabled = falseis_reporting_enabled = true[pipelex.reporting_config]diff --git a/pipelex/kit/configs/telemetry.toml b/pipelex/kit/configs/telemetry.tomlnew file mode 100644index 000000000..067123595--- /dev/null+++ b/pipelex/kit/configs/telemetry.toml@@ -0,0 +1,8 @@+settings_customized = false+telemetry_mode = "off" # Values: "off" | "anonymous" | "identified"+host = "https://eu.i.posthog.com"+project_api_key = "phc_HPJnNKpIXh0SxNDYyTAyUtnq9KxNNZJWQszynsWVx4Y"+respect_dnt = true+redact = ["prompt", "system_prompt", "response", "file_path", "url"]+debug = false+user_id = ""diff --git a/pipelex/observer/local_observer.py b/pipelex/observer/local_observer.pyindex 506b77922..e0428ecc0 100644--- a/pipelex/observer/local_observer.py+++ b/pipelex/observer/local_observer.py@@ -5,6 +5,13 @@ from typing_extensions import overridefrom pipelex.config import get_configfrom pipelex.observer.observer_protocol import ObserverProtocol, PayloadType+from pipelex.types import StrEnum+++class LocalObserverEventType(StrEnum):+ BEFORE_RUN = "before_run"+ AFTER_SUCCESSFUL_RUN = "after_successful_run"+ AFTER_FAILING_RUN = "after_failing_run"class LocalObserver(ObserverProtocol):@@ -24,12 +31,12 @@ class LocalObserver(ObserverProtocol):@overrideasync def observe_before_run(self, payload: PayloadType) -> None:- self._write_to_jsonl("before_run", payload)+ self._write_to_jsonl(LocalObserverEventType.BEFORE_RUN, payload)@overrideasync def observe_after_successful_run(self, payload: PayloadType) -> None:- self._write_to_jsonl("successful_run", payload)+ self._write_to_jsonl(LocalObserverEventType.AFTER_SUCCESSFUL_RUN, payload)@overrideasync def observe_after_failing_run(self, payload: PayloadType) -> None:- self._write_to_jsonl("failing_run", payload)+ self._write_to_jsonl(LocalObserverEventType.AFTER_FAILING_RUN, payload)diff --git a/pipelex/observer/observer_protocol.py b/pipelex/observer/observer_protocol.pyindex 94d7281a4..1f71edfea 100644--- a/pipelex/observer/observer_protocol.py+++ b/pipelex/observer/observer_protocol.py@@ -2,9 +2,18 @@ from typing import Any, Protocolfrom typing_extensions import override+from pipelex.types import StrEnum+PayloadType = dict[str, Any]+class PayloadKey(StrEnum):+ PIPELINE_RUN_ID = "pipeline_run_id"+ PIPE_JOB = "pipe_job"+ PIPE_OUTPUT = "pipe_output"+ ERROR = "error"++class ObserverProtocol(Protocol):async def observe_before_run(self,diff --git a/pipelex/pipe_controllers/condition/pipe_condition.py b/pipelex/pipe_controllers/condition/pipe_condition.pyindex df95af863..216df76e6 100644--- a/pipelex/pipe_controllers/condition/pipe_condition.py+++ b/pipelex/pipe_controllers/condition/pipe_condition.py@@ -15,9 +15,10 @@ from pipelex.core.pipes.input_requirements import InputRequirementsfrom pipelex.core.pipes.input_requirements_factory import InputRequirementsFactoryfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.exceptions import (- DryRunError,+ DryRunMissingInputsError,+ DryRunMissingPipesError,+ DryRunTemplatingError,PipeConditionError,- PipeExecutionError,PipeInputError,StaticValidationError,StaticValidationErrorType,@@ -30,6 +31,7 @@ from pipelex.pipe_controllers.pipe_controller import PipeControllerfrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params import PipeRunParamsfrom pipelex.pipeline.job_metadata import JobMetadata+from pipelex.tools.jinja2.jinja2_errors import Jinja2DetectVariablesErrorfrom pipelex.tools.jinja2.jinja2_required_variables import detect_jinja2_required_variablesfrom pipelex.tools.typing.validation_utils import has_exactly_one_among_attributes_from_listfrom pipelex.types import Self@@ -93,10 +95,11 @@ class PipeCondition(PipeController):def applied_expression_template(self) -> str:if self.expression_template:return self.expression_template- if self.expression:+ elif self.expression:return "{{ " + self.expression + " }}"- msg = "No expression or expression_template provided"- raise PipeExecutionError(msg)+ else:+ msg = "No expression or expression_template provided"+ raise PipeDefinitionError(message=msg, domain_code=self.domain, pipe_code=self.code, description=self.description)########################################################################################## Inputs@@ -366,10 +369,11 @@ class PipeCondition(PipeController):if missing_input_names:log.error(f"Dry run failed: missing required inputs: {missing_input_names}")- raise DryRunError(+ raise DryRunMissingInputsError(message=f"Dry run failed for pipe '{self.code}' (PipeCondition): missing required inputs: {', '.join(missing_input_names)}",- missing_inputs=missing_input_names,+ pipe_type=self.__class__.__name__,pipe_code=self.code,+ missing_inputs=missing_input_names,)# 2. Validate that the expression template is valid@@ -379,15 +383,18 @@ class PipeCondition(PipeController):template_source=self.applied_expression_template,)log.verbose(f"Expression template is valid, requires variables: {required_variables}")- except Exception as exc:- log.error(f"Dry run failed: invalid expression template: {exc}")- error_msg = (- f"Dry run failed for pipe '{self.code}' (PipeCondition): invalid expression template '{self.applied_expression_template}': {exc}"+ except Jinja2DetectVariablesError as exc:+ log.error(f"Dry run failed: could not detect required variables from expression template: {exc}")+ msg = (+ f"Dry run failed for pipe '{self.code}' (PipeCondition): could not detect required variables "+ f"from expression template: {exc}\nTemplate:\n'{self.applied_expression_template}'")- raise DryRunError(- message=error_msg,- missing_inputs=[],+ raise DryRunTemplatingError(+ message=msg,+ pipe_type=self.__class__.__name__,pipe_code=self.code,+ template_category=TemplateCategory.EXPRESSION,+ template=self.applied_expression_template,) from exc# 3. Validate that all values in the outcomes map (appart from special outcomes) do exist as pipe codes@@ -399,11 +406,11 @@ class PipeCondition(PipeController):missing_pipes = [pipe_code for pipe_code in all_pipe_codes if not get_optional_pipe(pipe_code=pipe_code)]if missing_pipes:- error_msg = (+ msg = (f"Dry run failed for PipeCondition '{self.code}': missing pipes: {', '.join(missing_pipes)}. "f"Pipe map: {self.outcome_map}, default: {self.default_outcome}")- raise DryRunError(message=error_msg, pipe_code=self.code)+ raise DryRunMissingPipesError(message=msg, pipe_type=self.__class__.__name__, pipe_code=self.code, missing_pipes=missing_pipes)# Here, it should launch the dry run of all the pipes in the outcomes mapfor pipe_code in self.mapped_pipe_codes:diff --git a/pipelex/pipe_controllers/parallel/pipe_parallel.py b/pipelex/pipe_controllers/parallel/pipe_parallel.pyindex 7be52e71e..dcda4d2e4 100644--- a/pipelex/pipe_controllers/parallel/pipe_parallel.py+++ b/pipelex/pipe_controllers/parallel/pipe_parallel.py@@ -1,7 +1,7 @@import asynciofrom typing import TYPE_CHECKING, Any, Literal-from pydantic import model_validator+from pydantic import field_validator, model_validatorfrom typing_extensions import overridefrom pipelex import log@@ -13,11 +13,12 @@ from pipelex.core.pipes.input_requirements import InputRequirementsfrom pipelex.core.pipes.input_requirements_factory import InputRequirementsFactoryfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.core.stuffs.stuff_factory import StuffFactory-from pipelex.exceptions import DryRunError, PipeRunParamsError, StaticValidationError, StaticValidationErrorType+from pipelex.exceptions import DryRunMissingInputsError, PipeRunParamsError, StaticValidationError, StaticValidationErrorTypefrom pipelex.hub import get_pipeline_tracker, get_required_pipefrom pipelex.pipe_controllers.pipe_controller import PipeControllerfrom pipelex.pipe_controllers.sub_pipe import SubPipe-from pipelex.pipe_run.pipe_run_params import PipeRunMode, PipeRunParams+from pipelex.pipe_run.pipe_run_mode import PipeRunMode+from pipelex.pipe_run.pipe_run_params import PipeRunParamsfrom pipelex.pipeline.job_metadata import JobMetadatafrom pipelex.types import Self@@ -35,6 +36,23 @@ class PipeParallel(PipeController):add_each_output: boolcombined_output: Concept | None+ @field_validator("parallel_sub_pipes", mode="before")+ @classmethod+ def validate_parallel_sub_pipes(cls, parallel_sub_pipes: list[SubPipe]) -> list[SubPipe]:+ seen_output_names: set[str] = set()+ for sub_pipe in parallel_sub_pipes:+ if not sub_pipe.output_name:+ msg = f"PipeParallel '{cls.code}' sub-pipe '{sub_pipe.pipe_code}' output name not specified"+ raise PipeDefinitionError(msg)+ if sub_pipe.output_name in seen_output_names:+ msg = (+ f"PipeParallel '{cls.code}' sub-pipe '{sub_pipe.pipe_code}' output name '{sub_pipe.output_name}' "+ "is already used by another sub-pipe"+ )+ raise PipeDefinitionError(msg)+ seen_output_names.add(sub_pipe.output_name)+ return parallel_sub_pipes+@overridedef required_variables(self) -> set[str]:return set()@@ -234,7 +252,6 @@ class PipeParallel(PipeController):# 1. Validate that all required inputs are present in the working memoryneeded_inputs = self.needed_inputs()missing_input_names: list[str] = []-for named_input_requirement in needed_inputs.named_input_requirements:if not working_memory.get_optional_stuff(named_input_requirement.variable_name):missing_input_names.append(named_input_requirement.variable_name)@@ -242,10 +259,11 @@ class PipeParallel(PipeController):if missing_input_names:msg = f"Dry run failed: missing required inputs: {missing_input_names}"log.error(f"Dry run failed: missing required inputs: {missing_input_names}")- raise DryRunError(+ raise DryRunMissingInputsError(message=msg,- missing_inputs=missing_input_names,+ pipe_type=self.__class__.__name__,pipe_code=self.code,+ missing_inputs=missing_input_names,)# 2. Validate that all sub-pipes exist@@ -269,16 +287,7 @@ class PipeParallel(PipeController):),)- try:- pipe_outputs = await asyncio.gather(*tasks)- except Exception as exc:- msg = f"Dry run failed: parallel sub-pipe execution failed: {exc}"- log.error(msg)- raise DryRunError(- message=msg,- missing_inputs=[],- pipe_code=self.code,- ) from exc+ pipe_outputs = await asyncio.gather(*tasks)# 4. Process outputs as in the regular runoutput_stuffs: dict[str, Stuff] = {}@@ -288,23 +297,19 @@ class PipeParallel(PipeController):output_stuff = pipe_output.main_stuffsub_pipe_output_name = self.parallel_sub_pipes[output_index].output_nameif not sub_pipe_output_name:- msg = f"Dry run failed for pipe '{self.code}' (PipeParallel): sub-pipe output name not specified"- raise DryRunError(- message=msg,- missing_inputs=[],- pipe_code=self.code,- )+ sub_pipe_code = self.parallel_sub_pipes[output_index].pipe_code+ msg = f"Dry run failed for pipe '{self.code}' (PipeParallel): sub-pipe '{sub_pipe_code}' output name not specified"+ raise PipeDefinitionError(msg)if self.add_each_output:working_memory.add_new_stuff(name=sub_pipe_output_name, stuff=output_stuff)if sub_pipe_output_name in output_stuffs:- msg = f"Dry run failed for pipe '{self.code}' (PipeParallel): duplicate output name '{sub_pipe_output_name}'"- raise DryRunError(- message=msg,- missing_inputs=[],- pipe_code=self.code,+ sub_pipe_code = self.parallel_sub_pipes[output_index].pipe_code+ msg = (+ f"Dry run failed for pipe '{self.code}' (PipeParallel): sub-pipe '{sub_pipe_code}' duplicate output name '{sub_pipe_output_name}'")+ raise PipeDefinitionError(msg)output_stuffs[sub_pipe_output_name] = output_stuffoutput_stuff_contents[sub_pipe_output_name] = output_stuff.contentdiff --git a/pipelex/pipe_controllers/pipe_controller.py b/pipelex/pipe_controllers/pipe_controller.pyindex d4d94430a..71b87c11c 100644--- a/pipelex/pipe_controllers/pipe_controller.py+++ b/pipelex/pipe_controllers/pipe_controller.py@@ -7,7 +7,8 @@ from pipelex import logfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.pipes.pipe_abstract import PipeAbstractfrom pipelex.core.pipes.pipe_output import PipeOutput-from pipelex.pipe_run.pipe_run_params import PipeRunMode, PipeRunParams+from pipelex.pipe_run.pipe_run_mode import PipeRunMode+from pipelex.pipe_run.pipe_run_params import PipeRunParamsfrom pipelex.pipeline.job_metadata import JobMetadatadiff --git a/pipelex/pipe_operators/compose/pipe_compose.py b/pipelex/pipe_operators/compose/pipe_compose.pyindex cdc7871ad..67675a2cd 100644--- a/pipelex/pipe_operators/compose/pipe_compose.py+++ b/pipelex/pipe_operators/compose/pipe_compose.py@@ -22,7 +22,8 @@ from pipelex.core.stuffs.text_content import TextContentfrom pipelex.exceptions import PipeRunParamsErrorfrom pipelex.hub import get_content_generatorfrom pipelex.pipe_operators.pipe_operator import PipeOperator-from pipelex.pipe_run.pipe_run_params import PipeRunMode, PipeRunParams+from pipelex.pipe_run.pipe_run_mode import PipeRunMode+from pipelex.pipe_run.pipe_run_params import PipeRunParamsfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.pipeline.job_metadata import JobMetadatafrom pipelex.tools.jinja2.jinja2_errors import Jinja2TemplateSyntaxErrordiff --git a/pipelex/pipe_operators/extract/pipe_extract.py b/pipelex/pipe_operators/extract/pipe_extract.pyindex c56eb9993..e32276a51 100644--- a/pipelex/pipe_operators/extract/pipe_extract.py+++ b/pipelex/pipe_operators/extract/pipe_extract.py@@ -33,7 +33,8 @@ from pipelex.hub import (get_native_concept,)from pipelex.pipe_operators.pipe_operator import PipeOperator-from pipelex.pipe_run.pipe_run_params import PipeRunMode, PipeRunParams+from pipelex.pipe_run.pipe_run_mode import PipeRunMode+from pipelex.pipe_run.pipe_run_params import PipeRunParamsfrom pipelex.pipeline.job_metadata import JobMetadatafrom pipelex.tools.pdf.pypdfium2_renderer import pypdfium2_rendererfrom pipelex.types import Selfdiff --git a/pipelex/pipe_operators/func/pipe_func.py b/pipelex/pipe_operators/func/pipe_func.pyindex c9e7a5350..63e4dc07c 100644--- a/pipelex/pipe_operators/func/pipe_func.py+++ b/pipelex/pipe_operators/func/pipe_func.py@@ -1,19 +1,21 @@import asynciofrom typing import Literal, cast, get_type_hints+from pydantic import field_validatorfrom typing_extensions import overridefrom pipelex import logfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactory+from pipelex.core.pipe_errors import PipeDefinitionErrorfrom pipelex.core.pipes.input_requirements import InputRequirements, TypedNamedInputRequirementfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.exceptions import DryRunError+from pipelex.exceptions import DryRunMissingInputsErrorfrom pipelex.pipe_operators.pipe_operator import PipeOperatorfrom pipelex.pipe_run.pipe_run_params import PipeRunParamsfrom pipelex.pipeline.job_metadata import JobMetadata@@ -28,6 +30,24 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):type: Literal["PipeFunc"] = "PipeFunc"function_name: str+ @field_validator("function_name", mode="before")+ @classmethod+ def validate_function_name(cls, function_name: str) -> str:+ function = func_registry.get_function(function_name)+ if not function:+ msg = f"Function '{function_name}' not found in registry"+ raise PipeDefinitionError(msg)++ return_type = get_type_hints(function).get("return")++ if return_type is None:+ msg = f"Function '{function_name}' has no return type annotation"+ raise PipeDefinitionError(msg)+ if not issubclass(return_type, StuffContent):+ msg = f"Function '{function_name}' return type {return_type} is not a subclass of StuffContent"+ raise PipeDefinitionError(msg)+ return function_name+@overridedef required_variables(self) -> set[str]:return set()@@ -99,38 +119,43 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):# Check that all needed inputs are present in working memoryneeded_inputs = self.needed_inputs()- for input_name, _ in needed_inputs.items:- if input_name not in working_memory.root:- msg = f"Required input '{input_name}' not found in working memory for function '{self.function_name}' in pipe '{self.code}'"- raise DryRunError(msg)-- try:- return_type = get_type_hints(function).get("return")-- if return_type is None:- msg = f"Function '{self.function_name}' has no return type annotation"- raise DryRunError(msg)- if not issubclass(return_type, StuffContent):- msg = f"Function '{self.function_name}' return type {return_type} is not a subclass of StuffContent"- raise DryRunError(msg)-- # TODO: Support PipeFunc returning with multiplicity. Create an equivalent of TypedNamedInputRequirement for outputs.- requirement = TypedNamedInputRequirement(- variable_name="mock_output",- concept=ConceptFactory.make(- concept_code=self.output.code,- domain="generic",- description="Lorem Ipsum",- structure_class_name=self.output.structure_class_name,- ),- structure_class=return_type,- multiplicity=False,++ missing_input_names: list[str] = []+ for named_input_requirement in needed_inputs.named_input_requirements:+ if not working_memory.get_optional_stuff(named_input_requirement.variable_name):+ missing_input_names.append(named_input_requirement.variable_name)+ if missing_input_names:+ msg = f"Dry run failed for PipeFunc (function '{self.function_name}'): missing required inputs: {missing_input_names}"+ log.error(f"Dry run failed: missing required inputs: {missing_input_names}")+ raise DryRunMissingInputsError(+ message=msg,+ pipe_type=self.__class__.__name__,+ pipe_code=self.code,+ missing_inputs=missing_input_names,)- mock_content = WorkingMemoryFactory.create_mock_content(requirement)- except Exception as exc:- msg = f"Failed to get type hints for function '{self.function_name}' in pipe '{self.code}': {exc}"- raise DryRunError(msg) from exc+ return_type = get_type_hints(function).get("return")++ if return_type is None:+ msg = f"Function '{self.function_name}' has no return type annotation"+ raise PipeDefinitionError(msg)+ if not issubclass(return_type, StuffContent):+ msg = f"Function '{self.function_name}' return type {return_type} is not a subclass of StuffContent"+ raise PipeDefinitionError(msg)++ # TODO: Support PipeFunc returning with multiplicity. Create an equivalent of TypedNamedInputRequirement for outputs.+ requirement = TypedNamedInputRequirement(+ variable_name="mock_output",+ concept=ConceptFactory.make(+ concept_code=self.output.code,+ domain="generic",+ description="Lorem Ipsum",+ structure_class_name=self.output.structure_class_name,+ ),+ structure_class=return_type,+ multiplicity=False,+ )+ mock_content = WorkingMemoryFactory.create_mock_content(requirement)output_stuff = StuffFactory.make_stuff(name=output_name,diff --git a/pipelex/pipe_operators/img_gen/pipe_img_gen.py b/pipelex/pipe_operators/img_gen/pipe_img_gen.pyindex c32fcd38d..4d2fcfa06 100644--- a/pipelex/pipe_operators/img_gen/pipe_img_gen.py+++ b/pipelex/pipe_operators/img_gen/pipe_img_gen.py@@ -32,7 +32,8 @@ from pipelex.exceptions import ()from pipelex.hub import get_concept_library, get_content_generator, get_model_deck, get_native_conceptfrom pipelex.pipe_operators.pipe_operator import PipeOperator-from pipelex.pipe_run.pipe_run_params import PipeRunMode, PipeRunParams, output_multiplicity_to_apply+from pipelex.pipe_run.pipe_run_mode import PipeRunMode+from pipelex.pipe_run.pipe_run_params import PipeRunParams, output_multiplicity_to_applyfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.pipeline.job_metadata import JobMetadatafrom pipelex.types import Selfdiff --git a/pipelex/pipe_operators/llm/pipe_llm.py b/pipelex/pipe_operators/llm/pipe_llm.pyindex 41f1218de..5c63350a3 100644--- a/pipelex/pipe_operators/llm/pipe_llm.py+++ b/pipelex/pipe_operators/llm/pipe_llm.py@@ -28,7 +28,7 @@ from pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContentfrom pipelex.exceptions import (- PipeExecutionError,+ PipeRunError,StaticValidationError,StaticValidationErrorType,)@@ -263,7 +263,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):except LLMCompletionError as exc:location = self._format_error_location(pipe_run_params=pipe_run_params)msg = f"Error generating text with LLM {location}: {exc}"- raise PipeExecutionError(msg) from exc+ raise PipeRunError(msg) from excthe_content = TextContent(text=generated_text,@@ -377,7 +377,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):except LLMCompletionError as exc:location = self._format_error_location(pipe_run_params=pipe_run_params)msg = f"Error generating list of objects with text then object {location}: {exc}"- raise PipeExecutionError(msg) from exc+ raise PipeRunError(msg) from excelse:# We're generating a list of objects directlymethod_desc = "object_direct"@@ -393,7 +393,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):except LLMCompletionError as exc:location = self._format_error_location(pipe_run_params=pipe_run_params)msg = f"Error generating list of objects with direct method {location}: {exc}"- raise PipeExecutionError(msg) from exc+ raise PipeRunError(msg) from excthe_content = ListContent(items=generated_objects)else:@@ -417,7 +417,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):except LLMCompletionError as exc:location = self._format_error_location(pipe_run_params=pipe_run_params)msg = f"Error generating single object with text then object {location}: {exc}"- raise PipeExecutionError(msg) from exc+ raise PipeRunError(msg) from excelse:# We're generating a single object directlymethod_desc = "object_direct"@@ -432,7 +432,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):except LLMCompletionError as exc:location = self._format_error_location(pipe_run_params=pipe_run_params)msg = f"Error generating single object with direct method {location}: {exc}"- raise PipeExecutionError(msg) from exc+ raise PipeRunError(msg) from excthe_content = generated_objectreturn the_contentdiff --git a/pipelex/pipe_operators/pipe_operator.py b/pipelex/pipe_operators/pipe_operator.pyindex a49103871..b87dd3cb8 100644--- a/pipelex/pipe_operators/pipe_operator.py+++ b/pipelex/pipe_operators/pipe_operator.py@@ -8,7 +8,8 @@ from pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.pipes.pipe_abstract import PipeAbstractfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.pipe_run.pipe_run_params import PipeRunMode, PipeRunParams+from pipelex.pipe_run.pipe_run_mode import PipeRunMode+from pipelex.pipe_run.pipe_run_params import PipeRunParamsfrom pipelex.pipeline.job_metadata import JobMetadataPipeOperatorOutputType = TypeVar("PipeOperatorOutputType", bound=PipeOutput)diff --git a/pipelex/pipe_run/pipe_router_protocol.py b/pipelex/pipe_run/pipe_router_protocol.pyindex 52d1c5aea..05bfb6299 100644--- a/pipelex/pipe_run/pipe_router_protocol.py+++ b/pipelex/pipe_run/pipe_router_protocol.py@@ -1,7 +1,8 @@from typing import Protocolfrom pipelex.core.pipes.pipe_output import PipeOutput-from pipelex.observer.observer_protocol import ObserverProtocol, PayloadType+from pipelex.exceptions import DryRunMissingInputsError, PipeRouterError, PipeRunError+from pipelex.observer.observer_protocol import ObserverProtocol, PayloadKey, PayloadTypefrom pipelex.pipe_run.pipe_job import PipeJob@@ -13,8 +14,8 @@ class PipeRouterProtocol(Protocol):pipe_job: PipeJob,) -> None:payload: PayloadType = {- "pipeline_run_id": pipe_job.job_metadata.pipeline_run_id,- "pipe_job": pipe_job,+ PayloadKey.PIPELINE_RUN_ID: pipe_job.job_metadata.pipeline_run_id,+ PayloadKey.PIPE_JOB: pipe_job,}await self.observer.observe_before_run(payload)@@ -24,9 +25,9 @@ class PipeRouterProtocol(Protocol):pipe_output: PipeOutput,) -> None:payload: PayloadType = {- "pipeline_run_id": pipe_job.job_metadata.pipeline_run_id,- "pipe_job": pipe_job,- "pipe_output": pipe_output,+ PayloadKey.PIPELINE_RUN_ID: pipe_job.job_metadata.pipeline_run_id,+ PayloadKey.PIPE_JOB: pipe_job,+ PayloadKey.PIPE_OUTPUT: pipe_output,}await self.observer.observe_after_successful_run(payload)@@ -36,9 +37,9 @@ class PipeRouterProtocol(Protocol):error: Exception,) -> None:payload: PayloadType = {- "pipeline_run_id": pipe_job.job_metadata.pipeline_run_id,- "pipe_job": pipe_job,- "error": error,+ PayloadKey.PIPELINE_RUN_ID: pipe_job.job_metadata.pipeline_run_id,+ PayloadKey.PIPE_JOB: pipe_job,+ PayloadKey.ERROR: error,}await self.observer.observe_after_failing_run(payload)@@ -50,9 +51,25 @@ class PipeRouterProtocol(Protocol):try:pipe_output = await self._run_pipe_job(pipe_job)- except Exception as exc:+ except DryRunMissingInputsError as exc:await self._after_failing_run(pipe_job, exc)- raise+ raise PipeRouterError(+ message=exc.message,+ run_mode=pipe_job.pipe_run_params.run_mode,+ pipe_code=pipe_job.pipe.code,+ output_name=pipe_job.output_name,+ pipe_stack=pipe_job.pipe_run_params.pipe_stack,+ missing_inputs=exc.missing_inputs,+ ) from exc+ except PipeRunError as exc:+ await self._after_failing_run(pipe_job, exc)+ raise PipeRouterError(+ message=exc.message,+ run_mode=pipe_job.pipe_run_params.run_mode,+ pipe_code=pipe_job.pipe.code,+ output_name=pipe_job.output_name,+ pipe_stack=pipe_job.pipe_run_params.pipe_stack,+ ) from excawait self._after_successful_run(pipe_job, pipe_output)diff --git a/pipelex/pipe_run/pipe_run_mode.py b/pipelex/pipe_run/pipe_run_mode.pynew file mode 100644index 000000000..5df56666a--- /dev/null+++ b/pipelex/pipe_run/pipe_run_mode.py@@ -0,0 +1,16 @@+from __future__ import annotations++from pipelex.types import StrEnum+++class PipeRunMode(StrEnum):+ LIVE = "live"+ DRY = "dry"++ @property+ def is_dry(self) -> bool:+ match self:+ case PipeRunMode.DRY:+ return True+ case PipeRunMode.LIVE:+ return Falsediff --git a/pipelex/pipe_run/pipe_run_params.py b/pipelex/pipe_run/pipe_run_params.pyindex 039339035..3cb8f6972 100644--- a/pipelex/pipe_run/pipe_run_params.py+++ b/pipelex/pipe_run/pipe_run_params.py@@ -8,6 +8,7 @@ from pipelex import logfrom pipelex.core.memory.working_memory import BATCH_ITEM_STUFF_NAME, MAIN_STUFF_NAMEfrom pipelex.core.pipes.variable_multiplicity import VariableMultiplicity, VariableMultiplicityResolutionfrom pipelex.exceptions import BatchParamsError+from pipelex.pipe_run.pipe_run_mode import PipeRunModefrom pipelex.types import Self, StrEnum@@ -16,19 +17,6 @@ class PipeRunParamKey(StrEnum):NB_OUTPUT = "_nb_output"-class PipeRunMode(StrEnum):- LIVE = "live"- DRY = "dry"-- @property- def is_dry(self) -> bool:- match self:- case PipeRunMode.DRY:- return True- case PipeRunMode.LIVE:- return False--FORCE_DRY_RUN_MODE_ENV_KEY = "PIPELEX_FORCE_DRY_RUN_MODE"diff --git a/pipelex/pipelex.py b/pipelex/pipelex.pyindex a42a24607..545828323 100644--- a/pipelex/pipelex.py+++ b/pipelex/pipelex.py@@ -50,6 +50,9 @@ from pipelex.reporting.reporting_protocol import ReportingNoOp, ReportingProtocofrom pipelex.system.configuration.config_root import ConfigRootfrom pipelex.system.registries.func_registry import func_registryfrom pipelex.system.runtime import runtime_manager+from pipelex.system.telemetry.observer_telemetry import ObserverTelemetry+from pipelex.system.telemetry.telemetry_manager import TelemetryManager+from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstractfrom pipelex.test_extras.registry_test_models import TestRegistryModelsfrom pipelex.tools.secrets.env_secrets_provider import EnvSecretsProviderfrom pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract@@ -149,6 +152,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.pipeline_tracker: PipelineTracker | None = None,pipe_router: PipeRouterProtocol | None = None,reporting_delegate: ReportingProtocol | None = None,+ telemetry_manager: TelemetryManagerAbstract | None = None,observers: dict[str, ObserverProtocol] | None = None,**kwargs: Any,):@@ -240,7 +244,12 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.log.verbose("Registering test models for unit testing")self.class_registry.register_classes(TestRegistryModels.get_all_models())- observers = observers or {"local": LocalObserver()}+ telemetry_manager = telemetry_manager or TelemetryManager()+ self.pipelex_hub.set_telemetry_manager(telemetry_manager=telemetry_manager)+ if not observers:+ local_observer = LocalObserver()+ observer_telemetry = ObserverTelemetry(telemetry_manager=telemetry_manager)+ observers = {"local": local_observer, "telemetry": observer_telemetry}multi_observer = MultiObserver(observers=observers)self.pipelex_hub.set_observer(observer=multi_observer)self.pipelex_hub.set_pipe_router(pipe_router or PipeRouter(observer=multi_observer))@@ -303,6 +312,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.pipeline_tracker: PipelineTracker | None = None,pipe_router: PipeRouterProtocol | None = None,reporting_delegate: ReportingProtocol | None = None,+ telemetry_manager: TelemetryManagerAbstract | None = None,observers: dict[str, ObserverProtocol] | None = None,**kwargs: Any,) -> Self:@@ -323,6 +333,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.pipeline_tracker: Custom pipeline tracking/loggingpipe_router: Custom pipe routing logicreporting_delegate: Custom reporting handler+ telemetry_manager: Custom telemetry managerobservers: Custom observers for pipeline events**kwargs: Additional configuration options, only supported by your own subclass of Pipelex if you really need one@@ -349,6 +360,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.pipeline_tracker=pipeline_tracker,pipe_router=pipe_router,reporting_delegate=reporting_delegate,+ telemetry_manager=telemetry_manager,observers=observers,**kwargs,)diff --git a/pipelex/pipelex.toml b/pipelex/pipelex.tomlindex d21a6f86e..c09065e1c 100644--- a/pipelex/pipelex.toml+++ b/pipelex/pipelex.toml@@ -24,7 +24,6 @@ excluded_dirs = [[pipelex.feature_config]# WIP/Experimental feature flagsis_pipeline_tracking_enabled = false-is_activity_tracking_enabled = falseis_reporting_enabled = true[pipelex.reporting_config]diff --git a/pipelex/pipeline/execute.py b/pipelex/pipeline/execute.pyindex 2e6b86e33..96f4093ab 100644--- a/pipelex/pipeline/execute.py+++ b/pipelex/pipeline/execute.py@@ -2,21 +2,24 @@ from pipelex.client.protocol import PipelineInputsfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.pipes.pipe_output import PipeOutput+from pipelex.exceptions import PipelineExecutionError, PipeRouterErrorfrom pipelex.hub import (get_pipe_router,get_pipeline_manager,get_report_delegate,get_required_pipe,+ get_telemetry_manager,)from pipelex.pipe_run.pipe_job_factory import PipeJobFactory+from pipelex.pipe_run.pipe_run_mode import PipeRunModefrom pipelex.pipe_run.pipe_run_params import (FORCE_DRY_RUN_MODE_ENV_KEY,- PipeRunMode,VariableMultiplicity,)from pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.pipeline.job_metadata import JobMetadatafrom pipelex.system.environment import get_optional_env+from pipelex.system.telemetry.events import EventName, EventProperty, Outcomeasync def execute_pipeline(@@ -104,4 +107,24 @@ async def execute_pipeline(output_name=output_name,)- return await get_pipe_router().run(pipe_job)+ properties = {+ EventProperty.PIPELINE_RUN_ID: job_metadata.pipeline_run_id,+ }+ get_telemetry_manager().track_event(event_name=EventName.PIPELINE_EXECUTE, properties=properties)++ try:+ pipe_output = await get_pipe_router().run(pipe_job)+ except PipeRouterError as exc:+ raise PipelineExecutionError(+ message=exc.message,+ run_mode=pipe_job.pipe_run_params.run_mode,+ pipe_code=pipe_job.pipe.code,+ output_name=pipe_job.output_name,+ pipe_stack=pipe_job.pipe_run_params.pipe_stack,+ ) from exc+ properties = {+ EventProperty.PIPELINE_RUN_ID: job_metadata.pipeline_run_id,+ EventProperty.PIPELINE_EXECUTE_OUTCOME: Outcome.SUCCESS,+ }+ get_telemetry_manager().track_event(event_name=EventName.PIPELINE_COMPLETE, properties=properties)+ return pipe_outputdiff --git a/pipelex/pipeline/start.py b/pipelex/pipeline/start.pyindex 18ba885d5..0e82923d8 100644--- a/pipelex/pipeline/start.py+++ b/pipelex/pipeline/start.py@@ -6,7 +6,8 @@ from pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.hub import get_pipe_router, get_pipeline_manager, get_report_delegate, get_required_pipefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactory-from pipelex.pipe_run.pipe_run_params import PipeRunMode, VariableMultiplicity+from pipelex.pipe_run.pipe_run_mode import PipeRunMode+from pipelex.pipe_run.pipe_run_params import VariableMultiplicityfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.pipeline.job_metadata import JobMetadatadiff --git a/pipelex/system/telemetry/__init__.py b/pipelex/system/telemetry/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/pipelex/system/telemetry/events.py b/pipelex/system/telemetry/events.pynew file mode 100644index 000000000..22e13f5cf--- /dev/null+++ b/pipelex/system/telemetry/events.py@@ -0,0 +1,25 @@+from pipelex.types import StrEnum+++class EventName(StrEnum):+ # Pipeline+ PIPELINE_EXECUTE = "pipeline_execute"+ PIPELINE_COMPLETE = "pipeline_complete"++ # Pipe+ PIPE_RUN = "pipe_run"+ PIPE_COMPLETE = "pipe_complete"+++class EventProperty(StrEnum):+ # Pipeline+ PIPELINE_RUN_ID = "pipeline_run_id"+ PIPELINE_EXECUTE_OUTCOME = "pipeline_execute_outcome"++ # Pipe+ PIPE_RUN_OUTCOME = "pipe_run_outcome"+++class Outcome(StrEnum):+ SUCCESS = "success"+ FAILURE = "failure"diff --git a/pipelex/system/telemetry/observer_telemetry.py b/pipelex/system/telemetry/observer_telemetry.pynew file mode 100644index 000000000..2176420ce--- /dev/null+++ b/pipelex/system/telemetry/observer_telemetry.py@@ -0,0 +1,36 @@+from typing_extensions import override++from pipelex.observer.observer_protocol import ObserverProtocol, PayloadKey, PayloadType+from pipelex.system.telemetry.events import EventName, EventProperty, Outcome+from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract+++class ObserverTelemetry(ObserverProtocol):+ def __init__(self, telemetry_manager: TelemetryManagerAbstract):+ self.telemetry_manager = telemetry_manager++ @override+ async def observe_before_run(self, payload: PayloadType) -> None:+ properties = {+ EventProperty.PIPELINE_RUN_ID: payload[PayloadKey.PIPELINE_RUN_ID],+ }+ self.telemetry_manager.track_event(event_name=EventName.PIPE_RUN, properties=properties)++ @override+ async def observe_after_successful_run(self, payload: PayloadType) -> None:+ properties = {+ EventProperty.PIPELINE_RUN_ID: payload[PayloadKey.PIPELINE_RUN_ID],+ EventProperty.PIPE_RUN_OUTCOME: Outcome.SUCCESS,+ }+ self.telemetry_manager.track_event(event_name=EventName.PIPE_COMPLETE, properties=properties)++ @override+ async def observe_after_failing_run(+ self,+ payload: PayloadType,+ ) -> None:+ properties = {+ EventProperty.PIPELINE_RUN_ID: payload[PayloadKey.PIPELINE_RUN_ID],+ EventProperty.PIPE_RUN_OUTCOME: Outcome.FAILURE,+ }+ self.telemetry_manager.track_event(event_name=EventName.PIPE_COMPLETE, properties=properties)diff --git a/pipelex/system/telemetry/telemetry_config.py b/pipelex/system/telemetry/telemetry_config.pynew file mode 100644index 000000000..4429791d4--- /dev/null+++ b/pipelex/system/telemetry/telemetry_config.py@@ -0,0 +1,21 @@+from pydantic import Field++from pipelex.system.configuration.config_model import ConfigModel+from pipelex.types import StrEnum+++class TelemetryMode(StrEnum):+ OFF = "off"+ ANONYMOUS = "anonymous"+ IDENTIFIED = "identified"+++class TelemetryConfig(ConfigModel):+ settings_customized: bool+ telemetry_mode: TelemetryMode = Field(strict=False)+ host: str+ project_api_key: str+ respect_dnt: bool+ redact: list[str]+ debug: bool+ user_id: strdiff --git a/pipelex/system/telemetry/telemetry_manager.py b/pipelex/system/telemetry/telemetry_manager.pynew file mode 100644index 000000000..39500da37--- /dev/null+++ b/pipelex/system/telemetry/telemetry_manager.py@@ -0,0 +1,92 @@+import os+from typing import Any++from posthog import Posthog+from typing_extensions import override++from pipelex.system.configuration.config_loader import config_manager+from pipelex.system.environment import get_optional_env+from pipelex.system.telemetry.events import EventName, EventProperty+from pipelex.system.telemetry.telemetry_config import TelemetryConfig, TelemetryMode+from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract+from pipelex.tools.log.log import log+from pipelex.tools.misc.toml_utils import load_toml_from_path++DO_NOT_TRACK_ENV_VAR_KEY = "DO_NOT_TRACK"+++class TelemetryManager(TelemetryManagerAbstract):+ def __init__(self):+ config_path = os.path.join(config_manager.pipelex_config_dir, "telemetry.toml")+ telemetry_config_toml = load_toml_from_path(path=config_path)+ self.telemetry_config = TelemetryConfig.model_validate(telemetry_config_toml)+ self.do_not_track: bool+ self.posthog: Posthog | None+ if self.telemetry_config.respect_dnt and (dnt := get_optional_env(DO_NOT_TRACK_ENV_VAR_KEY)) and dnt.lower() not in ["false", "0"]:+ self.do_not_track = True+ log.debug(f"Telemetry is disabled by env var 'DO_NOT_TRACK' which is set to {dnt}")+ self.posthog = None+ else:+ self.do_not_track = False+ self.posthog = Posthog(project_api_key=self.telemetry_config.project_api_key, host=self.telemetry_config.host)++ @override+ def get_telemetry_config(self) -> TelemetryConfig:+ return self.telemetry_config++ @override+ def setup(self):+ pass++ @override+ def teardown(self):+ pass++ @override+ def track_event(self, event_name: EventName, properties: dict[EventProperty, Any] | None = None):+ if self.do_not_track:+ return+ # We copy the incoming properties to avoid modifying the original dictionary+ # and to convert the keys to str+ # and to remove the properties that are in the redact list+ tracked_properties: dict[str, Any]+ if properties:+ tracked_properties = {key: value for key, value in properties.items() if key not in self.telemetry_config.redact}+ else:+ tracked_properties = {}+ match self.telemetry_config.telemetry_mode:+ case TelemetryMode.ANONYMOUS:+ self._track_anonymous_event(event_name=event_name, properties=tracked_properties)+ case TelemetryMode.IDENTIFIED:+ if not self.telemetry_config.user_id:+ log.error(f"Could not track event '{event_name}' as identified because user_id is not set, tracking as anonymous")+ self._track_anonymous_event(event_name=event_name, properties=tracked_properties)+ else:+ self._track_identified_event(event_name=event_name, properties=tracked_properties, user_id=self.telemetry_config.user_id)+ case TelemetryMode.OFF:+ log.dev(f"Telemetry is off, skipping event '{event_name}'")++ def _track_anonymous_event(self, event_name: str, properties: dict[str, Any]):+ if not self.posthog:+ return+ if self.telemetry_config.debug:+ if properties:+ log.debug(properties, title=f"Tracking anonymous event '{event_name}'. Properties")+ else:+ log.debug(f"Tracking anonymous event '{event_name}'. No properties.")+ else:+ properties["$process_person_profile"] = False+ self.posthog.capture(event_name, properties=properties)+ log.verbose(f"Tracked anonymous event '{event_name}' with properties: {properties}")++ def _track_identified_event(self, event_name: str, properties: dict[str, Any], user_id: str):+ if not self.posthog:+ return+ if self.telemetry_config.debug:+ if properties:+ log.debug(properties, title=f"Tracking identified event '{event_name}'. Properties")+ else:+ log.debug(f"Tracking identified event '{event_name}'. No properties.")+ else:+ self.posthog.capture(event_name, distinct_id=user_id, properties=properties)+ log.verbose(f"Tracked identified event '{event_name}' with properties: {properties}")diff --git a/pipelex/system/telemetry/telemetry_manager_abstract.py b/pipelex/system/telemetry/telemetry_manager_abstract.pynew file mode 100644index 000000000..eee06598a--- /dev/null+++ b/pipelex/system/telemetry/telemetry_manager_abstract.py@@ -0,0 +1,23 @@+from abc import ABC, abstractmethod+from typing import Any++from pipelex.system.telemetry.events import EventName, EventProperty+from pipelex.system.telemetry.telemetry_config import TelemetryConfig+++class TelemetryManagerAbstract(ABC):+ @abstractmethod+ def get_telemetry_config(self) -> TelemetryConfig:+ pass++ @abstractmethod+ def setup(self):+ pass++ @abstractmethod+ def teardown(self):+ pass++ @abstractmethod+ def track_event(self, event_name: EventName, properties: dict[EventProperty, Any] | None = None):+ passdiff --git a/pipelex/tools/misc/toml_utils.py b/pipelex/tools/misc/toml_utils.pyindex df67e28de..1ef69cd36 100644--- a/pipelex/tools/misc/toml_utils.py+++ b/pipelex/tools/misc/toml_utils.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import Anyimport tomli+import tomlkitfrom pipelex.system.exceptions import ToolExceptionfrom pipelex.tools.misc.file_utils import path_exists@@ -55,3 +56,29 @@ def load_toml_from_path_if_exists(path: str) -> dict[str, Any] | None:if not path_exists(path):return Nonereturn load_toml_from_path(path)+++def load_toml_with_tomlkit(path: str) -> tomlkit.TOMLDocument:+ """Load TOML using tomlkit to preserve formatting and comments.++ Args:+ path: Path to the TOML file++ Returns:+ TOMLDocument that preserves formatting and comments++ """+ with open(path, encoding="utf-8") as f:+ return tomlkit.load(f)+++def save_toml_to_path(data: dict[str, Any] | tomlkit.TOMLDocument, path: str) -> None:+ """Save dictionary as TOML to path, preserving formatting and comments.++ Args:+ data: Dictionary or TOMLDocument to save as TOML+ path: Path where the TOML file should be saved++ """+ with open(path, "w", encoding="utf-8") as f:+ tomlkit.dump(data, f) # type: ignore[arg-type]diff --git a/pyproject.toml b/pyproject.tomlindex c6699d362..995c78fdb 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -31,6 +31,7 @@ dependencies = ["openai>=1.60.1","pillow>=11.2.1","polyfactory>=2.21.0",+ "posthog>=6.7.0","pypdfium2>=4.30.0,!=4.30.1","pydantic>=2.10.6,<3.0.0","python-dotenv>=1.0.1",diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.pyindex e24ba958e..adada5154 100644--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py@@ -8,7 +8,7 @@ from pipelex.core.concepts.concept_native import NativeConceptCodefrom pipelex.core.domains.domain import SpecialDomainfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.pipes.input_requirements import TypedNamedInputRequirement-from pipelex.exceptions import DryRunError+from pipelex.exceptions import DryRunMissingInputsErrorfrom pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprintfrom pipelex.pipe_controllers.condition.pipe_condition_factory import PipeConditionFactoryfrom pipelex.pipe_run.pipe_run_params import PipeRunMode@@ -42,7 +42,7 @@ class TestPipeConditionSimple:# Test with empty working memory - should FAILempty_working_memory = WorkingMemoryFactory.make_empty()- with pytest.raises(DryRunError) as exc_info:+ with pytest.raises(DryRunMissingInputsError) as exc_info:await pipe_condition.run_pipe(job_metadata=JobMetadata(job_name="test_direct_condition_fail"),working_memory=empty_working_memory,@@ -102,7 +102,7 @@ class TestPipeConditionSimple:print("✅ Direct PipeCondition SUCCEEDED completely!")pretty_print(pipe_output)- except DryRunError as exc:+ except DryRunMissingInputsError as exc:msg_exc = str(exc)# If it fails, it should NOT be due to missing inputsassert "missing required inputs" not in str(msg_exc)diff --git a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.py b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.pyindex 584d5697c..d400470dc 100644--- a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.py+++ b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.py@@ -10,7 +10,7 @@ from pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.exceptions import DryRunError+from pipelex.exceptions import PipeRouterErrorfrom pipelex.hub import get_pipe_router, get_required_pipefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params import PipeRunMode@@ -264,7 +264,7 @@ class TestPipeConditionComplex:assert pipe_output.working_memory is not Noneasync def test_complex_pipeline_dry_run_missing_inputs(self, request: FixtureRequest):- """Test complex pipeline dry run with missing inputs - should fail."""+ """Test complex pipeline dry run with missing inputs - should fail with PipeRouterError."""doc_request = DocumentRequest(document_type="technical", priority="urgent", language="english", complexity="high")doc_stuff = StuffFactory.make_stuff(@@ -280,7 +280,7 @@ class TestPipeConditionComplex:working_memory = WorkingMemoryFactory.make_from_single_stuff(doc_stuff)- with pytest.raises(DryRunError) as exc_info:+ with pytest.raises(PipeRouterError) as exc_info:await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(pipe=get_required_pipe(pipe_code="complex_document_processor"),@@ -292,6 +292,7 @@ class TestPipeConditionComplex:error = exc_info.valueassert error.pipe_code == "complex_document_processor"+ assert error.missing_inputs is not Noneassert "user_profile" in error.missing_inputsassert "missing required inputs" in str(error)diff --git a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.py b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.pyindex 307118e67..d3a5180a2 100644--- a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.py+++ b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.py@@ -12,7 +12,7 @@ from pipelex.core.domains.domain import SpecialDomainfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.exceptions import DryRunError+from pipelex.exceptions import PipeRouterErrorfrom pipelex.hub import get_pipe_router, get_required_pipefrom pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprintfrom pipelex.pipe_controllers.condition.pipe_condition_factory import PipeConditionFactory@@ -214,12 +214,12 @@ class TestPipeConditionSimple:assert original_input.content.category == "small"async def test_condition_dry_run_missing_inputs_failure(self, request: FixtureRequest):- """Test PipeCondition dry run with missing inputs using real pipe - should fail with DryRunError."""+ """Test PipeCondition dry run with missing inputs using real pipe - should fail with PipeRouterError."""# Create empty working memory - missing required inputempty_working_memory = WorkingMemoryFactory.make_empty()- # Run dry run using the real pipe - this should fail with DryRunError- with pytest.raises(DryRunError) as exc_info:+ # Run dry run using the real pipe - this should fail with PipeRouterError+ with pytest.raises(PipeRouterError) as exc_info:await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(pipe=get_required_pipe(pipe_code="basic_condition_by_category_2"),@@ -232,6 +232,7 @@ class TestPipeConditionSimple:# Verify the error detailserror = exc_info.valueassert error.pipe_code == "basic_condition_by_category_2"+ assert error.missing_inputs is not Noneassert "input_data" in error.missing_inputsassert "missing required inputs" in str(error)assert "input_data" in str(error)diff --git a/tests/integration/pipelex/pipes/test_bracket_notation_operators.py b/tests/integration/pipelex/pipes/test_bracket_notation_operators.pyindex 29616378e..de667649b 100644--- a/tests/integration/pipelex/pipes/test_bracket_notation_operators.py+++ b/tests/integration/pipelex/pipes/test_bracket_notation_operators.py@@ -1,6 +1,9 @@"""Integration tests for bracket notation in operator pipe factories."""from pipelex.core.concepts.concept_native import NativeConceptCode+from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.stuffs.list_content import ListContent+from pipelex.core.stuffs.text_content import TextContentfrom pipelex.pipe_operators.compose.pipe_compose_blueprint import PipeComposeBlueprintfrom pipelex.pipe_operators.compose.pipe_compose_factory import PipeComposeFactoryfrom pipelex.pipe_operators.extract.pipe_extract_blueprint import PipeExtractBlueprint@@ -11,6 +14,18 @@ from pipelex.pipe_operators.img_gen.pipe_img_gen_blueprint import PipeImgGenBluefrom pipelex.pipe_operators.img_gen.pipe_img_gen_factory import PipeImgGenFactoryfrom pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprintfrom pipelex.pipe_operators.llm.pipe_llm_factory import PipeLLMFactory+from pipelex.system.registries.func_registry import pipe_func+++# Test function for PipeFunc bracket notation test+@pipe_func(name="process_function")+async def process_function(working_memory: WorkingMemory) -> ListContent[TextContent]:+ """Test function that processes items and returns a list."""+ items = working_memory.get_stuff_as_list(name="two_texts", item_type=TextContent).items+ # Process items and return as list+ # result_items = [TextContent(text=f"processed: {item.text}") for item in items.content.items]+ processed_items = [TextContent(text=f"processed: {item.text}") for item in items]+ return ListContent(items=processed_items)class TestBracketNotationInOperators:@@ -93,7 +108,7 @@ class TestBracketNotationInOperators:"""Test PipeFunc factory with bracket notation."""blueprint = PipeFuncBlueprint(description="Process items",- inputs={"items": f"{NativeConceptCode.TEXT}[2]"},+ inputs={"two_texts": f"{NativeConceptCode.TEXT}[2]"},output=f"{NativeConceptCode.TEXT}[]",function_name="process_function",)@@ -104,7 +119,7 @@ class TestBracketNotationInOperators:blueprint=blueprint,)- assert pipe.inputs.root["items"].multiplicity == 2+ assert pipe.inputs.root["two_texts"].multiplicity == 2assert pipe.output.code == "Text"def test_pipe_compose_with_bracket_notation(self):diff --git a/tests/integration/pipelex/test_data.py b/tests/integration/pipelex/test_data.pyindex b1189ed1e..b3738ca6b 100644--- a/tests/integration/pipelex/test_data.py+++ b/tests/integration/pipelex/test_data.py@@ -10,7 +10,7 @@ from pipelex.core.stuffs.structured_content import StructuredContentfrom pipelex.core.stuffs.stuff import Stufffrom pipelex.core.stuffs.stuff_factory import StuffBlueprint, StuffFactoryfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.exceptions import PipeStackOverflowError+from pipelex.exceptions import PipeRouterErrorfrom tests.cases import ImageTestCases, PDFTestCases@@ -155,7 +155,7 @@ class PipeTestCases:FAILURE_PIPES: ClassVar[list[tuple[str, type[Exception], str]]] = [("infinite_loop_1",- PipeStackOverflowError,+ PipeRouterError,"Exceeded pipe stack limit",),]diff --git a/tests/unit/pipelex/pipe_operators/pipe_func/data.py b/tests/unit/pipelex/pipe_operators/pipe_func/data.pyindex 6572cff4b..8aaef4cda 100644--- a/tests/unit/pipelex/pipe_operators/pipe_func/data.py+++ b/tests/unit/pipelex/pipe_operators/pipe_func/data.py@@ -1,6 +1,66 @@from typing import ClassVar+from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.stuffs.text_content import TextContentfrom pipelex.pipe_operators.func.pipe_func_blueprint import PipeFuncBlueprint+from pipelex.system.registries.func_registry import pipe_func+++# Register test functions for validation tests+@pipe_func(name="my_function")+async def my_function(working_memory: WorkingMemory) -> TextContent: # noqa: ARG001 # pyright: ignore[reportUnusedParameter]+ """Test function with no inputs."""+ return TextContent(text="test output")+++@pipe_func(name="process_text")+async def process_text(working_memory: WorkingMemory) -> TextContent:+ """Test function with single text input."""+ input_data = working_memory.get_stuff_as_str("input_data")+ return TextContent(text=f"processed: {input_data}")+++@pipe_func(name="combine_data")+async def combine_data(working_memory: WorkingMemory) -> TextContent:+ """Test function with multiple inputs."""+ text_input = working_memory.get_stuff_as_str("text_input")+ number_input = working_memory.get_stuff_as_number("number_input")+ return TextContent(text=f"combined: {text_input} and {number_input}")+++@pipe_func(name="process_image")+async def process_image(working_memory: WorkingMemory) -> TextContent:+ """Test function with image input."""+ image = working_memory.get_stuff_as_image("image")+ return TextContent(text=f"processed image: {image.url}")+++@pipe_func(name="process_all")+async def process_all(working_memory: WorkingMemory) -> TextContent:+ """Test function with mixed inputs."""+ text = working_memory.get_stuff_as_str("text")+ image = working_memory.get_stuff_as_image("image")+ number = working_memory.get_stuff_as_number("number")+ return TextContent(text=f"processed all: {text}, {image.url}, {number}")+++# Error test functions - these have validation issues+# NOT registered automatically - must be registered in test fixtures+async def no_return_type_func(working_memory: WorkingMemory): # noqa: ARG001 # pyright: ignore[reportUnusedParameter]+ """Test function with no return type annotation."""+ return TextContent(text="no return type")+++async def wrong_return_type_func(working_memory: WorkingMemory) -> str: # noqa: ARG001 # pyright: ignore[reportUnusedParameter]+ """Test function with wrong return type (not StuffContent)."""+ return "wrong type"+++# Map of error function names to actual functions (for test fixtures)+ERROR_TEST_FUNCTIONS = {+ "no_return_type": no_return_type_func,+ "wrong_return_type": wrong_return_type_func,+}class PipeFuncInputTestCases:@@ -65,7 +125,42 @@ class PipeFuncInputTestCases:VALID_MIXED_INPUTS,]- # Note: PipeFunc has minimal validation since it's very flexible- # The main validation is that function_name is required (enforced by Pydantic)- # We don't have error cases for inputs since any input configuration is valid- ERROR_CASES: ClassVar[list[tuple[str, PipeFuncBlueprint, str]]] = []+ # Error test cases: (test_id, blueprint, expected_error_message_substring)+ ERROR_FUNCTION_NOT_FOUND: ClassVar[tuple[str, PipeFuncBlueprint, str]] = (+ "function_not_found",+ PipeFuncBlueprint(+ description="Test case: function_not_found",+ inputs={},+ output="native.Text",+ function_name="nonexistent_function",+ ),+ "not found in registry",+ )++ ERROR_NO_RETURN_TYPE: ClassVar[tuple[str, PipeFuncBlueprint, str]] = (+ "no_return_type",+ PipeFuncBlueprint(+ description="Test case: no_return_type",+ inputs={},+ output="native.Text",+ function_name="no_return_type",+ ),+ "has no return type annotation",+ )++ ERROR_WRONG_RETURN_TYPE: ClassVar[tuple[str, PipeFuncBlueprint, str]] = (+ "wrong_return_type",+ PipeFuncBlueprint(+ description="Test case: wrong_return_type",+ inputs={},+ output="native.Text",+ function_name="wrong_return_type",+ ),+ "is not a subclass of StuffContent",+ )++ ERROR_CASES: ClassVar[list[tuple[str, PipeFuncBlueprint, str]]] = [+ ERROR_FUNCTION_NOT_FOUND,+ ERROR_NO_RETURN_TYPE,+ ERROR_WRONG_RETURN_TYPE,+ ]diff --git a/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_input.py b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_input.pyindex 6c799c372..199d0aa68 100644--- a/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_input.py+++ b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_input.py@@ -1,17 +1,52 @@import pytestfrom pipelex import log+from pipelex.core.pipe_errors import PipeDefinitionErrorfrom pipelex.pipe_operators.func.pipe_func_blueprint import PipeFuncBlueprintfrom pipelex.pipe_operators.func.pipe_func_factory import PipeFuncFactory-from tests.unit.pipelex.pipe_operators.pipe_func.data import PipeFuncInputTestCases+from pipelex.system.registries.func_registry import func_registry+from tests.unit.pipelex.pipe_operators.pipe_func.data import ERROR_TEST_FUNCTIONS, PipeFuncInputTestCases-class TestPipeFuncValidateInputs:[email protected](scope="class")+def register_error_test_functions():+ """Register error test functions that have validation issues.++ These functions have intentional validation issues (no return type, wrong return type)+ and need to be registered bypassing normal eligibility checks to test validation logic.+ They are properly cleaned up after the test class completes.+ """+ registered_names: list[str] = []++ # Register each error test function+ # Note: We use register_function first (which will skip ineligible functions),+ # then manually add if needed for testing validation+ for func_name, func in ERROR_TEST_FUNCTIONS.items():+ # Try normal registration first+ func_registry.register_function(func, name=func_name)++ # If not registered (due to eligibility check), manually add for testing+ if not func_registry.has_function(func_name):+ # Directly add to registry for testing validation (intentionally bypassing checks)+ func_registry.root[func_name] = func++ registered_names.append(func_name)++ yield registered_names++ # Cleanup: use proper accessor to unregister all error test functions+ for func_name in registered_names:+ if func_registry.has_function(func_name):+ func_registry.unregister_function_by_name(func_name)++[email protected]("register_error_test_functions")+class TestPipeFuncValidation:@pytest.mark.parametrize(("test_id", "blueprint"),PipeFuncInputTestCases.VALID_CASES,)- def test_validate_inputs_valid_cases(+ def test_pipe_func_validate_valid_cases(self,test_id: str,blueprint: PipeFuncBlueprint,@@ -28,3 +63,27 @@ class TestPipeFuncValidateInputs:assert pipe_func is not Noneassert pipe_func.code == f"test_pipe_{test_id}"assert pipe_func.function_name == blueprint.function_name++ @pytest.mark.parametrize(+ ("test_id", "blueprint", "expected_error_substring"),+ PipeFuncInputTestCases.ERROR_CASES,+ )+ def test_pipe_func_validate_error_cases(+ self,+ test_id: str,+ blueprint: PipeFuncBlueprint,+ expected_error_substring: str,+ ):+ log.verbose(f"Testing error case: {test_id}")++ # Assert that creating the pipe raises PipeDefinitionError+ with pytest.raises(PipeDefinitionError) as exc_info:+ PipeFuncFactory.make_from_blueprint(+ domain="test_domain",+ pipe_code=f"test_pipe_{test_id}",+ blueprint=blueprint,+ )++ # Assert that the error message contains the expected substring+ error_message = str(exc_info.value)+ assert expected_error_substring in error_message, f"Expected error message to contain '{expected_error_substring}', but got: {error_message}"diff --git a/uv.lock b/uv.lockindex c78f11aec..ccd76480b 100644--- a/uv.lock+++ b/uv.lock@@ -287,6 +287,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/b7/b8/3fe70c75fe32afc4bb507f75563d39bc5642255d1d94f1f23604725780bf/babel-2.17.0-py3-none-any.whl", hash = "sha256:4d0b53093fdfb4b21c92b5213dba5a1b23885afa8383709427046b21c366e5f2", size = 10182537, upload-time = "2025-02-01T15:17:37.39Z" },]+[[package]]+name = "backoff"+version = "2.2.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/47/d7/5bbeb12c44d7c4f2fb5b56abce497eb5ed9f34d85701de869acedd602619/backoff-2.2.1.tar.gz", hash = "sha256:03f829f5bb1923180821643f8753b0502c3b682293992485b0eef2807afa5cba", size = 17001, upload-time = "2022-10-05T19:19:32.061Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/df/73/b6e24bd22e6720ca8ee9a85a0c4a2971af8497d8f3193fa05390cbd46e09/backoff-2.2.1-py3-none-any.whl", hash = "sha256:63579f9a0628e06278f7e47b7d7d5b6ce20dc65c5e96a6f3ca99a6adca0396e8", size = 15148, upload-time = "2022-10-05T19:19:30.546Z" },+]+[[package]]name = "backports-asyncio-runner"version = "1.2.0"@@ -1908,6 +1917,7 @@ dependencies = [{ name = "openai" },{ name = "pillow" },{ name = "polyfactory" },+ { name = "posthog" },{ name = "pydantic" },{ name = "pypdfium2" },{ name = "python-dotenv" },@@ -1996,6 +2006,7 @@ requires-dist = [{ name = "openai", specifier = ">=1.60.1" },{ name = "pillow", specifier = ">=11.2.1" },{ name = "polyfactory", specifier = ">=2.21.0" },+ { name = "posthog", specifier = ">=6.7.0" },{ name = "pydantic", specifier = ">=2.10.6,<3.0.0" },{ name = "pylint", marker = "extra == 'dev'", specifier = ">=3.3.8" },{ name = "pypdfium2", specifier = ">=4.30.0,!=4.30.1" },@@ -2055,6 +2066,23 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/e7/fe/d52c90e07c458f38b26f9972a25cb011b2744813f76fcd6121dde64744fa/polyfactory-2.22.2-py3-none-any.whl", hash = "sha256:9bea58ac9a80375b4153cd60820f75e558b863e567e058794d28c6a52b84118a", size = 63715, upload-time = "2025-08-15T06:23:19.664Z" },]+[[package]]+name = "posthog"+version = "6.7.9"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "backoff" },+ { name = "distro" },+ { name = "python-dateutil" },+ { name = "requests" },+ { name = "six" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/88/f8/9118197ff1113b957fa3b5d206c0e41d8885afdbb9c590bc5274602e5e62/posthog-6.7.9.tar.gz", hash = "sha256:506fd31a6a4a1a6ca207df5a05ec9bef10b64bbe148d983d8d6956bffad195c3", size = 120171, upload-time = "2025-10-22T20:53:40.099Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/07/9c/72705369b4b8bbefebe60d5bc00ad04a76a91b1a437e8ef758cd17d12acb/posthog-6.7.9-py3-none-any.whl", hash = "sha256:1415c20fed34f4be2ed4fb910516637a28a18bdfa461ee6a41588baa2f4fa64a", size = 138472, upload-time = "2025-10-22T20:53:38.749Z" },+]+[[package]]name = "propcache"version = "0.4.1"