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 docs/llm-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ export OPENAI_API_KEY="sk-..."
# Uses OpenAI endpoints by default
```

Chat Completions remains the default. For models or providers that only support the OpenAI Responses API, select it explicitly:

```yaml
llm:
api_type: "responses"
primary_model: "your-responses-compatible-model"
```

The default is `api_type: "chat_completions"`. Responses support currently covers non-streaming text generation; tool calling and streaming are not included. The Responses API does not accept the `seed` parameter, so seeded runs are less deterministic with this API type.

### Google Gemini

```yaml
Expand Down
6 changes: 6 additions & 0 deletions openevolve/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class LLMModelConfig:
# API configuration
api_base: str = None
api_key: Optional[str] = None
api_type: Optional[str] = None
name: str = None

# LLM provider: "openai" (default), "claude_code" (Claude Code CLI)
Expand Down Expand Up @@ -100,6 +101,8 @@ class LLMModelConfig:

def __post_init__(self):
"""Post-initialization to resolve ${VAR} env var references in api_key"""
if self.api_type is not None and self.api_type not in {"chat_completions", "responses"}:
raise ValueError("llm.api_type must be 'chat_completions' or 'responses'")
self.api_key = _resolve_env_var(self.api_key)


Expand All @@ -109,6 +112,7 @@ class LLMConfig(LLMModelConfig):

# API configuration
api_base: str = "https://api.openai.com/v1"
api_type: Optional[str] = "chat_completions"

# Generation parameters
system_message: Optional[str] = "system_message"
Expand Down Expand Up @@ -194,6 +198,7 @@ def __post_init__(self):
"provider": self.provider,
"api_base": self.api_base,
"api_key": self.api_key,
"api_type": self.api_type,
"temperature": self.temperature,
"top_p": self.top_p,
"max_tokens": self.max_tokens,
Expand Down Expand Up @@ -254,6 +259,7 @@ def rebuild_models(self) -> None:
"provider": self.provider,
"api_base": self.api_base,
"api_key": self.api_key,
"api_type": self.api_type,
"temperature": self.temperature,
"top_p": self.top_p,
"max_tokens": self.max_tokens,
Expand Down
107 changes: 103 additions & 4 deletions openevolve/llm/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,22 @@ def __init__(
self.retry_delay = model_cfg.retry_delay
self.api_base = model_cfg.api_base
self.api_key = model_cfg.api_key
configured_api_type = getattr(model_cfg, "api_type", None)
self.api_type = (
configured_api_type
if isinstance(configured_api_type, str) and configured_api_type
else "chat_completions"
)
if self.api_type not in {"chat_completions", "responses"}:
raise ValueError("api_type must be 'chat_completions' or 'responses'")
self.random_seed = getattr(model_cfg, "random_seed", None)
self.reasoning_effort = getattr(model_cfg, "reasoning_effort", None)
self.last_usage: Optional[Dict[str, Any]] = None
self._seed_skip_logged = False
self._responses_seed_skip_logged = False

# Manual mode: enabled via llm.manual_mode in config.yaml
self.manual_mode = (getattr(model_cfg, "manual_mode", False) is True)
self.manual_mode = getattr(model_cfg, "manual_mode", False) is True
self.manual_queue_dir: Optional[Path] = None

if self.manual_mode:
Expand Down Expand Up @@ -222,6 +231,8 @@ async def _call_api(self, params: Dict[str, Any]) -> str:
"""Make the actual API call"""
if self.client is None:
raise RuntimeError("OpenAI client is not initialized (manual_mode enabled?)")
if self.api_type == "responses":
return await self._call_responses_api(params)

# Await the async client directly instead of running a blocking
# sync client in the default thread-pool executor, which can
Expand Down Expand Up @@ -273,13 +284,101 @@ async def _call_api(self, params: Dict[str, Any]) -> str:
# 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"
)
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

def _build_responses_params(self, params: Dict[str, Any]) -> Dict[str, Any]:
messages = params.get("messages", [])
instructions = [
message.get("content", "") for message in messages if message.get("role") == "system"
]
response_params: Dict[str, Any] = {
"model": params["model"],
"input": [message for message in messages if message.get("role") != "system"],
}
if instructions:
response_params["instructions"] = "\n\n".join(instructions)

max_output_tokens = params.get("max_completion_tokens") or params.get("max_tokens")
if max_output_tokens is not None:
response_params["max_output_tokens"] = max_output_tokens
for key in ("temperature", "top_p"):
if params.get(key) is not None:
response_params[key] = params[key]
if params.get("reasoning_effort") is not None:
response_params["reasoning"] = {"effort": params["reasoning_effort"]}
if params.get("verbosity") is not None:
response_params["text"] = {"verbosity": params["verbosity"]}

has_seed = "seed" in params or "random_seed" in params.get("extra_body", {})
if has_seed and not self._responses_seed_skip_logged:
logger.warning(
"OpenAI Responses API does not support seed; skipping it. "
"Reproducibility may be limited."
)
self._responses_seed_skip_logged = True
return response_params

async def _call_responses_api(self, params: Dict[str, Any]) -> str:
responses_client = getattr(self.client, "responses", None)
if responses_client is None:
raise RuntimeError(
"Responses API requires an OpenAI SDK with client.responses support; "
"upgrade the 'openai' package."
)
response_params = self._build_responses_params(params)
response = await responses_client.create(**response_params, stream=False)
if isinstance(response, str):
raise ValueError(
"LLM endpoint returned a raw string instead of a Responses API object "
f"(streaming responses are not supported): {response[:200]!r}"
)

content = getattr(response, "output_text", "") or ""
status = getattr(response, "status", None)
incomplete_details = getattr(response, "incomplete_details", None)
incomplete_reason = getattr(incomplete_details, "reason", None)
finish_reason = "stop" if status in (None, "completed") else str(status)
if status == "incomplete" and incomplete_reason == "max_output_tokens":
finish_reason = "length"

logger.debug(f"API parameters: {response_params}")
logger.debug(f"API response: {content}")
if finish_reason == "length":
logger.warning(
f"Response from {self.model} was cut off at the token limit "
f"(finish_reason=length, max_output_tokens={response_params.get('max_output_tokens')}). "
"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, "input_tokens", 0) or 0
completion_tokens = getattr(usage, "output_tokens", 0) or 0
total_tokens = getattr(usage, "total_tokens", 0) or (prompt_tokens + completion_tokens)
self.last_usage = {
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": total_tokens,
"model": str(self.model),
"finish_reason": finish_reason,
}
logger.info(
f"LLM Token Usage ({self.model}): "
f"prompt_tokens={prompt_tokens}, "
f"completion_tokens={completion_tokens}, "
f"total_tokens={total_tokens}"
)
else:
self.last_usage = None
logger.info(f"LLM Token Usage ({self.model}): usage info not returned by API")

if not content:
raise ValueError("Responses API returned no text content")
return content

async def _manual_wait_for_answer(
self, params: Dict[str, Any], timeout: Optional[Union[int, float]]
) -> str:
Expand Down
Loading
Loading