Skip to content

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.

Telemetry docs and changelog (#395)

Louis Choquelcfa53982a935
diff --git a/.pipelex/inference/backends/azure_openai.toml b/.pipelex/inference/backends/azure_openai.toml
index 26e01b4e1..5943007c4 100644
--- a/.pipelex/inference/backends/azure_openai.toml
+++ b/.pipelex/inference/backends/azure_openai.toml
@@ -96,3 +96,8 @@ inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
+[gpt-5]
+model_id = "gpt-5-2025-08-07"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
diff --git a/.pipelex/inference/backends/pipelex_inference.toml b/.pipelex/inference/backends/pipelex_inference.toml
index d22b08cea..0f5b09cf1 100644
--- a/.pipelex/inference/backends/pipelex_inference.toml
+++ b/.pipelex/inference/backends/pipelex_inference.toml
@@ -75,6 +75,12 @@ inputs = ["text", "images"]
outputs = ["text"]
costs = { input = 1.25, output = 10.00 }
+[gpt-5]
+model_id = "pipelex/gpt-5"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
+
# --- Claude LLMs --------------------------------------------------------------
["claude-4-sonnet"]
model_id = "pipelex/claude-4-sonnet"
diff --git a/.pipelex/inference/deck/base_deck.toml b/.pipelex/inference/deck/base_deck.toml
index 7cfc55299..7a52ca603 100644
--- a/.pipelex/inference/deck/base_deck.toml
+++ b/.pipelex/inference/deck/base_deck.toml
@@ -66,7 +66,7 @@ llm_cheap = { model = "base-gemini", temperature = 0.1 }
# Generation skills
llm_for_factual_writing = { model = "base-gpt", temperature = 0.1 }
-llm_for_creative_writing = { model = "claude-4.5-sonnet", temperature = 0.9 }
+llm_for_creative_writing = { model = "base-gpt", temperature = 0.9 }
llm_to_write_questions = { model = "gpt-4o-mini", temperature = 0.3 }
# Reasoning skills
diff --git a/.pipelex/telemetry.toml b/.pipelex/telemetry.toml
index 067123595..327955340 100644
--- a/.pipelex/telemetry.toml
+++ b/.pipelex/telemetry.toml
@@ -1,8 +1,9 @@
-settings_customized = false
-telemetry_mode = "off" # Values: "off" | "anonymous" | "identified"
+telemetry_mode = "anonymous" # 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
+geoip_enabled = true
+dry_mode_enabled = false
+verbose_enabled = false
user_id = ""
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f23e362ca..73bd79993 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,8 @@
### Added
- Added the `n8n` documentation page for the [n8n-nodes-pipelex](https://github.com/Pipelex/n8n-nodes-pipelex) package.
+- Added optional telemetry system with first-run interactive prompt offering three modes: off (no data collected), anonymous (usage data without identification), and identified (usage data with user identification). Automatically respects `DO_NOT_TRACK` environment variable and redacts sensitive data (prompts, responses, file paths, URLs). Configuration stored in `.pipelex/telemetry.toml`.
+- Added telemetry documentation: user-friendly setup guide and comprehensive configuration reference.
### Changed
diff --git a/README.md b/README.md
index ec71e96cb..3e7a8254c 100644
--- a/README.md
+++ b/README.md
@@ -235,6 +235,18 @@ Using `uv`:
uv pip install "pipelex[anthropic,google,google-genai,mistralai,bedrock,fal]"
```
+### Privacy & Telemetry
+
+Pipelex collects optional, anonymous usage data to help improve the product. On first run, you'll be prompted to choose your telemetry preference:
+
+- **Off**: No telemetry data collected
+- **Anonymous**: Anonymous usage data only (command usage, performance metrics, feature usage)
+- **Identified**: Usage data with user identification (helps us provide better support)
+
+Your prompts, LLM responses, file paths, and URLs are automatically redacted and never transmitted. You can change your preference at any time or disable telemetry completely by setting the `DO_NOT_TRACK` environment variable.
+
+For more details, see the [Telemetry Documentation](https://docs.pipelex.com/pages/setup/telemetry/).
+
---
## Example: optimizing a tweet in 2 steps
diff --git a/docs/index.md b/docs/index.md
index 1b84137e4..98e8156f6 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -43,8 +43,9 @@ pipelex build pipe "Imagine a cute animal mascot for a startup based on its elev
**Other useful use-cases for business:**
```bash
-pipelex build pipe "Given an expense report, apply company rules"
-pipelex build pipe "Take a CV in a PDF file, a Job offer text, and analyze if they match"
+pipelex build pipe "Given an expense report, apply company rules" --output results/expense.plx
+pipelex build pipe "Take a resume PDF, a Job offer text, and analyze if they match" --output results/resume_match.plx
+pipelex build pipe "Take a theme, write a joke about it, then roast the joke" --output results/self_roaster.plx
```
Each of these commands generates a complete production-ready script in our Pipelex language, saved as `.plx` file including domain definition, concepts, and the multiple _pipe_ steps to take to achieve the goal.
@@ -55,16 +56,8 @@ Each of these commands generates a complete production-ready script in our Pipel
```bash
# Run a pipe by code
-pipelex run <pipe_code>
-
-# Run with inputs (JSON file containing input_memory dict)
-pipelex run <pipe_code> --inputs input.json
-
-# Run a bundle's main_pipe (auto-detected from .plx extension)
-pipelex run bundle.plx --inputs input.json
-
-# Customize output location
-pipelex run <pipe_code> --output results/output.json
+pipelex run results/resume_match.plx --inputs inputs.json
+pipelex run results/self_roaster.plx --inputs '{"theme": "the prisoner dilemma"}'
```
The `--inputs` file should be a JSON dictionary where keys are input variable names and values are the input data. For native concepts like Text, you can use strings directly. For structured types, provide objects matching the expected structure.
diff --git a/docs/pages/configuration/config-practical/telemetry-config.md b/docs/pages/configuration/config-practical/telemetry-config.md
new file mode 100644
index 000000000..867be35b0
--- /dev/null
+++ b/docs/pages/configuration/config-practical/telemetry-config.md
@@ -0,0 +1,164 @@
+# Telemetry Configuration
+
+## Overview
+
+Telemetry configuration is stored in `.pipelex/telemetry.toml`, separate from the main `pipelex.toml` configuration. This file is created automatically the first time you run a Pipelex command (after `pipelex init config`) and are prompted to choose your telemetry preference.
+
+For a user-friendly introduction to telemetry, see [Telemetry Setup](../../setup/telemetry.md).
+
+## Configuration File Location
+
+```
+.pipelex/telemetry.toml
+```
+
+This file is created in the `.pipelex` directory at your project root.
+
+## Configuration Options
+
+### Example Configuration
+
+```toml
+telemetry_mode = "off"
+host = "https://eu.i.posthog.com"
+project_api_key = "phc_HPJnNKpIXh0SxNDYyTAyUtnq9KxNNZJWQszynsWVx4Y"
+respect_dnt = true
+redact = ["prompt", "system_prompt", "response", "file_path", "url"]
+geoip_enabled = true
+dry_mode_enabled = false
+verbose_enabled = false
+user_id = ""
+```
+
+### Settings Reference
+
+#### `telemetry_mode`
+
+- **Type**: `string`
+- **Default**: `"off"`
+- **Allowed values**: `"off"`, `"anonymous"`, `"identified"`
+- **Description**: Controls the telemetry collection mode.
+ - `"off"`: No telemetry data is collected
+ - `"anonymous"`: Anonymous usage data only (no user identification)
+ - `"identified"`: Usage data with user identification (requires `user_id` to be set)
+
+#### `host`
+
+- **Type**: `string`
+- **Default**: `"https://eu.i.posthog.com"`
+- **Description**: The PostHog server host URL. We use the EU-hosted instance for privacy compliance.
+
+**Note**: This is typically not changed unless you're self-hosting PostHog.
+
+#### `project_api_key`
+
+- **Type**: `string`
+- **Default**: `"phc_HPJnNKpIXh0SxNDYyTAyUtnq9KxNNZJWQszynsWVx4Y"`
+- **Description**: The PostHog project API key for the Pipelex telemetry project.
+
+**Note**: This is typically not changed unless you're using a custom telemetry backend.
+
+#### `respect_dnt`
+
+- **Type**: `boolean`
+- **Default**: `true`
+- **Description**: When `true`, Pipelex respects the `DO_NOT_TRACK` environment variable. If `DO_NOT_TRACK` is set to any value except `false` or `0`, telemetry is automatically disabled.
+
+#### `redact`
+
+- **Type**: `array` of `string`
+- **Default**: `["prompt", "system_prompt", "response", "file_path", "url"]`
+- **Description**: List of event properties to redact from telemetry data. These sensitive fields are automatically filtered out before any data is sent.
+
+**Privacy protection**: This ensures that your actual prompts, LLM responses, and file paths are never transmitted to telemetry servers.
+
+#### `debug`
+
+- **Type**: `boolean`
+- **Default**: `false`
+- **Description**: When `true`, telemetry events are logged locally but not actually sent to PostHog. Useful for debugging telemetry implementation.
+
+#### `user_id`
+
+- **Type**: `string`
+- **Default**: `""`
+- **Description**: User identifier for the `"identified"` telemetry mode. If `telemetry_mode` is set to `"identified"` but `user_id` is empty, telemetry falls back to anonymous mode.
+
+**Usage**: Set this to your email, username, or any identifier you prefer when using identified mode.
+
+## Manually Changing Settings
+
+Edit `.pipelex/telemetry.toml` directly. Changes take effect on the next command run.
+
+```toml
+telemetry_mode = "off" # Disable telemetry
+telemetry_mode = "anonymous" # Enable anonymous telemetry
+```
+
+### Example: Enable Identified Telemetry
+
+```toml
+telemetry_mode = "identified"
+user_id = "[email protected]"
+```
+
+## Re-triggering the Configuration Prompt
+
+If you want to see the configuration prompt again (for example, to change your choice through the interactive interface), delete the `.pipelex/telemetry.toml` file:
+
+```bash
+rm .pipelex/telemetry.toml
+```
+
+The next time you run a Pipelex command (except `pipelex init`), you'll be prompted to choose your telemetry preference.
+
+## Environment Variable Override
+
+The `DO_NOT_TRACK` environment variable provides a universal way to disable telemetry:
+
+```bash
+# Linux/MacOS
+export DO_NOT_TRACK=1
+
+# Windows PowerShell
+$env:DO_NOT_TRACK="1"
+
+# Windows CMD
+set DO_NOT_TRACK=1
+```
+
+When `respect_dnt = true` (the default), this will disable all telemetry regardless of the `telemetry_mode` setting.
+
+## What Data is Collected?
+
+When telemetry is enabled (anonymous or identified mode), Pipelex collects:
+
+- Whole pipeline execution events (start, success, failure)
+- Each pipe execution events (start, success, failure)
+
+soon to be added:
+- Error types (without error messages)
+- Command usage (which CLI commands are run)
+- Feature usage patterns (which pipe types are used)
+- Performance metrics (execution time, token usage)
+
+**Never collected** (automatically redacted):
+
+- Your prompts or system prompts
+- LLM responses
+- File paths
+- URLs
+- Any content from your documents or images
+- Personal data (unless you explicitly set a `user_id` in identified mode)
+
+## Privacy and Compliance
+
+- Telemetry is **opt-in** via the first-run prompt
+- All sensitive data is **automatically redacted**
+- We use **PostHog** (EU-hosted) for telemetry infrastructure
+- We **respect DO_NOT_TRACK** by default
+- You can **completely disable** telemetry at any time
+- Telemetry configuration is **stored locally** in your project
+
+For more information about our data practices, see our [privacy policy](https://pipelex.com/privacy-policy).
+
diff --git a/docs/pages/setup/telemetry.md b/docs/pages/setup/telemetry.md
new file mode 100644
index 000000000..c31ff9ffa
--- /dev/null
+++ b/docs/pages/setup/telemetry.md
@@ -0,0 +1,81 @@
+# Telemetry
+
+## What is Telemetry?
+
+Pipelex collects optional, anonymous usage data to help improve the product. This helps us understand how Pipelex is being used and identify areas for improvement.
+
+## First Run Experience
+
+When you run most Pipelex commands for the first time (after running `pipelex init`), you'll be prompted to configure your telemetry preferences:
+
+```
+======================================================================
+Telemetry Configuration
+======================================================================
+
+Pipelex can collect anonymous usage data to help improve the product.
+
+Please choose your telemetry preference:
+ [1] off - No telemetry data collected
+ [2] anonymous - Anonymous usage data only
+ [3] identified - Usage data with user identification
+ [q] quit - Exit without configuring
+
+Enter your choice:
+```
+
+## Telemetry Modes
+
+### Off
+
+No telemetry data is collected. Pipelex will not send any data to our servers.
+
+### Anonymous
+
+Anonymous usage data only. This includes:
+
+- Command usage (which commands are run)
+- Pipeline execution statistics (success/failure rates, performance metrics)
+- Feature usage patterns
+
+This mode does **not** include:
+
+- Personal identification
+- Your prompts or system prompts
+- LLM responses
+- File paths or URLs
+- Any sensitive information
+
+### Identified
+
+Same as anonymous mode, but includes a user identifier. This helps us provide better support and understand user journeys across sessions.
+
+If you choose this mode, you can optionally provide a `user_id` in the configuration file.
+
+## DO_NOT_TRACK Support
+
+Pipelex respects the `DO_NOT_TRACK` environment variable. If you have `DO_NOT_TRACK` set in your environment (to any value except `false` or `0`), telemetry will be automatically disabled regardless of your configuration settings.
+
+```bash
+# Disable telemetry via environment variable
+export DO_NOT_TRACK=1
+```
+
+## Changing Your Settings
+
+You can change your telemetry settings at any time:
+
+1. **Via configuration file**: Edit `.pipelex/telemetry.toml` directly (see [Telemetry Configuration](../configuration/config-practical/telemetry-config.md))
+2. **Trigger the prompt again**: Delete `.pipelex/telemetry.toml`, and the prompt will appear next time you run a command
+
+## Privacy
+
+We take your privacy seriously:
+
+- Sensitive data (prompts, responses, file paths, URLs) is automatically redacted
+- You have full control over what level of telemetry you're comfortable with
+- All telemetry can be completely disabled
+- Our telemetry infrastructure uses PostHog, hosted in the EU
+
+For detailed configuration options, see [Telemetry Configuration](../configuration/config-practical/telemetry-config.md).
+
diff --git a/mkdocs.yml b/mkdocs.yml
index 9b3104d63..16bcd4a78 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -89,6 +89,7 @@ nav:
- Setup:
- Configure AI Providers: pages/setup/configure-ai-providers.md
- Project Organization: pages/setup/project-organization.md
+ - Telemetry: pages/setup/telemetry.md
- Understand Pipelex:
- The Knowledge Pipeline Manifesto: manifesto.md
- The Pipelex Paradigm: pages/pipelex-paradigm-for-repeatable-ai-workflows/index.md
@@ -144,6 +145,7 @@ nav:
- Logging: pages/configuration/config-practical/logging-config.md
- Pipe Run: pages/configuration/config-practical/pipe-run-config.md
- Reporting: pages/configuration/config-practical/reporting-config.md
+ - Telemetry: pages/configuration/config-practical/telemetry-config.md
- Tracker: pages/configuration/config-practical/tracker-config.md
- Technical Configuration:
- AWS: pages/configuration/config-technical/aws-config.md
diff --git a/pipelex/cli/_cli.py b/pipelex/cli/_cli.py
index 69fab0190..c302453eb 100644
--- a/pipelex/cli/_cli.py
+++ b/pipelex/cli/_cli.py
@@ -12,8 +12,10 @@ from pipelex.cli.commands.kit_cmd import kit_app
from pipelex.cli.commands.run_cmd import run_cmd
from pipelex.cli.commands.show_cmd import show_app
from pipelex.cli.commands.validate_cmd import validate_cmd
+from pipelex.kit.paths import get_configs_dir
from pipelex.system.configuration.config_loader import config_manager
-from pipelex.system.telemetry.telemetry_config import TelemetryMode
+from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME, TelemetryMode
+from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract
from pipelex.tools.misc.file_utils import path_exists
from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_path
@@ -34,8 +36,8 @@ class PipelexCLI(TyperGroup):
return cmd
-def check_telemetry_consent() -> None:
- """Check if user has customized telemetry settings and prompt if not."""
+def check_telemetry_consent() -> TelemetryMode | None:
+ """Check if user has configured telemetry 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):
@@ -43,25 +45,22 @@ def check_telemetry_consent() -> None:
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)
+ telemetry_config_path = os.path.join(pipelex_config_dir, TELEMETRY_CONFIG_FILE_NAME)
- # Load the TOML file with tomlkit to preserve formatting and comments
- toml_doc = load_toml_with_tomlkit(telemetry_config_path)
+ # If telemetry.toml exists, settings are already configured
+ if path_exists(telemetry_config_path):
+ return None
+ # If file doesn't exist, prompt user and create it
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,
+ mode_map: dict[str, TelemetryMode] = {
+ "1": TelemetryMode.OFF,
+ "2": TelemetryMode.ANONYMOUS,
+ "3": TelemetryMode.IDENTIFIED,
+ "off": TelemetryMode.OFF,
+ "anonymous": TelemetryMode.ANONYMOUS,
+ "identified": TelemetryMode.IDENTIFIED,
}
# Prompt user for telemetry preference
@@ -70,53 +69,54 @@ def check_telemetry_consent() -> None:
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(f" [1] {TelemetryMode.OFF:11} - No telemetry data collected")
+ typer.echo(f" [2] {TelemetryMode.ANONYMOUS:11} - Anonymous usage data only")
+ typer.echo(f" [3] {TelemetryMode.IDENTIFIED: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
+ # Loop until valid input is received
+ telemetry_mode: TelemetryMode | None = None
+ while telemetry_mode is None:
+ choice_str = typer.prompt(
+ "Enter your choice",
+ type=str,
+ )
+
+ # Normalize input to lowercase
+ choice_normalized = choice_str.lower().strip()
+
+ # Handle quit option
+ if choice_normalized in ("q", "quit"):
+ typer.echo("\nExiting without configuring telemetry.")
+ raise typer.Exit(code=0)
+
+ # Check if valid choice
+ if choice_normalized in mode_map:
+ telemetry_mode = mode_map[choice_normalized]
+ else:
+ typer.echo(f"Invalid choice: '{choice_str}'. Please enter 1, 2, 3, off, anonymous, identified, or q to quit.\n")
+
+ # Load template and set the chosen mode
+ template_path = os.path.join(str(get_configs_dir()), TELEMETRY_CONFIG_FILE_NAME)
+ toml_doc = load_toml_with_tomlkit(template_path)
toml_doc["telemetry_mode"] = telemetry_mode
- # Save back to file
+ # Save to user's .pipelex directory
save_toml_to_path(toml_doc, telemetry_config_path)
typer.echo(f"\n✓ Telemetry mode set to: {telemetry_mode}")
typer.echo("=" * 70 + "\n")
+ return telemetry_mode
+
except typer.Exit:
# Re-raise Exit exceptions (e.g., when user quits)
raise
- except Exception as e:
+ except Exception as exc:
# Silently fail if there's any issue - don't block CLI usage
- typer.echo(f"Warning: Could not save telemetry preference: {e}", err=True)
+ typer.echo(f"Warning: Could not save telemetry preference: {exc}", err=True)
+ return None
def main() -> None:
@@ -155,7 +155,7 @@ def app_callback(ctx: typer.Context) -> None:
if ctx.invoked_subcommand is None or ctx.invoked_subcommand == "init":
return
- check_telemetry_consent()
+ TelemetryManagerAbstract.telemetry_mode_just_set = check_telemetry_consent()
app.add_typer(init_app, name="init", help="Initialize Pipelex configuration in a `.pipelex` directory")
diff --git a/pipelex/cli/commands/build_cmd.py b/pipelex/cli/commands/build_cmd.py
index c373ed1f6..94587ebb0 100644
--- a/pipelex/cli/commands/build_cmd.py
+++ b/pipelex/cli/commands/build_cmd.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Annotated
import click
import typer
+from posthog import new_context, tag
from pipelex import pretty_print
from pipelex.builder.builder import PipelexBundleSpec, load_and_validate_bundle
@@ -13,8 +14,10 @@ from pipelex.builder.runner_code import generate_runner_code
from pipelex.exceptions import PipeInputError, PipelineExecutionError
from pipelex.hub import get_report_delegate, get_required_pipe
from pipelex.language.plx_factory import PlxFactory
-from pipelex.pipelex import Pipelex
+from pipelex.pipelex import PACKAGE_VERSION, Pipelex
from pipelex.pipeline.execute import execute_pipeline
+from pipelex.system.runtime import IntegrationMode
+from pipelex.system.telemetry.events import EventProperty
from pipelex.tools.misc.file_utils import ensure_directory_for_file_path, get_incremental_file_path, save_text_to_path
from pipelex.tools.misc.json_utils import load_json_dict_from_path, save_as_json_to_path
@@ -43,8 +46,15 @@ pipelex build pipe "Given an RDFP PDF, build a compliance matrix"
pipelex build pipe "Given a theme, write a Haiku"
"""
+COMMAND = "build"
-@build_app.command("pipe", help="Build a Pipelex bundle with one validation/fix loop correcting deterministic issues")
+SUB_COMMAND_PIPE = "pipe"
+SUB_COMMAND_RUNNER = "runner"
+SUB_COMMAND_ONE_SHOT_PIPE = "one-shot-pipe"
+SUB_COMMAND_PARTIAL_PIPE = "partial-pipe"
+
+
+@build_app.command(SUB_COMMAND_PIPE, help="Build a Pipelex bundle with one validation/fix loop correcting deterministic issues")
def build_pipe_cmd(
prompt: Annotated[
str,
@@ -63,7 +73,7 @@ def build_pipe_cmd(
typer.Option("--no-output", help="Skip saving the pipeline to file"),
] = False,
) -> None:
- Pipelex.make()
+ Pipelex.make(integration_mode=IntegrationMode.CLI)
typer.echo("=" * 70)
typer.secho("🔥 Starting pipe builder... 🚀", fg=typer.colors.GREEN)
typer.echo("")
@@ -104,15 +114,20 @@ def build_pipe_cmd(
save_text_to_path(text=plx_content, path=output_path)
typer.secho(f"\n✅ Pipeline saved to: {output_path}", fg=typer.colors.GREEN)
- start_time = time.time()
- asyncio.run(run_pipeline())
- end_time = time.time()
- typer.secho(f"\n✅ Pipeline built in {end_time - start_time:.2f} seconds", fg=typer.colors.GREEN)
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_PIPE}")
+
+ start_time = time.time()
+ asyncio.run(run_pipeline())
+ end_time = time.time()
+ typer.secho(f"\n✅ Pipeline built in {end_time - start_time:.2f} seconds", fg=typer.colors.GREEN)
- get_report_delegate().generate_report()
+ get_report_delegate().generate_report()
-@build_app.command("runner", help="Build the Python code to run a pipe with the necessary inputs")
+@build_app.command(SUB_COMMAND_RUNNER, help="Build the Python code to run a pipe with the necessary inputs")
def prepare_runner_cmd(
target: Annotated[
str | None,
@@ -193,7 +208,7 @@ def prepare_runner_cmd(
async def prepare_runner(pipe_code: str | None = None, bundle_path: str | None = None):
# Initialize Pipelex
- Pipelex.make()
+ Pipelex.make(integration_mode=IntegrationMode.CLI)
if bundle_path:
try:
@@ -250,10 +265,15 @@ def prepare_runner_cmd(
typer.secho(f"❌ Error saving file: {exc}", fg=typer.colors.RED)
raise typer.Exit(1) from exc
- asyncio.run(prepare_runner(pipe_code=pipe_code, bundle_path=bundle_path))
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_RUNNER}")
+ asyncio.run(prepare_runner(pipe_code=pipe_code, bundle_path=bundle_path))
-@build_app.command("one-shot-pipe", help="Developer utility for contributors: deliver pipeline in one shot, without validation loop")
+
+@build_app.command(SUB_COMMAND_ONE_SHOT_PIPE, help="Developer utility for contributors: deliver pipeline in one shot, without validation loop")
def build_one_shot_cmd(
brief: Annotated[
str,
@@ -272,7 +292,7 @@ def build_one_shot_cmd(
typer.Option("--no-output", help="Skip saving the pipeline to file"),
] = False,
) -> None:
- Pipelex.make()
+ Pipelex.make(integration_mode=IntegrationMode.CLI)
typer.echo("=" * 70)
typer.secho("🔥 Starting pipe builder... 🚀", fg=typer.colors.GREEN)
typer.echo("")
@@ -306,16 +326,22 @@ def build_one_shot_cmd(
save_text_to_path(text=plx_content, path=output_path)
typer.secho(f"\n✅ Pipeline saved to: {output_path}", fg=typer.colors.GREEN)
- start_time = time.time()
- asyncio.run(run_pipeline())
- end_time = time.time()
- typer.secho(f"\n✅ Pipeline built in {end_time - start_time:.2f} seconds", fg=typer.colors.GREEN)
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_ONE_SHOT_PIPE}")
+
+ start_time = time.time()
+ asyncio.run(run_pipeline())
+ end_time = time.time()
+ typer.secho(f"\n✅ Pipeline built in {end_time - start_time:.2f} seconds", fg=typer.colors.GREEN)
- get_report_delegate().generate_report()
+ get_report_delegate().generate_report()
@build_app.command(
- "partial-pipe", help="Developer utility for contributors: deliver a partial pipeline specification (not an actual bundle) and save it as JSON"
+ SUB_COMMAND_PARTIAL_PIPE,
+ help="Developer utility for contributors: deliver a partial pipeline specification (not an actual bundle) and save it as JSON",
)
def build_partial_cmd(
inputs: Annotated[
@@ -343,7 +369,7 @@ def build_partial_cmd(
typer.Option("--no-output", help="Skip saving the pipeline to file"),
] = False,
) -> None:
- Pipelex.make()
+ Pipelex.make(integration_mode=IntegrationMode.CLI)
typer.echo("=" * 70)
typer.secho("🔥 Starting pipe builder... 🚀", fg=typer.colors.GREEN)
typer.echo("")
@@ -395,9 +421,14 @@ def build_partial_cmd(
else:
typer.secho("\n⚠️ Pipeline not saved to file (--no-output specified)", fg=typer.colors.YELLOW)
- start_time = time.time()
- asyncio.run(run_pipeline())
- end_time = time.time()
- typer.secho(f"\n✅ Pipeline built in {end_time - start_time:.2f} seconds", fg=typer.colors.GREEN)
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_PARTIAL_PIPE}")
+
+ start_time = time.time()
+ asyncio.run(run_pipeline())
+ end_time = time.time()
+ typer.secho(f"\n✅ Pipeline built in {end_time - start_time:.2f} seconds", fg=typer.colors.GREEN)
- get_report_delegate().generate_report()
+ get_report_delegate().generate_report()
diff --git a/pipelex/cli/commands/init_cmd.py b/pipelex/cli/commands/init_cmd.py
index e949fce2f..220ee92e4 100644
--- a/pipelex/cli/commands/init_cmd.py
+++ b/pipelex/cli/commands/init_cmd.py
@@ -8,6 +8,7 @@ import typer
from pipelex.exceptions import PipelexCLIError
from pipelex.kit.paths import get_configs_dir
from pipelex.system.configuration.config_loader import config_manager
+from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME
PACKAGE_NAME = __name__.split(".", maxsplit=1)[0]
PACKAGE_VERSION = metadata(PACKAGE_NAME)["Version"]
@@ -31,6 +32,10 @@ def do_init_config(reset: bool = False) -> None:
dst_item = os.path.join(dst_dir, item)
relative_item = os.path.join(relative_path, item) if relative_path else item
+ # Skip telemetry.toml - it will be created when user is prompted
+ if item == TELEMETRY_CONFIG_FILE_NAME:
+ continue
+
if os.path.isdir(src_item):
os.makedirs(dst_item, exist_ok=True)
copy_directory_structure(src_item, dst_item, relative_item)
diff --git a/pipelex/cli/commands/run_cmd.py b/pipelex/cli/commands/run_cmd.py
index 5ddaa9601..3470c28b8 100644
--- a/pipelex/cli/commands/run_cmd.py
+++ b/pipelex/cli/commands/run_cmd.py
@@ -6,6 +6,7 @@ from typing import Annotated
import click
import typer
+from posthog import new_context, tag
from pipelex import log, pretty_print_md
from pipelex.builder.builder import load_and_validate_bundle
@@ -13,9 +14,14 @@ from pipelex.builder.builder_errors import PipelexBundleError
from pipelex.exceptions import PipeInputError, PipelineExecutionError
from pipelex.pipelex import Pipelex
from pipelex.pipeline.execute import execute_pipeline
+from pipelex.system.runtime import IntegrationMode
+from pipelex.system.telemetry.events import EventProperty
+from pipelex.system.telemetry.telemetry_manager import PACKAGE_VERSION
from pipelex.tools.misc.file_utils import get_incremental_file_path
from pipelex.tools.misc.json_utils import JsonTypeError, load_json_dict_from_path, save_as_json_to_path
+COMMAND = "run"
+
def run_cmd(
target: Annotated[
@@ -105,7 +111,7 @@ def run_cmd(
async def run_pipeline(pipe_code: str | None = None, bundle_path: str | None = None):
# Initialize Pipelex
- Pipelex.make()
+ Pipelex.make(integration_mode=IntegrationMode.CLI)
source_description: str
if bundle_path:
try:
@@ -187,4 +193,8 @@ def run_cmd(
typer.secho(f"Failed to execute pipeline: {exc}", fg=typer.colors.RED, err=True)
raise typer.Exit(1) from exc
- asyncio.run(run_pipeline(pipe_code=pipe_code, bundle_path=bundle_path))
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.CLI_COMMAND, value=COMMAND)
+ asyncio.run(run_pipeline(pipe_code=pipe_code, bundle_path=bundle_path))
diff --git a/pipelex/cli/commands/show_cmd.py b/pipelex/cli/commands/show_cmd.py
index 5222e42b6..34e84d937 100644
--- a/pipelex/cli/commands/show_cmd.py
+++ b/pipelex/cli/commands/show_cmd.py
@@ -4,6 +4,7 @@ import asyncio
from typing import TYPE_CHECKING, Annotated, cast
import typer
+from posthog import new_context, tag
from rich import box
from rich.console import Console
from rich.table import Table
@@ -12,13 +13,22 @@ from pipelex import pretty_print
from pipelex.cogt.model_backends.backend_library import InferenceBackendLibrary
from pipelex.cogt.model_backends.model_lists import ModelLister
from pipelex.exceptions import PipelexCLIError, PipelexConfigError
-from pipelex.hub import get_models_manager, get_pipe_library, get_required_pipe
+from pipelex.hub import get_models_manager, get_pipe_library, get_required_pipe, get_telemetry_manager
from pipelex.pipelex import Pipelex
from pipelex.system.configuration.config_loader import config_manager
+from pipelex.system.runtime import IntegrationMode
+from pipelex.system.telemetry.events import EventName, EventProperty
+from pipelex.system.telemetry.telemetry_manager import PACKAGE_VERSION
if TYPE_CHECKING:
from pipelex.cogt.models.model_manager import ModelManager
+COMMAND = "show"
+SUB_COMMAND_PIPES = "pipes"
+SUB_COMMAND_PIPE = "pipe"
+SUB_COMMAND_MODELS = "models"
+SUB_COMMAND_BACKENDS = "backends"
+
def do_show_config() -> None:
"""Show the pipelex configuration."""
@@ -32,10 +42,9 @@ def do_show_config() -> None:
def do_list_pipes() -> None:
"""List all available pipes."""
- Pipelex.make()
-
try:
- get_pipe_library().pretty_list_pipes()
+ nb_pipes = get_pipe_library().pretty_list_pipes()
+ get_telemetry_manager().track_event(EventName.PIPES_LIST, properties={EventProperty.NB_PIPES: nb_pipes})
except Exception as exc:
msg = f"Failed to list pipes: {exc}"
raise PipelexCLIError(msg) from exc
@@ -43,15 +52,13 @@ def do_list_pipes() -> None:
def do_show_pipe(pipe_code: str) -> None:
"""Show a single pipe definition from the library."""
- Pipelex.make()
pipe = get_required_pipe(pipe_code=pipe_code)
+ get_telemetry_manager().track_event(EventName.PIPE_SHOW, properties={EventProperty.PIPE_TYPE: pipe.type})
pretty_print(pipe, title=f"Pipe '{pipe_code}'")
def do_show_backends(show_all: bool = False) -> None:
"""Display all backends and the active routing profile."""
- Pipelex.make()
-
try:
models_manager = cast("ModelManager", get_models_manager())
@@ -152,6 +159,7 @@ def do_show_backends(show_all: bool = False) -> None:
console.print("[dim]💡 To enable more backends, edit: [bold].pipelex/inference/backends.toml[/bold][/dim]")
console.print("[dim]💡 To list available models for a backend: [bold]pipelex show models <backend_name>[/bold][/dim]\n")
+ get_telemetry_manager().track_event(EventName.BACKENDS_SHOW, properties={EventProperty.NB_BACKENDS: len(all_backends)})
# Typer group for show commands
@@ -172,7 +180,14 @@ def list_pipes_cmd() -> None:
This includes pipes from your project's .plx files and any
pipes from imported packages.
"""
- do_list_pipes()
+ Pipelex.make(integration_mode=IntegrationMode.CLI)
+
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_PIPES}")
+
+ do_list_pipes()
@show_app.command("pipe", help="Display the detailed definition of a specific pipe")
@@ -185,7 +200,14 @@ def show_pipe_cmd(
Example:
pipelex show pipe hello_world
"""
- do_show_pipe(pipe_code=pipe_code)
+ Pipelex.make(integration_mode=IntegrationMode.CLI)
+
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_PIPE}")
+
+ do_show_pipe(pipe_code=pipe_code)
@show_app.command("models", help="List available AI models from a specific backend provider")
@@ -205,12 +227,18 @@ def show_models_cmd(
pipelex show models openai
pipelex show models anthropic --flat
"""
- asyncio.run(
- ModelLister.list_models(
- backend_name=backend_name,
- flat=flat,
+ Pipelex.make(integration_mode=IntegrationMode.CLI)
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_MODELS}")
+
+ asyncio.run(
+ ModelLister.list_models(
+ backend_name=backend_name,
+ flat=flat,
+ )
)
- )
@show_app.command("backends", help="Display backend configurations and active routing profile")
@@ -225,4 +253,10 @@ def show_backends_cmd(
pipelex show backends
pipelex show backends --all
"""
- do_show_backends(show_all=show_all_backends)
+ Pipelex.make(integration_mode=IntegrationMode.CLI)
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_BACKENDS}")
+
+ do_show_backends(show_all=show_all_backends)
diff --git a/pipelex/cli/commands/validate_cmd.py b/pipelex/cli/commands/validate_cmd.py
index 472277dcf..4a4e97248 100644
--- a/pipelex/cli/commands/validate_cmd.py
+++ b/pipelex/cli/commands/validate_cmd.py
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Annotated
import click
import typer
+from posthog import new_context, tag
from rich.console import Console
from rich.syntax import Syntax
@@ -13,21 +14,33 @@ from pipelex.builder.builder_errors import PipelexBundleError
from pipelex.builder.builder_validation import validate_dry_run_bundle_blueprint
from pipelex.core.interpreter import PipelexInterpreter
from pipelex.exceptions import LibraryLoadingError, PipeInputError
-from pipelex.hub import get_pipes, get_required_pipe
+from pipelex.hub import get_pipes, get_required_pipe, get_telemetry_manager
from pipelex.pipe_run.dry_run import dry_run_pipe, dry_run_pipes
from pipelex.pipelex import Pipelex
+from pipelex.system.runtime import IntegrationMode
+from pipelex.system.telemetry.events import EventName, EventProperty
+from pipelex.system.telemetry.telemetry_manager import PACKAGE_VERSION
if TYPE_CHECKING:
from pipelex.core.validation_errors import ValidationErrorDetailsProtocol
console = Console()
+COMMAND = "validate"
+
def do_validate_all_libraries_and_dry_run() -> None:
"""Validate libraries and dry-run all pipes."""
- pipelex_instance = Pipelex.make()
- pipelex_instance.validate_libraries()
- asyncio.run(dry_run_pipes(pipes=get_pipes(), raise_on_failure=True))
- log.info("Setup sequence passed OK, config and pipelines are validated.")
+ pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} all")
+
+ pipelex_instance.validate_libraries()
+ pipes = get_pipes()
+ get_telemetry_manager().track_event(EventName.PIPE_DRY_RUN, properties={EventProperty.NB_PIPES: len(pipes)})
+ asyncio.run(dry_run_pipes(pipes=pipes, raise_on_failure=True))
+ log.info("Setup sequence passed OK, config and pipelines are validated.")
def validate_cmd(
@@ -103,18 +116,14 @@ def validate_cmd(
raise typer.Exit(1)
async def validate_pipe(pipe_code: str | None = None, bundle_path: str | None = None):
- # Initialize Pipelex
- try:
- pipelex_instance = Pipelex.make()
- except LibraryLoadingError as library_loading_error:
- typer.secho(f"Failed to validate: {library_loading_error}", fg=typer.colors.RED, err=True)
- present_validation_error(details_provider=library_loading_error)
- raise typer.Exit(1) from library_loading_error
-
if bundle_path:
# When validating a bundle, load_pipe_from_bundle validates ALL pipes in the bundle
try:
bundle_blueprint = PipelexInterpreter.load_bundle_blueprint(bundle_path=bundle_path)
+ get_telemetry_manager().track_event(
+ EventName.BUNDLE_DRY_RUN,
+ properties={EventProperty.NB_PIPES: bundle_blueprint.nb_pipes, EventProperty.NB_CONCEPTS: bundle_blueprint.nb_concepts},
+ )
await validate_dry_run_bundle_blueprint(bundle_blueprint=bundle_blueprint)
if not pipe_code:
typer.secho(f"✅ Successfully validated all pipes in bundle '{bundle_path}'", fg=typer.colors.GREEN)
@@ -135,6 +144,9 @@ def validate_cmd(
elif pipe_code:
# Validate a single pipe by code
typer.echo(f"Validating pipe '{pipe_code}'...")
+ get_telemetry_manager().track_event(
+ EventName.PIPE_DRY_RUN, properties={EventProperty.PIPE_TYPE: get_required_pipe(pipe_code=pipe_code).type}
+ )
pipelex_instance.validate_libraries()
await dry_run_pipe(
get_required_pipe(pipe_code=pipe_code),
@@ -145,7 +157,23 @@ def validate_cmd(
typer.secho("Failed to validate: no pipe code or bundle specified", fg=typer.colors.RED, err=True)
raise typer.Exit(1)
- asyncio.run(validate_pipe(pipe_code=pipe_code, bundle_path=bundle_path))
+ # Initialize Pipelex
+ try:
+ pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
+ except LibraryLoadingError as library_loading_error:
+ typer.secho(f"Failed to validate: {library_loading_error}", fg=typer.colors.RED, err=True)
+ present_validation_error(details_provider=library_loading_error)
+ raise typer.Exit(1) from library_loading_error
+
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ if bundle_path:
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} bundle")
+ else:
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} pipe")
+
+ asyncio.run(validate_pipe(pipe_code=pipe_code, bundle_path=bundle_path))
def present_validation_error(details_provider: ValidationErrorDetailsProtocol):
diff --git a/pipelex/cogt/model_backends/model_lists.py b/pipelex/cogt/model_backends/model_lists.py
index 777571c18..c283ae6fe 100644
--- a/pipelex/cogt/model_backends/model_lists.py
+++ b/pipelex/cogt/model_backends/model_lists.py
@@ -18,7 +18,6 @@ if TYPE_CHECKING:
from pipelex.cogt.model_backends.backend import InferenceBackend
from pipelex.exceptions import PipelexCLIError
from pipelex.hub import get_models_manager
-from pipelex.pipelex import Pipelex
from pipelex.plugins.openai.openai_llms import openai_list_available_models
from pipelex.plugins.plugin_sdk_registry import Plugin
from pipelex.tools.aws.aws_config import AwsCredentialsError
@@ -39,8 +38,6 @@ class ModelLister:
backend_name: Name of the backend to list models for
flat: Whether to output in flat CSV format
"""
- Pipelex.make()
-
try:
backend = get_models_manager().get_required_inference_backend(backend_name)
except Exception as exc:
diff --git a/pipelex/core/bundles/pipelex_bundle_blueprint.py b/pipelex/core/bundles/pipelex_bundle_blueprint.py
index f55c599db..31cf0851c 100644
--- a/pipelex/core/bundles/pipelex_bundle_blueprint.py
+++ b/pipelex/core/bundles/pipelex_bundle_blueprint.py
@@ -54,3 +54,11 @@ class PipelexBundleBlueprint(BaseModel):
msg = f"Main pipe '{self.main_pipe}' could not be found in bundle spec"
raise PipelexBundleError(message=msg)
return self
+
+ @property
+ def nb_pipes(self) -> int:
+ return len(self.pipe) if self.pipe else 0
+
+ @property
+ def nb_concepts(self) -> int:
+ return len(self.concept) if self.concept else 0
diff --git a/pipelex/core/pipes/pipe_abstract.py b/pipelex/core/pipes/pipe_abstract.py
index ea2497967..bf7736bf8 100644
--- a/pipelex/core/pipes/pipe_abstract.py
+++ b/pipelex/core/pipes/pipe_abstract.py
@@ -24,6 +24,10 @@ class PipeAbstract(ABC, BaseModel):
inputs: InputRequirements = Field(default_factory=InputRequirements)
output: Concept
+ @property
+ def pipe_type(self) -> str:
+ return self.__class__.__name__
+
@field_validator("code", mode="before")
@classmethod
def validate_pipe_code_syntax(cls, code: str) -> str:
diff --git a/pipelex/core/pipes/pipe_library.py b/pipelex/core/pipes/pipe_library.py
index 9e07f0a09..d139d0206 100644
--- a/pipelex/core/pipes/pipe_library.py
+++ b/pipelex/core/pipes/pipe_library.py
@@ -89,7 +89,7 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):
self.root = {}
@override
- def pretty_list_pipes(self) -> None:
+ def pretty_list_pipes(self) -> int:
def _format_concept_code(concept_code: str | None, current_domain: str) -> str:
"""Format concept code by removing domain prefix if it matches current domain."""
if not concept_code:
@@ -145,3 +145,4 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):
}
pretty_print(table)
+ return len(pipes)
diff --git a/pipelex/core/pipes/pipe_library_abstract.py b/pipelex/core/pipes/pipe_library_abstract.py
index 434fae582..a33fc5f29 100644
--- a/pipelex/core/pipes/pipe_library_abstract.py
+++ b/pipelex/core/pipes/pipe_library_abstract.py
@@ -32,7 +32,7 @@ class PipeLibraryAbstract(ABC):
pass
@abstractmethod
- def pretty_list_pipes(self) -> None:
+ def pretty_list_pipes(self) -> int:
pass
@abstractmethod
diff --git a/pipelex/hub.py b/pipelex/hub.py
index 3662f9dc9..1af5c59b9 100644
--- a/pipelex/hub.py
+++ b/pipelex/hub.py
@@ -29,7 +29,6 @@ from pipelex.plugins.plugin_manager import PluginManager
from pipelex.reporting.reporting_protocol import ReportingProtocol
from pipelex.system.configuration.config_loader import config_manager
from pipelex.system.configuration.config_root import ConfigRoot
-from pipelex.system.telemetry.telemetry_config import TelemetryConfig
from pipelex.system.telemetry.telemetry_manager import TelemetryManagerAbstract
from pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract
from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract
@@ -326,10 +325,6 @@ def get_telemetry_manager() -> TelemetryManagerAbstract:
return get_pipelex_hub().get_telemetry_manager()
-def get_telemetry_config() -> TelemetryConfig:
- return get_telemetry_manager().get_telemetry_config()
-
-
# cogt
diff --git a/pipelex/kit/configs/inference/backends/azure_openai.toml b/pipelex/kit/configs/inference/backends/azure_openai.toml
index 26e01b4e1..5943007c4 100644
--- a/pipelex/kit/configs/inference/backends/azure_openai.toml
+++ b/pipelex/kit/configs/inference/backends/azure_openai.toml
@@ -96,3 +96,8 @@ inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
+[gpt-5]
+model_id = "gpt-5-2025-08-07"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
diff --git a/pipelex/kit/configs/inference/deck/base_deck.toml b/pipelex/kit/configs/inference/deck/base_deck.toml
index 7cfc55299..7a52ca603 100644
--- a/pipelex/kit/configs/inference/deck/base_deck.toml
+++ b/pipelex/kit/configs/inference/deck/base_deck.toml
@@ -66,7 +66,7 @@ llm_cheap = { model = "base-gemini", temperature = 0.1 }
# Generation skills
llm_for_factual_writing = { model = "base-gpt", temperature = 0.1 }
-llm_for_creative_writing = { model = "claude-4.5-sonnet", temperature = 0.9 }
+llm_for_creative_writing = { model = "base-gpt", temperature = 0.9 }
llm_to_write_questions = { model = "gpt-4o-mini", temperature = 0.3 }
# Reasoning skills
diff --git a/pipelex/kit/configs/telemetry.toml b/pipelex/kit/configs/telemetry.toml
index 067123595..bf3ea0e5b 100644
--- a/pipelex/kit/configs/telemetry.toml
+++ b/pipelex/kit/configs/telemetry.toml
@@ -1,8 +1,9 @@
-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
+geoip_enabled = true
+dry_mode_enabled = false
+verbose_enabled = false
user_id = ""
diff --git a/pipelex/pipe_run/pipe_job.py b/pipelex/pipe_run/pipe_job.py
index 0809850d4..7bd33cf65 100644
--- a/pipelex/pipe_run/pipe_job.py
+++ b/pipelex/pipe_run/pipe_job.py
@@ -12,3 +12,7 @@ class PipeJob(BaseModel):
pipe_run_params: PipeRunParams
job_metadata: JobMetadata
output_name: str | None = None
+
+ @property
+ def pipe_type(self) -> str:
+ return self.pipe.__class__.__name__
diff --git a/pipelex/pipelex.py b/pipelex/pipelex.py
index 545828323..978225131 100644
--- a/pipelex/pipelex.py
+++ b/pipelex/pipelex.py
@@ -1,3 +1,4 @@
+import os
from importlib.metadata import metadata
from typing import Any, cast
@@ -47,13 +48,17 @@ from pipelex.pipeline.track.pipeline_tracker_protocol import (
from pipelex.plugins.plugin_manager import PluginManager
from pipelex.reporting.reporting_manager import ReportingManager
from pipelex.reporting.reporting_protocol import ReportingNoOp, ReportingProtocol
+from pipelex.system.configuration.config_loader import config_manager
from pipelex.system.configuration.config_root import ConfigRoot
+from pipelex.system.environment import get_optional_env
from pipelex.system.registries.func_registry import func_registry
-from pipelex.system.runtime import runtime_manager
+from pipelex.system.runtime import IntegrationMode, 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 TelemetryManagerAbstract
+from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME, TelemetryConfig
+from pipelex.system.telemetry.telemetry_manager import DO_NOT_TRACK_ENV_VAR_KEY, TelemetryManager
+from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract, TelemetryManagerNoOp
from pipelex.test_extras.registry_test_models import TestRegistryModels
+from pipelex.tools.misc.toml_utils import load_toml_from_path
from pipelex.tools.secrets.env_secrets_provider import EnvSecretsProvider
from pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract
from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract
@@ -108,7 +113,7 @@ class Pipelex(metaclass=MetaSingleton):
self.pipelex_hub.set_library_manager(library_manager=self.library_manager)
self.reporting_delegate: ReportingProtocol | None = None
-
+ self.telemetry_manager: TelemetryManagerAbstract | None = None
# pipeline
self.pipeline_tracker: PipelineTrackerProtocol | None = None
@@ -142,6 +147,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
def setup(
self,
+ integration_mode: IntegrationMode,
class_registry: ClassRegistryAbstract | None = None,
secrets_provider: SecretsProviderAbstract | None = None,
storage_provider: StorageProviderAbstract | None = None,
@@ -152,6 +158,8 @@ 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,
+ force_enable_telemetry: bool = False,
+ telemetry_config: TelemetryConfig | None = None,
telemetry_manager: TelemetryManagerAbstract | None = None,
observers: dict[str, ObserverProtocol] | None = None,
**kwargs: Any,
@@ -244,11 +252,27 @@ 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())
- telemetry_manager = telemetry_manager or TelemetryManager()
- self.pipelex_hub.set_telemetry_manager(telemetry_manager=telemetry_manager)
+ if integration_mode.allows_telemetry() or force_enable_telemetry:
+ if not telemetry_config:
+ config_path = os.path.join(config_manager.pipelex_config_dir, TELEMETRY_CONFIG_FILE_NAME)
+ telemetry_config_toml = load_toml_from_path(path=config_path)
+ telemetry_config = TelemetryConfig.model_validate(telemetry_config_toml)
+
+ if telemetry_config.respect_dnt and (dnt := get_optional_env(DO_NOT_TRACK_ENV_VAR_KEY)) and dnt.lower() not in ["false", "0"]:
+ self.telemetry_manager = TelemetryManagerNoOp()
+ log.debug(f"Telemetry is disabled by env var 'DO_NOT_TRACK' which is set to {dnt}")
+ else:
+ self.telemetry_manager = telemetry_manager or TelemetryManager(telemetry_config=telemetry_config)
+ else:
+ self.telemetry_manager = TelemetryManagerNoOp()
+ log.debug(f"Telemetry is disabled because the integration mode '{integration_mode}' does not allow it")
+
+ self.telemetry_manager.setup(integration_mode=integration_mode)
+
+ self.pipelex_hub.set_telemetry_manager(telemetry_manager=self.telemetry_manager)
if not observers:
local_observer = LocalObserver()
- observer_telemetry = ObserverTelemetry(telemetry_manager=telemetry_manager)
+ observer_telemetry = ObserverTelemetry(telemetry_manager=self.telemetry_manager)
observers = {"local": local_observer, "telemetry": observer_telemetry}
multi_observer = MultiObserver(observers=observers)
self.pipelex_hub.set_observer(observer=multi_observer)
@@ -279,6 +303,8 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
self.pipeline_manager.teardown()
if self.pipeline_tracker:
self.pipeline_tracker.teardown()
+ if self.telemetry_manager:
+ self.telemetry_manager.teardown()
self.library_manager.teardown()
# cogt
@@ -302,6 +328,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
@classmethod
def make(
cls,
+ integration_mode: IntegrationMode = IntegrationMode.PYTHON,
class_registry: ClassRegistryAbstract | None = None,
secrets_provider: SecretsProviderAbstract | None = None,
storage_provider: StorageProviderAbstract | None = None,
@@ -312,6 +339,8 @@ 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,
+ force_enable_telemetry: bool = False,
+ telemetry_config: TelemetryConfig | None = None,
telemetry_manager: TelemetryManagerAbstract | None = None,
observers: dict[str, ObserverProtocol] | None = None,
**kwargs: Any,
@@ -323,6 +352,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
management, storage, model routing, and pipeline execution.
Args:
+ integration_mode: Integration mode (CLI, FASTAPI, DOCKER, MCP, N8N, PYTHON, PYTEST)
class_registry: Custom class registry for dynamic loading
secrets_provider: Custom secrets/credentials provider
storage_provider: Custom storage backend
@@ -333,6 +363,8 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
pipeline_tracker: Custom pipeline tracking/logging
pipe_router: Custom pipe routing logic
reporting_delegate: Custom reporting handler
+ force_enable_telemetry: Force enable telemetry even if the integration mode does not allow it
+ telemetry_config: Custom telemetry configuration
telemetry_manager: Custom telemetry manager
observers: Custom observers for pipeline events
**kwargs: Additional configuration options, only supported by your own subclass of Pipelex if you really need one
@@ -350,6 +382,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
pipelex_instance = cls()
pipelex_instance.setup(
+ integration_mode=integration_mode,
class_registry=class_registry,
secrets_provider=secrets_provider,
storage_provider=storage_provider,
@@ -360,6 +393,8 @@ 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,
+ force_enable_telemetry=force_enable_telemetry,
+ telemetry_config=telemetry_config,
telemetry_manager=telemetry_manager,
observers=observers,
**kwargs,
diff --git a/pipelex/pipeline/execute.py b/pipelex/pipeline/execute.py
index 274186dfc..4ca793adf 100644
--- a/pipelex/pipeline/execute.py
+++ b/pipelex/pipeline/execute.py
@@ -141,6 +141,7 @@ async def execute_pipeline(
properties = {
EventProperty.PIPELINE_RUN_ID: job_metadata.pipeline_run_id,
+ EventProperty.PIPE_TYPE: pipe.pipe_type,
}
get_telemetry_manager().track_event(event_name=EventName.PIPELINE_EXECUTE, properties=properties)
@@ -159,6 +160,7 @@ async def execute_pipeline(
get_library_manager().remove_from_blueprint(blueprint=blueprint)
properties = {
EventProperty.PIPELINE_RUN_ID: job_metadata.pipeline_run_id,
+ EventProperty.PIPE_TYPE: pipe.pipe_type,
EventProperty.PIPELINE_EXECUTE_OUTCOME: Outcome.SUCCESS,
}
get_telemetry_manager().track_event(event_name=EventName.PIPELINE_COMPLETE, properties=properties)
diff --git a/pipelex/system/runtime.py b/pipelex/system/runtime.py
index f23613e07..b2b4a1465 100644
--- a/pipelex/system/runtime.py
+++ b/pipelex/system/runtime.py
@@ -6,6 +6,33 @@ from pipelex.types import StrEnum
RUN_MODE_ENV_VAR_KEY = "RUN_MODE"
+class IntegrationMode(StrEnum):
+ CLI = "cli"
+ FASTAPI = "fastapi"
+ DOCKER = "docker"
+ MCP = "mcp"
+ N8N = "n8n"
+ PYTHON = "python"
+ PYTEST = "pytest"
+
+ def allows_telemetry(self) -> bool:
+ match self:
+ case IntegrationMode.CLI:
+ return True
+ case IntegrationMode.FASTAPI:
+ return True
+ case IntegrationMode.DOCKER:
+ return True
+ case IntegrationMode.MCP:
+ return True
+ case IntegrationMode.N8N:
+ return True
+ case IntegrationMode.PYTHON:
+ return False
+ case IntegrationMode.PYTEST:
+ return False
+
+
class RunMode(StrEnum):
NORMAL = "normal"
UNIT_TEST = "unit_test"
diff --git a/pipelex/system/telemetry/events.py b/pipelex/system/telemetry/events.py
index 22e13f5cf..2f8e7c708 100644
--- a/pipelex/system/telemetry/events.py
+++ b/pipelex/system/telemetry/events.py
@@ -2,23 +2,57 @@ from pipelex.types import StrEnum
class EventName(StrEnum):
+ # Settings
+ TELEMETRY_JUST_ENABLED = "telemetry_just_enabled"
+
+ # Show
+ BACKENDS_SHOW = "backends_show"
+
# Pipeline
PIPELINE_EXECUTE = "pipeline_execute"
PIPELINE_COMPLETE = "pipeline_complete"
# Pipe
+ PIPES_LIST = "pipes_list"
+ PIPE_SHOW = "pipe_show"
PIPE_RUN = "pipe_run"
PIPE_COMPLETE = "pipe_complete"
+ # Validation
+ BUNDLE_DRY_RUN = "bundle_dry_run"
+ PIPE_DRY_RUN = "pipe_dry_run"
+
+
+class Setting(StrEnum):
+ TELEMETRY_MODE = "telemetry_mode"
+
class EventProperty(StrEnum):
+ # Context
+ INTEGRATION = "integration"
+ PIPELEX_VERSION = "pipelex_version"
+ # Sub-context
+ CLI_COMMAND = "cli_command"
+ SETTING = "setting"
+
+ # Settings
+ TELEMETRY_MODE = "telemetry_mode"
+
+ # Show
+ NB_BACKENDS = "nb_backends"
+
# Pipeline
PIPELINE_RUN_ID = "pipeline_run_id"
PIPELINE_EXECUTE_OUTCOME = "pipeline_execute_outcome"
# Pipe
+ PIPE_TYPE = "pipe_type"
+ NB_PIPES = "nb_pipes"
PIPE_RUN_OUTCOME = "pipe_run_outcome"
+ # Bundle
+ NB_CONCEPTS = "nb_concepts"
+
class Outcome(StrEnum):
SUCCESS = "success"
diff --git a/pipelex/system/telemetry/observer_telemetry.py b/pipelex/system/telemetry/observer_telemetry.py
index 2176420ce..b358ec66f 100644
--- a/pipelex/system/telemetry/observer_telemetry.py
+++ b/pipelex/system/telemetry/observer_telemetry.py
@@ -11,15 +11,19 @@ class ObserverTelemetry(ObserverProtocol):
@override
async def observe_before_run(self, payload: PayloadType) -> None:
+ pipe_job = payload[PayloadKey.PIPE_JOB]
properties = {
EventProperty.PIPELINE_RUN_ID: payload[PayloadKey.PIPELINE_RUN_ID],
+ EventProperty.PIPE_TYPE: pipe_job.pipe_type,
}
self.telemetry_manager.track_event(event_name=EventName.PIPE_RUN, properties=properties)
@override
async def observe_after_successful_run(self, payload: PayloadType) -> None:
+ pipe_job = payload[PayloadKey.PIPE_JOB]
properties = {
EventProperty.PIPELINE_RUN_ID: payload[PayloadKey.PIPELINE_RUN_ID],
+ EventProperty.PIPE_TYPE: pipe_job.pipe_type,
EventProperty.PIPE_RUN_OUTCOME: Outcome.SUCCESS,
}
self.telemetry_manager.track_event(event_name=EventName.PIPE_COMPLETE, properties=properties)
@@ -29,8 +33,10 @@ class ObserverTelemetry(ObserverProtocol):
self,
payload: PayloadType,
) -> None:
+ pipe_job = payload[PayloadKey.PIPE_JOB]
properties = {
EventProperty.PIPELINE_RUN_ID: payload[PayloadKey.PIPELINE_RUN_ID],
+ EventProperty.PIPE_TYPE: pipe_job.pipe_type,
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.py
index 4429791d4..a607f5308 100644
--- a/pipelex/system/telemetry/telemetry_config.py
+++ b/pipelex/system/telemetry/telemetry_config.py
@@ -3,19 +3,32 @@ from pydantic import Field
from pipelex.system.configuration.config_model import ConfigModel
from pipelex.types import StrEnum
+TELEMETRY_CONFIG_FILE_NAME = "telemetry.toml"
+
class TelemetryMode(StrEnum):
OFF = "off"
ANONYMOUS = "anonymous"
IDENTIFIED = "identified"
+ @property
+ def is_enabled(self) -> bool:
+ match self:
+ case TelemetryMode.OFF:
+ return False
+ case TelemetryMode.ANONYMOUS:
+ return True
+ case TelemetryMode.IDENTIFIED:
+ return True
+
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
+ geoip_enabled: bool
+ dry_mode_enabled: bool
+ verbose_enabled: bool
user_id: str
diff --git a/pipelex/system/telemetry/telemetry_manager.py b/pipelex/system/telemetry/telemetry_manager.py
index 035502c8c..515fb678a 100644
--- a/pipelex/system/telemetry/telemetry_manager.py
+++ b/pipelex/system/telemetry/telemetry_manager.py
@@ -1,42 +1,105 @@
-import os
-from typing import Any
+from importlib.metadata import metadata
+from typing import Any, Callable
-from posthog import Posthog
-from typing_extensions import override
+import posthog
+from posthog import Posthog, new_context, tag
+from posthog.args import ExceptionArg, OptionalCaptureArgs
+from typing_extensions import Unpack, 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.exceptions import RootException
+from pipelex.system.runtime import IntegrationMode
+from pipelex.system.telemetry.events import EventName, EventProperty, Setting
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"
+PACKAGE_NAME = __name__.split(".", maxsplit=1)[0]
+PACKAGE_VERSION = metadata(PACKAGE_NAME)["Version"]
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)
+ PRIVACY_NOTICE = "[Privacy: exception message redacted]"
- @override
- def get_telemetry_config(self) -> TelemetryConfig:
- return self.telemetry_config
+ def __init__(self, telemetry_config: TelemetryConfig):
+ self.telemetry_config = telemetry_config
+
+ # Create PostHog client
+ self.posthog = Posthog(
+ project_api_key=self.telemetry_config.project_api_key,
+ host=self.telemetry_config.host,
+ disable_geoip=not self.telemetry_config.geoip_enabled,
+ debug=self.telemetry_config.verbose_enabled,
+ on_error=self._handle_transmission_error,
+ )
+
+ # Store original capture_exception method
+ self._original_capture_exception: Callable[..., Any] = self.posthog.capture_exception
+
+ # Wrap capture_exception to sanitize before sending
+ self._wrap_capture_exception()
+
+ posthog.privacy_mode = True
+ posthog.default_client = self.posthog
+
+ def _handle_transmission_error(self, error: Exception | None, _items: list[dict[str, Any]]) -> None:
+ """Handle errors that occur during telemetry transmission.
+
+ Args:
+ error: The transmission error that occurred
+ _items: List of telemetry items that failed to send
+ """
+ if error:
+ log.error(f"Telemetry transmission error: {error}")
+
+ def _wrap_capture_exception(self) -> None:
+ """Wrap the PostHog capture_exception method to sanitize exception messages."""
+
+ def sanitized_capture_exception(
+ exception: ExceptionArg | None = None,
+ **kwargs: Unpack[OptionalCaptureArgs],
+ ) -> Any:
+ """Capture exception with message sanitization for RootException subclasses."""
+ if exception and isinstance(exception, RootException):
+ # Create a new exception with sanitized message while preserving the class type
+ # Use __new__ to create an instance without calling __init__, which may require extra args
+ # This creates a "shell" instance with NO custom attributes (e.g., no tested_concept, wanted_concept, etc.)
+ exception_type = type(exception)
+ sanitized_exception = exception_type.__new__(exception_type)
+
+ # Set the exception args to our privacy notice
+ # This is what str(exception) will return
+ sanitized_exception.args = (self.PRIVACY_NOTICE,)
+
+ # Preserve the traceback so we still get stack trace information
+ if hasattr(exception, "__traceback__"):
+ sanitized_exception.__traceback__ = exception.__traceback__
+
+ # Note: No custom attributes (tested_concept, wanted_concept, etc.) are present
+ # because we used __new__() without calling __init__(). The __dict__ is already empty.
+
+ return self._original_capture_exception(sanitized_exception, **kwargs)
+ else:
+ # For non-RootException, capture as-is (or auto-detect current exception)
+ return self._original_capture_exception(exception, **kwargs)
+
+ # Replace the method
+ self.posthog.capture_exception = sanitized_capture_exception # type: ignore[method-assign]
@override
- def setup(self):
- pass
+ def setup(self, integration_mode: IntegrationMode):
+ if telemetry_mode := TelemetryManagerAbstract.telemetry_was_just_enabled():
+ with new_context():
+ tag(name=EventProperty.INTEGRATION, value=integration_mode)
+ tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)
+ tag(name=EventProperty.SETTING, value=Setting.TELEMETRY_MODE)
+ self.posthog.capture(
+ EventName.TELEMETRY_JUST_ENABLED,
+ properties={
+ EventProperty.TELEMETRY_MODE: telemetry_mode,
+ EventProperty.PIPELEX_VERSION: PACKAGE_VERSION,
+ },
+ )
@override
def teardown(self):
@@ -44,8 +107,6 @@ class TelemetryManager(TelemetryManagerAbstract):
@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
@@ -69,7 +130,7 @@ class TelemetryManager(TelemetryManagerAbstract):
def _track_anonymous_event(self, event_name: str, properties: dict[str, Any]):
if not self.posthog:
return
- if self.telemetry_config.debug:
+ if self.telemetry_config.dry_mode_enabled:
if properties:
log.debug(properties, title=f"Tracking anonymous event '{event_name}'. Properties")
else:
@@ -82,7 +143,7 @@ class TelemetryManager(TelemetryManagerAbstract):
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 self.telemetry_config.dry_mode_enabled:
if properties:
log.debug(properties, title=f"Tracking identified event '{event_name}'. Properties")
else:
diff --git a/pipelex/system/telemetry/telemetry_manager_abstract.py b/pipelex/system/telemetry/telemetry_manager_abstract.py
index eee06598a..529294468 100644
--- a/pipelex/system/telemetry/telemetry_manager_abstract.py
+++ b/pipelex/system/telemetry/telemetry_manager_abstract.py
@@ -1,23 +1,45 @@
from abc import ABC, abstractmethod
from typing import Any
+from typing_extensions import override
+
+from pipelex.system.runtime import IntegrationMode
from pipelex.system.telemetry.events import EventName, EventProperty
-from pipelex.system.telemetry.telemetry_config import TelemetryConfig
+from pipelex.system.telemetry.telemetry_config import TelemetryMode
class TelemetryManagerAbstract(ABC):
+ telemetry_mode_just_set: TelemetryMode | None = None
+
+ @classmethod
+ def telemetry_was_just_enabled(cls) -> TelemetryMode | None:
+ if cls.telemetry_mode_just_set is None:
+ return None
+ else:
+ return cls.telemetry_mode_just_set if cls.telemetry_mode_just_set.is_enabled else None
+
@abstractmethod
- def get_telemetry_config(self) -> TelemetryConfig:
+ def setup(self, integration_mode: IntegrationMode):
pass
@abstractmethod
- def setup(self):
+ def teardown(self):
pass
@abstractmethod
+ def track_event(self, event_name: EventName, properties: dict[EventProperty, Any] | None = None):
+ pass
+
+
+class TelemetryManagerNoOp(TelemetryManagerAbstract):
+ @override
+ def setup(self, integration_mode: IntegrationMode):
+ pass
+
+ @override
def teardown(self):
pass
- @abstractmethod
+ @override
def track_event(self, event_name: EventName, properties: dict[EventProperty, Any] | None = None):
pass
diff --git a/tests/conftest.py b/tests/conftest.py
index 0652aa35f..6bdc24aab 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -7,6 +7,7 @@ import pipelex.pipelex
from pipelex import log
from pipelex.config import get_config
from pipelex.hub import get_report_delegate
+from pipelex.system.runtime import IntegrationMode
pytest_plugins = [
"pipelex.test_extras.shared_pytest_plugins",
@@ -20,7 +21,7 @@ def reset_pipelex_config_fixture():
# Code to run before each test
Console().print("[magenta]pipelex setup[/magenta]")
try:
- pipelex_instance = pipelex.pipelex.Pipelex.make()
+ pipelex_instance = pipelex.pipelex.Pipelex.make(integration_mode=IntegrationMode.PYTEST)
config = get_config()
log.verbose(config, title="Test config")
assert isinstance(config, pipelex.config.PipelexConfig)