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
10 changes: 10 additions & 0 deletions openevolve/llm/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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}): "
Expand Down
2 changes: 2 additions & 0 deletions openevolve/process_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
29 changes: 27 additions & 2 deletions tests/test_diff_format_validation_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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)"""

Expand Down
65 changes: 65 additions & 0 deletions tests/test_openai_finish_reason.py
Original file line number Diff line number Diff line change
@@ -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()
Loading