Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.
Python ai-agentsaiopsdashboarddockerfastapihomelabincident-managementllmmonitoringopenaireactroot-cause-analysisself-hosteduptime-monitoring
fix(agent): send Claude the tools without strict so diagnoses fit its grammar limit (#200)
Karlo Kajba Šimanić5bf3c410b9ad
diff --git a/TESTS.md b/TESTS.mdindex 7f875fe..b25fc49 100644--- a/TESTS.md+++ b/TESTS.md@@ -325,7 +325,7 @@ shouldn't, or an admin might be locked out.|---|---|| `test_without_a_tool_budget_the_chat_is_one_call_without_tools` | With the chat's look-up budget at 0, a message is one call to the model, with no tools and effort `low`. || `test_a_reply_without_a_message_is_an_error` | A reply whose message is missing or empty is an error, not a blank answer. |-| `test_test_connection_tries_one_request_shaped_like_a_diagnosis_and_counts_it` | Test connection checks the key, then sends one request with every tool and the diagnosis schema (tools not allowed), counts it as a `test` call, and raises the provider's refusal (#196). |+| `test_test_connection_tries_one_request_shaped_like_a_diagnosis_and_counts_it` | Test connection checks the key, then sends one request exactly as a diagnosis does (every tool, calls allowed, the diagnosis schema), counts it as a `test` call, and raises the provider's refusal (#196, #199). || `test_the_reply_can_only_be_a_message` | The reply schema has one field, the message, and nothing else is allowed. || `test_the_chat_completions_provider_asks_for_the_reply_schema_and_reports_tokens` | Requests to the Chat Completions provider (Gemini) use Structured Outputs in strict mode with the reply schema, and token usage is read from the response. || `test_a_refusal_is_an_error_not_an_empty_reply` | When the model refuses, the chat gets an error instead of an empty answer. |@@ -358,7 +358,7 @@ request.|---|---|| `test_with_tools_the_model_can_still_answer_at_once` *(3 inputs)* | With tools offered, a model that answers straight away gives the final answer and its token usage. || `test_a_tool_call_is_answered_and_the_history_goes_back_unchanged` *(3 inputs)* | A tool call comes back parsed; after its result, the next request repeats every earlier turn exactly as sent and adds the result. |-| `test_claude_gets_its_own_answer_back_untouched_thinking_included` | Claude's own turn, thinking included, goes back unchanged; its tools are strict and the system prompt is sent apart. |+| `test_claude_gets_its_own_answer_back_untouched_thinking_included` | Claude's own turn, thinking included, goes back unchanged; its tools are sent without `strict` (#199) and the system prompt apart. || `test_several_tool_calls_in_one_turn_get_all_their_results` *(3 inputs)* | Several calls in one turn are all answered: in one message for Claude, one `function_call_output` item each for OpenAI, one tool message each for Gemini. || `test_a_failed_tool_is_reported_as_an_error` *(3 inputs)* | A failed tool is marked as an error for the model. || `test_tool_results_are_masked_before_they_leave` *(3 inputs)* | A password in a tool result is masked before it is sent to the provider. |@@ -453,7 +453,7 @@ and a firewall.| Test | What it checks ||---|---|| `test_no_request_has_more_union_typed_parameters_than_the_provider_accepts` *(2 inputs)* | The tools have no nullable or union-typed parameter, and with the diagnosis or chat schema a request stays within Anthropic's limit of 16 (#196). |-| `test_an_optional_argument_left_empty_or_null_means_not_given` | An optional argument sent as an empty string or null gives the same result (not given); a required one may not be empty. |+| `test_an_optional_argument_left_empty_or_null_means_not_given` | An optional argument sent as an empty string, null or left out gives the same result (not given); a required one may not be empty or left out. || `test_every_tool_is_listed_once_with_a_strict_schema` | The eleven tools are each listed once, every schema is strict (all fields required, nothing extra allowed), and every host metric offered can be read. || `test_an_unknown_tool_is_refused` | A call to a tool that isn't on the list (`run_shell`) is refused. || `test_bad_arguments_are_refused_with_a_reason_the_model_can_act_on` *(17 inputs)* | Missing or extra arguments, wrong types, values outside a list, oversized text, bad or reversed times, windows older than 90 days, container snapshots older than 7 days, and unknown checks or containers are refused before anything is read, with a reason (and the names that do exist). |diff --git a/docs/agent-investigation.md b/docs/agent-investigation.mdindex 008183c..70eeca8 100644--- a/docs/agent-investigation.md+++ b/docs/agent-investigation.md@@ -77,7 +77,8 @@ In more detail:`SYSTEM_PROMPT.md`), the message, the list of tools, and the JSON schema the final answer must follow. Withtools offered the model thinks harder (effort `high`; Claude and OpenAI use it). Optional arguments are plainstrings where empty means "not given", because providers limit nullable parameters in strict schemas (#196);- **Test connection** in Admin sends one request of this shape, so a provider that refuses it says so at once.+ **Test connection** in Admin sends one request of exactly this shape (calls allowed), so a provider that refuses+ it says so at once (#199).3. **The model takes a step.** It either answers, or asks for one or more tool calls. Each call is a tool name andarguments that follow the tool's schema, including `reason`: one sentence saying what the call should find out,written before any result exists.@@ -160,7 +161,8 @@ server's data (its history, ports, firewall) to the provider. Every change is in## What is checked-**Before a call runs** (`tools.run`): the tool exists; the arguments match its schema exactly; strings are+**Before a call runs** (`tools.run`): the tool exists; the arguments match its schema exactly (an optional+argument left out counts as empty, since Claude gets the tools without `strict`, see [Incident agent](assistant.md#chat)); strings arenon-empty and at most 200 characters, lists at most 12 items; the server, container or check exists (otherwise themodel is told the names it may use); windows lie within the last 90 days.diff --git a/docs/assistant.md b/docs/assistant.mdindex 5f448b7..f5dc577 100644--- a/docs/assistant.md+++ b/docs/assistant.md@@ -26,8 +26,9 @@ change files on your servers. Everything about it is in `src/agent/` and in **AdAnother model works if it supports structured (JSON schema) output and tool calls. With OpenAI it must be areasoning model (the gpt-5 family and later): the agent sets how hard it thinks.4. **Test connection** checks the key, that the model exists, and that the provider accepts the agent's real- requests: one small request with every tool and the diagnosis schema. It costs a few thousand tokens (about- 2 000 to 4 500 in our tests), counted in the usage like any other call. Run it after changing the provider or+ requests: one small request exactly as a diagnosis sends it, with every tool (calls allowed, though the model is+ told not to make any, and one it makes anyway isn't run) and the diagnosis schema. It costs a few thousand tokens+ (about 2 000 to 5 000 in our tests), counted in the usage like any other call. Run it after changing the provider orthe model; a provider that refuses the request says why here, instead of every diagnosis failing later.5. Enter the model's price per million tokens under **Prices** (from the provider's pricing page), so its callscount towards the budget, and set a **Monthly budget** if you want one.@@ -119,7 +120,9 @@ facts and the conversation so far (its latest 40 turns), and the model may lookquestions and replies stay in the conversation; the look-ups of an earlier message aren't sent again. Under a replythat used tools, **Looked up** (folded away) shows them the same way as in a diagnosis, and stays after a reload. Every replyis held to a JSON schema with the provider's structured output: one message. All three providers sit behind one-small interface (`src/agent/providers/`): Claude through Anthropic's Messages API; OpenAI through its Responses API+small interface (`src/agent/providers/`): Claude through Anthropic's Messages API, with the tools sent without+`strict` (Anthropic compiles strict tools and the strict answer schema into one grammar whose size limit the agent's+tools exceed; the answer stays strict and the backend checks every call itself); OpenAI through its Responses API(the only one where its reasoning models can use tools), sent with `store: false` so nothing is kept at OpenAI, withthe model's reasoning carried from one step to the next in encrypted form; Gemini through Google's OpenAI-compatibleChat Completions endpoint.@@ -195,7 +198,9 @@ facts each carry an `id` added with `facts.add`. Register it in `tools/__init__.strict schema (every property required, `additionalProperties: false`, and an optional text argument made with`_optional`, a plain string where empty means "not given", never a nullable type: Anthropic refuses strict schemaswith more than 16 nullable or union-typed parameters per request, counted over every tool and the answer's schema,-and `test_no_request_has_more_union_typed_parameters_than_the_provider_accepts` checks it), and add tests to+and `test_no_request_has_more_union_typed_parameters_than_the_provider_accepts` checks it). After adding a tool, run+**Test connection** with Claude: the size of the grammar its answer schema compiles to has a limit that no local test+can check. Add tests to`tests/assistant/test_agent_tools.py`: the shared tests then check that it stays bounded, masked, labelled andread-only.diff --git a/src/agent/chat.py b/src/agent/chat.pyindex f03bc21..8752233 100644--- a/src/agent/chat.py+++ b/src/agent/chat.py@@ -127,14 +127,16 @@ TRIAL_MESSAGES = [{"role": "system", "content": "This is a connection test. Do ndef check_provider_connection(db, user_id: int | None = None) -> dict:"""For Admin's "Test connection": the key works, the configured model exists, and the provider accepts a- request shaped like a diagnosis: every tool and the diagnosis schema, tools not allowed (#196). That one request+ request shaped like a diagnosis: every tool and the diagnosis schema, calls allowed (#196, #199). That one requestis the only thing here that costs tokens (a few thousand, mostly the tools' definitions), and it iscounted in the usage like any other (kind ``test``). Raises the provider's error when it is refused."""provider = get_provider(db)found = provider.check()started = time.monotonic()try:- completion = provider.start(TRIAL_MESSAGES, tools.TOOLS, diagnosis.SCHEMA, "incident_diagnosis", effort="low").step(allow_tools=False).completion+ # Calls allowed, as in a diagnosis: Anthropic only compiles the tools' grammar then (#199). A call the model+ # makes anyway is not run.+ completion = provider.start(TRIAL_MESSAGES, tools.TOOLS, diagnosis.SCHEMA, "incident_diagnosis", effort="low").step(allow_tools=True).completionexcept Exception as exc:usage.record(db, kind="test", status="error", model=provider.model, user_id=user_id, duration_ms=round((time.monotonic() - started) * 1000), error=f"{type(exc).__name__}: {exc}")raisediff --git a/src/agent/providers/claude.py b/src/agent/providers/claude.pyindex ba43545..a29d232 100644--- a/src/agent/providers/claude.py+++ b/src/agent/providers/claude.py@@ -33,7 +33,10 @@ class ClaudeConversation(Conversation):self.provider, self.schema, self.effort = provider, schema, effortself.system = "\n\n".join(message["content"] for message in messages if message["role"] == "system")self.history = [{"role": message["role"], "content": message["content"]} for message in messages if message["role"] != "system"]- self.tools = [{"name": tool.name, "description": tool.description, "input_schema": tool.schema, "strict": True} for tool in tools]+ # Not strict: Anthropic compiles strict tools and the strict answer schema into one grammar with an unpublished+ # size limit, and the agent's tools with the diagnosis schema are over it (#199). The answer stays strict, and+ # the backend checks every call's arguments itself (tools._check), so a malformed call goes back as an error.+ self.tools = [{"name": tool.name, "description": tool.description, "input_schema": tool.schema} for tool in tools]def step(self, allow_tools: bool = True) -> Turn:extra = {"tools": self.tools, "tool_choice": {"type": "auto" if allow_tools else "none"}} if self.tools else {}diff --git a/src/agent/tools/__init__.py b/src/agent/tools/__init__.pyindex bb0745d..37f9e53 100644--- a/src/agent/tools/__init__.py+++ b/src/agent/tools/__init__.py@@ -174,6 +174,9 @@ def run(db, name: str, arguments, now: datetime | None = None) -> Output:if name not in _REGISTRY:raise ToolError(f"There is no tool named {str(name)[:60]!r}.")tool, handler = _REGISTRY[name]+ if isinstance(arguments, dict):+ # A model without strict tools (Claude, #199) may leave out an optional argument: that is "not given" too.+ arguments = {**{key: None for key, schema in tool.schema["properties"].items() if isinstance(schema, _Optional)}, **arguments}_check(tool.schema, arguments, "arguments")# An optional argument left empty reaches the tool as None, whether the model sent "" or null.arguments = {key: None if isinstance(tool.schema["properties"][key], _Optional) and _blank(value) else value for key, value in arguments.items()}diff --git a/tests/assistant/test_agent_service.py b/tests/assistant/test_agent_service.pyindex 391c3f2..73d007f 100644--- a/tests/assistant/test_agent_service.py+++ b/tests/assistant/test_agent_service.py@@ -26,6 +26,7 @@ def test_a_reply_without_a_message_is_an_error():def test_test_connection_tries_one_request_shaped_like_a_diagnosis_and_counts_it(monkeypatch):+ # A call the model makes anyway is not run: the result comes from the first step only.from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmakerfrom sqlalchemy.pool import StaticPool@@ -43,7 +44,7 @@ def test_test_connection_tries_one_request_shaped_like_a_diagnosis_and_counts_itassert result == {"provider": "Anthropic", "model": "claude-test", "tokens": 3140}assert provider.started[0]["tools"] == [tool.name for tool in tools.TOOLS] and provider.started[0]["schema_name"] == "incident_diagnosis"- assert provider.allowed == [False] # the tools are listed, as in a diagnosis, but not called+ assert provider.allowed == [True] # exactly as a diagnosis sends it: Anthropic only checks the tools' grammar then (#199)run = db.query(AgentRun).one()assert (run.kind, run.status, run.input_tokens, run.user_id) == ("test", "ok", 3100, 1)diff --git a/tests/assistant/test_agent_tool_calls.py b/tests/assistant/test_agent_tool_calls.pyindex 5f11bae..c94dc35 100644--- a/tests/assistant/test_agent_tool_calls.py+++ b/tests/assistant/test_agent_tool_calls.py@@ -149,7 +149,8 @@ def test_claude_gets_its_own_answer_back_untouched_thinking_included():assistant = fake.sent(1)[1]assert assistant["role"] == "assistant" and assistant["content"][0].type == "thinking"tool = fake.calls[0]["tools"][0]- assert tool["strict"] is True and tool["input_schema"] == TOOLS[0].schema and fake.calls[0]["system"] == "You are the agent."+ # Claude's tools aren't strict (its compiled grammar has a size limit the agent's tools exceed, #199); the answer is.+ assert "strict" not in tool and tool["input_schema"] == TOOLS[0].schema and fake.calls[0]["system"] == "You are the agent."@pytest.mark.parametrize("build, Fake", PROVIDERS)diff --git a/tests/assistant/test_agent_tools.py b/tests/assistant/test_agent_tools.pyindex 67b7476..fcc6ba0 100644--- a/tests/assistant/test_agent_tools.py+++ b/tests/assistant/test_agent_tools.py@@ -135,8 +135,12 @@ def test_an_optional_argument_left_empty_or_null_means_not_given(db):null = run(db, "host_metrics", {"server": "web1", "metrics": ["cpu"], "from": None, "to": None}, now=NOW)assert empty.content == null.content and json.loads(empty.content)["to"] == "2026-11-07T12:00+00:00"+ left_out = run(db, "host_metrics", {"server": "web1", "metrics": ["cpu"]}, now=NOW) # a model without strict tools may omit them+ assert left_out.content == null.contentwith pytest.raises(tools.ToolError, match="non-empty"):run(db, "server_info", {"server": ""}, now=NOW) # a required one may not be empty+ with pytest.raises(tools.ToolError, match="Give exactly"):+ run(db, "host_metrics", {"server": "web1", "from": None, "to": None}, now=NOW) # nor left outdef test_an_unknown_tool_is_refused(db):