contiai / apps /api /tests /test_bag_models.py
aliroya's picture
ContiAI platform: API and queue worker in one container (part 2)
2bb5af3 verified
Raw History Blame Contribute Delete
5.36 kB
"""Which model each Arabic bag stage draws, and how the name is resolved.
Ported from the notebook that produced a working bag. Three things came with it:
* stages ask for a *kind* of model, not a name;
* the account's live catalogue decides which id in a tier is actually used,
because ids change and `LLM()` does not check the name when it is built - it
fails with a 404 on the first call, after earlier stages have been paid for;
* families that refuse a `max_tokens` above their own ceiling get it clamped,
rather than rejecting every request.
The tier assignment is also what makes a bag affordable: the writer runs once
per cover, and on the Arabic tier it costs about a third of what the model this
file used to name did.
"""
from __future__ import annotations
import pytest
from app.agents.arabic_bag import llms
@pytest.fixture(autouse=True)
def _forget_the_catalogue(monkeypatch):
"""Each test decides for itself what the account offers."""
monkeypatch.setattr(llms, "_available", None)
def catalogue(monkeypatch, ids):
monkeypatch.setattr(llms, "available", lambda: set(ids))
# ---------------------------------------------------------------- the tiers
def test_the_three_tiers_are_ordered_by_preference():
for tier in (llms.STRUCTURED, llms.ARABIC, llms.CHEAP):
assert len(tier) >= 3, "a tier with no alternatives is not a fallback chain"
assert len(set(tier)) == len(tier), "a repeated id is a dead fallback"
def test_the_first_choice_is_used_when_it_is_available(monkeypatch):
catalogue(monkeypatch, llms.STRUCTURED)
assert llms.pick(llms.STRUCTURED, "مهيكل") == llms.STRUCTURED[0]
def test_a_missing_first_choice_falls_through(monkeypatch):
"""The failure this replaced: a renamed id, a 404 on the first call, and
three paid stages already behind it."""
catalogue(monkeypatch, llms.STRUCTURED[1:])
assert llms.pick(llms.STRUCTURED, "مهيكل") == llms.STRUCTURED[1]
def test_an_unreadable_catalogue_does_not_stop_a_run(monkeypatch):
"""Better to try the first choice unchecked than to refuse to start."""
catalogue(monkeypatch, [])
assert llms.pick(llms.ARABIC, "عربي") == llms.ARABIC[0]
def test_a_tier_with_nothing_available_says_so(monkeypatch):
catalogue(monkeypatch, ["something/else"])
with pytest.raises(RuntimeError) as caught:
llms.pick(llms.ARABIC, "عربي")
assert "عربي" in str(caught.value)
def test_the_catalogue_is_read_once(monkeypatch):
calls = []
class Response:
@staticmethod
def raise_for_status():
pass
@staticmethod
def json():
return {"data": [{"id": "openai/gpt-4.1-mini"}]}
def get(*args, **kwargs):
calls.append(1)
return Response()
monkeypatch.setattr("httpx.get", get)
assert llms.available() == {"openai/gpt-4.1-mini"}
assert llms.available() == {"openai/gpt-4.1-mini"}
assert len(calls) == 1, "the catalogue was fetched twice"
def test_a_network_failure_is_swallowed(monkeypatch):
def boom(*args, **kwargs):
raise OSError("no network")
monkeypatch.setattr("httpx.get", boom)
assert llms.available() == set()
# ------------------------------------------------------------ the ceilings
def test_a_family_with_a_lower_ceiling_is_clamped():
"""Asking a 8,000-token family for 16,000 does not clamp - it rejects the
request, on every call."""
model = llms._or("anthropic/claude-haiku-4.5", max_tokens=16000)
assert model.max_tokens == llms.MODEL_MAX["anthropic/claude-haiku-4.5"]
def test_a_family_without_a_known_ceiling_is_left_alone():
assert llms._or("openai/gpt-4.1-mini", max_tokens=12000).max_tokens == 12000
def test_asking_under_the_ceiling_is_left_alone():
assert llms._or("anthropic/claude-haiku-4.5", max_tokens=6000).max_tokens == 6000
# -------------------------------------------------- which stage gets which
@pytest.mark.parametrize("factory, tier", [
("llm_blueprint", "STRUCTURED"),
("llm_planner", "STRUCTURED"),
("llm_quiz", "STRUCTURED"),
("llm_writer", "ARABIC"),
("llm_intro", "ARABIC"),
("llm_objectives", "ARABIC"),
("llm_activities", "ARABIC"),
("llm_refs", "CHEAP"),
("llm_seo", "CHEAP"),
])
def test_each_stage_draws_from_the_tier_the_notebook_gave_it(factory, tier, monkeypatch):
"""The assignment a working bag was tuned against. A stage quietly moved to
another tier changes either the prose or the bill."""
ids = getattr(llms, tier)
catalogue(monkeypatch, ids)
model = getattr(llms, factory)()
# CrewAI drops the `openrouter/` prefix once the provider is resolved.
assert model.model.endswith(ids[0])
def test_the_prose_stages_do_not_share_a_tier_with_the_schema_stages():
"""They are judged differently - one by whether the JSON is right, the
other by how the Arabic reads - so they must be separately swappable."""
assert llms.STRUCTURED[0] != llms.ARABIC[0]
def test_importing_this_module_reaches_no_network(monkeypatch):
"""The registry imports it while the API is still answering health checks."""
import importlib
def boom(*args, **kwargs):
raise AssertionError("the catalogue was fetched at import time")
monkeypatch.setattr("httpx.get", boom)
importlib.reload(llms)