Skip to content
13 changes: 5 additions & 8 deletions docs/reference/environment-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,16 @@ This page documents all environment variables that can be used to configure Holm

## LLM Tool Calling Configuration

### LLMS_WITH_STRICT_TOOL_CALLS
**Default:** `"azure/gpt-4.1, openai/*"`
### HOLMES_DISABLE_STRICT_TOOL_CALLS
**Default:** `false`

Comma-separated list of model patterns that support strict tool calling. When a model matches one of these patterns, HolmesGPT will:
- Enable the `strict` flag for function definitions
- Set `additionalProperties: false` in tool parameter schemas
- Enforce stricter schema validation for tool calls
When set to `true`, disables strict tool calling for all models. By default, strict mode is enabled universally — HolmesGPT sets `strict: true` and `additionalProperties: false` on all tool schemas. This prevents LLMs from hallucinating parameter names or sending malformed arguments.

This improves reliability of tool calling for supported models by ensuring the LLM adheres more strictly to the defined tool schemas.
Tools with dynamic-key parameters (`additionalProperties` with a schema, e.g., filter maps) are automatically excluded from strict mode on a per-tool basis, since both OpenAI and Anthropic require `additionalProperties: false` on all objects in strict mode.

**Example:**
```bash
export LLMS_WITH_STRICT_TOOL_CALLS="azure/gpt-4.1,openai/*,anthropic/claude-sonnet-4*"
export HOLMES_DISABLE_STRICT_TOOL_CALLS=true
```

### TOOL_SCHEMA_NO_PARAM_OBJECT_IF_NO_PARAMS
Expand Down
4 changes: 1 addition & 3 deletions holmes/common/env_vars.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,7 @@ def load_bool(env_var, default: Optional[bool]) -> Optional[bool]:
TOOL_CALL_SAFEGUARDS_ENABLED = load_bool("TOOL_CALL_SAFEGUARDS_ENABLED", True)
IS_OPENSHIFT = load_bool("IS_OPENSHIFT", False)

LLMS_WITH_STRICT_TOOL_CALLS = os.environ.get(
"LLMS_WITH_STRICT_TOOL_CALLS", "azure/gpt-4o, openai/*"
)
STRICT_TOOL_CALLS_ENABLED = not load_bool("HOLMES_DISABLE_STRICT_TOOL_CALLS", False)
TOOL_SCHEMA_NO_PARAM_OBJECT_IF_NO_PARAMS = load_bool(
"TOOL_SCHEMA_NO_PARAM_OBJECT_IF_NO_PARAMS", False
)
Expand Down
37 changes: 27 additions & 10 deletions holmes/core/openai_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,21 @@
from typing import Any, Optional

from holmes.common.env_vars import (
LLMS_WITH_STRICT_TOOL_CALLS,
STRICT_TOOL_CALLS_ENABLED,
TOOL_SCHEMA_NO_PARAM_OBJECT_IF_NO_PARAMS,
)
from holmes.utils.llms import model_matches_list

# parses both simple types: "int", "array", "string"
# but also arrays of those simpler types: "array[int]", "array[string]", etc.
pattern = r"^(array\[(?P<inner_type>\w+)\])|(?P<simple_type>\w+)$"

LLMS_WITH_STRICT_TOOL_CALLS_LIST = [
llm.strip() for llm in LLMS_WITH_STRICT_TOOL_CALLS.split(",")
]

def _is_tool_strict_compatible(tool_parameters: dict) -> bool:
"""Check if all parameters in a tool are compatible with strict mode."""
for param in tool_parameters.values():
if hasattr(param, "is_strict_compatible") and not param.is_strict_compatible():
return False
return True


