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/more remote config (#512)
Louis Choquelab615180715c
diff --git a/pipelex/cli/commands/doctor_cmd.py b/pipelex/cli/commands/doctor_cmd.pyindex 1311e69fc..c17567c12 100644--- a/pipelex/cli/commands/doctor_cmd.py+++ b/pipelex/cli/commands/doctor_cmd.py@@ -37,7 +37,7 @@ from pipelex.system.pipelex_service.pipelex_service_config import (is_pipelex_gateway_enabled,load_pipelex_service_config_if_exists,)-from pipelex.system.pipelex_service.remote_config import fetch_remote_config+from pipelex.system.pipelex_service.remote_config_fetcher import RemoteConfigFetcherfrom pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME, TelemetryConfigfrom pipelex.tools.misc.dict_utils import extract_vars_from_strings_recursivefrom pipelex.tools.misc.file_utils import path_exists@@ -608,7 +608,7 @@ def check_models() -> tuple[bool, str, dict[str, BackendFileReport]]:if not pipelex_service_config.agreement.terms_accepted:return False, "Pipelex Gateway is enabled but terms have not been accepted", backend_file_reportstry:- remote_config = fetch_remote_config()+ remote_config = RemoteConfigFetcher.fetch_remote_config()gateway_model_specs = remote_config.backend_model_specsexcept (RemoteConfigFetchError, RemoteConfigValidationError) as exc:return False, f"Failed to fetch Pipelex Gateway remote configuration: {exc}", backend_file_reportsdiff --git a/pipelex/pipelex.py b/pipelex/pipelex.pyindex 75cf4c7fb..1139cd688 100644--- a/pipelex/pipelex.py+++ b/pipelex/pipelex.py@@ -57,9 +57,7 @@ from pipelex.system.pipelex_service.pipelex_service_config import (is_pipelex_gateway_enabled,load_pipelex_service_config_if_exists,)-from pipelex.system.pipelex_service.remote_config import (- fetch_remote_config,-)+from pipelex.system.pipelex_service.remote_config_fetcher import RemoteConfigFetcherfrom pipelex.system.registries.func_registry import func_registryfrom pipelex.system.registries.singleton import MetaSingletonfrom pipelex.system.runtime import IntegrationMode, runtime_manager@@ -67,7 +65,7 @@ from pipelex.system.telemetry.observer_telemetry import ObserverTelemetryfrom pipelex.system.telemetry.telemetry_config import (TelemetryConfig,)-from pipelex.system.telemetry.telemetry_factory import make_telemetry_manager+from pipelex.system.telemetry.telemetry_factory import TelemetryFactoryfrom pipelex.system.telemetry.telemetry_manager_abstract import (TelemetryManagerAbstract,)@@ -81,6 +79,7 @@ from pipelex.urls import URLsif TYPE_CHECKING:from pipelex.cogt.model_backends.model_spec_factory import BackendModelSpecs+ from pipelex.system.pipelex_service.remote_config import RemoteConfigPACKAGE_NAME, PACKAGE_VERSION = get_package_info()@@ -182,6 +181,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.# for now the only servic is the Pipelex Gatewayis_pipelex_service_enabled = is_pipelex_gateway_enabled()+ remote_config: RemoteConfig | None = Nonegateway_model_specs: BackendModelSpecs | None = Noneif is_pipelex_service_enabled:# Skip terms check for CI mode - automated CI/CD pipelines don't require human consent@@ -191,13 +191,14 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.if pipelex_service_config is None or not pipelex_service_config.agreement.terms_accepted:raise GatewayTermsNotAcceptedError# Fetch remote configuration- remote_config = fetch_remote_config()+ remote_config = RemoteConfigFetcher.fetch_remote_config()log.verbose("Successfully fetched Pipelex Gateway remote configuration")gateway_model_specs = remote_config.backend_model_specs- self.telemetry_manager = make_telemetry_manager(+ self.telemetry_manager = TelemetryFactory.make_telemetry_manager(secrets_provider=secrets_provider,integration_mode=integration_mode,+ remote_config=remote_config,is_pipelex_telemetry_enabled=is_pipelex_service_enabled,telemetry_config=telemetry_config,injected_telemetry_manager=telemetry_manager,diff --git a/pipelex/system/pipelex_service/pipelex_details.py b/pipelex/system/pipelex_service/pipelex_details.pyindex f8b59e57a..cc54a3f10 100644--- a/pipelex/system/pipelex_service/pipelex_details.py+++ b/pipelex/system/pipelex_service/pipelex_details.py@@ -1,46 +1,9 @@-"""Embedded Pipelex credentials for internal services.--These credentials are used for:-1. Fetching remote configuration-2. Mandatory telemetry when using Pipelex Gateway--The PostHog project API key is write-only and used for event capture.-"""--import hashlib--# Environment variable name for Pipelex Gateway API key-PIPELEX_GATEWAY_API_KEY_VAR = "PIPELEX_GATEWAY_API_KEY"---def _hash_gateway_api_key(api_key: str, length: int) -> str:- """Hash the gateway API key using truncated SHA256 for use as PostHog distinct_id.-- Uses the first `length` characters of SHA256 hex digest, which provides- excellent collision resistance for practical purposes while being compact.-- Args:- api_key: The raw Pipelex Gateway API key.- length: The length of the hash to return.-- Returns:- First `length` characters of SHA256 hex digest.- """- return hashlib.sha256(api_key.encode("utf-8")).hexdigest()[:length]+from pipelex.tools.misc.hash_utils import hash_sha256class PipelexDetails:- """Base configuration for Pipelex's services."""-- # PostHog host for Pipelex services- POSTHOG_HOST = "https://eu.i.posthog.com"-- # Pipelex PostHog project API key (write-only, safe to embed)- # This is used for event capture only- POSTHOG_PROJECT_API_KEY = "phc_GXvlRgWMQ9c4xrxAMBsMeyOqHKyfSK0sAc2oEgu4jpT"-- # Public URL for remote gateway configuration (JSON file on S3)REMOTE_CONFIG_URL = "https://pipelex-config.s3.amazonaws.com/pipelex_remote_config.json"+ PIPELEX_GATEWAY_API_KEY_VAR = "PIPELEX_GATEWAY_API_KEY"@classmethoddef make_distinct_id(cls, gateway_api_key: str) -> str:@@ -52,4 +15,4 @@ class PipelexDetails:Returns:First 16 characters of SHA256 hex digest."""- return _hash_gateway_api_key(gateway_api_key, length=16)+ return hash_sha256(string=gateway_api_key, length=16)diff --git a/pipelex/system/pipelex_service/pipelex_service_agreement.py b/pipelex/system/pipelex_service/pipelex_service_agreement.pyindex de0ff5689..94b7784a7 100644--- a/pipelex/system/pipelex_service/pipelex_service_agreement.py+++ b/pipelex/system/pipelex_service/pipelex_service_agreement.py@@ -1,5 +1,3 @@-"""Configuration model for Pipelex managed services."""-import osfrom pydantic import Fielddiff --git a/pipelex/system/pipelex_service/pipelex_service_config.py b/pipelex/system/pipelex_service/pipelex_service_config.pyindex a09fbb619..7efceb098 100644--- a/pipelex/system/pipelex_service/pipelex_service_config.py+++ b/pipelex/system/pipelex_service/pipelex_service_config.py@@ -1,5 +1,3 @@-"""Configuration model for Pipelex managed services."""-import osfrom typing import Any, castdiff --git a/pipelex/system/pipelex_service/remote_config.py b/pipelex/system/pipelex_service/remote_config.pyindex d48299595..a7c8f454e 100644--- a/pipelex/system/pipelex_service/remote_config.py+++ b/pipelex/system/pipelex_service/remote_config.py@@ -1,98 +1,19 @@-import httpx-from pydantic import BaseModel, Field, ValidationError-from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential+from pydantic import BaseModel, ConfigDict, Field-from pipelex import logfrom pipelex.cogt.model_backends.model_spec_factory import BackendModelSpecs-from pipelex.system.pipelex_service.exceptions import (- RemoteConfigFetchError,- RemoteConfigValidationError,-)-from pipelex.system.pipelex_service.pipelex_details import PipelexDetails-from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error-# Retry configuration for remote config fetch-# Using hardcoded values since this runs before config is fully loaded-_FETCH_MAX_RETRIES = 5-_FETCH_WAIT_MULTIPLIER = 1-_FETCH_WAIT_MIN = 1-_FETCH_WAIT_MAX = 10-_FETCH_TIMEOUT = 10.0+class PipelexPosthogConfig(BaseModel):+ model_config = ConfigDict(extra="allow")-class RemoteConfig(BaseModel):- backend_model_specs: BackendModelSpecs = Field(description="Model specifications for Pipelex Gateway (model_name -> spec dict)")---def _log_retry_attempt(retry_state: RetryCallState) -> None:- """Log retry attempts for remote config fetch."""- exc = retry_state.outcome.exception() if retry_state.outcome else None- log.verbose(f"Remote config fetch attempt {retry_state.attempt_number} failed: {exc}. Retrying...")---@retry(- retry=retry_if_exception_type((httpx.TimeoutException, httpx.RequestError)),- stop=stop_after_attempt(_FETCH_MAX_RETRIES),- wait=wait_exponential(multiplier=_FETCH_WAIT_MULTIPLIER, min=_FETCH_WAIT_MIN, max=_FETCH_WAIT_MAX),- before_sleep=_log_retry_attempt,- reraise=True,-)-def _fetch_remote_config_with_retry(url: str) -> httpx.Response:- """Fetch remote config with retry logic for transient network errors.-- Args:- url: The URL to fetch the configuration from.-- Returns:- The HTTP response.+ project_api_key: str = Field(description="Posthog project API key")+ endpoint: str = Field(description="Posthog endpoint URL")+ is_geoip_enabled: bool = Field(description="Enable GeoIP lookup")+ is_debug_enabled: bool = Field(description="Enable PostHog debug mode")- Raises:- httpx.TimeoutException: If the request times out after all retries.- httpx.RequestError: If a network error occurs after all retries.- httpx.HTTPStatusError: If the server returns an error status (not retried).- """- response = httpx.get(url, timeout=_FETCH_TIMEOUT, follow_redirects=True)- response.raise_for_status()- return response+class RemoteConfig(BaseModel):+ model_config = ConfigDict(extra="allow")-def fetch_remote_config() -> RemoteConfig:- """Fetch Pipelex Service remote configuration.-- Returns:- RemoteConfig.-- Raises:- RemoteConfigFetchError: If the HTTP request fails or returns an error.- RemoteConfigValidationError: If the JSON doesn't match expected schema.- """- url = PipelexDetails.REMOTE_CONFIG_URL-- try:- response = _fetch_remote_config_with_retry(url)- except httpx.TimeoutException as exc:- msg = f"Timeout while fetching remote configuration from {url}: {exc}"- raise RemoteConfigFetchError(msg) from exc- except httpx.HTTPStatusError as exc:- msg = f"HTTP error {exc.response.status_code} while fetching remote configuration from {url}"- raise RemoteConfigFetchError(msg) from exc- except httpx.RequestError as exc:- msg = f"Failed to fetch remote configuration from {url} after {_FETCH_MAX_RETRIES} attempts: {exc}"- raise RemoteConfigFetchError(msg) from exc-- # Parse JSON content- try:- config_dict = response.json()- except Exception as exc:- msg = f"Failed to parse remote configuration JSON: {exc}"- raise RemoteConfigValidationError(msg) from exc-- # Validate the structure- try:- config = RemoteConfig.model_validate(config_dict)- except ValidationError as exc:- validation_error_msg = format_pydantic_validation_error(exc)- msg = f"Remote configuration validation failed: {validation_error_msg}"- raise RemoteConfigValidationError(msg) from exc-- return config+ posthog: PipelexPosthogConfig = Field(description="Posthog configuration")+ backend_model_specs: BackendModelSpecs = Field(description="Model specifications for Pipelex Gateway (model_name -> spec dict)")diff --git a/pipelex/system/pipelex_service/remote_config_fetcher.py b/pipelex/system/pipelex_service/remote_config_fetcher.pynew file mode 100644index 000000000..ad0748e4a--- /dev/null+++ b/pipelex/system/pipelex_service/remote_config_fetcher.py@@ -0,0 +1,102 @@+import httpx+from pydantic import ValidationError+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential++from pipelex import log+from pipelex.system.pipelex_service.exceptions import (+ RemoteConfigFetchError,+ RemoteConfigValidationError,+)+from pipelex.system.pipelex_service.pipelex_details import PipelexDetails+from pipelex.system.pipelex_service.remote_config import RemoteConfig+from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error+++class RemoteConfigFetcher:+ """Fetches Pipelex Service remote configuration with retry logic."""++ # Retry configuration for remote config fetch+ # Using hardcoded values since this runs before config is fully loaded+ FETCH_MAX_RETRIES = 5+ FETCH_WAIT_MULTIPLIER = 1+ FETCH_WAIT_MIN = 1+ FETCH_WAIT_MAX = 10+ FETCH_TIMEOUT = 10.0++ @classmethod+ def _log_retry_attempt(cls, retry_state: RetryCallState) -> None:+ """Log retry attempts for remote config fetch."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ log.verbose(f"Remote config fetch attempt {retry_state.attempt_number} failed: {exc}. Retrying...")++ @classmethod+ def _fetch_remote_config_with_retry(cls, url: str) -> httpx.Response:+ """Fetch remote config with retry logic for transient network errors.++ Args:+ url: The URL to fetch the configuration from.++ Returns:+ The HTTP response.++ Raises:+ httpx.TimeoutException: If the request times out after all retries.+ httpx.RequestError: If a network error occurs after all retries.+ httpx.HTTPStatusError: If the server returns an error status (not retried).+ """++ @retry(+ retry=retry_if_exception_type((httpx.TimeoutException, httpx.RequestError)),+ stop=stop_after_attempt(cls.FETCH_MAX_RETRIES),+ wait=wait_exponential(multiplier=cls.FETCH_WAIT_MULTIPLIER, min=cls.FETCH_WAIT_MIN, max=cls.FETCH_WAIT_MAX),+ before_sleep=cls._log_retry_attempt,+ reraise=True,+ )+ def _fetch_with_retry(url: str) -> httpx.Response:+ response = httpx.get(url, timeout=cls.FETCH_TIMEOUT, follow_redirects=True)+ response.raise_for_status()+ return response++ return _fetch_with_retry(url)++ @classmethod+ def fetch_remote_config(cls) -> RemoteConfig:+ """Fetch Pipelex Service remote configuration.++ Returns:+ RemoteConfig.++ Raises:+ RemoteConfigFetchError: If the HTTP request fails or returns an error.+ RemoteConfigValidationError: If the JSON doesn't match expected schema.+ """+ url = PipelexDetails.REMOTE_CONFIG_URL++ try:+ response = cls._fetch_remote_config_with_retry(url)+ except httpx.TimeoutException as exc:+ msg = f"Timeout while fetching remote configuration from {url}: {exc}"+ raise RemoteConfigFetchError(msg) from exc+ except httpx.HTTPStatusError as exc:+ msg = f"HTTP error {exc.response.status_code} while fetching remote configuration from {url}"+ raise RemoteConfigFetchError(msg) from exc+ except httpx.RequestError as exc:+ msg = f"Failed to fetch remote configuration from {url} after {cls.FETCH_MAX_RETRIES} attempts: {exc}"+ raise RemoteConfigFetchError(msg) from exc++ # Parse JSON content+ try:+ config_dict = response.json()+ except Exception as exc:+ msg = f"Failed to parse remote configuration JSON: {exc}"+ raise RemoteConfigValidationError(msg) from exc++ # Validate the structure+ try:+ config = RemoteConfig.model_validate(config_dict)+ except ValidationError as exc:+ validation_error_msg = format_pydantic_validation_error(exc)+ msg = f"Remote configuration validation failed: {validation_error_msg}"+ raise RemoteConfigValidationError(msg) from exc++ return configdiff --git a/pipelex/system/telemetry/otel_factory.py b/pipelex/system/telemetry/otel_factory.pyindex f2ce8cc1a..22dacd476 100644--- a/pipelex/system/telemetry/otel_factory.py+++ b/pipelex/system/telemetry/otel_factory.py@@ -25,6 +25,7 @@ from pipelex.system.telemetry.otel_constants import OTelConstantsfrom pipelex.system.telemetry.posthog_span_exporter import PostHogSpanExporterfrom pipelex.system.telemetry.telemetry_config import LangfuseConfig, OtlpExporterConfig, TelemetryRedactionConfigfrom pipelex.tools.log.log import log+from pipelex.tools.misc.hash_utils import hash_md5_to_intfrom pipelex.tools.misc.json_utils import JsonContent, pure_json_strfrom pipelex.tools.misc.package_utils import get_package_version@@ -127,7 +128,7 @@ class OtelFactory:Returns:A 128-bit integer suitable for use as an OTel trace ID."""- return int(hashlib.md5(pipeline_run_id.encode("utf-8")).hexdigest(), 16) # noqa: S324+ return hash_md5_to_int(pipeline_run_id)@classmethoddef make_trace_names(cls, pipeline_run_id: str, pipe_code: str) -> tuple[str, str]:diff --git a/pipelex/system/telemetry/telemetry_factory.py b/pipelex/system/telemetry/telemetry_factory.pyindex 46bb25df6..963e15bab 100644--- a/pipelex/system/telemetry/telemetry_factory.py+++ b/pipelex/system/telemetry/telemetry_factory.py@@ -8,7 +8,8 @@ from pipelex.system.pipelex_service.exceptions import (GatewayDoNotTrackConflictError,GatewayTelemetryManagerInjectedError,)-from pipelex.system.pipelex_service.pipelex_details import PIPELEX_GATEWAY_API_KEY_VAR+from pipelex.system.pipelex_service.pipelex_details import PipelexDetails+from pipelex.system.pipelex_service.remote_config import RemoteConfigfrom pipelex.system.runtime import IntegrationModefrom pipelex.system.telemetry.otel_constants import OTelConstantsfrom pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME, PostHogMode, TelemetryConfig, load_telemetry_config@@ -17,66 +18,74 @@ from pipelex.system.telemetry.telemetry_manager_abstract import (TelemetryManagerAbstract,TelemetryManagerNoOp,)+from pipelex.tools.secrets.secrets_errors import SecretNotFoundErrorfrom pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract-def make_telemetry_manager(- secrets_provider: SecretsProviderAbstract,- integration_mode: IntegrationMode,- is_pipelex_telemetry_enabled: bool,- telemetry_config: TelemetryConfig | None,- injected_telemetry_manager: TelemetryManagerAbstract | None,-) -> TelemetryManagerAbstract:- gateway_api_key: str | None = None- if is_pipelex_telemetry_enabled:- # Cannot inject custom TelemetryManager when gateway is enabled- if injected_telemetry_manager is not None:- raise GatewayTelemetryManagerInjectedError+class TelemetryFactory:+ @classmethod+ def make_telemetry_manager(+ cls,+ secrets_provider: SecretsProviderAbstract,+ integration_mode: IntegrationMode,+ remote_config: RemoteConfig | None,+ is_pipelex_telemetry_enabled: bool = False,+ telemetry_config: TelemetryConfig | None = None,+ injected_telemetry_manager: TelemetryManagerAbstract | None = None,+ ) -> TelemetryManagerAbstract:+ gateway_api_key: str | None = None+ if is_pipelex_telemetry_enabled:+ # Cannot inject custom TelemetryManager when gateway is enabled+ if injected_telemetry_manager is not None:+ raise GatewayTelemetryManagerInjectedError- # Get gateway API key for telemetry distinct_id- gateway_api_key = secrets_provider.get_optional_secret(PIPELEX_GATEWAY_API_KEY_VAR)- if not gateway_api_key:- raise GatewayApiKeyMissingError+ # Get gateway API key for telemetry distinct_id+ try:+ gateway_api_key = secrets_provider.get_required_secret(PipelexDetails.PIPELEX_GATEWAY_API_KEY_VAR)+ except SecretNotFoundError as exc:+ raise GatewayApiKeyMissingError from exc- # Always load telemetry config first to determine allowed modes- if not telemetry_config:- telemetry_config_path = os.path.join(config_manager.pipelex_config_dir, TELEMETRY_CONFIG_FILE_NAME)- telemetry_config = load_telemetry_config(path=telemetry_config_path, secrets_provider=secrets_provider)+ # Always load telemetry config first to determine allowed modes+ if not telemetry_config:+ telemetry_config_path = os.path.join(config_manager.pipelex_config_dir, TELEMETRY_CONFIG_FILE_NAME)+ telemetry_config = load_telemetry_config(path=telemetry_config_path, secrets_provider=secrets_provider)- allows_custom_telemetry = telemetry_config.is_custom_telemetry_allowed_for_mode(integration_mode)+ allows_custom_telemetry = telemetry_config.is_custom_telemetry_allowed_for_mode(integration_mode)- chosen_telemetry_manager: TelemetryManagerAbstract- if allows_custom_telemetry or is_pipelex_telemetry_enabled:- # Always respect DO_NOT_TRACK env var- if is_env_var_truthy(OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY):- if is_pipelex_telemetry_enabled:- # Gateway requires telemetry but DNT is set - we respect DNT- raise GatewayDoNotTrackConflictError(dnt_env_var=OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY)- chosen_telemetry_manager = TelemetryManagerNoOp()- log.debug(f"Telemetry is disabled by env var '{OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY}'")- return chosen_telemetry_manager-- match telemetry_config.posthog.mode:- case PostHogMode.OFF:+ chosen_telemetry_manager: TelemetryManagerAbstract+ if allows_custom_telemetry or is_pipelex_telemetry_enabled:+ # Always respect DO_NOT_TRACK env var+ if is_env_var_truthy(OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY):if is_pipelex_telemetry_enabled:- # Gateway requires telemetry - create manager with only Pipelex telemetry- chosen_telemetry_manager = TelemetryManager(+ # Gateway requires telemetry but DNT is set - we respect DNT+ raise GatewayDoNotTrackConflictError(dnt_env_var=OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY)+ chosen_telemetry_manager = TelemetryManagerNoOp()+ log.debug(f"Telemetry is disabled by env var '{OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY}'")+ return chosen_telemetry_manager++ match telemetry_config.posthog.mode:+ case PostHogMode.OFF:+ if is_pipelex_telemetry_enabled:+ # Gateway requires telemetry - create manager with only Pipelex telemetry+ chosen_telemetry_manager = TelemetryManager(+ telemetry_config=telemetry_config,+ remote_config=remote_config,+ pipelex_telemetry_enabled=True,+ gateway_api_key=gateway_api_key,+ )+ log.debug("Custom telemetry is off, but Pipelex Gateway telemetry is enabled")+ else:+ chosen_telemetry_manager = TelemetryManagerNoOp()+ log.debug("Telemetry is disabled because posthog.mode is set to 'off'")+ case PostHogMode.ANONYMOUS | PostHogMode.IDENTIFIED:+ chosen_telemetry_manager = injected_telemetry_manager or TelemetryManager(telemetry_config=telemetry_config,- pipelex_telemetry_enabled=True,+ remote_config=remote_config,+ pipelex_telemetry_enabled=is_pipelex_telemetry_enabled,gateway_api_key=gateway_api_key,)- log.debug("Custom telemetry is off, but Pipelex Gateway telemetry is enabled")- else:- chosen_telemetry_manager = TelemetryManagerNoOp()- log.debug("Telemetry is disabled because posthog.mode is set to 'off'")- case PostHogMode.ANONYMOUS | PostHogMode.IDENTIFIED:- chosen_telemetry_manager = injected_telemetry_manager or TelemetryManager(- telemetry_config=telemetry_config,- pipelex_telemetry_enabled=is_pipelex_telemetry_enabled,- gateway_api_key=gateway_api_key,- )- else:- chosen_telemetry_manager = TelemetryManagerNoOp()- log.verbose(f"Telemetry is disabled because the integration mode '{integration_mode}' does not allow it")+ else:+ chosen_telemetry_manager = TelemetryManagerNoOp()+ log.verbose(f"Telemetry is disabled because the integration mode '{integration_mode}' does not allow it")- return chosen_telemetry_manager+ return chosen_telemetry_managerdiff --git a/pipelex/system/telemetry/telemetry_manager.py b/pipelex/system/telemetry/telemetry_manager.pyindex 7aacd9f7d..d939dca37 100644--- a/pipelex/system/telemetry/telemetry_manager.py+++ b/pipelex/system/telemetry/telemetry_manager.py@@ -7,10 +7,12 @@ from posthog import Posthog, new_context # type: ignore[attr-defined]from posthog.args import ExceptionArg, OptionalCaptureArgsfrom typing_extensions import Unpack, override+from pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.plugins.portkey.portkey_constants import PortkeyEnvVarfrom pipelex.system.environment import is_env_var_truthyfrom pipelex.system.exceptions import PipelexErrorfrom pipelex.system.pipelex_service.pipelex_details import PipelexDetails+from pipelex.system.pipelex_service.remote_config import RemoteConfigfrom pipelex.system.runtime import IntegrationModefrom pipelex.system.telemetry.events import EventName, EventPropertyfrom pipelex.system.telemetry.otel_constants import OTelConstants, PostHogAttr, PostHogEvent@@ -29,6 +31,7 @@ class TelemetryManager(TelemetryManagerAbstract):def __init__(self,telemetry_config: TelemetryConfig,+ remote_config: RemoteConfig | None,pipelex_telemetry_enabled: bool = False,gateway_api_key: str | None = None,):@@ -36,6 +39,7 @@ class TelemetryManager(TelemetryManagerAbstract):Args:telemetry_config: User's telemetry configuration.+ remote_config: Remote configuration for Pipelex Service (including telemetry).pipelex_telemetry_enabled: Whether Pipelex internal telemetry is enabled (for gateway).gateway_api_key: The user's Pipelex Gateway API key (required if pipelex_telemetry_enabled)."""@@ -59,11 +63,15 @@ class TelemetryManager(TelemetryManagerAbstract):if pipelex_telemetry_enabled:if gateway_api_key:self._pipelex_distinct_id = PipelexDetails.make_distinct_id(gateway_api_key)+ if not remote_config:+ msg = "Pipelex Gateway telemetry is enabled but remote config is not set"+ raise PipelexUnexpectedError(msg)+ pipelex_posthog_config = remote_config.posthogself.pipelex_posthog_client = Posthog(- project_api_key=PipelexDetails.POSTHOG_PROJECT_API_KEY,- host=PipelexDetails.POSTHOG_HOST,- disable_geoip=False, # GeoIP enabled for Pipelex telemetry- debug=self.telemetry_config.posthog.debug,+ project_api_key=pipelex_posthog_config.project_api_key,+ host=pipelex_posthog_config.endpoint,+ disable_geoip=not pipelex_posthog_config.is_geoip_enabled,+ debug=pipelex_posthog_config.is_debug_enabled,on_error=self._handle_pipelex_transmission_error,)log.verbose("Pipelex Gateway telemetry enabled")diff --git a/pipelex/tools/misc/hash_utils.py b/pipelex/tools/misc/hash_utils.pynew file mode 100644index 000000000..dfdaeace2--- /dev/null+++ b/pipelex/tools/misc/hash_utils.py@@ -0,0 +1,35 @@+import hashlib+++def hash_sha256(string: str, length: int | None = None) -> str:+ """Hash the string using truncated SHA256.++ Uses the first `length` characters of SHA256 hex digest, which provides+ collision resistance for practical purposes while being compact.++ Args:+ string: The string to hash.+ length: The length of the hash to return.++ Returns:+ First `length` characters of SHA256 hex digest if length is provided, otherwise the full hash.+ """+ the_hash = hashlib.sha256(string.encode("utf-8")).hexdigest()+ if length is not None:+ return the_hash[:length]+ return the_hash+++def hash_md5_to_int(string: str) -> int:+ """Convert a string to an integer using MD5 hash (deterministic).++ Uses MD5 hash to generate a consistent integer from the input string.+ This is useful for creating deterministic numeric identifiers from strings.++ Args:+ string: The string to hash.++ Returns:+ A 128-bit integer derived from the MD5 hash of the input string.+ """+ return int(hashlib.md5(string.encode("utf-8")).hexdigest(), 16) # noqa: S324diff --git a/tests/unit/pipelex/system/pipelex_service/test_remote_config.py b/tests/unit/pipelex/system/pipelex_service/test_remote_config.pynew file mode 100644index 000000000..dc24d2b8b--- /dev/null+++ b/tests/unit/pipelex/system/pipelex_service/test_remote_config.py@@ -0,0 +1,46 @@+import pytest+from pydantic import ValidationError++from pipelex.system.pipelex_service.remote_config import RemoteConfig+++class TestRemoteConfig:+ """Tests for GatewayRemoteConfig model."""++ def test_remote_config_valid(self) -> None:+ """Test creating a valid GatewayRemoteConfig."""+ payload = {+ "backend_model_specs": {+ "defaults": {"sdk": "gateway_completions"},+ "gpt-4o": {"model_id": "gpt-4o-2024-11-20"},+ },+ "posthog": {+ "project_api_key": "test-project-api-key",+ "endpoint": "https://test-endpoint.com",+ "is_geoip_enabled": True,+ "is_debug_enabled": False,+ },+ }+ config = RemoteConfig.model_validate(payload)+ assert "defaults" in config.backend_model_specs+ assert "gpt-4o" in config.backend_model_specs++ def test_remote_config_missing_backend_fails(self) -> None:+ """Test that missing backend key raises validation error."""+ payload = {"other_key": "value"}+ with pytest.raises(ValidationError):+ RemoteConfig.model_validate(payload)++ def test_remote_config_empty_backend(self) -> None:+ """Test GatewayRemoteConfig with empty backend dict."""+ payload = {+ "backend_model_specs": {},+ "posthog": {+ "project_api_key": "test-project-api-key",+ "endpoint": "https://test-endpoint.com",+ "is_geoip_enabled": True,+ "is_debug_enabled": False,+ },+ }+ config = RemoteConfig.model_validate(payload)+ assert config.backend_model_specs == {}diff --git a/tests/unit/pipelex/system/pipelex_service/test_remote_config_provider.py b/tests/unit/pipelex/system/pipelex_service/test_remote_config_provider.pydeleted file mode 100644index e3b4f1ecb..000000000--- a/tests/unit/pipelex/system/pipelex_service/test_remote_config_provider.py+++ /dev/null@@ -1,69 +0,0 @@-"""Unit tests for remote config provider."""--import hashlib--import pytest-from pydantic import ValidationError--from pipelex.system.pipelex_service.remote_config import RemoteConfig---class TestGatewayRemoteConfig:- """Tests for GatewayRemoteConfig model."""-- def test_gateway_remote_config_valid(self) -> None:- """Test creating a valid GatewayRemoteConfig."""- payload = {- "backend_model_specs": {- "defaults": {"sdk": "gateway_completions"},- "gpt-4o": {"model_id": "gpt-4o-2024-11-20"},- }- }- config = RemoteConfig.model_validate(payload)- assert "defaults" in config.backend_model_specs- assert "gpt-4o" in config.backend_model_specs-- def test_gateway_remote_config_missing_backend_fails(self) -> None:- """Test that missing backend key raises validation error."""- payload = {"other_key": "value"}- with pytest.raises(ValidationError):- RemoteConfig.model_validate(payload)-- def test_gateway_remote_config_empty_backend(self) -> None:- """Test GatewayRemoteConfig with empty backend dict."""- payload: dict[str, dict[str, str]] = {"backend_model_specs": {}}- config = RemoteConfig.model_validate(payload)- assert config.backend_model_specs == {}---class TestApiKeyHashing:- """Tests for API key hashing functionality.-- The hash is used as distinct_id for Pipelex PostHog telemetry.- """-- @staticmethod- def _hash_api_key(api_key: str) -> str:- """Hash the API key using truncated SHA256 - same logic as hash_gateway_api_key."""- return hashlib.sha256(api_key.encode("utf-8")).hexdigest()[:16]-- def test_hash_api_key_deterministic(self) -> None:- """Test that API key hashing is deterministic."""- api_key = "test-api-key-123"- hash1 = self._hash_api_key(api_key)- hash2 = self._hash_api_key(api_key)- assert hash1 == hash2-- def test_hash_api_key_different_keys(self) -> None:- """Test that different API keys produce different hashes."""- hash1 = self._hash_api_key("key1")- hash2 = self._hash_api_key("key2")- assert hash1 != hash2-- def test_hash_api_key_is_truncated_sha256(self) -> None:- """Test that hash is 16 characters (truncated SHA256 hex)."""- api_key = "test-key"- hashed = self._hash_api_key(api_key)- assert len(hashed) == 16- # Verify it's a valid hex string- int(hashed, 16)diff --git a/tests/unit/pipelex/tools/misc/test_hash_md5.py b/tests/unit/pipelex/tools/misc/test_hash_md5.pynew file mode 100644index 000000000..f90b540bb--- /dev/null+++ b/tests/unit/pipelex/tools/misc/test_hash_md5.py@@ -0,0 +1,36 @@+import pytest++from pipelex.tools.misc.hash_utils import hash_md5_to_int+++class TestHashMd5ToInt:+ @pytest.mark.parametrize(+ ("input_string", "expected"),+ [+ # Known MD5 hashes converted to int+ ("hello", 0x5D41402ABC4B2A76B9719D911017C592),+ ("", 0xD41D8CD98F00B204E9800998ECF8427E),+ ("test", 0x098F6BCD4621D373CADE4E832627B4F6),+ ],+ )+ def test_hash_md5_to_int(self, input_string: str, expected: int) -> None:+ """Test MD5 hashing produces expected integer values."""+ assert hash_md5_to_int(input_string) == expected++ def test_hash_md5_to_int_deterministic(self) -> None:+ """Test that the same input always produces the same output."""+ input_string = "deterministic_test"+ result1 = hash_md5_to_int(input_string)+ result2 = hash_md5_to_int(input_string)+ assert result1 == result2++ def test_hash_md5_to_int_different_inputs_produce_different_values(self) -> None:+ """Test that different inputs produce different integer values."""+ int1 = hash_md5_to_int("input_a")+ int2 = hash_md5_to_int("input_b")+ assert int1 != int2++ def test_hash_md5_to_int_is_128_bit(self) -> None:+ """Test that the result is a 128-bit integer (MD5 produces 128 bits)."""+ result = hash_md5_to_int("any_input")+ assert 0 <= result < 2**128diff --git a/tests/unit/pipelex/tools/misc/test_hash_sha256.py b/tests/unit/pipelex/tools/misc/test_hash_sha256.pynew file mode 100644index 000000000..257aceb38--- /dev/null+++ b/tests/unit/pipelex/tools/misc/test_hash_sha256.py@@ -0,0 +1,44 @@+import pytest++from pipelex.tools.misc.hash_utils import hash_sha256+++class TestHashSha256:+ @pytest.mark.parametrize(+ ("input_string", "length", "expected"),+ [+ # Known SHA256 hashes (first N chars)+ ("hello", None, "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"),+ ("hello", 8, "2cf24dba"),+ ("hello", 16, "2cf24dba5fb0a30e"),+ ("hello", 64, "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"),+ # Empty string+ ("", None, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"),+ ("", 8, "e3b0c442"),+ # Short length+ ("test", 1, "9"),+ # Zero length edge case+ ("test", 0, ""),+ ],+ )+ def test_hash_sha256(self, input_string: str, length: int | None, expected: str) -> None:+ """Test SHA256 hashing with various inputs and truncation lengths."""+ assert hash_sha256(input_string, length) == expected++ def test_hash_sha256_deterministic(self) -> None:+ """Test that the same input always produces the same output."""+ input_string = "deterministic_test"+ result1 = hash_sha256(input_string)+ result2 = hash_sha256(input_string)+ assert result1 == result2++ def test_hash_sha256_different_inputs_produce_different_hashes(self) -> None:+ """Test that different inputs produce different hashes."""+ hash1 = hash_sha256("input_a")+ hash2 = hash_sha256("input_b")+ assert hash1 != hash2++ def test_hash_sha256_full_length_is_64_chars(self) -> None:+ """Test that full SHA256 hex digest is 64 characters."""+ result = hash_sha256("any_input")+ assert len(result) == 64