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.

9.5 KB
Raw Blame
from __future__ import annotations

import copy
import os
from collections.abc import Iterator
from unittest.mock import MagicMock, patch

import litellm
import pytest
from litellm.llms.anthropic.experimental_pass_through.messages.transformation import AnthropicMessagesConfig
from litellm.types.router import GenericLiteLLMParams

from llm_gateway.rate_limiting.cost_refresh import set_litellm_model_cost
from llm_gateway.rate_limiting.model_cost_overrides import (
    MODEL_COST_OVERRIDES,
    PINNED_MODEL_COST_OVERRIDES,
    apply_model_cost_overrides,
)
from llm_gateway.rate_limiting.model_cost_service import ModelCost, ModelCostService
from llm_gateway.services.model_registry import (
    ModelRegistryService,
    get_available_models,
)

PROVIDER_ENV_VARS = [
    "OPENAI_API_KEY",
    "ANTHROPIC_API_KEY",
    "OPENROUTER_API_KEY",
    "FIREWORKS_API_KEY",
]


class TestApplyModelCostOverrides:
    @pytest.mark.parametrize("model_id", sorted(MODEL_COST_OVERRIDES))
    def test_adds_missing_model(self, model_id: str) -> None:
        cost_map: dict[str, ModelCost] = {"gpt-4": {"litellm_provider": "openai"}}
        apply_model_cost_overrides(cost_map)
        assert cost_map[model_id] == MODEL_COST_OVERRIDES[model_id]

    @pytest.mark.parametrize("model_id", sorted(MODEL_COST_OVERRIDES.keys() - PINNED_MODEL_COST_OVERRIDES))
    def test_does_not_override_existing_upstream_entry(self, model_id: str) -> None:
        upstream: ModelCost = {"litellm_provider": "anthropic", "max_input_tokens": 1_000_000}
        cost_map: dict[str, ModelCost] = {model_id: upstream}
        apply_model_cost_overrides(cost_map)
        assert cost_map[model_id] is upstream

    @pytest.mark.parametrize("model_id", sorted(PINNED_MODEL_COST_OVERRIDES))
    def test_overrides_upstream_entry_for_pinned_contract_price(self, model_id: str) -> None:
        upstream: ModelCost = {
            "litellm_provider": "openai",
            "input_cost_per_token": -1.0,
            "output_cost_per_token": -1.0,
            "max_tokens": 777,
        }
        cost_map: dict[str, ModelCost] = {model_id: upstream}

        apply_model_cost_overrides(cost_map)

        actual = dict(cost_map[model_id])
        for key, value in dict(MODEL_COST_OVERRIDES[model_id]).items():
            assert actual[key] == value
        assert cost_map[model_id]["max_tokens"] == 777
        assert cost_map[model_id] is not MODEL_COST_OVERRIDES[model_id]

    def test_pinned_membership_is_exactly_the_contract_prices(self) -> None:
        # Literals on purpose: the parametrized tests above derive their groups from the
        # sets under test, so removing a member there only reshuffles which semantics get
        # asserted. Un-pinning a contract price must fail here.
        assert PINNED_MODEL_COST_OVERRIDES == {
            "baseten/zai-org/glm-5.2",
            "baseten/deepseek-ai/deepseek-v4-flash-0731",
            "baseten/zai-org/glm-5.3",
            "baseten/zai-org/glm-5.3-flash",
            "gpt-6-astra",
        }

    def test_returns_same_object_in_place(self) -> None:
        cost_map: dict[str, ModelCost] = {}
        assert apply_model_cost_overrides(cost_map) is cost_map

    @pytest.mark.parametrize("model_id", sorted(MODEL_COST_OVERRIDES))
    def test_inserted_entry_is_a_copy(self, model_id: str) -> None:
        # The shared constant must survive callers (and litellm) mutating the map.
        cost_map: dict[str, ModelCost] = {}
        apply_model_cost_overrides(cost_map)
        cost_map[model_id]["input_cost_per_token"] = -1.0
        assert MODEL_COST_OVERRIDES[model_id].get("input_cost_per_token") != -1.0


