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
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,11 @@ def _with_profile_llm_and_system_text(
llm: LLM,
system_text: str,
) -> OpenHandsAgentSettings | ACPAgentSettings:
updated = agent_settings.model_copy(update={"llm": llm})
updated = (
agent_settings.model_copy(update={"llm": llm})
if isinstance(agent_settings, OpenHandsAgentSettings)
else agent_settings
)
if not system_text:
return updated

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from openhands.sdk.settings import (
AgentSettingsConfig,
ConversationSettings,
OpenHandsAgentSettings,
apply_agent_settings_diff,
default_agent_settings,
validate_agent_settings,
Expand Down Expand Up @@ -143,7 +144,7 @@ def _deep_merge(
return result


PERSISTED_SETTINGS_SCHEMA_VERSION = 3
PERSISTED_SETTINGS_SCHEMA_VERSION = 4


class PersistedSettings(BaseModel):
Expand Down Expand Up @@ -210,6 +211,8 @@ class PersistedSettings(BaseModel):
@property
def llm_api_key_is_set(self) -> bool:
"""Check if an LLM API key is configured."""
if not isinstance(self.agent_settings, OpenHandsAgentSettings):
return False
raw = self.agent_settings.llm.api_key
if raw is None:
return False
Expand Down Expand Up @@ -390,11 +393,13 @@ def from_persisted(
- **v1**: ``agent_settings`` + ``conversation_settings`` plus
``active_profile``.
- **v2**: adds the opaque ``misc_settings`` container.
- **v3** (current): nested ``agent_settings`` advanced to schema v6
- **v3**: nested ``agent_settings`` advanced to schema v6
(dropped the removed ``llm.modify_params`` field). Nested payloads
are migrated through ``validate_agent_settings`` in
``_normalize_inputs``; the top-level bump keeps the file schema in
step with the nested shape change.
- **v4** (current): nested ``agent_settings`` advanced to schema v7
(dropped the deprecated ``llm`` from ACP settings).
"""
if not isinstance(data, dict):
return cls.model_validate(data, context=context)
Expand Down
22 changes: 16 additions & 6 deletions openhands-agent-server/openhands/agent_server/profiles_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
delete_llm_profile,
rename_llm_profile,
)
from openhands.sdk.settings import OpenHandsAgentSettings
from openhands.sdk.utils.redact import redact_text_secrets


Expand Down Expand Up @@ -455,7 +456,8 @@ async def activate_profile(

This endpoint:
1. Loads the named profile's LLM configuration
2. Applies it to the current agent settings (updates ``agent_settings.llm``)
2. Applies it to the current OpenHands agent settings (updates
``agent_settings.llm``); ACP settings have no LLM to update
3. Records the profile name as the active profile for frontend tracking

Returns 404 if the profile does not exist.
Expand Down Expand Up @@ -483,11 +485,15 @@ async def activate_profile(
)

settings_store = get_settings_store(config)
llm_applied = False

def apply_profile(settings: PersistedSettings) -> PersistedSettings:
settings.agent_settings = settings.agent_settings.model_copy(
update={"llm": llm}
)
nonlocal llm_applied
if isinstance(settings.agent_settings, OpenHandsAgentSettings):
settings.agent_settings = settings.agent_settings.model_copy(
update={"llm": llm}
)
llm_applied = True
settings.active_profile = name
return settings

Expand All @@ -506,6 +512,10 @@ def apply_profile(settings: PersistedSettings) -> PersistedSettings:
logger.info(f"Activated profile '{name}'")
return ActivateProfileResponse(
name=name,
message=f"Profile '{name}' activated and applied to current settings",
llm_applied=True,
message=(
f"Profile '{name}' activated and applied to current settings"
if llm_applied
else f"Profile '{name}' activated"
),
llm_applied=llm_applied,
)
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
ProviderConnectionNotFound,
)
from openhands.sdk.logger import get_logger
from openhands.sdk.settings import OpenHandsAgentSettings


logger = get_logger(__name__)
Expand Down Expand Up @@ -107,7 +108,9 @@ def _linked_profile_names(connection_id: str) -> list[str]:

def _active_settings_references_connection(config, connection_id: str) -> bool:
settings = get_settings_store(config).load()
if settings is None:
if settings is None or not isinstance(
settings.agent_settings, OpenHandsAgentSettings
):
return False
return settings.agent_settings.llm.provider_connection_id == connection_id

Expand Down
34 changes: 25 additions & 9 deletions openhands-agent-server/openhands/agent_server/settings_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
)
from openhands.agent_server.persistence.models import SettingsUpdatePayload
from openhands.agent_server.telemetry import notify_misc_settings_changed
from openhands.sdk.llm import LLM
from openhands.sdk.logger import get_logger
from openhands.sdk.mcp.config import MCPServer
from openhands.sdk.settings import (
Expand Down Expand Up @@ -238,16 +239,15 @@ async def update_settings(
)


def _resolve_active_profile_llm(
def _load_active_profile_llm(
request: Request, update_data: SettingsUpdatePayload
) -> SettingsUpdatePayload:
"""Fold the named profile's LLM into ``agent_settings_diff`` unless the
caller already gave one explicitly. Mirrors ``/activate``."""
) -> LLM | None:
"""Load the named profile's LLM unless the caller already gave one."""
profile_name = update_data.get("active_profile")
agent_diff = update_data.get("agent_settings_diff")
explicit_llm_diff = isinstance(agent_diff, dict) and "llm" in agent_diff
if not profile_name or explicit_llm_diff:
return update_data
return None

cipher = get_cipher(request)
profile_store = get_llm_profile_store()
Expand All @@ -262,13 +262,26 @@ def _resolve_active_profile_llm(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Profile '{profile_name}' not found",
)
return llm


def _with_profile_llm(
update_data: SettingsUpdatePayload,
llm: LLM | None,
settings: PersistedSettings,
) -> SettingsUpdatePayload:
"""Fold the profile's LLM into OpenHands settings. Mirrors ``/activate``."""
agent_diff = update_data.get("agent_settings_diff")
agent_diff = agent_diff if isinstance(agent_diff, dict) else {}
agent_kind = agent_diff.get("agent_kind") or settings.agent_settings.agent_kind
if llm is None or agent_kind == "acp":
return update_data
return cast(
SettingsUpdatePayload,
{
**update_data,
"agent_settings_diff": {
**(agent_diff if isinstance(agent_diff, dict) else {}),
**agent_diff,
"llm": llm.model_dump(mode="json", context={"expose_secrets": True}),
},
},
Expand All @@ -280,14 +293,17 @@ def _apply_settings_update(
update_data: SettingsUpdatePayload,
before_update: Callable[[PersistedSettings], None] | None = None,
) -> SettingsResponse:
update_data = _resolve_active_profile_llm(request, update_data)
profile_llm = _load_active_profile_llm(request, update_data)
applied_update = update_data

# Apply updates atomically with file locking
def apply_update(settings: PersistedSettings) -> PersistedSettings:
nonlocal applied_update
if before_update is not None:
before_update(settings)
context = {"cipher": config.cipher} if config.cipher is not None else None
settings.update(update_data, context=context)
applied_update = _with_profile_llm(update_data, profile_llm, settings)
settings.update(applied_update, context=context)
return settings

config = get_config(request)
Expand All @@ -300,7 +316,7 @@ def apply_update(settings: PersistedSettings) -> PersistedSettings:
"Settings updated",
extra={
"client_host": client_host,
"agent_settings_modified": "agent_settings_diff" in update_data,
"agent_settings_modified": "agent_settings_diff" in applied_update,
"conversation_settings_modified": (
"conversation_settings_diff" in update_data
),
Expand Down
76 changes: 43 additions & 33 deletions openhands-sdk/openhands/sdk/settings/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
ValidationInfo,
field_serializer,
field_validator,
model_validator,
)
from pydantic.fields import FieldInfo

Expand All @@ -54,6 +55,7 @@
from openhands.sdk.plugin import PluginSource
from openhands.sdk.subagent.schema import AgentDefinition
from openhands.sdk.tool import Tool
from openhands.sdk.utils.deprecation import warn_deprecated
from openhands.sdk.utils.pydantic_secrets import (
serialize_secret,
validate_secret,
Expand Down Expand Up @@ -471,7 +473,7 @@ def _default_llm_settings() -> LLM:

_RequestT = TypeVar("_RequestT")

AGENT_SETTINGS_SCHEMA_VERSION = 6
AGENT_SETTINGS_SCHEMA_VERSION = 7
CONVERSATION_SETTINGS_SCHEMA_VERSION = 1


Expand All @@ -486,9 +488,8 @@ class AgentSettingsBase(BaseModel):
- :meth:`create_agent` — canonical construction path; concrete subclasses
must override this.

The ``llm`` field is intentionally *not* hoisted here — its semantics
differ between variants (execution config vs. attribution identity) and
the metadata overrides would make a shared field awkward.
The ``llm`` field is intentionally *not* hoisted here: only
:class:`OpenHandsAgentSettings` calls an LLM.

Use :data:`AgentSettingsConfig` as the type for fields that may hold
either the :class:`OpenHandsAgentSettings` or :class:`ACPAgentSettings`
Expand Down Expand Up @@ -705,6 +706,15 @@ def _migrate_agent_settings_v5_to_v6(payload: dict[str, Any]) -> dict[str, Any]:
return migrated


def _migrate_agent_settings_v6_to_v7(payload: dict[str, Any]) -> dict[str, Any]:
"""Drop the deprecated ``llm`` from ACP settings."""
migrated = dict(payload)
if migrated.get("agent_kind") == "acp":
migrated.pop("llm", None)
migrated["schema_version"] = 7
return migrated


_MCP_OAUTH_TOKEN_COLLECTION = "mcp-oauth-token"
_MCP_OAUTH_CLIENT_INFO_COLLECTION = "mcp-oauth-client-info"
_MCP_OAUTH_TOKEN_EXPIRY_COLLECTION = "mcp-oauth-token-expiry"
Expand Down Expand Up @@ -1001,6 +1011,7 @@ def _migrate_conversation_settings_v0_to_v1(
3: _migrate_agent_settings_v3_to_v4,
4: _migrate_agent_settings_v4_to_v5,
5: _migrate_agent_settings_v5_to_v6,
6: _migrate_agent_settings_v6_to_v7,
}
_CONVERSATION_SETTINGS_MIGRATIONS: dict[int, PersistedSettingsMigrator] = {
0: _migrate_conversation_settings_v0_to_v1,
Expand Down Expand Up @@ -1551,10 +1562,9 @@ class ACPAgentSettings(AgentSettingsBase):
tools, MCP, and (primary) LLM calls; those fields from
:class:`OpenHandsAgentSettings` do not apply here.

``ACPAgent`` uses the :attr:`llm` field purely for cost/token attribution,
never for LLM requests; :attr:`acp_model` is the model identity. Any
credentials set on it (``llm.api_key`` / ``llm.base_url``) are ignored —
provider credentials ride the conversation secrets channel
:attr:`acp_model` is the model identity. The created ``ACPAgent`` keeps its
own metrics LLM, so title generation can tell it is never callable.
Provider credentials ride the conversation secrets channel
(``request.secrets`` / ``agent_context.secrets`` → ``state.secret_registry``)
keyed by the provider's env var name (:attr:`api_key_env_var`).
"""
Expand Down Expand Up @@ -1754,23 +1764,15 @@ class ACPAgentSettings(AgentSettingsBase):
)
llm: LLM = Field(
default_factory=_default_llm_settings,
exclude=True,
description=(
"DEPRECATED (removed in 1.33.0): LLM identity used for cost/token "
"attribution. The ACP subprocess makes its own model calls; "
"``acp_model`` is the model identity. Credentials set here "
"(``api_key`` / ``base_url``) are ignored — route provider "
"credentials through the conversation secrets channel "
"(agent_context.secrets / StartConversationRequest.secrets, which "
"route through state.secret_registry), keyed by the provider's "
"env var name."
"Deprecated since v1.51.0 and scheduled for removal in v1.56.0. "
"Ignored and not serialized: the ACP subprocess makes its own model "
"calls and ``acp_model`` is the model identity. Route provider "
"credentials through the conversation secrets channel, keyed by the "
"provider's env var name."
),
json_schema_extra={
SETTINGS_SECTION_METADATA_KEY: SettingsSectionMetadata(
key="llm",
label="LLM (for metrics)",
variant="acp",
).model_dump()
},
deprecated="ACPAgentSettings.llm is ignored; remove this argument.",
)
agent_context: AgentContext | None = Field(
default=None,
Expand All @@ -1787,6 +1789,19 @@ class ACPAgentSettings(AgentSettingsBase):
),
)

@model_validator(mode="before")
@classmethod
def _warn_deprecated_llm(cls, data: Any) -> Any:
if isinstance(data, Mapping) and "llm" in data:
warn_deprecated(
"ACPAgentSettings.llm",
deprecated_in="1.51.0",
removed_in="1.56.0",
details="It is ignored; remove this argument.",
stacklevel=4,
)
return data

@property
def provider_info(self) -> ACPProviderInfo | None:
"""Registry entry for :attr:`acp_server`, or ``None`` for ``'custom'``."""
Expand Down Expand Up @@ -1915,22 +1930,17 @@ def create_agent(self) -> ACPAgent:
which maps :attr:`acp_server` to a default when no explicit
:attr:`acp_command` is set.

Credentials on :attr:`llm` (``api_key`` / ``base_url``) are ignored:
provider credentials ride the conversation secrets channel
:attr:`llm` is not read: the agent keeps its default ``acp-managed``
metrics LLM, relabelled with :attr:`acp_model` when set. Provider
credentials ride the conversation secrets channel
(``agent_context.secrets`` / ``StartConversationRequest.secrets``,
which route through ``state.secret_registry``) keyed by the
provider's env var name (:attr:`api_key_env_var`), exactly like the
regular agent's credentials, and reach the subprocess from the
registry.
provider's env var name (:attr:`api_key_env_var`), and reach the
subprocess from the registry.
"""
from openhands.sdk.agent import ACPAgent

# Credentials on ``llm`` (api_key / base_url) are intentionally not read:
# provider credentials ride the conversation secrets channel keyed by the
# provider's env var name (#3632). ``llm`` is kept only for cost/token
# attribution; ``acp_model`` is the model identity.
return ACPAgent(
llm=self.llm,
acp_command=self.resolve_acp_command(),
# Carry the authoritative provider key onto the agent: acp_command
# alone does not reliably reverse-map to a provider, so consumers
Expand Down
8 changes: 8 additions & 0 deletions openhands-sdk/openhands/sdk/workspace/remote/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,13 +416,16 @@ def get_llm(self, profile_name: str | None = None, **llm_kwargs: Any) -> "LLM":
FileNotFoundError: If ``profile_name`` does not exist.
httpx.HTTPStatusError: If the API request fails.
RuntimeError: If the workspace host is not set.
ValueError: If no profile is active and the agent settings are for
an ACP agent, which has no LLM.

Example:
>>> with DockerWorkspace(...) as workspace:
... llm = workspace.get_llm(profile_name="fast")
... agent = Agent(llm=llm, tools=get_default_tools())
"""
from openhands.sdk.llm.llm import LLM
from openhands.sdk.settings import OpenHandsAgentSettings

if not self.host or self.host == "undefined":
raise RuntimeError("Workspace host is not set")
Expand All @@ -433,6 +436,11 @@ def get_llm(self, profile_name: str | None = None, **llm_kwargs: Any) -> "LLM":
if resolved_profile_name in (None, ""):
settings_response = self._fetch_settings_response()
agent_settings = settings_response.get_agent_settings()
if not isinstance(agent_settings, OpenHandsAgentSettings):
raise ValueError(
"No LLM profile is active and the agent settings are for "
"an ACP agent, which has no LLM; pass profile_name."
)
if not llm_kwargs:
return agent_settings.llm
llm_data = agent_settings.llm.model_dump(
Expand Down
Loading
Loading