Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions examples/r_robust_regression/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,14 @@ llm:
temperature: 0.8 # Higher temperature for more creative statistical approaches
max_tokens: 4096

# Prompt configuration
prompt:
# Custom system message for R statistical programming
system_message: |
You are an expert statistician and R programmer specializing in robust regression methods.
Focus on improving the algorithm's ability to handle outliers while maintaining accuracy.
Consider techniques like Huber regression, RANSAC, M-estimators, and other robust methods.
Ensure the R code is efficient and follows best practices.

# Prompt configuration
prompt:
num_top_programs: 3
num_diverse_programs: 2

Expand Down
5 changes: 2 additions & 3 deletions examples/rust_adaptive_sort/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,14 @@ llm:
temperature: 0.7
max_tokens: 16384

# Prompt configuration
prompt:
# Custom system message for Rust performance programming
system_message: |
You are an expert Rust systems programmer specializing in high-performance algorithms.
Focus on creating adaptive sorting algorithms that can handle different data patterns efficiently.
Consider hybrid approaches like introsort, adaptive pivot selection, and data-aware optimizations.
Ensure memory safety and idiomatic Rust code. Use appropriate data structures and leverage Rust's zero-cost abstractions.

# Prompt configuration
prompt:
num_top_programs: 4
num_diverse_programs: 3

Expand Down
26 changes: 26 additions & 0 deletions openevolve/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Configuration handling for OpenEvolve
"""

import logging
import os
import re
from dataclasses import asdict, dataclass, field
Expand All @@ -14,6 +15,7 @@
if TYPE_CHECKING:
from openevolve.llm.base import LLMInterface

logger = logging.getLogger(__name__)

_ENV_VAR_PATTERN = re.compile(r"^\$\{([^}]+)\}$") # ${VAR}

Expand Down Expand Up @@ -568,8 +570,32 @@ def from_dict(cls, config_dict: Dict[str, Any]) -> "Config":

config.validate_evolution_mode()

config.resolve_system_message()

return config

def resolve_system_message(self) -> None:
"""Make a system message set under llm reach the prompt.

The prompt sampler only reads prompt.system_message, so a message set as
llm.system_message used to be replaced by the default template without a warning.
Afterwards both fields hold the message in use, so a second call does nothing.
"""
llm_message = self.llm.system_message
if llm_message is None or llm_message == LLMConfig.system_message:
return
if self.prompt.system_message == PromptConfig.system_message:
logger.warning(
"llm.system_message is not read by the prompt sampler; using it as "
"prompt.system_message. Set prompt.system_message instead."
)
self.prompt.system_message = llm_message
elif self.prompt.system_message != llm_message:
logger.warning(
"Both llm.system_message and prompt.system_message are set; ignoring llm.system_message."
)
self.llm.system_message = self.prompt.system_message

def validate_evolution_mode(self) -> None:
"""Check that diff_based_evolution, full_rewrite_probability and
prompt.programs_as_changes_description agree"""
Expand Down
1 change: 1 addition & 0 deletions openevolve/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def __init__(
self.island_selector = island_selector
# A Config built in code never passes through Config.from_dict, so validate here too
self.config.validate_evolution_mode()
self.config.resolve_system_message()

# Set up output directory
self.output_dir = output_dir or os.path.join(
Expand Down
85 changes: 85 additions & 0 deletions tests/test_system_message_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""
Tests for where a custom system message is read from.
The prompt sampler only reads prompt.system_message, so a message set under llm must not be dropped silently.
"""

import os
import tempfile
import unittest

import yaml

# Dummy API key so LLM ensembles initialize without a real key
os.environ.setdefault("OPENAI_API_KEY", "test")

from openevolve.config import Config, load_config


class TestSystemMessagePlacement(unittest.TestCase):
def test_prompt_system_message_is_used_without_warning(self):
with self.assertNoLogs("openevolve.config", level="WARNING"):
config = Config.from_dict({"prompt": {"system_message": "From prompt."}})
self.assertEqual(config.prompt.system_message, "From prompt.")

def test_llm_system_message_fills_an_unset_prompt_system_message(self):
with self.assertLogs("openevolve.config", level="WARNING") as logs:
config = Config.from_dict({"llm": {"system_message": "From llm."}})
self.assertEqual(config.prompt.system_message, "From llm.")
self.assertIn("prompt.system_message", logs.output[0])

def test_prompt_system_message_wins_when_both_are_set(self):
with self.assertLogs("openevolve.config", level="WARNING") as logs:
config = Config.from_dict(
{
"llm": {"system_message": "From llm."},
"prompt": {"system_message": "From prompt."},
}
)
self.assertEqual(config.prompt.system_message, "From prompt.")
self.assertIn("llm.system_message", logs.output[0])

def test_models_get_the_system_message_set_under_llm(self):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "config.yaml")
with open(path, "w") as f:
yaml.safe_dump(
{"llm": {"primary_model": "test-model", "system_message": "From llm."}}, f
)
with self.assertLogs("openevolve.config", level="WARNING"):
config = load_config(path)
self.assertEqual(config.llm.models[0].system_message, "From llm.")

def test_resolving_again_does_not_warn_again(self):
for config_dict in (
{"llm": {"system_message": "From llm."}},
{"llm": {"system_message": "From llm."}, "prompt": {"system_message": "From prompt."}},
):
with self.assertLogs("openevolve.config", level="WARNING"):
config = Config.from_dict(config_dict)
with self.assertNoLogs("openevolve.config", level="WARNING"):
config.resolve_system_message()

def test_config_built_in_code_is_resolved_by_controller(self):
from openevolve.controller import OpenEvolve

config = Config()
config.llm.system_message = "From llm."
with tempfile.TemporaryDirectory() as tmp:
program = os.path.join(tmp, "initial_program.py")
with open(program, "w") as f:
f.write("# EVOLVE-BLOCK-START\nx = 1\n# EVOLVE-BLOCK-END\n")
evaluator = os.path.join(tmp, "evaluator.py")
with open(evaluator, "w") as f:
f.write("def evaluate(program_path):\n return {'combined_score': 0.0}\n")
with self.assertLogs("openevolve.config", level="WARNING"):
controller = OpenEvolve(
program, evaluator, config=config, output_dir=os.path.join(tmp, "out")
)
prompt = controller.prompt_sampler.build_prompt(
current_program="x = 1", program_metrics={"combined_score": 0.0}, language="python"
)
self.assertEqual(prompt["system"], "From llm.")


if __name__ == "__main__":
unittest.main()
Loading