class TestOverrideSurfacesThroughRefresh:
    @pytest.fixture(autouse=True)
    def restore_litellm_globals(self) -> Iterator[None]:
        model_cost_snapshot = litellm.model_cost
        # add_known_models mutates one provider set per provider in the cost map,
        # so snapshot every set in litellm's namespace rather than just anthropic's.
        set_snapshots = {name: value.copy() for name, value in vars(litellm).items() if isinstance(value, set)}
        try:
            yield
        finally:
            litellm.model_cost = model_cost_snapshot
            for name, snapshot in set_snapshots.items():
                provider_set = getattr(litellm, name)
                provider_set.clear()
                provider_set.update(snapshot)

    @pytest.fixture(autouse=True)
    def reset_singletons(self) -> Iterator[None]:
        ModelCostService.reset_instance()
        ModelRegistryService.reset_instance()
        yield
        ModelCostService.reset_instance()
        ModelRegistryService.reset_instance()

    @pytest.mark.parametrize(
        "model,provider,context_window",
        [
            ("claude-fable-5", "anthropic", 200_000),
            ("claude-fable-5-1", "anthropic", 200_000),
            ("claude-opus-5-5", "anthropic", 200_000),
            ("claude-sonnet-5-5", "anthropic", 1_000_000),
            ("gpt-6.1-sol", "openai", 1_050_000),
        ],
    )
    @patch("llm_gateway.rate_limiting.model_cost_service.get_model_cost_map")
    def test_refresh_injects_model_when_upstream_missing(
        self, mock_get_cost_map: MagicMock, model: str, provider: str, context_window: int
    ) -> None:
        mock_get_cost_map.return_value = {
            "claude-opus-4-8": {
                "litellm_provider": "anthropic",
                "mode": "chat",
                "max_input_tokens": 200_000,
            },
        }

        service = ModelCostService.get_instance()
        service._refresh_cache()

        costs = service.get_costs(model)
        assert costs is not None
        assert costs["litellm_provider"] == provider
        assert costs["max_input_tokens"] == context_window
        assert model in service.get_all_models()

    @patch("llm_gateway.rate_limiting.model_cost_service.get_model_cost_map")
    def test_bridge_models_listed_for_posthog_code(self, mock_get_cost_map: MagicMock) -> None:
        mock_get_cost_map.return_value = {
            "claude-opus-4-8": {
                "litellm_provider": "anthropic",
                "mode": "chat",
                "max_input_tokens": 200_000,
            },
        }
        ModelCostService.get_instance()._refresh_cache()

        settings = MagicMock()
        settings.openai_api_key = "sk-test"
        settings.anthropic_api_key = "sk-ant-test"
        settings.openrouter_api_key = None
        settings.fireworks_api_key = None

        with patch.dict(os.environ, {}, clear=False):
            for var in PROVIDER_ENV_VARS:
                os.environ.pop(var, None)
            with patch(
                "llm_gateway.services.model_registry.get_settings",
                return_value=settings,
            ):
                model_ids = {m.id for m in get_available_models("posthog_code")}

        assert "claude-opus-4-8" in model_ids
        assert "claude-fable-5" in model_ids
        assert "claude-fable-5-1" in model_ids
        assert "gpt-6.1-sol" in model_ids

    @pytest.mark.parametrize("product", ["posthog_code", "background_agents", "slack_app", "workflows"])
    @patch("llm_gateway.rate_limiting.model_cost_service.get_model_cost_map")
    def test_sonnet_5_5_listed_for_agent_products(self, mock_get_cost_map: MagicMock, product: str) -> None:
        mock_get_cost_map.return_value = {
            "claude-opus-4-8": {
                "litellm_provider": "anthropic",
                "mode": "chat",
                "max_input_tokens": 200_000,
            },
        }
        ModelCostService.get_instance()._refresh_cache()

        settings = MagicMock()
        settings.openai_api_key = None
        settings.anthropic_api_key = "sk-ant-test"
        settings.openrouter_api_key = None
        settings.fireworks_api_key = None

        with patch.dict(os.environ, {}, clear=False):
            for var in PROVIDER_ENV_VARS:
                os.environ.pop(var, None)
            with patch(
                "llm_gateway.services.model_registry.get_settings",
                return_value=settings,
            ):
                model_ids = {m.id for m in get_available_models(product)}

        assert "claude-sonnet-5-5" in model_ids


CLAUDE_BRIDGE_MODELS = ["claude-fable-5", "claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5-5"]


@pytest.fixture
def bridged_litellm_cost_map() -> Iterator[None]:
    """litellm.model_cost with every Claude bridge row applied over a map that lacks them."""
    original = litellm.model_cost
    model_cost = {k: v for k, v in copy.deepcopy(original).items() if k not in CLAUDE_BRIDGE_MODELS}
    apply_model_cost_overrides(model_cost)
    set_litellm_model_cost(model_cost)
    yield
    set_litellm_model_cost(original)


@pytest.mark.usefixtures("bridged_litellm_cost_map")
@pytest.mark.parametrize("model", CLAUDE_BRIDGE_MODELS)
@pytest.mark.parametrize(
    "thinking,effort",
    [({"type": "between_tools"}, "high"), ({"type": "adaptive"}, "xhigh")],
)
def test_claude_bridge_row_keeps_thinking_and_effort(model: str, thinking: dict[str, str], effort: str) -> None:
    # Without the capability flags litellm treats the model as non-adaptive and strips both fields.
    out = AnthropicMessagesConfig().transform_anthropic_messages_request(
        model=model,
        messages=[{"role": "user", "content": "hi"}],
        anthropic_messages_optional_request_params={
            "max_tokens": 1024,
            "thinking": dict(thinking),
            "output_config": {"effort": effort},
        },
        litellm_params=GenericLiteLLMParams(),
        headers={},
    )

    assert out["thinking"] == thinking
    assert out["output_config"] == {"effort": effort}