From d6b082eeab9251051a22d2a0276a615825c3c69c Mon Sep 17 00:00:00 2001 From: Chaitanya Date: Thu, 12 Nov 2026 18:49:11 +0530 Subject: [PATCH] fix: report responses cut off at max_tokens A reply that hits max_tokens comes back with finish_reason="length", but nothing checked it. The cut-off reply was parsed as if it were complete, and the iteration failed with "No valid diffs found in response" (or an unmatched delimiter error), which points at the model's output format instead of the limit. Thinking models count reasoning tokens toward max_tokens, so this happens a lot with them. _call_api now logs a warning with the model and the limit and records finish_reason in last_usage, and the iteration error says when the reply was cut off. --- openevolve/llm/openai.py | 10 ++++ openevolve/process_parallel.py | 2 + tests/test_diff_format_validation_worker.py | 29 ++++++++- tests/test_openai_finish_reason.py | 65 +++++++++++++++++++++ 4 files changed, 104 insertions(+), 2 deletions(-) create mode 100644 tests/test_openai_finish_reason.py diff --git a/openevolve/llm/openai.py b/openevolve/llm/openai.py index ee6019ec9..f867a1630 100644 --- a/openevolve/llm/openai.py +++ b/openevolve/llm/openai.py @@ -236,6 +236,15 @@ async def _call_api(self, params: Dict[str, Any]) -> str: logger.debug(f"API parameters: {params}") logger.debug(f"API response: {response.choices[0].message.content}") + finish_reason = getattr(response.choices[0], "finish_reason", None) + if finish_reason == "length": + limit = params.get("max_completion_tokens") or params.get("max_tokens") + logger.warning( + f"Response from {self.model} was cut off at the token limit " + f"(finish_reason=length, max_tokens={limit}). Thinking models count " + "reasoning tokens toward this limit; raise llm.max_tokens." + ) + usage = getattr(response, "usage", None) if usage is not None: prompt_tokens = getattr(usage, "prompt_tokens", 0) or 0 @@ -246,6 +255,7 @@ async def _call_api(self, params: Dict[str, Any]) -> str: "completion_tokens": completion_tokens, "total_tokens": total_tokens, "model": str(self.model), + "finish_reason": finish_reason, } logger.info( f"LLM Token Usage ({self.model}): " diff --git a/openevolve/process_parallel.py b/openevolve/process_parallel.py index 537d03723..dd414dd00 100644 --- a/openevolve/process_parallel.py +++ b/openevolve/process_parallel.py @@ -300,6 +300,8 @@ def _run_iteration( def _reject(error: str) -> SerializableResult: """A failed iteration that still carries what the LLM was asked and answered""" + if token_usage and token_usage.get("finish_reason") == "length": + error += " (response was cut off at llm.max_tokens)" return SerializableResult( error=error, iteration=iteration, diff --git a/tests/test_diff_format_validation_worker.py b/tests/test_diff_format_validation_worker.py index 22e5b7960..cc02d5eb3 100644 --- a/tests/test_diff_format_validation_worker.py +++ b/tests/test_diff_format_validation_worker.py @@ -53,11 +53,11 @@ def setUp(self): self.sampler = MagicMock() self.sampler.build_prompt.return_value = {"system": "sys", "user": "usr"} - def _run(self, llm_response, llm_error=None): + def _run(self, llm_response, llm_error=None, usage=USAGE): self.llm_response = llm_response llm = MagicMock() llm.generate_with_context = AsyncMock(return_value=llm_response, side_effect=llm_error) - llm.last_usage = USAGE + llm.last_usage = usage llm.last_model = MODEL # Worker globals are only created in worker processes, hence create=True. with patch.multiple( @@ -155,6 +155,31 @@ def test_llm_returns_none(self): self.assertEqual(result.token_usage, USAGE) +class TestWorkerTruncatedResponse(_WorkerTestBase): + """A response cut off at llm.max_tokens says so in the iteration error""" + + CUT_OFF = dict(USAGE, finish_reason="length") + + def test_cut_off_before_any_diff(self): + result = self._run("Plan: first I will", usage=self.CUT_OFF) + self.assertEqual( + result.error, + "No valid diffs found in response (response was cut off at llm.max_tokens)", + ) + self.evaluator.evaluate_program.assert_not_called() + + def test_cut_off_inside_a_diff(self): + result = self._run(VALID_BLOCK.replace(">>>>>>> REPLACE\n", ""), usage=self.CUT_OFF) + self.assertIn("(response was cut off at llm.max_tokens)", result.error) + self.evaluator.evaluate_program.assert_not_called() + + def test_complete_response_error_is_unchanged(self): + result = self._run( + "I could not think of a change.", usage=dict(USAGE, finish_reason="stop") + ) + self.assertEqual(result.error, "No valid diffs found in response") + + class TestWorkerRecordsModel(_WorkerTestBase): """Each program records the model that generated it (#381)""" diff --git a/tests/test_openai_finish_reason.py b/tests/test_openai_finish_reason.py new file mode 100644 index 000000000..d3738ec07 --- /dev/null +++ b/tests/test_openai_finish_reason.py @@ -0,0 +1,65 @@ +""" +Tests that a response cut off at the token limit (finish_reason="length") is reported +instead of being passed on as if it were complete +""" + +import asyncio +import unittest +from unittest.mock import AsyncMock, Mock, patch + +from openevolve.llm.openai import OpenAILLM + + +def _make_llm(): + model_cfg = Mock() + model_cfg.name = "test-model" + model_cfg.system_message = "system" + model_cfg.temperature = 0.7 + model_cfg.top_p = None + model_cfg.max_tokens = 100 + model_cfg.timeout = 60 + model_cfg.retries = 0 + model_cfg.retry_delay = 0 + model_cfg.api_base = "https://example.com/v1" + model_cfg.api_key = None # openai.AsyncOpenAI is patched + model_cfg.random_seed = None + model_cfg.reasoning_effort = None + with patch("openai.AsyncOpenAI"): + return OpenAILLM(model_cfg) + + +def _response(finish_reason): + response = Mock() + response.choices = [Mock()] + response.choices[0].message.content = "Plan: keep the quiet window in onSuccess to" + response.choices[0].finish_reason = finish_reason + # Numbers from a real cut-off reply: most of the limit went to thinking tokens + response.usage.prompt_tokens = 8411 + response.usage.completion_tokens = 322 + response.usage.total_tokens = 16598 + return response + + +class TestFinishReason(unittest.TestCase): + def test_cut_off_response_logs_a_warning(self): + llm = _make_llm() + llm.client.chat.completions.create = AsyncMock(return_value=_response("length")) + params = {"model": "test-model", "messages": [], "max_tokens": 8192} + + with self.assertLogs("openevolve.llm.openai", level="WARNING") as logs: + asyncio.run(llm._call_api(params)) + self.assertIn("max_tokens=8192", logs.output[0]) + self.assertEqual(llm.last_usage["finish_reason"], "length") + + def test_complete_response_does_not_warn(self): + llm = _make_llm() + llm.client.chat.completions.create = AsyncMock(return_value=_response("stop")) + params = {"model": "test-model", "messages": [], "max_tokens": 8192} + + with self.assertNoLogs("openevolve.llm.openai", level="WARNING"): + asyncio.run(llm._call_api(params)) + self.assertEqual(llm.last_usage["finish_reason"], "stop") + + +if __name__ == "__main__": + unittest.main()