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(egress): add a shared typesafe domain for jev (#105784)

Julian Bezf96b56e34c9e
diff --git a/posthog/egress/AGENTS.md b/posthog/egress/AGENTS.md
index 293e53224d44..5e5a8bdbaf12 100644
--- a/posthog/egress/AGENTS.md
+++ b/posthog/egress/AGENTS.md
@@ -4,5 +4,6 @@ Read the README before changing metrics, limiter keys, or adding an egress domai
Read a domain's own `README.md` before changing that domain, and invoke `/routing-outbound-api-calls` before adding or changing a domain.
Two things are easy to re-derive wrong: the identity model (key on the external budget owner, for example the GitHub App installation id, and **never** a PostHog DB row id) and GitHub's deliberate PAT scope decision in `github/README.md`.
A change to a domain's identity, budget, lanes, callers, or headers updates that domain's `README.md` in the same PR.
+A TypeSafe caller meets "Usage policy" in `typesafe/README.md` before it merges: a staff-only feature flag, no customer data, and explicit opt-in plus leadership sign-off before launch.
@README.md
diff --git a/posthog/egress/test/test_typesafe.py b/posthog/egress/test/test_typesafe.py
new file mode 100644
index 000000000000..8d8156fd1738
--- /dev/null
+++ b/posthog/egress/test/test_typesafe.py
@@ -0,0 +1,167 @@
+import json
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase, override_settings
+
+import requests
+from parameterized import parameterized
+from prometheus_client import REGISTRY
+
+from posthog.egress.limiter.policies import Priority, resolve_policy
+from posthog.egress.typesafe.client import (
+ ChoiceAnswer,
+ ChoiceQuestion,
+ NoulAnswer,
+ NoulQuestion,
+ Question,
+ TypeSafeNotConfigured,
+ TypeSafeRequestFailed,
+ system_one,
+)
+from posthog.egress.typesafe.limiter import typesafe_account_key
+
+_FAKE_API_KEY = "fake-key-for-tests"
+
+_QUESTIONS: dict[str, Question] = {
+ "urgent": NoulQuestion(instructions="Is this urgent?", criteria_true="Time-sensitive"),
+ "team": ChoiceQuestion(instructions="Which team handles this?", criteria={"billing": "Payments", "support": None}),
+}
+
+_ANSWERS: dict[str, Any] = {
+ "model": "jev-1.13.0",
+ "answers": {
+ "urgent": {"type": "noul", "noul": 0.95},
+ "team": {
+ "type": "choice",
+ "choice": "billing",
+ "probabilities": {"billing": 0.88, "support": 0.12},
+ "confidence": 0.81,
+ },
+ },
+ "usage": {"input_tokens": 296, "output_tokens": 20},
+}
+
+_COUNTER_LABELS = {
+ "account": "default",
+ "method": "POST",
+ "endpoint": "/v1/systemone",
+ "status_code": "200",
+ "source": "test",
+}
+
+
+def _response(status: int, body: str) -> requests.Response:
+ response = requests.models.Response()
+ response.status_code = status
+ response._content = body.encode()
+ return response
+
+
+def _with_answer(question_id: str, answer: dict[str, Any]) -> str:
+ return json.dumps({**_ANSWERS, "answers": {**_ANSWERS["answers"], question_id: answer}})
+
+
+@override_settings(TYPESAFE_API_KEY=_FAKE_API_KEY)
+class TestTypeSafeEgress(SimpleTestCase):
+ def test_sends_the_documented_request_and_records_it_without_the_key(self) -> None:
+ consume = MagicMock(return_value=True)
+ before = REGISTRY.get_sample_value("typesafe_api_requests_total", _COUNTER_LABELS) or 0.0
+ with (
+ patch("posthog.egress.typesafe.transport.consume_typesafe_sync", consume),
+ patch("requests.request", return_value=_response(200, json.dumps(_ANSWERS))) as request,
+ ):
+ result = system_one(state={"ticket": "Payouts fail"}, questions=_QUESTIONS, source="test")
+
+ assert request.call_args.args == ("POST", "https://api.typesafe.ai/v1/systemone")
+ kwargs = request.call_args.kwargs
+ assert kwargs["headers"]["Authorization"] == f"Bearer {_FAKE_API_KEY}"
+ assert kwargs["json"] == {
+ "model": "jev-latest",
+ "state": {"ticket": "Payouts fail"},
+ "questions": {
+ "urgent": {"type": "noul", "instructions": "Is this urgent?", "criteria": {"true": "Time-sensitive"}},
+ "team": {
+ "type": "choice",
+ "instructions": "Which team handles this?",
+ "criteria": {"billing": "Payments", "support": None},
+ },
+ },
+ }
+ assert result.model == "jev-1.13.0"
+ assert result.answers == {
+ "urgent": NoulAnswer(probability=0.95),
+ "team": ChoiceAnswer(choice="billing", confidence=0.81, probabilities={"billing": 0.88, "support": 0.12}),
+ }
+ assert result.input_tokens == 296
+ assert consume.call_args.kwargs["priority"] is Priority.NORMAL
+ assert REGISTRY.get_sample_value("typesafe_api_requests_total", _COUNTER_LABELS) == before + 1
+ assert _FAKE_API_KEY not in str(list(REGISTRY.collect()))
+
+ @parameterized.expand(
+ [
+ ("rate_limited", 429, json.dumps({"error": "rate limited"}), 429),
+ ("overloaded", 529, json.dumps({"error": "overloaded"}), 529),
+ ("non_json_body", 200, "<html>bad gateway</html>", None),
+ (
+ "missing_answer",
+ 200,
+ json.dumps({**_ANSWERS, "answers": {"urgent": {"type": "noul", "noul": 0.9}}}),
+ None,
+ ),
+ ("noul_out_of_range", 200, _with_answer("urgent", {"type": "noul", "noul": 1.5}), None),
+ ("noul_past_the_float_range", 200, _with_answer("urgent", {"type": "noul", "noul": 10**400}), None),
+ (
+ "choice_outside_the_options",
+ 200,
+ _with_answer("team", {"type": "choice", "choice": "sales", "probabilities": {}, "confidence": 1.0}),
+ None,
+ ),
+ (
+ "choice_missing_an_option_probability",
+ 200,
+ _with_answer(
+ "team",
+ {"type": "choice", "choice": "billing", "probabilities": {"billing": 1.0}, "confidence": 1.0},
+ ),
+ None,
+ ),
+ ("missing_model", 200, json.dumps({key: value for key, value in _ANSWERS.items() if key != "model"}), None),
+ (
+ "answer_of_the_wrong_type",
+ 200,
+ _with_answer("team", {"type": "noul", "noul": 0.5}),
+ None,
+ ),
+ ]
+ )
+ def test_raises_rather_than_returning_a_partial_answer(
+ self, _name: str, status: int, body: str, expected_status_code: int | None
+ ) -> None:
+ with (
+ patch("posthog.egress.typesafe.transport.consume_typesafe_sync", return_value=True),
+ patch("requests.request", return_value=_response(status, body)),
+ self.assertRaises(TypeSafeRequestFailed) as raised,
+ ):
+ system_one(state="Payouts fail", questions=_QUESTIONS, source="test")
+ assert raised.exception.status_code == expected_status_code
+
+ @parameterized.expand(
+ [
+ ("no_configured_key", "", Priority.NORMAL, TypeSafeNotConfigured),
+ ("critical_lane_skips_the_spend_ceiling", _FAKE_API_KEY, Priority.CRITICAL, ValueError),
+ ]
+ )
+ def test_never_calls_out(self, _name: str, api_key: str, priority: Priority, error: type[Exception]) -> None:
+ with (
+ override_settings(TYPESAFE_API_KEY=api_key),
+ patch("requests.request") as request,
+ self.assertRaises(error),
+ ):
+ system_one(state="hi", questions=_QUESTIONS, source="test", priority=priority)
+ request.assert_not_called()
+
+ @override_settings(TYPESAFE_EGRESS_PER_MINUTE_BUDGET=7, TYPESAFE_EGRESS_HOURLY_BUDGET=11)
+ def test_budgets_come_from_the_settings_they_are_named_after(self) -> None:
+ assert resolve_policy(typesafe_account_key()).limits == ((7, 60.0), (11, 3600.0))
diff --git a/posthog/egress/typesafe/README.md b/posthog/egress/typesafe/README.md
new file mode 100644
index 000000000000..b4d7490d54fd
--- /dev/null
+++ b/posthog/egress/typesafe/README.md
@@ -0,0 +1,76 @@
+# TypeSafe egress
+
+TypeSafe serves Jev, a System One model that answers typed questions (`noul`, `choice`, `score`) about a `state`.
+It returns probabilities, not free text.
+
+## Usage policy
+
+TypeSafe is approved for experiments only.
+Every caller meets these rules before it merges, and a reviewer blocks a caller that does not:
+
+- **Gate the caller behind a feature flag.** Until launch, the flag reaches PostHog staff only.
+- **Send no customer data during the experiment.** Customer data is anything from a customer's project or account: events, persons, recordings, insights, names, and text a user types into PostHog. Use synthetic data or data that PostHog owns.
+- **A launch that sends customer data needs an explicit opt-in.** Each customer turns it on before any of their data goes to TypeSafe. Use the approved opt-in copy. Until that copy exists, no caller sends customer data.
+- **A launch that sends customer data needs sign-off from leadership** before it ships, in addition to the opt-in.
+
+A self-hosted instance has no `TYPESAFE_API_KEY`, so it sends nothing.
+
+## Identity
+
+An instance holds a single TypeSafe API key.
+The whole instance draws from one budget under the key `typesafe:account:default`.
+TypeSafe does not say whether it meters its limits per API key or per account, so treat that as unverified.
+With one key per instance, both readings give the same single budget.
+
+## Budget
+
+TypeSafe publishes 1,200 requests per minute and 250,000 tokens per second for Jev 1.13.
+It also warns that these limits can change without notice.
+The budget reads from settings at acquire time:
+
+- `TYPESAFE_EGRESS_PER_MINUTE_BUDGET` (default 600) stays at half of the published request limit, so a limit that TypeSafe lowers still leaves headroom.
+- `TYPESAFE_EGRESS_HOURLY_BUDGET` (default 20,000) is an operator ceiling on spend, because TypeSafe bills every input token.
+
+At the 64k-token request limit and the published input price, the hourly ceiling caps spend at roughly $50 an hour.
+Typical requests are far smaller.
+The token-per-second limit has no budget of its own.
+At typical request sizes of a few hundred tokens, the request budget keeps the token rate far under it.
+At the 64k-token maximum, 600 requests a minute would exceed it, and TypeSafe answers with a 429.
+A caller that sends large states lowers its own request rate.
+Raise both settings when real traffic outgrows them.
+
+## Lanes and callers
+
+The default reserve ladder applies, and `typesafe_request` defaults to `NORMAL`.
+`typesafe_request` rejects `CRITICAL`, because a `CRITICAL` call is never shed and would skip the hourly spend ceiling.
+Give every caller an explicit lane: `NORMAL` when a person waits for the answer, `BATCH` for background work.
+No caller exists on master yet. Each new caller adds itself here with its lane and its feature flag.
+
+## Rate-limit headers
+
+TypeSafe documents no rate-limit status headers, so the domain declares no gauges.
+A 429 can carry `retry-after`, and a 529 means TypeSafe is overloaded.
+TypeSafe asks for exponential backoff on both, and the caller owns the retry.
+`TypeSafeRequestFailed.status_code` lets a caller defer a 429 or a 529 and drop the rest.
+The counter is `typesafe_api_requests_total`, labeled `account, method, endpoint, status_code, source`.
+
+## Auth
+
+`TYPESAFE_API_KEY` authenticates every call as a bearer token.
+An instance without one makes no request at all: `system_one` raises `TypeSafeNotConfigured`.
+
+## Typed client
+
+Callers use `client.py` rather than `typesafe_request`.
+`system_one(state=..., questions=..., source=..., model=...)` sends one state with a map of `NoulQuestion` and `ChoiceQuestion` entries.
+It returns a `SystemOneResult` with one `NoulAnswer` or `ChoiceAnswer` per question id, the versioned model that answered, and the input token count.
+It raises `TypeSafeRequestFailed` on an HTTP error, and on a body that lacks the answering model or a complete answer for any question.
+A choice outside the options the caller sent, or a choice without a probability for every option, counts as incomplete.
+`model` defaults to the `jev-latest` alias. A caller that tunes thresholds against one version pins that version's id, such as `jev-1.13.0`.
+Only `POST /v1/systemone` is wired up, and score questions are not.
+
+## Sources
+
+- [Models](https://docs.typesafe.ai/models): Jev 1.13 rate limits (1,200 requests per minute, 250,000 tokens per second), the warning that limits change without notice, billing per input token ($0.042 per million), the 64k context length, the `jev-latest` alias and version pinning, and `retry-after` on a rate-limited response.
+- [API reference](https://docs.typesafe.ai/api): the `POST /v1/systemone` request and answer shapes, bearer auth, the `401`, `422`, `429` and `529` statuses, exponential backoff on `429` and `529`, and no documented rate-limit status headers.
+- [Choice](https://docs.typesafe.ai/primitives/choice): at most 255 options per choice question.
diff --git a/posthog/egress/typesafe/__init__.py b/posthog/egress/typesafe/__init__.py
new file mode 100644
index 000000000000..e4375fc81b42
--- /dev/null
+++ b/posthog/egress/typesafe/__init__.py
@@ -0,0 +1,32 @@
+from posthog.egress.typesafe.client import (
+ JEV_LATEST,
+ Answer,
+ ChoiceAnswer,
+ ChoiceQuestion,
+ JsonValue,
+ NoulAnswer,
+ NoulQuestion,
+ Question,
+ SystemOneResult,
+ TypeSafeNotConfigured,
+ TypeSafeRequestFailed,
+ system_one,
+)
+from posthog.egress.typesafe.transport import TypeSafeEgressBudgetExhausted, typesafe_request
+
+__all__ = [
+ "JEV_LATEST",
+ "Answer",
+ "ChoiceAnswer",
+ "ChoiceQuestion",
+ "JsonValue",
+ "NoulAnswer",
+ "NoulQuestion",
+ "Question",
+ "SystemOneResult",
+ "TypeSafeEgressBudgetExhausted",
+ "TypeSafeNotConfigured",
+ "TypeSafeRequestFailed",
+ "system_one",
+ "typesafe_request",
+]
diff --git a/posthog/egress/typesafe/client.py b/posthog/egress/typesafe/client.py
new file mode 100644
index 000000000000..5cb358213b7a
--- /dev/null
+++ b/posthog/egress/typesafe/client.py
@@ -0,0 +1,229 @@
+"""Typed client for TypeSafe's System One endpoint, ``POST /v1/systemone``.
+
+A System One model such as Jev answers typed questions about a ``state`` and returns judgments
+rather than text. A noul question returns the probability that a yes/no statement holds. A choice
+question picks one option from the criteria the caller supplies, with a probability for every
+option. Score questions exist too and stay unwired until a caller needs one, so the request body
+remains a checked shape.
+
+Keep user text in ``state`` and refer to it from the instructions by name. Never interpolate it
+into ``instructions``, so user text cannot become an instruction.
+
+USAGE POLICY. TypeSafe is approved for experiments only. Read "Usage policy" in this package's
+README.md before you add a caller. In short: gate every caller behind a feature flag that reaches
+PostHog staff only, and send no customer data. A launch that sends customer data needs an explicit
+opt-in from each customer and sign-off from leadership first.
+"""
+
+import math
+from collections.abc import Mapping, Sequence
+from typing import cast
+
+from django.conf import settings
+
+from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
+from posthog.egress.typesafe.transport import DEFAULT_TIMEOUT, typesafe_request
+
+TYPESAFE_API_BASE = "https://api.typesafe.ai"
+SYSTEM_ONE_ENDPOINT = "/v1/systemone"
+
+# The alias moves to each new release. A caller that tunes thresholds against one version pins that
+# version's id instead, so a release cannot shift its answers without a code change.
+JEV_LATEST = "jev-latest"
+
+# TypeSafe rejects a choice question with more options than this.
+MAX_CHOICE_OPTIONS = 255
+
+type JsonValue = str | int | float | bool | None | Mapping[str, JsonValue] | Sequence[JsonValue]
+
+
+class TypeSafeNotConfigured(Exception):
+ """No TypeSafe API key is configured on this instance, so no call was made. Self-hosted
+ deployments run without one, so callers must treat this as a normal degraded path."""
+
+
+class TypeSafeRequestFailed(Exception):
+ """TypeSafe was reached but did not return a usable answer (HTTP error, or a body that does not
+ match the documented shape). ``status_code`` is set for an HTTP error, so a caller can defer a
+ 429 or 529 and drop the rest."""
+
+ def __init__(self, message: str, *, status_code: int | None = None) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+
+
+@frozen
+class NoulQuestion:
+ """A yes/no question. ``criteria_true`` and ``criteria_false`` optionally describe what each answer means."""
+
+ instructions: JsonValue
+ criteria_true: JsonValue = None
+ criteria_false: JsonValue = None
+
+ def to_json(self) -> dict[str, JsonValue]:
+ body: dict[str, JsonValue] = {"type": "noul", "instructions": self.instructions}
+ criteria = {
+ key: value
+ for key, value in (("true", self.criteria_true), ("false", self.criteria_false))
+ if value is not None
+ }
+ if criteria:
+ body["criteria"] = criteria
+ return body
+
+
+@frozen
+class ChoiceQuestion:
+ """A pick of one option. ``criteria`` maps each option to its description, or to ``None`` when
+ the option name is clear on its own."""
+
+ instructions: JsonValue
+ criteria: Mapping[str, JsonValue]
+
+ def __post_init__(self) -> None:
+ if not 1 <= len(self.criteria) <= MAX_CHOICE_OPTIONS:
+ raise ValueError(f"A choice question needs between 1 and {MAX_CHOICE_OPTIONS} options")
+
+ def to_json(self) -> dict[str, JsonValue]:
+ return {"type": "choice", "instructions": self.instructions, "criteria": dict(self.criteria)}
+
+
+type Question = NoulQuestion | ChoiceQuestion
+
+
+@frozen
+class NoulAnswer:
+ probability: float
+
+
+@frozen
+class ChoiceAnswer:
+ choice: str
+ confidence: float
+ probabilities: Mapping[str, float]
+
+
+type Answer = NoulAnswer | ChoiceAnswer
+
+
+@frozen
+class SystemOneResult:
+ """The answers to one request, keyed by the question ids the caller chose. ``model`` is the
+ versioned id that answered, also when the request named an alias."""
+
+ model: str
+ answers: Mapping[str, Answer]
+ input_tokens: int | None
+
+
+def _as_mapping(value: object) -> Mapping[str, object] | None:
+ # An isinstance check cannot narrow the key type, but these mappings come from a parsed JSON
+ # body, where every key is a string.
+ return cast(Mapping[str, object], value) if isinstance(value, Mapping) else None
+
+
+def _as_probability(value: object) -> float | None:
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ return None
+ try:
+ probability = float(value)
+ except OverflowError:
+ # JSON integers have no size limit, and one past the float range cannot be a probability.
+ return None
+ if not math.isfinite(probability) or not 0 <= probability <= 1:
+ return None
+ return probability
+
+
+def _parse_answer(question_id: str, question: Question, raw: object) -> Answer:
+ answer = _as_mapping(raw)
+ if answer is None:
+ raise TypeSafeRequestFailed(f"TypeSafe returned no answer for {question_id!r}")
+
+ if isinstance(question, NoulQuestion):
+ probability = _as_probability(answer.get("noul"))
+ if answer.get("type") != "noul" or probability is None:
+ raise TypeSafeRequestFailed(f"TypeSafe returned a malformed noul for {question_id!r}")
+ return NoulAnswer(probability=probability)
+
+ choice = answer.get("choice")
+ confidence = _as_probability(answer.get("confidence"))
+ if answer.get("type") != "choice" or not isinstance(choice, str) or choice not in question.criteria:
+ raise TypeSafeRequestFailed(f"TypeSafe returned a malformed choice for {question_id!r}")
+ if confidence is None:
+ raise TypeSafeRequestFailed(f"TypeSafe returned a malformed confidence for {question_id!r}")
+ raw_probabilities = _as_mapping(answer.get("probabilities")) or {}
+ probabilities = {option: _as_probability(raw_probabilities.get(option)) for option in question.criteria}
+ complete = {option: probability for option, probability in probabilities.items() if probability is not None}
+ if len(complete) != len(question.criteria):
+ raise TypeSafeRequestFailed(f"TypeSafe returned incomplete probabilities for {question_id!r}")
+ return ChoiceAnswer(choice=choice, confidence=confidence, probabilities=complete)
+
+
+def system_one(
+ *,
+ state: JsonValue,
+ questions: Mapping[str, Question],
+ source: str,
+ model: str = JEV_LATEST,
+ priority: Priority = Priority.NORMAL,
+ timeout: float | tuple[float, float] = DEFAULT_TIMEOUT,
+) -> SystemOneResult:
+ """Evaluate ``state`` against every question in one call. TypeSafe answers the questions in
+ parallel, so a caller asks everything it needs in one request.
+
+ Raises :class:`TypeSafeNotConfigured` when the instance has no API key,
+ :class:`TypeSafeRequestFailed` when TypeSafe answers with anything but a complete set of answers,
+ and :class:`~posthog.egress.typesafe.transport.TypeSafeEgressBudgetExhausted` when our own egress
+ budget sheds the call. Nothing retries a 429 or a 529 here, so the caller owns any retry.
+ """
+ if not questions:
+ raise ValueError("system_one needs at least one question")
+ api_key = settings.TYPESAFE_API_KEY
+ if not api_key:
+ raise TypeSafeNotConfigured("No TYPESAFE_API_KEY configured")
+
+ response = typesafe_request(
+ "POST",
+ f"{TYPESAFE_API_BASE}{SYSTEM_ONE_ENDPOINT}",
+ api_key=api_key,
+ source=source,
+ endpoint=SYSTEM_ONE_ENDPOINT,
+ priority=priority,
+ timeout=timeout,
+ allow_redirects=False,
+ json={
+ "model": model,
+ "state": state,
+ "questions": {question_id: question.to_json() for question_id, question in questions.items()},
+ },
+ )
+
+ if not response.ok:
+ # A 422 body echoes the offending field, which can carry the state, so keep the body out of
+ # the exception that gets logged.
+ raise TypeSafeRequestFailed(f"TypeSafe returned HTTP {response.status_code}", status_code=response.status_code)
+ try:
+ payload: object = response.json()
+ except ValueError as exc:
+ raise TypeSafeRequestFailed("TypeSafe returned a non-JSON body") from exc
+
+ body = _as_mapping(payload)
+ raw_answers = _as_mapping(body.get("answers")) if body is not None else None
+ if body is None or raw_answers is None:
+ raise TypeSafeRequestFailed("TypeSafe returned no answers")
+ answered_model = body.get("model")
+ if not isinstance(answered_model, str) or not answered_model:
+ raise TypeSafeRequestFailed("TypeSafe returned no model")
+
+ usage = _as_mapping(body.get("usage")) or {}
+ input_tokens = usage.get("input_tokens")
+ return SystemOneResult(
+ model=answered_model,
+ answers={
+ question_id: _parse_answer(question_id, question, raw_answers.get(question_id))
+ for question_id, question in questions.items()
+ },
+ input_tokens=input_tokens if isinstance(input_tokens, int) and not isinstance(input_tokens, bool) else None,
+ )
diff --git a/posthog/egress/typesafe/limiter.py b/posthog/egress/typesafe/limiter.py
new file mode 100644
index 000000000000..512e8c41168b
--- /dev/null
+++ b/posthog/egress/typesafe/limiter.py
@@ -0,0 +1,38 @@
+"""TypeSafe egress budget.
+
+A PostHog instance holds a single TypeSafe API key, so the whole instance draws from one shared
+budget under a constant scope. The per-minute default stays at half of TypeSafe's published request
+limit, because TypeSafe changes its limits without notice. The hourly default is an operator ceiling
+on spend, because TypeSafe bills every input token.
+
+Importing this module registers the policy as a side effect, so import it (directly or via
+``consume_typesafe_sync``) before using a ``typesafe:...`` limiter key.
+"""
+
+from posthog.egress.limiter.outbound import get_outbound_rate_limiter
+from posthog.egress.limiter.policies import Priority, per_minute_and_hourly_policy, register_policy
+
+TYPESAFE_DOMAIN = "typesafe"
+
+ACCOUNT_SCOPE_ID = "default"
+
+register_policy(
+ TYPESAFE_DOMAIN,
+ per_minute_and_hourly_policy(
+ per_minute_setting="TYPESAFE_EGRESS_PER_MINUTE_BUDGET",
+ per_minute_default=600,
+ hourly_setting="TYPESAFE_EGRESS_HOURLY_BUDGET",
+ hourly_default=20_000,
+ ),
+)
+
+
+def typesafe_account_key() -> str:
+ """Limiter key for the instance's single TypeSafe API key."""
+ return f"{TYPESAFE_DOMAIN}:account:{ACCOUNT_SCOPE_ID}"
+
+
+def consume_typesafe_sync(n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown") -> bool:
+ """Reserve ``n`` requests against the instance's TypeSafe budget. Returns False when the budget
+ (or this ``priority``'s reserved floor) is exhausted, so degrade gracefully rather than calling out."""
+ return get_outbound_rate_limiter().consume_sync(typesafe_account_key(), n, priority=priority, source=source)
diff --git a/posthog/egress/typesafe/observability.py b/posthog/egress/typesafe/observability.py
new file mode 100644
index 000000000000..ade4d25e053d
--- /dev/null
+++ b/posthog/egress/typesafe/observability.py
@@ -0,0 +1,22 @@
+"""TypeSafe egress telemetry.
+
+Every TypeSafe call records through ``typesafe_egress``, so request volume lands on one metric set
+whichever subsystem made the call, attributed by the ``source`` label.
+
+TypeSafe documents no rate-limit status headers, only ``retry-after`` on some 429s, so this domain
+declares no gauges.
+"""
+
+from prometheus_client import Counter
+
+from posthog.egress.observability.observability import EgressMetrics, EgressObservability
+
+typesafe_egress = EgressObservability(
+ EgressMetrics(
+ request_counter=Counter(
+ "typesafe_api_requests",
+ "Number of TypeSafe API requests made through the TypeSafe egress client.",
+ labelnames=["account", "method", "endpoint", "status_code", "source"],
+ ),
+ )
+)
diff --git a/posthog/egress/typesafe/transport.py b/posthog/egress/typesafe/transport.py
new file mode 100644
index 000000000000..5a7ae6e4660e
--- /dev/null
+++ b/posthog/egress/typesafe/transport.py
@@ -0,0 +1,76 @@
+"""TypeSafe incarnation of the egress transport.
+
+``typesafe_request`` is the one way to call TypeSafe from anywhere in the codebase: it gates on the
+instance's shared account budget and records telemetry by construction. It stays token-agnostic
+like the other incarnations, so the caller owns where the API key comes from:
+:mod:`posthog.egress.typesafe.client` reads it from settings.
+"""
+
+from typing import Any
+
+import requests
+
+from posthog.egress.limiter.policies import Priority
+from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient
+from posthog.egress.typesafe.limiter import ACCOUNT_SCOPE_ID, consume_typesafe_sync
+from posthog.egress.typesafe.observability import typesafe_egress
+
+
+class TypeSafeEgressBudgetExhausted(EgressBudgetExhausted):
+ """A sheddable (BATCH/NORMAL) TypeSafe call was shed by our egress limiter before it was sent.
+ Callers degrade by skipping the judgment or deferring it to a later run."""
+
+
+class TypeSafeClient(EgressClient):
+ """The TypeSafe incarnation of :class:`EgressClient`. Stateless, so one shared instance serves
+ every caller; wire it through :func:`typesafe_request`."""
+
+ observability = typesafe_egress
+
+ def _standard_headers(self) -> dict[str, str]:
+ return {"Accept": "application/json", "Content-Type": "application/json"}
+
+ def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
+ return consume_typesafe_sync(priority=priority, source=source)
+
+ def _budget_exhausted_error(self, scope: str) -> TypeSafeEgressBudgetExhausted:
+ return TypeSafeEgressBudgetExhausted("TypeSafe egress budget exhausted; degrading", scope=scope)
+
+
+_typesafe_client = TypeSafeClient()
+
+# A connection that will not open is never worth waiting on. A caller where a person waits for the
+# answer passes a shorter read timeout.
+DEFAULT_TIMEOUT: tuple[float, float] = (3.0, 15.0)
+
+
+def typesafe_request(
+ method: str,
+ url: str,
+ *,
+ api_key: str,
+ source: str,
+ endpoint: str,
+ priority: Priority = Priority.NORMAL,
+ timeout: float | tuple[float, float] = DEFAULT_TIMEOUT,
+ **kwargs: Any,
+) -> requests.Response:
+ """Make a gated, recorded TypeSafe request. ``source`` attributes the call to a subsystem.
+
+ Every call is sheddable: the state sent to TypeSafe is derived from user input, and every caller
+ can do without the judgment. A CRITICAL call is never shed, so it would skip the hourly ceiling,
+ which is the only cap on per-token spend. This function rejects CRITICAL for that reason.
+ """
+ if priority is Priority.CRITICAL:
+ raise ValueError("TypeSafe calls must be sheddable, so use NORMAL or BATCH")
+ return _typesafe_client.request(
+ method,
+ url,
+ source=source,
+ headers={"Authorization": f"Bearer {api_key}"},
+ scope=ACCOUNT_SCOPE_ID,
+ priority=priority,
+ endpoint=endpoint,
+ timeout=timeout,
+ **kwargs,
+ )
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index c1fcac17eefd..edfb93a5a886 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -932,6 +932,14 @@ FIRECRAWL_API_KEY = get_from_env("FIRECRAWL_API_KEY", "")
FIRECRAWL_EGRESS_PER_MINUTE_BUDGET = get_from_env("FIRECRAWL_EGRESS_PER_MINUTE_BUDGET", 60, type_cast=int)
FIRECRAWL_EGRESS_HOURLY_BUDGET = get_from_env("FIRECRAWL_EGRESS_HOURLY_BUDGET", 1000, type_cast=int)
+####
+# TypeSafe (System One judgments from the Jev model, see posthog/egress/typesafe/)
+TYPESAFE_API_KEY = get_from_env("TYPESAFE_API_KEY", "")
+# Half of TypeSafe's published per-minute request limit, which can change without notice.
+TYPESAFE_EGRESS_PER_MINUTE_BUDGET = get_from_env("TYPESAFE_EGRESS_PER_MINUTE_BUDGET", 600, type_cast=int)
+# An operator ceiling on spend, since TypeSafe bills every input token.
+TYPESAFE_EGRESS_HOURLY_BUDGET = get_from_env("TYPESAFE_EGRESS_HOURLY_BUDGET", 20000, type_cast=int)
+
####
# Feature flag billing analytics
# Used to track feature flag requests for billing purposes.