mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-25 09:35:49 +08:00
fix(explain): stop appending a version segment the gateway base already has (#968)
`POST /api/v1/alerts/{id}/explain` answered 200 with `llm_used: false`
on a default install, and served its deterministic template. The reason
was in its own response:
llm_reason: Client error '404 Not Found' for url
'http://litellm:4000/v1/v1/chat/completions'
Both explain paths built the 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 when no BYOK base is configured — which
is every default install. So the version segment was appended to a base
that already carried one, and the call 404'd against the gateway
running in the next container.
Nothing caught it because the failure is honest. `llm_used: false` and
a named reason are exactly what this path should report when no model
answers; they are indistinguishable from a deployment that genuinely
has no model, which is the state the feature was in from the outside.
Neither site could use `chat_completions_url`, which resolves the base
from the environment: explain's config is layered per tenant, so a BYOK
base wins and only the caller knows which applied. `completions_url_for_base`
takes the base the caller already resolved and decides the suffix from
it rather than assuming one — a version segment already present is not
added again, and a bare host still gets one so a BYOK value like
`https://api.openai.com` keeps working. Added to both services, because
one copy fixed and the other not is the drift this keeps producing.
The gate covers the rule and the call sites. Testing only the helper
would pass while either file grew a third hand-rolled copy, so it also
reads both files and refuses a literal `/v1/chat/completions` outside
the helper. Against the pre-fix tree it names both:
services/api/app/services/alert_explain.py:691
services/agents/app/api/explain.py:591
Verified live. Before: `llm_used: false`, 404. After, against the same
alert and the bundled llama3.2:3b, `llm_used: true` and real generated
text — "A high-severity alert from CrowdStrike Falcon indicates that an
encoded PowerShell script was detected in an Office file …" — with the
audit row recording `"llm_used": true` and a cost row written.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
This commit is contained in:
@@ -118,6 +118,7 @@ from pydantic import BaseModel, Field
|
||||
|
||||
from app.core.rate_limit import RateLimitDecision, TokenBucketLimiter
|
||||
from app.llm.contract import LLMContractViolation, safe_chat_completions_request
|
||||
from app.llm.factory import completions_url_for_base
|
||||
from app.security.llm_resolver import LlmConfig, resolve_llm_config
|
||||
from app.security.tenant_scope import (
|
||||
TenantPrincipal,
|
||||
@@ -587,8 +588,7 @@ async def _llm_summary(
|
||||
return fallback
|
||||
|
||||
try:
|
||||
base = llm_config.base_url.rstrip("/")
|
||||
url = f"{base}/v1/chat/completions"
|
||||
url = completions_url_for_base(llm_config.base_url)
|
||||
model = llm_config.model
|
||||
|
||||
tech_lines = [f"- {t['id']} {t['name']} ({', '.join(t.get('tactic_names') or []) or 'unknown tactic'})" for t in mitre_techs]
|
||||
|
||||
@@ -27,6 +27,7 @@ from __future__ import annotations
|
||||
import contextlib
|
||||
import contextvars
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Iterator
|
||||
from 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,
|
||||
*,
|
||||
|
||||
@@ -60,6 +60,7 @@ from app.models.detection_rule import DetectionRule
|
||||
from app.services.cost_dashboard import _impute_public_cost
|
||||
from app.services.llm_resolver import LlmConfig, resolve_llm_config
|
||||
from app.services.llm_safety import LLMContractViolation, safe_chat_completions_request
|
||||
from app.services.model_aliases import completions_url_for_base
|
||||
|
||||
logger = 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,
|
||||
|
||||
@@ -15,6 +15,7 @@ agents-side pins), or set a global ``LLM_MODEL`` at the call site.
|
||||
from __future__ import annotations
|
||||
|
||||
import 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", "re
|
||||
|
||||
DEFAULT_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"
|
||||
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user