Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(explain): stop appending a version segment the gateway base already has (#968)
Beenu Arora9878e6672256
diff --git a/services/agents/app/api/explain.py b/services/agents/app/api/explain.pyindex d0f685cba..5aec2ca93 100644--- a/services/agents/app/api/explain.py+++ b/services/agents/app/api/explain.py@@ -118,6 +118,7 @@ from pydantic import BaseModel, Fieldfrom app.core.rate_limit import RateLimitDecision, TokenBucketLimiterfrom app.llm.contract import LLMContractViolation, safe_chat_completions_request+from app.llm.factory import completions_url_for_basefrom app.security.llm_resolver import LlmConfig, resolve_llm_configfrom app.security.tenant_scope import (TenantPrincipal,@@ -587,8 +588,7 @@ async def _llm_summary(return fallbacktry:- base = llm_config.base_url.rstrip("/")- url = f"{base}/v1/chat/completions"+ url = completions_url_for_base(llm_config.base_url)model = llm_config.modeltech_lines = [f"- {t['id']} {t['name']} ({', '.join(t.get('tactic_names') or []) or 'unknown tactic'})" for t in mitre_techs]diff --git a/services/agents/app/llm/factory.py b/services/agents/app/llm/factory.pyindex 46a6366a8..1e42a3800 100644--- a/services/agents/app/llm/factory.py+++ b/services/agents/app/llm/factory.py@@ -27,6 +27,7 @@ from __future__ import annotationsimport contextlibimport contextvarsimport os+import refrom collections.abc import Iteratorfrom typing import Any@@ -116,6 +117,35 @@ def chat_completions_url(model: str | None = None) -> str:return DEFAULT_OPENAI_CHAT_COMPLETIONS_URL+#: A trailing OpenAI-compatible API version segment — `/v1`, and `/v2` etc. so+#: the rule does not have to be revisited for a provider that moves on.+_VERSION_SUFFIX = re.compile(r"/v\d+$")+++def completions_url_for_base(base_url: str) -> str:+ """Chat-completions URL for a base the *caller* resolved.++ Mirrors :func:`services.api.app.services.model_aliases.completions_url_for_base`;+ see it for why the suffix is decided rather than assumed.++ :func:`chat_completions_url` above reads the base out of the environment,+ which `/explain` cannot use — its config is layered per tenant, so a BYOK+ base wins over the process one and only the caller knows which applied. It+ built the URL by hand as ``f"{base}/v1/chat/completions"``, and since+ compose sets ``LLM_GATEWAY_URL=http://litellm:4000/v1`` that resolved to+ ``http://litellm:4000/v1/v1/chat/completions`` and 404'd against the+ gateway running beside it.+ """+ base = (base_url or "").strip().rstrip("/")+ if not base:+ return DEFAULT_OPENAI_CHAT_COMPLETIONS_URL+ if base.endswith("/chat/completions"):+ return base+ if _VERSION_SUFFIX.search(base):+ return f"{base}/chat/completions"+ return f"{base}/v1/chat/completions"++def make_chat_model(role: str,*,diff --git a/services/api/app/services/alert_explain.py b/services/api/app/services/alert_explain.pyindex 1990bdb36..9238e8493 100644--- a/services/api/app/services/alert_explain.py+++ b/services/api/app/services/alert_explain.py@@ -60,6 +60,7 @@ from app.models.detection_rule import DetectionRulefrom app.services.cost_dashboard import _impute_public_costfrom app.services.llm_resolver import LlmConfig, resolve_llm_configfrom app.services.llm_safety import LLMContractViolation, safe_chat_completions_request+from app.services.model_aliases import completions_url_for_baselogger = logging.getLogger(__name__)@@ -687,8 +688,7 @@ async def _call_llm_for_summary(metadata into ``aisoc_run_costs``."""started = time.monotonic()- base = llm_config.base_url.rstrip("/")- url = f"{base}/v1/chat/completions"+ url = completions_url_for_base(llm_config.base_url)prompt_alert = {"title": alert.title,diff --git a/services/api/app/services/model_aliases.py b/services/api/app/services/model_aliases.pyindex 3dd0f271f..255c4b271 100644--- a/services/api/app/services/model_aliases.py+++ b/services/api/app/services/model_aliases.py@@ -15,6 +15,7 @@ agents-side pins), or set a global ``LLM_MODEL`` at the call site.from __future__ import annotationsimport os+import re# Mirrors the roles in services/agents/app/llm/model_pins.py.ROLES = frozenset({"triage", "recon", "investigation", "copilot", "summary", "report", "nl", "hunt"})@@ -22,6 +23,10 @@ ROLES = frozenset({"triage", "recon", "investigation", "copilot", "summary", "reDEFAULT_OPENAI_CHAT_COMPLETIONS_URL = "https://api.openai.com/v1/chat/completions"+#: A trailing OpenAI-compatible API version segment — `/v1`, and `/v2` etc. so+#: the rule does not have to be revisited for a provider that moves on.+_VERSION_SUFFIX = re.compile(r"/v\d+$")+#: See :data:`services.agents.app.llm.routing.GATEWAY_ALIAS_PREFIX`.GATEWAY_ALIAS_PREFIX = "aisoc-"@@ -133,3 +138,36 @@ def chat_completions_url(model: str | None = None) -> str:if base:return base.rstrip("/") + "/chat/completions"return DEFAULT_OPENAI_CHAT_COMPLETIONS_URL+++def completions_url_for_base(base_url: str) -> str:+ """Chat-completions URL for a base the *caller* resolved.++ :func:`chat_completions_url` reads the base out of the environment, which+ the explain paths cannot use: theirs is layered per tenant, so a BYOK base+ wins over the process one and only the caller knows which applied.++ They therefore built the URL by hand, with ``f"{base}/v1/chat/completions"``+ — a different convention from the one every other caller uses. Compose+ sets ``LLM_GATEWAY_URL=http://litellm:4000/v1``, so against the bundled+ gateway that produced::++ http://litellm:4000/v1/v1/chat/completions -> 404++ and the explain path reported ``llm_used: false`` and served its+ deterministic template instead. Honest, and never once reaching the model+ that was running beside it.++ So the suffix is decided by what the base already carries rather than+ assumed: a base that ends in a version segment takes ``/chat/completions``,+ and a bare host takes ``/v1/chat/completions`` so a BYOK value like+ ``https://api.openai.com`` still resolves.+ """+ base = (base_url or "").strip().rstrip("/")+ if not base:+ return DEFAULT_OPENAI_CHAT_COMPLETIONS_URL+ if base.endswith("/chat/completions"):+ return base+ if _VERSION_SUFFIX.search(base):+ return f"{base}/chat/completions"+ return f"{base}/v1/chat/completions"diff --git a/services/api/tests/test_explain_completions_url.py b/services/api/tests/test_explain_completions_url.pynew file mode 100644index 000000000..0b2e34770--- /dev/null+++ b/services/api/tests/test_explain_completions_url.py@@ -0,0 +1,99 @@+"""`/explain` must not append a version segment the base already carries.++Both explain paths built their URL by hand:++ base = llm_config.base_url.rstrip("/")+ url = f"{base}/v1/chat/completions"++`docker-compose.yml` sets ``LLM_GATEWAY_URL=http://litellm:4000/v1``, and the+resolver falls back to it whenever no BYOK base is configured — which is the+default install. So the URL came out as++ http://litellm:4000/v1/v1/chat/completions++Measured against a running CORE stack that is a 404, and `/explain` answered+200 with ``llm_used: false`` and this in ``llm_reason``:++ Client error '404 Not Found' for url 'http://litellm:4000/v1/v1/chat/completions'++The deterministic template it served instead is honest, which is why nothing+caught it: the feature reported that no model answered, and the model was+running in the next container.++They could not use ``chat_completions_url``, which resolves the base from the+environment — explain's base is layered per tenant, so a BYOK value wins and+only the caller knows which applied. The answer is not to duplicate the+suffix rule but to decide it from the base: a version segment already there+is not added again, and a bare host still gets one so BYOK keeps working.++Both services are covered from here because both copies must agree; a fix to+one and not the other is the drift this repository keeps finding.+"""++from __future__ import annotations++import pathlib++import pytest+from app.services.model_aliases import completions_url_for_base++#: The compose default, which is the case that was broken.+GATEWAY = "http://litellm:4000/v1"+++class TestTheVersionSegmentIsNotDoubled:+ def test_the_bundled_gateway_base(self) -> None:+ assert completions_url_for_base(GATEWAY) == "http://litellm:4000/v1/chat/completions"++ def test_a_trailing_slash_does_not_change_the_answer(self) -> None:+ assert completions_url_for_base("http://litellm:4000/v1/") == "http://litellm:4000/v1/chat/completions"++ @pytest.mark.parametrize("base", [GATEWAY, "http://litellm:4000/v1/", "https://api.openai.com/v1"])+ def test_no_result_contains_a_doubled_version(self, base: str) -> None:+ assert "/v1/v1/" not in completions_url_for_base(base)+++class TestABareHostStillGetsOne:+ """BYOK values are entered by hand and often omit it."""++ @pytest.mark.parametrize(+ ("base", "expected"),+ [+ ("https://api.openai.com", "https://api.openai.com/v1/chat/completions"),+ ("https://api.openai.com/", "https://api.openai.com/v1/chat/completions"),+ ("http://vllm.internal:8000", "http://vllm.internal:8000/v1/chat/completions"),+ ],+ )+ def test_version_is_appended(self, base: str, expected: str) -> None:+ assert completions_url_for_base(base) == expected+++class TestOtherShapes:+ def test_a_v2_base_is_treated_the_same_way(self) -> None:+ """Written as a rule rather than a literal, so a provider that moves+ on does not reintroduce the bug."""+ assert completions_url_for_base("https://provider.test/v2") == "https://provider.test/v2/chat/completions"++ def test_a_full_endpoint_is_passed_through(self) -> None:+ full = "https://provider.test/v1/chat/completions"+ assert completions_url_for_base(full) == full++ def test_an_empty_base_falls_back_to_the_provider_default(self) -> None:+ assert completions_url_for_base("") == "https://api.openai.com/v1/chat/completions"+ assert completions_url_for_base(" ") == "https://api.openai.com/v1/chat/completions"+++def test_neither_explain_path_builds_the_url_by_hand() -> None:+ """The regression is a string literal, so the gate can look for it.++ Two files had the same hand-rolled suffix. Pinning the helper alone would+ let either of them grow a third copy.+ """+ repo = pathlib.Path(__file__).resolve().parents[3]+ offenders = []+ for rel in ("services/api/app/services/alert_explain.py", "services/agents/app/api/explain.py"):+ text = (repo / rel).read_text(encoding="utf-8")+ for lineno, line in enumerate(text.splitlines(), 1):+ if "/v1/chat/completions" in line and "completions_url_for_base" not in line and not line.lstrip().startswith(("#", "*")):+ offenders.append(f"{rel}:{lineno}: {line.strip()}")+ assert not offenders, "these build the completions URL by hand again:\n " + "\n ".join(offenders)