Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
8 changes: 7 additions & 1 deletion holmes/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ class SupportedTicketSources(str, Enum):

class Config(RobustaBaseConfig):
model: Optional[str] = None
api_key: Optional[SecretStr] = (
None # if None, read from OPENAI_API_KEY or AZURE_OPENAI_ENDPOINT env var
)
api_base: Optional[str] = None
api_version: Optional[str] = None
fast_model: Optional[str] = None
Expand Down Expand Up @@ -441,7 +444,8 @@ def create_slack_destination(self) -> "SlackDestination":
# TODO: move this to the llm model registry
def _get_llm(self, model_key: Optional[str] = None, tracer=None) -> "DefaultLLM":
sentry_sdk.set_tag("requested_model", model_key)
model_params = self.llm_model_registry.get_model_params(model_key)
model_entry = self.llm_model_registry.get_model_params(model_key)
model_params = model_entry.model_dump(exclude_none=True)
api_base = self.api_base
api_version = self.api_version

Expand All @@ -453,6 +457,8 @@ def _get_llm(self, model_key: Optional[str] = None, tracer=None) -> "DefaultLLM"
api_key = f"{account_id} {token}"
else:
api_key = model_params.pop("api_key", None)
if api_key is not None:
api_key = api_key.get_secret_value()

model = model_params.pop("model")
# It's ok if the model does not have api base and api version, which are defaults to None.
Expand Down
92 changes: 64 additions & 28 deletions holmes/core/llm.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
import json
import logging
import os
from abc import abstractmethod
from math import floor
from typing import Any, Dict, List, Optional, Type, Union, TYPE_CHECKING
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union

from litellm.types.utils import ModelResponse, TextCompletionResponse
import litellm
import sentry_sdk

from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper
from pydantic import BaseModel
import litellm
import os
from litellm.types.utils import ModelResponse, TextCompletionResponse
from pydantic import BaseModel, ConfigDict, SecretStr
from typing_extensions import Self

from holmes.clients.robusta_client import RobustaModelsResponse, fetch_robusta_models
from holmes.common.env_vars import (
FALLBACK_CONTEXT_WINDOW_SIZE,
LOAD_ALL_ROBUSTA_MODELS,
REASONING_EFFORT,
ROBUSTA_AI,
ROBUSTA_API_ENDPOINT,
THINKING,
FALLBACK_CONTEXT_WINDOW_SIZE,
)
from holmes.core.supabase_dal import SupabaseDal
from holmes.utils.env import environ_get_safe_int, replace_env_vars_values
Expand All @@ -37,6 +38,30 @@
ROBUSTA_AI_MODEL_NAME = "Robusta"


class ModelEntry(BaseModel):
"""ModelEntry represents a single LLM model configuration."""

model: str
# TODO: the name field seems to be redundant, can we remove it?
name: Optional[str] = None
Comment thread
moshemorad marked this conversation as resolved.
Resolved
api_key: Optional[SecretStr] = None
base_url: Optional[str] = None
is_robusta_model: Optional[bool] = None
custom_args: Optional[Dict[str, Any]] = None

# LLM configurations used services like Azure OpenAI Service
api_base: Optional[str] = None
api_version: Optional[str] = None

model_config = ConfigDict(
extra="allow",
)

@classmethod
def load_from_dict(cls, data: dict) -> Self:
return cls.model_validate(data)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


class LLM:
@abstractmethod
def __init__(self):
Expand Down Expand Up @@ -400,7 +425,7 @@ def _add_cache_control_to_last_message(
class LLMModelRegistry:
def __init__(self, config: "Config", dal: SupabaseDal) -> None:
self.config = config
self._llms: dict[str, dict[str, Any]] = {}
self._llms: dict[str, ModelEntry] = {}
self._default_robusta_model = None
self.dal = dal

Expand All @@ -422,6 +447,8 @@ def _init_models(self):
model_name=self.config.model,
base_url=self.config.api_base,
is_robusta_model=False,
api_key=self.config.api_key,
api_version=self.config.api_version,
)

def _should_load_config_model(self) -> bool:
Expand Down Expand Up @@ -474,13 +501,12 @@ def configure_robusta_ai_model(self) -> None:
def _load_default_robusta_config(self):
if self._should_load_robusta_ai():
logging.info("Loading default Robusta AI model")
self._llms[ROBUSTA_AI_MODEL_NAME] = {
"name": ROBUSTA_AI_MODEL_NAME,
"base_url": ROBUSTA_API_ENDPOINT,
"is_robusta_model": True,
# TODO: tech debt, this isn't really gpt-4o at all
"model": "gpt-4o",
}
self._llms[ROBUSTA_AI_MODEL_NAME] = ModelEntry(
name=ROBUSTA_AI_MODEL_NAME,
model="gpt-4o", # TODO: tech debt, this isn't really
base_url=ROBUSTA_API_ENDPOINT,
is_robusta_model=True,
)
self._default_robusta_model = ROBUSTA_AI_MODEL_NAME

def _should_load_robusta_ai(self) -> bool:
Expand All @@ -502,7 +528,7 @@ def _should_load_robusta_ai(self) -> bool:

return True

