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
13 changes: 12 additions & 1 deletion openevolve/llm/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ async def generate_with_context(
"Reproducibility may be limited."
)
self._seed_skip_logged = True
elif urlparse(self.api_base or "").hostname == "api.mistral.ai":
params["extra_body"] = {"random_seed": seed}
else:
params["seed"] = seed

Expand Down Expand Up @@ -257,7 +259,16 @@ async def _call_api(self, params: Dict[str, Any]) -> str:
self.last_usage = None
logger.info(f"LLM Token Usage ({self.model}): usage info not returned by API")

return response.choices[0].message.content
content = response.choices[0].message.content
# Mistral's API reasoning models return content as a list of typed
# chunks (thinking + text); keep only the text chunks
if isinstance(content, list):
content = "".join(
chunk["text"] for chunk in content if chunk.get("type") == "text"
)
if not content:
raise ValueError("API returned no text content in response chunks")
return content

async def _manual_wait_for_answer(
self, params: Dict[str, Any], timeout: Optional[Union[int, float]]
Expand Down
59 changes: 59 additions & 0 deletions tests/test_mistral_seed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""
Tests that the seed parameter is changed to 'random_seed' for Mistral's OpenAI-compatible endpoint (Derived from test_openai_seed.py)
"""

import asyncio
import unittest
from unittest.mock import AsyncMock, Mock, patch

from openevolve.llm.openai import OpenAILLM

MISTRAL = "https://api.mistral.ai/v1/"


def _make_llm(api_base):
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 = api_base
model_cfg.api_key = None # openai.AsyncOpenAI is patched
model_cfg.random_seed = 42
model_cfg.reasoning_effort = None
with patch("openai.AsyncOpenAI"):
llm = OpenAILLM(model_cfg)
response = Mock()
response.choices = [Mock()]
response.choices[0].message.content = "ok"
llm.client.chat.completions.create = AsyncMock(return_value=response)
return llm


def _sent_params(llm):
asyncio.run(
llm.generate_with_context(
system_message="sys", messages=[{"role": "user", "content": "hi"}]
)
)
return llm.client.chat.completions.create.call_args.kwargs


class TestSeedParameter(unittest.TestCase):
def test_seed_is_sent_to_other_endpoints(self):
self.assertEqual(_sent_params(_make_llm("https://api.openai.com/v1"))["seed"], 42)

def test_parameter_is_renamed_for_mistral_with_or_without_trailing_slash(self):
for api_base in (MISTRAL, MISTRAL.rstrip("/")):
with self.subTest(api_base=api_base):
params = _sent_params(_make_llm(api_base))
self.assertNotIn("seed", params)
self.assertEqual(params["extra_body"], {"random_seed": 42})


if __name__ == "__main__":
unittest.main()
124 changes: 124 additions & 0 deletions tests/test_openai_reasoning_chunks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
"""
Tests handling of a list of chunks returned from reasoning models
As returned by Mistral's API for reasoning models
"""

import asyncio
import unittest
from unittest.mock import AsyncMock, Mock, patch

from openevolve.llm.openai import OpenAILLM

MISTRAL = "https://api.mistral.ai/v1"


def _make_llm(api_base=MISTRAL, content="ok"):
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 = api_base
model_cfg.api_key = None # openai.AsyncOpenAI is patched
model_cfg.random_seed = 42
model_cfg.reasoning_effort = None
with patch("openai.AsyncOpenAI"):
llm = OpenAILLM(model_cfg)
response = Mock()
response.choices = [Mock()]
response.choices[0].message.content = content
llm.client.chat.completions.create = AsyncMock(return_value=response)
return llm


class TestListContentBlocks(unittest.TestCase):
def test_thinking_and_text_blocks_are_joined(self):
content = [
{
"type": "thinking",
"thinking": [
{
"type": "text",
"text": "Internal thinking...",
}
],
"closed": True,
},
{
"type": "text",
"text": "```python\nprint(hi)\n\n```",
},
]
llm = _make_llm(content=content)
result = asyncio.run(
llm.generate_with_context(
system_message="sys", messages=[{"role": "user", "content": "hi"}]
)
)
self.assertEqual(result, "```python\nprint(hi)\n\n```")

def test_multiple_text_blocks_are_concatenated(self):
content = [
{
"type": "thinking",
"thinking": [
{
"type": "text",
"text": "Thinking one...",
}
],
"closed": True,
},
{"type": "text", "text": "part one "},
{
"type": "thinking",
"thinking": [
{
"type": "text",
"text": "Thinking two...",
}
],
"closed": True,
},
{"type": "text", "text": "part two"},
]
llm = _make_llm(content=content)
result = asyncio.run(
llm.generate_with_context(
system_message="sys", messages=[{"role": "user", "content": "hi"}]
)
)
self.assertEqual(result, "part one part two")

def test_only_thinking_blocks_raises(self):
content = [
{
"type": "thinking",
"thinking": [{"type": "text", "text": "reasoning only"}],
"closed": True,
},
]
llm = _make_llm(content=content)
with self.assertRaises(ValueError):
asyncio.run(
llm.generate_with_context(
system_message="sys", messages=[{"role": "user", "content": "hi"}]
)
)

def test_plain_string_content_is_unchanged(self):
llm = _make_llm(content="plain response")
result = asyncio.run(
llm.generate_with_context(
system_message="sys", messages=[{"role": "user", "content": "hi"}]
)
)
self.assertEqual(result, "plain response")


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