def type_to_open_ai_schema(param_attributes: Any, strict_mode: bool) -> dict[str, Any]:
Expand All @@ -33,8 +36,6 @@ def type_to_open_ai_schema(param_attributes: Any, strict_mode: bool) -> dict[str

if param_type == "object":
type_obj = {"type": "object"}
if strict_mode:
type_obj["additionalProperties"] = False

# Use explicit properties if provided
if hasattr(param_attributes, "properties") and param_attributes.properties:
Expand All @@ -44,6 +45,13 @@ def type_to_open_ai_schema(param_attributes: Any, strict_mode: bool) -> dict[str
}
if strict_mode:
type_obj["required"] = list(param_attributes.properties.keys())
type_obj["additionalProperties"] = False

# Preserve additionalProperties schema for dynamic-key objects
elif hasattr(param_attributes, "additional_properties") and param_attributes.additional_properties not in (None, False):
type_obj["additionalProperties"] = param_attributes.additional_properties
elif strict_mode:
type_obj["additionalProperties"] = False

elif param_type == "array":
# Handle arrays with explicit item schemas
Expand Down Expand Up @@ -72,6 +80,11 @@ def type_to_open_ai_schema(param_attributes: Any, strict_mode: bool) -> dict[str
else:
type_obj = {"type": match.group("simple_type")}

# Merge passthrough JSON Schema keywords (minItems, maxItems, minimum, etc.)
# so the LLM sees validation constraints from the source schema.
if type_obj and hasattr(param_attributes, "json_schema_extra") and param_attributes.json_schema_extra:
type_obj.update(param_attributes.json_schema_extra)

# Add nullability using anyOf per the OpenAI Structured Outputs spec when strict mode
# requires optional params to accept null, or when the source schema explicitly marks
# the field as nullable (e.g., MCP ["string", "null"]).
Expand All @@ -82,11 +95,15 @@ def type_to_open_ai_schema(param_attributes: Any, strict_mode: bool) -> dict[str


def format_tool_to_open_ai_standard(
tool_name: str, tool_description: str, tool_parameters: dict, target_model: str
tool_name: str, tool_description: str, tool_parameters: dict
):
tool_properties = {}
# Strict mode is enabled globally unless disabled via HOLMES_DISABLE_STRICT_TOOL_CALLS.
# However, tools with dynamic-key objects (additionalProperties with a schema) are
# automatically excluded from strict mode since both OpenAI and Anthropic require
# additionalProperties: false on all objects in strict mode.
strict_mode = STRICT_TOOL_CALLS_ENABLED and _is_tool_strict_compatible(tool_parameters)

strict_mode = model_matches_list(target_model, LLMS_WITH_STRICT_TOOL_CALLS_LIST)
tool_properties = {}

for param_name, param_attributes in tool_parameters.items():
tool_properties[param_name] = type_to_open_ai_schema(
Expand Down
1 change: 0 additions & 1 deletion holmes/core/tool_calling_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,6 @@ def _should_include_restricted_tools(self) -> bool:
def _get_tools(self) -> list:
"""Get tools list, filtering restricted tools based on authorization."""
return self.tool_executor.get_all_tools_openai_format(
target_model=self.llm.model,
include_restricted=self._should_include_restricted_tools(),
)

Expand Down
32 changes: 30 additions & 2 deletions holmes/core/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,35 @@ class ToolParameter(BaseModel):
properties: Optional[Dict[str, "ToolParameter"]] = None # For object types
items: Optional["ToolParameter"] = None # For array item schemas
enum: Optional[List[str]] = None # For restricting to specific values
# For object types: stores the additionalProperties JSON Schema value.
# None = not specified, False = no additional properties allowed,
# dict = schema for dynamic key-value maps (e.g. Dict[str, str])
additional_properties: Optional[Union[bool, Dict[str, Any]]] = None
# JSON Schema validation keywords (minItems, maxItems, minimum, maximum,
# minLength, maxLength, pattern, etc.) preserved from the source schema.
# These are passed through to the OpenAI-formatted schema so the LLM
# knows about constraints.
json_schema_extra: Optional[Dict[str, Any]] = None

def is_strict_compatible(self) -> bool:
"""Check if this parameter (and all nested parameters) can be used in strict mode.

Strict mode requires additionalProperties: false on all objects.
Parameters with dynamic keys (additionalProperties set to a schema dict or True)
are incompatible with strict mode.
"""
# If this parameter has additionalProperties with a schema or True, it's not strict-compatible
if self.additional_properties is not None and self.additional_properties is not False:
return False
# Recursively check nested properties
if self.properties:
for prop in self.properties.values():
if not prop.is_strict_compatible():
return False
# Recursively check array items
if self.items and not self.items.is_strict_compatible():
return False
return True


class ToolInvokeContext(BaseModel):
Expand Down Expand Up @@ -266,12 +295,11 @@ def model_post_init(self, __context) -> None:
logger.debug(f"Tool '{self.name}' has no transformers")
self._transformer_instances = None

def get_openai_format(self, target_model: str):
def get_openai_format(self):
return format_tool_to_open_ai_standard(
tool_name=self.name,
tool_description=self.description,
tool_parameters=self.parameters,
target_model=target_model,
)

def invoke(
Expand Down
4 changes: 1 addition & 3 deletions holmes/core/tools_utils/tool_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,11 @@ def ensure_toolset_initialized(self, tool_name: str) -> Optional[str]:
@sentry_sdk.trace
def get_all_tools_openai_format(
self,
target_model: str,
include_restricted: bool = True,
):
"""Get all tools in OpenAI format.

Args:
target_model: The target LLM model name
include_restricted: If False, filter out tools marked as restricted.
Set to True when runbook is in use or restricted
tools are explicitly enabled.
Expand All @@ -97,5 +95,5 @@ def get_all_tools_openai_format(
# Filter out restricted tools if not authorized
if not include_restricted and tool._is_restricted():
continue
tools.append(tool.get_openai_format(target_model=target_model))
tools.append(tool.get_openai_format())
return tools
30 changes: 30 additions & 0 deletions holmes/plugins/toolsets/mcp/toolset_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,13 +398,43 @@ def _parse_tool_parameter(

enum = schema.get("enum")

additional_properties = None
raw_ap = schema.get("additionalProperties")
if raw_ap is not None:
if isinstance(raw_ap, bool):
additional_properties = raw_ap
elif isinstance(raw_ap, dict):
# Resolve $ref pointers so the LLM sees concrete types, but
# preserve compound keywords (anyOf/oneOf) intact — _resolve_schema
# collapses those to a single branch which loses type information
# (e.g. string|array becomes just string).
if "$ref" in raw_ap:
additional_properties = cls._resolve_schema(raw_ap, root_schema)
else:
additional_properties = raw_ap

# Capture JSON Schema validation keywords that aren't modeled as
# dedicated ToolParameter fields. These are passed through to the
# OpenAI-formatted schema so the LLM sees constraints like array
# length limits, numeric ranges, and string patterns.
_PASSTHROUGH_KEYWORDS = {
"minItems", "maxItems",
"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum",
"minLength", "maxLength",
"pattern",
"default",
}
json_schema_extra = {k: v for k, v in schema.items() if k in _PASSTHROUGH_KEYWORDS}

return ToolParameter(
description=schema.get("description"),
type=param_type,
required=required,
items=items,
properties=properties,
enum=enum,
additional_properties=additional_properties,
json_schema_extra=json_schema_extra or None,
)

def get_parameterized_one_liner(self, params: Dict) -> str:
Expand Down
2 changes: 1 addition & 1 deletion tests/core/test_todo_write_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def test_task_status_enum(self):
def test_openai_format(self):
"""Test that the tool generates correct OpenAI format."""
tool = TodoWriteTool()
openai_format = tool.get_openai_format("azure/gpt-4o")
openai_format = tool.get_openai_format()

assert openai_format["type"] == "function"
assert openai_format["function"]["name"] == "TodoWrite"
Expand Down
Loading
Loading