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.

feature/JSONContent (#452)

Thomas Hebrarddd0c9d26623f
diff --git a/.pipelex/inference/deck/base_deck.toml b/.pipelex/inference/deck/base_deck.toml
index be034698e..954a65d57 100644
--- a/.pipelex/inference/deck/base_deck.toml
+++ b/.pipelex/inference/deck/base_deck.toml
@@ -44,7 +44,6 @@ fast-img-gen = "fast-lightning-sdxl"
[waterfalls]
smart_llm = [
- "llama-3.3-70b-versatile",
"claude-4.5-sonnet",
"claude-4.1-opus",
"claude-4-sonnet",
@@ -128,7 +127,7 @@ llm_to_prompt_img_gen = { model = "base-claude", temperature = 0.2 }
llm_to_prompt_img_gen_cheap = { model = "gpt-4o-mini", temperature = 0.5 }
# Groq-specific presets (fast inference, low cost)
-llm_groq_fast_text = { model = "fast-groq", temperature = 0.2 }
+llm_groq_fast_text = { model = "fast-groq", temperature = 0.7 }
llm_groq_balanced = { model = "base-groq", temperature = 0.5 }
llm_groq_vision = { model = "vision-groq", temperature = 0.3 }
diff --git a/.pipelex/pipelex.toml b/.pipelex/pipelex.toml
index b6e4fc791..4a164cd80 100644
--- a/.pipelex/pipelex.toml
+++ b/.pipelex/pipelex.toml
@@ -52,6 +52,10 @@ excluded_dirs = [
[pipelex.log_config]
default_log_level = "INFO"
+# Uncomment to log to stderr instead of stdout
+# console_log_target = "stderr"
+# console_print_target = "stderr"
+
[pipelex.log_config.package_log_levels]
pipelex = "INFO"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a1d1a871d..2bde10241 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,12 @@
- **Groq plugin**: Dedicated `pipelex/plugins/groq` plugin removed (now uses standard `openai` SDK).
- **Global instructor config**: Global `is_openai_structured_output_enabled` setting, replaced by per-model `structure_method` approach.
+## Unrelease
+
+### Added
+
+- JSONContent to have as inputs and outputs of pipe unknown JSON format
+
## [v0.15.4] - 2025-11-12
### Added
diff --git a/docs/home/6-build-reliable-ai-workflows/concepts/native-concepts.md b/docs/home/6-build-reliable-ai-workflows/concepts/native-concepts.md
index 2c86ab14a..995154387 100644
--- a/docs/home/6-build-reliable-ai-workflows/concepts/native-concepts.md
+++ b/docs/home/6-build-reliable-ai-workflows/concepts/native-concepts.md
@@ -28,6 +28,7 @@ Here are all the native concepts you can use out of the box:
| `Number` | A number | `NumberContent` |
| `Page` | A document page with text, images, and optional page view | `PageContent` |
| `Dynamic` | A dynamic concept that adapts to context | `DynamicContent` |
+| `JSON` | A JSON object | `JSONContent` |
| `Anything` | Any type of content | *No specific implementation* |
## Native Concept Structures
@@ -131,6 +132,15 @@ class DynamicContent(StuffContent):
**Use for:** Workflows where the content structure isn't known in advance.
+### JSONContent
+
+A concept that represents a JSON object. This enables pipes to receive as input or to output any JSON object.
+
+```python
+class JSONContent(StuffContent):
+ json_obj: dict[str, Any]
+```
+
### Anything
!!! note "Special Concepts"
diff --git a/pipelex/builder/builder_loop.py b/pipelex/builder/builder_loop.py
index 29e69128f..070fbcb80 100644
--- a/pipelex/builder/builder_loop.py
+++ b/pipelex/builder/builder_loop.py
@@ -1,5 +1,3 @@
-from rich.console import Console
-
from pipelex import log, pretty_print
from pipelex.builder.builder import (
PipelexBundleSpec,
@@ -17,7 +15,7 @@ from pipelex.client.protocol import PipelineInputs
from pipelex.core.memory.exceptions import WorkingMemoryStuffNotFoundError
from pipelex.core.pipes.exceptions import StaticValidationErrorType
from pipelex.core.pipes.pipe_blueprint import AllowedPipeCategories
-from pipelex.hub import get_required_pipe
+from pipelex.hub import get_console, get_required_pipe
from pipelex.language.plx_factory import PlxFactory
from pipelex.pipeline.exceptions import PipelineExecutionError
from pipelex.pipeline.execute import execute_pipeline
@@ -42,7 +40,7 @@ class BuilderLoop:
)
except PipelineExecutionError as exc:
msg = f"Builder loop: Failed to execute pipeline: {exc}."
- console = Console(stderr=True)
+ console = get_console()
console.print_exception()
raise PipeBuilderError(message=msg) from exc
diff --git a/pipelex/cli/_cli.py b/pipelex/cli/_cli.py
index 6cf96874a..26034ccb6 100644
--- a/pipelex/cli/_cli.py
+++ b/pipelex/cli/_cli.py
@@ -2,7 +2,6 @@ from typing import Annotated
import typer
from click import Command, Context
-from rich.console import Console
from typer.core import TyperGroup
from typing_extensions import override
@@ -15,6 +14,7 @@ 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.cli.readiness import check_readiness
+from pipelex.hub import get_console
from pipelex.tools.misc.package_utils import get_package_version
@@ -49,7 +49,7 @@ app = typer.Typer(
@app.callback(invoke_without_command=True)
def app_callback(ctx: typer.Context) -> None:
- console = Console()
+ console = get_console()
package_version = get_package_version()
console.print(
f"""
diff --git a/pipelex/cli/commands/build_cmd.py b/pipelex/cli/commands/build_cmd.py
index cdc08465b..a85cc05c7 100644
--- a/pipelex/cli/commands/build_cmd.py
+++ b/pipelex/cli/commands/build_cmd.py
@@ -6,7 +6,6 @@ from typing import TYPE_CHECKING, Annotated
import click
import typer
from posthog import tag
-from rich.console import Console
from pipelex import pretty_print
from pipelex.builder.builder import PipelexBundleSpec, load_and_validate_bundle
@@ -24,7 +23,7 @@ from pipelex.cli.error_handlers import (
from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.config import get_config
from pipelex.core.pipes.exceptions import PipeInputError, PipeOperatorModelChoiceError
-from pipelex.hub import get_report_delegate, get_required_pipe, get_telemetry_manager
+from pipelex.hub import get_console, get_report_delegate, get_required_pipe, get_telemetry_manager
from pipelex.language.plx_factory import PlxFactory
from pipelex.libraries.exceptions import LibraryLoadingError
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
@@ -65,10 +64,7 @@ pipelex build pipe "Take a CV and Job offer in PDF, analyze if they match and ge
pipelex build pipe \
"Take a Job offer text and a bunch of CVs (PDF), analyze how each CV matches the Job offer and generate 5 questions for each interview"
-pipelex build partial "Given an expense report, apply company rules" -o results/generated.json
-pipelex build flow "Given an expense report, apply company rules" -o results/flow.json
-
-Other ideas:
+# Other ideas:
pipelex build pipe "Take a photo as input, and render the opposite of the photo, don't structure anything, use only text content, be super concise"
pipelex build pipe "Take a photo as input, and render the opposite of the photo"
pipelex build pipe "Given an RDFP PDF, build a compliance matrix"
@@ -223,7 +219,7 @@ def build_pipe_cmd(
get_report_delegate().generate_report()
# Show how to run the pipe
- console = Console()
+ console = get_console()
console.print("\n๐Ÿ“‹ [cyan]To run your pipeline:[/cyan]")
console.print(f" [cyan]โ€ข Execute the runner:[/cyan] python {runner_path}")
console.print(f" [cyan]โ€ข Or use CLI:[/cyan] pipelex run {main_pipe_code} --inputs {inputs_json_path}\n")
diff --git a/pipelex/cli/commands/doctor_cmd.py b/pipelex/cli/commands/doctor_cmd.py
index 7f32f4ec9..5acda2810 100644
--- a/pipelex/cli/commands/doctor_cmd.py
+++ b/pipelex/cli/commands/doctor_cmd.py
@@ -9,7 +9,6 @@ from pathlib import Path
from typing import Any
from pydantic import BaseModel, ValidationError
-from rich.console import Console
from rich.panel import Panel
from rich.prompt import Confirm
from rich.text import Text
@@ -24,7 +23,7 @@ from pipelex.cogt.model_backends.backend_library import BackendCredentialsReport
from pipelex.cogt.models.model_manager import ModelManager
from pipelex.config import PipelexConfig, get_config
from pipelex.core.validation import report_validation_error
-from pipelex.hub import PipelexHub, set_pipelex_hub
+from pipelex.hub import PipelexHub, get_console, set_pipelex_hub
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.system.configuration.config_loader import config_manager
from pipelex.system.environment import get_optional_env
@@ -339,7 +338,6 @@ def check_backend_files() -> tuple[bool, dict[str, BackendFileReport], str]:
def display_health_report(
- console: Console,
config_healthy: bool,
config_message: str,
config_missing_count: int,
@@ -384,6 +382,7 @@ def display_health_report(
border_style="cyan" if all_healthy else "yellow",
padding=(1, 2),
)
+ console = get_console()
console.print()
console.print(status_panel)
console.print()
@@ -610,10 +609,9 @@ def doctor_cmd(
Args:
fix: If True, offer to fix detected issues interactively
"""
- console = Console()
- do_doctor_cmd(console=console, fix=fix)
+ console = get_console()
try:
- do_doctor_cmd(console=console, fix=fix)
+ do_doctor_cmd(fix=fix)
except Exception as exc:
# Handle unexpected errors gracefully without printing traces
@@ -628,13 +626,11 @@ def doctor_cmd(
def do_doctor_cmd(
- console: Console,
fix: bool = False,
) -> None:
"""Check Pipelex configuration health and suggest fixes.
Args:
- console: Rich Console instance for output
fix: If True, offer to fix detected issues interactively
"""
# Run health checks
@@ -645,7 +641,6 @@ def do_doctor_cmd(
# Display report
display_health_report(
- console=console,
config_healthy=config_healthy,
config_message=config_message,
config_missing_count=config_missing_count,
@@ -687,6 +682,7 @@ def do_doctor_cmd(
# If --fix flag is provided, offer to fix auto-fixable issues
if fix and has_auto_fixable_issues:
+ console = get_console()
console.print("[bold yellow]Interactive Fix Mode[/bold yellow]")
console.print()
@@ -739,6 +735,7 @@ def do_doctor_cmd(
# Handle issues that can't be auto-fixed
if has_config_validation_error or has_telemetry_validation_error or has_backend_credential_issues:
+ console = get_console()
console.print("[bold yellow]Manual Fixes Required[/bold yellow]")
console.print()
diff --git a/pipelex/cli/commands/init/backends.py b/pipelex/cli/commands/init/backends.py
index e0d9b4423..e4451ef35 100644
--- a/pipelex/cli/commands/init/backends.py
+++ b/pipelex/cli/commands/init/backends.py
@@ -3,8 +3,6 @@
import os
from typing import Any
-from rich.console import Console
-
from pipelex.cli.commands.init.ui.backends_ui import (
build_backend_selection_panel,
display_selected_backends,
@@ -12,6 +10,7 @@ from pipelex.cli.commands.init.ui.backends_ui import (
get_currently_enabled_backends,
prompt_backend_indices,
)
+from pipelex.hub import get_console
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.system.configuration.config_loader import config_manager
from pipelex.tools.misc.file_utils import path_exists
@@ -65,7 +64,7 @@ def get_selected_backend_keys(backends_toml_path: str) -> list[str]:
def customize_backends_config() -> None:
"""Interactively customize which inference backends are enabled in backends.toml."""
- console = Console()
+ console = get_console()
backends_toml_path = os.path.join(config_manager.pipelex_config_dir, "inference", "backends.toml")
template_backends_path = os.path.join(str(get_kit_configs_dir()), "inference", "backends.toml")
diff --git a/pipelex/cli/commands/init/command.py b/pipelex/cli/commands/init/command.py
index 41b9707a0..8fb0addf5 100644
--- a/pipelex/cli/commands/init/command.py
+++ b/pipelex/cli/commands/init/command.py
@@ -13,6 +13,7 @@ from pipelex.cli.commands.init.routing import customize_routing_profile
from pipelex.cli.commands.init.telemetry import setup_telemetry
from pipelex.cli.commands.init.ui.general_ui import build_initialization_panel, display_already_configured_message
from pipelex.cli.commands.init.ui.types import InitFocus
+from pipelex.hub import get_console
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.system.configuration.config_loader import config_manager
from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME
@@ -240,7 +241,7 @@ def init_cmd(
skip_confirmation: If True, skip the confirmation prompt (used when called from doctor --fix)
silent: If True, suppress all output when everything is already configured
"""
- console = Console()
+ console = get_console()
pipelex_config_dir = config_manager.pipelex_config_dir
telemetry_config_path = os.path.join(pipelex_config_dir, TELEMETRY_CONFIG_FILE_NAME)
backends_toml_path = os.path.join(pipelex_config_dir, "inference", "backends.toml")
diff --git a/pipelex/cli/commands/init/routing.py b/pipelex/cli/commands/init/routing.py
index cb0504e17..0b8c158fa 100644
--- a/pipelex/cli/commands/init/routing.py
+++ b/pipelex/cli/commands/init/routing.py
@@ -3,7 +3,6 @@
import os
from typing import Any
-from rich.console import Console
from rich.prompt import Confirm
from tomlkit import table
@@ -15,6 +14,7 @@ from pipelex.cli.commands.init.ui.routing_ui import (
prompt_fallback_order,
prompt_primary_backend,
)
+from pipelex.hub import get_console
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.system.configuration.config_loader import config_manager
from pipelex.tools.misc.file_utils import path_exists
@@ -27,7 +27,7 @@ def customize_routing_profile(selected_backend_keys: list[str]) -> None:
Args:
selected_backend_keys: List of backend keys that are enabled.
"""
- console = Console()
+ console = get_console()
routing_profiles_toml_path = os.path.join(config_manager.pipelex_config_dir, "inference", "routing_profiles.toml")
template_routing_path = os.path.join(str(get_kit_configs_dir()), "inference", "routing_profiles.toml")
backends_toml_path = os.path.join(config_manager.pipelex_config_dir, "inference", "backends.toml")
diff --git a/pipelex/cli/commands/run_cmd.py b/pipelex/cli/commands/run_cmd.py
index 872469d6e..828cc4d82 100644
--- a/pipelex/cli/commands/run_cmd.py
+++ b/pipelex/cli/commands/run_cmd.py
@@ -7,7 +7,6 @@ from typing import Annotated
import click
import typer
from posthog import tag
-from rich.console import Console
from pipelex import log
from pipelex.builder.builder import load_and_validate_bundle
@@ -21,7 +20,7 @@ from pipelex.cli.error_handlers import (
)
from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.core.pipes.exceptions import PipeInputError, PipeOperatorModelChoiceError
-from pipelex.hub import get_telemetry_manager
+from pipelex.hub import get_console, get_telemetry_manager
from pipelex.libraries.exceptions import LibraryLoadingError
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
from pipelex.pipelex import Pipelex
@@ -224,7 +223,7 @@ def run_cmd(
except Exception as exc:
log.error(f"Error executing pipeline: {exc}")
- console = Console(stderr=True)
+ console = get_console()
console.print("\n[bold red]Failed to execute pipeline[/bold red]\n")
console.print_exception(show_locals=True)
raise typer.Exit(1) from exc
diff --git a/pipelex/cli/commands/show_cmd.py b/pipelex/cli/commands/show_cmd.py
index db0f93d2a..e63f67754 100644
--- a/pipelex/cli/commands/show_cmd.py
+++ b/pipelex/cli/commands/show_cmd.py
@@ -6,7 +6,6 @@ from typing import TYPE_CHECKING, Annotated, cast
import typer
from posthog import tag
from rich import box
-from rich.console import Console
from rich.table import Table
from pipelex import pretty_print
@@ -21,7 +20,7 @@ from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.cogt.model_backends.backend_library import InferenceBackendLibrary
from pipelex.cogt.model_backends.model_lists import ModelLister
from pipelex.config import ConfigPaths
-from pipelex.hub import get_models_manager, get_pipe_library, get_required_pipe, get_secrets_provider, get_telemetry_manager
+from pipelex.hub import get_console, get_models_manager, get_pipe_library, get_required_pipe, get_secrets_provider, get_telemetry_manager
from pipelex.libraries.exceptions import LibraryLoadingError
from pipelex.pipelex import Pipelex
from pipelex.system.configuration.config_loader import config_manager
@@ -89,7 +88,7 @@ def do_show_backends(show_all: bool = False) -> None:
msg = f"Error accessing backend or routing configuration: {exc}"
raise PipelexCLIError(msg) from exc
- console = Console()
+ console = get_console()
# Get all backends
all_backends = list(backend_library.root.values())
diff --git a/pipelex/cli/commands/validate_cmd.py b/pipelex/cli/commands/validate_cmd.py
index c55051890..fa54b461f 100644
--- a/pipelex/cli/commands/validate_cmd.py
+++ b/pipelex/cli/commands/validate_cmd.py
@@ -7,7 +7,6 @@ from typing import TYPE_CHECKING, Annotated
import click
import typer
from posthog import tag
-from rich.console import Console
from rich.traceback import Traceback
from pipelex import log
@@ -23,7 +22,7 @@ from pipelex.cli.error_handlers import (
from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.core.interpreter import PipelexInterpreter
from pipelex.core.pipes.exceptions import PipeInputError, PipeOperatorModelChoiceError
-from pipelex.hub import get_library_manager, get_pipes, get_required_pipe, get_telemetry_manager
+from pipelex.hub import get_console, get_library_manager, get_pipes, get_required_pipe, get_telemetry_manager
from pipelex.libraries.exceptions import LibraryLoadingError
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
from pipelex.pipe_run.dry_run import dry_run_pipe, dry_run_pipes
@@ -35,8 +34,6 @@ from pipelex.tools.misc.package_utils import get_package_version
if TYPE_CHECKING:
from pipelex.core.pipes.pipe_abstract import PipeAbstract
-console = Console()
-
COMMAND = "validate"
@@ -168,14 +165,14 @@ def validate_cmd(
else:
typer.secho(f"โœ… Successfully validated all pipes in bundle '{bundle_path}' (including '{pipe_code}')", fg=typer.colors.GREEN)
except FileNotFoundError as exc:
- console.print(Traceback())
+ get_console().print(Traceback())
typer.secho(f"Failed to load bundle '{bundle_path}':", fg=typer.colors.RED, err=True)
raise typer.Exit(1) from exc
except PipelexBundleError as bundle_error:
- console.print(Traceback())
+ get_console().print(Traceback())
handle_validation_error(exc=bundle_error, context=ErrorContext.VALIDATION)
except PipeInputError as exc:
- console.print(Traceback())
+ get_console().print(Traceback())
typer.secho(f"\nโŒ Failed to validate bundle '{bundle_path}':", fg=typer.colors.RED, err=True)
raise typer.Exit(1) from exc
elif pipe_code:
diff --git a/pipelex/cli/error_handlers.py b/pipelex/cli/error_handlers.py
index b9327363f..2e54ba2c1 100644
--- a/pipelex/cli/error_handlers.py
+++ b/pipelex/cli/error_handlers.py
@@ -1,12 +1,12 @@
from typing import NoReturn
import typer
-from rich.console import Console
from rich.syntax import Syntax
from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.core.concepts.exceptions import PipelexValidationExceptionAbstract
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
+from pipelex.hub import get_console
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
from pipelex.types import StrEnum
from pipelex.urls import URLs
@@ -39,7 +39,7 @@ def handle_model_choice_error(exc: PipeOperatorModelChoiceError, context: ErrorC
exc: The model choice error exception
context: Context for the error message
"""
- console = Console(stderr=True)
+ console = get_console()
console.print(f"\n[bold red]โŒ {context} failed because of a model choice could not be interpreted correctly[/bold red]\n")
console.print(f"[bold cyan]Pipe:[/bold cyan] [yellow]'{exc.pipe_code}'[/yellow] [dim]({exc.pipe_type})[/dim]")
console.print(f"[bold cyan]Model Type:[/bold cyan] [yellow]'{exc.model_type}'[/yellow]")
@@ -61,7 +61,7 @@ def handle_model_availability_error(exc: PipeOperatorModelAvailabilityError, con
exc: The model availability error exception
context: Context for the error message
"""
- console = Console(stderr=True)
+ console = get_console()
console.print(f"\n[bold red]โŒ {context} failed because a model wasn't available[/bold red]\n")
console.print(f"[bold cyan]Pipe:[/bold cyan] [yellow]'{exc.pipe_code}'[/yellow] [dim]({exc.pipe_type})[/dim]")
console.print(f"[bold cyan]Model:[/bold cyan] [yellow]'{exc.model_handle}'[/yellow]")
@@ -88,7 +88,7 @@ def handle_model_deck_preset_error(exc: ModelDeckPresetValidatonError, context:
exc: The model deck preset validation error exception
context: Context for the error message
"""
- console = Console(stderr=True)
+ console = get_console()
console.print(f"\n[bold red]โŒ {context} failed due to model deck preset validation error[/bold red]\n")
console.print(f"[bold cyan]Preset ID:[/bold cyan] [yellow]'{exc.preset_id}'[/yellow]")
console.print(f"[bold cyan]Model Type:[/bold cyan] [yellow]'{exc.model_type}'[/yellow]")
@@ -121,7 +121,7 @@ def handle_validation_error(exc: PipelexValidationExceptionAbstract, context: Er
exc: The validation error exception (implements ValidationErrorDetailsProtocol)
context: Context for the error message
"""
- console = Console(stderr=True)
+ console = get_console()
console.print(f"\n[bold red]โŒ {context} failed due to validation error[/bold red]\n")
console.print(f"[bold red]Error:[/bold red] {exc}\n")
diff --git a/pipelex/cli/readiness.py b/pipelex/cli/readiness.py
index c2a283c57..646f36f60 100644
--- a/pipelex/cli/readiness.py
+++ b/pipelex/cli/readiness.py
@@ -6,10 +6,9 @@ import os
import sys
from pathlib import Path
-from rich.console import Console
-
import pipelex
from pipelex.cli.exceptions import ReadinessCheckError
+from pipelex.hub import get_console
def _is_in_virtual_environment() -> bool:
@@ -75,7 +74,7 @@ def check_readiness() -> None:
"""
# Then check virtual environment requirement for development installs
if _is_development_install() and not _is_in_virtual_environment():
- console = Console(stderr=True)
+ console = get_console()
console.print("\n[bold red]โŒ Virtual Environment Required (Development Mode)[/bold red]\n")
console.print("[yellow]Pipelex is running in development mode but no virtual environment is active.[/yellow]\n")
diff --git a/pipelex/cogt/model_backends/model_lists.py b/pipelex/cogt/model_backends/model_lists.py
index e2c3b11b7..ddccdcf5a 100644
--- a/pipelex/cogt/model_backends/model_lists.py
+++ b/pipelex/cogt/model_backends/model_lists.py
@@ -5,11 +5,11 @@ from datetime import datetime
from typing import TYPE_CHECKING, Any
from rich import box
-from rich.console import Console
from rich.table import Table
from pipelex.cogt.exceptions import MissingDependencyError
from pipelex.config import get_config
+from pipelex.hub import get_console
if TYPE_CHECKING:
from anthropic.types import ModelInfo
@@ -45,8 +45,6 @@ class ModelLister:
# TODO: This should not raise this error in here.
raise PipelexCLIError(msg) from exc
- console = Console()
-
# Determine which SDKs are used in this backend
if not backend.model_specs:
msg = f"Backend '{backend_name}' has no model specifications"
@@ -73,7 +71,6 @@ class ModelLister:
sdk=sdk,
backend_name=backend_name,
backend=backend,
- console=console,
flat=flat,
any_listed=any_listed,
)
@@ -101,7 +98,6 @@ class ModelLister:
sdk=sdk,
backend_name=backend_name,
backend=backend,
- console=console,
flat=flat,
any_listed=any_listed,
)
@@ -128,7 +124,6 @@ class ModelLister:
cls._list_mistral_models(
sdk=sdk,
backend_name=backend_name,
- console=console,
flat=flat,
any_listed=any_listed,
)
@@ -149,7 +144,6 @@ class ModelLister:
sdk=sdk,
backend_name=backend_name,
backend=backend,
- console=console,
flat=flat,
any_listed=any_listed,
)
@@ -172,7 +166,6 @@ class ModelLister:
unsupported_sdks=unsupported_sdks,
backend_name=backend_name,
models_by_sdk=models_by_sdk,
- console=console,
flat=flat,
)
@@ -182,7 +175,6 @@ class ModelLister:
sdk: str,
backend_name: str,
backend: InferenceBackend,
- console: Console,
flat: bool,
any_listed: bool,
) -> None:
@@ -198,7 +190,6 @@ class ModelLister:
models=openai_models,
sdk=sdk,
backend_name=backend_name,
- console=console,
any_listed=any_listed,
)
else:
@@ -206,7 +197,6 @@ class ModelLister:
models=openai_models,
sdk=sdk,
backend_name=backend_name,
- console=console,
)
@classmethod
@@ -215,7 +205,6 @@ class ModelLister:
sdk: str,
backend_name: str,
backend: InferenceBackend,
- console: Console,
flat: bool,
any_listed: bool,
) -> None:
@@ -250,7 +239,6 @@ class ModelLister:
models=anthropic_models,
sdk=sdk,
backend_name=backend_name,
- console=console,
any_listed=any_listed,
)
else:
@@ -258,7 +246,6 @@ class ModelLister:
models=anthropic_models,
sdk=sdk,
backend_name=backend_name,
- console=console,
)
except AuthenticationError as auth_exc:
msg = f"Authentication error for SDK '{sdk}' in backend '{backend_name}': {auth_exc}"
@@ -269,7 +256,6 @@ class ModelLister:
cls,
sdk: str,
backend_name: str,
- console: Console,
flat: bool,
any_listed: bool,
) -> None:
@@ -297,7 +283,6 @@ class ModelLister:
models=mistral_models,
sdk=sdk,
backend_name=backend_name,
- console=console,
any_listed=any_listed,
)
else:
@@ -305,7 +290,6 @@ class ModelLister:
models=mistral_models,
sdk=sdk,
backend_name=backend_name,
- console=console,
)
@classmethod
@@ -314,7 +298,6 @@ class ModelLister:
sdk: str,
backend_name: str,
backend: InferenceBackend,
- console: Console,
flat: bool,
any_listed: bool,
) -> None:
@@ -354,7 +337,6 @@ class ModelLister:
sdk=sdk,
backend_name=backend_name,
aws_region=aws_region,
- console=console,
any_listed=any_listed,
)
else:
@@ -362,7 +344,6 @@ class ModelLister:
models=bedrock_models_list,
sdk=sdk,
aws_region=aws_region,
- console=console,
)
except Exception as exc:
@@ -374,10 +355,10 @@ class ModelLister:
models: list[Model],
sdk: str,
backend_name: str,
- console: Console,
any_listed: bool,
) -> None:
"""Display OpenAI models in CSV format."""
+ console = get_console()
if not any_listed:
console.print("model_id,created,owned_by,sdk,backend")
for model in models:
@@ -394,7 +375,6 @@ class ModelLister:
models: list[Model],
sdk: str,
backend_name: str,
- console: Console,
) -> None:
"""Display OpenAI models in table format."""
table = Table(
@@ -415,7 +395,7 @@ class ModelLister:
created = "N/A"
owned_by = model.owned_by if hasattr(model, "owned_by") else "N/A"
table.add_row(model.id, created, owned_by)
-
+ console = get_console()
console.print("\n")
console.print(table)
console.print("\n")
@@ -425,10 +405,10 @@ class ModelLister:
models: list[ModelInfo],
sdk: str,
backend_name: str,
- console: Console,
any_listed: bool,
) -> None:
"""Display Anthropic models in CSV format."""
+ console = get_console()
if not any_listed:
console.print("model_id,display_name,created_at,sdk,backend")
for anthropic_model in models:
@@ -441,7 +421,6 @@ class ModelLister:
models: list[ModelInfo],
sdk: str,
backend_name: str,
- console: Console,
) -> None:
"""Display Anthropic models in table format."""
table = Table(
@@ -458,6 +437,7 @@ class ModelLister:
created_date = anthropic_model.created_at.strftime("%Y-%m-%d") if anthropic_model.created_at else "N/A"
table.add_row(anthropic_model.id, anthropic_model.display_name, created_date)
+ console = get_console()
console.print("\n")
console.print(table)
console.print("\n")
@@ -467,10 +447,10 @@ class ModelLister:
models: list[Any],
sdk: str,
backend_name: str,
- console: Console,
any_listed: bool,
) -> None:
"""Display Mistral models in CSV format."""
+ console = get_console()
if not any_listed:
console.print("model_id,max_context_length,sdk,backend")
for mistral_model in models:
@@ -482,7 +462,6 @@ class ModelLister:
models: list[Any],
sdk: str,
backend_name: str,
- console: Console,
) -> None:
"""Display Mistral models in table format."""
table = Table(
@@ -498,6 +477,7 @@ class ModelLister:
max_ctx = str(mistral_model.max_context_length) if mistral_model.max_context_length else "N/A"
table.add_row(mistral_model.id, max_ctx)
+ console = get_console()
console.print("\n")
console.print(table)
console.print("\n")
@@ -508,10 +488,10 @@ class ModelLister:
sdk: str,
backend_name: str,
aws_region: str,
- console: Console,
any_listed: bool,
) -> None:
"""Display Bedrock models in CSV format."""
+ console = get_console()
if not any_listed:
console.print("model_id,provider,model_arn,sdk,backend,region")
for bedrock_model in models: # pyright: ignore[reportUnknownVariableType]
@@ -525,7 +505,6 @@ class ModelLister:
models: list[dict[str, Any]],
sdk: str,
aws_region: str,
- console: Console,
) -> None:
"""Display Bedrock models in table format."""
table = Table(
@@ -544,6 +523,7 @@ class ModelLister:
model_arn = bedrock_model.get("modelArn", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
table.add_row(model_id, provider, model_arn) # pyright: ignore[reportUnknownArgumentType]
+ console = get_console()
console.print("\n")
console.print(table)
console.print("\n")
@@ -554,11 +534,11 @@ class ModelLister:
unsupported_sdks: list[str],
backend_name: str,
models_by_sdk: dict[str, list[str]],
- console: Console,
flat: bool,
) -> None:
"""Display message about unsupported SDKs."""
if not any_listed and unsupported_sdks:
+ console = get_console()
if not flat:
console.print(f"\n[yellow]Note: Backend '{backend_name}' has models using SDKs that don't support remote listing:[/yellow]")
for sdk in unsupported_sdks:
diff --git a/pipelex/cogt/usage/cost_registry.py b/pipelex/cogt/usage/cost_registry.py
index 171ade7a7..7cfe3998a 100644
--- a/pipelex/cogt/usage/cost_registry.py
+++ b/pipelex/cogt/usage/cost_registry.py
@@ -3,7 +3,6 @@ from typing import Any
from pydantic import Field, RootModel
from rich import box
-from rich.console import Console
from rich.table import Table
from pipelex import log
@@ -12,6 +11,7 @@ from pipelex.cogt.llm.llm_report import LLMTokenCostReport, LLMTokenCostReportFi
from pipelex.cogt.usage.cost_category import CostCategory, CostsByCategoryDict
from pipelex.cogt.usage.costs_per_token import model_cost_per_token
from pipelex.cogt.usage.token_category import TokenCategory
+from pipelex.hub import get_console
from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
CostRegistryRoot = list[LLMTokenCostReport]
@@ -97,7 +97,7 @@ class CostRegistry(RootModel[CostRegistryRoot]):
msg = "Empty report aggregation by LLM name"
raise CostRegistryError(msg)
- console = Console()
+ console = get_console()
title = f"Costs by LLM model for pipeline '{pipeline_run_id}'"
table = Table(title=title, box=box.ROUNDED)
diff --git a/pipelex/core/concepts/concept_factory.py b/pipelex/core/concepts/concept_factory.py
index 3798fefe7..db8f174af 100644
--- a/pipelex/core/concepts/concept_factory.py
+++ b/pipelex/core/concepts/concept_factory.py
@@ -141,6 +141,13 @@ class ConceptFactory:
description="Anything",
structure_class_name=structure_class_name,
)
+ case NativeConceptCode.JSON:
+ return Concept(
+ code=native_concept_code,
+ domain=SpecialDomain.NATIVE,
+ description="A JSON object",
+ structure_class_name=structure_class_name,
+ )
@classmethod
def make_all_native_concepts(cls) -> list[Concept]:
diff --git a/pipelex/core/concepts/concept_native.py b/pipelex/core/concepts/concept_native.py
index 49ef6f836..e9c2e1d21 100644
--- a/pipelex/core/concepts/concept_native.py
+++ b/pipelex/core/concepts/concept_native.py
@@ -15,6 +15,7 @@ class NativeConceptCode(StrEnum):
NUMBER = "Number"
IMG_GEN_PROMPT = "ImgGenPrompt"
PAGE = "Page"
+ JSON = "JSON"
ANYTHING = "Anything"
@property
@@ -48,6 +49,7 @@ class NativeConceptCode(StrEnum):
| NativeConceptCode.IMG_GEN_PROMPT
| NativeConceptCode.PAGE
| NativeConceptCode.ANYTHING
+ | NativeConceptCode.JSON
):
return False
@@ -68,6 +70,7 @@ class NativeConceptCode(StrEnum):
| NativeConceptCode.IMG_GEN_PROMPT
| NativeConceptCode.PAGE
| NativeConceptCode.ANYTHING
+ | NativeConceptCode.JSON
):
return False
case NativeConceptCode.DYNAMIC:
diff --git a/pipelex/core/registry_models.py b/pipelex/core/registry_models.py
index 4cebf39c9..d5921cd0d 100644
--- a/pipelex/core/registry_models.py
+++ b/pipelex/core/registry_models.py
@@ -5,6 +5,7 @@ from pipelex.core.pipes.pipe_factory import PipeFactoryProtocol
from pipelex.core.stuffs.dynamic_content import DynamicContent
from pipelex.core.stuffs.html_content import HtmlContent
from pipelex.core.stuffs.image_content import ImageContent
+from pipelex.core.stuffs.json_content import JSONContent
from pipelex.core.stuffs.list_content import ListContent
from pipelex.core.stuffs.number_content import NumberContent
from pipelex.core.stuffs.page_content import PageContent
@@ -80,6 +81,7 @@ class CoreRegistryModels(RegistryModels):
PDFContent,
TextAndImagesContent,
PageContent,
+ JSONContent,
]
EXPERIMENTAL: ClassVar[list[ModelType]] = [
diff --git a/pipelex/core/stuffs/json_content.py b/pipelex/core/stuffs/json_content.py
index e2cb175f7..525232495 100644
--- a/pipelex/core/stuffs/json_content.py
+++ b/pipelex/core/stuffs/json_content.py
@@ -1,20 +1,54 @@
+import json
from typing import Any
from json2html import json2html
-from kajson import kajson
+from pydantic import field_validator
+from rich.json import JSON
from typing_extensions import override
from pipelex.core.stuffs.stuff_content import StuffContent
from pipelex.tools.misc.markdown_utils import convert_to_markdown
+from pipelex.tools.misc.pretty import PrettyPrintable
+# TODO: use pipelex.tools.misc.json_utils.JsonContent to support lists in addition to dicts
class JSONContent(StuffContent):
json_obj: dict[str, Any]
+ @field_validator("json_obj", mode="before")
+ @classmethod
+ def check_valid_json(cls, value: dict[str, Any]) -> dict[str, Any]:
+ try:
+ json.dumps(value)
+ except TypeError as exc:
+ msg = f"json_obj is not valid JSON: {exc}"
+ raise TypeError(msg) from exc
+ except json.JSONDecodeError as exc:
+ msg = f"json_obj is not valid JSON: {exc}"
+ raise ValueError(msg) from exc
+ return value
+
@override
def rendered_html(self) -> str:
- return str(json2html.convert(json=kajson.dumps(self.json_obj, indent=4), clubbing=True)) # pyright: ignore[reportUnknownArgumentType]
+ html: str = json2html.convert( # pyright: ignore[reportAssignmentType, reportUnknownVariableType]
+ json=self.json_obj, # pyright: ignore[reportArgumentType]
+ clubbing=True,
+ table_attributes="",
+ )
+ return html
@override
def rendered_markdown(self, level: int = 1, is_pretty: bool = False) -> str:
- return convert_to_markdown(self.json_obj)
+ return convert_to_markdown(data=self.json_obj, level=level, is_pretty=is_pretty)
+
+ @override
+ def rendered_plain(self) -> str:
+ return json.dumps(self.json_obj, indent=4)
+
+ @override
+ def rendered_json(self) -> str:
+ return json.dumps(self.json_obj, indent=4)
+
+ @override
+ def rendered_pretty(self, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ return JSON.from_data(self.json_obj, indent=4)
diff --git a/pipelex/core/stuffs/stuff.py b/pipelex/core/stuffs/stuff.py
index b3aea6cae..588c148be 100644
--- a/pipelex/core/stuffs/stuff.py
+++ b/pipelex/core/stuffs/stuff.py
@@ -16,11 +16,12 @@ from pipelex.core.stuffs.stuff_artefact import StuffArtefact
from pipelex.core.stuffs.stuff_content import StuffContent, StuffContentType
from pipelex.core.stuffs.text_and_images_content import TextAndImagesContent
from pipelex.core.stuffs.text_content import TextContent
+from pipelex.tools.misc.pretty import PrettyPrintable, PrettyRenderable
from pipelex.tools.misc.string_utils import pascal_case_to_snake_case
from pipelex.tools.typing.pydantic_utils import CustomBaseModel, format_pydantic_validation_error
-class Stuff(CustomBaseModel):
+class Stuff(PrettyRenderable, CustomBaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
stuff_code: str
@@ -193,6 +194,24 @@ Forbidden fields are: 'stuff_name', 'content_class', 'concept_code', 'stuff_code
"""Get content as MermaidContent if applicable."""
return self.content_as(MermaidContent)
+ @override
+ def rendered_pretty(self, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ """Render stuff for pretty printing.
+
+ Args:
+ title: Optional title for the rendering
+ depth: Current nesting depth, used to prevent nesting too many sub-tables which would end up too narrow in the console
+ """
+ if title and self.stuff_name:
+ title = f"[cyan]{title}:[/cyan] โ€” {self.stuff_name} ([bold green]{self.concept.code}[/bold green]"
+ elif self.stuff_name:
+ title = f"[cyan]{self.stuff_name}[/cyan] ([bold green]{self.concept.code}[/bold green])"
+ elif title:
+ title = f"[cyan]{title}:[/cyan] some stuff ([bold green]{self.concept.code}[/bold green])"
+ else:
+ title = f"Some stuff ([bold green]{self.concept.code}[/bold green])"
+ return self.content.rendered_pretty(title=title, depth=depth)
+
def pretty_print_stuff(self, title: str | None = None) -> None:
title = title or f"[cyan]{self.stuff_name}[/cyan] ([bold green]{self.concept.code}[/bold green])"
self.content.pretty_print_content(title=title)
diff --git a/pipelex/core/stuffs/stuff_content.py b/pipelex/core/stuffs/stuff_content.py
index f012a9d93..7686901ff 100644
--- a/pipelex/core/stuffs/stuff_content.py
+++ b/pipelex/core/stuffs/stuff_content.py
@@ -7,13 +7,13 @@ from typing_extensions import override
from pipelex.cogt.templating.templating_style import TextFormat
from pipelex.tools.misc.json_utils import remove_none_values
-from pipelex.tools.misc.pretty import PrettyPrintable, PrettyPrinter, pretty_print
+from pipelex.tools.misc.pretty import PrettyPrintable, PrettyPrinter, PrettyRenderable, pretty_print
from pipelex.tools.typing.pydantic_utils import CustomBaseModel
StuffContentType = TypeVar("StuffContentType", bound="StuffContent")
-class StuffContent(ABC, CustomBaseModel):
+class StuffContent(PrettyRenderable, CustomBaseModel, ABC):
@property
def short_desc(self) -> str:
return f"some {self.__class__.__name__}"
@@ -55,7 +55,8 @@ class StuffContent(ABC, CustomBaseModel):
def rendered_json(self) -> str:
return kajson.dumps(self.smart_dump(), indent=4)
- def rendered_pretty(self, title: str | None = None, depth: int = 0) -> PrettyPrintable: # noqa: ARG002
+ @override
+ def rendered_pretty(self, title: str | None = None, depth: int = 0) -> PrettyPrintable:
"""Render content for pretty printing.
Args:
diff --git a/pipelex/dev_cli/_dev_cli.py b/pipelex/dev_cli/_dev_cli.py
index 0d9111333..659b9bbc5 100644
--- a/pipelex/dev_cli/_dev_cli.py
+++ b/pipelex/dev_cli/_dev_cli.py
@@ -4,11 +4,11 @@ from typing import Annotated
import typer
from click import Command, Context
-from rich.console import Console
from typer.core import TyperGroup
from typing_extensions import override
from pipelex.dev_cli.commands.check_config_sync_cmd import LeadingConfig, check_config_sync_cmd
+from pipelex.hub import get_console
from pipelex.tools.misc.package_utils import get_package_version
@@ -46,7 +46,7 @@ app = typer.Typer(
@app.callback(invoke_without_command=True)
def app_callback(_ctx: typer.Context) -> None:
- console = Console()
+ console = get_console()
package_version = get_package_version()
console.print(
f"""
diff --git a/pipelex/dev_cli/commands/check_config_sync_cmd.py b/pipelex/dev_cli/commands/check_config_sync_cmd.py
index 859dc93a0..b43a7f70d 100644
--- a/pipelex/dev_cli/commands/check_config_sync_cmd.py
+++ b/pipelex/dev_cli/commands/check_config_sync_cmd.py
@@ -5,9 +5,9 @@ from __future__ import annotations
import sys
from pathlib import Path
-from rich.console import Console
from rich.panel import Panel
+from pipelex.hub import get_console
from pipelex.tools.misc.diff import has_diff_dirs, make_diff_dirs_pretty
from pipelex.types import StrEnum
@@ -31,7 +31,7 @@ def check_config_sync_cmd(
LeadingConfig.INSTALLED means .pipelex is the reference (default),
LeadingConfig.KIT means pipelex/kit/configs is the reference
"""
- console = Console()
+ console = get_console()
# Define the directories to compare
pipelex_dir = Path(".pipelex")
diff --git a/pipelex/hub.py b/pipelex/hub.py
index 8e1015210..81b380446 100644
--- a/pipelex/hub.py
+++ b/pipelex/hub.py
@@ -1,6 +1,8 @@
+import sys
from typing import ClassVar, Optional
from kajson.class_registry_abstract import ClassRegistryAbstract
+from rich.console import Console
from pipelex import log
from pipelex.cogt.content_generation.content_generator_protocol import (
@@ -29,6 +31,7 @@ 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.console_target import ConsoleTarget
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
@@ -45,6 +48,7 @@ class PipelexHub:
def __init__(self):
# tools
self._config: ConfigRoot | None = None
+ self._console: Console | None = None
self._secrets_provider: SecretsProviderAbstract | None = None
self._class_registry: ClassRegistryAbstract | None = None
self._storage_provider: StorageProviderAbstract | None = None
@@ -73,6 +77,10 @@ class PipelexHub:
# Class methods for singleton management
############################################################
+ @classmethod
+ def get_optional_instance(cls) -> "PipelexHub | None":
+ return cls._instance
+
@classmethod
def get_instance(cls) -> "PipelexHub":
if cls._instance is None:
@@ -110,6 +118,19 @@ class PipelexHub:
self._config = None
log.reset()
+ def set_console_print_target(self, target: ConsoleTarget):
+ match target:
+ case ConsoleTarget.STDOUT:
+ self._console = Console(file=sys.stdout)
+ case ConsoleTarget.STDERR:
+ self._console = Console(file=sys.stderr)
+ case _:
+ msg = f"Invalid console target: {target}"
+ raise ValueError(msg)
+
+ def set_console(self, console: Console):
+ self._console = console
+
def set_secrets_provider(self, secrets_provider: SecretsProviderAbstract):
self._secrets_provider = secrets_provider
@@ -188,6 +209,12 @@ class PipelexHub:
raise RuntimeError(msg)
return self._config
+ def get_console(self) -> Console:
+ if self._console is None:
+ msg = "Console is not set. You must initialize Pipelex first."
+ raise RuntimeError(msg)
+ return self._console
+
def get_required_secrets_provider(self) -> SecretsProviderAbstract:
if self._secrets_provider is None:
msg = "Secrets provider is not set. You must initialize Pipelex first."
@@ -435,3 +462,11 @@ def get_observer() -> ObserverProtocol:
def get_native_concept(native_concept: NativeConceptCode) -> Concept:
return get_pipelex_hub().get_required_concept_library().get_native_concept(native_concept=native_concept)
+
+
+def get_console() -> Console:
+ pipelex_hub = PipelexHub.get_optional_instance()
+ if pipelex_hub:
+ return get_pipelex_hub().get_console()
+ else:
+ return Console(stderr=True)
diff --git a/pipelex/kit/agent_rules/write_pipelex.md b/pipelex/kit/agent_rules/write_pipelex.md
index aa4110624..ca54a8d01 100644
--- a/pipelex/kit/agent_rules/write_pipelex.md
+++ b/pipelex/kit/agent_rules/write_pipelex.md
@@ -38,10 +38,10 @@ ConceptName = "Description of the concept"
- Use PascalCase for concept names
- Never use plurals (no "Stories", use "Story") - lists are handled implicitly by Pipelex
- Avoid circumstantial adjectives (no "LargeText", use "Text") - focus on the essence of what the concept represents
-- Don't redefine native concepts (Text, Image, PDF, TextAndImages, Number, Page)
+- Don't redefine native concepts (Text, Image, PDF, TextAndImages, Number, Page, JSON)
**Native Concepts:**
-Pipelex provides built-in native concepts: `Text`, `Image`, `PDF`, `TextAndImages`, `Number`, `Page`. Use these directly or refine them when appropriate.
+Pipelex provides built-in native concepts: `Text`, `Image`, `PDF`, `TextAndImages`, `Number`, `Page`, `JSON`. Use these directly or refine them when appropriate.
**Refining Native Concepts:**
To create a concept that specializes a native concept without adding fields:
diff --git a/pipelex/kit/configs/inference/deck/base_deck.toml b/pipelex/kit/configs/inference/deck/base_deck.toml
index be034698e..954a65d57 100644
--- a/pipelex/kit/configs/inference/deck/base_deck.toml
+++ b/pipelex/kit/configs/inference/deck/base_deck.toml
@@ -44,7 +44,6 @@ fast-img-gen = "fast-lightning-sdxl"
[waterfalls]
smart_llm = [
- "llama-3.3-70b-versatile",
"claude-4.5-sonnet",
"claude-4.1-opus",
"claude-4-sonnet",
@@ -128,7 +127,7 @@ llm_to_prompt_img_gen = { model = "base-claude", temperature = 0.2 }
llm_to_prompt_img_gen_cheap = { model = "gpt-4o-mini", temperature = 0.5 }
# Groq-specific presets (fast inference, low cost)
-llm_groq_fast_text = { model = "fast-groq", temperature = 0.2 }
+llm_groq_fast_text = { model = "fast-groq", temperature = 0.7 }
llm_groq_balanced = { model = "base-groq", temperature = 0.5 }
llm_groq_vision = { model = "vision-groq", temperature = 0.3 }
diff --git a/pipelex/kit/configs/pipelex.toml b/pipelex/kit/configs/pipelex.toml
index b6e4fc791..4a164cd80 100644
--- a/pipelex/kit/configs/pipelex.toml
+++ b/pipelex/kit/configs/pipelex.toml
@@ -52,6 +52,10 @@ excluded_dirs = [
[pipelex.log_config]
default_log_level = "INFO"
+# Uncomment to log to stderr instead of stdout
+# console_log_target = "stderr"
+# console_print_target = "stderr"
+
[pipelex.log_config.package_log_levels]
pipelex = "INFO"
diff --git a/pipelex/pipelex.py b/pipelex/pipelex.py
index 03a8d7b05..76e75d5a8 100644
--- a/pipelex/pipelex.py
+++ b/pipelex/pipelex.py
@@ -96,7 +96,9 @@ class Pipelex(metaclass=MetaSingleton):
msg = f"Could not setup config because of: {validation_error_msg}"
raise PipelexConfigError(msg) from validation_error
- log.configure(log_config=get_config().pipelex.log_config)
+ log_config = get_config().pipelex.log_config
+ self.pipelex_hub.set_console_print_target(target=log_config.console_print_target)
+ log.configure(log_config=log_config)
log.verbose("Logs are configured")
# tools
diff --git a/pipelex/pipelex.toml b/pipelex/pipelex.toml
index 0a916d20a..19b3fc8fa 100644
--- a/pipelex/pipelex.toml
+++ b/pipelex/pipelex.toml
@@ -45,7 +45,8 @@ cost_report_unit_scale = 1.0
[pipelex.log_config]
default_log_level = "INFO"
-
+console_log_target = "stdout"
+console_print_target = "stdout"
is_console_logging_enabled = true
json_logs_indent = 4
diff --git a/pipelex/pipeline/track/pipeline_tracker.py b/pipelex/pipeline/track/pipeline_tracker.py
index 7f5c18328..d4f20d464 100644
--- a/pipelex/pipeline/track/pipeline_tracker.py
+++ b/pipelex/pipeline/track/pipeline_tracker.py
@@ -23,6 +23,7 @@ from pipelex.pipeline.track.tracker_models import (
SpecialNodeName,
)
from pipelex.tools.misc.mermaid_utils import print_mermaid_url
+from pipelex.tools.misc.terminal_utils import print_to_stderr
# TODO: manage a separate graph for each pipeline_run_id
@@ -335,7 +336,7 @@ class PipelineTracker(PipelineTrackerProtocol):
raise JobHistoryError(msg)
flowchart = PipelineFlowChart(nx_graph=self.nx_graph, start_node=self.start_node, tracker_config=self._tracker_config)
mermaid_code, url = flowchart.generate_mermaid_flowchart(title=title, subtitle=subtitle)
- print(mermaid_code)
+ print_to_stderr(mermaid_code)
title_to_print = "Mermaid flowchart URL"
if title:
title_to_print += f" for {title}"
diff --git a/pipelex/plugins/fal/fal_img_gen_worker.py b/pipelex/plugins/fal/fal_img_gen_worker.py
index b8a1db9ef..5674dd637 100644
--- a/pipelex/plugins/fal/fal_img_gen_worker.py
+++ b/pipelex/plugins/fal/fal_img_gen_worker.py
@@ -11,6 +11,7 @@ from pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstract
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
from pipelex.plugins.fal.fal_factory import FalFactory
from pipelex.reporting.reporting_protocol import ReportingProtocol
+from pipelex.tools.misc.terminal_utils import print_to_stderr
class FalImgGenWorker(ImgGenWorkerAbstract):
@@ -52,7 +53,7 @@ class FalImgGenWorker(ImgGenWorkerAbstract):
continue
new_logs = event.logs[log_index:]
for event_log in new_logs:
- print(event_log["message"])
+ print_to_stderr(event_log["message"])
log_index = len(event.logs)
fal_result = await handler.get()
diff --git a/pipelex/system/configuration/config_check.py b/pipelex/system/configuration/config_check.py
index d2ce7d298..e6657c215 100644
--- a/pipelex/system/configuration/config_check.py
+++ b/pipelex/system/configuration/config_check.py
@@ -1,8 +1,8 @@
-from rich.console import Console
from rich.panel import Panel
from pipelex.cli.commands.init.config_files import init_config
from pipelex.config import ConfigPaths
+from pipelex.hub import get_console
from pipelex.tools.misc.file_utils import path_exists
from pipelex.urls import URLs
@@ -19,7 +19,7 @@ def check_is_initialized(print_warning_if_not: bool = True) -> bool:
is_initialized = config_exists and backends_exists and routing_exists
if not is_initialized and print_warning_if_not:
- console = Console()
+ console = get_console()
# Build a descriptive message about what's missing
issues: list[str] = []
diff --git a/pipelex/system/console_target.py b/pipelex/system/console_target.py
new file mode 100644
index 000000000..20d0b8ef9
--- /dev/null
+++ b/pipelex/system/console_target.py
@@ -0,0 +1,7 @@
+from pipelex.types import StrEnum
+
+
+class ConsoleTarget(StrEnum):
+ STDOUT = "stdout"
+ STDERR = "stderr"
+ FILE = "file"
diff --git a/pipelex/test_extras/shared_pytest_plugins.py b/pipelex/test_extras/shared_pytest_plugins.py
index 66056164b..8adef1d3d 100644
--- a/pipelex/test_extras/shared_pytest_plugins.py
+++ b/pipelex/test_extras/shared_pytest_plugins.py
@@ -2,8 +2,8 @@ import os
import pytest
from pytest import FixtureRequest, Parser
-from rich import print # noqa: A004
+from pipelex.hub import get_console
from pipelex.pipe_run.pipe_run_params import PipeRunMode
from pipelex.system.environment import is_env_var_set, set_env
from pipelex.system.runtime import RunMode, runtime_manager
@@ -81,7 +81,7 @@ def _setup_env_var_placeholders(env_var_keys: list[str]) -> None:
substitutions_counter += 1
if substitutions_counter > 0:
- print(f"[yellow]Set {substitutions_counter} placeholder environment variables[/yellow]")
+ get_console().print(f"[yellow]Set {substitutions_counter} placeholder environment variables[/yellow]")
def _cleanup_placeholder_env_vars(env_var_keys: list[str]) -> None:
@@ -104,7 +104,7 @@ def _cleanup_placeholder_env_vars(env_var_keys: list[str]) -> None:
removed_counter += 1
if removed_counter > 0:
- print(f"[yellow]Cleaned up {removed_counter} placeholder environment variables[/yellow]")
+ get_console().print(f"[yellow]Cleaned up {removed_counter} placeholder environment variables[/yellow]")
@pytest.fixture(scope="session", autouse=True)
diff --git a/pipelex/tools/log/log.py b/pipelex/tools/log/log.py
index d3c9d6fd1..c61771d86 100644
--- a/pipelex/tools/log/log.py
+++ b/pipelex/tools/log/log.py
@@ -84,7 +84,7 @@ class Log:
self._log_config_instance = log_config
- self.rich_handler = log_config.rich_log_config.make_rich_handler()
+ self.rich_handler = log_config.rich_log_config.make_rich_handler(target=log_config.console_log_target)
self.rich_handler.setFormatter(EmojiLogFormatter())
# Configure the root logger
diff --git a/pipelex/tools/log/log_config.py b/pipelex/tools/log/log_config.py
index bd8b56d4b..1595fb93a 100644
--- a/pipelex/tools/log/log_config.py
+++ b/pipelex/tools/log/log_config.py
@@ -1,11 +1,14 @@
+import sys
from enum import Enum
from typing import cast
from pydantic import Field, field_validator
+from rich.console import Console
from rich.highlighter import Highlighter, JSONHighlighter, ReprHighlighter
from rich.logging import RichHandler
from pipelex.system.configuration.config_model import ConfigModel
+from pipelex.system.console_target import ConsoleTarget
from pipelex.tools.log.log_levels import LogLevel
from pipelex.types import StrEnum
@@ -59,7 +62,17 @@ class RichLogConfig(ConfigModel):
tracebacks_suppress: list[str]
keywords_to_hilight: list[str]
- def make_rich_handler(self) -> RichHandler:
+ def make_rich_handler(self, target: ConsoleTarget) -> RichHandler:
+ match target:
+ case ConsoleTarget.STDOUT:
+ console = Console(file=sys.stdout)
+ case ConsoleTarget.STDERR:
+ console = Console(file=sys.stderr)
+ # case ConsoleTarget.FILE:
+ # console = Console(file=target.file_path)
+ case _:
+ msg = f"Invalid console target: {target}"
+ raise ValueError(msg)
highlighter: Highlighter
match self.highlighter_name:
case HighlighterName.JSON:
@@ -68,6 +81,7 @@ class RichLogConfig(ConfigModel):
highlighter = ReprHighlighter()
return RichHandler(
+ console=console,
show_time=self.is_show_time,
show_level=self.is_show_level,
enable_link_path=self.is_link_path_enabled,
@@ -85,6 +99,8 @@ class LogConfig(ConfigModel):
default_log_level: LogLevel = Field(strict=False)
package_log_levels: dict[str, LogLevel]
log_mode: LogMode = Field(strict=False)
+ console_log_target: ConsoleTarget = Field(strict=False)
+ console_print_target: ConsoleTarget = Field(strict=False)
is_console_logging_enabled: bool
@@ -102,8 +118,8 @@ class LogConfig(ConfigModel):
poor_loggers: list[str]
@field_validator("package_log_levels", mode="before")
- @staticmethod
- def validate_package_log_levels(value: dict[str, str]) -> dict[str, LogLevel]:
+ @classmethod
+ def validate_package_log_levels(cls, value: dict[str, str]) -> dict[str, LogLevel]:
return cast(
"dict[str, LogLevel]",
ConfigModel.transform_dict_str_to_enum(input_dict=value, value_enum_cls=LogLevel),
diff --git a/pipelex/tools/log/log_dispatch.py b/pipelex/tools/log/log_dispatch.py
index 9822cd507..be42a241f 100644
--- a/pipelex/tools/log/log_dispatch.py
+++ b/pipelex/tools/log/log_dispatch.py
@@ -245,6 +245,7 @@ class LogDispatch:
case LogMode.POOR:
logger = logging.getLogger(self._log_config.generic_poor_logger)
logger.log(level=severity, msg=message, stacklevel=6)
+ return
stack = inspect.stack()
try:
diff --git a/pipelex/tools/misc/pretty.py b/pipelex/tools/misc/pretty.py
index f07fd58fa..ef6cf3383 100644
--- a/pipelex/tools/misc/pretty.py
+++ b/pipelex/tools/misc/pretty.py
@@ -1,4 +1,5 @@
import shutil
+from abc import ABC, abstractmethod
from io import StringIO
from typing import Any, ClassVar
@@ -15,7 +16,7 @@ from rich.table import Table
from rich.terminal_theme import TerminalTheme
from rich.text import Text, TextType
-from pipelex.tools.misc.terminal_utils import BOLD_FONT, RESET_FONT, TerminalColor
+from pipelex.tools.misc.terminal_utils import BOLD_FONT, RESET_FONT, TerminalColor, print_to_stderr
from pipelex.types import StrEnum
TEXT_COLOR = TerminalColor.WHITE
@@ -54,6 +55,12 @@ EXPORT_THEME = TerminalTheme(
PrettyPrintable = Markdown | Text | JSON | Table | Group | Syntax | Pretty
+class PrettyRenderable(ABC):
+ @abstractmethod
+ def rendered_pretty(self, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ pass
+
+
class PrettyPrintMode(StrEnum):
RICH = "rich"
POOR = "poor"
@@ -230,7 +237,7 @@ class PrettyPrinter:
elif isinstance(value, (int, float, bool)):
# For primitive types, convert to string
pretty = Text(str(value))
- elif hasattr(value, "rendered_pretty"):
+ elif isinstance(value, PrettyRenderable):
pretty = value.rendered_pretty(depth=depth)
else:
# For other types, use Pretty
@@ -284,15 +291,15 @@ class PrettyPrinter:
top_border = "โ•ญ" + "โ”€" * (frame_width - 2) + "โ•ฎ"
bottom_border = "โ•ฐ" + "โ”€" * (frame_width - 2) + "โ•ฏ"
- print(f"{BORDER_COLOR}{top_border}{RESET_FONT}")
+ print_to_stderr(f"{BORDER_COLOR}{top_border}{RESET_FONT}")
# Print each title line separately
for title_line in title_lines:
padding = " " * (frame_width - len(title_line) - 4)
- print(f"{BORDER_COLOR}โ”‚ {BOLD_FONT}{TITLE_COLOR}{title_line}{RESET_FONT}:{padding}{BORDER_COLOR}โ”‚{RESET_FONT}")
+ print_to_stderr(f"{BORDER_COLOR}โ”‚ {BOLD_FONT}{TITLE_COLOR}{title_line}{RESET_FONT}:{padding}{BORDER_COLOR}โ”‚{RESET_FONT}")
for line in wrapped_lines:
padding = " " * (frame_width - len(line) - 3)
- print(f"{BORDER_COLOR}โ”‚ {TEXT_COLOR}{line}{RESET_FONT}{padding}{BORDER_COLOR}โ”‚{RESET_FONT}")
- print(f"{BORDER_COLOR}{bottom_border}{RESET_FONT}")
+ print_to_stderr(f"{BORDER_COLOR}โ”‚ {TEXT_COLOR}{line}{RESET_FONT}{padding}{BORDER_COLOR}โ”‚{RESET_FONT}")
+ print_to_stderr(f"{BORDER_COLOR}{bottom_border}{RESET_FONT}")
@classmethod
def pretty_print_url_without_rich(
@@ -309,8 +316,9 @@ class PrettyPrinter:
top_border = "โ•ญ" + "โ”€" * (frame_width - 2) + "โ•ฎ"
bottom_border = "โ•ฐ" + "โ”€" * (frame_width - 2) + "โ•ฏ"
- print(f"{BORDER_COLOR}{top_border}{RESET_FONT}")
+ print_to_stderr(f"{BORDER_COLOR}{top_border}{RESET_FONT}")
if title:
- print(f"{BORDER_COLOR}โ”‚ {BOLD_FONT}{TITLE_COLOR}{title}{RESET_FONT}:{' ' * (frame_width - len(title) - 4)}{BORDER_COLOR}โ”‚{RESET_FONT}")
- print(f"{TEXT_COLOR}{content}{RESET_FONT}")
- print(f"{BORDER_COLOR}{bottom_border}{RESET_FONT}")
+ title_padding = " " * (frame_width - len(title) - 4)
+ print_to_stderr(f"{BORDER_COLOR}โ”‚ {BOLD_FONT}{TITLE_COLOR}{title}{RESET_FONT}:{title_padding}{BORDER_COLOR}โ”‚{RESET_FONT}")
+ print_to_stderr(f"{TEXT_COLOR}{content}{RESET_FONT}")
+ print_to_stderr(f"{BORDER_COLOR}{bottom_border}{RESET_FONT}")
diff --git a/pipelex/tools/misc/terminal_utils.py b/pipelex/tools/misc/terminal_utils.py
index 2f88f9278..ef1c3e7a2 100644
--- a/pipelex/tools/misc/terminal_utils.py
+++ b/pipelex/tools/misc/terminal_utils.py
@@ -1,3 +1,6 @@
+import sys
+from typing import Any
+
from pipelex.types import StrEnum
BOLD_FONT = "\033[1m"
@@ -12,3 +15,8 @@ class TerminalColor(StrEnum):
CYAN = "\033[0;36m"
MAGENTA = "\033[0;35m"
YELLOW = "\033[0;33m"
+
+
+def print_to_stderr(*args: Any, **kwargs: Any):
+ kwargs.setdefault("file", sys.stderr)
+ print(*args, **kwargs)
diff --git a/tests/conftest.py b/tests/conftest.py
index e5d058d9c..2edc9a91c 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,12 +1,11 @@
import pytest
-from rich.console import Console
from rich.traceback import Traceback
import pipelex.config
import pipelex.pipelex
from pipelex import log
from pipelex.config import get_config
-from pipelex.hub import get_report_delegate
+from pipelex.hub import get_console, get_report_delegate
from pipelex.system.runtime import IntegrationMode
pytest_plugins = [
@@ -30,17 +29,18 @@ def routing_profile_setup(request: pytest.FixtureRequest): # noqa: ARG001 # py
def reset_pipelex_config_fixture(routing_profile_setup: str | None): # noqa: ARG001
# Code to run before each test
# The routing_profile_setup dependency ensures any routing overrides happen first
- Console().print("[magenta]pipelex setup[/magenta]")
+ console = get_console()
+ console.print("[magenta]pipelex setup[/magenta]")
try:
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)
except Exception as exc:
- Console().print(Traceback())
+ console.print(Traceback())
pytest.exit(f"Critical Pipelex setup error: {exc}")
yield
# Code to run after each test
get_report_delegate().generate_report()
- Console().print("[dim magenta]pipelex teardown[/dim magenta]")
+ console.print("[dim magenta]pipelex teardown[/dim magenta]")
pipelex_instance.teardown()
diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py
index 14eec0a68..92e2dab1e 100644
--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py
+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py
@@ -2,7 +2,7 @@
import pytest
-from pipelex import pretty_print
+from pipelex import log, pretty_print
from pipelex.core.concepts.concept_factory import ConceptFactory
from pipelex.core.concepts.concept_native import NativeConceptCode
from pipelex.core.domains.domain import SpecialDomain
@@ -100,7 +100,7 @@ class TestPipeConditionSimple:
# If it succeeds completely
assert pipe_output is not None
assert pipe_output.working_memory is not None
- print("โœ… Direct PipeCondition SUCCEEDED completely!")
+ log.info("โœ… Direct PipeCondition SUCCEEDED completely!")
pretty_print(pipe_output)
except DryRunMissingInputsError as exc:
@@ -109,5 +109,5 @@ class TestPipeConditionSimple:
assert "missing required inputs" not in str(msg_exc)
# Should be due to expression evaluation or other validation
assert any(keyword in str(msg_exc) for keyword in ["expression", "evaluation", "empty result"])
- print(f"โœ… Direct PipeCondition passed input validation, failed at expression evaluation (expected): {exc}")
- print("โœ… Direct PipeCondition test completed successfully!")
+ log.info(f"โœ… Direct PipeCondition passed input validation, failed at expression evaluation (expected): {exc}")
+ log.info("โœ… Direct PipeCondition test completed successfully!")
diff --git a/tests/helpers/init_cmd_helpers.py b/tests/helpers/init_cmd_helpers.py
index e9370b258..4572135ba 100644
--- a/tests/helpers/init_cmd_helpers.py
+++ b/tests/helpers/init_cmd_helpers.py
@@ -188,10 +188,16 @@ class MockedInitEnvironment:
self.mocker.patch("pipelex.cli.commands.init.config_files.config_manager", self.mock_config_manager)
def mock_console_outputs(self) -> None:
- """Mock Console to suppress output."""
- self.mock_console = self.mocker.patch("pipelex.cli.commands.init.command.Console")
- self.mocker.patch("pipelex.cli.commands.init.backends.Console")
- self.mocker.patch("pipelex.cli.commands.init.routing.Console")
+ """Mock Console handling to suppress output."""
+ self.mock_console = self.mocker.MagicMock()
+
+ # Patch modules that use the Pipelex hub console provider
+ self.mocker.patch("pipelex.hub.get_console", return_value=self.mock_console)
+ self.mocker.patch("pipelex.cli.commands.init.command.get_console", return_value=self.mock_console)
+ self.mocker.patch("pipelex.cli.commands.init.backends.get_console", return_value=self.mock_console)
+ self.mocker.patch("pipelex.cli.commands.init.routing.get_console", return_value=self.mock_console)
+
+ # Patch UI modules that still instantiate Console directly
self.mocker.patch("pipelex.cli.commands.init.telemetry.Console")
self.mocker.patch("pipelex.cli.commands.init.ui.backends_ui.Console")
self.mocker.patch("pipelex.cli.commands.init.ui.routing_ui.Console")
@@ -218,19 +224,22 @@ class MockedInitEnvironment:
self.mock_config_manager_paths()
self.mock_console_outputs()
- # Mock Prompt.ask with side_effect for sequential inputs
- if self.prompt_inputs:
- self.mock_prompt_ask = self.mocker.patch(
- "rich.prompt.Prompt.ask",
- side_effect=self.prompt_inputs,
- )
-
- # Mock Confirm.ask with side_effect for sequential inputs
- if self.confirm_inputs:
- self.mock_confirm_ask = self.mocker.patch(
- "rich.prompt.Confirm.ask",
- side_effect=self.confirm_inputs,
- )
+ def prompt_side_effect(*args: Any, **_kwargs: Any) -> str:
+ if not self.prompt_inputs:
+ question = str(args[0]) if args else "<unknown prompt>"
+ msg = f"Unexpected prompt without predefined input: {question}"
+ raise AssertionError(msg)
+ return self.prompt_inputs.pop(0)
+
+ def confirm_side_effect(*args: Any, **_kwargs: Any) -> bool:
+ if not self.confirm_inputs:
+ question = str(args[0]) if args else "<unknown confirmation>"
+ msg = f"Unexpected confirm without predefined input: {question}"
+ raise AssertionError(msg)
+ return self.confirm_inputs.pop(0)
+
+ self.mock_prompt_ask = self.mocker.patch("rich.prompt.Prompt.ask", side_effect=prompt_side_effect)
+ self.mock_confirm_ask = self.mocker.patch("rich.prompt.Confirm.ask", side_effect=confirm_side_effect)
# Mock typer.echo to suppress output
self.mocker.patch("typer.echo")
diff --git a/tests/integration/pipelex/cli/test_init_cmd_backend_customization.py b/tests/integration/pipelex/cli/test_init_cmd_backend_customization.py
index 59691d595..bd11c89c7 100644
--- a/tests/integration/pipelex/cli/test_init_cmd_backend_customization.py
+++ b/tests/integration/pipelex/cli/test_init_cmd_backend_customization.py
@@ -50,8 +50,8 @@ class TestBackendCustomization:
mock_config_manager.pipelex_config_dir = str(tmp_path / ".pipelex")
mocker.patch("pipelex.cli.commands.init.backends.config_manager", mock_config_manager)
- # Mock Console and Prompt to simulate user selecting default [1]
- mocker.patch("pipelex.cli.commands.init.backends.Console")
+ # Mock console provider and Prompt to simulate user selecting default [1]
+ mocker.patch("pipelex.cli.commands.init.backends.get_console", return_value=mocker.MagicMock())
mocker.patch("pipelex.cli.commands.init.ui.backends_ui.Prompt.ask", return_value="1")
# Execute
@@ -93,7 +93,7 @@ class TestBackendCustomization:
mocker.patch("pipelex.cli.commands.init.backends.config_manager", mock_config_manager)
# Mock user input with dynamically determined indices
- mocker.patch("pipelex.cli.commands.init.backends.Console")
+ mocker.patch("pipelex.cli.commands.init.backends.get_console", return_value=mocker.MagicMock())
mocker.patch("pipelex.cli.commands.init.ui.backends_ui.Prompt.ask", return_value=indices_str)
# Execute
@@ -135,7 +135,7 @@ class TestBackendCustomization:
mocker.patch("pipelex.cli.commands.init.backends.config_manager", mock_config_manager)
# Mock user input with spaces and dynamically determined indices
- mocker.patch("pipelex.cli.commands.init.backends.Console")
+ mocker.patch("pipelex.cli.commands.init.backends.get_console", return_value=mocker.MagicMock())
mocker.patch("pipelex.cli.commands.init.ui.backends_ui.Prompt.ask", return_value=indices_str)
# Execute
@@ -205,10 +205,11 @@ class TestBackendCustomization:
mock_config_manager.pipelex_config_dir = str(config_dir)
mocker.patch("pipelex.cli.commands.init.backends.config_manager", mock_config_manager)
- mock_console = mocker.patch("pipelex.cli.commands.init.backends.Console")
+ mock_console = mocker.MagicMock()
+ mocker.patch("pipelex.cli.commands.init.backends.get_console", return_value=mock_console)
# Execute - should not raise exception
customize_backends_config()
# Verify warning was printed
- mock_console.return_value.print.assert_called()
+ mock_console.print.assert_called()
diff --git a/tests/integration/pipelex/cogt/test_img_gen.py b/tests/integration/pipelex/cogt/test_img_gen.py
index 83de3fb03..8c9197bfb 100644
--- a/tests/integration/pipelex/cogt/test_img_gen.py
+++ b/tests/integration/pipelex/cogt/test_img_gen.py
@@ -11,6 +11,7 @@ from pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, Background,
from pipelex.cogt.img_gen.img_gen_job_factory import ImgGenJobFactory
from pipelex.hub import get_img_gen_worker
from pipelex.tools.misc.file_utils import ensure_path
+from pipelex.tools.misc.terminal_utils import print_to_stderr
from tests.integration.pipelex.test_data import ImageGenTestCases
TEMP_OUTPUTS_DIR = "temp/img_gen_by_gpt_image"
@@ -59,7 +60,7 @@ class TestImageGeneration:
extension = ""
output_path = f"{image_name}{extension}"
image.save(output_path)
- print(f"โœ“ Image saved to: {output_path}\n")
+ print_to_stderr(f"โœ“ Image saved to: {output_path}\n")
@pytest.mark.parametrize(("topic", "img_gen_prompt_text"), ImageGenTestCases.IMAGE_DESC)
async def test_img_gen_transparent(self, img_gen_handle: str, topic: str, img_gen_prompt_text: str):
@@ -103,4 +104,4 @@ class TestImageGeneration:
extension = ""
output_path = f"{image_name}{extension}"
image.save(output_path)
- print(f"โœ“ Image saved to: {output_path}\n")
+ print_to_stderr(f"โœ“ Image saved to: {output_path}\n")
diff --git a/tests/integration/pipelex/fixtures/routing_fixtures.py b/tests/integration/pipelex/fixtures/routing_fixtures.py
index 5ec51ecf8..58a88a598 100644
--- a/tests/integration/pipelex/fixtures/routing_fixtures.py
+++ b/tests/integration/pipelex/fixtures/routing_fixtures.py
@@ -6,9 +6,9 @@ from pathlib import Path
import pytest
from pytest import MonkeyPatch
-from rich.console import Console
from pipelex.config import ConfigPaths
+from pipelex.hub import get_console
from pipelex.tools.misc.toml_utils import load_toml_from_path, load_toml_with_tomlkit, save_toml_to_path
# ================================================================================================
@@ -102,7 +102,7 @@ def routing_profile_setup(request: pytest.FixtureRequest): # pyright: ignore[re
"ROUTING_PROFILES_FILE_PATH",
str(routing_override_path),
)
- Console().print(f"[cyan]Overriding routing profile:[/cyan] {routing_profile_name}")
+ get_console().print(f"[cyan]Overriding routing profile:[/cyan] {routing_profile_name}")
yield routing_profile_name
diff --git a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py
index 332cf4848..4f4ce427d 100644
--- a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py
+++ b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py
@@ -3,7 +3,7 @@ from typing import TYPE_CHECKING
import pytest
from pytest import FixtureRequest
-from pipelex import pretty_print
+from pipelex import log, pretty_print
from pipelex.core.concepts.concept_factory import ConceptFactory
from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory
from pipelex.core.stuffs.list_content import ListContent
@@ -116,7 +116,7 @@ class TestPipeSequenceDryRun:
"Number of summaries should match number of original channel updates"
)
- print("โœ… Successfully verified dry run working memory:")
- print(f" - discord_channel_updates: ListContent with {len(discord_updates_list.items)} items")
- print(f" - channel_summaries: ListContent with {len(channel_summaries_list.items)} items")
- print(f" - Final output: ChannelSummary list with concept code {pipe_output.main_stuff.concept.code}")
+ log.info("โœ… Successfully verified dry run working memory:")
+ log.info(f" - discord_channel_updates: ListContent with {len(discord_updates_list.items)} items")
+ log.info(f" - channel_summaries: ListContent with {len(channel_summaries_list.items)} items")
+ log.info(f" - Final output: ChannelSummary list with concept code {pipe_output.main_stuff.concept.code}")
diff --git a/tests/integration/pipelex/plugins/test_anthropic.py b/tests/integration/pipelex/plugins/test_anthropic.py
index 0c03c4256..1de1ea625 100644
--- a/tests/integration/pipelex/plugins/test_anthropic.py
+++ b/tests/integration/pipelex/plugins/test_anthropic.py
@@ -1,10 +1,9 @@
import pytest
from anthropic import AuthenticationError
from rich import box
-from rich.console import Console
from rich.table import Table
-from pipelex.hub import get_models_manager
+from pipelex.hub import get_console, get_models_manager
from pipelex.plugins.anthropic.anthropic_exceptions import AnthropicSDKUnsupportedError
from pipelex.plugins.anthropic.anthropic_llms import anthropic_list_available_models
from pipelex.plugins.plugin_sdk_registry import Plugin
@@ -48,7 +47,7 @@ class TestAnthropic:
pytest.fail(f"Error listing Anthropic models: {exc}")
if pytestconfig.get_verbosity() >= 2:
# Create and configure the table
- console = Console()
+ console = get_console()
table = Table(
title="Available Anthropic Models",
show_header=True,
diff --git a/tests/integration/pipelex/plugins/test_bedrock.py b/tests/integration/pipelex/plugins/test_bedrock.py
index 816a4a395..20de72917 100644
--- a/tests/integration/pipelex/plugins/test_bedrock.py
+++ b/tests/integration/pipelex/plugins/test_bedrock.py
@@ -4,9 +4,9 @@ from typing import Any
import boto3
import pytest
from rich import box
-from rich.console import Console
from rich.table import Table
+from pipelex.hub import get_console
from pipelex.system.environment import all_env_vars_are_set, any_env_var_is_placeholder
warnings.filterwarnings(
@@ -40,7 +40,7 @@ class TestBedrock:
bedrock_models_list: list[dict[str, Any]] = response["modelSummaries"] # pyright: ignore[reportUnknownVariableType]
if pytestconfig.get_verbosity() >= 2:
# Create and configure the table
- console = Console()
+ console = get_console()
table = Table(
title=f"Models from {bedrock_provider} available for Bedrock in {bedrock_region_name}",
show_header=True,
@@ -76,7 +76,7 @@ class TestBedrock:
inference_profiles_list: list[dict[str, Any]] = response["inferenceProfileSummaries"] # pyright: ignore[reportUnknownVariableType]
if pytestconfig.get_verbosity() >= 2:
# Create and configure the table
- console = Console()
+ console = get_console()
table = Table(
title=f"Inference Profiles Available for Bedrock in {bedrock_region_name}",
show_header=True,
diff --git a/tests/integration/pipelex/plugins/test_mistral.py b/tests/integration/pipelex/plugins/test_mistral.py
index 840a1a94b..24b793224 100644
--- a/tests/integration/pipelex/plugins/test_mistral.py
+++ b/tests/integration/pipelex/plugins/test_mistral.py
@@ -1,9 +1,9 @@
import pytest
from rich import box
-from rich.console import Console
from rich.table import Table
from pipelex import pretty_print
+from pipelex.hub import get_console
from pipelex.plugins.mistral.mistral_llms import mistral_list_available_models
from pipelex.system.environment import all_env_vars_are_set, any_env_var_is_placeholder
from tests.integration.pipelex.plugins.conftest import is_backend_available
@@ -27,7 +27,7 @@ class TestMistral:
mistral_models_list = mistral_list_available_models()
if pytestconfig.get_verbosity() >= 2:
# Create and configure the table
- console = Console()
+ console = get_console()
table = Table(
title="Available Mistral Models",
show_header=True,
diff --git a/tests/integration/pipelex/test_libraries.py b/tests/integration/pipelex/test_libraries.py
index 42fca143f..58598bb17 100644
--- a/tests/integration/pipelex/test_libraries.py
+++ b/tests/integration/pipelex/test_libraries.py
@@ -2,12 +2,12 @@ from pathlib import Path
import pytest
from rich import box
-from rich.console import Console
from rich.table import Table
from pipelex import pretty_print
from pipelex.core.concepts.concept_library import ConceptLibrary
from pipelex.core.pipes.pipe_library import PipeLibrary
+from pipelex.hub import get_console
from pipelex.libraries.library_manager_factory import LibraryManagerFactory
from tests.integration.pipelex.test_data import LibraryTestCases
@@ -16,7 +16,7 @@ def pretty_print_all_pipes(
pipe_library: PipeLibrary,
title: str | None = None,
):
- console = Console()
+ console = get_console()
table = Table(
title=title,
show_header=True,
@@ -50,7 +50,7 @@ def pretty_print_all_concepts(
concept_library: ConceptLibrary,
title: str | None = None,
):
- console = Console()
+ console = get_console()
table = Table(
title=title,
show_header=True,
diff --git a/tests/integration/pipelex/tools/pdf/test_pdf_render.py b/tests/integration/pipelex/tools/pdf/test_pdf_render.py
index 3e893d34c..7a7f99d22 100644
--- a/tests/integration/pipelex/tools/pdf/test_pdf_render.py
+++ b/tests/integration/pipelex/tools/pdf/test_pdf_render.py
@@ -24,5 +24,4 @@ class TestPdfRender:
assert all(isinstance(text, str) for text in texts)
if pytestconfig.get_verbosity() >= 2:
full_text = "\n".join(texts)
- print("\n")
pretty_print(full_text, title=f"Full text from pdf '{file_path}'")
diff --git a/tests/unit/pipelex/cogt/usage/test_cost_registry.py b/tests/unit/pipelex/cogt/usage/test_cost_registry.py
index 6a2ba78c2..351cc023d 100644
--- a/tests/unit/pipelex/cogt/usage/test_cost_registry.py
+++ b/tests/unit/pipelex/cogt/usage/test_cost_registry.py
@@ -177,7 +177,8 @@ class TestCostRegistry:
def test_generate_report_aggregation(self, mocker: MockerFixture, tmp_path: Path):
"""Test groupby logic and cost calculations are correct."""
# Mock console output to avoid printing during tests
- mock_console = mocker.patch("pipelex.cogt.usage.cost_registry.Console")
+ mock_console = mocker.MagicMock()
+ mocker.patch("pipelex.cogt.usage.cost_registry.get_console", return_value=mock_console)
# Create test data with multiple LLM usages
job_metadata = JobMetadata(pipeline_run_id="test-pipeline")
@@ -243,9 +244,7 @@ class TestCostRegistry:
)
# Verify console was called to print table
- mock_console.assert_called_once()
- mock_instance = mock_console.return_value
- mock_instance.print.assert_called_once()
+ mock_console.print.assert_called_once()
# Read the CSV and verify aggregation
with open(csv_file, encoding="utf-8") as file:
@@ -307,7 +306,7 @@ class TestCostRegistry:
def test_generate_report_with_file_output(self, tmp_path: Path, mocker: MockerFixture):
"""Test that CSV file is created when file path is provided."""
# Mock console output
- mocker.patch("pipelex.cogt.usage.cost_registry.Console")
+ mocker.patch("pipelex.cogt.usage.cost_registry.get_console", return_value=mocker.MagicMock())
# Create test data
job_metadata = JobMetadata(pipeline_run_id="test-pipeline")
@@ -370,7 +369,7 @@ class TestCostRegistry:
def test_generate_report_unit_scaling(self, unit_scale: float, expected_scaled_cost: float, mocker: MockerFixture):
"""Test that unit scaling is applied correctly to cost display."""
# Mock console to avoid output during tests
- mocker.patch("pipelex.cogt.usage.cost_registry.Console")
+ mocker.patch("pipelex.cogt.usage.cost_registry.get_console", return_value=mocker.MagicMock())
mock_table_class = mocker.patch("pipelex.cogt.usage.cost_registry.Table")
mock_table = mock_table_class.return_value
diff --git a/tests/unit/pipelex/core/stuffs/test_json_content_edge_cases.py b/tests/unit/pipelex/core/stuffs/test_json_content_edge_cases.py
new file mode 100644
index 000000000..1cbf038e8
--- /dev/null
+++ b/tests/unit/pipelex/core/stuffs/test_json_content_edge_cases.py
@@ -0,0 +1,96 @@
+import json
+
+from pipelex.core.stuffs.json_content import JSONContent
+
+
+class TestJSONContentEdgeCases:
+ """Test edge cases for JSONContent."""
+
+ def test_json_with_unicode(self):
+ """Test JSONContent with Unicode characters."""
+ json_obj = {"message": "Hello ไธ–็•Œ", "emoji": "๐ŸŽ‰", "symbol": "โ‚ฌ"}
+ content = JSONContent(json_obj=json_obj)
+
+ # Should handle Unicode in all rendering methods
+ plain = content.rendered_plain()
+ assert "ไธ–็•Œ" in plain or "\\u" in plain # Either literal or escaped
+
+ markdown = content.rendered_markdown()
+ assert "message" in markdown
+
+ html = content.rendered_html()
+ assert isinstance(html, str)
+
+ def test_json_with_special_characters(self):
+ """Test JSONContent with special characters."""
+ json_obj = {
+ "quote": 'He said "hello"',
+ "newline": "line1\nline2",
+ "tab": "col1\tcol2",
+ }
+ content = JSONContent(json_obj=json_obj)
+
+ plain = content.rendered_plain()
+ parsed = json.loads(plain)
+ assert parsed == json_obj
+
+ def test_json_with_numbers(self):
+ """Test JSONContent with various number types."""
+ json_obj = {
+ "integer": 42,
+ "float": 3.14159,
+ "negative": -10,
+ "zero": 0,
+ "scientific": 1.23e-4,
+ }
+ content = JSONContent(json_obj=json_obj)
+
+ plain = content.rendered_plain()
+ parsed = json.loads(plain)
+ assert parsed == json_obj
+
+ def test_json_with_boolean_and_null(self):
+ """Test JSONContent with boolean and null values."""
+ json_obj = {
+ "is_active": True,
+ "is_deleted": False,
+ "data": None,
+ }
+ content = JSONContent(json_obj=json_obj)
+
+ plain = content.rendered_plain()
+ parsed = json.loads(plain)
+ assert parsed == json_obj
+ assert parsed["is_active"] is True
+ assert parsed["is_deleted"] is False
+ assert parsed["data"] is None
+
+ def test_json_with_deeply_nested_structure(self):
+ """Test JSONContent with deeply nested structure."""
+ json_obj = {
+ "level1": {
+ "level2": {
+ "level3": {
+ "level4": {
+ "level5": {"value": "deep"},
+ },
+ },
+ },
+ },
+ }
+ content = JSONContent(json_obj=json_obj)
+
+ plain = content.rendered_plain()
+ parsed = json.loads(plain)
+ assert parsed == json_obj
+ assert parsed["level1"]["level2"]["level3"]["level4"]["level5"]["value"] == "deep"
+
+ def test_json_with_large_array(self):
+ """Test JSONContent with a large array."""
+ json_obj = {"numbers": list(range(100))}
+ content = JSONContent(json_obj=json_obj)
+
+ plain = content.rendered_plain()
+ parsed = json.loads(plain)
+ assert parsed == json_obj
+ assert len(parsed["numbers"]) == 100
diff --git a/tests/unit/pipelex/core/stuffs/test_json_content_rendering.py b/tests/unit/pipelex/core/stuffs/test_json_content_rendering.py
new file mode 100644
index 000000000..30ae5ad19
--- /dev/null
+++ b/tests/unit/pipelex/core/stuffs/test_json_content_rendering.py
@@ -0,0 +1,280 @@
+import json
+import re
+from typing import Any
+
+from pytest import CaptureFixture
+
+from pipelex.core.stuffs.json_content import JSONContent
+from pipelex.tools.misc.pretty import pretty_print
+
+
+def remove_ansi_escape_codes(text: str) -> str:
+ """Remove ANSI color codes from terminal output."""
+ ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
+ return ansi_escape.sub("", text)
+
+
+class TestJSONContentRendering:
+ """Test JSONContent rendering methods."""
+
+ # rendered_plain() tests
+
+ def test_rendered_plain_simple(self):
+ """Test plain rendering of simple JSON."""
+ json_obj = {"name": "test", "value": 42}
+ content = JSONContent(json_obj=json_obj)
+ output = content.rendered_plain()
+
+ # Should be valid JSON
+ parsed = json.loads(output)
+ assert parsed == json_obj
+
+ # Should be indented (4 spaces)
+ assert " " in output
+
+ def test_rendered_plain_nested(self):
+ """Test plain rendering of nested JSON."""
+ json_obj = {
+ "user": {"name": "John", "age": 30},
+ "active": True,
+ }
+ content = JSONContent(json_obj=json_obj)
+ output = content.rendered_plain()
+
+ parsed = json.loads(output)
+ assert parsed == json_obj
+ assert "John" in output
+ assert "30" in output
+
+ def test_rendered_plain_empty(self):
+ """Test plain rendering of empty JSON."""
+ json_obj: dict[str, Any] = {}
+ content = JSONContent(json_obj=json_obj)
+ output = content.rendered_plain()
+
+ assert output.strip() == "{}"
+
+ # rendered_json() tests
+
+ def test_rendered_json_matches_plain(self):
+ """Test that rendered_json produces same output as rendered_plain."""
+ json_obj = {"name": "test", "value": 42, "nested": {"key": "value"}}
+ content = JSONContent(json_obj=json_obj)
+
+ json_output = content.rendered_json()
+ plain_output = content.rendered_plain()
+
+ assert json_output == plain_output
+
+ def test_rendered_json_valid_format(self):
+ """Test that rendered_json produces valid JSON."""
+ json_obj = {"items": [1, 2, 3], "metadata": {"count": 3}}
+ content = JSONContent(json_obj=json_obj)
+ output = content.rendered_json()
+
+ # Should be parseable
+ parsed = json.loads(output)
+ assert parsed == json_obj
+
+ # rendered_markdown() tests
+
+ def test_rendered_markdown_simple(self):
+ """Test markdown rendering of simple JSON."""
+ json_obj = {"name": "test", "value": 42}
+ content = JSONContent(json_obj=json_obj)
+ output = content.rendered_markdown()
+
+ # Should contain key-value pairs
+ assert "name" in output
+ assert "test" in output
+ assert "value" in output
+ assert "42" in output
+
+ def test_rendered_markdown_with_level(self):
+ """Test markdown rendering with custom heading level."""
+ json_obj = {"title": "Test"}
+ content = JSONContent(json_obj=json_obj)
+
+ output_level1 = content.rendered_markdown(level=1)
+ output_level2 = content.rendered_markdown(level=2)
+ output_level3 = content.rendered_markdown(level=3)
+
+ # Different levels should produce different output
+ # (exact format depends on convert_to_markdown implementation)
+ assert output_level1 != output_level2
+ assert output_level2 != output_level3
+
+ def test_rendered_markdown_nested(self):
+ """Test markdown rendering of nested JSON."""
+ json_obj = {
+ "user": {"name": "John", "age": 30},
+ "settings": {"theme": "dark"},
+ }
+ content = JSONContent(json_obj=json_obj)
+ output = content.rendered_markdown()
+
+ # Should contain nested structure
+ assert "user" in output
+ assert "John" in output
+ assert "settings" in output
+ assert "dark" in output
+
+ def test_rendered_markdown_pretty_mode(self):
+ """Test markdown rendering with pretty mode."""
+ json_obj = {"name": "test", "value": 42}
+ content = JSONContent(json_obj=json_obj)
+
+ output_normal = content.rendered_markdown(is_pretty=False)
+ output_pretty = content.rendered_markdown(is_pretty=True)
+
+ # Both should contain the data (pretty mode may capitalize)
+ assert "name" in output_normal.lower()
+ assert "name" in output_pretty.lower()
+ assert "test" in output_normal.lower()
+ assert "test" in output_pretty.lower()
+
+ # rendered_html() tests
+
+ def test_rendered_html_simple(self):
+ """Test HTML rendering of simple JSON."""
+ json_obj = {"name": "test", "value": 42}
+ content = JSONContent(json_obj=json_obj)
+ output = content.rendered_html()
+
+ # Should contain HTML table structure
+ assert "<" in output # HTML tags
+ assert ">" in output
+ # Should contain the data
+ assert "name" in output or "test" in output
+
+ def test_rendered_html_nested(self):
+ """Test HTML rendering of nested JSON."""
+ json_obj = {
+ "user": {"name": "John", "age": 30},
+ "items": ["apple", "banana"],
+ }
+ content = JSONContent(json_obj=json_obj)
+ output = content.rendered_html()
+
+ # Should contain HTML markup
+ assert "<" in output
+ assert ">" in output
+ # Should contain the data
+ assert "John" in output or "apple" in output
+
+ def test_rendered_html_empty(self):
+ """Test HTML rendering of empty JSON."""
+ json_obj: dict[str, Any] = {}
+ content = JSONContent(json_obj=json_obj)
+ output = content.rendered_html()
+
+ # Should still produce some HTML output
+ # (exact format depends on json2html implementation)
+ assert isinstance(output, str)
+
+ # rendered_pretty() tests
+
+ def test_rendered_pretty_simple(self, capsys: CaptureFixture[str]):
+ """Test pretty rendering of simple JSON."""
+ json_obj = {"name": "test", "value": 42, "active": True}
+ content = JSONContent(json_obj=json_obj)
+
+ pretty_print(content.rendered_pretty(title="Simple JSON"))
+
+ captured = capsys.readouterr()
+ output = remove_ansi_escape_codes(captured.out)
+
+ # Should contain the data (Rich JSON doesn't use title parameter)
+ assert "test" in output
+ assert "42" in output
+ assert "true" in output
+
+ def test_rendered_pretty_nested(self, capsys: CaptureFixture[str]):
+ """Test pretty rendering of nested JSON."""
+ json_obj = {
+ "user": {"name": "Alice", "age": 25},
+ "settings": {"theme": "light", "notifications": True},
+ }
+ content = JSONContent(json_obj=json_obj)
+
+ pretty_print(content.rendered_pretty(title="Nested JSON"))
+
+ captured = capsys.readouterr()
+ output = remove_ansi_escape_codes(captured.out)
+
+ # Should contain the data
+ assert "Alice" in output
+ assert "theme" in output
+ assert "light" in output
+
+ def test_rendered_pretty_with_arrays(self, capsys: CaptureFixture[str]):
+ """Test pretty rendering of JSON with arrays."""
+ json_obj = {
+ "items": ["apple", "banana", "cherry"],
+ "numbers": [1, 2, 3],
+ }
+ content = JSONContent(json_obj=json_obj)
+
+ pretty_print(content.rendered_pretty(title="JSON with Arrays"))
+
+ captured = capsys.readouterr()
+ output = remove_ansi_escape_codes(captured.out)
+
+ # Should contain the array data
+ assert "apple" in output
+ assert "banana" in output
+ assert "cherry" in output
+
+ def test_rendered_pretty_complex(self, capsys: CaptureFixture[str]):
+ """Test pretty rendering of complex JSON structure."""
+ json_obj = {
+ "id": "abc123",
+ "metadata": {
+ "created": "2024-01-01",
+ "tags": ["important", "urgent"],
+ },
+ "data": [
+ {"name": "item1", "count": 10},
+ {"name": "item2", "count": 20},
+ ],
+ "score": 95.5,
+ }
+ content = JSONContent(json_obj=json_obj)
+
+ pretty_print(content.rendered_pretty(title="Complex JSON"))
+
+ captured = capsys.readouterr()
+ output = remove_ansi_escape_codes(captured.out)
+
+ # Should contain the complex data
+ assert "abc123" in output
+ assert "important" in output
+ assert "item1" in output
+
+ def test_rendered_pretty_without_title(self, capsys: CaptureFixture[str]):
+ """Test pretty rendering without a title."""
+ json_obj = {"name": "test", "value": 42}
+ content = JSONContent(json_obj=json_obj)
+
+ pretty_print(content.rendered_pretty())
+
+ captured = capsys.readouterr()
+ output = remove_ansi_escape_codes(captured.out)
+
+ # Should still contain the data
+ assert "test" in output
+ assert "42" in output
+
+ def test_rendered_pretty_empty(self, capsys: CaptureFixture[str]):
+ """Test pretty rendering of empty JSON."""
+ json_obj: dict[str, Any] = {}
+ content = JSONContent(json_obj=json_obj)
+
+ pretty_print(content.rendered_pretty(title="Empty JSON"))
+
+ captured = capsys.readouterr()
+ output = remove_ansi_escape_codes(captured.out)
+
+ # Should render empty object
+ assert "{" in output
+ assert "}" in output
diff --git a/tests/unit/pipelex/core/stuffs/test_json_content_validation.py b/tests/unit/pipelex/core/stuffs/test_json_content_validation.py
new file mode 100644
index 000000000..b77f7cf88
--- /dev/null
+++ b/tests/unit/pipelex/core/stuffs/test_json_content_validation.py
@@ -0,0 +1,55 @@
+import pytest
+
+from pipelex.core.stuffs.json_content import JSONContent
+
+
+class TestJSONContentValidation:
+ """Test JSONContent validation."""
+
+ def test_valid_complex_json(self):
+ """Test creating JSONContent with a complex structure."""
+ json_obj = {
+ "id": "123",
+ "metadata": {
+ "created": "2024-01-01",
+ "updated": "2024-01-02",
+ "tags": ["important", "urgent"],
+ },
+ "data": [
+ {"name": "item1", "count": 10},
+ {"name": "item2", "count": 20},
+ ],
+ "active": True,
+ "score": 95.5,
+ }
+ content = JSONContent(json_obj=json_obj)
+ assert content.json_obj == json_obj
+
+ def test_invalid_json_with_non_serializable_object(self):
+ """Test that non-JSON-serializable objects raise TypeError."""
+
+ class NonSerializable:
+ pass
+
+ json_obj = {"object": NonSerializable()}
+
+ with pytest.raises(TypeError, match="json_obj is not valid JSON"):
+ JSONContent(json_obj=json_obj)
+
+ def test_invalid_json_with_non_serializable_function(self):
+ """Test that functions in JSON object raise TypeError."""
+
+ def some_function():
+ pass
+
+ json_obj = {"func": some_function}
+
+ with pytest.raises(TypeError, match="json_obj is not valid JSON"):
+ JSONContent(json_obj=json_obj)
+
+ def test_invalid_json_with_set(self):
+ """Test that sets in JSON object raise TypeError."""
+ json_obj = {"data": {1, 2, 3}}
+
+ with pytest.raises(TypeError, match="json_obj is not valid JSON"):
+ JSONContent(json_obj=json_obj)
diff --git a/tests/unit/pipelex/tools/misc/test_markdown.py b/tests/unit/pipelex/tools/misc/test_markdown.py
index 943269d56..15025ef40 100644
--- a/tests/unit/pipelex/tools/misc/test_markdown.py
+++ b/tests/unit/pipelex/tools/misc/test_markdown.py
@@ -3,6 +3,7 @@ from typing import Any
from pydantic import BaseModel
from pipelex.tools.misc.markdown_utils import convert_to_markdown
+from pipelex.tools.misc.terminal_utils import print_to_stderr
class Article(BaseModel):
@@ -28,8 +29,8 @@ def test_convert_md():
json_data = obj.model_dump()
json_data_md = convert_to_markdown(json_data)
- print(json_data_md)
+ print_to_stderr(json_data_md)
# Convert that dictionary to Markdown
obj_md = convert_to_markdown(obj)
- print(obj_md)
+ print_to_stderr(obj_md)
diff --git a/tests/unit/pipelex/tools/misc/test_pretty.py b/tests/unit/pipelex/tools/misc/test_pretty.py
index 0839fbc6c..63c5afcfb 100644
--- a/tests/unit/pipelex/tools/misc/test_pretty.py
+++ b/tests/unit/pipelex/tools/misc/test_pretty.py
@@ -233,7 +233,7 @@ class TestPrettyPrintInSandbox:
PrettyPrinter.pretty_print_without_rich(content="")
captured = capsys.readouterr()
- output = remove_ansi_escape_codes(captured.out)
+ output = remove_ansi_escape_codes(captured.err)
expected_output = textwrap.dedent("""\
โ•ญโ”€โ”€โ”€โ”€โ•ฎ
@@ -247,7 +247,7 @@ class TestPrettyPrintInSandbox:
PrettyPrinter.pretty_print_without_rich(content=None, title="title", subtitle="subtitle")
captured = capsys.readouterr()
- output = remove_ansi_escape_codes(captured.out)
+ output = remove_ansi_escape_codes(captured.err)
expected_output = textwrap.dedent("""\
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
diff --git a/tests/unit/test_pipelex_check_initialization.py b/tests/unit/test_pipelex_check_initialization.py
index a8eb96e8e..890e89c0d 100644
--- a/tests/unit/test_pipelex_check_initialization.py
+++ b/tests/unit/test_pipelex_check_initialization.py
@@ -103,14 +103,15 @@ class TestPipelexCheckInitialization:
mocker.patch.object(ConfigPaths, "ROUTING_PROFILES_FILE_PATH", str(routing_file))
# Mock console.print to suppress output during test
- mock_console_print = mocker.patch("pipelex.system.configuration.config_check.Console.print")
+ mock_console = mocker.MagicMock()
+ mocker.patch("pipelex.system.configuration.config_check.get_console", return_value=mock_console)
# Test - should print warning and return False
result = check_is_initialized(print_warning_if_not=True)
# Verify
assert result is False
- assert mock_console_print.called
+ assert mock_console.print.called
def test_check_is_initialized_returns_true_when_initialized_with_print_warning(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test that check_is_initialized returns True when initialized with print_warning_if_not=True."""
@@ -146,7 +147,7 @@ class TestPipelexCheckInitialization:
mocker.patch.object(ConfigPaths, "ROUTING_PROFILES_FILE_PATH", str(routing_file))
# Mock console.print to suppress output during test
- mocker.patch("pipelex.system.configuration.config_check.Console.print")
+ mocker.patch("pipelex.system.configuration.config_check.get_console", return_value=mocker.MagicMock())
# Test
result = check_is_initialized(print_warning_if_not=True)
@@ -168,7 +169,7 @@ class TestPipelexCheckInitialization:
mocker.patch.object(ConfigPaths, "ROUTING_PROFILES_FILE_PATH", str(routing_file))
# Mock console.print to suppress output during test
- mocker.patch("pipelex.system.configuration.config_check.Console.print")
+ mocker.patch("pipelex.system.configuration.config_check.get_console", return_value=mocker.MagicMock())
# Test
result = check_is_initialized(print_warning_if_not=True)