Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

fix(agents): bound the investigator's completions, and make the bound reach Ollama (#1007)

Beenu Arorae3c7fd300114
diff --git a/services/agents/app/investigator/deep_investigation.py b/services/agents/app/investigator/deep_investigation.py
index b6f4751d5..acda5244a 100644
--- a/services/agents/app/investigator/deep_investigation.py
+++ b/services/agents/app/investigator/deep_investigation.py
@@ -46,6 +46,8 @@ from app.tools.customer_tools import scoped_customer_tools
from app.tools.investigation import investigation_tools
from app.tools.registry import default_registry
+from .limits import max_completion_tokens
+
logger = structlog.get_logger()
#: Off by default is wrong here — a shipped capability nobody enables is the
@@ -475,7 +477,7 @@ async def run_deep_investigation(
tokens_before = governor.spent_tokens(tenant_id)
try:
- model = llm if llm is not None else make_chat_model("investigation")
+ model = llm if llm is not None else make_chat_model("investigation", max_tokens=max_completion_tokens())
registry = default_registry()
for tool in investigation_tools(tenant_id):
diff --git a/services/agents/app/investigator/forensic_agent.py b/services/agents/app/investigator/forensic_agent.py
index 26f41b5bc..4747caf64 100644
--- a/services/agents/app/investigator/forensic_agent.py
+++ b/services/agents/app/investigator/forensic_agent.py
@@ -24,6 +24,7 @@ from app.llm.factory import make_chat_model, resolve_model_alias
from app.prompt_serialization import summarize_structure_for_llm
from .bundle_prompt import format_bundle_prompt_append
+from .limits import max_completion_tokens
from .prompt_sanitizer import (
sanitize_iterable_of_strings,
sanitize_text,
@@ -55,7 +56,7 @@ Respond ONLY with a JSON object:
async def _llm_forensic(state: InvestigatorState) -> dict[str, Any]:
model = resolve_model_alias("investigation")
- llm = make_chat_model("investigation", temperature=0)
+ llm = make_chat_model("investigation", temperature=0, max_tokens=max_completion_tokens())
# Defence-in-depth: alert_summary, recon.summary, and the enrichment cache
# can all carry attacker-controlled strings (banners, dark-web excerpts,
diff --git a/services/agents/app/investigator/limits.py b/services/agents/app/investigator/limits.py
new file mode 100644
index 000000000..12eafe284
--- /dev/null
+++ b/services/agents/app/investigator/limits.py
@@ -0,0 +1,55 @@
+"""How long an investigator agent's reply is allowed to get.
+
+Every LLM call in the four-agent investigator pipeline was placed with no
+completion bound, so a model that failed to stop generated until it hit the
+context window. That is not theoretical: dispatching the pipeline against
+``qwen2.5:0.5b`` on a GitHub-hosted runner produced
+
+ completion_tokens=40960 latency_ms=1208829.8 step=recon
+
+— the model's whole context, twenty minutes, for one call, twice in the same
+investigation. The identical call on a developer machine returned 200 tokens
+in two seconds. Greedy decoding is only deterministic *for a fixed kernel*,
+and a small quantised model that diverges by one token can fall into a
+repetition loop that nothing downstream interrupts.
+
+Unbounded is the wrong default wherever this runs. Against a hosted provider
+it is a 41,000-token bill per degenerate call and an investigation that never
+returns, and the reply is unusable either way: the four agents parse JSON, and
+a reply that ran past the schema was never going to parse.
+
+The bound is deliberately well clear of what the agents legitimately produce.
+Measured over the pipeline's calls on the eval corpus, the largest legitimate
+completion was 876 tokens (the report writer, which writes the longest
+output); recon, forensic and responder sit between 200 and 400. 2048 leaves
+more than double the headroom over the longest real reply, so it truncates
+nothing the agents actually emit and stops a runaway inside a few seconds.
+
+Override with ``AISOC_INVESTIGATOR_MAX_COMPLETION_TOKENS`` for a deployment
+running a model whose replies are genuinely longer. Zero or negative removes
+the bound, which is the pre-existing behaviour and has to stay reachable —
+but it is now a decision somebody makes rather than the default.
+"""
+
+from __future__ import annotations
+
+import os
+
+#: Headroom over the longest legitimate reply measured on the eval corpus.
+DEFAULT_MAX_COMPLETION_TOKENS = 2048
+
+_ENV_VAR = "AISOC_INVESTIGATOR_MAX_COMPLETION_TOKENS"
+
+
+def max_completion_tokens() -> int | None:
+ """The completion bound, or ``None`` when an operator has removed it."""
+ raw = os.getenv(_ENV_VAR)
+ if raw is None or not raw.strip():
+ return DEFAULT_MAX_COMPLETION_TOKENS
+ try:
+ value = int(raw)
+ except ValueError:
+ # A typo must not silently restore the unbounded behaviour this
+ # module exists to end, so it falls back to the bound, not past it.
+ return DEFAULT_MAX_COMPLETION_TOKENS
+ return value if value > 0 else None
diff --git a/services/agents/app/investigator/recon_agent.py b/services/agents/app/investigator/recon_agent.py
index f55840df4..99907496a 100644
--- a/services/agents/app/investigator/recon_agent.py
+++ b/services/agents/app/investigator/recon_agent.py
@@ -23,6 +23,7 @@ from app.llm.factory import make_chat_model, resolve_model_alias
from app.prompt_serialization import summarize_structure_for_llm
from .bundle_prompt import format_bundle_prompt_append
+from .limits import max_completion_tokens
from .prompt_sanitizer import sanitize_text
from .state import InvestigatorState, ReconFindings, StepKind
from .tools import enrich_ioc, extract_iocs, map_to_mitre, sha256_of
@@ -56,7 +57,7 @@ async def _llm_recon(state: InvestigatorState) -> dict[str, Any]:
import json
model = resolve_model_alias("recon")
- llm = make_chat_model("recon", temperature=0)
+ llm = make_chat_model("recon", temperature=0, max_tokens=max_completion_tokens())
# Defence-in-depth: every field surfaced here can be attacker-influenced
# (alert_summary often echoes log lines; raw_alert is verbatim event data).
diff --git a/services/agents/app/investigator/report_writer_agent.py b/services/agents/app/investigator/report_writer_agent.py
index db6221f55..4a97811e8 100644
--- a/services/agents/app/investigator/report_writer_agent.py
+++ b/services/agents/app/investigator/report_writer_agent.py
@@ -23,6 +23,7 @@ from app.llm.factory import make_chat_model, resolve_model_alias
from app.prompt_serialization import summarize_structure_for_llm
from .bundle_prompt import format_bundle_prompt_append
+from .limits import max_completion_tokens
from .prompt_sanitizer import (
sanitize_iterable_of_strings,
sanitize_text,
@@ -169,7 +170,7 @@ async def run_report_writer(state_dict: dict[str, Any]) -> dict[str, Any]:
logger.info("report_writer.start", case_id=state.case_id)
model = resolve_model_alias("report")
- llm = make_chat_model("report", temperature=0)
+ llm = make_chat_model("report", temperature=0, max_tokens=max_completion_tokens())
context = _build_context(state)
bundle_append = format_bundle_prompt_append(state.context_bundle)
diff --git a/services/agents/app/investigator/responder_agent.py b/services/agents/app/investigator/responder_agent.py
index 66b6caa42..20356fa78 100644
--- a/services/agents/app/investigator/responder_agent.py
+++ b/services/agents/app/investigator/responder_agent.py
@@ -23,6 +23,7 @@ from app.llm.factory import make_chat_model, resolve_model_alias
from app.prompt_serialization import summarize_structure_for_llm
from .bundle_prompt import format_bundle_prompt_append
+from .limits import max_completion_tokens
from .prompt_sanitizer import (
sanitize_iterable_of_strings,
sanitize_text,
@@ -53,7 +54,7 @@ Respond ONLY with a JSON object:
async def _llm_responder(state: InvestigatorState) -> dict[str, Any]:
model = resolve_model_alias("investigation")
- llm = make_chat_model("investigation", temperature=0)
+ llm = make_chat_model("investigation", temperature=0, max_tokens=max_completion_tokens())
# Defence-in-depth: every field surfaced here originated in attacker-
# influenced data (alert payloads, banners, dark-web excerpts, LLM
diff --git a/services/agents/app/llm/factory.py b/services/agents/app/llm/factory.py
index 1e42a3800..1fd377f6d 100644
--- a/services/agents/app/llm/factory.py
+++ b/services/agents/app/llm/factory.py
@@ -146,6 +146,19 @@ def completions_url_for_base(base_url: str) -> str:
return f"{base}/v1/chat/completions"
+def _needs_legacy_max_tokens(base_url: str | None) -> bool:
+ """True when the endpoint reads ``max_tokens`` rather than its newer name.
+
+ Anything that is not OpenAI's own API. OpenAI rejects ``max_tokens`` for
+ its newer models and wants ``max_completion_tokens``; every
+ OpenAI-compatible server in this project's path — Ollama, vLLM, LiteLLM —
+ still reads the legacy name, and Ollama ignores the new one in silence.
+ """
+ if not base_url:
+ return False
+ return "api.openai.com" not in base_url.lower()
+
+
def make_chat_model(
role: str,
*,
@@ -195,6 +208,22 @@ def make_chat_model(
assert_routable(model, base_url)
if base_url:
params["base_url"] = base_url
+ if max_tokens is not None and _needs_legacy_max_tokens(base_url):
+ # langchain-openai 1.x renders the typed `max_tokens` field onto the
+ # wire as `max_completion_tokens`, OpenAI's newer name for it. Ollama
+ # reads only `max_tokens` and ignores the new name silently, so a
+ # bound set here reached the bundled local model as no bound at all.
+ # Measured directly against Ollama with qwen2.5:0.5b, asking for 500
+ # numbered lines with a limit of 64:
+ #
+ # max_tokens -> 64 tokens, finish_reason "length"
+ # max_completion_tokens -> 72 tokens, finish_reason "stop"
+ #
+ # `extra_body` puts the legacy name back on the request beside the
+ # new one. It is added only for a non-OpenAI endpoint because OpenAI
+ # itself rejects `max_tokens` outright for its newer models, and the
+ # bundled gateway drops what a provider does not support anyway.
+ params["extra_body"] = {"max_tokens": max_tokens, **(kwargs.pop("extra_body", None) or {})}
api_key = (override or {}).get("api_key") or resolve_api_key(model)
if api_key:
params["api_key"] = api_key
diff --git a/services/agents/tests/test_investigator_completion_bound.py b/services/agents/tests/test_investigator_completion_bound.py
new file mode 100644
index 000000000..dadced9ef
--- /dev/null
+++ b/services/agents/tests/test_investigator_completion_bound.py
@@ -0,0 +1,108 @@
+"""Every investigator LLM call carries a completion bound.
+
+The pipeline placed all four of its calls with no bound, and a small
+quantised model that failed to stop generated 40,960 tokens over twenty
+minutes on one of them. A test that only exercised `max_completion_tokens()`
+would not have caught that, because the defect was at the call sites: the
+helper is worth nothing if an agent forgets to pass it. So the call sites are
+read off disk, which is the direction this drifts — a fifth agent added later
+inherits the old default by simply not knowing about this module.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import pytest
+from app.investigator.limits import DEFAULT_MAX_COMPLETION_TOKENS, max_completion_tokens
+from app.llm.factory import make_chat_model
+
+INVESTIGATOR = Path(__file__).resolve().parents[1] / "app" / "investigator"
+
+#: The largest legitimate completion measured across the pipeline on the eval
+#: corpus — the report writer, which writes the longest output of the four.
+LONGEST_LEGITIMATE_COMPLETION = 876
+
+
+def _make_chat_model_calls() -> list[tuple[str, ast.Call]]:
+ found: list[tuple[str, ast.Call]] = []
+ for path in sorted(INVESTIGATOR.glob("*.py")):
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Call) and getattr(node.func, "id", None) == "make_chat_model":
+ found.append((path.name, node))
+ return found
+
+
+def test_the_call_sites_exist_so_this_test_is_not_vacuous():
+ assert len(_make_chat_model_calls()) >= 4
+
+
[email protected]("module_and_call", _make_chat_model_calls(), ids=lambda mc: f"{mc[0]}:{mc[1].lineno}")
+def test_every_investigator_llm_call_bounds_its_completion(module_and_call):
+ module, call = module_and_call
+ passed = {kw.arg for kw in call.keywords}
+ assert "max_tokens" in passed, (
+ f"{module}:{call.lineno} places an LLM call with no completion bound — a model that fails to stop runs to the context window"
+ )
+
+
+def test_the_bound_clears_the_longest_reply_the_agents_actually_write():
+ """A bound that truncates real output would be a quality regression."""
+ assert DEFAULT_MAX_COMPLETION_TOKENS > LONGEST_LEGITIMATE_COMPLETION * 2
+
+
+def test_the_default_applies_with_no_configuration(monkeypatch):
+ monkeypatch.delenv("AISOC_INVESTIGATOR_MAX_COMPLETION_TOKENS", raising=False)
+ assert max_completion_tokens() == DEFAULT_MAX_COMPLETION_TOKENS
+
+
+def test_an_operator_can_raise_it(monkeypatch):
+ monkeypatch.setenv("AISOC_INVESTIGATOR_MAX_COMPLETION_TOKENS", "8192")
+ assert max_completion_tokens() == 8192
+
+
+def test_removing_the_bound_stays_reachable_but_deliberate(monkeypatch):
+ monkeypatch.setenv("AISOC_INVESTIGATOR_MAX_COMPLETION_TOKENS", "0")
+ assert max_completion_tokens() is None
+
+
+def test_the_bound_reaches_an_openai_compatible_server_under_its_old_name(monkeypatch):
+ """langchain-openai renames the field on the wire; Ollama reads the old name.
+
+ A bound the provider ignores is not a bound. Measured against Ollama with
+ `qwen2.5:0.5b`, a 64-token limit returned 64 tokens under `max_tokens`
+ and 72 under `max_completion_tokens`, which is what the typed field now
+ becomes.
+ """
+ monkeypatch.setenv("OPENAI_API_KEY", "probe")
+ monkeypatch.setenv("OPENAI_BASE_URL", "http://127.0.0.1:11434/v1")
+ monkeypatch.setenv("AISOC_MODEL_PIN_RECON", "qwen2.5:0.5b")
+ llm = make_chat_model("recon", temperature=0, max_tokens=123)
+ assert (getattr(llm, "extra_body", None) or {}).get("max_tokens") == 123
+
+
+def test_openai_itself_is_not_sent_the_name_it_rejects(monkeypatch):
+ """OpenAI refuses `max_tokens` for its newer models, so only the field goes."""
+ monkeypatch.setenv("OPENAI_API_KEY", "probe")
+ monkeypatch.setenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
+ monkeypatch.setenv("AISOC_MODEL_PIN_RECON", "gpt-4o-mini")
+ llm = make_chat_model("recon", temperature=0, max_tokens=123)
+ assert not (getattr(llm, "extra_body", None) or {})
+
+
+def test_no_bound_means_no_compatibility_shim(monkeypatch):
+ monkeypatch.setenv("OPENAI_API_KEY", "probe")
+ monkeypatch.setenv("OPENAI_BASE_URL", "http://127.0.0.1:11434/v1")
+ monkeypatch.setenv("AISOC_MODEL_PIN_RECON", "qwen2.5:0.5b")
+ llm = make_chat_model("recon", temperature=0)
+ assert not (getattr(llm, "extra_body", None) or {})
+
+
+def test_a_typo_falls_back_to_the_bound_not_past_it(monkeypatch):
+ """Unbounded must never be reachable by accident."""
+ monkeypatch.setenv("AISOC_INVESTIGATOR_MAX_COMPLETION_TOKENS", "lots")
+ assert max_completion_tokens() == DEFAULT_MAX_COMPLETION_TOKENS
+ monkeypatch.setenv("AISOC_INVESTIGATOR_MAX_COMPLETION_TOKENS", "")
+ assert max_completion_tokens() == DEFAULT_MAX_COMPLETION_TOKENS