π OpenHands: AI-Driven Development
Remove legacy condenser_config and model_routing_config (#14203)
Tim O'Farrellf94608549ec9
diff --git a/openhands/core/config/__init__.py b/openhands/core/config/__init__.pyindex dd8fb92c86..7ffc658269 100644--- a/openhands/core/config/__init__.py+++ b/openhands/core/config/__init__.py@@ -10,7 +10,6 @@ from openhands.core.config.config_utils import (from openhands.core.config.extended_config import ExtendedConfigfrom openhands.core.config.llm_config import LLMConfigfrom openhands.core.config.mcp_config import MCPConfig-from openhands.core.config.model_routing_config import ModelRoutingConfigfrom openhands.core.config.openhands_config import OpenHandsConfigfrom openhands.core.config.sandbox_config import SandboxConfigfrom openhands.core.config.security_config import SecurityConfig@@ -18,8 +17,6 @@ from openhands.core.config.utils import (finalize_config,get_agent_config_arg,get_llm_config_arg,- get_llms_for_routing_config,- get_model_routing_config_arg,load_from_env,load_from_toml,load_openhands_config,@@ -36,7 +33,6 @@ __all__ = ['LLMConfig','SandboxConfig','SecurityConfig',- 'ModelRoutingConfig','ExtendedConfig','load_openhands_config','load_from_env',@@ -48,6 +44,4 @@ __all__ = ['get_evaluation_parser','parse_arguments','setup_config_from_args',- 'get_model_routing_config_arg',- 'get_llms_for_routing_config',]diff --git a/openhands/core/config/agent_config.py b/openhands/core/config/agent_config.pyindex 09034a6a76..03124dcac7 100644--- a/openhands/core/config/agent_config.py+++ b/openhands/core/config/agent_config.py@@ -9,12 +9,7 @@ from __future__ import annotationsfrom pydantic import BaseModel, ConfigDict, Field, ValidationError-from openhands.core.config.condenser_config import (- CondenserConfig,- ConversationWindowCondenserConfig,-)from openhands.core.config.extended_config import ExtendedConfig-from openhands.core.config.model_routing_config import ModelRoutingConfigfrom openhands.core.logger import openhands_logger as logger@@ -59,21 +54,14 @@ class AgentConfig(BaseModel):"""Whether to enable plan mode, which uses the long horizon system message and add the new tool - task_tracker - for planning, tracking and executing complex tasks."""enable_stuck_detection: bool = Field(default=True)"""Whether to enable stuck/loop detection. When disabled, the agent will not automatically detect and recover from loops."""- condenser: CondenserConfig = Field(- # The default condenser is set to the conversation window condenser -- if- # we use NoOp and the conversation hits the LLM context length limit,- # the agent will generate a condensation request which will never be- # handled.- default_factory=lambda: ConversationWindowCondenserConfig()- )- model_routing: ModelRoutingConfig = Field(default_factory=ModelRoutingConfig)- """Model routing configuration settings."""extended: ExtendedConfig = Field(default_factory=lambda: ExtendedConfig({}))"""Extended configuration for the agent."""runtime: str | None = Field(default=None)"""Runtime type (e.g., 'docker', 'local', 'cli') used for runtime-specific tool behavior."""- model_config = ConfigDict(extra='forbid')+ # Allow extra fields for backwards compatibility with old config.toml files+ # that may have condenser or model_routing sections+ model_config = ConfigDict(extra='ignore')@propertydef resolved_system_prompt_filename(self) -> str:diff --git a/openhands/core/config/condenser_config.py b/openhands/core/config/condenser_config.pydeleted file mode 100644index 912c57331b..0000000000--- a/openhands/core/config/condenser_config.py+++ /dev/null@@ -1,319 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from __future__ import annotations--from typing import Literal, cast--from pydantic import BaseModel, ConfigDict, Field, ValidationError--from openhands.core import logger-from openhands.core.config.llm_config import LLMConfig---class NoOpCondenserConfig(BaseModel):- """Configuration for NoOpCondenser."""-- type: Literal['noop'] = Field(default='noop')-- model_config = ConfigDict(extra='forbid')---class ObservationMaskingCondenserConfig(BaseModel):- """Configuration for ObservationMaskingCondenser."""-- type: Literal['observation_masking'] = Field(default='observation_masking')- attention_window: int = Field(- default=100,- description='The number of most-recent events where observations will not be masked.',- ge=1,- )-- model_config = ConfigDict(extra='forbid')---class BrowserOutputCondenserConfig(BaseModel):- """Configuration for the BrowserOutputCondenser."""-- type: Literal['browser_output_masking'] = Field(default='browser_output_masking')- attention_window: int = Field(- default=1,- description='The number of most recent browser output observations that will not be masked.',- ge=1,- )---class RecentEventsCondenserConfig(BaseModel):- """Configuration for RecentEventsCondenser."""-- type: Literal['recent'] = Field(default='recent')-- # at least one event by default, because the best guess is that it is the user task- keep_first: int = Field(- default=1,- description='The number of initial events to condense.',- ge=0,- )- max_events: int = Field(- default=100, description='Maximum number of events to keep.', ge=1- )-- model_config = ConfigDict(extra='forbid')---class LLMSummarizingCondenserConfig(BaseModel):- """Configuration for LLMCondenser."""-- type: Literal['llm'] = Field(default='llm')- llm_config: LLMConfig = Field(- ..., description='Configuration for the LLM to use for condensing.'- )-- # at least one event by default, because the best guess is that it's the user task- keep_first: int = Field(- default=1,- description='Number of initial events to always keep in history.',- ge=0,- )- max_size: int = Field(- default=100,- description='Maximum size of the condensed history before triggering forgetting.',- ge=2,- )- max_event_length: int = Field(- default=10_000,- description='Maximum length of the event representations to be passed to the LLM.',- )-- model_config = ConfigDict(extra='forbid')---class AmortizedForgettingCondenserConfig(BaseModel):- """Configuration for AmortizedForgettingCondenser."""-- type: Literal['amortized'] = Field(default='amortized')- max_size: int = Field(- default=100,- description='Maximum size of the condensed history before triggering forgetting.',- ge=2,- )-- # at least one event by default, because the best guess is that it's the user task- keep_first: int = Field(- default=1,- description='Number of initial events to always keep in history.',- ge=0,- )-- model_config = ConfigDict(extra='forbid')---class LLMAttentionCondenserConfig(BaseModel):- """Configuration for LLMAttentionCondenser."""-- type: Literal['llm_attention'] = Field(default='llm_attention')- llm_config: LLMConfig = Field(- ..., description='Configuration for the LLM to use for attention.'- )- max_size: int = Field(- default=100,- description='Maximum size of the condensed history before triggering forgetting.',- ge=2,- )-- # at least one event by default, because the best guess is that it's the user task- keep_first: int = Field(- default=1,- description='Number of initial events to always keep in history.',- ge=0,- )-- model_config = ConfigDict(extra='forbid')---class StructuredSummaryCondenserConfig(BaseModel):- """Configuration for StructuredSummaryCondenser instances."""-- type: Literal['structured'] = Field(default='structured')- llm_config: LLMConfig = Field(- ..., description='Configuration for the LLM to use for condensing.'- )-- # at least one event by default, because the best guess is that it's the user task- keep_first: int = Field(- default=1,- description='Number of initial events to always keep in history.',- ge=0,- )- max_size: int = Field(- default=100,- description='Maximum size of the condensed history before triggering forgetting.',- ge=2,- )- max_event_length: int = Field(- default=10_000,- description='Maximum length of the event representations to be passed to the LLM.',- )-- model_config = ConfigDict(extra='forbid')---class CondenserPipelineConfig(BaseModel):- """Configuration for the CondenserPipeline."""-- type: Literal['pipeline'] = Field(default='pipeline')- condensers: list[CondenserConfig] = Field(- default_factory=list,- description='List of condenser configurations to be used in the pipeline.',- )-- model_config = ConfigDict(extra='forbid')---class ConversationWindowCondenserConfig(BaseModel):- """Configuration for ConversationWindowCondenser.-- Not currently supported by the TOML or ENV_VAR configuration strategies.- """-- type: Literal['conversation_window'] = Field(default='conversation_window')-- model_config = ConfigDict(extra='forbid')---# Type alias for convenience-CondenserConfig = (- NoOpCondenserConfig- | ObservationMaskingCondenserConfig- | BrowserOutputCondenserConfig- | RecentEventsCondenserConfig- | LLMSummarizingCondenserConfig- | AmortizedForgettingCondenserConfig- | LLMAttentionCondenserConfig- | StructuredSummaryCondenserConfig- | CondenserPipelineConfig- | ConversationWindowCondenserConfig-)---def condenser_config_from_toml_section(- data: dict, llm_configs: dict | None = None-) -> dict[str, CondenserConfig]:- """Create a CondenserConfig instance from a toml dictionary representing the [condenser] section.-- For CondenserConfig, the handling is different since it's a union type. The type of condenser- is determined by the 'type' field in the section.-- Example:- Parse condenser config like:- [condenser]- type = "noop"-- For condensers that require an LLM config, you can specify the name of an LLM config:- [condenser]- type = "llm"- llm_config = "my_llm" # References [llm.my_llm] section-- Args:- data: The TOML dictionary representing the [condenser] section.- llm_configs: Optional dictionary of LLMConfig objects keyed by name.-- Returns:- dict[str, CondenserConfig]: A mapping where the key "condenser" corresponds to the configuration.- """- # Initialize the result mapping- condenser_mapping: dict[str, CondenserConfig] = {}-- # Process config- try:- # Determine which condenser type to use based on 'type' field- condenser_type = data.get('type', 'noop')-- # Handle LLM config reference if needed- if (- condenser_type in ('llm', 'llm_attention')- and 'llm_config' in data- and isinstance(data['llm_config'], str)- ):- llm_config_name = data['llm_config']- if llm_configs and llm_config_name in llm_configs:- # Replace the string reference with the actual LLMConfig object- data_copy = data.copy()- data_copy['llm_config'] = llm_configs[llm_config_name]- config = create_condenser_config(condenser_type, data_copy)- else:- logger.openhands_logger.warning(- f"LLM config '{llm_config_name}' not found for condenser. Using default LLMConfig."- )- # Create a default LLMConfig if the referenced one doesn't exist- data_copy = data.copy()- # Try to use the fallback 'llm' config- if llm_configs is not None:- data_copy['llm_config'] = llm_configs.get('llm')- config = create_condenser_config(condenser_type, data_copy)- else:- config = create_condenser_config(condenser_type, data)-- condenser_mapping['condenser'] = config- except (ValidationError, ValueError) as e:- logger.openhands_logger.warning(- f'Invalid condenser configuration: {e}. Using NoOpCondenserConfig.'- )- # Default to NoOpCondenserConfig if config fails- config = NoOpCondenserConfig(type='noop')- condenser_mapping['condenser'] = config-- return condenser_mapping---# For backward compatibility-from_toml_section = condenser_config_from_toml_section---def create_condenser_config(condenser_type: str, data: dict) -> CondenserConfig:- """Create a CondenserConfig instance based on the specified type.-- Args:- condenser_type: The type of condenser to create.- data: The configuration data.-- Returns:- A CondenserConfig instance.-- Raises:- ValueError: If the condenser type is unknown.- ValidationError: If the provided data fails validation for the condenser type.- """- # Mapping of condenser types to their config classes- condenser_classes = {- 'noop': NoOpCondenserConfig,- 'observation_masking': ObservationMaskingCondenserConfig,- 'recent': RecentEventsCondenserConfig,- 'llm': LLMSummarizingCondenserConfig,- 'amortized': AmortizedForgettingCondenserConfig,- 'llm_attention': LLMAttentionCondenserConfig,- 'structured': StructuredSummaryCondenserConfig,- 'pipeline': CondenserPipelineConfig,- 'conversation_window': ConversationWindowCondenserConfig,- 'browser_output_masking': BrowserOutputCondenserConfig,- }-- if condenser_type not in condenser_classes:- raise ValueError(f'Unknown condenser type: {condenser_type}')-- # Create and validate the config using direct instantiation- # Explicitly handle ValidationError to provide more context- try:- config_class = condenser_classes[condenser_type]- # Use type casting to help mypy understand the return type- return cast(CondenserConfig, config_class(**data))- except ValidationError as e:- # Just re-raise with a more descriptive message, but don't try to pass the errors- # which can cause compatibility issues with different pydantic versions- raise ValueError(- f"Validation failed for condenser type '{condenser_type}': {e}"- )diff --git a/openhands/core/config/model_routing_config.py b/openhands/core/config/model_routing_config.pydeleted file mode 100644index 18dd03af55..0000000000--- a/openhands/core/config/model_routing_config.py+++ /dev/null@@ -1,46 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from pydantic import BaseModel, ConfigDict, Field, ValidationError--from openhands.core.config.llm_config import LLMConfig---class ModelRoutingConfig(BaseModel):- """Configuration for model routing.-- Attributes:- router_name (str): The name of the router to use. Default is 'noop_router'.- llms_for_routing (dict[str, LLMConfig]): A dictionary mapping config names of LLMs for routing to their configurations.- """-- router_name: str = Field(default='noop_router')- llms_for_routing: dict[str, LLMConfig] = Field(default_factory=dict)-- model_config = ConfigDict(extra='forbid')-- @classmethod- def from_toml_section(cls, data: dict) -> dict[str, 'ModelRoutingConfig']:- """- Create a mapping of ModelRoutingConfig instances from a toml dictionary representing the [model_routing] section.-- The configuration is built from all keys in data.-- Returns:- dict[str, ModelRoutingConfig]: A mapping where the key "model_routing" corresponds to the [model_routing] configuration- """-- # Initialize the result mapping- model_routing_mapping: dict[str, ModelRoutingConfig] = {}-- # Try to create the configuration instance- try:- model_routing_mapping['model_routing'] = cls.model_validate(data)- except ValidationError as e:- raise ValueError(f'Invalid model routing configuration: {e}')-- return model_routing_mappingdiff --git a/openhands/core/config/utils.py b/openhands/core/config/utils.pyindex f392c830e0..63bb2140b6 100644--- a/openhands/core/config/utils.py+++ b/openhands/core/config/utils.py@@ -24,14 +24,10 @@ from openhands.app_server.file_store.files import FileStorefrom openhands.core import loggerfrom openhands.core.config.agent_config import AgentConfigfrom openhands.core.config.arg_utils import get_headless_parser-from openhands.core.config.condenser_config import (- condenser_config_from_toml_section,-)from openhands.core.config.extended_config import ExtendedConfigfrom openhands.core.config.kubernetes_config import KubernetesConfigfrom openhands.core.config.llm_config import LLMConfigfrom openhands.core.config.mcp_config import mcp_config_from_toml-from openhands.core.config.model_routing_config import ModelRoutingConfigfrom openhands.core.config.openhands_config import OpenHandsConfigfrom openhands.core.config.sandbox_config import SandboxConfigfrom openhands.core.config.security_config import SecurityConfig@@ -230,35 +226,6 @@ def load_from_toml(cfg: OpenHandsConfig, toml_file: str = 'config.toml') -> None# Re-raise ValueError from SecurityConfig.from_toml_sectionraise ValueError('Error in [security] section in config.toml')- if 'model_routing' in toml_config:- try:- model_routing_mapping = ModelRoutingConfig.from_toml_section(- toml_config['model_routing']- )- # We only use the base model routing config for now- if 'model_routing' in model_routing_mapping:- default_agent_config = cfg.get_agent_config()- default_agent_config.model_routing = model_routing_mapping[- 'model_routing'- ]-- # Construct the llms_for_routing by filtering llms with for_routing = True- llms_for_routing_dict = {}- for llm_name, llm_config in cfg.llms.items():- if llm_config and llm_config.for_routing:- llms_for_routing_dict[llm_name] = llm_config- default_agent_config.model_routing.llms_for_routing = (- llms_for_routing_dict- )-- logger.openhands_logger.debug(- 'Default model routing configuration loaded from config toml and assigned to default agent'- )- except (TypeError, KeyError, ValidationError) as e:- logger.openhands_logger.warning(- f'Cannot parse [model_routing] config from toml, values have not been applied.\nError: {e}'- )-# Process sandbox section if presentif 'sandbox' in toml_config:try:@@ -300,45 +267,6 @@ def load_from_toml(cfg: OpenHandsConfig, toml_file: str = 'config.toml') -> Nonef'Cannot parse [kubernetes] config from toml, values have not been applied.\nError: {e}')- # Process condenser section if present- if 'condenser' in toml_config:- try:- # Pass the LLM configs to the condenser config parser- condenser_mapping = condenser_config_from_toml_section(- toml_config['condenser'], cfg.llms- )- # Assign the default condenser configuration to the default agent configuration- if 'condenser' in condenser_mapping:- # Get the default agent config and assign the condenser config to it- default_agent_config = cfg.get_agent_config()- default_agent_config.condenser = condenser_mapping['condenser']- logger.openhands_logger.debug(- 'Default condenser configuration loaded from config toml and assigned to default agent'- )- except (TypeError, KeyError, ValidationError) as e:- logger.openhands_logger.warning(- f'Cannot parse [condenser] config from toml, values have not been applied.\nError: {e}'- )- # If no condenser section is in toml but enable_default_condenser is True,- # set LLMSummarizingCondenserConfig as default- elif cfg.enable_default_condenser:- from openhands.core.config.condenser_config import LLMSummarizingCondenserConfig-- # Get default agent config- default_agent_config = cfg.get_agent_config()-- # Create default LLM summarizing condenser config- default_condenser = LLMSummarizingCondenserConfig(- llm_config=cfg.get_llm_config(), # Use default LLM config- type='llm',- )-- # Set as default condenser- default_agent_config.condenser = default_condenser- logger.openhands_logger.debug(- 'Default LLM summarizing condenser assigned to default agent (no condenser in config)'- )-# Process extended section if presentif 'extended' in toml_config:try:@@ -349,6 +277,8 @@ def load_from_toml(cfg: OpenHandsConfig, toml_file: str = 'config.toml') -> None)# Check for unknown sections+ # Note: 'condenser' and 'model_routing' are kept for backwards compatibility+ # with old config files - they are silently ignoredknown_sections = {'core','extended',@@ -356,10 +286,10 @@ def load_from_toml(cfg: OpenHandsConfig, toml_file: str = 'config.toml') -> None'llm','security','sandbox',- 'condenser',+ 'condenser', # Legacy, ignored'mcp','kubernetes',- 'model_routing',+ 'model_routing', # Legacy, ignored}for key in toml_config:if key.lower() not in known_sections:@@ -587,88 +517,6 @@ def get_llm_config_arg(return None-def get_llms_for_routing_config(toml_file: str = 'config.toml') -> dict[str, LLMConfig]:- """Get the LLMs that are configured for routing from the config file.-- This function will return a dictionary of LLMConfig objects that are configured- for routing, i.e., those with `for_routing` set to True.-- Args:- toml_file: Path to the configuration file to read from. Defaults to 'config.toml'.-- Returns:- dict[str, LLMConfig]: A dictionary of LLMConfig objects for routing.- """- llms_for_routing: dict[str, LLMConfig] = {}-- try:- with open(toml_file, 'r', encoding='utf-8') as toml_contents:- toml_config = toml.load(toml_contents)- except FileNotFoundError as e:- logger.openhands_logger.info(- f'Config file not found: {e}. Toml values have not been applied.'- )- return llms_for_routing- except toml.TomlDecodeError as e:- logger.openhands_logger.error(- f'Cannot parse LLM configs from {toml_file}. Exception: {e}'- )- return llms_for_routing-- llm_configs = LLMConfig.from_toml_section(toml_config.get('llm', {}))-- if llm_configs:- for llm_name, llm_config in llm_configs.items():- if llm_config.for_routing:- llms_for_routing[llm_name] = llm_config-- return llms_for_routing---def get_model_routing_config_arg(toml_file: str = 'config.toml') -> ModelRoutingConfig:- """Get the model routing settings from the config file. We only support the default model routing config [model_routing].-- Args:- toml_file: Path to the configuration file to read from. Defaults to 'config.toml'.-- Returns:- ModelRoutingConfig: The ModelRoutingConfig object with the settings from the config file, or the object with default values if not found/error.- """- logger.openhands_logger.debug(- f"Loading model routing config ['model_routing'] from {toml_file}"- )- default_cfg = ModelRoutingConfig()-- # load the toml file- try:- with open(toml_file, 'r', encoding='utf-8') as toml_contents:- toml_config = toml.load(toml_contents)- except FileNotFoundError as e:- logger.openhands_logger.info(f'Config file not found: {toml_file}. Error: {e}')- return default_cfg- except toml.TomlDecodeError as e:- logger.openhands_logger.error(- f'Cannot parse model routing group [model_routing] from {toml_file}. Exception: {e}'- )- return default_cfg-- # Update the model routing config with the specified section- if 'model_routing' in toml_config:- try:- model_routing_data = toml_config['model_routing']- return ModelRoutingConfig(**model_routing_data)- except ValidationError as e:- logger.openhands_logger.error(- f'Invalid model routing configuration for [model_routing]: {e}'- )- return default_cfg-- logger.openhands_logger.warning(- f'Model routing config section [model_routing] not found in {toml_file}'- )- return default_cfg--def parse_arguments() -> argparse.Namespace:"""Parse command line arguments."""parser = get_headless_parser()diff --git a/tests/unit/core/config/test_config.py b/tests/unit/core/config/test_config.pyindex eb025f7e4e..33e69fdf2b 100644--- a/tests/unit/core/config/test_config.py+++ b/tests/unit/core/config/test_config.py@@ -13,12 +13,6 @@ from openhands.core.config import (load_from_env,load_from_toml,)-from openhands.core.config.condenser_config import (- ConversationWindowCondenserConfig,- LLMSummarizingCondenserConfig,- NoOpCondenserConfig,- RecentEventsCondenserConfig,-)from openhands.core.logger import openhands_logger@@ -666,13 +660,6 @@ def test_sandbox_volumes_with_workspace_not_first(default_config):assert default_config.workspace_base == '/home/user/mydir'-def test_agent_config_condenser_with_no_enabled():- """Test default agent condenser with enable_default_condenser=False."""- config = OpenHandsConfig(enable_default_condenser=False)- agent_config = config.get_agent_config()- assert isinstance(agent_config.condenser, ConversationWindowCondenserConfig)--def test_sandbox_volumes_toml(default_config, temp_toml_file):"""Test that volumes configuration under [sandbox] works correctly."""with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:@@ -696,236 +683,6 @@ timeout = 1assert default_config.sandbox.timeout == 1-def test_condenser_config_from_toml_basic(default_config, temp_toml_file):- """Test loading basic condenser configuration from TOML."""- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:- toml_file.write("""-[condenser]-type = "recent"-keep_first = 3-max_events = 15-""")-- load_from_toml(default_config, temp_toml_file)-- # Verify that the condenser config is correctly assigned to the default agent config- agent_config = default_config.get_agent_config()- assert isinstance(agent_config.condenser, RecentEventsCondenserConfig)- assert agent_config.condenser.keep_first == 3- assert agent_config.condenser.max_events == 15-- # We can also verify the function works directly- from openhands.core.config.condenser_config import (- condenser_config_from_toml_section,- )-- condenser_data = {'type': 'recent', 'keep_first': 3, 'max_events': 15}- condenser_mapping = condenser_config_from_toml_section(condenser_data)-- assert 'condenser' in condenser_mapping- assert isinstance(condenser_mapping['condenser'], RecentEventsCondenserConfig)- assert condenser_mapping['condenser'].keep_first == 3- assert condenser_mapping['condenser'].max_events == 15---def test_condenser_config_from_toml_with_llm_reference(default_config, temp_toml_file):- """Test loading condenser configuration with LLM reference from TOML."""- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:- toml_file.write("""-[llm.condenser_llm]-model = "gpt-4"-api_key = "test-key"--[condenser]-type = "llm"-llm_config = "condenser_llm"-keep_first = 2-max_size = 50-""")-- load_from_toml(default_config, temp_toml_file)-- # Verify that the LLM config was loaded- assert 'condenser_llm' in default_config.llms- assert default_config.llms['condenser_llm'].model == 'gpt-4'-- # Verify that the condenser config is correctly assigned to the default agent config- agent_config = default_config.get_agent_config()- assert isinstance(agent_config.condenser, LLMSummarizingCondenserConfig)- assert agent_config.condenser.keep_first == 2- assert agent_config.condenser.max_size == 50- assert agent_config.condenser.llm_config.model == 'gpt-4'-- # Test the condenser config with the LLM reference- from openhands.core.config.condenser_config import (- condenser_config_from_toml_section,- )-- condenser_data = {- 'type': 'llm',- 'llm_config': 'condenser_llm',- 'keep_first': 2,- 'max_size': 50,- }- condenser_mapping = condenser_config_from_toml_section(- condenser_data, default_config.llms- )-- assert 'condenser' in condenser_mapping- assert isinstance(condenser_mapping['condenser'], LLMSummarizingCondenserConfig)- assert condenser_mapping['condenser'].keep_first == 2- assert condenser_mapping['condenser'].max_size == 50- assert condenser_mapping['condenser'].llm_config.model == 'gpt-4'---def test_condenser_config_from_toml_with_missing_llm_reference(- default_config, temp_toml_file-):- """Test loading condenser configuration with missing LLM reference from TOML."""- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:- toml_file.write("""-[condenser]-type = "llm"-llm_config = "missing_llm"-keep_first = 2-max_size = 50-""")-- load_from_toml(default_config, temp_toml_file)-- # Test the condenser config with a missing LLM reference- from openhands.core.config.condenser_config import (- condenser_config_from_toml_section,- )-- condenser_data = {- 'type': 'llm',- 'llm_config': 'missing_llm',- 'keep_first': 2,- 'max_size': 50,- }- condenser_mapping = condenser_config_from_toml_section(- condenser_data, default_config.llms- )-- assert 'condenser' in condenser_mapping- assert isinstance(condenser_mapping['condenser'], NoOpCondenserConfig)- # Should not have a default LLMConfig when the reference is missing- assert not hasattr(condenser_mapping['condenser'], 'llm_config')---def test_condenser_config_from_toml_with_invalid_config(default_config, temp_toml_file):- """Test loading invalid condenser configuration from TOML."""- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:- toml_file.write("""-[condenser]-type = "invalid_type"-""")-- load_from_toml(default_config, temp_toml_file)-- # Test the condenser config with an invalid type- from openhands.core.config.condenser_config import (- condenser_config_from_toml_section,- )-- condenser_data = {'type': 'invalid_type'}- condenser_mapping = condenser_config_from_toml_section(condenser_data)-- # Should default to NoOpCondenserConfig when the type is invalid- assert 'condenser' in condenser_mapping- assert isinstance(condenser_mapping['condenser'], NoOpCondenserConfig)---def test_condenser_config_from_toml_with_validation_error(- default_config, temp_toml_file-):- """Test loading condenser configuration with validation error from TOML."""- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:- toml_file.write("""-[condenser]-type = "recent"-keep_first = -1 # Invalid: must be >= 0-max_events = 0 # Invalid: must be >= 1-""")-- load_from_toml(default_config, temp_toml_file)-- # Test the condenser config with validation errors- from openhands.core.config.condenser_config import (- condenser_config_from_toml_section,- )-- condenser_data = {'type': 'recent', 'keep_first': -1, 'max_events': 0}- condenser_mapping = condenser_config_from_toml_section(condenser_data)-- # Should default to NoOpCondenserConfig when validation fails- assert 'condenser' in condenser_mapping- assert isinstance(condenser_mapping['condenser'], NoOpCondenserConfig)---def test_default_condenser_behavior_enabled(default_config, temp_toml_file):- """Test the default condenser behavior when enable_default_condenser is True."""- # Create a minimal TOML file with no condenser section- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:- toml_file.write("""-[core]-# Empty core section, no condenser section-""")-- # Set enable_default_condenser to True- default_config.enable_default_condenser = True- load_from_toml(default_config, temp_toml_file)-- # Verify the default agent config has LLMSummarizingCondenserConfig- agent_config = default_config.get_agent_config()- assert isinstance(agent_config.condenser, LLMSummarizingCondenserConfig)- assert agent_config.condenser.keep_first == 1- assert agent_config.condenser.max_size == 100---def test_default_condenser_behavior_disabled(default_config, temp_toml_file):- """Test the default condenser behavior when enable_default_condenser is False."""- # Create a minimal TOML file with no condenser section- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:- toml_file.write("""-[core]-# Empty core section, no condenser section-""")-- # Set enable_default_condenser to False- default_config.enable_default_condenser = False- load_from_toml(default_config, temp_toml_file)-- # Verify the agent config uses ConversationWindowCondenserConfig- agent_config = default_config.get_agent_config()- assert isinstance(agent_config.condenser, ConversationWindowCondenserConfig)---def test_default_condenser_explicit_toml_override(default_config, temp_toml_file):- """Test that explicit condenser in TOML takes precedence over the default."""- # Set enable_default_condenser to True- default_config.enable_default_condenser = True-- # Create a TOML file with an explicit condenser section- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:- toml_file.write("""-[condenser]-type = "recent"-keep_first = 3-max_events = 15-""")-- # Load the config- load_from_toml(default_config, temp_toml_file)-- # Verify the explicit condenser from TOML takes precedence- agent_config = default_config.get_agent_config()- assert isinstance(agent_config.condenser, RecentEventsCondenserConfig)- assert agent_config.condenser.keep_first == 3- assert agent_config.condenser.max_events == 15--def test_api_keys_repr_str():# Test LLMConfigllm_config = LLMConfig(