From 8672fe274d24240b7501b9b57d9d4ae1d647fa42 Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Thu, 10 Jul 2025 14:44:05 +1000 Subject: [PATCH 01/11] feat: Support llm-based message summarization by introducing Transformer mechanism --- README.md | 8 + config.example.yaml | 5 + docs/transformers.md | 269 ++++++ holmes/config.py | 32 + holmes/core/tools.py | 242 ++++- holmes/core/toolset_manager.py | 153 +++- holmes/core/transformers/__init__.py | 23 + holmes/core/transformers/base.py | 62 ++ holmes/core/transformers/llm_summarize.py | 178 ++++ holmes/core/transformers/registry.py | 122 +++ holmes/core/transformers/transformer.py | 31 + holmes/main.py | 5 + holmes/plugins/toolsets/aks-node-health.yaml | 39 + holmes/plugins/toolsets/aks.yaml | 55 ++ holmes/plugins/toolsets/kubernetes.yaml | 51 ++ holmes/plugins/toolsets/kubernetes_logs.yaml | 28 + holmes/utils/config_utils.py | 91 ++ .../config_class/test_config_transformers.py | 260 ++++++ tests/core/test_config_transformers.py | 302 +++++++ tests/core/test_tool_transformers.py | 827 ++++++++++++++++++ tests/core/test_toolset_manager.py | 138 +++ ...est_transformer_backwards_compatibility.py | 283 ++++++ tests/core/transformers/__init__.py | 1 + tests/core/transformers/test_llm_summarize.py | 471 ++++++++++ tests/core/transformers/test_transformers.py | 344 ++++++++ .../test_config_merging_integration.py | 406 +++++++++ .../test_kubernetes_transformer_execution.py | 539 ++++++++++++ .../test_tool_execution_pipeline.py | 341 ++++++++ .../plugins/toolsets/test_aks_transformers.py | 260 ++++++ .../toolsets/test_kubernetes_transformers.py | 573 ++++++++++++ .../toolsets/test_transformer_validation.py | 361 ++++++++ .../toolsets/transformer_test_utils.py | 29 + tests/utils/test_config_utils.py | 185 ++++ 33 files changed, 6698 insertions(+), 16 deletions(-) create mode 100644 docs/transformers.md create mode 100644 holmes/core/transformers/__init__.py create mode 100644 holmes/core/transformers/base.py create mode 100644 holmes/core/transformers/llm_summarize.py create mode 100644 holmes/core/transformers/registry.py create mode 100644 holmes/core/transformers/transformer.py create mode 100644 holmes/utils/config_utils.py create mode 100644 tests/config_class/test_config_transformers.py create mode 100644 tests/core/test_config_transformers.py create mode 100644 tests/core/test_tool_transformers.py create mode 100644 tests/core/test_transformer_backwards_compatibility.py create mode 100644 tests/core/transformers/__init__.py create mode 100644 tests/core/transformers/test_llm_summarize.py create mode 100644 tests/core/transformers/test_transformers.py create mode 100644 tests/integration/test_config_merging_integration.py create mode 100644 tests/integration/test_kubernetes_transformer_execution.py create mode 100644 tests/integration/test_tool_execution_pipeline.py create mode 100644 tests/plugins/toolsets/test_aks_transformers.py create mode 100644 tests/plugins/toolsets/test_kubernetes_transformers.py create mode 100644 tests/plugins/toolsets/test_transformer_validation.py create mode 100644 tests/plugins/toolsets/transformer_test_utils.py create mode 100644 tests/utils/test_config_utils.py diff --git a/README.md b/README.md index c351994054..9f21428ba6 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,14 @@ You can save common settings and API Keys in a config file to avoid passing them You can save common settings and API keys in config file for re-use. Place the config file in ~/.holmes/config.yaml` or pass it using the --config You can view an example config file with all available settings [here](config.example.yaml). + +### Tool Output Transformers + +HolmesGPT supports **transformers** to process large tool outputs before sending them to your primary LLM. This feature helps manage context window limits while preserving essential information. + +The most common transformer is `llm_summarize`, which uses a fast secondary model to summarize lengthy outputs from tools like `kubectl describe`, log queries, or metrics collection. + +📖 **Learn more**: [Tool Output Transformers Documentation](docs/transformers.md) ## 🔐 Data Privacy diff --git a/config.example.yaml b/config.example.yaml index f56f08e698..8d444e7d0a 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -4,6 +4,11 @@ #model: "azure/model-deployment-name" #api_key: "..." +# Fast Model Summarization +# Optional fast model for summarizing large tool outputs before sending to main LLM +# Helps reduce context window usage, improve performance, and reduce costs +#fast_model: "gpt-4o-mini" + # try adding your own tools here! # e.g. query company-specific data, fetch logs from your existing observability tools, etc #custom_toolsets: ["examples/custom_toolset.yaml"] diff --git a/docs/transformers.md b/docs/transformers.md new file mode 100644 index 0000000000..bebc6a954a --- /dev/null +++ b/docs/transformers.md @@ -0,0 +1,269 @@ +# Tool Output Transformers + +HolmesGPT supports **transformers** that can process tool outputs before they're sent to the primary LLM. This enables automatic summarization of large outputs, reducing context window usage while preserving essential information. + +## Overview + +Transformers are functions that take a tool's raw output and transform it before returning to the LLM. The primary use case is the `llm_summarize` transformer, which uses a fast secondary model to summarize lengthy outputs from tools like `kubectl describe`, log queries, or metrics collection. + +## Configuration + +### Global Configuration + +Configure transformer behavior globally in your HolmesGPT configuration: + +```bash +# CLI flags +holmes ask "what pods are unhealthy?" --fast-model gpt-4o-mini + +# Environment variables +export FAST_MODEL="gpt-4o-mini" + +# Or via config file +# ~/.holmes/config.yaml: +# fast_model: gpt-4o-mini +``` + +| Parameter | Description | Default | +|-----------|-------------|---------| +| `--fast-model` | Fast model for summarization tasks | `None` (disabled) | + +### Tool-Level Configuration + +Tools can declare transformers in their definitions: + +#### YAML Tools + +```yaml +# Basic summarization with defaults +- name: "kubectl_get_by_kind_in_namespace" + description: "Get all resources of a type in a namespace" + command: "kubectl get --show-labels -o wide {{ kind }} -n {{ namespace }}" + transformers: + - llm_summarize: {} + +# Custom threshold and prompt +- name: "kubectl_describe" + description: "Describe a Kubernetes resource" + command: "kubectl describe {{ kind }} {{ name }}{% if namespace %} -n {{ namespace }}{% endif %}" + transformers: + - llm_summarize: + input_threshold: 1000 + prompt: | + Summarize this kubectl describe output focusing on: + - What needs attention or immediate action + - Resource status and health indicators + - Any errors, warnings, or non-standard states + - Key configuration details that could affect functionality + - When possible, mention exact field names so the user can grep for specific details +``` + +#### Python Toolsets + +```python +class PrometheusToolset(Toolset): + def __init__(self): + super().__init__( + name="prometheus/metrics", + tools=[ + ListPrometheusRules( + toolset=self, + transformers=[ + {"llm_summarize": {}} # use default config + ] + ), + ListAvailableMetrics( + toolset=self, + transformers=[ + { + "llm_summarize": { + "input_threshold": 800, + "prompt": "Summarize the available Prometheus metrics, grouping similar metrics and highlighting any unusual patterns." + } + } + ] + ), + ] + ) +``` + +#### MCP Tools + +To be implemented in future phases, allowing MCP tools to leverage transformers similarly to YAML and Python tools. + +## LLM Summarize Transformer + +The `llm_summarize` transformer is the primary transformer available in HolmesGPT. + +### Behavior + +1. **Threshold Check**: Only processes outputs longer than `input_threshold` characters +2. **Fast Model Required**: Skips summarization if no `--fast-model` is configured +3. **Context Preservation**: Maintains essential debugging information while reducing size +4. **Error Handling**: Falls back to original output if summarization fails + +### Configuration Options + +| Option | Description | Default | +|--------|-------------|---------| +| `input_threshold` | Minimum characters to trigger summarization | `1000` characters (default) | +| `prompt` | Custom summarization instructions | Default diagnostic prompt | + +### Default Prompt + +The default summarization prompt is optimized for operational diagnostics: + +```text +Summarize this operational data focusing on: +- What needs attention or immediate action +- Group similar entries into a single line and description +- Make sure to mention outliers, errors, and non-standard patterns +- List normal/healthy patterns as aggregate descriptions +- When listing problematic entries, also try to use aggregate descriptions when possible +- When possible, mention exact keywords, IDs, or patterns so the user can filter/search the original data and drill down on the parts they care about +``` + +## When to Use Transformers + +### ✅ Good Candidates for Transformers + +- **Large kubectl outputs** (`kubectl get -A`, `kubectl describe`) +- **Log aggregation results** with many similar entries +- **Metrics queries** returning extensive time series data +- **Database query results** with repetitive rows +- **API responses** with verbose metadata + +### ❌ Poor Candidates for Transformers + +- **Small, structured outputs** (single resource descriptions) +- **Error messages** that need exact preservation +- **Configuration files** where details matter +- **Already concise outputs** under the threshold + +## Examples + +### Kubernetes Resource Listing + +**Without Transformer:** +```text +NAME READY STATUS RESTARTS AGE IP NODE +pod-1 1/1 Running 0 5d 10.1.1.1 node-1 +pod-2 1/1 Running 0 5d 10.1.1.2 node-1 +pod-3 1/1 Running 0 5d 10.1.1.3 node-2 +pod-4 0/1 CrashLoopBackOff 15 1h 10.1.1.4 node-2 +[... 100 more similar pods ...] +``` + +**With Transformer:** +```text +Found 104 pods across 2 nodes: +- 103 pods are healthy and running (age: 5d, on node-1 and node-2) +- 1 pod in CrashLoopBackOff state: pod-4 (15 restarts, 1h old, IP 10.1.1.4, node-2) +- Search with "grep pod-4" or "grep CrashLoopBackOff" to drill down on the problematic pod +``` + +### Log Analysis + +**Without Transformer:** +```text +2024-01-15T10:30:01Z INFO Starting application... +2024-01-15T10:30:02Z INFO Database connection established +2024-01-15T10:30:03Z INFO Loading configuration... +[... 1000 similar INFO logs ...] +2024-01-15T10:35:15Z ERROR Failed to connect to Redis: connection timeout +2024-01-15T10:35:16Z WARN Retrying Redis connection (attempt 1/3) +``` + +**With Transformer:** +```text +Log analysis (2024-01-15 10:30-10:35): +- 1000+ INFO messages showing normal application startup and operations +- 1 ERROR: Redis connection timeout at 10:35:15Z +- 1 WARN: Redis retry attempt at 10:35:16Z +- Search with "grep ERROR" or "grep Redis" to investigate the connection issue +``` + +## Best Practices + +### Prompt Design + +1. **Focus on actionable information** - what needs attention +2. **Group similar items** - avoid repetitive listings +3. **Preserve searchable keywords** - help users drill down +4. **Highlight anomalies** - errors, warnings, outliers +5. **Use aggregate descriptions** - "5 pods in pending state" vs listing each + +### Configuration + +1. **Set appropriate thresholds** - avoid summarizing small outputs +2. **Use fast models** - gpt-4o-mini, claude-3-haiku for cost/speed +3. **Customize prompts** - tailor to specific tool output types +4. **Test thoroughly** - ensure key information isn't lost + +### Tool Integration + +1. **High-value targets first** - kubectl, logs, metrics +2. **Preserve debug capability** - users should be able to get raw output +3. **Graceful degradation** - work without transformers configured +4. **Monitor effectiveness** - track context window reduction + +## Troubleshooting + +### Transformer Not Running + +- **Check fast model configuration**: Ensure `--fast-model` is set +- **Verify threshold**: Output must exceed `input_threshold` characters +- **Review tool configuration**: Confirm `transformers` is properly defined + +### Poor Summarization Quality + +- **Customize the prompt**: Add domain-specific instructions +- **Adjust threshold**: Lower threshold for smaller outputs +- **Try different fast models**: Some models excel at different tasks +- **Check original output**: Ensure raw data contains the expected information + +### Performance Issues + +- **Monitor token usage**: Fast models should be cost-effective +- **Set reasonable thresholds**: Avoid processing small outputs +- **Consider rate limits**: Fast model APIs have usage constraints +- **Cache when possible**: Some tools may benefit from result caching + +## Migration Guide + +### Existing YAML Tools + +Add transformer configuration to tools that generate large outputs: + +```yaml +# Before +- name: "my_large_output_tool" + command: "some command that produces lots of output" + +# After +- name: "my_large_output_tool" + command: "some command that produces lots of output" + transformers: + - llm_summarize: + input_threshold: 1000 + prompt: "Custom prompt for this tool's output type" +``` + +### Python Toolsets + +Update tool constructors to accept transformer configurations: + +```python +# Before +MyTool(toolset=self) + +# After +MyTool( + toolset=self, + transformers=[ + {"llm_summarize": {"input_threshold": 800}} + ] +) +``` + +For more information, see the [HolmesGPT documentation](https://docs.robusta.dev/master/configuration/holmesgpt/toolsets/). diff --git a/holmes/config.py b/holmes/config.py index 0613831f10..4307e43926 100644 --- a/holmes/config.py +++ b/holmes/config.py @@ -18,6 +18,7 @@ ROBUSTA_API_ENDPOINT, ROBUSTA_CONFIG_PATH, ) +from holmes.core.transformers import Transformer from holmes.core.tools_utils.tool_executor import ToolExecutor from holmes.core.toolset_manager import ToolsetManager from holmes.plugins.runbooks import ( @@ -83,6 +84,8 @@ class Config(RobustaBaseConfig): session_token: Optional[SecretStr] = None model: Optional[str] = "gpt-4o" + fast_model: Optional[str] = None + transformers: Optional[List[Transformer]] = None max_steps: int = 40 cluster_name: Optional[str] = None @@ -140,6 +143,7 @@ def toolset_manager(self) -> ToolsetManager: mcp_servers=self.mcp_servers, custom_toolsets=self.custom_toolsets, custom_toolsets_from_cli=self.custom_toolsets_from_cli, + global_fast_model=self.fast_model, ) return self._toolset_manager @@ -192,6 +196,9 @@ def _load_default_robusta_config(self): "is_robusta_model": True, } + # Auto-generate transformers from CLI fast_model parameter + self._auto_generate_transformers() + def _should_load_robusta_ai(self) -> bool: if not self.should_try_robusta_ai: return False @@ -211,6 +218,24 @@ def _should_load_robusta_ai(self) -> bool: return True + def _auto_generate_transformers(self) -> None: + """ + Auto-generate transformers from CLI fast_model parameter. + Only generates if fast_model is provided and transformers is not already set. + """ + if self.fast_model and not self.transformers: + self.transformers = [ + Transformer( + name="llm_summarize", + config={ + "fast_model": self.fast_model, + }, + ) + ] + logging.debug( + f"Auto-generated transformer config with fast_model: {self.fast_model}" + ) + def log_useful_info(self): if self._model_list: logging.info(f"loaded models: {list(self._model_list.keys())}") @@ -227,6 +252,9 @@ def load_from_file(cls, config_file: Optional[Path], **kwargs) -> "Config": Returns: Config instance with merged settings """ + # Rebuild the model to resolve forward references + cls.model_rebuild() + config_from_file: Optional[Config] = None if config_file is not None and config_file.exists(): logging.debug(f"Loading config from {config_file}") @@ -247,9 +275,13 @@ def load_from_file(cls, config_file: Optional[Path], **kwargs) -> "Config": @classmethod def load_from_env(cls): + # Rebuild the model to resolve forward references + cls.model_rebuild() + kwargs = {} for field_name in [ "model", + "fast_model", "api_key", "max_steps", "alertmanager_url", diff --git a/holmes/core/tools.py b/holmes/core/tools.py index 89b433bb24..8751c41446 100644 --- a/holmes/core/tools.py +++ b/holmes/core/tools.py @@ -8,17 +8,45 @@ from abc import ABC, abstractmethod from datetime import datetime from enum import Enum -from typing import Any, Callable, Dict, List, Optional, OrderedDict, Tuple, Union +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + Optional, + OrderedDict, + Tuple, + Union, +) from jinja2 import Template -from pydantic import BaseModel, ConfigDict, Field, FilePath, model_validator +from pydantic import ( + BaseModel, + ConfigDict, + Field, + FilePath, + model_validator, + PrivateAttr, +) from rich.console import Console from holmes.core.openai_formatting import format_tool_to_open_ai_standard from holmes.plugins.prompts import load_and_render_prompt +from holmes.core.transformers import ( + registry, + TransformerError, + Transformer, +) + +if TYPE_CHECKING: + from holmes.core.transformers import BaseTransformer +from holmes.utils.config_utils import merge_transformers import time from rich.table import Table +logger = logging.getLogger(__name__) + class ToolResultStatus(str, Enum): SUCCESS = "success" @@ -138,6 +166,48 @@ class Tool(ABC, BaseModel): default=None, description="The URL of the icon for the tool, if None will get toolset icon", ) + transformers: Optional[List[Transformer]] = None + + # Private attribute to store initialized transformer instances for performance + _transformer_instances: Optional[List["BaseTransformer"]] = PrivateAttr( + default=None + ) + + def model_post_init(self, __context) -> None: + """Initialize transformer instances once during tool creation for better performance.""" + logger.debug( + f"Tool '{self.name}' model_post_init: creating transformer instances" + ) + + if self.transformers: + logger.debug( + f"Tool '{self.name}' has {len(self.transformers)} transformers to initialize" + ) + self._transformer_instances = [] + for transformer in self.transformers: + if not transformer: + continue + logger.debug( + f" Initializing transformer '{transformer.name}' with config: {transformer.config}" + ) + try: + # Create transformer instance once and cache it + transformer_instance = registry.create_transformer( + transformer.name, transformer.config + ) + self._transformer_instances.append(transformer_instance) + logger.debug( + f"Initialized transformer '{transformer.name}' for tool '{self.name}'" + ) + except Exception as e: + logger.warning( + f"Failed to initialize transformer '{transformer.name}' for tool '{self.name}': {e}" + ) + # Continue with other transformers, don't fail the entire initialization + continue + else: + logger.debug(f"Tool '{self.name}' has no transformers") + self._transformer_instances = None def get_openai_format(self, target_model: str): return format_tool_to_open_ai_standard( @@ -151,23 +221,96 @@ def invoke( self, params: Dict, tool_number: Optional[int] = None ) -> StructuredToolResult: tool_number_str = f"#{tool_number} " if tool_number else "" - logging.info( + logger.info( f"Running tool {tool_number_str}[bold]{self.name}[/bold]: {self.get_parameterized_one_liner(params)}" ) start_time = time.time() result = self._invoke(params) result.icon_url = self.icon_url + + # Apply transformers to the result + transformed_result = self._apply_transformers(result) elapsed = time.time() - start_time output_str = ( - result.get_stringified_data() - if hasattr(result, "get_stringified_data") - else str(result) + transformed_result.get_stringified_data() + if hasattr(transformed_result, "get_stringified_data") + else str(transformed_result) ) show_hint = f"/show {tool_number}" if tool_number else "/show" line_count = output_str.count("\n") + 1 if output_str else 0 - logging.info( + logger.info( f" [dim]Finished {tool_number_str}in {elapsed:.2f}s, output length: {len(output_str):,} characters ({line_count:,} lines) - {show_hint} to view contents[/dim]" ) + return transformed_result + + def _apply_transformers(self, result: StructuredToolResult) -> StructuredToolResult: + """ + Apply configured transformers to the tool result. + + Args: + result: The original tool result + + Returns: + The tool result with transformed data, or original result if transformation fails + """ + if not self._transformer_instances or result.status != ToolResultStatus.SUCCESS: + return result + + # Get the output string to transform + original_data = result.get_stringified_data() + if not original_data: + return result + + transformed_data = original_data + transformers_applied = [] + + # Use cached transformer instances instead of creating new ones + for transformer_instance in self._transformer_instances: + try: + # Check if transformer should be applied + if not transformer_instance.should_apply(transformed_data): + logger.debug( + f"Transformer '{transformer_instance.name}' skipped for tool '{self.name}' (conditions not met)" + ) + continue + + # Apply transformation + pre_transform_size = len(transformed_data) + transform_start_time = time.time() + transformed_data = transformer_instance.transform(transformed_data) + transform_elapsed = time.time() - transform_start_time + + transformers_applied.append(transformer_instance.name) + + # Generic logging - transformers can override this with their own specific metrics + post_transform_size = len(transformed_data) + size_change = post_transform_size - pre_transform_size + logger.info( + f"Applied transformer '{transformer_instance.name}' to tool '{self.name}' output " + f"in {transform_elapsed:.2f}s (size: {pre_transform_size:,} → {post_transform_size:,} chars, " + f"change: {size_change:+,})" + ) + + except TransformerError as e: + logger.warning( + f"Transformer '{transformer_instance.name}' failed for tool '{self.name}': {e}" + ) + # Continue with other transformers, don't fail the entire chain + continue + except Exception as e: + logger.error( + f"Unexpected error applying transformer '{transformer_instance.name}' to tool '{self.name}': {e}" + ) + # Continue with other transformers + continue + + # If any transformers were applied, update the result + if transformers_applied: + # Create a copy of the result with transformed data + result_dict = result.model_dump(exclude={"data"}) + result_dict["data"] = transformed_data + return StructuredToolResult(**result_dict) + return result @abstractmethod @@ -230,7 +373,7 @@ def _invoke(self, params) -> StructuredToolResult: raw_output, return_code, invocation = self.__invoke_script(params) # type: ignore if self.additional_instructions and return_code == 0: - logging.info( + logger.info( f"Applying additional instructions: {self.additional_instructions}" ) output_with_instructions = self.__apply_additional_instructions(raw_output) @@ -265,7 +408,7 @@ def __apply_additional_instructions(self, raw_output: str) -> str: ) return result.stdout.strip() except subprocess.CalledProcessError as e: - logging.error( + logger.error( f"Failed to apply additional instructions: {self.additional_instructions}. " f"Error: {e.stderr}" ) @@ -300,7 +443,7 @@ def __invoke_script(self, params) -> str: def __execute_subprocess(self, cmd) -> Tuple[str, int]: try: - logging.debug(f"Running `{cmd}`") + logger.debug(f"Running `{cmd}`") result = subprocess.run( cmd, shell=True, @@ -313,7 +456,7 @@ def __execute_subprocess(self, cmd) -> Tuple[str, int]: return result.stdout.strip(), result.returncode except Exception as e: - logging.error( + logger.error( f"An unexpected error occurred while running '{cmd}': {e}", exc_info=True, ) @@ -365,6 +508,7 @@ class Toolset(BaseModel): config: Optional[Any] = None is_default: bool = False llm_instructions: Optional[str] = None + transformers: Optional[List[Transformer]] = None # warning! private attributes are not copied, which can lead to subtle bugs. # e.g. l.extend([some_tool]) will reset these private attribute to None @@ -390,13 +534,85 @@ def override_with(self, override: "Toolset") -> None: @model_validator(mode="before") def preprocess_tools(cls, values): additional_instructions = values.get("additional_instructions", "") + transformers = values.get("transformers", None) tools_data = values.get("tools", []) + + # Convert raw dict transformers to Transformer objects BEFORE merging + if transformers: + converted_transformers = [] + for t in transformers: + if isinstance(t, dict): + try: + transformer_obj = Transformer(**t) + # Check if transformer is registered + from holmes.core.transformers import registry + + if not registry.is_registered(transformer_obj.name): + logger.warning( + f"Invalid toolset transformer configuration: Transformer '{transformer_obj.name}' is not registered" + ) + continue # Skip invalid transformer + converted_transformers.append(transformer_obj) + except Exception as e: + # Log warning and skip invalid transformer + logger.warning( + f"Invalid toolset transformer configuration: {e}" + ) + continue + else: + # Already a Transformer object + converted_transformers.append(t) + transformers = converted_transformers if converted_transformers else None + tools = [] for tool in tools_data: if isinstance(tool, dict): tool["additional_instructions"] = additional_instructions + + # Convert tool-level transformers to Transformer objects + tool_transformers = tool.get("transformers") + if tool_transformers: + converted_tool_transformers = [] + for t in tool_transformers: + if isinstance(t, dict): + try: + transformer_obj = Transformer(**t) + # Check if transformer is registered + from holmes.core.transformers import registry + + if not registry.is_registered(transformer_obj.name): + logger.warning( + f"Invalid tool transformer configuration: Transformer '{transformer_obj.name}' is not registered" + ) + continue # Skip invalid transformer + converted_tool_transformers.append(transformer_obj) + except Exception as e: + # Log warning and skip invalid transformer + logger.warning( + f"Invalid tool transformer configuration: {e}" + ) + continue + else: + # Already a Transformer object + converted_tool_transformers.append(t) + tool_transformers = ( + converted_tool_transformers + if converted_tool_transformers + else None + ) + + # Merge toolset-level transformers with tool-level configs + tool["transformers"] = merge_transformers( + base_transformers=transformers, + override_transformers=tool_transformers, + ) if isinstance(tool, Tool): tool.additional_instructions = additional_instructions + # Merge toolset-level transformers with tool-level configs + tool.transformers = merge_transformers( # type: ignore + base_transformers=transformers, + override_transformers=tool.transformers, + ) tools.append(tool) values["tools"] = tools @@ -466,11 +682,11 @@ def check_prerequisites(self): self.status == ToolsetStatusEnum.DISABLED or self.status == ToolsetStatusEnum.FAILED ): - logging.info(f"❌ Toolset {self.name}: {self.error}") + logger.info(f"❌ Toolset {self.name}: {self.error}") # no point checking further prerequisites if one failed return - logging.info(f"✅ Toolset {self.name}") + logger.info(f"✅ Toolset {self.name}") @abstractmethod def get_example_config(self) -> Dict[str, Any]: diff --git a/holmes/core/toolset_manager.py b/holmes/core/toolset_manager.py index 9d21f6f5e6..5aa5b4263c 100644 --- a/holmes/core/toolset_manager.py +++ b/holmes/core/toolset_manager.py @@ -2,7 +2,7 @@ import json import logging import os -from typing import Any, List, Optional +from typing import Any, List, Optional, TYPE_CHECKING from benedict import benedict from pydantic import FilePath @@ -13,6 +13,9 @@ from holmes.plugins.toolsets import load_builtin_toolsets, load_toolsets_from_config from holmes.utils.definitions import CUSTOM_TOOLSET_LOCATION +if TYPE_CHECKING: + pass + DEFAULT_TOOLSET_STATUS_LOCATION = os.path.join(config_path_dir, "toolsets_status.json") @@ -30,6 +33,7 @@ def __init__( custom_toolsets: Optional[List[FilePath]] = None, custom_toolsets_from_cli: Optional[List[FilePath]] = None, toolset_status_location: Optional[FilePath] = None, + global_fast_model: Optional[str] = None, ): self.toolsets = toolsets self.toolsets = toolsets or {} @@ -38,6 +42,7 @@ def __init__( mcp_server["type"] = ToolsetType.MCP.value self.toolsets.update(mcp_servers or {}) self.custom_toolsets = custom_toolsets + self.global_fast_model = global_fast_model if toolset_status_location is None: toolset_status_location = FilePath(DEFAULT_TOOLSET_STATUS_LOCATION) @@ -118,9 +123,13 @@ def _list_all_toolsets( if any(tag in toolset_tags for tag in toolset.tags) } + # Inject global fast_model into all toolsets + final_toolsets = list(toolsets_by_name.values()) + self._inject_fast_model_into_transformers(final_toolsets) + # check_prerequisites against each enabled toolset if not check_prerequisites: - return list(toolsets_by_name.values()) + return final_toolsets enabled_toolsets: List[Toolset] = [] for _, toolset in toolsets_by_name.items(): @@ -130,7 +139,7 @@ def _list_all_toolsets( toolset.status = ToolsetStatusEnum.DISABLED self.check_toolset_prerequisites(enabled_toolsets) - return list(toolsets_by_name.values()) + return final_toolsets @classmethod def check_toolset_prerequisites(cls, toolsets: list[Toolset]): @@ -276,6 +285,10 @@ def load_toolset_with_status( list(toolsets_status_by_name.keys()), check_conflict_default=True, ) + + # Inject fast_model into CLI custom toolsets + self._inject_fast_model_into_transformers(custom_toolsets_from_cli) + # custom toolsets from cli as experimental toolset should not override custom toolsets from config enabled_toolsets_from_cli: List[Toolset] = [] for custom_toolset_from_cli in custom_toolsets_from_cli: @@ -438,3 +451,137 @@ def add_or_merge_onto_toolsets( else: existing_toolsets_by_name[new_toolset.name] = new_toolset existing_toolsets_by_name[new_toolset.name] = new_toolset + + def _inject_fast_model_into_transformers(self, toolsets: List[Toolset]) -> None: + """ + Inject global fast_model setting into all llm_summarize transformers that don't already have fast_model. + This ensures --fast-model reaches all tools regardless of toolset-level transformer configuration. + + IMPORTANT: This also forces recreation of transformer instances since they may already be created. + """ + import logging + from holmes.core.transformers import registry + + logger = logging.getLogger(__name__) + + logger.info( + f"Starting fast_model injection. global_fast_model={self.global_fast_model}" + ) + + if not self.global_fast_model: + logger.info("No global_fast_model configured, skipping injection") + return + + injected_count = 0 + toolset_count = 0 + + for toolset in toolsets: + toolset_count += 1 + toolset_injected = 0 + logger.debug( + f"Processing toolset '{toolset.name}', has toolset transformers: {toolset.transformers is not None}" + ) + + # Inject into toolset-level transformers + if toolset.transformers: + logger.debug( + f"Toolset '{toolset.name}' has {len(toolset.transformers)} toolset-level transformers" + ) + for transformer in toolset.transformers: + logger.debug( + f" Toolset transformer: name='{transformer.name}', config keys={list(transformer.config.keys())}" + ) + if ( + transformer.name == "llm_summarize" + and "fast_model" not in transformer.config + ): + transformer.config["global_fast_model"] = self.global_fast_model + injected_count += 1 + toolset_injected += 1 + logger.info( + f" ✓ Injected global_fast_model into toolset '{toolset.name}' transformer" + ) + elif transformer.name == "llm_summarize": + logger.debug( + f" - Toolset transformer already has fast_model: {transformer.config.get('fast_model')}" + ) + else: + logger.debug( + f"Toolset '{toolset.name}' has no toolset-level transformers" + ) + + # Inject into tool-level transformers + if hasattr(toolset, "tools") and toolset.tools: + logger.debug(f"Toolset '{toolset.name}' has {len(toolset.tools)} tools") + for tool in toolset.tools: + logger.debug( + f" Processing tool '{tool.name}', has transformers: {tool.transformers is not None}" + ) + if tool.transformers: + logger.debug( + f" Tool '{tool.name}' has {len(tool.transformers)} transformers" + ) + tool_updated = False + for transformer in tool.transformers: + logger.debug( + f" Tool transformer: name='{transformer.name}', config keys={list(transformer.config.keys())}" + ) + if ( + transformer.name == "llm_summarize" + and "fast_model" not in transformer.config + ): + transformer.config["global_fast_model"] = ( + self.global_fast_model + ) + injected_count += 1 + toolset_injected += 1 + tool_updated = True + logger.info( + f" ✓ Injected global_fast_model into tool '{tool.name}' transformer" + ) + elif transformer.name == "llm_summarize": + logger.debug( + f" - Tool transformer already has fast_model: {transformer.config.get('fast_model')}" + ) + + # CRITICAL: Force recreation of transformer instances if we updated the config + if tool_updated: + logger.info( + f" 🔄 Recreating transformer instances for tool '{tool.name}' after injection" + ) + if tool.transformers: + tool._transformer_instances = [] + for transformer in tool.transformers: + if not transformer: + continue + try: + # Create transformer instance with updated config + transformer_instance = ( + registry.create_transformer( + transformer.name, transformer.config + ) + ) + tool._transformer_instances.append( + transformer_instance + ) + logger.debug( + f" Recreated transformer '{transformer.name}' for tool '{tool.name}' with config: {transformer.config}" + ) + except Exception as e: + logger.warning( + f" Failed to recreate transformer '{transformer.name}' for tool '{tool.name}': {e}" + ) + continue + else: + logger.debug(f" Tool '{tool.name}' has no transformers") + else: + logger.debug(f"Toolset '{toolset.name}' has no tools") + + if toolset_injected > 0: + logger.info( + f"Toolset '{toolset.name}': injected into {toolset_injected} transformers" + ) + + logger.info( + f"Fast_model injection complete: {injected_count} transformers updated across {toolset_count} toolsets" + ) diff --git a/holmes/core/transformers/__init__.py b/holmes/core/transformers/__init__.py new file mode 100644 index 0000000000..c282d24fa6 --- /dev/null +++ b/holmes/core/transformers/__init__.py @@ -0,0 +1,23 @@ +""" +Transformer system for processing tool outputs. + +This module provides the infrastructure for transforming tool outputs +before they are passed to the LLM for analysis. +""" + +from .base import BaseTransformer, TransformerError +from .registry import TransformerRegistry, registry +from .llm_summarize import LLMSummarizeTransformer +from .transformer import Transformer + +# Register built-in transformers +registry.register(LLMSummarizeTransformer) + +__all__ = [ + "BaseTransformer", + "TransformerError", + "TransformerRegistry", + "registry", + "LLMSummarizeTransformer", + "Transformer", +] diff --git a/holmes/core/transformers/base.py b/holmes/core/transformers/base.py new file mode 100644 index 0000000000..3ebb25031c --- /dev/null +++ b/holmes/core/transformers/base.py @@ -0,0 +1,62 @@ +""" +Base transformer abstract class for tool output transformation. +""" + +__all__ = ["BaseTransformer", "TransformerError"] + +from abc import ABC, abstractmethod +from pydantic import BaseModel + + +class TransformerError(Exception): + """Exception raised when transformer operations fail.""" + + pass + + +class BaseTransformer(BaseModel, ABC): + """ + Abstract base class for all tool output transformers. + + Transformers process tool outputs before they are returned to the LLM, + enabling operations like summarization, filtering, or format conversion. + """ + + @abstractmethod + def transform(self, input_text: str) -> str: + """ + Transform the input text and return the transformed output. + + Args: + input_text: The raw tool output to transform + + Returns: + The transformed output text + + Raises: + TransformerError: If transformation fails + """ + pass + + @abstractmethod + def should_apply(self, input_text: str) -> bool: + """ + Determine whether this transformer should be applied to the input. + + Args: + input_text: The raw tool output to check + + Returns: + True if the transformer should be applied, False otherwise + """ + pass + + @property + def name(self) -> str: + """ + Get the transformer name. + + Returns: + The transformer name (class name by default) + """ + return self.__class__.__name__ diff --git a/holmes/core/transformers/llm_summarize.py b/holmes/core/transformers/llm_summarize.py new file mode 100644 index 0000000000..2a09612864 --- /dev/null +++ b/holmes/core/transformers/llm_summarize.py @@ -0,0 +1,178 @@ +""" +LLM Summarize Transformer for fast model summarization of large tool outputs. +""" + +import logging +from typing import Optional, ClassVar +from pydantic import Field, PrivateAttr + +from .base import BaseTransformer, TransformerError +from ..llm import DefaultLLM, LLM + +logger = logging.getLogger(__name__) + + +class LLMSummarizeTransformer(BaseTransformer): + """ + Transformer that uses a fast LLM model to summarize large tool outputs. + + This transformer applies summarization when: + 1. A fast model is available + 2. The input length exceeds the configured threshold + + Configuration options: + - input_threshold: Minimum input length to trigger summarization (default: 1000) + - prompt: Custom prompt template for summarization (optional) + - fast_model: Fast model name for summarization (e.g., "gpt-4o-mini") + - api_key: API key for the fast model (optional, uses default if not provided) + """ + + DEFAULT_PROMPT: ClassVar[str] = """Summarize this operational data focusing on: +- What needs attention or immediate action +- Group similar entries into a single line and description +- Make sure to mention outliers, errors, and non-standard patterns +- List normal/healthy patterns as aggregate descriptions +- When listing problematic entries, also try to use aggregate descriptions when possible +- When possible, mention exact keywords, IDs, or patterns so the user can filter/search the original data and drill down on the parts they care about (extraction over abstraction)""" + + # Pydantic fields with validation + input_threshold: int = Field( + default=1000, ge=0, description="Minimum input length to trigger summarization" + ) + prompt: Optional[str] = Field( + default=None, + min_length=1, + description="Custom prompt template for summarization", + ) + fast_model: Optional[str] = Field( + default=None, + min_length=1, + description="Fast model name for summarization (e.g., 'gpt-4o-mini')", + ) + global_fast_model: Optional[str] = Field( + default=None, + min_length=1, + description="Global fast model name fallback when fast_model is not set", + ) + api_key: Optional[str] = Field( + default=None, + description="API key for the fast model (optional, uses default if not provided)", + ) + + # Private attribute for the LLM instance (not serialized) + _fast_llm: Optional[LLM] = PrivateAttr(default=None) + + def model_post_init(self, __context) -> None: + """Initialize the fast LLM instance after model validation.""" + import logging + + logger = logging.getLogger(__name__) + + self._fast_llm = None + + # Determine which fast model to use: fast_model takes precedence over global_fast_model + effective_fast_model = self.fast_model or self.global_fast_model + + logger.debug( + f"LLMSummarizeTransformer initialization: fast_model='{self.fast_model}', global_fast_model='{self.global_fast_model}', effective='{effective_fast_model}'" + ) + + # Create fast LLM instance if a fast model is available + if effective_fast_model: + try: + self._fast_llm = DefaultLLM(effective_fast_model, self.api_key) + logger.info( + f"Created fast LLM instance with model: {effective_fast_model}" + ) + except Exception as e: + logger.warning(f"Failed to create fast LLM instance: {e}") + self._fast_llm = None + else: + logger.debug( + "No fast model configured (neither fast_model nor global_fast_model)" + ) + + def should_apply(self, input_text: str) -> bool: + """ + Determine if summarization should be applied to the input. + + Args: + input_text: The tool output to check + + Returns: + True if summarization should be applied, False otherwise + """ + import logging + + logger = logging.getLogger(__name__) + + # Skip if no fast model is configured + if self._fast_llm is None: + logger.debug( + f"Skipping summarization: no fast model configured (fast_model='{self.fast_model}', global_fast_model='{self.global_fast_model}')" + ) + return False + + # Check if input exceeds threshold + input_length = len(input_text) + + if input_length <= self.input_threshold: + logger.debug( + f"Skipping summarization: input length {input_length} <= threshold {self.input_threshold}" + ) + return False + + logger.debug( + f"Applying summarization: input length {input_length} > threshold {self.input_threshold}" + ) + return True + + def transform(self, input_text: str) -> str: + """ + Transform the input text by summarizing it with the fast model. + + Args: + input_text: The tool output to summarize + + Returns: + Summarized text + + Raises: + TransformerError: If summarization fails + """ + if self._fast_llm is None: + raise TransformerError("Cannot transform: no fast model configured") + + try: + # Get the prompt to use + prompt = self.prompt or self.DEFAULT_PROMPT + + # Construct the full prompt with the content + full_prompt = f"{prompt}\n\nContent to summarize:\n{input_text}" + + # Perform the summarization + logger.debug(f"Summarizing {len(input_text)} characters with fast model") + + response = self._fast_llm.completion( + [{"role": "user", "content": full_prompt}] + ) + summarized_text = response.choices[0].message.content # type: ignore + + if not summarized_text or not summarized_text.strip(): + raise TransformerError("Fast model returned empty summary") + + logger.debug( + f"Summarization complete: {len(input_text)} -> {len(summarized_text)} characters" + ) + + return summarized_text.strip() + + except Exception as e: + error_msg = f"Failed to summarize content with fast model: {e}" + logger.error(error_msg) + raise TransformerError(error_msg) from e + + @property + def name(self) -> str: + """Get the transformer name.""" + return "llm_summarize" diff --git a/holmes/core/transformers/registry.py b/holmes/core/transformers/registry.py new file mode 100644 index 0000000000..09f068447b --- /dev/null +++ b/holmes/core/transformers/registry.py @@ -0,0 +1,122 @@ +""" +Transformer registry for managing available transformers. +""" + +from typing import Dict, Type, Optional, Any, List +from .base import BaseTransformer, TransformerError + + +class TransformerRegistry: + """ + Registry for managing transformer types and creating transformer instances. + + This registry provides a centralized way to register transformer classes + and create instances based on configuration. + """ + + def __init__(self): + self._transformers: Dict[str, Type[BaseTransformer]] = {} + + def register(self, transformer_class: Type[BaseTransformer]) -> None: + """ + Register a transformer class, using the transformer's name property. + + Args: + transformer_class: The transformer class to register + + Raises: + ValueError: If name is already registered or transformer_class is invalid + """ + if not issubclass(transformer_class, BaseTransformer): + raise ValueError( + f"Transformer class must inherit from BaseTransformer, got {transformer_class}" + ) + + # Get name from the transformer class + try: + temp_instance = transformer_class() + name = temp_instance.name + except Exception: + # Fallback to class name if instantiation fails + name = transformer_class.__name__ + + if name in self._transformers: + raise ValueError(f"Transformer '{name}' is already registered") + + self._transformers[name] = transformer_class + + def unregister(self, name: str) -> None: + """ + Unregister a transformer by name. + + Args: + name: The name of the transformer to unregister + + Raises: + KeyError: If transformer name is not registered + """ + if name not in self._transformers: + raise KeyError(f"Transformer '{name}' is not registered") + + del self._transformers[name] + + def create_transformer( + self, name: str, config: Optional[Dict[str, Any]] = None + ) -> BaseTransformer: + """ + Create a transformer instance by name. + + Args: + name: The name of the transformer to create + config: Optional configuration for the transformer + + Returns: + A new transformer instance + + Raises: + KeyError: If transformer name is not registered + TransformerError: If transformer creation fails + """ + if name not in self._transformers: + raise KeyError(f"Transformer '{name}' is not registered") + + transformer_class = self._transformers[name] + + try: + # Handle both old-style dict config and new Pydantic models + if config is None: + return transformer_class() + else: + # For Pydantic models, pass config as keyword arguments + return transformer_class(**config) + except Exception as e: + raise TransformerError(f"Failed to create transformer '{name}': {e}") from e + + def is_registered(self, name: str) -> bool: + """ + Check if a transformer is registered. + + Args: + name: The name to check + + Returns: + True if the transformer is registered, False otherwise + """ + return name in self._transformers + + def list_transformers(self) -> List[str]: + """ + Get a list of all registered transformer names. + + Returns: + List of registered transformer names + """ + return list(self._transformers.keys()) + + def clear(self) -> None: + """Clear all registered transformers.""" + self._transformers.clear() + + +# Global transformer registry instance +registry = TransformerRegistry() diff --git a/holmes/core/transformers/transformer.py b/holmes/core/transformers/transformer.py new file mode 100644 index 0000000000..673a2c4421 --- /dev/null +++ b/holmes/core/transformers/transformer.py @@ -0,0 +1,31 @@ +""" +Configuration class for tool transformers. +""" + +import logging +from typing import Any, Dict +from pydantic import BaseModel, Field, model_validator + +from .registry import registry + + +class Transformer(BaseModel): + """ + Configuration for a tool transformer. + + Each transformer config specifies a transformer type and its parameters. + This replaces the previous dict-based configuration with proper type safety. + """ + + name: str = Field(description="Name of the transformer (e.g., 'llm_summarize')") + config: Dict[str, Any] = Field( + default_factory=dict, description="Configuration parameters for the transformer" + ) + + @model_validator(mode="after") + def validate_transformer(self): + """Validate that the transformer name is known to the registry.""" + if not registry.is_registered(self.name): + # Log warning but don't fail validation - allows for graceful degradation + logging.warning(f"Transformer '{self.name}' is not registered") + return self diff --git a/holmes/main.py b/holmes/main.py index f1c07126c7..5afd86103a 100644 --- a/holmes/main.py +++ b/holmes/main.py @@ -76,6 +76,9 @@ help="API key to use for the LLM (if not given, uses environment variables OPENAI_API_KEY or AZURE_API_KEY)", ) opt_model: Optional[str] = typer.Option(None, help="Model to use for the LLM") +opt_fast_model: Optional[str] = typer.Option( + None, help="Optional fast model for summarization tasks" +) opt_config_file: Optional[Path] = typer.Option( DEFAULT_CONFIG_LOCATION, # type: ignore "--config", @@ -177,6 +180,7 @@ def ask( # common options api_key: Optional[str] = opt_api_key, model: Optional[str] = opt_model, + fast_model: Optional[str] = opt_fast_model, config_file: Optional[Path] = opt_config_file, custom_toolsets: Optional[List[Path]] = opt_custom_toolsets, max_steps: Optional[int] = opt_max_steps, @@ -244,6 +248,7 @@ def ask( config_file, api_key=api_key, model=model, + fast_model=fast_model, max_steps=max_steps, custom_toolsets_from_cli=custom_toolsets, slack_token=slack_token, diff --git a/holmes/plugins/toolsets/aks-node-health.yaml b/holmes/plugins/toolsets/aks-node-health.yaml index 848cf186ed..26be97604d 100644 --- a/holmes/plugins/toolsets/aks-node-health.yaml +++ b/holmes/plugins/toolsets/aks-node-health.yaml @@ -7,17 +7,44 @@ toolsets: - command: "az account show" - command: "az aks --help" - command: "kubectl version --client" + + # Note: Tools in this toolset use transformers with llm_summarize + # to automatically summarize large outputs from Azure CLI and kubectl commands + # when a fast model is configured, focusing on health issues and troubleshooting. tools: - name: "check_node_status" description: "Checks the status of all nodes in the AKS cluster." user_description: "get the status of all nodes in the AKS cluster" command: | kubectl get nodes + transformers: + - name: llm_summarize + config: + input_threshold: 800 + prompt: | + Summarize this node status output focusing on: + - Any nodes that are NotReady or in error states + - Node health patterns and issues requiring attention + - Group healthy nodes together with aggregate counts + - Highlight nodes with concerning conditions or ages + - When possible, mention exact node names for follow-up investigation - name: "describe_node" description: "Describes a specific node in the AKS cluster to inspect its conditions." user_description: "describe node {{ NODE_NAME }} in the AKS cluster" command: | kubectl describe node {{ NODE_NAME }} + transformers: + - name: llm_summarize + config: + input_threshold: 1200 + prompt: | + Summarize this node description focusing on: + - Node conditions and health status (Ready, MemoryPressure, DiskPressure, etc.) + - Resource capacity vs allocatable vs current usage + - Any taints, labels, or annotations indicating issues + - Recent events that show problems or state changes + - System information relevant to troubleshooting + - When possible, highlight specific condition reasons for investigation - name: "get_node_events" description: "Fetches recent events for a specific node to surface warnings and errors." user_description: "get events for node {{ NODE_NAME }}" @@ -33,6 +60,18 @@ toolsets: user_description: "review Azure Activity Log for resource group {{ RESOURCE_GROUP_NAME }}" command: | az monitor activity-log list --resource-group {{ RESOURCE_GROUP_NAME }} + transformers: + - name: llm_summarize + config: + input_threshold: 1500 + prompt: | + Summarize this Azure Activity Log focusing on: + - Recent administrative actions or configuration changes + - Any failed operations or errors that could impact node health + - Resource scaling, updates, or maintenance activities + - Network security group, load balancer, or VM-related changes + - Group similar activities and highlight time patterns + - When possible, mention specific operation names and correlation IDs - name: "check_top_resource_consuming_pods" description: "Checks for the top resource-consuming pods on a specific node." user_description: "get the top resource-consuming pods on node {{ NODE_NAME }}" diff --git a/holmes/plugins/toolsets/aks.yaml b/holmes/plugins/toolsets/aks.yaml index 007d6cbf94..d9f4b79328 100644 --- a/holmes/plugins/toolsets/aks.yaml +++ b/holmes/plugins/toolsets/aks.yaml @@ -7,6 +7,10 @@ toolsets: - command: "az account show" - command: "az aks --help" - command: "kubectl version --client" + + # Note: Tools in this toolset use transformers with llm_summarize + # to automatically summarize large JSON outputs from Azure CLI commands + # when a fast model is configured, focusing on key configuration and status information. tools: - name: "cloud_provider" description: "Fetches the cloud provider of the kubernetes cluster, determined by the providerID of the nodes" @@ -18,16 +22,54 @@ toolsets: user_description: "get AKS cluster {{ CLUSTER_NAME }} under resource group {{ RESOURCE_GROUP_NAME }} in subscription {{ SUBSCRIPTION_ID }}" command: | az aks show --resource-group {{ RESOURCE_GROUP_NAME }} --name {{ CLUSTER_NAME }} --subscription {{ SUBSCRIPTION_ID }} + transformers: + - name: llm_summarize + config: + input_threshold: 1500 + prompt: | + Summarize this AKS cluster configuration focusing on: + - Cluster status, health state, and version information + - Node pool configuration and scaling settings + - Network configuration (subnet, load balancer, network policy) + - Add-ons and features enabled (monitoring, auto-scaling, etc.) + - Security settings (RBAC, managed identity, private cluster) + - Any warnings or deprecated configurations + - When possible, highlight settings that might impact performance or security - name: "aks_list_clusters_by_rg" description: "Lists all AKS clusters under a specific resource group. Only run this tool when you need to get all clusters in a resource group, rather than a specific one." user_description: "list AKS clusters in resource group {{ RESOURCE_GROUP_NAME }} under subscription {{ SUBSCRIPTION_ID }}" command: | az aks list --resource-group {{ RESOURCE_GROUP_NAME }} --subscription {{ SUBSCRIPTION_ID }} + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: | + Summarize this AKS clusters list focusing on: + - Cluster names, locations, and current status + - Kubernetes versions and any version skew issues + - Node pool counts and VM SKUs + - Key configuration differences between clusters + - Any clusters in error or unusual states + - When possible, group clusters by similar configurations - name: "aks_list_node_pools" description: "Lists node pools in an AKS cluster" user_description: "list node pools for AKS cluster {{ CLUSTER_NAME }} under resource group {{ RESOURCE_GROUP_NAME }}" command: | az aks nodepool list --resource-group {{ RESOURCE_GROUP_NAME }} --cluster-name {{ CLUSTER_NAME }} --subscription {{ SUBSCRIPTION_ID }} + transformers: + - name: llm_summarize + config: + input_threshold: 1200 + prompt: | + Summarize this AKS node pools list focusing on: + - Node pool names, VM sizes, and current node counts + - Scaling configuration (min/max nodes, auto-scaling enabled) + - Node pool status and provisioning state + - OS types, Kubernetes versions, and any upgrade patterns + - Taints, labels, and specialized configurations + - Any node pools in error states or with scaling issues + - When possible, identify resource allocation patterns - name: "aks_show_node_pool" description: "Shows details of a specific node pool in an AKS cluster" user_description: "get node pool {{ NODE_POOL_NAME }} in AKS cluster {{ CLUSTER_NAME }} under resource group {{ RESOURCE_GROUP_NAME }}" @@ -84,3 +126,16 @@ toolsets: user_description: "list NSG rules for NSG {{ NSG_NAME }} in resource group {{ RESOURCE_GROUP_NAME }} under subscription {{ SUBSCRIPTION_ID }}" command: | az network nsg rule list --resource-group {{ RESOURCE_GROUP_NAME }} --nsg-name {{ NSG_NAME }} --subscription {{ SUBSCRIPTION_ID }} --include-default -o table + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: | + Summarize these NSG rules focusing on: + - Allow vs deny rules and their priority order + - Inbound vs outbound traffic rules + - Port ranges and protocols affected + - Source and destination configurations + - Any overly permissive or potentially insecure rules + - Default rules vs custom rules + - When possible, highlight rules that might impact AKS connectivity diff --git a/holmes/plugins/toolsets/kubernetes.yaml b/holmes/plugins/toolsets/kubernetes.yaml index 81e61412ba..821b441be8 100644 --- a/holmes/plugins/toolsets/kubernetes.yaml +++ b/holmes/plugins/toolsets/kubernetes.yaml @@ -8,6 +8,10 @@ toolsets: prerequisites: - command: "kubectl version --client" + # Note: Many tools in this toolset use transformers with llm_summarize + # to automatically summarize large kubectl outputs when a fast model is configured. + # This reduces context window usage while preserving key information for debugging. + tools: - name: "kubectl_describe" description: > @@ -17,6 +21,17 @@ toolsets: - 'describe pod xyz-123' - 'show service xyz-123 in namespace my-ns' command: "kubectl describe {{ kind }} {{ name }}{% if namespace %} -n {{ namespace }}{% endif %}" + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: | + Summarize this kubectl describe output focusing on: + - What needs attention or immediate action + - Resource status and health indicators + - Any errors, warnings, or non-standard states + - Key configuration details that could affect functionality + - When possible, mention exact field names so the user can grep for specific details - name: "kubectl_get_by_name" description: "Run `kubectl get --show-labels`" @@ -25,10 +40,34 @@ toolsets: - name: "kubectl_get_by_kind_in_namespace" description: "Run `kubectl get -n --show-labels` to get all resources of a given type in namespace" command: "kubectl get --show-labels -o wide {{ kind }} -n {{namespace}}" + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: | + Summarize this kubectl output focusing on: + - What needs attention or immediate action + - Group similar resources into aggregate descriptions + - Make sure to mention outliers, errors, and non-standard states + - List healthy resources as aggregate descriptions + - When listing unhealthy resources, also try to use aggregate descriptions when possible + - When possible, mention exact keywords so the user can rerun the command with | grep and drill down - name: "kubectl_get_by_kind_in_cluster" description: "Run `kubectl get -A --show-labels` to get all resources of a given type in the cluster" command: "kubectl get -A --show-labels -o wide {{ kind }}" + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: | + Summarize this kubectl output focusing on: + - What needs attention or immediate action + - Group similar resources into a single line and description + - Make sure to mention outliers, errors, and non-standard states + - List healthy resources as aggregate descriptions + - When listing unhealthy resources, also try to use aggregate descriptions when possible + - When possible, mention exact keywords so the user can rerun the command with | grep and drill down on the parts they care about - name: "kubectl_find_resource" description: "Run `kubectl get {{ kind }} -A --show-labels | grep {{ keyword }}` to find a resource where you know a substring of the name, IP, namespace, or labels" @@ -131,6 +170,18 @@ toolsets: description: > Use kubectl to get json for all resources of a specific kind pipe the results to jq to filter them. Do not worry about escaping the jq_expr it will be done by the system on an unescaped expression that you give. e.g. give an expression like .items[] | .spec.containers[].image | select(test("^gcr.io/") | not) command: kubectl get {{ kind }} --all-namespaces -o json | jq -r {{ jq_expr }} + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: | + Summarize this jq query output focusing on: + - Key patterns and commonalities in the data + - Notable outliers, anomalies, or items that need attention + - Group similar results into aggregate descriptions when possible + - Highlight any empty results, null values, or missing data + - When applicable, mention specific resource names, namespaces, or values that stand out + - Organize findings in a structured way that helps with troubleshooting - name: "kubernetes_count" user_description: "Count Kubernetes Resources: kubectl get {{kind}} --all-namespaces -o json | jq -c -r {{ jq_expr }}" diff --git a/holmes/plugins/toolsets/kubernetes_logs.yaml b/holmes/plugins/toolsets/kubernetes_logs.yaml index bdfa696791..82713886d4 100644 --- a/holmes/plugins/toolsets/kubernetes_logs.yaml +++ b/holmes/plugins/toolsets/kubernetes_logs.yaml @@ -8,6 +8,10 @@ toolsets: prerequisites: - command: "kubectl version --client" + # Note: Log tools use transformers with llm_summarize to automatically + # summarize large log outputs when a fast model is configured. This helps + # focus on errors, patterns, and key information while reducing context usage. + tools: - name: "kubectl_previous_logs" description: "Run `kubectl logs --previous` on a single Kubernetes pod. Used to fetch logs for a pod that crashed and see logs from before the crash. Never give a deployment name or a resource that is not a pod." @@ -24,10 +28,34 @@ toolsets: - name: "kubectl_logs" description: "Run `kubectl logs` on a single Kubernetes pod. Never give a deployment name or a resource that is not a pod." command: "kubectl logs {{pod_name}} -n {{ namespace }}" + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: | + Summarize these pod logs focusing on: + - Errors, exceptions, and warning messages + - Recent activity patterns and trends + - Any authentication, connection, or startup issues + - Performance indicators (response times, throughput) + - Group similar log entries together + - When possible, mention exact error codes or keywords for easier searching - name: "kubectl_logs_all_containers" description: "Run `kubectl logs` on all containers within a single Kubernetes pod." command: "kubectl logs {{pod_name}} -n {{ namespace }} --all-containers" + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: | + Summarize these multi-container pod logs focusing on: + - Errors, exceptions, and warning messages by container + - Inter-container communication patterns + - Any authentication, connection, or startup issues + - Performance indicators and resource usage patterns + - Group similar log entries together by container + - When possible, mention exact error codes or keywords for easier searching - name: "kubectl_container_logs" description: "Run `kubectl logs` on a single container within a Kubernetes pod. This is to get the logs of a specific container in a multi-container pod." diff --git a/holmes/utils/config_utils.py b/holmes/utils/config_utils.py new file mode 100644 index 0000000000..a13728b27a --- /dev/null +++ b/holmes/utils/config_utils.py @@ -0,0 +1,91 @@ +""" +Configuration utility functions for HolmesGPT. +""" + +from typing import List, Optional, TYPE_CHECKING + +if TYPE_CHECKING: + from holmes.core.transformers import Transformer + + +def merge_transformers( + base_transformers: Optional[List["Transformer"]], + override_transformers: Optional[List["Transformer"]], + only_merge_when_override_exists: bool = False, +) -> Optional[List["Transformer"]]: + """ + Merge transformer configurations with intelligent field-level merging. + + Logic: + - Override transformers take precedence for existing fields + - Base transformers provide missing fields + - Merge at transformer-type level (e.g., "llm_summarize") + + Args: + base_transformers: Base transformer configurations (e.g., global transformers) + override_transformers: Override transformer configurations (e.g., toolset transformers) + only_merge_when_override_exists: If True, only merge when override_transformers exist. + + Returns: + Merged transformer configuration list or None if both inputs are None/empty + """ + if not base_transformers and not override_transformers: + return None + if not base_transformers: + return override_transformers + if not override_transformers: + if only_merge_when_override_exists: + return None # Don't apply base transformers if override doesn't exist + else: + return base_transformers # Original behavior: return base transformers + + # Convert lists to dicts keyed by transformer name for easier merging + base_dict = {} + for transformer in base_transformers: + base_dict[transformer.name] = transformer + + override_dict = {} + for transformer in override_transformers: + override_dict[transformer.name] = transformer + + # Merge configurations at field level + merged_transformers = [] + + # Start with all base transformer types + for transformer_name, base_transformer in base_dict.items(): + if transformer_name in override_dict: + # Merge fields: override takes precedence, base provides missing fields + override_transformer = override_dict[transformer_name] + merged_config = dict(base_transformer.config) # Start with base + merged_config.update( + override_transformer.config + ) # Override with specific fields + + # IMPORTANT: Preserve global_fast_model from both base and override + # This ensures our injected global_fast_model settings aren't lost during merging + if "global_fast_model" in base_transformer.config: + merged_config["global_fast_model"] = base_transformer.config[ + "global_fast_model" + ] + if "global_fast_model" in override_transformer.config: + merged_config["global_fast_model"] = override_transformer.config[ + "global_fast_model" + ] + + # Create new transformer with merged config + from holmes.core.transformers import Transformer + + merged_transformer = Transformer( + name=transformer_name, config=merged_config + ) + merged_transformers.append(merged_transformer) + else: + # No override, use base transformer as-is + merged_transformers.append(base_transformer) + + # Add any override-only transformer types + for transformer_name, override_transformer in override_dict.items(): + if transformer_name not in base_dict: + merged_transformers.append(override_transformer) + + return merged_transformers diff --git a/tests/config_class/test_config_transformers.py b/tests/config_class/test_config_transformers.py new file mode 100644 index 0000000000..b3008cffc6 --- /dev/null +++ b/tests/config_class/test_config_transformers.py @@ -0,0 +1,260 @@ +""" +Unit tests for transformer configuration fields. + +These tests verify that the fast_model configuration +fields work correctly with different configuration sources (file, env, CLI). +""" + +import os +import tempfile +import yaml +from pathlib import Path +from unittest.mock import patch + + +def test_transformer_fields_exist(): + """Test that Config class has the transformer configuration fields.""" + # Mock the dependencies at their actual import locations + with patch("holmes.version.get_version", return_value="1.0.0"), patch( + "holmes.clients.robusta_client.fetch_holmes_info", return_value=None + ), patch("holmes.config.parse_models_file", return_value={}), patch( + "holmes.common.env_vars.ROBUSTA_AI", False + ): + from holmes.config import Config + from holmes.core.transformers import Transformer + + # Import Transformer class to resolve forward reference + import sys + + sys.modules[__name__].__dict__["Transformer"] = Transformer + + # Rebuild the model to resolve forward references + Config.model_rebuild() + + # Test default values + config = Config() + assert hasattr(config, "fast_model") + assert config.fast_model is None + + +def test_transformer_from_file(): + """Test loading transformer config from YAML file.""" + with patch("holmes.version.get_version", return_value="1.0.0"), patch( + "holmes.clients.robusta_client.fetch_holmes_info", return_value=None + ), patch("holmes.config.parse_models_file", return_value={}), patch( + "holmes.common.env_vars.ROBUSTA_AI", False + ): + from holmes.config import Config + from holmes.core.transformers import Transformer + import sys + + sys.modules[__name__].__dict__["Transformer"] = Transformer + Config.model_rebuild() + + with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f: + config_data = { + "fast_model": "gpt-4o-mini", + "model": "gpt-4o", + } + yaml.dump(config_data, f) + f.flush() + + try: + config = Config.load_from_file(Path(f.name)) + assert config.fast_model == "gpt-4o-mini" + assert config.model == "gpt-4o" + finally: + os.unlink(f.name) + + +def test_transformer_from_env(): + """Test loading transformer config from environment variables.""" + with patch("holmes.version.get_version", return_value="1.0.0"), patch( + "holmes.clients.robusta_client.fetch_holmes_info", return_value=None + ), patch("holmes.config.parse_models_file", return_value={}), patch( + "holmes.common.env_vars.ROBUSTA_AI", False + ): + from holmes.config import Config + from holmes.core.transformers import Transformer + import sys + + sys.modules[__name__].__dict__["Transformer"] = Transformer + Config.model_rebuild() + + with patch.dict( + os.environ, + { + "FAST_MODEL": "gpt-3.5-turbo", + "MODEL": "gpt-4o", + }, + ): + config = Config.load_from_env() + assert config.fast_model == "gpt-3.5-turbo" + assert config.model == "gpt-4o" + + +def test_transformer_cli_override(): + """Test that CLI options override config file values.""" + with patch("holmes.version.get_version", return_value="1.0.0"), patch( + "holmes.clients.robusta_client.fetch_holmes_info", return_value=None + ), patch("holmes.config.parse_models_file", return_value={}), patch( + "holmes.common.env_vars.ROBUSTA_AI", False + ): + from holmes.config import Config + from holmes.core.transformers import Transformer + import sys + + sys.modules[__name__].__dict__["Transformer"] = Transformer + Config.model_rebuild() + + with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f: + config_data = {"fast_model": "gpt-4o-mini"} + yaml.dump(config_data, f) + f.flush() + + try: + config = Config.load_from_file(Path(f.name), fast_model="gpt-3.5-turbo") + assert config.fast_model == "gpt-3.5-turbo" + finally: + os.unlink(f.name) + + +def test_transformer_backward_compatibility(): + """Test that existing configs without transformer fields still work.""" + with patch("holmes.version.get_version", return_value="1.0.0"), patch( + "holmes.clients.robusta_client.fetch_holmes_info", return_value=None + ), patch("holmes.config.parse_models_file", return_value={}), patch( + "holmes.common.env_vars.ROBUSTA_AI", False + ): + from holmes.config import Config + from holmes.core.transformers import Transformer + import sys + + sys.modules[__name__].__dict__["Transformer"] = Transformer + Config.model_rebuild() + + with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f: + config_data = {"model": "gpt-4o", "max_steps": 5} + yaml.dump(config_data, f) + f.flush() + + try: + config = Config.load_from_file(Path(f.name)) + assert config.model == "gpt-4o" + assert config.max_steps == 5 + # New fields should have defaults + assert config.fast_model is None + finally: + os.unlink(f.name) + + +def test_transformer_env_vars_in_load_from_env_list(): + """Test that the fast_model environment variable is properly loaded by load_from_env method.""" + # This tests that the fast_model field is correctly loaded from environment variables + with patch("holmes.version.get_version", return_value="1.0.0"), patch( + "holmes.clients.robusta_client.fetch_holmes_info", return_value=None + ), patch("holmes.config.parse_models_file", return_value={}), patch( + "holmes.common.env_vars.ROBUSTA_AI", False + ): + from holmes.config import Config + from holmes.core.transformers import Transformer + import sys + + sys.modules[__name__].__dict__["Transformer"] = Transformer + Config.model_rebuild() + + # Test that FAST_MODEL environment variable is properly loaded + with patch.dict(os.environ, {"FAST_MODEL": "test-model"}): + config = Config.load_from_env() + assert config.fast_model == "test-model" + + +def test_auto_generate_transformers_with_fast_model(): + """Test that Config stores fast_model for ToolsetManager injection.""" + with patch("holmes.version.get_version", return_value="1.0.0"), patch( + "holmes.clients.robusta_client.fetch_holmes_info", return_value=None + ), patch("holmes.config.parse_models_file", return_value={}), patch( + "holmes.common.env_vars.ROBUSTA_AI", False + ): + from holmes.config import Config + from holmes.core.transformers import Transformer + import sys + + sys.modules[__name__].__dict__["Transformer"] = Transformer + Config.model_rebuild() + + # Test with fast_model provided + config = Config(fast_model="gpt-4o-mini") + + # Should store fast_model for ToolsetManager injection + assert config.fast_model == "gpt-4o-mini" + # Should auto-generate transformers for backwards compatibility + assert config.transformers is not None + assert len(config.transformers) == 1 + assert config.transformers[0].name == "llm_summarize" + assert config.transformers[0].config["fast_model"] == "gpt-4o-mini" + + +def test_auto_generate_transformers_without_fast_model(): + """Test that transformers are not auto-generated when fast_model is not provided.""" + with patch("holmes.version.get_version", return_value="1.0.0"), patch( + "holmes.clients.robusta_client.fetch_holmes_info", return_value=None + ), patch("holmes.config.parse_models_file", return_value={}), patch( + "holmes.common.env_vars.ROBUSTA_AI", False + ): + from holmes.config import Config + from holmes.core.transformers import Transformer + import sys + + sys.modules[__name__].__dict__["Transformer"] = Transformer + Config.model_rebuild() + + # Test without fast_model + config = Config() + + # Should not auto-generate transformers + assert config.transformers is None + assert config.fast_model is None + + +def test_auto_generate_transformers_respects_existing_configs(): + """Test that existing transformers are not overridden by auto-generation.""" + with patch("holmes.version.get_version", return_value="1.0.0"), patch( + "holmes.clients.robusta_client.fetch_holmes_info", return_value=None + ), patch("holmes.config.parse_models_file", return_value={}), patch( + "holmes.common.env_vars.ROBUSTA_AI", False + ): + from holmes.config import Config + from holmes.core.transformers import Transformer + + # Test with existing transformers + existing_configs = [ + Transformer(name="custom_transformer", config={"param": "value"}) + ] + config = Config(fast_model="gpt-4o-mini", transformers=existing_configs) + + # Should preserve existing transformers + assert config.transformers == existing_configs + + +def test_auto_generate_transformers_cli_override(): + """Test that CLI fast_model parameter is stored for ToolsetManager injection.""" + with patch("holmes.version.get_version", return_value="1.0.0"), patch( + "holmes.clients.robusta_client.fetch_holmes_info", return_value=None + ), patch("holmes.config.parse_models_file", return_value={}), patch( + "holmes.common.env_vars.ROBUSTA_AI", False + ): + from holmes.config import Config + + # Test CLI override case (similar to holmes ask --fast-model) + config = Config.load_from_file( + None, # No config file + fast_model="azure/gpt-4.1", + ) + + # Should store fast_model for ToolsetManager injection and auto-generate transformers + assert config.fast_model == "azure/gpt-4.1" + assert config.transformers is not None + assert len(config.transformers) == 1 + assert config.transformers[0].name == "llm_summarize" + assert config.transformers[0].config["fast_model"] == "azure/gpt-4.1" diff --git a/tests/core/test_config_transformers.py b/tests/core/test_config_transformers.py new file mode 100644 index 0000000000..7ffb772574 --- /dev/null +++ b/tests/core/test_config_transformers.py @@ -0,0 +1,302 @@ +"""Tests for global transformer configuration inheritance.""" + +from unittest.mock import Mock, patch +import sys + +from holmes.config import Config +from holmes.core.toolset_manager import ToolsetManager +from holmes.core.tools import Toolset, Tool +from holmes.core.transformers import Transformer, registry + +# Setup global namespace for Config model rebuilding +sys.modules[__name__].__dict__["Transformer"] = Transformer +Config.model_rebuild() + + +class TestConfigTransformers: + """Test global transformer configuration functionality.""" + + def test_config_loads_transformers_from_dict(self): + """Test that Config correctly loads transformers from dict.""" + transformers = [ + Transformer( + name="llm_summarize", + config={"input_threshold": 1000, "prompt": "Test prompt"}, + ) + ] + config_data = { + "model": "gpt-4o", + "transformers": transformers, + } + + config = Config(**config_data) + + assert config.transformers is not None + assert len(config.transformers) == 1 + assert config.transformers[0].name == "llm_summarize" + assert config.transformers[0].config["input_threshold"] == 1000 + assert config.transformers[0].config["prompt"] == "Test prompt" + + def test_config_handles_none_transformers(self): + """Test that Config handles None transformers gracefully.""" + + config_data = {"model": "gpt-4o", "transformers": None} + + config = Config(**config_data) + + assert config.transformers is None + + def test_config_handles_empty_transformers(self): + """Test that Config handles empty transformers list.""" + + config_data = {"model": "gpt-4o", "transformers": []} + + config = Config(**config_data) + + assert config.transformers == [] + + def test_config_passes_fast_model_to_toolset_manager(self): + """Test that Config passes fast_model to ToolsetManager.""" + + config_data = {"model": "gpt-4o", "fast_model": "gpt-4o-mini"} + + config = Config(**config_data) + + # Access the toolset_manager property to trigger creation + toolset_manager = config.toolset_manager + + assert toolset_manager.global_fast_model == "gpt-4o-mini" + + @patch("holmes.config.ToolsetManager") + def test_toolset_manager_receives_fast_model(self, mock_toolset_manager): + """Test that ToolsetManager receives global fast_model.""" + + config_data = {"model": "gpt-4o", "fast_model": "gpt-4o-mini"} + + config = Config(**config_data) + + # Access toolset_manager to trigger creation + _ = config.toolset_manager + + # Verify ToolsetManager was called with global_fast_model + mock_toolset_manager.assert_called_once() + call_kwargs = mock_toolset_manager.call_args[1] + assert call_kwargs["global_fast_model"] == "gpt-4o-mini" + + +class TestToolsetManagerFastModel: + """Test ToolsetManager fast model injection functionality.""" + + def test_toolset_manager_stores_global_fast_model(self): + """Test that ToolsetManager stores global fast model.""" + global_fast_model = "gpt-4o-mini" + + manager = ToolsetManager(global_fast_model=global_fast_model) + + assert manager.global_fast_model == global_fast_model + + def test_inject_fast_model_to_transformers_with_existing_configs(self): + """Test that fast model is injected into transformers without fast_model config.""" + global_fast_model = "gpt-4o-mini" + + # Create a real Transformer instance with the config (not a mock) + mock_transformer = Transformer( + name="llm_summarize", config={"input_threshold": 1000} + ) + + mock_toolset = Mock(spec=Toolset) + mock_toolset.transformers = [mock_transformer] + mock_toolset.tools = [] + mock_toolset.name = "test_toolset" + + manager = ToolsetManager(global_fast_model=global_fast_model) + manager._inject_fast_model_into_transformers([mock_toolset]) + + # Should inject global_fast_model into transformer config + assert mock_transformer.config["global_fast_model"] == "gpt-4o-mini" + + def test_does_not_inject_when_fast_model_already_exists(self): + """Test that existing fast_model configs are not overridden.""" + global_fast_model = "gpt-4o-mini" + + # Create transformer with existing fast_model using real Transformer instance + mock_transformer = Transformer( + name="llm_summarize", + config={ + "input_threshold": 500, + "fast_model": "existing-model", + }, + ) + + mock_toolset = Mock(spec=Toolset) + mock_toolset.transformers = [mock_transformer] + mock_toolset.tools = [] + mock_toolset.name = "test_toolset" + + manager = ToolsetManager(global_fast_model=global_fast_model) + manager._inject_fast_model_into_transformers([mock_toolset]) + + # Should NOT override existing fast_model + assert mock_transformer.config["fast_model"] == "existing-model" + assert "global_fast_model" not in mock_transformer.config + + def test_inject_into_tool_level_transformers(self): + """Test that fast model is injected into tool-level transformers.""" + global_fast_model = "gpt-4o-mini" + + # Create mock tool with transformers that need fast_model using real Transformer + mock_tool_transformer = Transformer( + name="llm_summarize", config={"input_threshold": 200} + ) + + mock_tool = Mock(spec=Tool) + mock_tool.transformers = [mock_tool_transformer] + mock_tool.name = "test_tool" + mock_tool._transformer_instances = [] + + # Create mock toolset without toolset-level transformers + mock_toolset = Mock(spec=Toolset) + mock_toolset.transformers = None + mock_toolset.tools = [mock_tool] + mock_toolset.name = "test_toolset" + + # Mock the transformer registry + mock_instance = Mock() + with patch.object(registry, "create_transformer") as mock_create_transformer: + mock_create_transformer.return_value = mock_instance + + manager = ToolsetManager(global_fast_model=global_fast_model) + manager._inject_fast_model_into_transformers([mock_toolset]) + + # Should inject global_fast_model into tool transformer + assert mock_tool_transformer.config["global_fast_model"] == "gpt-4o-mini" + # Should recreate transformer instances + mock_create_transformer.assert_called_once_with( + "llm_summarize", mock_tool_transformer.config + ) + assert mock_tool._transformer_instances == [mock_instance] + + def test_skips_non_llm_summarize_transformers(self): + """Test that injection only affects llm_summarize transformers.""" + global_fast_model = "gpt-4o-mini" + + # Create transformers with different names using real Transformer instances + llm_transformer = Transformer( + name="llm_summarize", config={"input_threshold": 200} + ) + + other_transformer = Transformer( + name="custom_transformer", config={"some_param": "value"} + ) + + mock_toolset = Mock(spec=Toolset) + mock_toolset.transformers = [llm_transformer, other_transformer] + mock_toolset.tools = [] + mock_toolset.name = "test_toolset" + + manager = ToolsetManager(global_fast_model=global_fast_model) + manager._inject_fast_model_into_transformers([mock_toolset]) + + # Should inject into llm_summarize transformer + assert llm_transformer.config["global_fast_model"] == "gpt-4o-mini" + # Should NOT inject into other transformer + assert "global_fast_model" not in other_transformer.config + + def test_handles_none_global_fast_model_gracefully(self): + """Test that None global fast model is handled gracefully.""" + # Create mock toolset + mock_toolset = Mock(spec=Toolset) + mock_toolset.transformers = None + mock_toolset.tools = [] + mock_toolset.name = "test_toolset" + + manager = ToolsetManager(global_fast_model=None) + + # Should not raise an exception + manager._inject_fast_model_into_transformers([mock_toolset]) + + # Toolset configs should remain unchanged + assert mock_toolset.transformers is None + + def test_handles_empty_global_fast_model_gracefully(self): + """Test that empty global fast model is handled gracefully.""" + # Create mock toolset + mock_toolset = Mock(spec=Toolset) + mock_toolset.transformers = None + mock_toolset.tools = [] + mock_toolset.name = "test_toolset" + + manager = ToolsetManager(global_fast_model="") + + # Should not raise an exception and should not inject + manager._inject_fast_model_into_transformers([mock_toolset]) + + # Toolset configs should remain unchanged + assert mock_toolset.transformers is None + + +class TestFastModelInjectionIntegration: + """Integration tests for fast model injection functionality.""" + + def test_fast_model_injection_end_to_end(self): + """Test complete fast model injection: ToolsetManager → Transformers.""" + global_fast_model = "gpt-4o-mini" + + # Create transformers with different configurations using real Transformer instances + toolset_transformer = Transformer( + name="llm_summarize", config={"input_threshold": 500} + ) + + tool_transformer = Transformer( + name="llm_summarize", config={"input_threshold": 200} + ) + + existing_fast_model_transformer = Transformer( + name="llm_summarize", config={"fast_model": "existing-model"} + ) + + # Create tools + tool_with_transformers = Mock(spec=Tool) + tool_with_transformers.transformers = [tool_transformer] + tool_with_transformers.name = "tool1" + tool_with_transformers._transformer_instances = [] + + tool_with_existing_fast_model = Mock(spec=Tool) + tool_with_existing_fast_model.transformers = [existing_fast_model_transformer] + tool_with_existing_fast_model.name = "tool2" + tool_with_existing_fast_model._transformer_instances = [] + + # Create toolset with transformers and tools + toolset_with_transformers = Mock(spec=Toolset) + toolset_with_transformers.transformers = [toolset_transformer] + toolset_with_transformers.tools = [ + tool_with_transformers, + tool_with_existing_fast_model, + ] + toolset_with_transformers.name = "test_toolset" + + # Mock transformer recreation + mock_instance = Mock() + with patch("holmes.core.transformers.registry") as mock_registry: + mock_registry.create_transformer.return_value = mock_instance + + # Apply fast model injection + manager = ToolsetManager(global_fast_model=global_fast_model) + manager._inject_fast_model_into_transformers([toolset_with_transformers]) + + # Verify injection results: + # 1. Toolset transformer should get global_fast_model + assert toolset_transformer.config["global_fast_model"] == "gpt-4o-mini" + + # 2. Tool transformer should get global_fast_model + assert tool_transformer.config["global_fast_model"] == "gpt-4o-mini" + + # 3. Transformer with existing fast_model should remain unchanged + assert "global_fast_model" not in existing_fast_model_transformer.config + assert existing_fast_model_transformer.config["fast_model"] == "existing-model" + + # 4. Only tool transformers should trigger instance recreation + # (toolset transformers don't have _transformer_instances) + assert ( + mock_registry.create_transformer.call_count == 1 + ) # Only tool should get recreation diff --git a/tests/core/test_tool_transformers.py b/tests/core/test_tool_transformers.py new file mode 100644 index 0000000000..e221e3bfb8 --- /dev/null +++ b/tests/core/test_tool_transformers.py @@ -0,0 +1,827 @@ +""" +Unit tests for Phase 2.1: Tool transformer integration and validation. +""" + +from typing import Dict +from unittest.mock import Mock, patch + +from holmes.core.tools import ( + Tool, + YAMLTool, + YAMLToolset, + ToolsetYamlFromConfig, + StructuredToolResult, + ToolResultStatus, +) +from holmes.core.transformers import ( + registry, + TransformerError, + Transformer, +) +from holmes.core.transformers.base import BaseTransformer + + +class MockTransformer(BaseTransformer): + """Mock transformer for testing.""" + + def transform(self, input_text: str) -> str: + return f"mock_transformed: {input_text}" + + def should_apply(self, input_text: str) -> bool: + return len(input_text) > 5 + + @property + def name(self) -> str: + return "mock_transformer" + + +class TestToolTransformField: + """Test that Tool and YAMLTool accept transformers field.""" + + def test_tool_with_transforms(self): + """Test that Tool accepts transformers field.""" + transformers = [ + Transformer(name="llm_summarize", config={"input_threshold": 500}) + ] + + # Create a concrete tool for testing + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> Mock: + return Mock() + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", + description="Test tool with transformers", + transformers=transformers, + ) + + assert tool.transformers == transformers + + def test_yaml_tool_with_transforms(self): + """Test that YAMLTool accepts transformers field.""" + transformers = [ + Transformer(name="llm_summarize", config={"input_threshold": 1000}) + ] + + tool = YAMLTool( + name="test_yaml_tool", + description="Test YAML tool with transformers", + command="echo 'test'", + transformers=transformers, + ) + + assert tool.transformers == transformers + + def test_tool_without_transforms(self): + """Test that tools work without transformers field.""" + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> Mock: + return Mock() + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", description="Test tool without transformers" + ) + + assert tool.transformers is None + + +class TestToolsetTransformers: + """Test that Toolset classes accept transformers parameter.""" + + def test_toolset_with_transformers(self): + """Test that Toolset accepts transformers field.""" + transformers = [ + Transformer(name="llm_summarize", config={"input_threshold": 800}) + ] + + toolset = YAMLToolset( + name="test_toolset", + description="Test toolset with transformers", + transformers=transformers, + tools=[], + ) + + assert toolset.transformers == transformers + + def test_toolset_yaml_from_config_with_transformers(self): + """Test that ToolsetYamlFromConfig accepts transformers.""" + transformers = [ + Transformer(name="llm_summarize", config={"input_threshold": 1200}) + ] + + toolset = ToolsetYamlFromConfig( + name="test_config_toolset", transformers=transformers + ) + + assert toolset.transformers == transformers + + def test_toolset_transformers_propagation(self): + """Test that toolset transformers propagate to tools that don't have their own.""" + toolset_transformers = [ + Transformer(name="llm_summarize", config={"input_threshold": 600}) + ] + + # Create toolset with transformers + toolset_data = { + "name": "test_toolset", + "description": "Test toolset", + "transformers": toolset_transformers, + "tools": [ + { + "name": "tool_without_transforms", + "description": "Tool without its own transforms", + "command": "echo 'test1'", + }, + { + "name": "tool_with_transforms", + "description": "Tool with its own transforms", + "command": "echo 'test2'", + "transformers": [ + Transformer( + name="llm_summarize", config={"input_threshold": 300} + ) + ], + }, + ], + } + + toolset = YAMLToolset(**toolset_data) + + # Tool without transforms should inherit from toolset + assert toolset.tools[0].transformers == toolset_transformers + + # Tool with transforms should have merged configs (toolset + tool) + tool_with_transforms = toolset.tools[1] + assert tool_with_transforms.transformers is not None + assert len(tool_with_transforms.transformers) == 1 + # The tool should get the merged config (override takes precedence) + assert tool_with_transforms.transformers[0].config["input_threshold"] == 300 + + +class TestToolValidationIntegration: + """Test transformer validation integration in Tool classes.""" + + def setup_method(self): + """Set up test fixtures.""" + registry.register(MockTransformer) + + def teardown_method(self): + """Clean up test fixtures.""" + if registry.is_registered("mock_transformer"): + registry.unregister("mock_transformer") + + def test_tool_validation_success(self): + """Test tool creation succeeds with valid transforms.""" + transforms = [Transformer(name="mock_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> Mock: + return Mock() + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transforms + ) + + assert tool.transformers == transforms + + def test_tool_validation_clears_invalid_transforms(self): + """Test tool creation with invalid transformers logs warning but continues.""" + # Note: Tool.__init__ validates transformers during instantiation + # Invalid transformers will cause validation to fail during model creation + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> Mock: + return Mock() + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + # Test creating tool with valid transformers works + valid_transforms = [Transformer(name="mock_transformer", config={})] + tool = ConcreteTestTool( + name="test_tool", + description="Test tool", + transformers=valid_transforms, + ) + + assert tool.transformers == valid_transforms + + def test_yaml_tool_validation(self): + """Test YAMLTool transformer validation.""" + transforms = [Transformer(name="mock_transformer", config={})] + + tool = YAMLTool( + name="test_yaml_tool", + description="Test YAML tool", + command="echo 'test'", + transformers=transforms, + ) + + assert tool.transformers == transforms + + +class TestBackwardCompatibility: + """Test that existing tools continue to work without transformers.""" + + def test_existing_yaml_tool_compatibility(self): + """Test that existing YAML tools work without transforms.""" + tool = YAMLTool( + name="legacy_tool", + description="Legacy tool without transforms", + command="echo 'legacy'", + ) + + assert tool.transformers is None + assert tool.name == "legacy_tool" + + def test_existing_toolset_compatibility(self): + """Test that existing toolsets work without transformers.""" + toolset = YAMLToolset( + name="legacy_toolset", description="Legacy toolset", tools=[] + ) + + assert toolset.transformers is None + assert toolset.name == "legacy_toolset" + + def test_mixed_old_new_tools(self): + """Test toolset with mix of tools with and without transforms.""" + toolset_data = { + "name": "mixed_toolset", + "description": "Mixed toolset", + "tools": [ + { + "name": "legacy_tool", + "description": "Legacy tool", + "command": "echo 'legacy'", + }, + { + "name": "new_tool", + "description": "New tool with transforms", + "command": "echo 'new'", + "transformers": [Transformer(name="llm_summarize", config={})], + }, + ], + } + + toolset = YAMLToolset(**toolset_data) + + assert toolset.tools[0].transformers is None + assert toolset.tools[1].transformers == [ + Transformer(name="llm_summarize", config={}) + ] + + +class TestToolExecutionPipeline: + """Test Tool Execution Pipeline with transformers.""" + + def setup_method(self): + """Set up test fixtures.""" + registry.register(MockTransformer) + + def teardown_method(self): + """Clean up test fixtures.""" + if registry.is_registered("mock_transformer"): + registry.unregister("mock_transformer") + + def test_successful_tool_execution_with_transformers(self): + """Test that tools execute successfully and apply transformers.""" + transforms = [Transformer(name="mock_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="This is a long test output that should be transformed", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transforms + ) + + result = tool.invoke({}) + + # Should have applied transformation + assert result.status == ToolResultStatus.SUCCESS + assert result.data is not None + assert "mock_transformed:" in result.data + assert "This is a long test output that should be transformed" in result.data + + def test_tool_execution_skips_transformers_on_error(self): + """Test that transformers are not applied when tool execution fails.""" + transforms = [Transformer(name="mock_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.ERROR, + error="Tool execution failed", + data="Some error output", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transforms + ) + + result = tool.invoke({}) + + # Should not have applied transformation due to error status + assert result.status == ToolResultStatus.ERROR + assert "mock_transformed:" not in str(result.data) + assert result.data == "Some error output" + + def test_tool_execution_skips_transformers_on_empty_data(self): + """Test that transformers are not applied when data is empty.""" + transforms = [Transformer(name="mock_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult(status=ToolResultStatus.NO_DATA, data="") + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transforms + ) + + result = tool.invoke({}) + + # Should not have applied transformation due to empty data + assert result.status == ToolResultStatus.NO_DATA + assert result.data == "" + + def test_transformer_failure_handling(self): + """Test that transformer failures are handled gracefully.""" + + # Create a transformer that will fail + class FailingTransformer(BaseTransformer): + def transform(self, input_text: str) -> str: + raise TransformerError("Transformer failed") + + def should_apply(self, input_text: str) -> bool: + return True + + @property + def name(self) -> str: + return "failing_transformer" + + registry.register(FailingTransformer) + + try: + transforms = [Transformer(name="failing_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, data="Test output" + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", + description="Test tool", + transformers=transforms, + ) + + with patch("holmes.core.tools.logger") as mock_logging: + result = tool.invoke({}) + + # Should return original data when transformer fails + assert result.status == ToolResultStatus.SUCCESS + assert result.data == "Test output" + + # Should log warning about transformer failure + mock_logging.warning.assert_called() + warning_call = mock_logging.warning.call_args[0][0] + assert "failing_transformer" in warning_call + assert "failed" in warning_call + + finally: + if registry.is_registered("failing_transformer"): + registry.unregister("failing_transformer") + + def test_multiple_transformers_chaining(self): + """Test that multiple transformers are applied in sequence.""" + + class SecondTransformer(BaseTransformer): + def transform(self, input_text: str) -> str: + return f"second_transformed: {input_text}" + + def should_apply(self, input_text: str) -> bool: + return True + + @property + def name(self) -> str: + return "second_transformer" + + registry.register(SecondTransformer) + + try: + transforms = [ + Transformer(name="mock_transformer", config={}), + Transformer(name="second_transformer", config={}), + ] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Original text that should be transformed twice", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", + description="Test tool", + transformers=transforms, + ) + + result = tool.invoke({}) + + # Should have applied both transformations in sequence + assert result.status == ToolResultStatus.SUCCESS + assert result.data is not None + assert "second_transformed:" in result.data + assert "mock_transformed:" in result.data + + finally: + if registry.is_registered("second_transformer"): + registry.unregister("second_transformer") + + def test_transformer_conditional_application(self): + """Test that transformers are only applied when should_apply returns True.""" + + class ConditionalTransformer(BaseTransformer): + def transform(self, input_text: str) -> str: + return f"conditional_transformed: {input_text}" + + def should_apply(self, input_text: str) -> bool: + # Only apply to inputs longer than 10 characters + return len(input_text) > 10 + + @property + def name(self) -> str: + return "conditional_transformer" + + registry.register(ConditionalTransformer) + + try: + transforms = [Transformer(name="conditional_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + data = params.get("data", "short") + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, data=data + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", + description="Test tool", + transformers=transforms, + ) + + # Test with short input - should not transform + result = tool.invoke({"data": "short"}) + assert result.data == "short" + assert ( + result.data is not None + and "conditional_transformed:" not in result.data + ) + + # Test with long input - should transform + result = tool.invoke( + {"data": "this is a very long input that should be transformed"} + ) + assert result.data is not None + assert "conditional_transformed:" in result.data + + finally: + if registry.is_registered("conditional_transformer"): + registry.unregister("conditional_transformer") + + def test_transformer_preserves_original_result_structure(self): + """Test that transformer only modifies data field, preserving other result fields.""" + transforms = [Transformer(name="mock_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Test output to transform", + url="http://example.com", + invocation="test command", + params={"test": "param"}, + return_code=0, + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transforms + ) + + result = tool.invoke({}) + + # Data should be transformed + assert result.data is not None + assert "mock_transformed:" in result.data + + # Other fields should be preserved + assert result.status == ToolResultStatus.SUCCESS + assert result.url == "http://example.com" + assert result.invocation == "test command" + assert result.params == {"test": "param"} + assert result.return_code == 0 + + def test_performance_metrics_logging(self): + """Test that transformer performance metrics are logged.""" + transforms = [Transformer(name="mock_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Test output that will be transformed for performance measurement", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transforms + ) + + with patch("holmes.core.tools.logger") as mock_logging: + tool.invoke({}) + + # Should log transformer application with performance metrics + info_calls = [call[0][0] for call in mock_logging.info.call_args_list] + transformer_log = next( + (call for call in info_calls if "Applied transformer" in call), None + ) + + assert transformer_log is not None + assert "mock_transformer" in transformer_log + assert "test_tool" in transformer_log + assert "size:" in transformer_log + assert "chars" in transformer_log + + def test_tool_without_transformers_unchanged(self): + """Test that tools without transformers work exactly as before.""" + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Test output without transformation", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", + description="Test tool", + # No transformers + ) + + result = tool.invoke({}) + + # Should return unchanged result + assert result.status == ToolResultStatus.SUCCESS + assert result.data == "Test output without transformation" + + +class TestTransformerCachingOptimization: + """Test the transformer caching optimization behavior.""" + + def setup_method(self): + """Set up test fixtures.""" + # Register mock transformer for tests + if not registry.is_registered("mock_transformer"): + registry.register(MockTransformer) + + def teardown_method(self): + """Clean up test fixtures.""" + # Unregister mock transformer + if registry.is_registered("mock_transformer"): + registry.unregister("mock_transformer") + + def test_transformer_instances_cached_during_initialization(self): + """Test that transformer instances are created once during tool initialization and cached.""" + transformers = [Transformer(name="mock_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Test output for transformation", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + # Create tool - this should trigger model_post_init and cache transformers + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transformers + ) + + # Verify that transformer instances are cached + assert tool._transformer_instances is not None + assert len(tool._transformer_instances) == 1 + assert tool._transformer_instances[0].name == "mock_transformer" + + # Verify the cached instance is a real transformer, not a config + cached_transformer = tool._transformer_instances[0] + assert hasattr(cached_transformer, "transform") + assert hasattr(cached_transformer, "should_apply") + + def test_transformer_instances_reused_across_multiple_calls(self): + """Test that the same transformer instances are reused across multiple tool invocations.""" + transformers = [Transformer(name="mock_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Test output for transformation", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transformers + ) + + # Get reference to cached transformer instance + initial_transformer = tool._transformer_instances[0] + initial_id = id(initial_transformer) + + # Invoke the tool multiple times + result1 = tool.invoke({}) + result2 = tool.invoke({}) + result3 = tool.invoke({}) + + # Verify that the same transformer instance is still cached + assert tool._transformer_instances[0] is initial_transformer + assert id(tool._transformer_instances[0]) == initial_id + + # Verify transformations worked correctly + assert "mock_transformed:" in result1.data + assert "mock_transformed:" in result2.data + assert "mock_transformed:" in result3.data + + def test_model_post_init_with_no_transformers(self): + """Test that model_post_init handles tools with no transformers correctly.""" + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Test output without transformers", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + # Create tool without transformers + tool = ConcreteTestTool( + name="test_tool", + description="Test tool", + # No transformers + ) + + # Verify that _transformer_instances is None + assert tool._transformer_instances is None + + # Verify tool still works correctly + result = tool.invoke({}) + assert result.status == ToolResultStatus.SUCCESS + assert result.data == "Test output without transformers" + + def test_transformer_initialization_failure_handling(self): + """Test graceful handling when transformer initialization fails during model_post_init.""" + + # Create a transformer config that will fail to initialize + transformers = [ + Transformer(name="nonexistent_transformer", config={}), + Transformer(name="mock_transformer", config={}), # This one should succeed + ] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Test output for transformation", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + # Create tool - initialization should handle the failure gracefully + with patch("logging.warning") as mock_warning: + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transformers + ) + + # Verify that warning was logged for failed transformer + mock_warning.assert_called() + warning_calls = [ + call + for call in mock_warning.call_args_list + if "nonexistent_transformer" in str(call) + ] + assert len(warning_calls) > 0 + + # Verify that only the successful transformer was cached + assert tool._transformer_instances is not None + assert len(tool._transformer_instances) == 1 + assert tool._transformer_instances[0].name == "mock_transformer" + + # Verify tool still works with the successful transformer + result = tool.invoke({}) + assert result.status == ToolResultStatus.SUCCESS + assert "mock_transformed:" in result.data + + def test_transformer_initialization_empty_transformers_list(self): + """Test that model_post_init handles empty transformers list correctly.""" + transformers = [] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Test output", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transformers + ) + + # Empty transformers list should result in None (no transformer processing needed) + assert tool._transformer_instances is None + + # Tool should still work correctly + result = tool.invoke({}) + assert result.status == ToolResultStatus.SUCCESS + assert result.data == "Test output" + + def test_performance_optimization_prevents_recreation(self): + """Test that transformers are not recreated on each tool call.""" + transformers = [Transformer(name="mock_transformer", config={})] + + class ConcreteTestTool(Tool): + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Test output for transformation", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "test command" + + tool = ConcreteTestTool( + name="test_tool", description="Test tool", transformers=transformers + ) + + # Mock the registry.create_transformer to track calls + with patch.object( + registry, "create_transformer", wraps=registry.create_transformer + ) as mock_create: + # Invoke the tool multiple times + tool.invoke({}) + tool.invoke({}) + tool.invoke({}) + + # create_transformer should NOT be called during tool invocation + # It should only be called during initialization (which happened before this patch) + mock_create.assert_not_called() diff --git a/tests/core/test_toolset_manager.py b/tests/core/test_toolset_manager.py index b1723bd87f..b00a21c598 100644 --- a/tests/core/test_toolset_manager.py +++ b/tests/core/test_toolset_manager.py @@ -342,3 +342,141 @@ def test_mcp_servers_from_config(toolset_manager): assert len(toolset_manager.toolsets) == 1 assert "mcp1" in toolset_manager.toolsets assert toolset_manager.toolsets["mcp1"]["type"] == ToolsetType.MCP.value + + +# Tests for transformer config merging functionality + + +def test_inject_fast_model_with_existing_transformers(): + """Test that global fast model is injected into existing transformer configs.""" + from holmes.core.transformers import Transformer + + global_fast_model = "gpt-4o-mini" + + # Create toolset with existing transformers (should get injection) + toolset = YAMLToolset( + name="test_toolset", + tags=[ToolsetTag.CORE], + description="Test toolset", + transformers=[ + Transformer( + name="llm_summarize", + config={"input_threshold": 1000, "prompt": "Custom"}, + ) + ], + ) + + manager = ToolsetManager(global_fast_model=global_fast_model) + manager._inject_fast_model_into_transformers([toolset]) + + # Verify injection occurred + assert toolset.transformers is not None + config_dict = {t.name: t.config for t in toolset.transformers} + + # Should have global_fast_model injected, original config preserved + assert config_dict["llm_summarize"]["global_fast_model"] == "gpt-4o-mini" + assert config_dict["llm_summarize"]["input_threshold"] == 1000 # Original + assert config_dict["llm_summarize"]["prompt"] == "Custom" # Original + + +def test_no_injection_when_no_transformers(): + """Test that no injection occurs when toolset has no transformers (new behavior).""" + + global_fast_model = "gpt-4o-mini" + + # Create toolset without transformers + toolset = YAMLToolset( + name="test_toolset", tags=[ToolsetTag.CORE], description="Test toolset" + ) + + manager = ToolsetManager(global_fast_model=global_fast_model) + manager._inject_fast_model_into_transformers([toolset]) + + # No injection should occur when toolset has no transformers + assert toolset.transformers is None + + +def test_no_injection_when_no_global_fast_model(): + """Test that nothing happens when no global fast model is provided.""" + from holmes.core.transformers import Transformer + + toolset = YAMLToolset( + name="test_toolset", + tags=[ToolsetTag.CORE], + description="Test toolset", + transformers=[ + Transformer(name="llm_summarize", config={"input_threshold": 1000}) + ], + ) + original_transformers = toolset.transformers + + manager = ToolsetManager() # No global fast model + manager._inject_fast_model_into_transformers([toolset]) + + # Toolset configs should remain unchanged (no injection) + assert toolset.transformers == original_transformers + assert "global_fast_model" not in toolset.transformers[0].config + + +def test_injection_only_affects_llm_summarize_transformers(): + """Test that injection only affects llm_summarize transformers, not others.""" + from holmes.core.transformers import Transformer + + global_fast_model = "gpt-4o-mini" + + toolset = YAMLToolset( + name="test_toolset", + tags=[ToolsetTag.CORE], + description="Test toolset", + transformers=[ + Transformer(name="llm_summarize", config={"input_threshold": 1000}), + Transformer(name="custom_transformer", config={"param": "value"}), + ], + ) + + manager = ToolsetManager(global_fast_model=global_fast_model) + manager._inject_fast_model_into_transformers([toolset]) + + # Check that only llm_summarize got injection + config_dict = {t.name: t.config for t in toolset.transformers} + + assert "llm_summarize" in config_dict + assert "custom_transformer" in config_dict + assert config_dict["llm_summarize"]["global_fast_model"] == "gpt-4o-mini" + assert "global_fast_model" not in config_dict["custom_transformer"] + assert config_dict["custom_transformer"]["param"] == "value" # Unchanged + + +@patch("holmes.core.toolset_manager.load_builtin_toolsets") +def test_list_all_toolsets_applies_fast_model_injection(mock_load_builtin_toolsets): + """Integration test that global fast model is injected during toolset loading.""" + from holmes.core.transformers import Transformer + + # Create toolset with transformers + toolset = YAMLToolset( + name="kubernetes", + tags=[ToolsetTag.CORE], + description="Kubernetes toolset", + transformers=[ + Transformer( + name="llm_summarize", + config={"input_threshold": 1000, "prompt": "K8s prompt"}, + ) + ], + ) + mock_load_builtin_toolsets.return_value = [toolset] + + # Create manager with CLI fast_model + global_fast_model = "azure/gpt-4.1" + manager = ToolsetManager(global_fast_model=global_fast_model) + + # Load toolsets (this triggers injection) + result = manager._list_all_toolsets(check_prerequisites=False) + + # Verify the toolset received the global_fast_model injection + kubernetes_toolset = next(t for t in result if t.name == "kubernetes") + config_dict = {t.name: t.config for t in kubernetes_toolset.transformers} + + assert config_dict["llm_summarize"]["global_fast_model"] == "azure/gpt-4.1" + assert config_dict["llm_summarize"]["input_threshold"] == 1000 # Original + assert config_dict["llm_summarize"]["prompt"] == "K8s prompt" # Original diff --git a/tests/core/test_transformer_backwards_compatibility.py b/tests/core/test_transformer_backwards_compatibility.py new file mode 100644 index 0000000000..41a1ec81af --- /dev/null +++ b/tests/core/test_transformer_backwards_compatibility.py @@ -0,0 +1,283 @@ +"""Tests for backwards compatibility of transformer configuration changes.""" + +from unittest.mock import Mock, patch +from pathlib import Path +import sys + +from holmes.config import Config +from holmes.core.toolset_manager import ToolsetManager +from holmes.core.tools import Toolset, Tool +from holmes.core.transformers import Transformer + +# Setup global namespace for Config model rebuilding +sys.modules[__name__].__dict__["Transformer"] = Transformer +Config.model_rebuild() + + +class TestBackwardsCompatibility: + """Test that existing configurations continue to work unchanged.""" + + def test_existing_config_without_transformers_works(self): + """Test that existing configs without transformers still work.""" + # Simulate an existing config file without transformers + config_data = {"model": "gpt-4o", "api_key": "test-key", "max_steps": 5} + + # Should not raise any exceptions + config = Config(**config_data) + + assert config.model == "gpt-4o" + assert config.transformers is None + assert config.max_steps == 5 + + def test_existing_toolsets_without_transformers_work(self): + """Test that existing toolsets without transformers continue to work.""" + # Create a toolset without transformers (existing behavior) + mock_tool = Mock(spec=Tool) + mock_tool.transformers = None + mock_tool.name = "test_tool" + + mock_toolset = Mock(spec=Toolset) + mock_toolset.transformers = None + mock_toolset.tools = [mock_tool] + mock_toolset.name = "test_toolset" + + # Create ToolsetManager without global fast model (existing behavior) + manager = ToolsetManager() + + # Should not raise any exceptions + manager._inject_fast_model_into_transformers([mock_toolset]) + + # Nothing should change (no injection occurs when no global_fast_model) + assert mock_toolset.transformers is None + assert mock_tool.transformers is None + + def test_existing_toolsets_with_transformers_unchanged(self): + """Test that existing toolsets with transformers get global_fast_model injection.""" + existing_tool_configs = [ + Transformer(name="llm_summarize", config={"input_threshold": 300}) + ] + existing_toolset_configs = [ + Transformer(name="llm_summarize", config={"input_threshold": 600}) + ] + + # Create tool and toolset with existing configs + mock_tool = Mock(spec=Tool) + mock_tool.transformers = existing_tool_configs + mock_tool.name = "test_tool" + mock_tool._transformer_instances = [] + + mock_toolset = Mock(spec=Toolset) + mock_toolset.transformers = existing_toolset_configs + mock_toolset.tools = [mock_tool] + mock_toolset.name = "test_toolset" + + # Apply global fast model + global_fast_model = "gpt-4o-mini" + + with patch("holmes.core.transformers.registry") as mock_registry: + mock_instance = Mock() + mock_registry.create_transformer.return_value = mock_instance + + manager = ToolsetManager(global_fast_model=global_fast_model) + manager._inject_fast_model_into_transformers([mock_toolset]) + + # Existing configs should get global_fast_model injected + assert existing_tool_configs[0].config["global_fast_model"] == "gpt-4o-mini" + assert ( + existing_toolset_configs[0].config["global_fast_model"] == "gpt-4o-mini" + ) + + # Original config values should remain + assert existing_tool_configs[0].config["input_threshold"] == 300 + assert existing_toolset_configs[0].config["input_threshold"] == 600 + + def test_config_load_from_file_backwards_compatible(self): + """Test that Config.load_from_file works with existing config files.""" + # Mock an existing config file without transformers + mock_config_content = { + "model": "gpt-4o", + "max_steps": 10, + "alertmanager_url": "http://localhost:9093", + } + + with patch("holmes.config.load_model_from_file") as mock_load: + mock_load.return_value = Config(**mock_config_content) + + with patch("pathlib.Path.exists") as mock_exists: + mock_exists.return_value = True + + # Should load successfully without transformers + config = Config.load_from_file(Path("fake_config.yaml")) + + assert config.model == "gpt-4o" + assert config.max_steps == 10 + assert config.transformers is None + + def test_config_load_from_env_backwards_compatible(self): + """Test that Config.load_from_env works as before.""" + test_env = {"MODEL": "gpt-4o", "API_KEY": "test-key", "MAX_STEPS": "8"} + + with patch.dict("os.environ", test_env): + with patch( + "holmes.config.Config._Config__get_cluster_name" + ) as mock_cluster: + mock_cluster.return_value = "test-cluster" + + config = Config.load_from_env() + + assert config.model == "gpt-4o" + assert config.max_steps == 8 + assert config.transformers is None + + def test_toolset_preprocess_tools_still_works(self): + """Test that Toolset.preprocess_tools validator still works with Transformer objects.""" + # Test the existing behavior for toolset-level transformers + values = { + "additional_instructions": "Test instructions", + "transformers": [ + Transformer(name="llm_summarize", config={"input_threshold": 500}) + ], + "tools": [ + { + "name": "test_tool", + "description": "Test tool", + # No transformers - should inherit from toolset + }, + { + "name": "tool_with_configs", + "description": "Tool with configs", + "transformers": [ + Transformer( + name="llm_summarize", config={"input_threshold": 200} + ) + ], + # Has its own configs - should not inherit + }, + ], + } + + # Import the actual validator + from holmes.core.tools import Toolset + + # Call the validator (this is what Pydantic does internally) + processed_values = Toolset.preprocess_tools(values) + + # Check that existing behavior is preserved + assert ( + processed_values["tools"][0]["additional_instructions"] + == "Test instructions" + ) + assert ( + processed_values["tools"][1]["additional_instructions"] + == "Test instructions" + ) + + # Tool without configs should inherit toolset configs (as Transformer objects) + tool0_transformers = processed_values["tools"][0]["transformers"] + assert len(tool0_transformers) == 1 + assert tool0_transformers[0].name == "llm_summarize" + assert tool0_transformers[0].config["input_threshold"] == 500 + + # Tool with configs should keep its own (as Transformer objects) + tool1_transformers = processed_values["tools"][1]["transformers"] + assert len(tool1_transformers) == 1 + assert tool1_transformers[0].name == "llm_summarize" + assert tool1_transformers[0].config["input_threshold"] == 200 + + def test_yaml_toolsets_continue_working(self): + """Test that YAML toolsets without transformers continue working.""" + # This would be a typical YAML toolset definition without transformers + yaml_toolset_data = { + "name": "test/toolset", + "description": "Test toolset", + "enabled": True, + "tools": [ + { + "name": "test_tool", + "description": "Test tool", + "command": "echo 'test'", + } + ], + } + + # Should create successfully without transformers + from holmes.core.tools import YAMLToolset + + toolset = YAMLToolset(**yaml_toolset_data) + + assert toolset.name == "test/toolset" + assert toolset.transformers is None + assert len(toolset.tools) == 1 + assert toolset.tools[0].transformers is None + + def test_python_toolsets_continue_working(self): + """Test that Python toolsets without transformers continue working.""" + # Simulate existing Python toolset without transformers + from holmes.core.tools import Toolset, Tool + + # Create a basic tool without transformers + basic_tool = Mock(spec=Tool) + basic_tool.name = "basic_tool" + basic_tool.transformers = None + + # Create toolset data without transformers + toolset_data = { + "name": "test/python_toolset", + "description": "Test Python toolset", + "tools": [basic_tool], + } + + # Should work exactly as before + class TestToolset(Toolset): + def get_example_config(self): + return {} + + toolset = TestToolset(**toolset_data) + + assert toolset.name == "test/python_toolset" + assert toolset.transformers is None + assert len(toolset.tools) == 1 + + def test_no_regression_in_tool_execution(self): + """Test that tool execution behavior hasn't regressed.""" + # Mock a tool without transformers + from holmes.core.tools import StructuredToolResult, ToolResultStatus + + class TestTool(Tool): + def _invoke(self, params): + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, data="test output" + ) + + def get_parameterized_one_liner(self, params): + return "test tool execution" + + tool = TestTool(name="test_tool", description="Test tool", transformers=None) + + # Tool should execute normally without transformers + result = tool.invoke({}) + + assert result.status == ToolResultStatus.SUCCESS + assert result.data == "test output" + + def test_toolset_manager_backwards_compatible_constructor(self): + """Test that ToolsetManager constructor is backwards compatible.""" + # Old way of creating ToolsetManager (without global_fast_model) + manager = ToolsetManager( + toolsets={"test": {"enabled": True}}, + custom_toolsets=None, + custom_toolsets_from_cli=None, + ) + + # Should work fine + assert manager.toolsets == {"test": {"enabled": True}} + assert manager.global_fast_model is None + + # New way should also work + global_fast_model = "gpt-4o-mini" + manager_with_fast_model = ToolsetManager( + toolsets={"test": {"enabled": True}}, + global_fast_model=global_fast_model, + ) + + assert manager_with_fast_model.global_fast_model == global_fast_model diff --git a/tests/core/transformers/__init__.py b/tests/core/transformers/__init__.py new file mode 100644 index 0000000000..abb53fad3c --- /dev/null +++ b/tests/core/transformers/__init__.py @@ -0,0 +1 @@ +"""Init file for transformer tests.""" diff --git a/tests/core/transformers/test_llm_summarize.py b/tests/core/transformers/test_llm_summarize.py new file mode 100644 index 0000000000..4f6f185e8a --- /dev/null +++ b/tests/core/transformers/test_llm_summarize.py @@ -0,0 +1,471 @@ +""" +Unit tests for LLMSummarizeTransformer. +""" + +import pytest +from unittest.mock import Mock, patch +from pydantic import ValidationError + +from holmes.core.transformers.llm_summarize import LLMSummarizeTransformer +from holmes.core.transformers.base import TransformerError + + +class TestLLMSummarizeTransformer: + """Test cases for LLMSummarizeTransformer class.""" + + def create_mock_llm(self, response_content: str = "Summarized content"): + """Create a mock LLM that returns the specified response.""" + mock_llm = Mock() + mock_response = Mock() + mock_choice = Mock() + mock_message = Mock() + + mock_message.content = response_content + mock_choice.message = mock_message + mock_response.choices = [mock_choice] + mock_llm.completion.return_value = mock_response + + return mock_llm + + def test_init_with_no_config(self): + """Test transformer initialization without config.""" + transformer = LLMSummarizeTransformer() + assert transformer.input_threshold == 1000 # default value + assert transformer.prompt is None # default value + assert transformer.fast_model is None # default value + assert transformer.api_key is None # default value + assert transformer._fast_llm is None + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_init_with_fast_model_config(self, mock_default_llm): + """Test transformer initialization with fast_model config.""" + mock_llm_instance = self.create_mock_llm() + mock_default_llm.return_value = mock_llm_instance + + transformer = LLMSummarizeTransformer( + input_threshold=500, + prompt="Custom prompt", + fast_model="gpt-4o-mini", + api_key="test-key", + ) + + assert transformer.input_threshold == 500 + assert transformer.prompt == "Custom prompt" + assert transformer.fast_model == "gpt-4o-mini" + assert transformer.api_key == "test-key" + assert transformer._fast_llm is mock_llm_instance + mock_default_llm.assert_called_once_with("gpt-4o-mini", "test-key") + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_init_with_fast_model_no_api_key(self, mock_default_llm): + """Test transformer initialization with fast_model but no API key.""" + mock_llm_instance = self.create_mock_llm() + mock_default_llm.return_value = mock_llm_instance + + transformer = LLMSummarizeTransformer(fast_model="gpt-4o-mini") + + assert transformer._fast_llm is mock_llm_instance + mock_default_llm.assert_called_once_with("gpt-4o-mini", None) + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_init_fast_model_creation_failure(self, mock_default_llm): + """Test transformer initialization handles LLM creation failure.""" + mock_default_llm.side_effect = Exception("LLM creation failed") + + transformer = LLMSummarizeTransformer(fast_model="invalid-model") + + assert transformer._fast_llm is None + mock_default_llm.assert_called_once_with("invalid-model", None) + + def test_name_property(self): + """Test transformer name property.""" + transformer = LLMSummarizeTransformer() + assert transformer.name == "llm_summarize" + + def test_config_validation_success(self): + """Test successful config validation.""" + with patch("holmes.core.transformers.llm_summarize.DefaultLLM"): + transformer = LLMSummarizeTransformer( + input_threshold=100, + prompt="Valid prompt", + fast_model="gpt-4o-mini", + ) + assert transformer.input_threshold == 100 + assert transformer.prompt == "Valid prompt" + assert transformer.fast_model == "gpt-4o-mini" + + def test_config_validation_invalid_threshold(self): + """Test config validation with invalid threshold.""" + # Negative threshold + with pytest.raises(ValidationError): + LLMSummarizeTransformer(input_threshold=-1) + + # Non-integer threshold + with pytest.raises(ValidationError): + LLMSummarizeTransformer(input_threshold="invalid") + + # Non-integer threshold (float) - Pydantic v2 will reject this + with pytest.raises(ValidationError): + LLMSummarizeTransformer(input_threshold=100.5) + + def test_config_validation_invalid_prompt(self): + """Test config validation with invalid prompt.""" + # Empty prompt + with pytest.raises(ValidationError): + LLMSummarizeTransformer(prompt="") + + # Non-string prompt + with pytest.raises(ValidationError): + LLMSummarizeTransformer(prompt=123) + + def test_config_validation_invalid_fast_model(self): + """Test config validation with invalid fast_model.""" + # Empty fast_model + with pytest.raises(ValidationError): + LLMSummarizeTransformer(fast_model="") + + # Non-string fast_model + with pytest.raises(ValidationError): + LLMSummarizeTransformer(fast_model=123) + + def test_should_apply_no_fast_model(self): + """Test should_apply when no fast model is configured.""" + transformer = LLMSummarizeTransformer() + + # Should not apply regardless of input length + assert not transformer.should_apply("short") + assert not transformer.should_apply("a" * 2000) # Very long input + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_should_apply_with_fast_model_default_threshold(self, mock_default_llm): + """Test should_apply with fast model and default threshold.""" + mock_default_llm.return_value = self.create_mock_llm() + transformer = LLMSummarizeTransformer(fast_model="gpt-4o-mini") + + # Default threshold is 1000 characters + short_text = "a" * 999 + long_text = "a" * 1001 + + assert not transformer.should_apply(short_text) + assert transformer.should_apply(long_text) + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_should_apply_with_custom_threshold(self, mock_default_llm): + """Test should_apply with custom threshold.""" + mock_default_llm.return_value = self.create_mock_llm() + transformer = LLMSummarizeTransformer( + fast_model="gpt-4o-mini", input_threshold=500 + ) + + short_text = "a" * 499 + exact_threshold = "a" * 500 + long_text = "a" * 501 + + assert not transformer.should_apply(short_text) + assert not transformer.should_apply(exact_threshold) # <= threshold, not > + assert transformer.should_apply(long_text) + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_transform_success_default_prompt(self, mock_default_llm): + """Test successful transformation with default prompt.""" + mock_llm = self.create_mock_llm("This is a summary") + mock_default_llm.return_value = mock_llm + transformer = LLMSummarizeTransformer(fast_model="gpt-4o-mini") + + input_text = "Original content to be summarized" + result = transformer.transform(input_text) + + assert result == "This is a summary" + + # Verify the LLM was called with correct prompt + mock_llm.completion.assert_called_once() + call_args = mock_llm.completion.call_args[0][0] + assert len(call_args) == 1 + assert call_args[0]["role"] == "user" + assert "Original content to be summarized" in call_args[0]["content"] + assert transformer.DEFAULT_PROMPT in call_args[0]["content"] + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_transform_success_custom_prompt(self, mock_default_llm): + """Test successful transformation with custom prompt.""" + mock_llm = self.create_mock_llm("Custom summary") + mock_default_llm.return_value = mock_llm + custom_prompt = "Summarize this in a custom way" + transformer = LLMSummarizeTransformer( + fast_model="gpt-4o-mini", prompt=custom_prompt + ) + + input_text = "Content to summarize" + result = transformer.transform(input_text) + + assert result == "Custom summary" + + # Verify custom prompt was used + call_args = mock_llm.completion.call_args[0][0] + assert custom_prompt in call_args[0]["content"] + assert transformer.DEFAULT_PROMPT not in call_args[0]["content"] + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_transform_strips_whitespace(self, mock_default_llm): + """Test that transformation strips whitespace from response.""" + mock_llm = self.create_mock_llm(" Summary with whitespace ") + mock_default_llm.return_value = mock_llm + transformer = LLMSummarizeTransformer(fast_model="gpt-4o-mini") + + result = transformer.transform("input text") + assert result == "Summary with whitespace" + + def test_transform_no_fast_model(self): + """Test transform fails when no fast model is configured.""" + transformer = LLMSummarizeTransformer() + + with pytest.raises( + TransformerError, match="Cannot transform: no fast model configured" + ): + transformer.transform("input text") + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_transform_empty_response(self, mock_default_llm): + """Test transform fails when model returns empty response.""" + mock_llm = self.create_mock_llm("") + mock_default_llm.return_value = mock_llm + transformer = LLMSummarizeTransformer(fast_model="gpt-4o-mini") + + with pytest.raises(TransformerError, match="Fast model returned empty summary"): + transformer.transform("input text") + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_transform_whitespace_only_response(self, mock_default_llm): + """Test transform fails when model returns whitespace-only response.""" + mock_llm = self.create_mock_llm(" ") + mock_default_llm.return_value = mock_llm + transformer = LLMSummarizeTransformer(fast_model="gpt-4o-mini") + + with pytest.raises(TransformerError, match="Fast model returned empty summary"): + transformer.transform("input text") + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_transform_llm_exception(self, mock_default_llm): + """Test transform handles LLM exceptions properly.""" + mock_llm = Mock() + mock_llm.completion.side_effect = Exception("LLM API error") + mock_default_llm.return_value = mock_llm + transformer = LLMSummarizeTransformer(fast_model="gpt-4o-mini") + + with pytest.raises( + TransformerError, + match="Failed to summarize content with fast model: LLM API error", + ): + transformer.transform("input text") + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_transform_malformed_response(self, mock_default_llm): + """Test transform handles malformed LLM response.""" + mock_llm = Mock() + mock_response = Mock() + mock_response.choices = [] # Empty choices + mock_llm.completion.return_value = mock_response + mock_default_llm.return_value = mock_llm + transformer = LLMSummarizeTransformer(fast_model="gpt-4o-mini") + + with pytest.raises( + TransformerError, match="Failed to summarize content with fast model" + ): + transformer.transform("input text") + + def test_default_prompt_content(self): + """Test that default prompt contains expected guidelines.""" + transformer = LLMSummarizeTransformer() + + # Check key elements of the default prompt + assert "attention or immediate action" in transformer.DEFAULT_PROMPT + assert "Group similar entries" in transformer.DEFAULT_PROMPT + assert ( + "outliers, errors, and non-standard patterns" in transformer.DEFAULT_PROMPT + ) + assert "exact keywords" in transformer.DEFAULT_PROMPT + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_prompt_construction(self, mock_default_llm): + """Test that prompts are properly constructed with content.""" + mock_llm = self.create_mock_llm("test response") + mock_default_llm.return_value = mock_llm + custom_prompt = "Custom summarization prompt" + transformer = LLMSummarizeTransformer( + fast_model="gpt-4o-mini", prompt=custom_prompt + ) + + input_text = "Test content" + transformer.transform(input_text) + + # Verify prompt structure + call_args = mock_llm.completion.call_args[0][0] + full_prompt = call_args[0]["content"] + + assert full_prompt.startswith(custom_prompt) + assert "Content to summarize:" in full_prompt + assert full_prompt.endswith(input_text) + + +class TestLLMSummarizeTransformerIntegration: + """Integration tests for LLMSummarizeTransformer.""" + + def create_mock_llm(self, response_content: str = "Summarized content"): + """Create a mock LLM that returns the specified response.""" + mock_llm = Mock() + mock_response = Mock() + mock_choice = Mock() + mock_message = Mock() + + mock_message.content = response_content + mock_choice.message = mock_message + mock_response.choices = [mock_choice] + mock_llm.completion.return_value = mock_response + + return mock_llm + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_end_to_end_summarization_workflow(self, mock_default_llm): + """Test complete summarization workflow.""" + mock_llm = self.create_mock_llm( + "Summarized: kubectl shows 3 healthy pods, 1 failing" + ) + mock_default_llm.return_value = mock_llm + transformer = LLMSummarizeTransformer( + fast_model="gpt-4o-mini", input_threshold=100 + ) + + # Simulate large kubectl output + large_output = """ +NAME READY STATUS RESTARTS AGE +webapp-deployment-abc123-def456 1/1 Running 0 2d +webapp-deployment-abc123-ghi789 1/1 Running 0 2d +webapp-deployment-abc123-jkl012 1/1 Running 0 2d +database-deployment-mno345-pqr678 0/1 Error 3 1d +service/webapp-service ClusterIP 10.0.1.100 80/TCP 2d +service/database-service ClusterIP 10.0.1.101 5432/TCP 2d + """.strip() + + # Should apply due to length + assert transformer.should_apply(large_output) + + # Transform and verify + result = transformer.transform(large_output) + assert result == "Summarized: kubectl shows 3 healthy pods, 1 failing" + + # Verify LLM was called with full output + mock_llm.completion.assert_called_once() + call_args = mock_llm.completion.call_args[0][0] + assert large_output in call_args[0]["content"] + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_conditional_application_workflow(self, mock_default_llm): + """Test that transformation is conditionally applied based on threshold.""" + mock_llm = self.create_mock_llm("Should not be called") + mock_default_llm.return_value = mock_llm + transformer = LLMSummarizeTransformer( + fast_model="gpt-4o-mini", input_threshold=1000 + ) + + # Small output that shouldn't be summarized + small_output = "pod/webapp-123 is running" + + # Should not apply + assert not transformer.should_apply(small_output) + + # Large output that should be summarized + large_output = "a" * 1001 + assert transformer.should_apply(large_output) + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_error_handling_workflow(self, mock_default_llm): + """Test error handling in real-world scenarios.""" + # Test with failing LLM + mock_llm = Mock() + mock_llm.completion.side_effect = ConnectionError("Network timeout") + mock_default_llm.return_value = mock_llm + transformer = LLMSummarizeTransformer(fast_model="gpt-4o-mini") + + with pytest.raises(TransformerError) as exc_info: + transformer.transform("input to summarize") + + # Verify error is properly wrapped and chained + assert "Failed to summarize content with fast model" in str(exc_info.value) + assert isinstance(exc_info.value.__cause__, ConnectionError) + assert "Network timeout" in str(exc_info.value.__cause__) + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_different_threshold_scenarios(self, mock_default_llm): + """Test various threshold scenarios.""" + mock_llm = self.create_mock_llm("summary") + + test_cases = [ + (0, "x", True), # Zero threshold, any input > 0 applies + (1, "", False), # Empty input, any positive threshold + (5, "short", False), # Input exactly at threshold (not >) + (5, "longer", True), # Input above threshold + (1000, "x" * 999, False), # Just below default + (1000, "x" * 1000, False), # Exactly at threshold + (1000, "x" * 1001, True), # Above threshold + ] + + for threshold, input_text, expected in test_cases: + mock_default_llm.return_value = mock_llm + transformer = LLMSummarizeTransformer( + fast_model="gpt-4o-mini", input_threshold=threshold + ) + + result = transformer.should_apply(input_text) + assert ( + result == expected + ), f"Failed for threshold={threshold}, input_len={len(input_text)}" + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_multiple_transformer_instances(self, mock_default_llm): + """Test using multiple transformer instances with different configs.""" + mock_llm1 = self.create_mock_llm("Summary 1") + mock_llm2 = self.create_mock_llm("Summary 2") + + def mock_llm_side_effect(model, api_key): + if model == "gpt-4o-mini": + return mock_llm1 + elif model == "gpt-3.5-turbo": + return mock_llm2 + return Mock() + + mock_default_llm.side_effect = mock_llm_side_effect + + transformer1 = LLMSummarizeTransformer( + fast_model="gpt-4o-mini", + input_threshold=10, + prompt="Brief summary:", + ) + + transformer2 = LLMSummarizeTransformer( + fast_model="gpt-3.5-turbo", + input_threshold=20, + prompt="Detailed summary:", + ) + + test_input = "This is test input content" + + # Both should apply (length > both thresholds) + assert transformer1.should_apply(test_input) + assert transformer2.should_apply(test_input) + + # Transform with both + result1 = transformer1.transform(test_input) + result2 = transformer2.transform(test_input) + + assert result1 == "Summary 1" + assert result2 == "Summary 2" + + # Verify each used their own LLM and prompt + mock_llm1.completion.assert_called_once() + mock_llm2.completion.assert_called_once() + + call1 = mock_llm1.completion.call_args[0][0][0]["content"] + call2 = mock_llm2.completion.call_args[0][0][0]["content"] + + assert "Brief summary:" in call1 + assert "Detailed summary:" in call2 diff --git a/tests/core/transformers/test_transformers.py b/tests/core/transformers/test_transformers.py new file mode 100644 index 0000000000..bd3e81d0c8 --- /dev/null +++ b/tests/core/transformers/test_transformers.py @@ -0,0 +1,344 @@ +""" +Unit tests for transformer base classes and registry. +""" + +import pytest +from pydantic import Field + +from holmes.core.transformers.base import BaseTransformer, TransformerError +from holmes.core.transformers.registry import TransformerRegistry + + +class MockTransformer(BaseTransformer): + """Mock transformer for testing.""" + + def transform(self, input_text: str) -> str: + return f"transformed: {input_text}" + + def should_apply(self, input_text: str) -> bool: + return len(input_text) > 10 + + @property + def name(self) -> str: + return "mock" + + +class ThresholdTransformer(BaseTransformer): + """Transformer with configurable threshold for testing.""" + + threshold: int = Field( + default=5, ge=0, description="Threshold for triggering transformation" + ) + + def transform(self, input_text: str) -> str: + return input_text.upper() + + def should_apply(self, input_text: str) -> bool: + return len(input_text) > self.threshold + + @property + def name(self) -> str: + return "threshold" + + +class FailingTransformer(BaseTransformer): + """Transformer that always fails for testing error handling.""" + + def transform(self, input_text: str) -> str: + raise RuntimeError("Transformation failed") + + def should_apply(self, input_text: str) -> bool: + return True + + @property + def name(self) -> str: + return "failing" + + +class TestBaseTransformer: + """Test cases for BaseTransformer class.""" + + def test_init_with_no_config(self): + """Test transformer initialization without config.""" + transformer = MockTransformer() + # Pydantic models don't have a 'config' attribute - they have field values directly + assert hasattr(transformer, "model_fields") + + def test_init_with_config(self): + """Test transformer initialization with config.""" + # ThresholdTransformer has a threshold field + transformer = ThresholdTransformer(threshold=100) + assert transformer.threshold == 100 + + def test_name_property(self): + """Test transformer name property.""" + transformer = MockTransformer() + assert transformer.name == "mock" + + def test_transform_method(self): + """Test transform method execution.""" + transformer = MockTransformer() + result = transformer.transform("test input") + assert result == "transformed: test input" + + def test_should_apply_method(self): + """Test should_apply method logic.""" + transformer = MockTransformer() + + # Short input should not apply + assert not transformer.should_apply("short") + + # Long input should apply + assert transformer.should_apply("this is a longer input") + + def test_config_validation_success(self): + """Test successful config validation.""" + transformer = ThresholdTransformer(threshold=100) + assert transformer.threshold == 100 + + def test_config_validation_failure(self): + """Test config validation failure.""" + from pydantic import ValidationError + + with pytest.raises(ValidationError): + ThresholdTransformer(threshold=-1) + + def test_threshold_transformer_behavior(self): + """Test transformer with configurable threshold.""" + # Default threshold (5) + transformer = ThresholdTransformer() + assert not transformer.should_apply("short") + assert transformer.should_apply("longer text") + + # Custom threshold (20) + transformer = ThresholdTransformer(threshold=20) + assert not transformer.should_apply("short text") + assert transformer.should_apply("this is a much longer text input") + + def test_abstract_methods_must_be_implemented(self): + """Test that abstract methods must be implemented.""" + + class IncompleteTransformer(BaseTransformer): + pass + + with pytest.raises(TypeError): + IncompleteTransformer() # type: ignore[abstract] + + +class TestTransformerRegistry: + """Test cases for TransformerRegistry class.""" + + def setup_method(self): + """Set up test registry for each test.""" + self.registry = TransformerRegistry() + + def test_register_transformer(self): + """Test registering a transformer.""" + self.registry.register(MockTransformer) + assert self.registry.is_registered("mock") + assert "mock" in self.registry.list_transformers() + + def test_register_duplicate_name(self): + """Test registering transformer with duplicate name fails.""" + self.registry.register(MockTransformer) + + # Create another transformer with the same name + class DuplicateMockTransformer(BaseTransformer): + def transform(self, input_text: str) -> str: + return f"duplicate: {input_text}" + + def should_apply(self, input_text: str) -> bool: + return True + + @property + def name(self) -> str: + return "mock" # Same name as MockTransformer + + with pytest.raises( + ValueError, match="Transformer 'mock' is already registered" + ): + self.registry.register(DuplicateMockTransformer) + + def test_register_invalid_transformer_class(self): + """Test registering invalid transformer class fails.""" + + class NotATransformer: + pass + + with pytest.raises( + ValueError, match="Transformer class must inherit from BaseTransformer" + ): + self.registry.register(NotATransformer) # type: ignore[abstract] + + def test_unregister_transformer(self): + """Test unregistering a transformer.""" + self.registry.register(MockTransformer) + assert self.registry.is_registered("mock") + + self.registry.unregister("mock") + assert not self.registry.is_registered("mock") + assert "mock" not in self.registry.list_transformers() + + def test_unregister_nonexistent_transformer(self): + """Test unregistering non-existent transformer fails.""" + with pytest.raises( + KeyError, match="Transformer 'nonexistent' is not registered" + ): + self.registry.unregister("nonexistent") + + def test_create_transformer_success(self): + """Test successful transformer creation.""" + self.registry.register(MockTransformer) + transformer = self.registry.create_transformer("mock") + + assert isinstance(transformer, MockTransformer) + # Pydantic models don't have a config attribute + assert hasattr(transformer, "model_fields") + + def test_create_transformer_with_config(self): + """Test transformer creation with config.""" + self.registry.register(ThresholdTransformer) + config = {"threshold": 15} + transformer = self.registry.create_transformer("threshold", config) + + assert isinstance(transformer, ThresholdTransformer) + assert transformer.threshold == 15 + + def test_create_transformer_nonexistent(self): + """Test creating non-existent transformer fails.""" + with pytest.raises( + KeyError, match="Transformer 'nonexistent' is not registered" + ): + self.registry.create_transformer("nonexistent") + + def test_create_transformer_initialization_failure(self): + """Test transformer creation with initialization failure.""" + self.registry.register(ThresholdTransformer) + + with pytest.raises( + TransformerError, match="Failed to create transformer 'threshold'" + ): + self.registry.create_transformer("threshold", {"threshold": -1}) + + def test_is_registered(self): + """Test checking if transformer is registered.""" + assert not self.registry.is_registered("mock") + + self.registry.register(MockTransformer) + assert self.registry.is_registered("mock") + + def test_list_transformers_empty(self): + """Test listing transformers when registry is empty.""" + assert self.registry.list_transformers() == [] + + def test_list_transformers_multiple(self): + """Test listing multiple registered transformers.""" + self.registry.register(MockTransformer) + self.registry.register(ThresholdTransformer) + + transformers = self.registry.list_transformers() + assert len(transformers) == 2 + assert "mock" in transformers + assert "threshold" in transformers + + def test_clear_registry(self): + """Test clearing all transformers from registry.""" + self.registry.register(MockTransformer) + self.registry.register(ThresholdTransformer) + assert len(self.registry.list_transformers()) == 2 + + self.registry.clear() + assert len(self.registry.list_transformers()) == 0 + + def test_transformer_creation_preserves_isolation(self): + """Test that created transformers are independent instances.""" + self.registry.register(ThresholdTransformer) + + transformer1 = self.registry.create_transformer("threshold", {"threshold": 10}) + transformer2 = self.registry.create_transformer("threshold", {"threshold": 20}) + + assert transformer1 is not transformer2 + assert transformer1.threshold == 10 + assert transformer2.threshold == 20 + + +class TestTransformerIntegration: + """Integration tests combining transformers and registry.""" + + def setup_method(self): + """Set up test registry for each test.""" + self.registry = TransformerRegistry() + self.registry.register(MockTransformer) + self.registry.register(ThresholdTransformer) + + def test_end_to_end_transformation(self): + """Test complete transformation workflow.""" + transformer = self.registry.create_transformer("mock") + + input_text = "this is a test input" + + # Check if transformation should apply + assert transformer.should_apply(input_text) + + # Perform transformation + result = transformer.transform(input_text) + assert result == "transformed: this is a test input" + + def test_conditional_transformation(self): + """Test transformation that conditionally applies.""" + transformer = self.registry.create_transformer("threshold", {"threshold": 20}) + + short_text = "short" + long_text = "this is a much longer text that exceeds the threshold" + + # Short text should not be transformed + assert not transformer.should_apply(short_text) + + # Long text should be transformed + assert transformer.should_apply(long_text) + result = transformer.transform(long_text) + assert result == long_text.upper() + + def test_multiple_transformer_instances(self): + """Test using multiple transformer instances simultaneously.""" + mock_transformer = self.registry.create_transformer("mock") + threshold_transformer = self.registry.create_transformer( + "threshold", {"threshold": 5} + ) + + test_input = "test input text" + + # Both transformers should apply + assert mock_transformer.should_apply(test_input) + assert threshold_transformer.should_apply(test_input) + + # Transform with both + mock_result = mock_transformer.transform(test_input) + threshold_result = threshold_transformer.transform(test_input) + + assert mock_result == "transformed: test input text" + assert threshold_result == "TEST INPUT TEXT" + + +class TestTransformerError: + """Test cases for TransformerError exception.""" + + def test_transformer_error_creation(self): + """Test creating TransformerError.""" + error = TransformerError("Test error message") + assert str(error) == "Test error message" + assert isinstance(error, Exception) + + def test_transformer_error_in_registry(self): + """Test TransformerError raised by registry.""" + registry = TransformerRegistry() + registry.register(FailingTransformer) + + # Creation should succeed + transformer = registry.create_transformer("failing") + + # But transformation should fail with TransformerError would be caught + # at the tool execution level, not here. The transformer itself + # raises RuntimeError, which is expected behavior. + with pytest.raises(RuntimeError, match="Transformation failed"): + transformer.transform("test input") diff --git a/tests/integration/test_config_merging_integration.py b/tests/integration/test_config_merging_integration.py new file mode 100644 index 0000000000..c1672dea44 --- /dev/null +++ b/tests/integration/test_config_merging_integration.py @@ -0,0 +1,406 @@ +""" +Integration tests for config merging functionality. +Tests the complete CLI --fast-model workflow with real-world toolset configurations. +""" + +from unittest.mock import patch + +from holmes.core.tools import YAMLTool, YAMLToolset, ToolsetTag +from holmes.core.transformers import Transformer +from holmes.core.toolset_manager import ToolsetManager + + +def create_kubernetes_toolset(): + """Create a Kubernetes toolset similar to the real one with transformers.""" + # Create tools with transformers like the real Kubernetes toolset + kubectl_describe = YAMLTool( + name="kubectl_describe", + description="Run kubectl describe", + command="kubectl describe {{ kind }} {{ name }}", + transformers=[ + Transformer( + name="llm_summarize", + config={ + "input_threshold": 1000, + "prompt": "Summarize kubectl describe output...", + }, + ) + ], + ) + + kubectl_get = YAMLTool( + name="kubectl_get_by_kind_in_namespace", + description="Run kubectl get", + command="kubectl get {{ kind }} -n {{ namespace }}", + transformers=[ + Transformer( + name="llm_summarize", + config={ + "input_threshold": 1000, + "prompt": "Summarize kubectl output...", + }, + ) + ], + ) + + # Create toolset without fast_model (like real YAML configs) + return YAMLToolset( + name="kubernetes/core", + tags=[ToolsetTag.CORE], + description="Kubernetes toolset", + tools=[kubectl_describe, kubectl_get], + ) + + +def test_cli_fast_model_integration_with_kubernetes(): + """ + Integration test: CLI --fast-model should work with Kubernetes toolset. + This is the critical test case from the plan. + """ + # Simulate CLI --fast-model setting + global_fast_model = "azure/gpt-4.1" + + kubernetes_toolset = create_kubernetes_toolset() + + with patch("holmes.core.toolset_manager.load_builtin_toolsets") as mock_load: + mock_load.return_value = [kubernetes_toolset] + + manager = ToolsetManager(global_fast_model=global_fast_model) + toolsets = manager._list_all_toolsets(check_prerequisites=False) + + # Find the Kubernetes toolset + k8s_toolset = next(t for t in toolsets if t.name == "kubernetes/core") + + # Verify that tools inherited the fast_model from global config + kubectl_describe = next( + t for t in k8s_toolset.tools if t.name == "kubectl_describe" + ) + + # Extract transformer config + config_dict = {t.name: t.config for t in kubectl_describe.transformers} + + # Verify injection worked correctly + assert ( + config_dict["llm_summarize"]["global_fast_model"] == "azure/gpt-4.1" + ) # From CLI + assert config_dict["llm_summarize"]["input_threshold"] == 1000 # From YAML + assert "prompt" in config_dict["llm_summarize"] # From YAML + + +def test_fast_model_injection_chain(): + """ + Test the fast model injection: global_fast_model → llm_summarize transformers + """ + # Global fast model (CLI --fast-model) + global_fast_model = "gpt-4.1" + + # Tool with specific transformer (no fast_model - should get injection) + tool_with_transformer = YAMLTool( + name="specific_tool", + description="Tool with transformer", + command="echo test", + transformers=[ + Transformer(name="llm_summarize", config={"input_threshold": 2000}) + ], + ) + + # Tool without transformers (should inherit from toolset) + tool_without_transformer = YAMLTool( + name="generic_tool", description="Generic tool", command="echo generic" + ) + + # Toolset with transformers (should get injection) + toolset = YAMLToolset( + name="test_toolset", + tags=[ToolsetTag.CORE], + description="Test toolset", + transformers=[ + Transformer( + name="llm_summarize", + config={"input_threshold": 1000, "prompt": "Toolset prompt"}, + ) + ], + tools=[tool_with_transformer, tool_without_transformer], + ) + + with patch("holmes.core.toolset_manager.load_builtin_toolsets") as mock_load: + mock_load.return_value = [toolset] + + manager = ToolsetManager(global_fast_model=global_fast_model) + toolsets = manager._list_all_toolsets(check_prerequisites=False) + + test_toolset = toolsets[0] + + # Check toolset transformer (should get global_fast_model injection) + assert test_toolset.transformers is not None + toolset_config = {t.name: t.config for t in test_toolset.transformers} + assert toolset_config["llm_summarize"]["global_fast_model"] == "gpt-4.1" + assert toolset_config["llm_summarize"]["input_threshold"] == 1000 # Original + assert "Toolset prompt" in toolset_config["llm_summarize"]["prompt"] + + # Check tool with transformer (should get global_fast_model injection) + specific_tool = next(t for t in test_toolset.tools if t.name == "specific_tool") + assert specific_tool.transformers is not None + specific_config = {t.name: t.config for t in specific_tool.transformers} + assert specific_config["llm_summarize"]["global_fast_model"] == "gpt-4.1" + assert specific_config["llm_summarize"]["input_threshold"] == 2000 # Original + + # Check tool without transformers (should inherit from toolset and get injection) + generic_tool = next(t for t in test_toolset.tools if t.name == "generic_tool") + assert generic_tool.transformers is not None + generic_config = {t.name: t.config for t in generic_tool.transformers} + assert generic_config["llm_summarize"]["global_fast_model"] == "gpt-4.1" + assert ( + generic_config["llm_summarize"]["input_threshold"] == 1000 + ) # From toolset + assert ( + "Toolset prompt" in generic_config["llm_summarize"]["prompt"] + ) # From toolset + + +def test_fast_model_injection_with_different_transformers(): + """ + Test that fast model injection works correctly with different transformer configurations. + """ + global_fast_model = "gpt-4o-mini" + + # Transformer that should get injection + toolset_configs = [ + Transformer( + name="llm_summarize", + config={"input_threshold": 1000, "prompt": "Toolset prompt"}, + ) + ] + + # Tool transformer that should get injection + tool_configs = [ + Transformer(name="llm_summarize", config={"prompt": "Custom prompt"}) + ] + + tool = YAMLTool( + name="multi_transformer_tool", + description="Tool with transformer", + command="echo test", + transformers=tool_configs, + ) + + toolset = YAMLToolset( + name="multi_transformer_toolset", + tags=[ToolsetTag.CORE], + description="Multi transformer toolset", + transformers=toolset_configs, + tools=[tool], + ) + + with patch("holmes.core.toolset_manager.load_builtin_toolsets") as mock_load: + mock_load.return_value = [toolset] + + manager = ToolsetManager(global_fast_model=global_fast_model) + toolsets = manager._list_all_toolsets(check_prerequisites=False) + + result_toolset = toolsets[0] + result_tool = result_toolset.tools[0] + + # Check toolset transformer got injection + assert result_toolset.transformers is not None + toolset_config = {t.name: t.config for t in result_toolset.transformers} + assert toolset_config["llm_summarize"]["global_fast_model"] == "gpt-4o-mini" + assert toolset_config["llm_summarize"]["input_threshold"] == 1000 # Original + assert "Toolset prompt" in toolset_config["llm_summarize"]["prompt"] + + # Check tool transformer got injection + assert result_tool.transformers is not None + final_config = {t.name: t.config for t in result_tool.transformers} + assert final_config["llm_summarize"]["global_fast_model"] == "gpt-4o-mini" + assert "Custom prompt" in final_config["llm_summarize"]["prompt"] + + # Should have 1 transformer type + assert len(final_config) == 1 + + +def test_backward_compatibility(): + """ + Test that toolsets without transformers still work correctly (no injection occurs). + """ + global_fast_model = "gpt-4o-mini" + + # Toolset without transformers (like some existing toolsets) + simple_toolset = YAMLToolset( + name="simple_toolset", + tags=[ToolsetTag.CORE], + description="Simple toolset without transformers", + tools=[YAMLTool(name="simple_tool", description="Simple", command="echo")], + ) + + with patch("holmes.core.toolset_manager.load_builtin_toolsets") as mock_load: + mock_load.return_value = [simple_toolset] + + manager = ToolsetManager(global_fast_model=global_fast_model) + toolsets = manager._list_all_toolsets(check_prerequisites=False) + + result_toolset = toolsets[0] + + # Toolset should NOT receive any transformers (new injection behavior) + assert result_toolset.transformers is None + + # Tool should also remain without transformers + tool = result_toolset.tools[0] + assert tool.transformers is None + + +def test_no_global_configs_no_regression(): + """ + Test that existing behavior is unchanged when no global configs are provided. + """ + toolset_configs = [ + Transformer(name="llm_summarize", config={"input_threshold": 1000}) + ] + + toolset = YAMLToolset( + name="existing_toolset", + tags=[ToolsetTag.CORE], + description="Existing toolset", + transformers=toolset_configs, + ) + + with patch("holmes.core.toolset_manager.load_builtin_toolsets") as mock_load: + mock_load.return_value = [toolset] + + # No global configs (normal case) + manager = ToolsetManager() + toolsets = manager._list_all_toolsets(check_prerequisites=False) + + result_toolset = toolsets[0] + + # Should remain unchanged + assert result_toolset.transformers == toolset_configs + + +def test_toolset_with_only_tool_level_transformers_gets_fast_model(): + """ + Test that toolsets with ONLY tool-level transformers (no toolset-level transformers) + DO receive global fast-model settings with the new simplified injection approach. + + This test verifies the fix for the issue where kubernetes_jq_query didn't get fast_model. + """ + # Global fast_model from CLI --fast-model + global_fast_model = "gpt-4o-mini" + + # Create a tool with transformers (like kubernetes_jq_query) + jq_query_tool = YAMLTool( + name="kubernetes_jq_query", + description="Query Kubernetes Resources with jq", + command="kubectl get {{ kind }} --all-namespaces -o json | jq -r {{ jq_expr }}", + transformers=[ + Transformer( + name="llm_summarize", + config={ + "input_threshold": 1000, + "prompt": "Summarize jq query output focusing on patterns...", + }, + ) + ], + ) + + # Create toolset WITHOUT toolset-level transformers (like many real toolsets) + toolset_without_toolset_transformers = YAMLToolset( + name="kubernetes/core", + tags=[ToolsetTag.CORE], + description="Kubernetes toolset with only tool-level transformers", + tools=[jq_query_tool], + # Note: NO transformers defined at toolset level + ) + + with patch("holmes.core.toolset_manager.load_builtin_toolsets") as mock_load: + mock_load.return_value = [toolset_without_toolset_transformers] + + manager = ToolsetManager(global_fast_model=global_fast_model) + toolsets = manager._list_all_toolsets(check_prerequisites=False) + + result_toolset = toolsets[0] + + # The tool SHOULD now receive the global fast_model via injection + jq_tool = next( + t for t in result_toolset.tools if t.name == "kubernetes_jq_query" + ) + config_dict = {t.name: t.config for t in jq_tool.transformers} + + # This assertion should now PASS, proving the issue is fixed + assert "global_fast_model" in config_dict["llm_summarize"], ( + "Tool should have global_fast_model because new injection mechanism " + "injects it into all tools regardless of toolset-level transformers" + ) + assert config_dict["llm_summarize"]["global_fast_model"] == "gpt-4o-mini" + + # Tool should still have its original config + assert config_dict["llm_summarize"]["input_threshold"] == 1000 + assert "Summarize jq query output" in config_dict["llm_summarize"]["prompt"] + + +def test_toolset_with_toolset_level_transformers_works(): + """ + Contrast test: Verify that toolsets WITH toolset-level transformers + DO receive global fast-model injection correctly. + """ + # Global config from CLI --fast-model + global_fast_model = "gpt-4o-mini" + + # Create a tool with transformers + kubectl_describe = YAMLTool( + name="kubectl_describe", + description="Run kubectl describe", + command="kubectl describe {{ kind }} {{ name }}", + transformers=[ + Transformer( + name="llm_summarize", + config={ + "input_threshold": 1000, + "prompt": "Summarize kubectl describe output...", + }, + ) + ], + ) + + # Create toolset WITH toolset-level transformers + toolset_with_toolset_transformers = YAMLToolset( + name="kubernetes/core", + tags=[ToolsetTag.CORE], + description="Kubernetes toolset with toolset-level transformers", + tools=[kubectl_describe], + # KEY DIFFERENCE: Has toolset-level transformers + transformers=[ + Transformer( + name="llm_summarize", + config={"input_threshold": 800}, # Different from tool-level + ) + ], + ) + + with patch("holmes.core.toolset_manager.load_builtin_toolsets") as mock_load: + mock_load.return_value = [toolset_with_toolset_transformers] + + manager = ToolsetManager(global_fast_model=global_fast_model) + toolsets = manager._list_all_toolsets(check_prerequisites=False) + + result_toolset = toolsets[0] + + # Toolset SHOULD receive global_fast_model injection + assert result_toolset.transformers is not None + toolset_config = {t.name: t.config for t in result_toolset.transformers} + assert toolset_config["llm_summarize"]["global_fast_model"] == "gpt-4o-mini" + + # Tool SHOULD also receive global_fast_model injection + describe_tool = next( + t for t in result_toolset.tools if t.name == "kubectl_describe" + ) + tool_config = {t.name: t.config for t in describe_tool.transformers} + + # Should have global_fast_model injected + assert tool_config["llm_summarize"]["global_fast_model"] == "gpt-4o-mini" + # Should have input_threshold from tool (original) + assert tool_config["llm_summarize"]["input_threshold"] == 1000 + # Should have prompt from tool + assert ( + "Summarize kubectl describe output" + in tool_config["llm_summarize"]["prompt"] + ) diff --git a/tests/integration/test_kubernetes_transformer_execution.py b/tests/integration/test_kubernetes_transformer_execution.py new file mode 100644 index 0000000000..5844c12400 --- /dev/null +++ b/tests/integration/test_kubernetes_transformer_execution.py @@ -0,0 +1,539 @@ +""" +Integration tests for Phase 3.1: Kubernetes tools with transformer execution. +""" + +import tempfile +import os +from unittest.mock import patch + +from holmes.plugins.toolsets import load_toolsets_from_file +from holmes.core.tools import ToolResultStatus +from holmes.core.transformers import registry +from holmes.core.transformers.base import BaseTransformer + + +class MockSummarizeTransformer(BaseTransformer): + """Mock LLM summarize transformer for testing.""" + + input_threshold: int = 1000 # default value + prompt: str = "Default summarization prompt" + + def transform(self, input_text: str) -> str: + # Simulate summarization by truncating and adding prefix + if len(input_text) > 100: + return f"SUMMARIZED: {input_text[:50]}... [Original length: {len(input_text)} chars]" + return f"SUMMARIZED: {input_text}" + + def should_apply(self, input_text: str) -> bool: + return len(input_text) >= self.input_threshold + + @property + def name(self) -> str: + return "llm_summarize" # Changed to match kubernetes.yaml transformer name + + +class TestKubernetesTransformerExecution: + """Test full execution of Kubernetes tools with transformers.""" + + def setup_method(self): + """Set up test fixtures.""" + # Clean up any existing registrations first + for transformer_name in ["llm_summarize", "MockSummarizeTransformer"]: + if registry.is_registered(transformer_name): + registry.unregister(transformer_name) + + # Register mock transformer with a different name to avoid conflicts + registry.register(MockSummarizeTransformer) + + def teardown_method(self): + """Clean up test fixtures.""" + # Unregister mock transformer + for transformer_name in ["llm_summarize", "MockSummarizeTransformer"]: + if registry.is_registered(transformer_name): + registry.unregister(transformer_name) + + def test_kubectl_describe_with_large_output(self): + """Test kubectl_describe applies transformer for large output.""" + # Load the actual kubernetes.yaml file + current_dir = os.path.dirname(os.path.abspath(__file__)) + kubernetes_yaml_path = os.path.join( + current_dir, "..", "..", "holmes", "plugins", "toolsets", "kubernetes.yaml" + ) + + toolsets = load_toolsets_from_file(kubernetes_yaml_path) + kubernetes_core = next(ts for ts in toolsets if ts.name == "kubernetes/core") + kubectl_describe = next( + tool for tool in kubernetes_core.tools if tool.name == "kubectl_describe" + ) + + # Create large kubectl describe output that should trigger transformation + large_output = ( + """ +Name: test-pod-12345 +Namespace: default +Priority: 0 +Node: node-1/10.0.1.5 +Start Time: Mon, 01 Jan 2024 10:00:00 +0000 +Labels: app=test + version=1.0.0 +Annotations: deployment.kubernetes.io/revision: 1 +Status: Running +IP: 10.244.0.15 +IPs: + IP: 10.244.0.15 +Containers: + test-container: + Container ID: containerd://abc123def456 + Image: nginx:1.21 + Image ID: docker-pullable://nginx@sha256:abc123 + Port: 80/TCP + Host Port: 0/TCP + State: Running + Started: Mon, 01 Jan 2024 10:01:00 +0000 + Ready: True + Restart Count: 0 + Environment: + Mounts: + /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-xyz (ro) +Conditions: + Type Status + Initialized True + Ready True + ContainersReady True + PodScheduled True +Volumes: + kube-api-access-xyz: + Type: Projected (a volume that contains injected data from multiple sources) + TokenExpirationSeconds: 3607 + ConfigMapName: kube-root-ca.crt +Events: + Type Reason Age From Message + ---- ------ ---- ---- ------- + Normal Scheduled 5m default-scheduler Successfully assigned default/test-pod-12345 to node-1 + Normal Pulling 5m kubelet Pulling image "nginx:1.21" + Normal Pulled 4m kubelet Successfully pulled image "nginx:1.21" + Normal Created 4m kubelet Created container test-container + Normal Started 4m kubelet Started container test-container +""" + * 3 + ) # Repeat to make it large enough to trigger transformation + + # Mock the subprocess execution + with patch.object( + kubectl_describe, "_YAMLTool__execute_subprocess" + ) as mock_subprocess: + mock_subprocess.return_value = (large_output, 0) + + # Execute the tool + result = kubectl_describe.invoke( + {"kind": "pod", "name": "test-pod-12345", "namespace": "default"} + ) + + # Should have applied transformation + assert result.status == ToolResultStatus.SUCCESS + assert result.data is not None + assert "SUMMARIZED:" in result.data + assert f"Original length: {len(large_output)}" in result.data + assert len(result.data) < len( + large_output + ) # Should be shorter due to summarization + + def test_kubectl_describe_with_small_output(self): + """Test kubectl_describe skips transformer for small output.""" + # Load the actual kubernetes.yaml file + current_dir = os.path.dirname(os.path.abspath(__file__)) + kubernetes_yaml_path = os.path.join( + current_dir, "..", "..", "holmes", "plugins", "toolsets", "kubernetes.yaml" + ) + + toolsets = load_toolsets_from_file(kubernetes_yaml_path) + kubernetes_core = next(ts for ts in toolsets if ts.name == "kubernetes/core") + kubectl_describe = next( + tool for tool in kubernetes_core.tools if tool.name == "kubectl_describe" + ) + + # Create small output that should NOT trigger transformation + small_output = "Name: test\nStatus: Running" + + # Mock the subprocess execution + with patch.object( + kubectl_describe, "_YAMLTool__execute_subprocess" + ) as mock_subprocess: + mock_subprocess.return_value = (small_output, 0) + + # Execute the tool + result = kubectl_describe.invoke( + {"kind": "pod", "name": "test-pod", "namespace": "default"} + ) + + # Should NOT have applied transformation + assert result.status == ToolResultStatus.SUCCESS + assert result.data == small_output + assert "SUMMARIZED:" not in result.data + + def test_kubectl_logs_with_large_output(self): + """Test kubectl_logs applies transformer for large log output.""" + # Load the actual kubernetes_logs.yaml file + current_dir = os.path.dirname(os.path.abspath(__file__)) + kubernetes_logs_yaml_path = os.path.join( + current_dir, + "..", + "..", + "holmes", + "plugins", + "toolsets", + "kubernetes_logs.yaml", + ) + + toolsets = load_toolsets_from_file(kubernetes_logs_yaml_path) + kubernetes_logs = next(ts for ts in toolsets if ts.name == "kubernetes/logs") + kubectl_logs = next( + tool for tool in kubernetes_logs.tools if tool.name == "kubectl_logs" + ) + + # Create large log output that should trigger transformation + large_log_output = ( + """ +2024-01-01T10:00:01.123Z INFO Starting application server on port 8080 +2024-01-01T10:00:01.234Z INFO Loading configuration from /app/config.yaml +2024-01-01T10:00:01.345Z INFO Database connection established to postgresql://db:5432/app +2024-01-01T10:00:01.456Z INFO Redis cache connection established to redis://cache:6379 +2024-01-01T10:00:01.567Z INFO Metrics endpoint available at /metrics +2024-01-01T10:00:01.678Z INFO Health check endpoint available at /health +2024-01-01T10:00:01.789Z INFO Application started successfully +2024-01-01T10:00:02.123Z INFO Processing request GET /api/users +2024-01-01T10:00:02.234Z INFO Processing request POST /api/orders +2024-01-01T10:00:02.345Z WARN High memory usage detected: 85% +2024-01-01T10:00:02.456Z INFO Processing request GET /api/products +2024-01-01T10:00:02.567Z ERROR Failed to connect to external API: connection timeout +2024-01-01T10:00:02.678Z WARN Retrying external API connection (attempt 1/3) +2024-01-01T10:00:02.789Z INFO External API connection restored +""" + * 20 + ) # Repeat to make it large enough to trigger transformation + + # Mock the subprocess execution + with patch.object( + kubectl_logs, "_YAMLTool__execute_subprocess" + ) as mock_subprocess: + mock_subprocess.return_value = (large_log_output, 0) + + # Execute the tool + result = kubectl_logs.invoke( + {"pod_name": "test-app-12345", "namespace": "default"} + ) + + # Should have applied transformation + assert result.status == ToolResultStatus.SUCCESS + assert result.data is not None + assert "SUMMARIZED:" in result.data + assert f"Original length: {len(large_log_output)}" in result.data + assert len(result.data) < len( + large_log_output + ) # Should be shorter due to summarization + + def test_kubectl_get_cluster_with_transformer(self): + """Test kubectl_get_by_kind_in_cluster applies transformer for large output.""" + # Load the actual kubernetes.yaml file + current_dir = os.path.dirname(os.path.abspath(__file__)) + kubernetes_yaml_path = os.path.join( + current_dir, "..", "..", "holmes", "plugins", "toolsets", "kubernetes.yaml" + ) + + toolsets = load_toolsets_from_file(kubernetes_yaml_path) + kubernetes_core = next(ts for ts in toolsets if ts.name == "kubernetes/core") + kubectl_get_cluster = next( + tool + for tool in kubernetes_core.tools + if tool.name == "kubectl_get_by_kind_in_cluster" + ) + + # Create large kubectl get output + large_get_output = ( + """ +NAMESPACE NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES LABELS +kube-system coredns-558bd4d5db-abc123 1/1 Running 0 10d 10.244.0.2 node-1 k8s-app=kube-dns,pod-template-hash=558bd4d5db +kube-system coredns-558bd4d5db-def456 1/1 Running 0 10d 10.244.0.3 node-1 k8s-app=kube-dns,pod-template-hash=558bd4d5db +kube-system etcd-node-1 1/1 Running 0 10d 10.0.1.5 node-1 component=etcd,tier=control-plane +kube-system kube-apiserver-node-1 1/1 Running 0 10d 10.0.1.5 node-1 component=kube-apiserver,tier=control-plane +default nginx-deployment-abc123 1/1 Running 0 5d 10.244.1.5 node-2 app=nginx,pod-template-hash=abc123 +default nginx-deployment-def456 1/1 Running 0 5d 10.244.1.6 node-2 app=nginx,pod-template-hash=def456 +default redis-master-789 1/1 Running 0 3d 10.244.1.7 node-2 app=redis,role=master +monitoring prometheus-server-xyz 1/1 Running 0 2d 10.244.1.8 node-2 app=prometheus,component=server +""" + * 5 + ) # Repeat to make it large enough + + # Mock the subprocess execution + with patch.object( + kubectl_get_cluster, "_YAMLTool__execute_subprocess" + ) as mock_subprocess: + mock_subprocess.return_value = (large_get_output, 0) + + # Execute the tool + result = kubectl_get_cluster.invoke({"kind": "pods"}) + + # Should have applied transformation + assert result.status == ToolResultStatus.SUCCESS + assert result.data is not None + assert "SUMMARIZED:" in result.data + assert len(result.data) < len(large_get_output) + + def test_transformer_failure_handling(self): + """Test that tool execution continues gracefully when transformer fails.""" + + # Create a failing transformer + class FailingTransformer(BaseTransformer): + def transform(self, input_text: str) -> str: + raise Exception("Transformer failed") + + def should_apply(self, input_text: str) -> bool: + return True + + @property + def name(self) -> str: + return "failing_summarize" + + # Register failing transformer temporarily + registry.register(FailingTransformer) + + try: + # Create a YAML toolset with the failing transformer + yaml_content = """ +toolsets: + test/failing: + description: "Test toolset with failing transformer" + tools: + - name: "kubectl_failing" + description: "Tool with failing transformer" + command: "echo 'test output that should not be transformed'" + transformers: + - name: failing_summarize + config: {} +""" + + # Write to temporary file + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + # Load toolsets and get the tool + toolsets = load_toolsets_from_file(tmp_file_path) + toolset = toolsets[0] + tool = toolset.tools[0] + + # Mock subprocess execution + test_output = "This is test output that should remain unchanged due to transformer failure" + with patch.object( + tool, "_YAMLTool__execute_subprocess" + ) as mock_subprocess: + mock_subprocess.return_value = (test_output, 0) + + # Execute with logging to catch transformer failure + with patch("holmes.core.tools.logger") as mock_logging: + result = tool.invoke({}) + + # Should return original output when transformer fails + assert result.status == ToolResultStatus.SUCCESS + assert result.data == test_output + + # Should log error about transformer failure (generic Exception -> error log) + mock_logging.error.assert_called() + error_call = mock_logging.error.call_args[0][0] + assert "failing_summarize" in error_call + assert "failed" in error_call + + finally: + os.unlink(tmp_file_path) + + finally: + if registry.is_registered("failing_summarize"): + registry.unregister("failing_summarize") + + def test_transformer_error_status_handling(self): + """Test that transformers are not applied when tool returns error status.""" + # Load the actual kubernetes.yaml file + current_dir = os.path.dirname(os.path.abspath(__file__)) + kubernetes_yaml_path = os.path.join( + current_dir, "..", "..", "holmes", "plugins", "toolsets", "kubernetes.yaml" + ) + + toolsets = load_toolsets_from_file(kubernetes_yaml_path) + kubernetes_core = next(ts for ts in toolsets if ts.name == "kubernetes/core") + kubectl_describe = next( + tool for tool in kubernetes_core.tools if tool.name == "kubectl_describe" + ) + + # Mock subprocess to return error + error_output = "Error: pod 'nonexistent' not found" + with patch.object( + kubectl_describe, "_YAMLTool__execute_subprocess" + ) as mock_subprocess: + # For error case, mock the subprocess to return error code + mock_subprocess.return_value = (error_output, 1) + + # Execute the tool + result = kubectl_describe.invoke( + {"kind": "pod", "name": "nonexistent", "namespace": "default"} + ) + + # Should NOT have applied transformation due to error status + assert result.status == ToolResultStatus.ERROR + assert result.data == error_output + assert "SUMMARIZED:" not in result.data + + def test_multiple_transformers_chaining(self): + """Test that multiple transformers are applied in sequence.""" + + # Create a second transformer + class SecondTransformer(BaseTransformer): + def transform(self, input_text: str) -> str: + return f"SECOND_TRANSFORM: {input_text}" + + def should_apply(self, input_text: str) -> bool: + return True + + @property + def name(self) -> str: + return "second_transformer" + + registry.register(SecondTransformer) + + try: + # Create YAML with multiple transformers + yaml_content = """ +toolsets: + test/multi: + description: "Test toolset with multiple transformers" + tools: + - name: "kubectl_multi" + description: "Tool with multiple transformers" + command: "echo 'test'" + transformers: + - name: llm_summarize + config: + input_threshold: 10 # Low threshold to ensure it triggers + - name: second_transformer + config: {} +""" + + # Write to temporary file + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + # Load toolsets and get the tool + toolsets = load_toolsets_from_file(tmp_file_path) + toolset = toolsets[0] + tool = toolset.tools[0] + + # Mock subprocess execution with output that will trigger both transformers + test_output = "This is a longer test output that should trigger both transformers in sequence" + with patch.object( + tool, "_YAMLTool__execute_subprocess" + ) as mock_subprocess: + mock_subprocess.return_value = (test_output, 0) + + # Execute the tool + result = tool.invoke({}) + + # Should have applied both transformers in sequence + assert result.status == ToolResultStatus.SUCCESS + assert result.data is not None + assert "SECOND_TRANSFORM:" in result.data + assert "SUMMARIZED:" in result.data + + finally: + os.unlink(tmp_file_path) + + finally: + if registry.is_registered("second_transformer"): + registry.unregister("second_transformer") + + +class TestTransformerPerformanceMetrics: + """Test performance monitoring and metrics for transformers.""" + + def setup_method(self): + """Set up test fixtures.""" + # Clean up any existing registrations first + for transformer_name in ["llm_summarize", "MockSummarizeTransformer"]: + if registry.is_registered(transformer_name): + registry.unregister(transformer_name) + + # Register mock transformer with a different name to avoid conflicts + registry.register(MockSummarizeTransformer) + + def teardown_method(self): + """Clean up test fixtures.""" + # Unregister mock transformer + for transformer_name in ["llm_summarize", "MockSummarizeTransformer"]: + if registry.is_registered(transformer_name): + registry.unregister(transformer_name) + + def test_transformer_performance_logging(self): + """Test that transformer execution metrics are logged.""" + # Create a YAML toolset for testing + yaml_content = """ +toolsets: + test/perf: + description: "Test toolset for performance monitoring" + tools: + - name: "kubectl_perf" + description: "Tool for performance testing" + command: "echo 'test'" + transformers: + - name: llm_summarize + config: + input_threshold: 10 +""" + + # Write to temporary file + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + # Load toolsets and get the tool + toolsets = load_toolsets_from_file(tmp_file_path) + toolset = toolsets[0] + tool = toolset.tools[0] + + # Mock subprocess execution + test_output = "This is a test output that should trigger the transformer and performance logging" + with patch.object(tool, "_YAMLTool__execute_subprocess") as mock_subprocess: + mock_subprocess.return_value = (test_output, 0) + + # Execute with logging to capture performance metrics + with patch("holmes.core.tools.logger") as mock_logging: + tool.invoke({}) + + # Should have logged transformer application with metrics + info_calls = [ + call[0][0] for call in mock_logging.info.call_args_list + ] + transformer_log = next( + (call for call in info_calls if "Applied transformer" in call), + None, + ) + + assert transformer_log is not None + assert "llm_summarize" in transformer_log + assert "kubectl_perf" in transformer_log + assert ( + "size:" in transformer_log + ) # Changed from "output size:" to "size:" + assert ( + "chars," in transformer_log + ) # Changed from "characters)" to "chars," (from tools.py line 305-306) + + finally: + os.unlink(tmp_file_path) diff --git a/tests/integration/test_tool_execution_pipeline.py b/tests/integration/test_tool_execution_pipeline.py new file mode 100644 index 0000000000..c3d0c77a1e --- /dev/null +++ b/tests/integration/test_tool_execution_pipeline.py @@ -0,0 +1,341 @@ +""" +Integration tests for Phase 2.2: Tool Execution Pipeline with transformers. + +These tests verify the complete tool execution flow with transformers +in a more realistic environment. +""" + +from unittest.mock import patch +from typing import Dict +import time + +from holmes.core.tools import ( + Tool, + YAMLTool, + StructuredToolResult, + ToolResultStatus, +) +from holmes.core.transformers import ( + registry, + BaseTransformer, + TransformerError, + Transformer, +) + + +class MockLLMSummarizeTransformer(BaseTransformer): + """Mock LLM summarize transformer for integration testing.""" + + input_threshold: int = 100 + + def transform(self, input_text: str) -> str: + # Simulate LLM summarization by shortening the text + words = input_text.split() + if len(words) > 10: + return f"SUMMARIZED: {' '.join(words[:5])}... (truncated {len(words) - 5} words)" + return input_text + + def should_apply(self, input_text: str) -> bool: + # Apply threshold logic - only transform if input is long enough + return len(input_text) >= self.input_threshold + + @property + def name(self) -> str: + return "llm_summarize" + + +class TestToolExecutionPipelineIntegration: + """Integration tests for complete tool execution pipeline.""" + + def setup_method(self): + """Set up test fixtures.""" + # Save original state for restoration + self._original_llm_summarize = None + if registry.is_registered("llm_summarize"): + # Store the original transformer class for restoration + # Use create_transformer to verify it exists and get the class reference + try: + test_instance = registry.create_transformer("llm_summarize", {}) + self._original_llm_summarize = test_instance.__class__ + except Exception: + self._original_llm_summarize = None + registry.unregister("llm_summarize") + + # Register our mock transformer + registry.register(MockLLMSummarizeTransformer) + + def teardown_method(self): + """Clean up test fixtures.""" + # Clean up our mock transformer + if registry.is_registered("llm_summarize"): + registry.unregister("llm_summarize") + + # Restore original transformer if it existed + if self._original_llm_summarize is not None: + registry.register(self._original_llm_summarize) + + def test_yaml_tool_with_transformer_integration(self): + """Test complete YAML tool execution with transformer.""" + tool = YAMLTool( + name="test_yaml_tool", + description="Test YAML tool with transformer", + command="echo 'This is a very long output from a kubectl command that would normally overwhelm the LLM context window with unnecessary details and verbose information that should be summarized'", + transformers=[ + Transformer(name="llm_summarize", config={"input_threshold": 50}) + ], + ) + + result = tool.invoke({}) + + # Should have executed successfully + assert result.status == ToolResultStatus.SUCCESS + + # Should have applied transformation (output should be summarized) + assert result.data is not None + assert "SUMMARIZED:" in result.data + assert "truncated" in result.data + + # Original long text should not be in the result + assert len(result.data) < 200 # Should be much shorter than original + + def test_python_tool_with_multiple_transformers_integration(self): + """Test Python tool with multiple transformers in sequence.""" + + class LogReaderTool(Tool): + """Simulates a tool that reads large log files.""" + + def _invoke(self, params: Dict) -> StructuredToolResult: + # Simulate reading a large log file + log_entries = [ + "2024-01-01 10:00:00 INFO Starting application", + "2024-01-01 10:00:01 INFO Loading configuration", + "2024-01-01 10:00:02 DEBUG Database connection established", + "2024-01-01 10:00:03 INFO Server listening on port 8080", + "2024-01-01 10:01:00 ERROR Failed to process request: timeout", + "2024-01-01 10:01:01 WARN Retrying request", + "2024-01-01 10:01:02 INFO Request processed successfully", + ] * 20 # Repeat to make it large + + large_log = "\n".join(log_entries) + + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data=large_log, + invocation="tail -n 1000 /var/log/app.log", + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return "tail -n 1000 /var/log/app.log" + + tool = LogReaderTool( + name="log_reader", + description="Read application logs", + transformers=[ + Transformer(name="llm_summarize", config={"input_threshold": 100}) + ], + ) + + result = tool.invoke({}) + + # Should have executed successfully + assert result.status == ToolResultStatus.SUCCESS + + # Should have applied transformation + assert result.data is not None + assert "SUMMARIZED:" in result.data + + # Should be much shorter than original + # Calculate size based on the actual test data: 7 different log entries * 20 repetitions + log_entries = [ + "2024-01-01 10:00:00 INFO Starting application", + "2024-01-01 10:00:01 INFO Loading configuration", + "2024-01-01 10:00:02 DEBUG Database connection established", + "2024-01-01 10:00:03 INFO Server listening on port 8080", + "2024-01-01 10:01:00 ERROR Failed to process request: timeout", + "2024-01-01 10:01:01 WARN Retrying request", + "2024-01-01 10:01:02 INFO Request processed successfully", + ] * 20 + original_size = len("\n".join(log_entries)) + assert len(result.data) < original_size / 2 + + def test_transformer_failure_recovery_integration(self): + """Test that tool execution continues when transformer fails.""" + + class FailingTransformer(BaseTransformer): + def transform(self, input_text: str) -> str: + raise TransformerError("Simulated transformer failure") + + def should_apply(self, input_text: str) -> bool: + return True + + @property + def name(self) -> str: + return "failing_transformer" + + registry.register(FailingTransformer) + + try: + tool = YAMLTool( + name="test_tool", + description="Test tool with failing transformer", + command="echo 'This is test output that should remain unchanged due to transformer failure'", + transformers=[ + Transformer(name="failing_transformer", config={}), + Transformer( + name="llm_summarize", config={"input_threshold": 10} + ), # This should still work + ], + ) + + with patch("holmes.core.tools.logger") as mock_logging: + result = tool.invoke({}) + + # Tool execution should still succeed + assert result.status == ToolResultStatus.SUCCESS + + # Should contain original output since first transformer failed + # but second transformer should still be applied + assert "This is test output" in result.data + + # Should log warning about transformer failure + warning_calls = [call for call in mock_logging.warning.call_args_list] + assert any("failing_transformer" in str(call) for call in warning_calls) + + finally: + if registry.is_registered("failing_transformer"): + registry.unregister("failing_transformer") + + def test_conditional_transformer_application_integration(self): + """Test that transformers are conditionally applied based on content.""" + tool = YAMLTool( + name="conditional_tool", + description="Tool with conditional transformer", + command="echo 'Short'", # Short output + transformers=[ + Transformer( + name="llm_summarize", config={"input_threshold": 100} + ) # Higher than output length + ], + ) + + result = tool.invoke({}) + + # Should execute successfully + assert result.status == ToolResultStatus.SUCCESS + + # Should NOT have applied transformation (output too short) + assert "SUMMARIZED:" not in result.data + assert result.data.strip() == "Short" + + def test_transformer_performance_monitoring_integration(self): + """Test that transformer performance is properly monitored and logged.""" + + class SlowTransformer(BaseTransformer): + def transform(self, input_text: str) -> str: + time.sleep(0.1) # Simulate slow transformation + return f"SLOW_TRANSFORMED: {input_text}" + + def should_apply(self, input_text: str) -> bool: + return True + + @property + def name(self) -> str: + return "slow_transformer" + + registry.register(SlowTransformer) + + try: + tool = YAMLTool( + name="performance_test_tool", + description="Tool for testing transformer performance monitoring", + command="echo 'Test output for performance monitoring of transformer execution'", + transformers=[Transformer(name="slow_transformer", config={})], + ) + + with patch("holmes.core.tools.logger") as mock_logging: + result = tool.invoke({}) + + # Should execute successfully + assert result.status == ToolResultStatus.SUCCESS + + # Should have applied transformation + assert "SLOW_TRANSFORMED:" in result.data + + # Should log performance metrics + info_calls = [call[0][0] for call in mock_logging.info.call_args_list] + performance_log = next( + (call for call in info_calls if "Applied transformer" in call), None + ) + + assert performance_log is not None + assert "slow_transformer" in performance_log + assert "performance_test_tool" in performance_log + assert ( + " in " in performance_log and "s " in performance_log + ) # Should show elapsed time pattern like "in X.XXs" + assert "size:" in performance_log # Should show size information + + finally: + if registry.is_registered("slow_transformer"): + registry.unregister("slow_transformer") + + def test_real_world_kubectl_scenario_integration(self): + """Test a realistic kubectl-like scenario with large output.""" + + # Simulate kubectl get pods output + kubectl_output = ( + """NAME READY STATUS RESTARTS AGE +app-deployment-5d7c9b9b9-abc12 1/1 Running 0 2d +app-deployment-5d7c9b9b9-def34 1/1 Running 0 2d +app-deployment-5d7c9b9b9-ghi56 1/1 Running 0 2d +database-pod-7f8d5c6b4-jkl78 1/1 Running 1 5d +nginx-ingress-controller-mno90 1/1 Running 0 10d +prometheus-server-pqr12 1/1 Running 0 7d +grafana-dashboard-stu34 1/1 Running 0 7d +elasticsearch-cluster-vwx56 1/1 Running 0 3d +kibana-dashboard-yz789 1/1 Running 0 3d +redis-cache-abc123 1/1 Running 0 1d""" + * 5 + ) # Repeat to make it larger + + tool = YAMLTool( + name="kubectl_get_pods", + description="Get all pods in namespace", + command=f"echo '{kubectl_output}'", + transformers=[ + Transformer(name="llm_summarize", config={"input_threshold": 200}) + ], + ) + + result = tool.invoke({}) + + # Should execute successfully + assert result.status == ToolResultStatus.SUCCESS + + # Should have applied transformation (output should be summarized) + assert "SUMMARIZED:" in result.data + + # Should preserve important information structure + assert len(result.data) < len(kubectl_output) # Much shorter than original + + def test_error_handling_preserves_debugging_info_integration(self): + """Test that original output is preserved for debugging when transformers fail.""" + tool = YAMLTool( + name="debug_tool", + description="Tool for testing debug preservation", + command="echo 'Important debugging information that should not be lost and contains many additional details about the system state and error conditions that occurred during processing'", + transformers=[ + Transformer(name="llm_summarize", config={"input_threshold": 10}) + ], + ) + + # Even if transformer modifies the output, the result structure should be preserved + result = tool.invoke({}) + + assert result.status == ToolResultStatus.SUCCESS + assert result.invocation is not None # Debug info preserved + assert "echo" in result.invocation # Original command preserved + + # Transformation applied but structure preserved + assert "SUMMARIZED:" in result.data + assert "Important debugging information" in result.data diff --git a/tests/plugins/toolsets/test_aks_transformers.py b/tests/plugins/toolsets/test_aks_transformers.py new file mode 100644 index 0000000000..212f216f64 --- /dev/null +++ b/tests/plugins/toolsets/test_aks_transformers.py @@ -0,0 +1,260 @@ +""" +Unit tests for AKS toolsets with transformer configurations. +""" + +import os +from holmes.plugins.toolsets import load_toolsets_from_file +from .transformer_test_utils import ensure_transformers_registered + + +class TestAKSTransformers: + """Test that AKS toolsets correctly parse transformer configurations.""" + + def test_load_aks_node_health_yaml_with_transformers(self): + """Test loading the aks-node-health.yaml file with transformers.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + # Find the actual aks-node-health.yaml file + current_dir = os.path.dirname(os.path.abspath(__file__)) + aks_node_health_yaml_path = os.path.join( + current_dir, + "..", + "..", + "..", + "holmes", + "plugins", + "toolsets", + "aks-node-health.yaml", + ) + + # Load toolsets from the file + toolsets = load_toolsets_from_file(aks_node_health_yaml_path) + + # Find the aks/node-health toolset + aks_node_health = None + for toolset in toolsets: + if toolset.name == "aks/node-health": + aks_node_health = toolset + break + + assert aks_node_health is not None, "aks/node-health toolset not found" + + # Test check_node_status has transformer config + check_node_status = None + for tool in aks_node_health.tools: + if tool.name == "check_node_status": + check_node_status = tool + break + + assert check_node_status is not None, "check_node_status tool not found" + assert check_node_status.transformers is not None + assert len(check_node_status.transformers) == 1 + assert check_node_status.transformers[0].name == "llm_summarize" + assert check_node_status.transformers[0].config["input_threshold"] == 800 + + # Test describe_node has transformer config + describe_node = None + for tool in aks_node_health.tools: + if tool.name == "describe_node": + describe_node = tool + break + + assert describe_node is not None, "describe_node tool not found" + assert describe_node.transformers is not None + assert len(describe_node.transformers) == 1 + assert describe_node.transformers[0].name == "llm_summarize" + assert describe_node.transformers[0].config["input_threshold"] == 1200 + + def test_load_aks_core_yaml_with_transformers(self): + """Test loading the aks.yaml file with transformers.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + # Find the actual aks.yaml file + current_dir = os.path.dirname(os.path.abspath(__file__)) + aks_yaml_path = os.path.join( + current_dir, "..", "..", "..", "holmes", "plugins", "toolsets", "aks.yaml" + ) + + # Load toolsets from the file + toolsets = load_toolsets_from_file(aks_yaml_path) + + # Find the aks/core toolset + aks_core = None + for toolset in toolsets: + if toolset.name == "aks/core": + aks_core = toolset + break + + assert aks_core is not None, "aks/core toolset not found" + + # Test aks_get_cluster has transformer config + aks_get_cluster = None + for tool in aks_core.tools: + if tool.name == "aks_get_cluster": + aks_get_cluster = tool + break + + assert aks_get_cluster is not None, "aks_get_cluster tool not found" + assert aks_get_cluster.transformers is not None + assert len(aks_get_cluster.transformers) == 1 + assert aks_get_cluster.transformers[0].name == "llm_summarize" + assert aks_get_cluster.transformers[0].config["input_threshold"] == 1500 + + # Test aks_list_node_pools has transformer config + aks_list_node_pools = None + for tool in aks_core.tools: + if tool.name == "aks_list_node_pools": + aks_list_node_pools = tool + break + + assert aks_list_node_pools is not None, "aks_list_node_pools tool not found" + assert aks_list_node_pools.transformers is not None + assert len(aks_list_node_pools.transformers) == 1 + assert aks_list_node_pools.transformers[0].name == "llm_summarize" + assert aks_list_node_pools.transformers[0].config["input_threshold"] == 1200 + + def test_aks_transformer_prompts(self): + """Test that AKS tools have appropriate transformer prompts.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + # Test AKS node health prompts + current_dir = os.path.dirname(os.path.abspath(__file__)) + aks_node_health_yaml_path = os.path.join( + current_dir, + "..", + "..", + "..", + "holmes", + "plugins", + "toolsets", + "aks-node-health.yaml", + ) + + toolsets = load_toolsets_from_file(aks_node_health_yaml_path) + aks_node_health = next( + (ts for ts in toolsets if ts.name == "aks/node-health"), None + ) + assert aks_node_health is not None, "aks/node-health toolset not found" + + # Test check_node_status prompt + check_node_status = next( + ( + tool + for tool in aks_node_health.tools + if tool.name == "check_node_status" + ), + None, + ) + assert check_node_status is not None, "check_node_status tool not found" + assert check_node_status.transformers is not None + prompt = check_node_status.transformers[0].config["prompt"] + assert "NotReady or in error states" in prompt + assert "Node health patterns" in prompt + assert "exact node names" in prompt + + # Test describe_node prompt + describe_node = next( + (tool for tool in aks_node_health.tools if tool.name == "describe_node"), + None, + ) + assert describe_node is not None, "describe_node tool not found" + assert describe_node.transformers is not None + prompt = describe_node.transformers[0].config["prompt"] + assert "Node conditions and health status" in prompt + assert "Resource capacity vs allocatable" in prompt + assert "taints, labels" in prompt + + # Test AKS core prompts + aks_yaml_path = os.path.join( + current_dir, "..", "..", "..", "holmes", "plugins", "toolsets", "aks.yaml" + ) + + toolsets = load_toolsets_from_file(aks_yaml_path) + aks_core = next((ts for ts in toolsets if ts.name == "aks/core"), None) + assert aks_core is not None, "aks/core toolset not found" + + # Test aks_get_cluster prompt + aks_get_cluster = next( + (tool for tool in aks_core.tools if tool.name == "aks_get_cluster"), None + ) + assert aks_get_cluster is not None, "aks_get_cluster tool not found" + assert aks_get_cluster.transformers is not None + prompt = aks_get_cluster.transformers[0].config["prompt"] + assert "Cluster status, health state" in prompt + assert "Network configuration" in prompt + assert "Security settings" in prompt + + def test_aks_transformer_thresholds(self): + """Test that AKS tools have appropriate transformer thresholds.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + # Load both YAML files + current_dir = os.path.dirname(os.path.abspath(__file__)) + + # Test AKS node health thresholds + aks_node_health_yaml_path = os.path.join( + current_dir, + "..", + "..", + "..", + "holmes", + "plugins", + "toolsets", + "aks-node-health.yaml", + ) + toolsets = load_toolsets_from_file(aks_node_health_yaml_path) + aks_node_health = next( + (ts for ts in toolsets if ts.name == "aks/node-health"), None + ) + assert aks_node_health is not None, "aks/node-health toolset not found" + + # check_node_status should have lower threshold (simpler output) + check_node_status = next( + ( + tool + for tool in aks_node_health.tools + if tool.name == "check_node_status" + ), + None, + ) + assert check_node_status is not None, "check_node_status tool not found" + assert check_node_status.transformers is not None + assert check_node_status.transformers[0].config["input_threshold"] == 800 + + # describe_node should have higher threshold (detailed output) + describe_node = next( + (tool for tool in aks_node_health.tools if tool.name == "describe_node"), + None, + ) + assert describe_node is not None, "describe_node tool not found" + assert describe_node.transformers is not None + assert describe_node.transformers[0].config["input_threshold"] == 1200 + + # Test AKS core thresholds + aks_yaml_path = os.path.join( + current_dir, "..", "..", "..", "holmes", "plugins", "toolsets", "aks.yaml" + ) + toolsets = load_toolsets_from_file(aks_yaml_path) + aks_core = next((ts for ts in toolsets if ts.name == "aks/core"), None) + assert aks_core is not None, "aks/core toolset not found" + + # aks_get_cluster should have highest threshold (very detailed JSON) + aks_get_cluster = next( + (tool for tool in aks_core.tools if tool.name == "aks_get_cluster"), None + ) + assert aks_get_cluster is not None, "aks_get_cluster tool not found" + assert aks_get_cluster.transformers is not None + assert aks_get_cluster.transformers[0].config["input_threshold"] == 1500 + + # aks_list_clusters_by_rg should have medium threshold (list of clusters) + aks_list_clusters = next( + (tool for tool in aks_core.tools if tool.name == "aks_list_clusters_by_rg"), + None, + ) + assert aks_list_clusters is not None, "aks_list_clusters_by_rg tool not found" + assert aks_list_clusters.transformers is not None + assert aks_list_clusters.transformers[0].config["input_threshold"] == 1000 diff --git a/tests/plugins/toolsets/test_kubernetes_transformers.py b/tests/plugins/toolsets/test_kubernetes_transformers.py new file mode 100644 index 0000000000..a05ce0db04 --- /dev/null +++ b/tests/plugins/toolsets/test_kubernetes_transformers.py @@ -0,0 +1,573 @@ +""" +Unit tests for Phase 3.1: Kubernetes YAML tools with transformer configurations. +""" + +import tempfile +import os +from unittest.mock import patch + +from holmes.plugins.toolsets import load_toolsets_from_file +from .transformer_test_utils import ensure_transformers_registered + + +class TestKubernetesYAMLTransformers: + """Test that Kubernetes YAML tools correctly parse transformer configurations.""" + + def test_load_kubernetes_yaml_with_transformers(self): + """Test loading the actual kubernetes.yaml file with transformers.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + # Find the actual kubernetes.yaml file + current_dir = os.path.dirname(os.path.abspath(__file__)) + kubernetes_yaml_path = os.path.join( + current_dir, + "..", + "..", + "..", + "holmes", + "plugins", + "toolsets", + "kubernetes.yaml", + ) + + # Load toolsets from the file + toolsets = load_toolsets_from_file(kubernetes_yaml_path) + + # Find the kubernetes/core toolset + kubernetes_core = None + for toolset in toolsets: + if toolset.name == "kubernetes/core": + kubernetes_core = toolset + break + + assert kubernetes_core is not None, "kubernetes/core toolset not found" + + # Test kubectl_describe has transformer config + kubectl_describe = None + for tool in kubernetes_core.tools: + if tool.name == "kubectl_describe": + kubectl_describe = tool + break + + assert kubectl_describe is not None, "kubectl_describe tool not found" + assert kubectl_describe.transformers is not None + assert len(kubectl_describe.transformers) == 1 + assert kubectl_describe.transformers[0].name == "llm_summarize" + assert kubectl_describe.transformers[0].config["input_threshold"] == 1000 + + # Test kubectl_get_by_kind_in_namespace has transformer config + kubectl_get_namespace = None + for tool in kubernetes_core.tools: + if tool.name == "kubectl_get_by_kind_in_namespace": + kubectl_get_namespace = tool + break + + assert ( + kubectl_get_namespace is not None + ), "kubectl_get_by_kind_in_namespace tool not found" + assert kubectl_get_namespace.transformers is not None + assert len(kubectl_get_namespace.transformers) == 1 + assert kubectl_get_namespace.transformers[0].name == "llm_summarize" + + # Test kubectl_get_by_kind_in_cluster has transformer config + kubectl_get_cluster = None + for tool in kubernetes_core.tools: + if tool.name == "kubectl_get_by_kind_in_cluster": + kubectl_get_cluster = tool + break + + assert ( + kubectl_get_cluster is not None + ), "kubectl_get_by_kind_in_cluster tool not found" + assert kubectl_get_cluster.transformers is not None + assert len(kubectl_get_cluster.transformers) == 1 + assert kubectl_get_cluster.transformers[0].name == "llm_summarize" + + def test_load_kubernetes_logs_yaml_with_transformers(self): + """Test loading the kubernetes_logs.yaml file with transformers.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + # Find the actual kubernetes_logs.yaml file + current_dir = os.path.dirname(os.path.abspath(__file__)) + kubernetes_logs_yaml_path = os.path.join( + current_dir, + "..", + "..", + "..", + "holmes", + "plugins", + "toolsets", + "kubernetes_logs.yaml", + ) + + # Load toolsets from the file + toolsets = load_toolsets_from_file(kubernetes_logs_yaml_path) + + # Find the kubernetes/logs toolset + kubernetes_logs = None + for toolset in toolsets: + if toolset.name == "kubernetes/logs": + kubernetes_logs = toolset + break + + assert kubernetes_logs is not None, "kubernetes/logs toolset not found" + + # Test kubectl_logs has transformer config + kubectl_logs = None + for tool in kubernetes_logs.tools: + if tool.name == "kubectl_logs": + kubectl_logs = tool + break + + assert kubectl_logs is not None, "kubectl_logs tool not found" + assert kubectl_logs.transformers is not None + assert len(kubectl_logs.transformers) == 1 + assert kubectl_logs.transformers[0].name == "llm_summarize" + assert kubectl_logs.transformers[0].config["input_threshold"] == 1000 + + # Test kubectl_logs_all_containers has transformer config + kubectl_logs_all = None + for tool in kubernetes_logs.tools: + if tool.name == "kubectl_logs_all_containers": + kubectl_logs_all = tool + break + + assert ( + kubectl_logs_all is not None + ), "kubectl_logs_all_containers tool not found" + assert kubectl_logs_all.transformers is not None + assert len(kubectl_logs_all.transformers) == 1 + assert kubectl_logs_all.transformers[0].name == "llm_summarize" + assert kubectl_logs_all.transformers[0].config["input_threshold"] == 1000 + + def test_yaml_transformer_parsing(self): + """Test YAML parsing of transformer configurations with various options.""" + yaml_content = """ +toolsets: + test/kubernetes: + description: "Test Kubernetes toolset with transformers" + tools: + - name: "kubectl_test_basic" + description: "Basic test tool" + command: "kubectl get pods" + transformers: + - name: llm_summarize + config: + input_threshold: 500 + + - name: "kubectl_test_custom_prompt" + description: "Test tool with custom prompt" + command: "kubectl describe pod test" + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: | + Custom summarization prompt for testing: + - Focus on errors + - Group similar items + + - name: "kubectl_test_no_transform" + description: "Test tool without transformers" + command: "kubectl get nodes" +""" + + # Write to temporary file + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + # Load toolsets from the temporary file + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + assert toolset.name == "test/kubernetes" + assert len(toolset.tools) == 3 + + # Test basic transformer config + basic_tool = toolset.tools[0] + assert basic_tool.name == "kubectl_test_basic" + assert basic_tool.transformers is not None + assert len(basic_tool.transformers) == 1 + config = basic_tool.transformers[0].config + assert config["input_threshold"] == 500 + assert "prompt" not in config # Should use default prompt + + # Test custom prompt transformer config + custom_tool = toolset.tools[1] + assert custom_tool.name == "kubectl_test_custom_prompt" + assert custom_tool.transformers is not None + config = custom_tool.transformers[0].config + assert config["input_threshold"] == 1000 + assert "Custom summarization prompt for testing:" in config["prompt"] + + # Test tool without transformers + no_transform_tool = toolset.tools[2] + assert no_transform_tool.name == "kubectl_test_no_transform" + assert no_transform_tool.transformers is None + + finally: + # Clean up temporary file + os.unlink(tmp_file_path) + + def test_toolset_level_transformer_inheritance(self): + """Test that tools inherit transformers from toolset level.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + yaml_content = """ +toolsets: + test/kubernetes: + description: "Test Kubernetes toolset with toolset-level transformers" + transformers: + - name: llm_summarize + config: + input_threshold: 800 + prompt: "Toolset default prompt" + tools: + - name: "kubectl_inherit" + description: "Tool that inherits toolset transformers" + command: "kubectl get pods" + + - name: "kubectl_override" + description: "Tool that overrides toolset transformers" + command: "kubectl describe pod test" + transformers: + - name: llm_summarize + config: + input_threshold: 1200 + prompt: "Tool-specific override prompt" +""" + + # Write to temporary file + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + # Load toolsets from the temporary file + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + assert len(toolset.tools) == 2 + + # Test tool that inherits from toolset + inherit_tool = toolset.tools[0] + assert inherit_tool.name == "kubectl_inherit" + assert inherit_tool.transformers is not None + config = inherit_tool.transformers[0].config + assert config["input_threshold"] == 800 + assert config["prompt"] == "Toolset default prompt" + + # Test tool that overrides toolset config + override_tool = toolset.tools[1] + assert override_tool.name == "kubectl_override" + assert override_tool.transformers is not None + config = override_tool.transformers[0].config + assert config["input_threshold"] == 1200 + assert config["prompt"] == "Tool-specific override prompt" + + finally: + # Clean up temporary file + os.unlink(tmp_file_path) + + def test_backward_compatibility_no_transformers(self): + """Test that existing YAML files without transformers still work.""" + yaml_content = """ +toolsets: + test/legacy: + description: "Legacy toolset without transformers" + tools: + - name: "kubectl_legacy" + description: "Legacy tool" + command: "kubectl get pods" + + - name: "kubectl_legacy_2" + description: "Another legacy tool" + command: "kubectl get nodes" +""" + + # Write to temporary file + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + # Load toolsets from the temporary file + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + assert toolset.name == "test/legacy" + assert toolset.transformers is None + + # All tools should have no transformers + for tool in toolset.tools: + assert tool.transformers is None + + finally: + # Clean up temporary file + os.unlink(tmp_file_path) + + def test_invalid_transformer_handling(self): + """Test that invalid transformers are handled gracefully.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + yaml_content = """ +toolsets: + test/invalid: + description: "Test toolset with invalid transformer config" + tools: + - name: "kubectl_invalid" + description: "Tool with invalid transformer" + command: "kubectl get pods" + transformers: + - name: unknown_transformer + config: + some_param: "value" +""" + + # Write to temporary file + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + # Load toolsets from the temporary file + with patch("holmes.core.tools.logging") as mock_tools_logging, patch( + "holmes.core.transformers.transformer.logging" + ) as mock_transformer_logging: + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + + # Tool should have been created but with cleared transformers + tool = toolset.tools[0] + assert tool.name == "kubectl_invalid" + assert ( + tool.transformers is None + ) # Should be cleared due to validation failure + + # Should have logged warning about invalid config in either module + assert ( + mock_tools_logging.warning.called + or mock_transformer_logging.warning.called + ) + + finally: + # Clean up temporary file + os.unlink(tmp_file_path) + + def test_multiple_transformers_in_yaml(self): + """Test YAML parsing with multiple transformers per tool.""" + yaml_content = """ +toolsets: + test/multi: + description: "Test toolset with multiple transformers" + tools: + - name: "kubectl_multi" + description: "Tool with multiple transformers" + command: "kubectl get pods -o yaml" + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: "First transformer" + - name: llm_summarize + config: + input_threshold: 500 + prompt: "Second transformer" +""" + + # Write to temporary file + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + # Load toolsets from the temporary file + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + tool = toolset.tools[0] + + assert tool.name == "kubectl_multi" + assert tool.transformers is not None + assert len(tool.transformers) == 2 + + # Check first transformer + config1 = tool.transformers[0].config + assert config1["input_threshold"] == 1000 + assert config1["prompt"] == "First transformer" + + # Check second transformer + config2 = tool.transformers[1].config + assert config2["input_threshold"] == 500 + assert config2["prompt"] == "Second transformer" + + finally: + # Clean up temporary file + os.unlink(tmp_file_path) + + +class TestKubernetesTransformerPrompts: + """Test the specific transformer prompts configured for Kubernetes tools.""" + + def test_kubectl_describe_prompt_content(self): + """Test that kubectl_describe has appropriate summarization prompt.""" + current_dir = os.path.dirname(os.path.abspath(__file__)) + kubernetes_yaml_path = os.path.join( + current_dir, + "..", + "..", + "..", + "holmes", + "plugins", + "toolsets", + "kubernetes.yaml", + ) + + toolsets = load_toolsets_from_file(kubernetes_yaml_path) + kubernetes_core = next( + (ts for ts in toolsets if ts.name == "kubernetes/core"), None + ) + assert kubernetes_core is not None, "kubernetes/core toolset not found" + kubectl_describe = next( + (tool for tool in kubernetes_core.tools if tool.name == "kubectl_describe"), + None, + ) + assert kubectl_describe is not None, "kubectl_describe tool not found" + + assert kubectl_describe.transformers is not None + prompt = kubectl_describe.transformers[0].config["prompt"] + + # Check that prompt contains key elements for kubectl describe + assert "What needs attention or immediate action" in prompt + assert "Resource status and health indicators" in prompt + assert "errors, warnings" in prompt + assert "grep" in prompt # Should mention grep for drilling down + + def test_kubectl_logs_prompt_content(self): + """Test that kubectl_logs has appropriate summarization prompt.""" + current_dir = os.path.dirname(os.path.abspath(__file__)) + kubernetes_logs_yaml_path = os.path.join( + current_dir, + "..", + "..", + "..", + "holmes", + "plugins", + "toolsets", + "kubernetes_logs.yaml", + ) + + toolsets = load_toolsets_from_file(kubernetes_logs_yaml_path) + kubernetes_logs = next( + (ts for ts in toolsets if ts.name == "kubernetes/logs"), None + ) + assert kubernetes_logs is not None, "kubernetes/logs toolset not found" + kubectl_logs = next( + (tool for tool in kubernetes_logs.tools if tool.name == "kubectl_logs"), + None, + ) + assert kubectl_logs is not None, "kubectl_logs tool not found" + + assert kubectl_logs.transformers is not None + prompt = kubectl_logs.transformers[0].config["prompt"] + + # Check that prompt contains key elements for log analysis + assert "Errors, exceptions, and warning messages" in prompt + assert "activity patterns" in prompt + assert "authentication, connection" in prompt + assert "Performance indicators" in prompt + assert "exact error codes" in prompt + + def test_threshold_values_are_appropriate(self): + """Test that threshold values are set appropriately for different tool types.""" + # Load both YAML files + current_dir = os.path.dirname(os.path.abspath(__file__)) + + # Test kubernetes core tools (kubectl get, describe) + kubernetes_yaml_path = os.path.join( + current_dir, + "..", + "..", + "..", + "holmes", + "plugins", + "toolsets", + "kubernetes.yaml", + ) + toolsets = load_toolsets_from_file(kubernetes_yaml_path) + kubernetes_core = next( + (ts for ts in toolsets if ts.name == "kubernetes/core"), None + ) + assert kubernetes_core is not None, "kubernetes/core toolset not found" + + # kubectl describe should have threshold of 1000 + kubectl_describe = next( + (tool for tool in kubernetes_core.tools if tool.name == "kubectl_describe"), + None, + ) + assert kubectl_describe is not None, "kubectl_describe tool not found" + assert kubectl_describe.transformers is not None + assert kubectl_describe.transformers[0].config["input_threshold"] == 1000 + + # kubectl get tools should have threshold of 1000 + kubectl_get_ns = next( + ( + tool + for tool in kubernetes_core.tools + if tool.name == "kubectl_get_by_kind_in_namespace" + ), + None, + ) + assert ( + kubectl_get_ns is not None + ), "kubectl_get_by_kind_in_namespace tool not found" + assert kubectl_get_ns.transformers is not None + assert kubectl_get_ns.transformers[0].config["input_threshold"] == 1000 + + # Test kubernetes logs tools (higher threshold for logs) + kubernetes_logs_yaml_path = os.path.join( + current_dir, + "..", + "..", + "..", + "holmes", + "plugins", + "toolsets", + "kubernetes_logs.yaml", + ) + toolsets = load_toolsets_from_file(kubernetes_logs_yaml_path) + kubernetes_logs = next( + (ts for ts in toolsets if ts.name == "kubernetes/logs"), None + ) + assert kubernetes_logs is not None, "kubernetes/logs toolset not found" + + # kubectl logs should have higher threshold of 1000 (logs can be longer) + kubectl_logs = next( + (tool for tool in kubernetes_logs.tools if tool.name == "kubectl_logs"), + None, + ) + assert kubectl_logs is not None, "kubectl_logs tool not found" + assert kubectl_logs.transformers is not None + assert kubectl_logs.transformers[0].config["input_threshold"] == 1000 diff --git a/tests/plugins/toolsets/test_transformer_validation.py b/tests/plugins/toolsets/test_transformer_validation.py new file mode 100644 index 0000000000..dbd6115a16 --- /dev/null +++ b/tests/plugins/toolsets/test_transformer_validation.py @@ -0,0 +1,361 @@ +""" +Tests for transformer validation and conversion logic introduced with Pydantic refactoring. +""" + +import tempfile +import os +from unittest.mock import patch + +from holmes.plugins.toolsets import load_toolsets_from_file +from .transformer_test_utils import ensure_transformers_registered + + +class TestTransformerValidationAndConversion: + """Test the new transformer validation and conversion logic in preprocess_tools.""" + + def test_malformed_transformer_dict_tool_level(self): + """Test that malformed transformer dicts at tool level are handled gracefully.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + yaml_content = """ +toolsets: + test/malformed: + description: "Test toolset with malformed transformer config at tool level" + tools: + - name: "kubectl_malformed" + description: "Tool with malformed transformers" + command: "kubectl get pods" + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + - invalid_structure: "missing required fields" + - name: "missing_config_field" +""" + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + # Focus on the core functionality - invalid transformers should be filtered out + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + + # Tool should have only the valid transformer + tool = toolset.tools[0] + assert tool.name == "kubectl_malformed" + assert tool.transformers is not None + assert len(tool.transformers) == 1 + assert tool.transformers[0].name == "llm_summarize" + + finally: + os.unlink(tmp_file_path) + + def test_mixed_valid_invalid_transformers_toolset_level(self): + """Test mixing valid and invalid transformers at toolset level.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + yaml_content = """ +toolsets: + test/mixed: + description: "Test toolset with mixed valid/invalid transformers" + transformers: + - name: llm_summarize + config: + input_threshold: 500 + - name: unknown_transformer + config: + param: "value" + - name: llm_summarize + config: + input_threshold: 1000 + prompt: "Second valid transformer" + tools: + - name: "kubectl_inherit" + description: "Tool that inherits mixed transformers" + command: "kubectl get pods" +""" + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + with patch("holmes.core.tools.logging") as mock_tools_logging, patch( + "holmes.core.transformers.transformer.logging" + ) as mock_transformer_logging: + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + + # Tool should inherit only valid transformers + tool = toolset.tools[0] + assert tool.transformers is not None + # Should have 2 valid llm_summarize transformers + assert len(tool.transformers) == 2 + assert all(t.name == "llm_summarize" for t in tool.transformers) + + # Should have logged warning for unknown_transformer in either module + assert ( + mock_tools_logging.warning.called + or mock_transformer_logging.warning.called + ) + + finally: + os.unlink(tmp_file_path) + + def test_mixed_valid_invalid_transformers_tool_level(self): + """Test mixing valid and invalid transformers at tool level.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + yaml_content = """ +toolsets: + test/mixed_tool: + description: "Test toolset with mixed transformers at tool level" + tools: + - name: "kubectl_mixed" + description: "Tool with mixed valid/invalid transformers" + command: "kubectl get pods" + transformers: + - name: llm_summarize + config: + input_threshold: 800 + - name: invalid_transformer + config: + param: "value" + - malformed: "structure" +""" + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + # Don't worry about exact logging counts, just test the core functionality + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + + # Tool should have only valid transformers + tool = toolset.tools[0] + assert tool.transformers is not None + assert len(tool.transformers) == 1 + assert tool.transformers[0].name == "llm_summarize" + assert tool.transformers[0].config["input_threshold"] == 800 + + finally: + os.unlink(tmp_file_path) + + def test_inheritance_with_mixed_validation_states(self): + """Test inheritance when toolset has valid transformers and tool has invalid ones.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + yaml_content = """ +toolsets: + test/inheritance_mixed: + description: "Test inheritance with mixed validation states" + transformers: + - name: llm_summarize + config: + input_threshold: 500 + prompt: "Toolset default" + tools: + - name: "kubectl_inherit_good" + description: "Tool that inherits valid toolset transformers" + command: "kubectl get pods" + + - name: "kubectl_override_bad" + description: "Tool with invalid transformers that should fall back to toolset" + command: "kubectl describe pod" + transformers: + - name: unknown_transformer + config: + param: "value" + - malformed: "config" + + - name: "kubectl_override_mixed" + description: "Tool with mixed transformers that should merge with toolset" + command: "kubectl logs pod" + transformers: + - name: llm_summarize + config: + input_threshold: 1200 + prompt: "Tool override" + - name: invalid_transformer + config: + param: "value" +""" + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + with patch("holmes.core.tools.logging") as mock_tools_logging, patch( + "holmes.core.transformers.transformer.logging" + ) as mock_transformer_logging: + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + assert len(toolset.tools) == 3 + + # Tool 1: Should inherit valid toolset transformers + inherit_tool = toolset.tools[0] + assert inherit_tool.name == "kubectl_inherit_good" + assert inherit_tool.transformers is not None + assert len(inherit_tool.transformers) == 1 + assert ( + inherit_tool.transformers[0].config["prompt"] == "Toolset default" + ) + + # Tool 2: Should fall back to toolset transformers after invalid tool transformers are filtered + fallback_tool = toolset.tools[1] + assert fallback_tool.name == "kubectl_override_bad" + assert fallback_tool.transformers is not None + assert len(fallback_tool.transformers) == 1 + assert ( + fallback_tool.transformers[0].config["prompt"] == "Toolset default" + ) + + # Tool 3: Should have merged valid transformers (tool overrides toolset) + mixed_tool = toolset.tools[2] + assert mixed_tool.name == "kubectl_override_mixed" + assert mixed_tool.transformers is not None + assert len(mixed_tool.transformers) == 1 + assert mixed_tool.transformers[0].config["input_threshold"] == 1200 + assert mixed_tool.transformers[0].config["prompt"] == "Tool override" + + # Should have logged warnings for invalid transformers in either module + assert ( + mock_tools_logging.warning.called + or mock_transformer_logging.warning.called + ) + + finally: + os.unlink(tmp_file_path) + + def test_empty_transformer_lists_after_validation(self): + """Test behavior when all transformers are invalid and lists become empty.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + yaml_content = """ +toolsets: + test/all_invalid: + description: "Test toolset where all transformers are invalid" + transformers: + - name: unknown_transformer_1 + config: + param: "value1" + - name: unknown_transformer_2 + config: + param: "value2" + tools: + - name: "kubectl_no_transformers" + description: "Tool that should end up with no transformers" + command: "kubectl get pods" +""" + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + with patch("holmes.core.tools.logging") as mock_tools_logging, patch( + "holmes.core.transformers.transformer.logging" + ) as mock_transformer_logging: + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + + # Tool should have no transformers after invalid ones are filtered + tool = toolset.tools[0] + assert tool.transformers is None + + # Should have logged warnings for both invalid transformers in either module + total_warning_calls = ( + mock_tools_logging.warning.call_count + + mock_transformer_logging.warning.call_count + ) + assert total_warning_calls >= 2 + + finally: + os.unlink(tmp_file_path) + + def test_transformer_conversion_preserves_config_structure(self): + """Test that the dict-to-Transformer conversion preserves complex config structures.""" + # Ensure transformer registry is properly initialized + ensure_transformers_registered() + + yaml_content = """ +toolsets: + test/complex_config: + description: "Test toolset with complex transformer configurations" + transformers: + - name: llm_summarize + config: + input_threshold: 1000 + prompt: | + Multi-line prompt with: + - Bullet points + - Complex formatting + - Variables: {{ variable }} + nested_config: + level1: + level2: "deep value" + array: [1, 2, 3] + boolean_flag: true + null_value: null + tools: + - name: "kubectl_complex" + description: "Tool with complex config" + command: "kubectl get pods" +""" + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as tmp_file: + tmp_file.write(yaml_content) + tmp_file_path = tmp_file.name + + try: + toolsets = load_toolsets_from_file(tmp_file_path) + + assert len(toolsets) == 1 + toolset = toolsets[0] + tool = toolset.tools[0] + + assert tool.transformers is not None + assert len(tool.transformers) == 1 + + config = tool.transformers[0].config + assert config["input_threshold"] == 1000 + assert "Multi-line prompt with:" in config["prompt"] + assert config["nested_config"]["level1"]["level2"] == "deep value" + assert config["nested_config"]["array"] == [1, 2, 3] + assert config["boolean_flag"] is True + assert config["null_value"] is None + + finally: + os.unlink(tmp_file_path) diff --git a/tests/plugins/toolsets/transformer_test_utils.py b/tests/plugins/toolsets/transformer_test_utils.py new file mode 100644 index 0000000000..981ac66937 --- /dev/null +++ b/tests/plugins/toolsets/transformer_test_utils.py @@ -0,0 +1,29 @@ +""" +Common test utilities for transformer testing. +""" + + +def ensure_transformers_registered(): + """ + Ensure required transformers are registered in the global registry. + + This utility handles the case where other tests may have cleared or modified + the global transformer registry, ensuring that required transformers are + available for YAML parsing and validation tests. + + Returns: + registry: The transformer registry instance + """ + # Import the transformers module to trigger automatic registration + from holmes.core.transformers import registry, LLMSummarizeTransformer + + # Re-register if missing (some tests may clear the global registry) + if not registry.is_registered("llm_summarize"): + registry.register(LLMSummarizeTransformer) + + # Verify registration + assert registry.is_registered( + "llm_summarize" + ), "llm_summarize transformer should be registered for tests" + + return registry diff --git a/tests/utils/test_config_utils.py b/tests/utils/test_config_utils.py new file mode 100644 index 0000000000..76cb43da58 --- /dev/null +++ b/tests/utils/test_config_utils.py @@ -0,0 +1,185 @@ +""" +Tests for configuration utility functions. +""" + +from holmes.utils.config_utils import merge_transformers +from holmes.core.transformers import Transformer + + +def test_merge_transformers_both_none(): + """Test that merging None transformers returns None.""" + result = merge_transformers(None, None) + assert result is None + + +def test_merge_transformers_base_none(): + """Test that when base is None, override transformers are returned.""" + override = [Transformer(name="llm_summarize", config={"input_threshold": 1000})] + result = merge_transformers(None, override) + assert result == override + + +def test_merge_transformers_override_none(): + """Test that when override is None, base transformers are returned (default behavior).""" + base = [Transformer(name="llm_summarize", config={"fast_model": "gpt-4o-mini"})] + result = merge_transformers(base, None) + assert result == base + + +def test_merge_transformers_both_empty(): + """Test that merging empty lists returns None.""" + result = merge_transformers([], []) + assert result is None + + +def test_merge_transformers_field_level_merge(): + """Test field-level merging with precedence.""" + base = [ + Transformer( + name="llm_summarize", + config={"fast_model": "gpt-4o-mini", "input_threshold": 500}, + ) + ] + override = [ + Transformer( + name="llm_summarize", config={"input_threshold": 1000, "prompt": "Custom"} + ) + ] + + result = merge_transformers(base, override) + + assert len(result) == 1 + assert result[0].name == "llm_summarize" + assert result[0].config == { + "fast_model": "gpt-4o-mini", # From base + "input_threshold": 1000, # Override wins + "prompt": "Custom", # From override + } + + +def test_merge_transformers_different_types(): + """Test merging different transformer types.""" + base = [Transformer(name="llm_summarize", config={"fast_model": "gpt-4o-mini"})] + override = [Transformer(name="custom_transformer", config={"param": "value"})] + + result = merge_transformers(base, override) + + # Should have both transformers + result_names = {t.name for t in result} + assert "llm_summarize" in result_names + assert "custom_transformer" in result_names + assert len(result) == 2 + + +def test_merge_transformers_multiple_base(): + """Test merging with multiple transformers in base list.""" + base = [ + Transformer(name="llm_summarize", config={"fast_model": "gpt-4o-mini"}), + Transformer(name="custom_transformer", config={"param": "base_value"}), + ] + override = [Transformer(name="llm_summarize", config={"input_threshold": 1000})] + + result = merge_transformers(base, override) + + # Check that llm_summarize was merged and custom_transformer was preserved + result_dict = {t.name: t.config for t in result} + + assert result_dict["llm_summarize"]["fast_model"] == "gpt-4o-mini" + assert result_dict["llm_summarize"]["input_threshold"] == 1000 + assert result_dict["custom_transformer"]["param"] == "base_value" + + +def test_merge_transformers_override_precedence(): + """Test that override transformers take precedence for existing fields.""" + base = [ + Transformer( + name="llm_summarize", + config={ + "fast_model": "gpt-4o-mini", + "input_threshold": 500, + "prompt": "Base prompt", + }, + ) + ] + override = [ + Transformer( + name="llm_summarize", + config={"input_threshold": 2000, "prompt": "Override prompt"}, + ) + ] + + result = merge_transformers(base, override) + + assert len(result) == 1 + assert result[0].name == "llm_summarize" + assert result[0].config == { + "fast_model": "gpt-4o-mini", # From base (not overridden) + "input_threshold": 2000, # Override wins + "prompt": "Override prompt", # Override wins + } + + +def test_merge_transformers_complex_scenario(): + """Test complex merging scenario with multiple types and transformers.""" + base = [ + Transformer( + name="llm_summarize", + config={"fast_model": "gpt-4o-mini", "input_threshold": 500}, + ), + Transformer(name="data_filter", config={"max_items": 100}), + ] + override = [ + Transformer( + name="llm_summarize", config={"input_threshold": 1000, "prompt": "Custom"} + ), + Transformer(name="result_formatter", config={"format": "json"}), + ] + + result = merge_transformers(base, override) + + # Convert to dict for easier assertions + result_dict = {t.name: t.config for t in result} + + # Check llm_summarize was merged properly + assert result_dict["llm_summarize"]["fast_model"] == "gpt-4o-mini" # From base + assert result_dict["llm_summarize"]["input_threshold"] == 1000 # Override + assert result_dict["llm_summarize"]["prompt"] == "Custom" # Override + + # Check other types were preserved + assert result_dict["data_filter"]["max_items"] == 100 + assert result_dict["result_formatter"]["format"] == "json" + + # Should have 3 transformer types + assert len(result_dict) == 3 + + +def test_merge_transformers_only_merge_when_override_exists_true(): + """Test that with only_merge_when_override_exists=True, None is returned when no override exists.""" + base = [Transformer(name="llm_summarize", config={"fast_model": "gpt-4o-mini"})] + result = merge_transformers(base, None, only_merge_when_override_exists=True) + assert result is None + + +def test_merge_transformers_only_merge_when_override_exists_false(): + """Test that with only_merge_when_override_exists=False, base transformers are returned.""" + base = [Transformer(name="llm_summarize", config={"fast_model": "gpt-4o-mini"})] + result = merge_transformers(base, None, only_merge_when_override_exists=False) + assert result == base + + +def test_merge_transformers_only_merge_when_override_exists_with_override(): + """Test that the parameter doesn't affect behavior when both base and override exist.""" + base = [Transformer(name="llm_summarize", config={"fast_model": "gpt-4o-mini"})] + override = [Transformer(name="llm_summarize", config={"prompt": "Custom"})] + + # Should work the same regardless of parameter value when both exist + result_true = merge_transformers( + base, override, only_merge_when_override_exists=True + ) + result_false = merge_transformers( + base, override, only_merge_when_override_exists=False + ) + + assert result_true == result_false + assert len(result_true) == 1 + assert result_true[0].config == {"fast_model": "gpt-4o-mini", "prompt": "Custom"} From 5bd9dbae7f8d845a9139a33e6563cb07ee45d3f0 Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Fri, 29 Aug 2025 11:22:20 +1000 Subject: [PATCH 02/11] remove global transfomer --- holmes/config.py | 25 -- .../test_config_fast_model_flow.py | 129 ++++++++ .../config_class/test_config_transformers.py | 260 --------------- tests/core/test_config_transformers.py | 302 ------------------ ...est_transformer_backwards_compatibility.py | 283 ---------------- 5 files changed, 129 insertions(+), 870 deletions(-) create mode 100644 tests/config_class/test_config_fast_model_flow.py delete mode 100644 tests/config_class/test_config_transformers.py delete mode 100644 tests/core/test_config_transformers.py delete mode 100644 tests/core/test_transformer_backwards_compatibility.py diff --git a/holmes/config.py b/holmes/config.py index 4307e43926..826fec6174 100644 --- a/holmes/config.py +++ b/holmes/config.py @@ -18,7 +18,6 @@ ROBUSTA_API_ENDPOINT, ROBUSTA_CONFIG_PATH, ) -from holmes.core.transformers import Transformer from holmes.core.tools_utils.tool_executor import ToolExecutor from holmes.core.toolset_manager import ToolsetManager from holmes.plugins.runbooks import ( @@ -85,7 +84,6 @@ class Config(RobustaBaseConfig): model: Optional[str] = "gpt-4o" fast_model: Optional[str] = None - transformers: Optional[List[Transformer]] = None max_steps: int = 40 cluster_name: Optional[str] = None @@ -196,8 +194,6 @@ def _load_default_robusta_config(self): "is_robusta_model": True, } - # Auto-generate transformers from CLI fast_model parameter - self._auto_generate_transformers() def _should_load_robusta_ai(self) -> bool: if not self.should_try_robusta_ai: @@ -218,23 +214,6 @@ def _should_load_robusta_ai(self) -> bool: return True - def _auto_generate_transformers(self) -> None: - """ - Auto-generate transformers from CLI fast_model parameter. - Only generates if fast_model is provided and transformers is not already set. - """ - if self.fast_model and not self.transformers: - self.transformers = [ - Transformer( - name="llm_summarize", - config={ - "fast_model": self.fast_model, - }, - ) - ] - logging.debug( - f"Auto-generated transformer config with fast_model: {self.fast_model}" - ) def log_useful_info(self): if self._model_list: @@ -252,8 +231,6 @@ def load_from_file(cls, config_file: Optional[Path], **kwargs) -> "Config": Returns: Config instance with merged settings """ - # Rebuild the model to resolve forward references - cls.model_rebuild() config_from_file: Optional[Config] = None if config_file is not None and config_file.exists(): @@ -275,8 +252,6 @@ def load_from_file(cls, config_file: Optional[Path], **kwargs) -> "Config": @classmethod def load_from_env(cls): - # Rebuild the model to resolve forward references - cls.model_rebuild() kwargs = {} for field_name in [ diff --git a/tests/config_class/test_config_fast_model_flow.py b/tests/config_class/test_config_fast_model_flow.py new file mode 100644 index 0000000000..d33e7ac396 --- /dev/null +++ b/tests/config_class/test_config_fast_model_flow.py @@ -0,0 +1,129 @@ +""" +Unit tests for Config.fast_model flow to ToolsetManager. + +These tests verify that the fast_model configuration flows correctly from +Config.fast_model to ToolsetManager.global_fast_model. +""" + +import tempfile +import yaml +from pathlib import Path +from unittest.mock import patch + +from holmes.config import Config + + +class TestConfigFastModelFlow: + """Test that Config.fast_model flows correctly to ToolsetManager.""" + + def test_config_fast_model_flows_to_toolset_manager(self): + """Test that Config.fast_model is passed to ToolsetManager.global_fast_model.""" + # Create config with fast_model + config = Config(fast_model="gpt-3.5-turbo") + + # Verify fast_model is set + assert config.fast_model == "gpt-3.5-turbo" + + # Verify ToolsetManager receives the fast_model + toolset_manager = config.toolset_manager + assert toolset_manager.global_fast_model == "gpt-3.5-turbo" + + def test_config_no_fast_model_flows_to_toolset_manager(self): + """Test that Config without fast_model passes None to ToolsetManager.""" + # Create config without fast_model + config = Config() + + # Verify fast_model is None + assert config.fast_model is None + + # Verify ToolsetManager receives None + toolset_manager = config.toolset_manager + assert toolset_manager.global_fast_model is None + + def test_config_from_file_fast_model_flows_to_toolset_manager(self): + """Test that Config loaded from file passes fast_model to ToolsetManager.""" + # Create temporary config file with fast_model + config_data = { + "model": "gpt-4o", + "fast_model": "gpt-4o-mini", + "max_steps": 20 + } + + with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f: + yaml.dump(config_data, f) + config_path = Path(f.name) + + try: + # Mock dependencies to avoid side effects + with patch("holmes.config.parse_models_file", return_value={}): + config = Config.load_from_file(config_path) + + # Verify fast_model is loaded + assert config.fast_model == "gpt-4o-mini" + + # Verify ToolsetManager receives the fast_model + toolset_manager = config.toolset_manager + assert toolset_manager.global_fast_model == "gpt-4o-mini" + + finally: + config_path.unlink() # Clean up temp file + + def test_config_from_env_fast_model_flows_to_toolset_manager(self): + """Test that Config loaded from env passes fast_model to ToolsetManager.""" + test_env = { + "MODEL": "gpt-4o", + "FAST_MODEL": "gpt-3.5-turbo" + } + + with patch.dict("os.environ", test_env): + with patch("holmes.config.Config._Config__get_cluster_name", return_value=None): + with patch("holmes.config.parse_models_file", return_value={}): + config = Config.load_from_env() + + # Verify fast_model is loaded from env + assert config.fast_model == "gpt-3.5-turbo" + + # Verify ToolsetManager receives the fast_model + toolset_manager = config.toolset_manager + assert toolset_manager.global_fast_model == "gpt-3.5-turbo" + + def test_config_cli_override_fast_model_flows_to_toolset_manager(self): + """Test that CLI override of fast_model flows to ToolsetManager.""" + # Create temporary config file without fast_model + config_data = { + "model": "gpt-4o", + "max_steps": 20 + } + + with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f: + yaml.dump(config_data, f) + config_path = Path(f.name) + + try: + # Mock dependencies to avoid side effects + with patch("holmes.config.parse_models_file", return_value={}): + # CLI option overrides file config + config = Config.load_from_file(config_path, fast_model="claude-3-sonnet") + + # Verify fast_model is set from CLI + assert config.fast_model == "claude-3-sonnet" + + # Verify ToolsetManager receives the CLI fast_model + toolset_manager = config.toolset_manager + assert toolset_manager.global_fast_model == "claude-3-sonnet" + + finally: + config_path.unlink() # Clean up temp file + + def test_config_toolset_manager_caching(self): + """Test that toolset_manager property is cached correctly.""" + config = Config(fast_model="gpt-4o-mini") + + # First access creates the toolset manager + toolset_manager1 = config.toolset_manager + assert toolset_manager1.global_fast_model == "gpt-4o-mini" + + # Second access returns the same instance + toolset_manager2 = config.toolset_manager + assert toolset_manager2 is toolset_manager1 + assert toolset_manager2.global_fast_model == "gpt-4o-mini" \ No newline at end of file diff --git a/tests/config_class/test_config_transformers.py b/tests/config_class/test_config_transformers.py deleted file mode 100644 index b3008cffc6..0000000000 --- a/tests/config_class/test_config_transformers.py +++ /dev/null @@ -1,260 +0,0 @@ -""" -Unit tests for transformer configuration fields. - -These tests verify that the fast_model configuration -fields work correctly with different configuration sources (file, env, CLI). -""" - -import os -import tempfile -import yaml -from pathlib import Path -from unittest.mock import patch - - -def test_transformer_fields_exist(): - """Test that Config class has the transformer configuration fields.""" - # Mock the dependencies at their actual import locations - with patch("holmes.version.get_version", return_value="1.0.0"), patch( - "holmes.clients.robusta_client.fetch_holmes_info", return_value=None - ), patch("holmes.config.parse_models_file", return_value={}), patch( - "holmes.common.env_vars.ROBUSTA_AI", False - ): - from holmes.config import Config - from holmes.core.transformers import Transformer - - # Import Transformer class to resolve forward reference - import sys - - sys.modules[__name__].__dict__["Transformer"] = Transformer - - # Rebuild the model to resolve forward references - Config.model_rebuild() - - # Test default values - config = Config() - assert hasattr(config, "fast_model") - assert config.fast_model is None - - -def test_transformer_from_file(): - """Test loading transformer config from YAML file.""" - with patch("holmes.version.get_version", return_value="1.0.0"), patch( - "holmes.clients.robusta_client.fetch_holmes_info", return_value=None - ), patch("holmes.config.parse_models_file", return_value={}), patch( - "holmes.common.env_vars.ROBUSTA_AI", False - ): - from holmes.config import Config - from holmes.core.transformers import Transformer - import sys - - sys.modules[__name__].__dict__["Transformer"] = Transformer - Config.model_rebuild() - - with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f: - config_data = { - "fast_model": "gpt-4o-mini", - "model": "gpt-4o", - } - yaml.dump(config_data, f) - f.flush() - - try: - config = Config.load_from_file(Path(f.name)) - assert config.fast_model == "gpt-4o-mini" - assert config.model == "gpt-4o" - finally: - os.unlink(f.name) - - -def test_transformer_from_env(): - """Test loading transformer config from environment variables.""" - with patch("holmes.version.get_version", return_value="1.0.0"), patch( - "holmes.clients.robusta_client.fetch_holmes_info", return_value=None - ), patch("holmes.config.parse_models_file", return_value={}), patch( - "holmes.common.env_vars.ROBUSTA_AI", False - ): - from holmes.config import Config - from holmes.core.transformers import Transformer - import sys - - sys.modules[__name__].__dict__["Transformer"] = Transformer - Config.model_rebuild() - - with patch.dict( - os.environ, - { - "FAST_MODEL": "gpt-3.5-turbo", - "MODEL": "gpt-4o", - }, - ): - config = Config.load_from_env() - assert config.fast_model == "gpt-3.5-turbo" - assert config.model == "gpt-4o" - - -def test_transformer_cli_override(): - """Test that CLI options override config file values.""" - with patch("holmes.version.get_version", return_value="1.0.0"), patch( - "holmes.clients.robusta_client.fetch_holmes_info", return_value=None - ), patch("holmes.config.parse_models_file", return_value={}), patch( - "holmes.common.env_vars.ROBUSTA_AI", False - ): - from holmes.config import Config - from holmes.core.transformers import Transformer - import sys - - sys.modules[__name__].__dict__["Transformer"] = Transformer - Config.model_rebuild() - - with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f: - config_data = {"fast_model": "gpt-4o-mini"} - yaml.dump(config_data, f) - f.flush() - - try: - config = Config.load_from_file(Path(f.name), fast_model="gpt-3.5-turbo") - assert config.fast_model == "gpt-3.5-turbo" - finally: - os.unlink(f.name) - - -def test_transformer_backward_compatibility(): - """Test that existing configs without transformer fields still work.""" - with patch("holmes.version.get_version", return_value="1.0.0"), patch( - "holmes.clients.robusta_client.fetch_holmes_info", return_value=None - ), patch("holmes.config.parse_models_file", return_value={}), patch( - "holmes.common.env_vars.ROBUSTA_AI", False - ): - from holmes.config import Config - from holmes.core.transformers import Transformer - import sys - - sys.modules[__name__].__dict__["Transformer"] = Transformer - Config.model_rebuild() - - with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f: - config_data = {"model": "gpt-4o", "max_steps": 5} - yaml.dump(config_data, f) - f.flush() - - try: - config = Config.load_from_file(Path(f.name)) - assert config.model == "gpt-4o" - assert config.max_steps == 5 - # New fields should have defaults - assert config.fast_model is None - finally: - os.unlink(f.name) - - -def test_transformer_env_vars_in_load_from_env_list(): - """Test that the fast_model environment variable is properly loaded by load_from_env method.""" - # This tests that the fast_model field is correctly loaded from environment variables - with patch("holmes.version.get_version", return_value="1.0.0"), patch( - "holmes.clients.robusta_client.fetch_holmes_info", return_value=None - ), patch("holmes.config.parse_models_file", return_value={}), patch( - "holmes.common.env_vars.ROBUSTA_AI", False - ): - from holmes.config import Config - from holmes.core.transformers import Transformer - import sys - - sys.modules[__name__].__dict__["Transformer"] = Transformer - Config.model_rebuild() - - # Test that FAST_MODEL environment variable is properly loaded - with patch.dict(os.environ, {"FAST_MODEL": "test-model"}): - config = Config.load_from_env() - assert config.fast_model == "test-model" - - -def test_auto_generate_transformers_with_fast_model(): - """Test that Config stores fast_model for ToolsetManager injection.""" - with patch("holmes.version.get_version", return_value="1.0.0"), patch( - "holmes.clients.robusta_client.fetch_holmes_info", return_value=None - ), patch("holmes.config.parse_models_file", return_value={}), patch( - "holmes.common.env_vars.ROBUSTA_AI", False - ): - from holmes.config import Config - from holmes.core.transformers import Transformer - import sys - - sys.modules[__name__].__dict__["Transformer"] = Transformer - Config.model_rebuild() - - # Test with fast_model provided - config = Config(fast_model="gpt-4o-mini") - - # Should store fast_model for ToolsetManager injection - assert config.fast_model == "gpt-4o-mini" - # Should auto-generate transformers for backwards compatibility - assert config.transformers is not None - assert len(config.transformers) == 1 - assert config.transformers[0].name == "llm_summarize" - assert config.transformers[0].config["fast_model"] == "gpt-4o-mini" - - -def test_auto_generate_transformers_without_fast_model(): - """Test that transformers are not auto-generated when fast_model is not provided.""" - with patch("holmes.version.get_version", return_value="1.0.0"), patch( - "holmes.clients.robusta_client.fetch_holmes_info", return_value=None - ), patch("holmes.config.parse_models_file", return_value={}), patch( - "holmes.common.env_vars.ROBUSTA_AI", False - ): - from holmes.config import Config - from holmes.core.transformers import Transformer - import sys - - sys.modules[__name__].__dict__["Transformer"] = Transformer - Config.model_rebuild() - - # Test without fast_model - config = Config() - - # Should not auto-generate transformers - assert config.transformers is None - assert config.fast_model is None - - -def test_auto_generate_transformers_respects_existing_configs(): - """Test that existing transformers are not overridden by auto-generation.""" - with patch("holmes.version.get_version", return_value="1.0.0"), patch( - "holmes.clients.robusta_client.fetch_holmes_info", return_value=None - ), patch("holmes.config.parse_models_file", return_value={}), patch( - "holmes.common.env_vars.ROBUSTA_AI", False - ): - from holmes.config import Config - from holmes.core.transformers import Transformer - - # Test with existing transformers - existing_configs = [ - Transformer(name="custom_transformer", config={"param": "value"}) - ] - config = Config(fast_model="gpt-4o-mini", transformers=existing_configs) - - # Should preserve existing transformers - assert config.transformers == existing_configs - - -def test_auto_generate_transformers_cli_override(): - """Test that CLI fast_model parameter is stored for ToolsetManager injection.""" - with patch("holmes.version.get_version", return_value="1.0.0"), patch( - "holmes.clients.robusta_client.fetch_holmes_info", return_value=None - ), patch("holmes.config.parse_models_file", return_value={}), patch( - "holmes.common.env_vars.ROBUSTA_AI", False - ): - from holmes.config import Config - - # Test CLI override case (similar to holmes ask --fast-model) - config = Config.load_from_file( - None, # No config file - fast_model="azure/gpt-4.1", - ) - - # Should store fast_model for ToolsetManager injection and auto-generate transformers - assert config.fast_model == "azure/gpt-4.1" - assert config.transformers is not None - assert len(config.transformers) == 1 - assert config.transformers[0].name == "llm_summarize" - assert config.transformers[0].config["fast_model"] == "azure/gpt-4.1" diff --git a/tests/core/test_config_transformers.py b/tests/core/test_config_transformers.py deleted file mode 100644 index 7ffb772574..0000000000 --- a/tests/core/test_config_transformers.py +++ /dev/null @@ -1,302 +0,0 @@ -"""Tests for global transformer configuration inheritance.""" - -from unittest.mock import Mock, patch -import sys - -from holmes.config import Config -from holmes.core.toolset_manager import ToolsetManager -from holmes.core.tools import Toolset, Tool -from holmes.core.transformers import Transformer, registry - -# Setup global namespace for Config model rebuilding -sys.modules[__name__].__dict__["Transformer"] = Transformer -Config.model_rebuild() - - -class TestConfigTransformers: - """Test global transformer configuration functionality.""" - - def test_config_loads_transformers_from_dict(self): - """Test that Config correctly loads transformers from dict.""" - transformers = [ - Transformer( - name="llm_summarize", - config={"input_threshold": 1000, "prompt": "Test prompt"}, - ) - ] - config_data = { - "model": "gpt-4o", - "transformers": transformers, - } - - config = Config(**config_data) - - assert config.transformers is not None - assert len(config.transformers) == 1 - assert config.transformers[0].name == "llm_summarize" - assert config.transformers[0].config["input_threshold"] == 1000 - assert config.transformers[0].config["prompt"] == "Test prompt" - - def test_config_handles_none_transformers(self): - """Test that Config handles None transformers gracefully.""" - - config_data = {"model": "gpt-4o", "transformers": None} - - config = Config(**config_data) - - assert config.transformers is None - - def test_config_handles_empty_transformers(self): - """Test that Config handles empty transformers list.""" - - config_data = {"model": "gpt-4o", "transformers": []} - - config = Config(**config_data) - - assert config.transformers == [] - - def test_config_passes_fast_model_to_toolset_manager(self): - """Test that Config passes fast_model to ToolsetManager.""" - - config_data = {"model": "gpt-4o", "fast_model": "gpt-4o-mini"} - - config = Config(**config_data) - - # Access the toolset_manager property to trigger creation - toolset_manager = config.toolset_manager - - assert toolset_manager.global_fast_model == "gpt-4o-mini" - - @patch("holmes.config.ToolsetManager") - def test_toolset_manager_receives_fast_model(self, mock_toolset_manager): - """Test that ToolsetManager receives global fast_model.""" - - config_data = {"model": "gpt-4o", "fast_model": "gpt-4o-mini"} - - config = Config(**config_data) - - # Access toolset_manager to trigger creation - _ = config.toolset_manager - - # Verify ToolsetManager was called with global_fast_model - mock_toolset_manager.assert_called_once() - call_kwargs = mock_toolset_manager.call_args[1] - assert call_kwargs["global_fast_model"] == "gpt-4o-mini" - - -class TestToolsetManagerFastModel: - """Test ToolsetManager fast model injection functionality.""" - - def test_toolset_manager_stores_global_fast_model(self): - """Test that ToolsetManager stores global fast model.""" - global_fast_model = "gpt-4o-mini" - - manager = ToolsetManager(global_fast_model=global_fast_model) - - assert manager.global_fast_model == global_fast_model - - def test_inject_fast_model_to_transformers_with_existing_configs(self): - """Test that fast model is injected into transformers without fast_model config.""" - global_fast_model = "gpt-4o-mini" - - # Create a real Transformer instance with the config (not a mock) - mock_transformer = Transformer( - name="llm_summarize", config={"input_threshold": 1000} - ) - - mock_toolset = Mock(spec=Toolset) - mock_toolset.transformers = [mock_transformer] - mock_toolset.tools = [] - mock_toolset.name = "test_toolset" - - manager = ToolsetManager(global_fast_model=global_fast_model) - manager._inject_fast_model_into_transformers([mock_toolset]) - - # Should inject global_fast_model into transformer config - assert mock_transformer.config["global_fast_model"] == "gpt-4o-mini" - - def test_does_not_inject_when_fast_model_already_exists(self): - """Test that existing fast_model configs are not overridden.""" - global_fast_model = "gpt-4o-mini" - - # Create transformer with existing fast_model using real Transformer instance - mock_transformer = Transformer( - name="llm_summarize", - config={ - "input_threshold": 500, - "fast_model": "existing-model", - }, - ) - - mock_toolset = Mock(spec=Toolset) - mock_toolset.transformers = [mock_transformer] - mock_toolset.tools = [] - mock_toolset.name = "test_toolset" - - manager = ToolsetManager(global_fast_model=global_fast_model) - manager._inject_fast_model_into_transformers([mock_toolset]) - - # Should NOT override existing fast_model - assert mock_transformer.config["fast_model"] == "existing-model" - assert "global_fast_model" not in mock_transformer.config - - def test_inject_into_tool_level_transformers(self): - """Test that fast model is injected into tool-level transformers.""" - global_fast_model = "gpt-4o-mini" - - # Create mock tool with transformers that need fast_model using real Transformer - mock_tool_transformer = Transformer( - name="llm_summarize", config={"input_threshold": 200} - ) - - mock_tool = Mock(spec=Tool) - mock_tool.transformers = [mock_tool_transformer] - mock_tool.name = "test_tool" - mock_tool._transformer_instances = [] - - # Create mock toolset without toolset-level transformers - mock_toolset = Mock(spec=Toolset) - mock_toolset.transformers = None - mock_toolset.tools = [mock_tool] - mock_toolset.name = "test_toolset" - - # Mock the transformer registry - mock_instance = Mock() - with patch.object(registry, "create_transformer") as mock_create_transformer: - mock_create_transformer.return_value = mock_instance - - manager = ToolsetManager(global_fast_model=global_fast_model) - manager._inject_fast_model_into_transformers([mock_toolset]) - - # Should inject global_fast_model into tool transformer - assert mock_tool_transformer.config["global_fast_model"] == "gpt-4o-mini" - # Should recreate transformer instances - mock_create_transformer.assert_called_once_with( - "llm_summarize", mock_tool_transformer.config - ) - assert mock_tool._transformer_instances == [mock_instance] - - def test_skips_non_llm_summarize_transformers(self): - """Test that injection only affects llm_summarize transformers.""" - global_fast_model = "gpt-4o-mini" - - # Create transformers with different names using real Transformer instances - llm_transformer = Transformer( - name="llm_summarize", config={"input_threshold": 200} - ) - - other_transformer = Transformer( - name="custom_transformer", config={"some_param": "value"} - ) - - mock_toolset = Mock(spec=Toolset) - mock_toolset.transformers = [llm_transformer, other_transformer] - mock_toolset.tools = [] - mock_toolset.name = "test_toolset" - - manager = ToolsetManager(global_fast_model=global_fast_model) - manager._inject_fast_model_into_transformers([mock_toolset]) - - # Should inject into llm_summarize transformer - assert llm_transformer.config["global_fast_model"] == "gpt-4o-mini" - # Should NOT inject into other transformer - assert "global_fast_model" not in other_transformer.config - - def test_handles_none_global_fast_model_gracefully(self): - """Test that None global fast model is handled gracefully.""" - # Create mock toolset - mock_toolset = Mock(spec=Toolset) - mock_toolset.transformers = None - mock_toolset.tools = [] - mock_toolset.name = "test_toolset" - - manager = ToolsetManager(global_fast_model=None) - - # Should not raise an exception - manager._inject_fast_model_into_transformers([mock_toolset]) - - # Toolset configs should remain unchanged - assert mock_toolset.transformers is None - - def test_handles_empty_global_fast_model_gracefully(self): - """Test that empty global fast model is handled gracefully.""" - # Create mock toolset - mock_toolset = Mock(spec=Toolset) - mock_toolset.transformers = None - mock_toolset.tools = [] - mock_toolset.name = "test_toolset" - - manager = ToolsetManager(global_fast_model="") - - # Should not raise an exception and should not inject - manager._inject_fast_model_into_transformers([mock_toolset]) - - # Toolset configs should remain unchanged - assert mock_toolset.transformers is None - - -class TestFastModelInjectionIntegration: - """Integration tests for fast model injection functionality.""" - - def test_fast_model_injection_end_to_end(self): - """Test complete fast model injection: ToolsetManager → Transformers.""" - global_fast_model = "gpt-4o-mini" - - # Create transformers with different configurations using real Transformer instances - toolset_transformer = Transformer( - name="llm_summarize", config={"input_threshold": 500} - ) - - tool_transformer = Transformer( - name="llm_summarize", config={"input_threshold": 200} - ) - - existing_fast_model_transformer = Transformer( - name="llm_summarize", config={"fast_model": "existing-model"} - ) - - # Create tools - tool_with_transformers = Mock(spec=Tool) - tool_with_transformers.transformers = [tool_transformer] - tool_with_transformers.name = "tool1" - tool_with_transformers._transformer_instances = [] - - tool_with_existing_fast_model = Mock(spec=Tool) - tool_with_existing_fast_model.transformers = [existing_fast_model_transformer] - tool_with_existing_fast_model.name = "tool2" - tool_with_existing_fast_model._transformer_instances = [] - - # Create toolset with transformers and tools - toolset_with_transformers = Mock(spec=Toolset) - toolset_with_transformers.transformers = [toolset_transformer] - toolset_with_transformers.tools = [ - tool_with_transformers, - tool_with_existing_fast_model, - ] - toolset_with_transformers.name = "test_toolset" - - # Mock transformer recreation - mock_instance = Mock() - with patch("holmes.core.transformers.registry") as mock_registry: - mock_registry.create_transformer.return_value = mock_instance - - # Apply fast model injection - manager = ToolsetManager(global_fast_model=global_fast_model) - manager._inject_fast_model_into_transformers([toolset_with_transformers]) - - # Verify injection results: - # 1. Toolset transformer should get global_fast_model - assert toolset_transformer.config["global_fast_model"] == "gpt-4o-mini" - - # 2. Tool transformer should get global_fast_model - assert tool_transformer.config["global_fast_model"] == "gpt-4o-mini" - - # 3. Transformer with existing fast_model should remain unchanged - assert "global_fast_model" not in existing_fast_model_transformer.config - assert existing_fast_model_transformer.config["fast_model"] == "existing-model" - - # 4. Only tool transformers should trigger instance recreation - # (toolset transformers don't have _transformer_instances) - assert ( - mock_registry.create_transformer.call_count == 1 - ) # Only tool should get recreation diff --git a/tests/core/test_transformer_backwards_compatibility.py b/tests/core/test_transformer_backwards_compatibility.py deleted file mode 100644 index 41a1ec81af..0000000000 --- a/tests/core/test_transformer_backwards_compatibility.py +++ /dev/null @@ -1,283 +0,0 @@ -"""Tests for backwards compatibility of transformer configuration changes.""" - -from unittest.mock import Mock, patch -from pathlib import Path -import sys - -from holmes.config import Config -from holmes.core.toolset_manager import ToolsetManager -from holmes.core.tools import Toolset, Tool -from holmes.core.transformers import Transformer - -# Setup global namespace for Config model rebuilding -sys.modules[__name__].__dict__["Transformer"] = Transformer -Config.model_rebuild() - - -class TestBackwardsCompatibility: - """Test that existing configurations continue to work unchanged.""" - - def test_existing_config_without_transformers_works(self): - """Test that existing configs without transformers still work.""" - # Simulate an existing config file without transformers - config_data = {"model": "gpt-4o", "api_key": "test-key", "max_steps": 5} - - # Should not raise any exceptions - config = Config(**config_data) - - assert config.model == "gpt-4o" - assert config.transformers is None - assert config.max_steps == 5 - - def test_existing_toolsets_without_transformers_work(self): - """Test that existing toolsets without transformers continue to work.""" - # Create a toolset without transformers (existing behavior) - mock_tool = Mock(spec=Tool) - mock_tool.transformers = None - mock_tool.name = "test_tool" - - mock_toolset = Mock(spec=Toolset) - mock_toolset.transformers = None - mock_toolset.tools = [mock_tool] - mock_toolset.name = "test_toolset" - - # Create ToolsetManager without global fast model (existing behavior) - manager = ToolsetManager() - - # Should not raise any exceptions - manager._inject_fast_model_into_transformers([mock_toolset]) - - # Nothing should change (no injection occurs when no global_fast_model) - assert mock_toolset.transformers is None - assert mock_tool.transformers is None - - def test_existing_toolsets_with_transformers_unchanged(self): - """Test that existing toolsets with transformers get global_fast_model injection.""" - existing_tool_configs = [ - Transformer(name="llm_summarize", config={"input_threshold": 300}) - ] - existing_toolset_configs = [ - Transformer(name="llm_summarize", config={"input_threshold": 600}) - ] - - # Create tool and toolset with existing configs - mock_tool = Mock(spec=Tool) - mock_tool.transformers = existing_tool_configs - mock_tool.name = "test_tool" - mock_tool._transformer_instances = [] - - mock_toolset = Mock(spec=Toolset) - mock_toolset.transformers = existing_toolset_configs - mock_toolset.tools = [mock_tool] - mock_toolset.name = "test_toolset" - - # Apply global fast model - global_fast_model = "gpt-4o-mini" - - with patch("holmes.core.transformers.registry") as mock_registry: - mock_instance = Mock() - mock_registry.create_transformer.return_value = mock_instance - - manager = ToolsetManager(global_fast_model=global_fast_model) - manager._inject_fast_model_into_transformers([mock_toolset]) - - # Existing configs should get global_fast_model injected - assert existing_tool_configs[0].config["global_fast_model"] == "gpt-4o-mini" - assert ( - existing_toolset_configs[0].config["global_fast_model"] == "gpt-4o-mini" - ) - - # Original config values should remain - assert existing_tool_configs[0].config["input_threshold"] == 300 - assert existing_toolset_configs[0].config["input_threshold"] == 600 - - def test_config_load_from_file_backwards_compatible(self): - """Test that Config.load_from_file works with existing config files.""" - # Mock an existing config file without transformers - mock_config_content = { - "model": "gpt-4o", - "max_steps": 10, - "alertmanager_url": "http://localhost:9093", - } - - with patch("holmes.config.load_model_from_file") as mock_load: - mock_load.return_value = Config(**mock_config_content) - - with patch("pathlib.Path.exists") as mock_exists: - mock_exists.return_value = True - - # Should load successfully without transformers - config = Config.load_from_file(Path("fake_config.yaml")) - - assert config.model == "gpt-4o" - assert config.max_steps == 10 - assert config.transformers is None - - def test_config_load_from_env_backwards_compatible(self): - """Test that Config.load_from_env works as before.""" - test_env = {"MODEL": "gpt-4o", "API_KEY": "test-key", "MAX_STEPS": "8"} - - with patch.dict("os.environ", test_env): - with patch( - "holmes.config.Config._Config__get_cluster_name" - ) as mock_cluster: - mock_cluster.return_value = "test-cluster" - - config = Config.load_from_env() - - assert config.model == "gpt-4o" - assert config.max_steps == 8 - assert config.transformers is None - - def test_toolset_preprocess_tools_still_works(self): - """Test that Toolset.preprocess_tools validator still works with Transformer objects.""" - # Test the existing behavior for toolset-level transformers - values = { - "additional_instructions": "Test instructions", - "transformers": [ - Transformer(name="llm_summarize", config={"input_threshold": 500}) - ], - "tools": [ - { - "name": "test_tool", - "description": "Test tool", - # No transformers - should inherit from toolset - }, - { - "name": "tool_with_configs", - "description": "Tool with configs", - "transformers": [ - Transformer( - name="llm_summarize", config={"input_threshold": 200} - ) - ], - # Has its own configs - should not inherit - }, - ], - } - - # Import the actual validator - from holmes.core.tools import Toolset - - # Call the validator (this is what Pydantic does internally) - processed_values = Toolset.preprocess_tools(values) - - # Check that existing behavior is preserved - assert ( - processed_values["tools"][0]["additional_instructions"] - == "Test instructions" - ) - assert ( - processed_values["tools"][1]["additional_instructions"] - == "Test instructions" - ) - - # Tool without configs should inherit toolset configs (as Transformer objects) - tool0_transformers = processed_values["tools"][0]["transformers"] - assert len(tool0_transformers) == 1 - assert tool0_transformers[0].name == "llm_summarize" - assert tool0_transformers[0].config["input_threshold"] == 500 - - # Tool with configs should keep its own (as Transformer objects) - tool1_transformers = processed_values["tools"][1]["transformers"] - assert len(tool1_transformers) == 1 - assert tool1_transformers[0].name == "llm_summarize" - assert tool1_transformers[0].config["input_threshold"] == 200 - - def test_yaml_toolsets_continue_working(self): - """Test that YAML toolsets without transformers continue working.""" - # This would be a typical YAML toolset definition without transformers - yaml_toolset_data = { - "name": "test/toolset", - "description": "Test toolset", - "enabled": True, - "tools": [ - { - "name": "test_tool", - "description": "Test tool", - "command": "echo 'test'", - } - ], - } - - # Should create successfully without transformers - from holmes.core.tools import YAMLToolset - - toolset = YAMLToolset(**yaml_toolset_data) - - assert toolset.name == "test/toolset" - assert toolset.transformers is None - assert len(toolset.tools) == 1 - assert toolset.tools[0].transformers is None - - def test_python_toolsets_continue_working(self): - """Test that Python toolsets without transformers continue working.""" - # Simulate existing Python toolset without transformers - from holmes.core.tools import Toolset, Tool - - # Create a basic tool without transformers - basic_tool = Mock(spec=Tool) - basic_tool.name = "basic_tool" - basic_tool.transformers = None - - # Create toolset data without transformers - toolset_data = { - "name": "test/python_toolset", - "description": "Test Python toolset", - "tools": [basic_tool], - } - - # Should work exactly as before - class TestToolset(Toolset): - def get_example_config(self): - return {} - - toolset = TestToolset(**toolset_data) - - assert toolset.name == "test/python_toolset" - assert toolset.transformers is None - assert len(toolset.tools) == 1 - - def test_no_regression_in_tool_execution(self): - """Test that tool execution behavior hasn't regressed.""" - # Mock a tool without transformers - from holmes.core.tools import StructuredToolResult, ToolResultStatus - - class TestTool(Tool): - def _invoke(self, params): - return StructuredToolResult( - status=ToolResultStatus.SUCCESS, data="test output" - ) - - def get_parameterized_one_liner(self, params): - return "test tool execution" - - tool = TestTool(name="test_tool", description="Test tool", transformers=None) - - # Tool should execute normally without transformers - result = tool.invoke({}) - - assert result.status == ToolResultStatus.SUCCESS - assert result.data == "test output" - - def test_toolset_manager_backwards_compatible_constructor(self): - """Test that ToolsetManager constructor is backwards compatible.""" - # Old way of creating ToolsetManager (without global_fast_model) - manager = ToolsetManager( - toolsets={"test": {"enabled": True}}, - custom_toolsets=None, - custom_toolsets_from_cli=None, - ) - - # Should work fine - assert manager.toolsets == {"test": {"enabled": True}} - assert manager.global_fast_model is None - - # New way should also work - global_fast_model = "gpt-4o-mini" - manager_with_fast_model = ToolsetManager( - toolsets={"test": {"enabled": True}}, - global_fast_model=global_fast_model, - ) - - assert manager_with_fast_model.global_fast_model == global_fast_model From ab22d9d9ce4462956fc9e78509468e2e5336f66e Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Fri, 29 Aug 2025 12:25:17 +1000 Subject: [PATCH 03/11] remove local imports in llm_summarize.py --- holmes/core/transformers/llm_summarize.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/holmes/core/transformers/llm_summarize.py b/holmes/core/transformers/llm_summarize.py index 2a09612864..12e87a09ed 100644 --- a/holmes/core/transformers/llm_summarize.py +++ b/holmes/core/transformers/llm_summarize.py @@ -64,8 +64,6 @@ class LLMSummarizeTransformer(BaseTransformer): def model_post_init(self, __context) -> None: """Initialize the fast LLM instance after model validation.""" - import logging - logger = logging.getLogger(__name__) self._fast_llm = None @@ -102,8 +100,6 @@ def should_apply(self, input_text: str) -> bool: Returns: True if summarization should be applied, False otherwise """ - import logging - logger = logging.getLogger(__name__) # Skip if no fast model is configured From 626f6d2527d781084d22abe8dc65a79edfd40b77 Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Fri, 29 Aug 2025 12:34:45 +1000 Subject: [PATCH 04/11] improve unit tests --- tests/core/test_tool_transformers.py | 47 +++++++++++++++++++--------- 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/tests/core/test_tool_transformers.py b/tests/core/test_tool_transformers.py index e221e3bfb8..7347c8a760 100644 --- a/tests/core/test_tool_transformers.py +++ b/tests/core/test_tool_transformers.py @@ -200,21 +200,40 @@ def test_tool_validation_clears_invalid_transforms(self): # Invalid transformers will cause validation to fail during model creation class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> Mock: - return Mock() + def _invoke(self, params: Dict) -> StructuredToolResult: + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Test output", + ) def get_parameterized_one_liner(self, params: Dict) -> str: return "test command" - # Test creating tool with valid transformers works - valid_transforms = [Transformer(name="mock_transformer", config={})] - tool = ConcreteTestTool( - name="test_tool", - description="Test tool", - transformers=valid_transforms, - ) - - assert tool.transformers == valid_transforms + # Test creating tool with invalid transformers logs warnings but continues + invalid_transforms = [ + Transformer(name="nonexistent_transformer", config={}), + Transformer(name="mock_transformer", config={}), # This one should succeed + ] + + with patch("holmes.core.tools.logger.warning") as mock_logger_warning: + tool = ConcreteTestTool( + name="test_tool", + description="Test tool", + transformers=invalid_transforms, + ) + + # Verify that warning was logged for invalid transformer + mock_logger_warning.assert_called() + warning_calls = [ + call + for call in mock_logger_warning.call_args_list + if "nonexistent_transformer" in str(call) + ] + assert len(warning_calls) > 0 + + # Tool should still work despite invalid transformer + result = tool.invoke({}) + assert result.status == ToolResultStatus.SUCCESS def test_yaml_tool_validation(self): """Test YAMLTool transformer validation.""" @@ -745,16 +764,16 @@ def get_parameterized_one_liner(self, params: Dict) -> str: return "test command" # Create tool - initialization should handle the failure gracefully - with patch("logging.warning") as mock_warning: + with patch("holmes.core.tools.logger.warning") as mock_logger_warning: tool = ConcreteTestTool( name="test_tool", description="Test tool", transformers=transformers ) # Verify that warning was logged for failed transformer - mock_warning.assert_called() + mock_logger_warning.assert_called() warning_calls = [ call - for call in mock_warning.call_args_list + for call in mock_logger_warning.call_args_list if "nonexistent_transformer" in str(call) ] assert len(warning_calls) > 0 From 727a6ca721ad726cca4f67cecfcde4acd7e453c7 Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Fri, 29 Aug 2025 14:04:11 +1000 Subject: [PATCH 05/11] make sure transfomed data is shorter than original --- holmes/core/tools.py | 14 +- holmes/plugins/toolsets/aks-node-health.yaml | 7 + holmes/plugins/toolsets/aks.yaml | 9 + holmes/plugins/toolsets/kubernetes.yaml | 7 + holmes/plugins/toolsets/kubernetes_logs.yaml | 4 + tests/core/transformers/test_llm_summarize.py | 214 ++++++++++++++++++ 6 files changed, 254 insertions(+), 1 deletion(-) diff --git a/holmes/core/tools.py b/holmes/core/tools.py index 8751c41446..601d908d40 100644 --- a/holmes/core/tools.py +++ b/holmes/core/tools.py @@ -277,13 +277,25 @@ def _apply_transformers(self, result: StructuredToolResult) -> StructuredToolRes # Apply transformation pre_transform_size = len(transformed_data) transform_start_time = time.time() + original_data = transformed_data # Keep a copy for potential reversion transformed_data = transformer_instance.transform(transformed_data) transform_elapsed = time.time() - transform_start_time + # Check if this is llm_summarize and revert if summary is not smaller + post_transform_size = len(transformed_data) + if (transformer_instance.name == "llm_summarize" and + post_transform_size >= pre_transform_size): + # Revert to original data if summary is not smaller + transformed_data = original_data + logger.debug( + f"Transformer '{transformer_instance.name}' reverted for tool '{self.name}' " + f"(output size {post_transform_size:,} >= input size {pre_transform_size:,})" + ) + continue # Don't mark as applied + transformers_applied.append(transformer_instance.name) # Generic logging - transformers can override this with their own specific metrics - post_transform_size = len(transformed_data) size_change = post_transform_size - pre_transform_size logger.info( f"Applied transformer '{transformer_instance.name}' to tool '{self.name}' output " diff --git a/holmes/plugins/toolsets/aks-node-health.yaml b/holmes/plugins/toolsets/aks-node-health.yaml index 26be97604d..de65782684 100644 --- a/holmes/plugins/toolsets/aks-node-health.yaml +++ b/holmes/plugins/toolsets/aks-node-health.yaml @@ -28,6 +28,9 @@ toolsets: - Group healthy nodes together with aggregate counts - Highlight nodes with concerning conditions or ages - When possible, mention exact node names for follow-up investigation + - Be concise: aim for ≤ 50% of the original length; avoid repeating defaults/healthy/unchanged details + - Prefer aggregates and counts; list only outliers and actionable items + - Keep grep-friendly: include exact field names/values that matter - name: "describe_node" description: "Describes a specific node in the AKS cluster to inspect its conditions." user_description: "describe node {{ NODE_NAME }} in the AKS cluster" @@ -45,6 +48,8 @@ toolsets: - Recent events that show problems or state changes - System information relevant to troubleshooting - When possible, highlight specific condition reasons for investigation + - Strive for ≤ 50% of the original size; keep results compact and grep-friendly (one line per aggregate) + - Prioritize aggregates and actionable outliers over comprehensive details - name: "get_node_events" description: "Fetches recent events for a specific node to surface warnings and errors." user_description: "get events for node {{ NODE_NAME }}" @@ -72,6 +77,8 @@ toolsets: - Network security group, load balancer, or VM-related changes - Group similar activities and highlight time patterns - When possible, mention specific operation names and correlation IDs + - Be concise and avoid expansion: target ≤ 50% of input size; prefer counts + outliers over full listings + - Include grep-ready keys/values; avoid repeating entire objects or unchanged defaults - name: "check_top_resource_consuming_pods" description: "Checks for the top resource-consuming pods on a specific node." user_description: "get the top resource-consuming pods on node {{ NODE_NAME }}" diff --git a/holmes/plugins/toolsets/aks.yaml b/holmes/plugins/toolsets/aks.yaml index d9f4b79328..af9d188749 100644 --- a/holmes/plugins/toolsets/aks.yaml +++ b/holmes/plugins/toolsets/aks.yaml @@ -35,6 +35,9 @@ toolsets: - Security settings (RBAC, managed identity, private cluster) - Any warnings or deprecated configurations - When possible, highlight settings that might impact performance or security + - Be concise: aim for ≤ 50% of the original length; avoid repeating defaults/healthy/unchanged details + - Prefer aggregates and counts; list only outliers and actionable items + - Keep grep-friendly: include exact field names/values that matter - name: "aks_list_clusters_by_rg" description: "Lists all AKS clusters under a specific resource group. Only run this tool when you need to get all clusters in a resource group, rather than a specific one." user_description: "list AKS clusters in resource group {{ RESOURCE_GROUP_NAME }} under subscription {{ SUBSCRIPTION_ID }}" @@ -52,6 +55,8 @@ toolsets: - Key configuration differences between clusters - Any clusters in error or unusual states - When possible, group clusters by similar configurations + - Be concise and avoid expansion: target ≤ 50% of input size; prefer counts + outliers over full listings + - Include grep-ready keys/values; avoid repeating entire objects or unchanged defaults - name: "aks_list_node_pools" description: "Lists node pools in an AKS cluster" user_description: "list node pools for AKS cluster {{ CLUSTER_NAME }} under resource group {{ RESOURCE_GROUP_NAME }}" @@ -70,6 +75,8 @@ toolsets: - Taints, labels, and specialized configurations - Any node pools in error states or with scaling issues - When possible, identify resource allocation patterns + - Strive for ≤ 50% of the original size; keep results compact and grep-friendly (one line per aggregate) + - Prioritize aggregates and actionable outliers over comprehensive details - name: "aks_show_node_pool" description: "Shows details of a specific node pool in an AKS cluster" user_description: "get node pool {{ NODE_POOL_NAME }} in AKS cluster {{ CLUSTER_NAME }} under resource group {{ RESOURCE_GROUP_NAME }}" @@ -139,3 +146,5 @@ toolsets: - Any overly permissive or potentially insecure rules - Default rules vs custom rules - When possible, highlight rules that might impact AKS connectivity + - Be concise: aim for ≤ 50% of the original text; prioritize aggregates and actionable outliers + - Include grep-ready keys/values; avoid repeating entire rules or unchanged defaults diff --git a/holmes/plugins/toolsets/kubernetes.yaml b/holmes/plugins/toolsets/kubernetes.yaml index 821b441be8..df59202a0a 100644 --- a/holmes/plugins/toolsets/kubernetes.yaml +++ b/holmes/plugins/toolsets/kubernetes.yaml @@ -32,6 +32,9 @@ toolsets: - Any errors, warnings, or non-standard states - Key configuration details that could affect functionality - When possible, mention exact field names so the user can grep for specific details + - Be concise: aim for ≤ 50% of the original length; avoid repeating defaults/healthy/unchanged details + - Prefer aggregates and counts; list only outliers and actionable items + - Keep grep-friendly: include exact field names/values that matter - name: "kubectl_get_by_name" description: "Run `kubectl get --show-labels`" @@ -52,6 +55,7 @@ toolsets: - List healthy resources as aggregate descriptions - When listing unhealthy resources, also try to use aggregate descriptions when possible - When possible, mention exact keywords so the user can rerun the command with | grep and drill down + - Be concise and avoid expansion: target ≤ 50% of input size; prefer counts + outliers over full listings - name: "kubectl_get_by_kind_in_cluster" description: "Run `kubectl get -A --show-labels` to get all resources of a given type in the cluster" @@ -68,6 +72,7 @@ toolsets: - List healthy resources as aggregate descriptions - When listing unhealthy resources, also try to use aggregate descriptions when possible - When possible, mention exact keywords so the user can rerun the command with | grep and drill down on the parts they care about + - Strive for ≤ 50% of the original size; keep results compact and grep-friendly (one line per aggregate) - name: "kubectl_find_resource" description: "Run `kubectl get {{ kind }} -A --show-labels | grep {{ keyword }}` to find a resource where you know a substring of the name, IP, namespace, or labels" @@ -182,6 +187,8 @@ toolsets: - Highlight any empty results, null values, or missing data - When applicable, mention specific resource names, namespaces, or values that stand out - Organize findings in a structured way that helps with troubleshooting + - Be concise: aim for ≤ 50% of the original text; prioritize aggregates and actionable outliers + - Include grep-ready keys/values; avoid repeating entire objects or unchanged defaults - name: "kubernetes_count" user_description: "Count Kubernetes Resources: kubectl get {{kind}} --all-namespaces -o json | jq -c -r {{ jq_expr }}" diff --git a/holmes/plugins/toolsets/kubernetes_logs.yaml b/holmes/plugins/toolsets/kubernetes_logs.yaml index 82713886d4..943c00951c 100644 --- a/holmes/plugins/toolsets/kubernetes_logs.yaml +++ b/holmes/plugins/toolsets/kubernetes_logs.yaml @@ -40,6 +40,8 @@ toolsets: - Performance indicators (response times, throughput) - Group similar log entries together - When possible, mention exact error codes or keywords for easier searching + - Be concise: aim for ≤ 50% of the original text; prioritize aggregates and actionable outliers + - Include grep-ready keys/values; avoid repeating entire logs or unchanged defaults - name: "kubectl_logs_all_containers" description: "Run `kubectl logs` on all containers within a single Kubernetes pod." @@ -56,6 +58,8 @@ toolsets: - Performance indicators and resource usage patterns - Group similar log entries together by container - When possible, mention exact error codes or keywords for easier searching + - Strive for ≤ 50% of the original size; keep results compact and grep-friendly (one line per aggregate) + - Prioritize aggregates and actionable outliers over comprehensive details - name: "kubectl_container_logs" description: "Run `kubectl logs` on a single container within a Kubernetes pod. This is to get the logs of a specific container in a multi-container pod." diff --git a/tests/core/transformers/test_llm_summarize.py b/tests/core/transformers/test_llm_summarize.py index 4f6f185e8a..057d32e29f 100644 --- a/tests/core/transformers/test_llm_summarize.py +++ b/tests/core/transformers/test_llm_summarize.py @@ -469,3 +469,217 @@ def mock_llm_side_effect(model, api_key): assert "Brief summary:" in call1 assert "Detailed summary:" in call2 + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_non_expanding_behavior_integration(self, mock_default_llm): + """Test that transformer reverts to original data when summary is larger.""" + # Test case 1: Summary that expands the original data + expanding_summary = "This is a very long and detailed expansion of the original short input that makes the content much larger than it was before processing with lots of extra words" + mock_llm_expanding = self.create_mock_llm(expanding_summary) + mock_default_llm.return_value = mock_llm_expanding + + transformer = LLMSummarizeTransformer( + fast_model="gpt-4o-mini", + input_threshold=10 + ) + + original_input = "Short input data" + + # Verify that this would normally apply + assert transformer.should_apply(original_input) + + # When used in the transformation pipeline, the non-expanding logic + # is handled at the tools.py level, not in the transformer itself. + # This test verifies the transformer can produce larger output + result = transformer.transform(original_input) + assert result == expanding_summary + assert len(result) > len(original_input) + + # Test case 2: Summary that properly reduces size + reducing_summary = "Short" + mock_llm_reducing = self.create_mock_llm(reducing_summary) + mock_default_llm.return_value = mock_llm_reducing + + transformer2 = LLMSummarizeTransformer( + fast_model="gpt-4o-mini", + input_threshold=10 + ) + + longer_input = "This is a much longer input that should be summarized into something shorter" + + assert transformer2.should_apply(longer_input) + result2 = transformer2.transform(longer_input) + assert result2 == reducing_summary + assert len(result2) < len(longer_input) + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_integration_with_tools_non_expanding_logic(self, mock_default_llm): + """Test integration with the tools.py non-expanding logic.""" + from holmes.core.tools import Tool, StructuredToolResult, ToolResultStatus + from holmes.core.transformers import Transformer + + # Create a mock expanding transformer response + expanding_response = "This response is much much much longer than the original input and would not be useful as a summary since it expands rather than contracts the content size making it counterproductive" + mock_llm = self.create_mock_llm(expanding_response) + mock_default_llm.return_value = mock_llm + + # Create a concrete tool class for testing + class TestTool(Tool): + def _invoke(self, params): + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data="Original short data" + ) + + def get_parameterized_one_liner(self, params): + return "test command" + + # Create tool with llm_summarize transformer + tool = TestTool( + name="test_tool", + description="Test tool", + transformers=[Transformer(name="llm_summarize", config={"input_threshold": 5})] + ) + + # Invoke the tool - this should trigger the non-expanding logic in tools.py + result = tool.invoke({}) + + # The result should be the original data, not the expanded summary + # because tools.py should revert when llm_summarize expands the content + assert result.data == "Original short data" + assert len(result.data) < len(expanding_response) + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_non_expanding_logic_with_debug_logging(self, mock_default_llm): + """Test that explicitly verifies the non-expanding logic is triggered.""" + from holmes.core.tools import Tool, StructuredToolResult, ToolResultStatus + from holmes.core.transformers import Transformer + + # Create a mock expanding transformer response that's much larger than original + original_data = "This is some original data that is long enough to trigger the llm_summarize transformer because it exceeds the input threshold that we set to a low value so the transformer will definitely apply to this input text" # Long enough to trigger threshold + expanding_response = "This is an extremely long and detailed expansion of the original input that goes on and on with lots of additional unnecessary details that make it much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much longer than the original data, completely defeating the purpose of summarization and making the output counterproductive and should be reverted automatically" # Much longer + + mock_llm = self.create_mock_llm(expanding_response) + mock_default_llm.return_value = mock_llm + + # Create a concrete tool class for testing + class TestTool(Tool): + def _invoke(self, params): + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data=original_data # This will be the input to the transformer + ) + + def get_parameterized_one_liner(self, params): + return "test command" + + # Create tool with llm_summarize transformer (low threshold so it applies) + # Need to ensure fast_model is configured AND global_fast_model fallback + tool = TestTool( + name="test_tool", + description="Test tool", + transformers=[Transformer( + name="llm_summarize", + config={ + "input_threshold": 50, # Much lower than our input length + "fast_model": "gpt-4o-mini", # Provide fast_model + } + )] + ) + + # Patch the logger to capture debug messages + with patch("holmes.core.tools.logger.debug") as mock_debug_logger: + # Invoke the tool - this should trigger the non-expanding logic + result = tool.invoke({}) + + # Verify that the result is the original data (not the expanded response) + assert result.data == original_data + assert len(result.data) < len(expanding_response) + + # Most importantly: Check that the debug log for reversion was called + debug_calls = mock_debug_logger.call_args_list + reversion_logged = any( + "reverted" in str(call) and "llm_summarize" in str(call) + for call in debug_calls + ) + assert reversion_logged, f"Expected debug log about reversion, got: {debug_calls}" + + # Also verify the LLM was actually called (so we know the transformer ran) + mock_llm.completion.assert_called_once() + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_non_expanding_vs_successful_summarization_comparison(self, mock_default_llm): + """Test comparing expanding vs reducing scenarios to ensure logic works correctly.""" + from holmes.core.tools import Tool, StructuredToolResult, ToolResultStatus + from holmes.core.transformers import Transformer + + original_data = "This is some longer original data that should be summarized by the transformer if it works properly and produces a smaller result" + + # Create a concrete tool class for testing + class TestTool(Tool): + def _invoke(self, params): + return StructuredToolResult( + status=ToolResultStatus.SUCCESS, + data=original_data + ) + + def get_parameterized_one_liner(self, params): + return "test command" + + # Test Case 1: Expanding response (should be reverted) + expanding_response = "This is an extremely long and detailed expansion of the original input that goes on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on with lots of additional unnecessary details that make it much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much longer than the original data, completely defeating the purpose of summarization and making the output counterproductive" + mock_llm_expanding = self.create_mock_llm(expanding_response) + + tool1 = TestTool( + name="expanding_tool", + description="Test tool with expanding transformer", + transformers=[Transformer(name="llm_summarize", config={ + "input_threshold": 50, + "fast_model": "gpt-4o-mini" + })] + ) + + mock_default_llm.return_value = mock_llm_expanding + + with patch("holmes.core.tools.logger.debug") as mock_debug1: + result1 = tool1.invoke({}) + + # Should revert to original data + assert result1.data == original_data + assert len(result1.data) < len(expanding_response) + + # Should log reversion + reversion_logged = any( + "reverted" in str(call) and "llm_summarize" in str(call) + for call in mock_debug1.call_args_list + ) + assert reversion_logged, f"Expected reversion log, got: {mock_debug1.call_args_list}" + + # Test Case 2: Reducing response (should be applied) + reducing_response = "Short summary" + mock_llm_reducing = self.create_mock_llm(reducing_response) + + tool2 = TestTool( + name="reducing_tool", + description="Test tool with reducing transformer", + transformers=[Transformer(name="llm_summarize", config={ + "input_threshold": 50, + "fast_model": "gpt-4o-mini" + })] + ) + + mock_default_llm.return_value = mock_llm_reducing + + with patch("holmes.core.tools.logger.info") as mock_info: + result2 = tool2.invoke({}) + + # Should use the summarized data + assert result2.data == reducing_response + assert len(result2.data) < len(original_data) + + # Should log successful transformation + transformation_logged = any( + "Applied transformer 'llm_summarize'" in str(call) + for call in mock_info.call_args_list + ) + assert transformation_logged, f"Expected transformation log, got: {mock_info.call_args_list}" From ed3e02e46d884533510a23f81f4a83d5f7e2366b Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Fri, 29 Aug 2025 15:17:27 +1000 Subject: [PATCH 06/11] post commit check --- holmes/config.py | 3 - holmes/core/tools.py | 6 +- .../test_config_fast_model_flow.py | 70 ++++---- tests/core/test_tool_transformers.py | 6 +- tests/core/transformers/test_llm_summarize.py | 168 ++++++++++-------- 5 files changed, 129 insertions(+), 124 deletions(-) diff --git a/holmes/config.py b/holmes/config.py index 826fec6174..9e3ab5828d 100644 --- a/holmes/config.py +++ b/holmes/config.py @@ -194,7 +194,6 @@ def _load_default_robusta_config(self): "is_robusta_model": True, } - def _should_load_robusta_ai(self) -> bool: if not self.should_try_robusta_ai: return False @@ -214,7 +213,6 @@ def _should_load_robusta_ai(self) -> bool: return True - def log_useful_info(self): if self._model_list: logging.info(f"loaded models: {list(self._model_list.keys())}") @@ -252,7 +250,6 @@ def load_from_file(cls, config_file: Optional[Path], **kwargs) -> "Config": @classmethod def load_from_env(cls): - kwargs = {} for field_name in [ "model", diff --git a/holmes/core/tools.py b/holmes/core/tools.py index 601d908d40..a545ef4e82 100644 --- a/holmes/core/tools.py +++ b/holmes/core/tools.py @@ -283,8 +283,10 @@ def _apply_transformers(self, result: StructuredToolResult) -> StructuredToolRes # Check if this is llm_summarize and revert if summary is not smaller post_transform_size = len(transformed_data) - if (transformer_instance.name == "llm_summarize" and - post_transform_size >= pre_transform_size): + if ( + transformer_instance.name == "llm_summarize" + and post_transform_size >= pre_transform_size + ): # Revert to original data if summary is not smaller transformed_data = original_data logger.debug( diff --git a/tests/config_class/test_config_fast_model_flow.py b/tests/config_class/test_config_fast_model_flow.py index d33e7ac396..1394e79f2b 100644 --- a/tests/config_class/test_config_fast_model_flow.py +++ b/tests/config_class/test_config_fast_model_flow.py @@ -1,7 +1,7 @@ """ Unit tests for Config.fast_model flow to ToolsetManager. -These tests verify that the fast_model configuration flows correctly from +These tests verify that the fast_model configuration flows correctly from Config.fast_model to ToolsetManager.global_fast_model. """ @@ -20,10 +20,10 @@ def test_config_fast_model_flows_to_toolset_manager(self): """Test that Config.fast_model is passed to ToolsetManager.global_fast_model.""" # Create config with fast_model config = Config(fast_model="gpt-3.5-turbo") - + # Verify fast_model is set assert config.fast_model == "gpt-3.5-turbo" - + # Verify ToolsetManager receives the fast_model toolset_manager = config.toolset_manager assert toolset_manager.global_fast_model == "gpt-3.5-turbo" @@ -32,10 +32,10 @@ def test_config_no_fast_model_flows_to_toolset_manager(self): """Test that Config without fast_model passes None to ToolsetManager.""" # Create config without fast_model config = Config() - + # Verify fast_model is None assert config.fast_model is None - + # Verify ToolsetManager receives None toolset_manager = config.toolset_manager assert toolset_manager.global_fast_model is None @@ -43,46 +43,41 @@ def test_config_no_fast_model_flows_to_toolset_manager(self): def test_config_from_file_fast_model_flows_to_toolset_manager(self): """Test that Config loaded from file passes fast_model to ToolsetManager.""" # Create temporary config file with fast_model - config_data = { - "model": "gpt-4o", - "fast_model": "gpt-4o-mini", - "max_steps": 20 - } - - with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f: + config_data = {"model": "gpt-4o", "fast_model": "gpt-4o-mini", "max_steps": 20} + + with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f: yaml.dump(config_data, f) config_path = Path(f.name) - + try: # Mock dependencies to avoid side effects with patch("holmes.config.parse_models_file", return_value={}): config = Config.load_from_file(config_path) - + # Verify fast_model is loaded assert config.fast_model == "gpt-4o-mini" - + # Verify ToolsetManager receives the fast_model toolset_manager = config.toolset_manager assert toolset_manager.global_fast_model == "gpt-4o-mini" - + finally: config_path.unlink() # Clean up temp file def test_config_from_env_fast_model_flows_to_toolset_manager(self): """Test that Config loaded from env passes fast_model to ToolsetManager.""" - test_env = { - "MODEL": "gpt-4o", - "FAST_MODEL": "gpt-3.5-turbo" - } - + test_env = {"MODEL": "gpt-4o", "FAST_MODEL": "gpt-3.5-turbo"} + with patch.dict("os.environ", test_env): - with patch("holmes.config.Config._Config__get_cluster_name", return_value=None): + with patch( + "holmes.config.Config._Config__get_cluster_name", return_value=None + ): with patch("holmes.config.parse_models_file", return_value={}): config = Config.load_from_env() - + # Verify fast_model is loaded from env assert config.fast_model == "gpt-3.5-turbo" - + # Verify ToolsetManager receives the fast_model toolset_manager = config.toolset_manager assert toolset_manager.global_fast_model == "gpt-3.5-turbo" @@ -90,40 +85,39 @@ def test_config_from_env_fast_model_flows_to_toolset_manager(self): def test_config_cli_override_fast_model_flows_to_toolset_manager(self): """Test that CLI override of fast_model flows to ToolsetManager.""" # Create temporary config file without fast_model - config_data = { - "model": "gpt-4o", - "max_steps": 20 - } - - with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f: + config_data = {"model": "gpt-4o", "max_steps": 20} + + with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f: yaml.dump(config_data, f) config_path = Path(f.name) - + try: # Mock dependencies to avoid side effects with patch("holmes.config.parse_models_file", return_value={}): # CLI option overrides file config - config = Config.load_from_file(config_path, fast_model="claude-3-sonnet") - + config = Config.load_from_file( + config_path, fast_model="claude-3-sonnet" + ) + # Verify fast_model is set from CLI assert config.fast_model == "claude-3-sonnet" - + # Verify ToolsetManager receives the CLI fast_model toolset_manager = config.toolset_manager assert toolset_manager.global_fast_model == "claude-3-sonnet" - + finally: config_path.unlink() # Clean up temp file def test_config_toolset_manager_caching(self): """Test that toolset_manager property is cached correctly.""" config = Config(fast_model="gpt-4o-mini") - + # First access creates the toolset manager toolset_manager1 = config.toolset_manager assert toolset_manager1.global_fast_model == "gpt-4o-mini" - + # Second access returns the same instance toolset_manager2 = config.toolset_manager assert toolset_manager2 is toolset_manager1 - assert toolset_manager2.global_fast_model == "gpt-4o-mini" \ No newline at end of file + assert toolset_manager2.global_fast_model == "gpt-4o-mini" diff --git a/tests/core/test_tool_transformers.py b/tests/core/test_tool_transformers.py index 7347c8a760..78c4c2a28d 100644 --- a/tests/core/test_tool_transformers.py +++ b/tests/core/test_tool_transformers.py @@ -214,14 +214,14 @@ def get_parameterized_one_liner(self, params: Dict) -> str: Transformer(name="nonexistent_transformer", config={}), Transformer(name="mock_transformer", config={}), # This one should succeed ] - + with patch("holmes.core.tools.logger.warning") as mock_logger_warning: tool = ConcreteTestTool( name="test_tool", description="Test tool", transformers=invalid_transforms, ) - + # Verify that warning was logged for invalid transformer mock_logger_warning.assert_called() warning_calls = [ @@ -230,7 +230,7 @@ def get_parameterized_one_liner(self, params: Dict) -> str: if "nonexistent_transformer" in str(call) ] assert len(warning_calls) > 0 - + # Tool should still work despite invalid transformer result = tool.invoke({}) assert result.status == ToolResultStatus.SUCCESS diff --git a/tests/core/transformers/test_llm_summarize.py b/tests/core/transformers/test_llm_summarize.py index 057d32e29f..6d145e537e 100644 --- a/tests/core/transformers/test_llm_summarize.py +++ b/tests/core/transformers/test_llm_summarize.py @@ -477,209 +477,221 @@ def test_non_expanding_behavior_integration(self, mock_default_llm): expanding_summary = "This is a very long and detailed expansion of the original short input that makes the content much larger than it was before processing with lots of extra words" mock_llm_expanding = self.create_mock_llm(expanding_summary) mock_default_llm.return_value = mock_llm_expanding - + transformer = LLMSummarizeTransformer( - fast_model="gpt-4o-mini", - input_threshold=10 + fast_model="gpt-4o-mini", input_threshold=10 ) - + original_input = "Short input data" - + # Verify that this would normally apply assert transformer.should_apply(original_input) - + # When used in the transformation pipeline, the non-expanding logic # is handled at the tools.py level, not in the transformer itself. # This test verifies the transformer can produce larger output result = transformer.transform(original_input) assert result == expanding_summary assert len(result) > len(original_input) - + # Test case 2: Summary that properly reduces size reducing_summary = "Short" mock_llm_reducing = self.create_mock_llm(reducing_summary) mock_default_llm.return_value = mock_llm_reducing - + transformer2 = LLMSummarizeTransformer( - fast_model="gpt-4o-mini", - input_threshold=10 + fast_model="gpt-4o-mini", input_threshold=10 ) - + longer_input = "This is a much longer input that should be summarized into something shorter" - + assert transformer2.should_apply(longer_input) result2 = transformer2.transform(longer_input) assert result2 == reducing_summary assert len(result2) < len(longer_input) - - @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") def test_integration_with_tools_non_expanding_logic(self, mock_default_llm): """Test integration with the tools.py non-expanding logic.""" from holmes.core.tools import Tool, StructuredToolResult, ToolResultStatus from holmes.core.transformers import Transformer - + # Create a mock expanding transformer response expanding_response = "This response is much much much longer than the original input and would not be useful as a summary since it expands rather than contracts the content size making it counterproductive" mock_llm = self.create_mock_llm(expanding_response) mock_default_llm.return_value = mock_llm - + # Create a concrete tool class for testing class TestTool(Tool): def _invoke(self, params): return StructuredToolResult( - status=ToolResultStatus.SUCCESS, - data="Original short data" + status=ToolResultStatus.SUCCESS, data="Original short data" ) - + def get_parameterized_one_liner(self, params): return "test command" - + # Create tool with llm_summarize transformer tool = TestTool( name="test_tool", - description="Test tool", - transformers=[Transformer(name="llm_summarize", config={"input_threshold": 5})] + description="Test tool", + transformers=[ + Transformer(name="llm_summarize", config={"input_threshold": 5}) + ], ) - + # Invoke the tool - this should trigger the non-expanding logic in tools.py result = tool.invoke({}) - + # The result should be the original data, not the expanded summary # because tools.py should revert when llm_summarize expands the content assert result.data == "Original short data" assert len(result.data) < len(expanding_response) - @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") def test_non_expanding_logic_with_debug_logging(self, mock_default_llm): """Test that explicitly verifies the non-expanding logic is triggered.""" from holmes.core.tools import Tool, StructuredToolResult, ToolResultStatus from holmes.core.transformers import Transformer - + # Create a mock expanding transformer response that's much larger than original original_data = "This is some original data that is long enough to trigger the llm_summarize transformer because it exceeds the input threshold that we set to a low value so the transformer will definitely apply to this input text" # Long enough to trigger threshold expanding_response = "This is an extremely long and detailed expansion of the original input that goes on and on with lots of additional unnecessary details that make it much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much longer than the original data, completely defeating the purpose of summarization and making the output counterproductive and should be reverted automatically" # Much longer - + mock_llm = self.create_mock_llm(expanding_response) mock_default_llm.return_value = mock_llm - + # Create a concrete tool class for testing class TestTool(Tool): def _invoke(self, params): return StructuredToolResult( status=ToolResultStatus.SUCCESS, - data=original_data # This will be the input to the transformer + data=original_data, # This will be the input to the transformer ) - + def get_parameterized_one_liner(self, params): return "test command" - + # Create tool with llm_summarize transformer (low threshold so it applies) # Need to ensure fast_model is configured AND global_fast_model fallback tool = TestTool( name="test_tool", - description="Test tool", - transformers=[Transformer( - name="llm_summarize", - config={ - "input_threshold": 50, # Much lower than our input length - "fast_model": "gpt-4o-mini", # Provide fast_model - } - )] + description="Test tool", + transformers=[ + Transformer( + name="llm_summarize", + config={ + "input_threshold": 50, # Much lower than our input length + "fast_model": "gpt-4o-mini", # Provide fast_model + }, + ) + ], ) - + # Patch the logger to capture debug messages with patch("holmes.core.tools.logger.debug") as mock_debug_logger: # Invoke the tool - this should trigger the non-expanding logic result = tool.invoke({}) - + # Verify that the result is the original data (not the expanded response) assert result.data == original_data assert len(result.data) < len(expanding_response) - + # Most importantly: Check that the debug log for reversion was called debug_calls = mock_debug_logger.call_args_list reversion_logged = any( - "reverted" in str(call) and "llm_summarize" in str(call) + "reverted" in str(call) and "llm_summarize" in str(call) for call in debug_calls ) - assert reversion_logged, f"Expected debug log about reversion, got: {debug_calls}" - + assert ( + reversion_logged + ), f"Expected debug log about reversion, got: {debug_calls}" + # Also verify the LLM was actually called (so we know the transformer ran) mock_llm.completion.assert_called_once() - - @patch("holmes.core.transformers.llm_summarize.DefaultLLM") - def test_non_expanding_vs_successful_summarization_comparison(self, mock_default_llm): + + @patch("holmes.core.transformers.llm_summarize.DefaultLLM") + def test_non_expanding_vs_successful_summarization_comparison( + self, mock_default_llm + ): """Test comparing expanding vs reducing scenarios to ensure logic works correctly.""" from holmes.core.tools import Tool, StructuredToolResult, ToolResultStatus from holmes.core.transformers import Transformer - + original_data = "This is some longer original data that should be summarized by the transformer if it works properly and produces a smaller result" - + # Create a concrete tool class for testing class TestTool(Tool): def _invoke(self, params): return StructuredToolResult( - status=ToolResultStatus.SUCCESS, - data=original_data + status=ToolResultStatus.SUCCESS, data=original_data ) - + def get_parameterized_one_liner(self, params): return "test command" - + # Test Case 1: Expanding response (should be reverted) expanding_response = "This is an extremely long and detailed expansion of the original input that goes on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on with lots of additional unnecessary details that make it much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much longer than the original data, completely defeating the purpose of summarization and making the output counterproductive" mock_llm_expanding = self.create_mock_llm(expanding_response) - + tool1 = TestTool( name="expanding_tool", description="Test tool with expanding transformer", - transformers=[Transformer(name="llm_summarize", config={ - "input_threshold": 50, - "fast_model": "gpt-4o-mini" - })] + transformers=[ + Transformer( + name="llm_summarize", + config={"input_threshold": 50, "fast_model": "gpt-4o-mini"}, + ) + ], ) - + mock_default_llm.return_value = mock_llm_expanding - + with patch("holmes.core.tools.logger.debug") as mock_debug1: result1 = tool1.invoke({}) - + # Should revert to original data assert result1.data == original_data assert len(result1.data) < len(expanding_response) - + # Should log reversion reversion_logged = any( "reverted" in str(call) and "llm_summarize" in str(call) for call in mock_debug1.call_args_list ) - assert reversion_logged, f"Expected reversion log, got: {mock_debug1.call_args_list}" - - # Test Case 2: Reducing response (should be applied) + assert ( + reversion_logged + ), f"Expected reversion log, got: {mock_debug1.call_args_list}" + + # Test Case 2: Reducing response (should be applied) reducing_response = "Short summary" mock_llm_reducing = self.create_mock_llm(reducing_response) - + tool2 = TestTool( - name="reducing_tool", + name="reducing_tool", description="Test tool with reducing transformer", - transformers=[Transformer(name="llm_summarize", config={ - "input_threshold": 50, - "fast_model": "gpt-4o-mini" - })] + transformers=[ + Transformer( + name="llm_summarize", + config={"input_threshold": 50, "fast_model": "gpt-4o-mini"}, + ) + ], ) - + mock_default_llm.return_value = mock_llm_reducing - + with patch("holmes.core.tools.logger.info") as mock_info: result2 = tool2.invoke({}) - + # Should use the summarized data assert result2.data == reducing_response assert len(result2.data) < len(original_data) - + # Should log successful transformation transformation_logged = any( "Applied transformer 'llm_summarize'" in str(call) - for call in mock_info.call_args_list + for call in mock_info.call_args_list ) - assert transformation_logged, f"Expected transformation log, got: {mock_info.call_args_list}" + assert ( + transformation_logged + ), f"Expected transformation log, got: {mock_info.call_args_list}" From e0ac35af5f26e46bed985e81f11a9a76769fc190 Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Fri, 29 Aug 2025 15:52:28 +1000 Subject: [PATCH 07/11] resolve ai comments --- docs/transformers.md | 24 +++-- .../test_kubernetes_transformer_execution.py | 100 ++++++++++++++---- 2 files changed, 94 insertions(+), 30 deletions(-) diff --git a/docs/transformers.md b/docs/transformers.md index bebc6a954a..281abc872e 100644 --- a/docs/transformers.md +++ b/docs/transformers.md @@ -40,14 +40,16 @@ Tools can declare transformers in their definitions: description: "Get all resources of a type in a namespace" command: "kubectl get --show-labels -o wide {{ kind }} -n {{ namespace }}" transformers: - - llm_summarize: {} + - name: llm_summarize + config: {} # Custom threshold and prompt - name: "kubectl_describe" description: "Describe a Kubernetes resource" command: "kubectl describe {{ kind }} {{ name }}{% if namespace %} -n {{ namespace }}{% endif %}" transformers: - - llm_summarize: + - name: llm_summarize + config: input_threshold: 1000 prompt: | Summarize this kubectl describe output focusing on: @@ -61,6 +63,8 @@ Tools can declare transformers in their definitions: #### Python Toolsets ```python +from holmes.core.transformers import Transformer + class PrometheusToolset(Toolset): def __init__(self): super().__init__( @@ -69,18 +73,19 @@ class PrometheusToolset(Toolset): ListPrometheusRules( toolset=self, transformers=[ - {"llm_summarize": {}} # use default config + Transformer(name="llm_summarize", config={}) # use default config ] ), ListAvailableMetrics( toolset=self, transformers=[ - { - "llm_summarize": { + Transformer( + name="llm_summarize", + config={ "input_threshold": 800, "prompt": "Summarize the available Prometheus metrics, grouping similar metrics and highlighting any unusual patterns." } - } + ) ] ), ] @@ -244,7 +249,8 @@ Add transformer configuration to tools that generate large outputs: - name: "my_large_output_tool" command: "some command that produces lots of output" transformers: - - llm_summarize: + - name: llm_summarize + config: input_threshold: 1000 prompt: "Custom prompt for this tool's output type" ``` @@ -254,6 +260,8 @@ Add transformer configuration to tools that generate large outputs: Update tool constructors to accept transformer configurations: ```python +from holmes.core.transformers import Transformer + # Before MyTool(toolset=self) @@ -261,7 +269,7 @@ MyTool(toolset=self) MyTool( toolset=self, transformers=[ - {"llm_summarize": {"input_threshold": 800}} + Transformer(name="llm_summarize", config={"input_threshold": 800}) ] ) ``` diff --git a/tests/integration/test_kubernetes_transformer_execution.py b/tests/integration/test_kubernetes_transformer_execution.py index 5844c12400..608014d58f 100644 --- a/tests/integration/test_kubernetes_transformer_execution.py +++ b/tests/integration/test_kubernetes_transformer_execution.py @@ -11,18 +11,43 @@ from holmes.core.transformers import registry from holmes.core.transformers.base import BaseTransformer +from pydantic import Field + class MockSummarizeTransformer(BaseTransformer): """Mock LLM summarize transformer for testing.""" - input_threshold: int = 1000 # default value - prompt: str = "Default summarization prompt" + # Pydantic fields with validation + input_threshold: int = Field( + default=1000, ge=0, description="Minimum input length to trigger summarization" + ) + prompt: str = Field( + default="Default summarization prompt", description="Custom prompt for testing" + ) def transform(self, input_text: str) -> str: - # Simulate summarization by truncating and adding prefix - if len(input_text) > 100: - return f"SUMMARIZED: {input_text[:50]}... [Original length: {len(input_text)} chars]" - return f"SUMMARIZED: {input_text}" + # Simulate summarization by always reducing the text size + # Include original length info that tests expect + original_length = len(input_text) + length_info = f"[Original length: {original_length} chars]" + + if len(input_text) <= 50: + # For short inputs, create a minimal summary + return f"SUMMARIZED: Short content {length_info}" + + # For longer inputs, reduce to approximately 60% of original size + target_length = int(len(input_text) * 0.6) + prefix = "SUMMARIZED: " + suffix = f"... {length_info}" + + # Calculate how much content we can include + available_length = target_length - len(prefix) - len(suffix) + + if available_length < 10: + # If we don't have much space, just use a short summary + return f"{prefix}Content truncated {length_info}" + + return f"{prefix}{input_text[:available_length]}...{length_info}" def should_apply(self, input_text: str) -> bool: return len(input_text) >= self.input_threshold @@ -37,20 +62,30 @@ class TestKubernetesTransformerExecution: def setup_method(self): """Set up test fixtures.""" - # Clean up any existing registrations first - for transformer_name in ["llm_summarize", "MockSummarizeTransformer"]: - if registry.is_registered(transformer_name): - registry.unregister(transformer_name) + # Save original transformer registration if it exists + self.original_llm_summarize = None + if registry.is_registered("llm_summarize"): + self.original_llm_summarize = registry._transformers["llm_summarize"] + registry.unregister("llm_summarize") + + # Clean up any mock registrations + if registry.is_registered("MockSummarizeTransformer"): + registry.unregister("MockSummarizeTransformer") - # Register mock transformer with a different name to avoid conflicts + # Register mock transformer registry.register(MockSummarizeTransformer) def teardown_method(self): """Clean up test fixtures.""" # Unregister mock transformer - for transformer_name in ["llm_summarize", "MockSummarizeTransformer"]: - if registry.is_registered(transformer_name): - registry.unregister(transformer_name) + if registry.is_registered("llm_summarize"): + registry.unregister("llm_summarize") + if registry.is_registered("MockSummarizeTransformer"): + registry.unregister("MockSummarizeTransformer") + + # Restore original transformer if it existed + if self.original_llm_summarize is not None: + registry._transformers["llm_summarize"] = self.original_llm_summarize def test_kubectl_describe_with_large_output(self): """Test kubectl_describe applies transformer for large output.""" @@ -435,6 +470,12 @@ def name(self) -> str: # Mock subprocess execution with output that will trigger both transformers test_output = "This is a longer test output that should trigger both transformers in sequence" + + # Re-register mock transformer after toolset loading (imports may have restored original) + if registry.is_registered("llm_summarize"): + registry.unregister("llm_summarize") + registry.register(MockSummarizeTransformer) + with patch.object( tool, "_YAMLTool__execute_subprocess" ) as mock_subprocess: @@ -462,20 +503,30 @@ class TestTransformerPerformanceMetrics: def setup_method(self): """Set up test fixtures.""" - # Clean up any existing registrations first - for transformer_name in ["llm_summarize", "MockSummarizeTransformer"]: - if registry.is_registered(transformer_name): - registry.unregister(transformer_name) + # Save original transformer registration if it exists + self.original_llm_summarize = None + if registry.is_registered("llm_summarize"): + self.original_llm_summarize = registry._transformers["llm_summarize"] + registry.unregister("llm_summarize") - # Register mock transformer with a different name to avoid conflicts + # Clean up any mock registrations + if registry.is_registered("MockSummarizeTransformer"): + registry.unregister("MockSummarizeTransformer") + + # Register mock transformer registry.register(MockSummarizeTransformer) def teardown_method(self): """Clean up test fixtures.""" # Unregister mock transformer - for transformer_name in ["llm_summarize", "MockSummarizeTransformer"]: - if registry.is_registered(transformer_name): - registry.unregister(transformer_name) + if registry.is_registered("llm_summarize"): + registry.unregister("llm_summarize") + if registry.is_registered("MockSummarizeTransformer"): + registry.unregister("MockSummarizeTransformer") + + # Restore original transformer if it existed + if self.original_llm_summarize is not None: + registry._transformers["llm_summarize"] = self.original_llm_summarize def test_transformer_performance_logging(self): """Test that transformer execution metrics are logged.""" @@ -507,6 +558,11 @@ def test_transformer_performance_logging(self): toolset = toolsets[0] tool = toolset.tools[0] + # Re-register mock transformer after toolset loading (imports may have restored original) + if registry.is_registered("llm_summarize"): + registry.unregister("llm_summarize") + registry.register(MockSummarizeTransformer) + # Mock subprocess execution test_output = "This is a test output that should trigger the transformer and performance logging" with patch.object(tool, "_YAMLTool__execute_subprocess") as mock_subprocess: From 350d7ef02af3ea0992d4b3877c9eb7f56e5a9984 Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Fri, 29 Aug 2025 16:12:20 +1000 Subject: [PATCH 08/11] fix ut --- tests/core/transformers/test_llm_summarize.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/core/transformers/test_llm_summarize.py b/tests/core/transformers/test_llm_summarize.py index 6d145e537e..f5effb963b 100644 --- a/tests/core/transformers/test_llm_summarize.py +++ b/tests/core/transformers/test_llm_summarize.py @@ -317,6 +317,7 @@ def create_mock_llm(self, response_content: str = "Summarized content"): mock_choice = Mock() mock_message = Mock() + # Properly configure the mock message.content to return a string that supports .strip() mock_message.content = response_content mock_choice.message = mock_message mock_response.choices = [mock_choice] @@ -634,6 +635,9 @@ def get_parameterized_one_liner(self, params): expanding_response = "This is an extremely long and detailed expansion of the original input that goes on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on with lots of additional unnecessary details that make it much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much much longer than the original data, completely defeating the purpose of summarization and making the output counterproductive" mock_llm_expanding = self.create_mock_llm(expanding_response) + # Set up mock BEFORE creating the tool + mock_default_llm.return_value = mock_llm_expanding + tool1 = TestTool( name="expanding_tool", description="Test tool with expanding transformer", @@ -645,8 +649,6 @@ def get_parameterized_one_liner(self, params): ], ) - mock_default_llm.return_value = mock_llm_expanding - with patch("holmes.core.tools.logger.debug") as mock_debug1: result1 = tool1.invoke({}) @@ -667,6 +669,9 @@ def get_parameterized_one_liner(self, params): reducing_response = "Short summary" mock_llm_reducing = self.create_mock_llm(reducing_response) + # Set up mock BEFORE creating the second tool + mock_default_llm.return_value = mock_llm_reducing + tool2 = TestTool( name="reducing_tool", description="Test tool with reducing transformer", @@ -678,8 +683,6 @@ def get_parameterized_one_liner(self, params): ], ) - mock_default_llm.return_value = mock_llm_reducing - with patch("holmes.core.tools.logger.info") as mock_info: result2 = tool2.invoke({}) From 4e3cd4276f9408a521fa75f43c0edbd815e43356 Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Fri, 29 Aug 2025 16:38:56 +1000 Subject: [PATCH 09/11] resolve ai comments --- docs/transformers.md | 1 + holmes/core/transformers/llm_summarize.py | 8 ++++---- tests/core/transformers/test_llm_summarize.py | 12 ++++++++++-- .../test_kubernetes_transformer_execution.py | 16 +++++++--------- 4 files changed, 22 insertions(+), 15 deletions(-) diff --git a/docs/transformers.md b/docs/transformers.md index 281abc872e..27724b5cde 100644 --- a/docs/transformers.md +++ b/docs/transformers.md @@ -106,6 +106,7 @@ The `llm_summarize` transformer is the primary transformer available in HolmesGP 2. **Fast Model Required**: Skips summarization if no `--fast-model` is configured 3. **Context Preservation**: Maintains essential debugging information while reducing size 4. **Error Handling**: Falls back to original output if summarization fails +5. **Non-Expanding Fallback**: If the generated summary is not smaller than the original output, preserves the original output to prevent expansion ### Configuration Options diff --git a/holmes/core/transformers/llm_summarize.py b/holmes/core/transformers/llm_summarize.py index 12e87a09ed..742e91b024 100644 --- a/holmes/core/transformers/llm_summarize.py +++ b/holmes/core/transformers/llm_summarize.py @@ -4,7 +4,7 @@ import logging from typing import Optional, ClassVar -from pydantic import Field, PrivateAttr +from pydantic import Field, PrivateAttr, StrictStr from .base import BaseTransformer, TransformerError from ..llm import DefaultLLM, LLM @@ -39,17 +39,17 @@ class LLMSummarizeTransformer(BaseTransformer): input_threshold: int = Field( default=1000, ge=0, description="Minimum input length to trigger summarization" ) - prompt: Optional[str] = Field( + prompt: Optional[StrictStr] = Field( default=None, min_length=1, description="Custom prompt template for summarization", ) - fast_model: Optional[str] = Field( + fast_model: Optional[StrictStr] = Field( default=None, min_length=1, description="Fast model name for summarization (e.g., 'gpt-4o-mini')", ) - global_fast_model: Optional[str] = Field( + global_fast_model: Optional[StrictStr] = Field( default=None, min_length=1, description="Global fast model name fallback when fast_model is not set", diff --git a/tests/core/transformers/test_llm_summarize.py b/tests/core/transformers/test_llm_summarize.py index f5effb963b..95f41c5e61 100644 --- a/tests/core/transformers/test_llm_summarize.py +++ b/tests/core/transformers/test_llm_summarize.py @@ -473,7 +473,12 @@ def mock_llm_side_effect(model, api_key): @patch("holmes.core.transformers.llm_summarize.DefaultLLM") def test_non_expanding_behavior_integration(self, mock_default_llm): - """Test that transformer reverts to original data when summary is larger.""" + """Test that transformer may produce longer output and that expansion behavior is handled. + + This test verifies that the transformer itself can produce summaries that are longer + than the original input. The non-expansion/reversion logic (preventing output that + is larger than input) is implemented at the tools.py level, not in the transformer. + """ # Test case 1: Summary that expands the original data expanding_summary = "This is a very long and detailed expansion of the original short input that makes the content much larger than it was before processing with lots of extra words" mock_llm_expanding = self.create_mock_llm(expanding_summary) @@ -537,7 +542,10 @@ def get_parameterized_one_liner(self, params): name="test_tool", description="Test tool", transformers=[ - Transformer(name="llm_summarize", config={"input_threshold": 5}) + Transformer( + name="llm_summarize", + config={"input_threshold": 5, "fast_model": "fast"}, + ) ], ) diff --git a/tests/integration/test_kubernetes_transformer_execution.py b/tests/integration/test_kubernetes_transformer_execution.py index 608014d58f..fb897f5657 100644 --- a/tests/integration/test_kubernetes_transformer_execution.py +++ b/tests/integration/test_kubernetes_transformer_execution.py @@ -85,7 +85,7 @@ def teardown_method(self): # Restore original transformer if it existed if self.original_llm_summarize is not None: - registry._transformers["llm_summarize"] = self.original_llm_summarize + registry.register(self.original_llm_summarize) def test_kubectl_describe_with_large_output(self): """Test kubectl_describe applies transformer for large output.""" @@ -503,13 +503,12 @@ class TestTransformerPerformanceMetrics: def setup_method(self): """Set up test fixtures.""" - # Save original transformer registration if it exists - self.original_llm_summarize = None + # Track whether llm_summarize was originally registered for restoration + self.llm_summarize_was_registered = registry.is_registered("llm_summarize") + + # Clean up existing registrations if registry.is_registered("llm_summarize"): - self.original_llm_summarize = registry._transformers["llm_summarize"] registry.unregister("llm_summarize") - - # Clean up any mock registrations if registry.is_registered("MockSummarizeTransformer"): registry.unregister("MockSummarizeTransformer") @@ -524,9 +523,8 @@ def teardown_method(self): if registry.is_registered("MockSummarizeTransformer"): registry.unregister("MockSummarizeTransformer") - # Restore original transformer if it existed - if self.original_llm_summarize is not None: - registry._transformers["llm_summarize"] = self.original_llm_summarize + # Note: Original transformer restoration is not possible without accessing private registry attributes. + # Test isolation is maintained by cleaning up our mock registrations. def test_transformer_performance_logging(self): """Test that transformer execution metrics are logged.""" From f59e660cefa59b0ad19219441e5b8845b28cb7e2 Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Wed, 3 Sep 2025 10:56:29 +1000 Subject: [PATCH 10/11] pre commit check --- tests/core/test_tool_transformers.py | 70 ++++++++++++++----- .../test_tool_execution_pipeline.py | 4 +- 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/tests/core/test_tool_transformers.py b/tests/core/test_tool_transformers.py index 78c4c2a28d..b82f82a17f 100644 --- a/tests/core/test_tool_transformers.py +++ b/tests/core/test_tool_transformers.py @@ -46,7 +46,7 @@ def test_tool_with_transforms(self): # Create a concrete tool for testing class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> Mock: + def _invoke(self, params: Dict, user_approved: bool = False) -> Mock: return Mock() def get_parameterized_one_liner(self, params: Dict) -> str: @@ -79,7 +79,7 @@ def test_tool_without_transforms(self): """Test that tools work without transformers field.""" class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> Mock: + def _invoke(self, params: Dict, user_approved: bool = False) -> Mock: return Mock() def get_parameterized_one_liner(self, params: Dict) -> str: @@ -182,7 +182,7 @@ def test_tool_validation_success(self): transforms = [Transformer(name="mock_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> Mock: + def _invoke(self, params: Dict, user_approved: bool = False) -> Mock: return Mock() def get_parameterized_one_liner(self, params: Dict) -> str: @@ -200,7 +200,9 @@ def test_tool_validation_clears_invalid_transforms(self): # Invalid transformers will cause validation to fail during model creation class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output", @@ -317,7 +319,9 @@ def test_successful_tool_execution_with_transformers(self): transforms = [Transformer(name="mock_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="This is a long test output that should be transformed", @@ -343,7 +347,9 @@ def test_tool_execution_skips_transformers_on_error(self): transforms = [Transformer(name="mock_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.ERROR, error="Tool execution failed", @@ -369,7 +375,9 @@ def test_tool_execution_skips_transformers_on_empty_data(self): transforms = [Transformer(name="mock_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult(status=ToolResultStatus.NO_DATA, data="") def get_parameterized_one_liner(self, params: Dict) -> str: @@ -406,7 +414,9 @@ def name(self) -> str: transforms = [Transformer(name="failing_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output" ) @@ -460,7 +470,9 @@ def name(self) -> str: ] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Original text that should be transformed twice", @@ -508,7 +520,9 @@ def name(self) -> str: transforms = [Transformer(name="conditional_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: data = params.get("data", "short") return StructuredToolResult( status=ToolResultStatus.SUCCESS, data=data @@ -547,7 +561,9 @@ def test_transformer_preserves_original_result_structure(self): transforms = [Transformer(name="mock_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output to transform", @@ -582,7 +598,9 @@ def test_performance_metrics_logging(self): transforms = [Transformer(name="mock_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output that will be transformed for performance measurement", @@ -614,7 +632,9 @@ def test_tool_without_transformers_unchanged(self): """Test that tools without transformers work exactly as before.""" class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output without transformation", @@ -656,7 +676,9 @@ def test_transformer_instances_cached_during_initialization(self): transformers = [Transformer(name="mock_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output for transformation", @@ -685,7 +707,9 @@ def test_transformer_instances_reused_across_multiple_calls(self): transformers = [Transformer(name="mock_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output for transformation", @@ -720,7 +744,9 @@ def test_model_post_init_with_no_transformers(self): """Test that model_post_init handles tools with no transformers correctly.""" class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output without transformers", @@ -754,7 +780,9 @@ def test_transformer_initialization_failure_handling(self): ] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output for transformation", @@ -793,7 +821,9 @@ def test_transformer_initialization_empty_transformers_list(self): transformers = [] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output", @@ -819,7 +849,9 @@ def test_performance_optimization_prevents_recreation(self): transformers = [Transformer(name="mock_transformer", config={})] class ConcreteTestTool(Tool): - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Test output for transformation", diff --git a/tests/integration/test_tool_execution_pipeline.py b/tests/integration/test_tool_execution_pipeline.py index c3d0c77a1e..8eb9be8f51 100644 --- a/tests/integration/test_tool_execution_pipeline.py +++ b/tests/integration/test_tool_execution_pipeline.py @@ -104,7 +104,9 @@ def test_python_tool_with_multiple_transformers_integration(self): class LogReaderTool(Tool): """Simulates a tool that reads large log files.""" - def _invoke(self, params: Dict) -> StructuredToolResult: + def _invoke( + self, params: Dict, user_approved: bool = False + ) -> StructuredToolResult: # Simulate reading a large log file log_entries = [ "2024-01-01 10:00:00 INFO Starting application", From 74c277f92b88c09264fdff420a04511b4b24f483 Mon Sep 17 00:00:00 2001 From: Qi Ni Date: Wed, 3 Sep 2025 11:40:46 +1000 Subject: [PATCH 11/11] fix ut --- tests/core/transformers/test_llm_summarize.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/core/transformers/test_llm_summarize.py b/tests/core/transformers/test_llm_summarize.py index 95f41c5e61..e803bb32fa 100644 --- a/tests/core/transformers/test_llm_summarize.py +++ b/tests/core/transformers/test_llm_summarize.py @@ -529,7 +529,7 @@ def test_integration_with_tools_non_expanding_logic(self, mock_default_llm): # Create a concrete tool class for testing class TestTool(Tool): - def _invoke(self, params): + def _invoke(self, params, user_approved: bool = False): return StructuredToolResult( status=ToolResultStatus.SUCCESS, data="Original short data" ) @@ -572,7 +572,7 @@ def test_non_expanding_logic_with_debug_logging(self, mock_default_llm): # Create a concrete tool class for testing class TestTool(Tool): - def _invoke(self, params): + def _invoke(self, params, user_approved: bool = False): return StructuredToolResult( status=ToolResultStatus.SUCCESS, data=original_data, # This will be the input to the transformer @@ -631,7 +631,7 @@ def test_non_expanding_vs_successful_summarization_comparison( # Create a concrete tool class for testing class TestTool(Tool): - def _invoke(self, params): + def _invoke(self, params, user_approved: bool = False): return StructuredToolResult( status=ToolResultStatus.SUCCESS, data=original_data )