Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ml_inference): attribute decision calls to the customer team (#107181)

Brandon6fa15dca3bf9
diff --git a/posthog/llm/system_one_client.py b/posthog/llm/system_one_client.py
index 8b4452195eb2..f9d1595cb01c 100644
--- a/posthog/llm/system_one_client.py
+++ b/posthog/llm/system_one_client.py
@@ -19,7 +19,7 @@ import structlog
from posthog.dataclasses import frozen
from posthog.egress.limiter.policies import Priority
from posthog.egress.typesafe.client import system_one
-from posthog.llm.gateway_client import AIGatewayConfig, ai_gateway_headers, resolve_ai_gateway_config
+from posthog.llm.gateway_client import AIGatewayConfig, ai_gateway_headers, resolve_ai_gateway_config, team_distinct_id
from posthog.llm.system_one import (
SYSTEM_ONE_PATH,
ChoiceQuestion,
@@ -135,6 +135,7 @@ def build_system_one_client(
*,
model: str,
ai_product: str,
+ team_id: int | None = None,
typesafe_fallback: TypeSafeFallback | None = None,
distinct_id: str | None = None,
trace_id: str | None = None,
@@ -144,16 +145,26 @@ def build_system_one_client(
"""A client for ``model`` on the Go ai-gateway when it is configured, else for TypeSafe when the
caller passes ``typesafe_fallback``.
- ``ai_product``, ``distinct_id``, ``trace_id`` and ``properties`` label the gateway's event. Raises
+ ``ai_product``, ``distinct_id``, ``trace_id`` and ``properties`` label the gateway's event. ``team_id``
+ is the customer team the gateway bills, and labels the event when ``distinct_id`` is unset. Raises
:class:`SystemOneNotConfigured` when no server the caller allows is configured.
"""
+ if not ai_product:
+ raise ValueError("ai_product is required")
+ if team_id is not None and team_id <= 0:
+ raise ValueError(f"team_id must be positive, got {team_id}")
gateway = _usable_gateway()
if gateway is not None:
+ labels = dict(properties or {})
+ if team_id is not None:
+ labels["team_id"] = str(team_id)
+ if not distinct_id and team_id is not None:
+ distinct_id = team_distinct_id(team_id)
return GatewaySystemOneClient(
url=_system_one_url(gateway.url),
api_key=gateway.api_key,
headers=ai_gateway_headers(
- ai_product=ai_product, trace_id=trace_id, properties=properties, distinct_id=distinct_id
+ ai_product=ai_product, trace_id=trace_id, properties=labels, distinct_id=distinct_id
)
or {},
model=model,
diff --git a/posthog/llm/test_system_one_client.py b/posthog/llm/test_system_one_client.py
index b3a03d251f2a..7c1d79c676a9 100644
--- a/posthog/llm/test_system_one_client.py
+++ b/posthog/llm/test_system_one_client.py
@@ -117,6 +117,38 @@ class TestBuildSystemOneClient(SimpleTestCase):
"team": ChoiceAnswer(choice="billing", confidence=0.7, probabilities={"billing": 0.7, "support": 0.3}),
}
+ @parameterized.expand(
+ [
+ ("user_distinct_id", "user-abc", "user-abc"),
+ ("team_fallback", None, "team-42"),
+ ]
+ )
+ def test_gateway_request_names_the_customer_team(
+ self, _name: str, distinct_id: str | None, expected_distinct_id: str
+ ) -> None:
+ with override_settings(**{**NOTHING, **GATEWAY}):
+ client = build_system_one_client(
+ model=GATEWAY_MODEL,
+ ai_product="test_product",
+ team_id=42,
+ distinct_id=distinct_id,
+ properties={"source": "cmdk", "team_id": "2"},
+ )
+ assert isinstance(client, GatewaySystemOneClient)
+
+ assert client.headers["X-PostHog-Product"] == "test_product"
+ assert client.headers["X-PostHog-Distinct-Id"] == expected_distinct_id
+ assert json.loads(client.headers["X-PostHog-Properties"]) == {
+ "source": "cmdk",
+ "team_id": "42",
+ "ai_product": "test_product",
+ }
+
+ @parameterized.expand([("no_product", "", 42, "ai_product"), ("zero_team", "test_product", 0, "team_id")])
+ def test_refuses_an_unlabelled_call(self, _name: str, ai_product: str, team_id: int, arg: str) -> None:
+ with override_settings(**{**NOTHING, **GATEWAY}), self.assertRaisesRegex(ValueError, arg):
+ build_system_one_client(model=GATEWAY_MODEL, ai_product=ai_product, team_id=team_id)
+
@parameterized.expand(
[
("http_error", httpx.Response(404, json={"error": "not found"}), 404),
diff --git a/products/ml_inference/backend/facade/contracts.py b/products/ml_inference/backend/facade/contracts.py
index 8e2224cd8922..73f0d40c49a8 100644
--- a/products/ml_inference/backend/facade/contracts.py
+++ b/products/ml_inference/backend/facade/contracts.py
@@ -67,8 +67,14 @@ class DecisionRequest:
ai_product: str = "ml_inference"
trace_id: str | None = None
properties: dict[str, str] | None = None
+ # The acting user; unset for background work, which is labelled with the team.
+ distinct_id: str | None = None
def __post_init__(self) -> None:
+ if self.team_id <= 0:
+ raise ValueError(f"team_id must be positive, got {self.team_id}")
+ if not self.ai_product:
+ raise ValueError("ai_product is required")
if len(self.questions) > MAX_QUESTIONS_PER_REQUEST:
raise ValueError(f"a request takes at most {MAX_QUESTIONS_PER_REQUEST} questions")
diff --git a/products/ml_inference/backend/logic/decisions.py b/products/ml_inference/backend/logic/decisions.py
index ef469b23e226..f13aa7f0e9a1 100644
--- a/products/ml_inference/backend/logic/decisions.py
+++ b/products/ml_inference/backend/logic/decisions.py
@@ -96,12 +96,14 @@ def decide(
if not carries_credentials_safely(config.url):
raise GatewayNotConfiguredError("AI_GATEWAY_URL must use https unless it points at this machine")
headers = {"Authorization": f"Bearer {config.api_key}"}
+ # Names the customer the relay credential calls for. Set last so a caller's team_id cannot override it.
+ properties = {**(request.properties or {}), "team_id": str(request.team_id)}
headers.update(
ai_gateway_headers(
ai_product=request.ai_product,
trace_id=request.trace_id,
- properties=request.properties,
- distinct_id=team_distinct_id(request.team_id),
+ properties=properties,
+ distinct_id=request.distinct_id or team_distinct_id(request.team_id),
)
or {}
)
diff --git a/products/ml_inference/backend/presentation/views.py b/products/ml_inference/backend/presentation/views.py
index e03535fc1a23..4087c507b160 100644
--- a/products/ml_inference/backend/presentation/views.py
+++ b/products/ml_inference/backend/presentation/views.py
@@ -67,7 +67,11 @@ class DecisionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
for question_id, question in data["questions"].items()
}
decision = contracts.DecisionRequest(
- team_id=self.team_id, state=data["state"], questions=questions, model=data["model"]
+ team_id=self.team_id,
+ state=data["state"],
+ questions=questions,
+ model=data["model"],
+ distinct_id=getattr(request.user, "distinct_id", None) or None,
)
try:
result = api.decide(decision)
diff --git a/products/ml_inference/backend/tests/test_logic.py b/products/ml_inference/backend/tests/test_logic.py
index d9c6eeca7e15..90a16fea230e 100644
--- a/products/ml_inference/backend/tests/test_logic.py
+++ b/products/ml_inference/backend/tests/test_logic.py
@@ -55,6 +55,7 @@ def _request(
ai_product: str = "ml_inference",
trace_id: str | None = None,
properties: dict[str, str] | None = None,
+ distinct_id: str | None = None,
) -> DecisionRequest:
return DecisionRequest(
team_id=42,
@@ -63,6 +64,7 @@ def _request(
ai_product=ai_product,
trace_id=trace_id,
properties=properties,
+ distinct_id=distinct_id,
)
@@ -72,6 +74,16 @@ def test_a_request_refuses_more_questions_than_the_cap() -> None:
DecisionRequest(team_id=1, state="text", questions={f"q{i}": question for i in range(33)})
+ "team_id,ai_product,arg", [(0, "ml_inference", "team_id"), (-1, "ml_inference", "team_id"), (1, "", "ai_product")]
+)
+def test_a_request_refuses_an_unattributed_call(team_id: int, ai_product: str, arg: str) -> None:
+ with pytest.raises(ValidationError) as exc:
+ DecisionRequest(team_id=team_id, state="text", questions=QUESTIONS, ai_product=ai_product)
+ # The whole error string repeats the input, so read the message alone.
+ assert arg in exc.value.errors()[0]["msg"]
+
+
def test_a_request_refuses_non_json_state() -> None:
state: Any = {"created_at": object()}
with pytest.raises(ValidationError):
@@ -120,10 +132,12 @@ class TestDecide:
assert [str(request.url) for request in seen] == ["https://gateway.example.com/v1/systemone"]
request = seen[0]
assert request.headers["Authorization"] == "Bearer phs_test"
+ assert request.headers["X-PostHog-Product"] == ai_product
assert json.loads(request.headers["X-PostHog-Properties"]) == {
"ai_product": ai_product,
"signals_decision_id": "decision-1",
"ai_stage": "signal_safety",
+ "team_id": "42",
}
assert request.headers["X-PostHog-Trace-Id"] == "decision-1"
assert request.headers["X-PostHog-Distinct-Id"] == "team-42"
@@ -135,6 +149,23 @@ class TestDecide:
assert result.input_tokens == 772
assert result.latency_ms == 41.25
+ def test_attributes_the_call_to_the_customer_team_and_acting_user(self) -> None:
+ seen: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ return httpx.Response(200, json=ANSWERS)
+
+ with override_settings(**GATEWAY):
+ decisions.decide(
+ _request(distinct_id="user-abc", properties={"team_id": "2"}),
+ transport=httpx.MockTransport(handler),
+ )
+
+ assert seen[0].headers["X-PostHog-Distinct-Id"] == "user-abc"
+ assert seen[0].headers["X-PostHog-Product"] == "ml_inference"
+ assert json.loads(seen[0].headers["X-PostHog-Properties"]) == {"ai_product": "ml_inference", "team_id": "42"}
+
def test_parses_every_answer_type(self) -> None:
result = decisions.parse_result(ANSWERS, QUESTIONS)
diff --git a/products/ml_inference/backend/tests/test_presentation.py b/products/ml_inference/backend/tests/test_presentation.py
index b0af7a812f55..f95a6051a3dd 100644
--- a/products/ml_inference/backend/tests/test_presentation.py
+++ b/products/ml_inference/backend/tests/test_presentation.py
@@ -148,6 +148,7 @@ class TestDecideEndpoint(APIBaseTest):
assert body["latency_ms"] == 31.5
sent = decide.call_args.args[0]
assert sent.team_id == self.team.id
+ assert sent.distinct_id == self.user.distinct_id
assert sent.questions["queue"].criteria == {"billing": "money", "support": "product"}
@patch("products.ml_inference.backend.presentation.views.api.decide", side_effect=DecisionsDisabledError(1))