def get_model_params(self, model_key: Optional[str] = None) -> dict:
def get_model_params(self, model_key: Optional[str] = None) -> ModelEntry:
if not self._llms:
raise Exception("No llm models were loaded")

Expand Down Expand Up @@ -534,27 +560,31 @@ def get_llm(self, name: str) -> LLM: # TODO: fix logic
return self._llms[name] # type: ignore

@property
def models(self) -> dict[str, dict[str, Any]]:
def models(self) -> dict[str, ModelEntry]:
return self._llms

def _parse_models_file(self, path: str):
def _parse_models_file(self, path: str) -> dict[str, ModelEntry]:
models = load_yaml_file(path, raise_error=False, warn_not_found=False)
for _, params in models.items():
params = replace_env_vars_values(params)

return models
llms = {}
for model_name, params in models.items():
llms[model_name] = ModelEntry.model_validate(params)

return llms

def _create_robusta_model_entry(
self, model_name: str, args: Optional[dict[str, Any]] = None
) -> dict[str, Any]:
) -> ModelEntry:
entry = self._create_model_entry(
# TODO: tech debt, this isn't really gpt-4o at all (wont token counts be wrong etc)
model="gpt-4o", # Robusta AI model is using openai like API.
model_name=model_name,
base_url=f"{ROBUSTA_API_ENDPOINT}/llm/{model_name}",
is_robusta_model=True,
)
entry["custom_args"] = args or {} # type: ignore[assignment]
entry.custom_args = args or {}
return entry

def _create_model_entry(
Expand All @@ -563,13 +593,19 @@ def _create_model_entry(
model_name: str,
base_url: Optional[str] = None,
is_robusta_model: Optional[bool] = None,
) -> dict[str, Any]:
return {
"name": model_name,
"base_url": base_url,
"is_robusta_model": is_robusta_model,
"model": model,
}
api_key: Optional[SecretStr] = None,
api_base: Optional[str] = None,
api_version: Optional[str] = None,
) -> ModelEntry:
return ModelEntry(
name=model_name,
model=model,
base_url=base_url,
is_robusta_model=is_robusta_model,
api_key=api_key,
api_base=api_base,
api_version=api_version,
)


def get_llm_usage(
Expand Down
29 changes: 28 additions & 1 deletion tests/config_class/test_config_api_base_version.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from unittest.mock import MagicMock, patch

import yaml
from unittest.mock import patch, MagicMock

from holmes.config import Config

Expand Down Expand Up @@ -56,6 +57,32 @@ def test_config_get_llm_with_api_base_version():
assert result == mock_llm_instance


def test_config_get_llm_with_azure_openai_parameters():
"""Test that Config._get_llm passes api_base and api_version to DefaultLLM."""
config = Config(
model="azure/gpt-4o",
api_key="test-key",
api_base="https://test.api.base",
api_version="2023-12-01",
)

with patch("holmes.config.DefaultLLM") as mock_default_llm:
mock_llm_instance = MagicMock()
mock_default_llm.return_value = mock_llm_instance

result = config._get_llm()

# Check that DefaultLLM was called with the right positional arguments
call_args = mock_default_llm.call_args[0]
assert call_args[0] == "azure/gpt-4o"
assert call_args[1] == "test-key"
assert call_args[2] == "https://test.api.base"
assert call_args[3] == "2023-12-01"
assert call_args[4] == {}
assert call_args[5] is None # tracer
assert result == mock_llm_instance


def test_config_get_llm_with_model_list_api_base_version(monkeypatch, tmp_path):
"""Test that api_base and api_version from model list are passed to DefaultLLM."""
temp_config_file = tmp_path / "model_list.yaml"
Expand Down
11 changes: 5 additions & 6 deletions tests/config_class/test_config_load_model_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,24 @@ def test_load_custom_toolsets_config_valid(monkeypatch, tmp_path):
assert isinstance(config.llm_model_registry.models, dict)
assert len(list(config.llm_model_registry.models.keys())) == 3
az = config.llm_model_registry.models.get("azure")
assert az.get("model") == "test-value"
assert az.model == "test-value"


def test_config_load_model_list_valid_with_robusta_ai(server_config: Config):
assert isinstance(server_config.llm_model_registry.models, dict)
assert len(list(server_config.llm_model_registry.models.keys())) == 5
assert (
server_config.llm_model_registry.models["our_local_model"]["model"]
server_config.llm_model_registry.models["our_local_model"].model
== "bedrock/custom_ai_model"
)

sonnet_model = server_config.llm_model_registry.models["Robusta/sonnet-4 preview"]

assert (
sonnet_model.get("base_url")
== f"{ROBUSTA_API_ENDPOINT}/llm/Robusta/sonnet-4 preview"
sonnet_model.base_url == f"{ROBUSTA_API_ENDPOINT}/llm/Robusta/sonnet-4 preview"
)
assert sonnet_model.get("name") == "Robusta/sonnet-4 preview"
assert sonnet_model.get("is_robusta_model")
assert sonnet_model.name == "Robusta/sonnet-4 preview"
assert sonnet_model.is_robusta_model

assert (
server_config.llm_model_registry.default_robusta_model
Expand Down