Files
OpenJarvis/tests/cli/test_ask_router.py
T
555e982f51 feat: query complexity analyzer for local/cloud routing (#102)
* feat: add query complexity analyzer with CLI and UI integration

Classify incoming queries by difficulty (trivial→very_complex) to
suggest appropriate token budgets for local vs. cloud routing.

- Add score_complexity() with weighted signals (length, code, math,
  reasoning, multi-step, creative) and token tier mapping
- Wire into `jarvis ask`: auto-suggest max_tokens when not set by user,
  show complexity in --profile output, log at DEBUG level
- Add complexity metadata to /v1/chat/completions API response
- Display complexity tier and score in frontend XRayFooter
- Extend RoutingContext with complexity_score, suggested_max_tokens,
  has_reasoning fields
- Update HeuristicRouter to route on complexity_score instead of
  raw query_length
- Remove duplicated regex patterns from router.py (use complexity
  module as single source of truth)
- Add 30 unit tests for complexity module
- Fix existing router tests for new complexity-based routing

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: pass temperature and max_tokens from UI settings to backend

The settings page stores temperature and max_tokens in the frontend
store, but these values were never included in the chat API request.
The backend Pydantic model defaults max_tokens to 1024 when the field
is absent, which is too low for thinking models like qwen3.5 — they
consume all tokens on reasoning and return empty content.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: pass UI settings to backend and auto-bump max_tokens from complexity

- Pass temperature and max_tokens from frontend Settings store to the
  backend API (cherry-picked from fix/ui-max-tokens-passthrough)
- Server-side: bump max_tokens when the complexity analyzer suggests a
  higher budget (e.g. for thinking models on complex queries), never
  reduce below the client-requested value
- Fixes empty responses with thinking models (e.g. qwen3.5) that
  consumed all tokens on internal reasoning

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: raise token budget tiers to prevent empty responses on thinking models

Double all tier budgets (trivial: 512→1024, simple: 1024→2048, etc.)
so that thinking models like qwen3.5 have enough headroom for internal
chain-of-thought plus visible output, even on simple queries.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: CI lint and test failures

- Break long lines in routes.py to satisfy 88-char limit (E501)
- Add intelligence.max_tokens and temperature to mocked config in
  test_ask_router.py so complexity analyzer can compare against int
  instead of MagicMock

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: line too long in test_complexity.py (E501)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 15:27:23 -07:00

132 lines
4.3 KiB
Python

"""Tests for model resolution fallback chain in jarvis ask."""
from __future__ import annotations
import importlib
from unittest import mock
from click.testing import CliRunner
from openjarvis.cli import cli
_ask_mod = importlib.import_module("openjarvis.cli.ask")
def _mock_engine():
"""Create a mock engine that returns a simple response."""
engine = mock.MagicMock()
engine.engine_id = "mock"
engine.health.return_value = True
engine.list_models.return_value = ["test-model"]
engine.generate.return_value = {
"content": "Hello!",
"usage": {"prompt_tokens": 5, "completion_tokens": 3, "total_tokens": 8},
"model": "test-model",
"finish_reason": "stop",
}
return engine
def _patch_engine(engine):
"""Return context managers that patch engine discovery to use our mock."""
return (
mock.patch.object(
_ask_mod,
"get_engine",
return_value=("mock", engine),
),
mock.patch.object(
_ask_mod,
"discover_engines",
return_value={"mock": engine},
),
mock.patch.object(
_ask_mod,
"discover_models",
return_value={"mock": ["test-model"]},
),
mock.patch.object(_ask_mod, "register_builtin_models"),
mock.patch.object(_ask_mod, "merge_discovered_models"),
mock.patch.object(_ask_mod, "TelemetryStore"),
)
class TestAskModelResolution:
def test_default_model_from_config(self) -> None:
"""When no -m flag, uses config.intelligence.default_model."""
engine = _mock_engine()
patches = _patch_engine(engine)
with patches[0], patches[1], patches[2], patches[3], patches[4], patches[5]:
result = CliRunner().invoke(cli, ["ask", "Hello"])
assert result.exit_code == 0
assert "Hello!" in result.output
def test_explicit_model_flag(self) -> None:
"""The -m flag directly selects a model, bypassing fallback chain."""
engine = _mock_engine()
patches = _patch_engine(engine)
with patches[0], patches[1], patches[2], patches[3], patches[4], patches[5]:
result = CliRunner().invoke(
cli,
["ask", "-m", "test-model", "Hello"],
)
assert result.exit_code == 0
assert "Hello!" in result.output
def test_fallback_to_engine_models(self) -> None:
"""When default_model is empty, falls back to first engine model."""
engine = _mock_engine()
patches = _patch_engine(engine)
with (
patches[0],
patches[1],
patches[2],
patches[3],
patches[4],
patches[5],
mock.patch.object(
_ask_mod,
"load_config",
) as mock_config,
):
cfg = mock_config.return_value
cfg.telemetry.enabled = False
cfg.intelligence.default_model = ""
cfg.intelligence.fallback_model = ""
cfg.intelligence.temperature = 0.7
cfg.intelligence.max_tokens = 1024
cfg.agent.context_from_memory = False
result = CliRunner().invoke(cli, ["ask", "Hello"])
assert result.exit_code == 0
def test_fallback_to_fallback_model(self) -> None:
"""When default_model is empty and no engine models, uses fallback_model."""
engine = _mock_engine()
patches = _patch_engine(engine)
# Override discover_models to return empty list
with (
patches[0],
patches[1],
mock.patch.object(
_ask_mod,
"discover_models",
return_value={"mock": []},
),
patches[3],
patches[4],
patches[5],
mock.patch.object(
_ask_mod,
"load_config",
) as mock_config,
):
cfg = mock_config.return_value
cfg.telemetry.enabled = False
cfg.intelligence.default_model = ""
cfg.intelligence.fallback_model = "fallback-model"
cfg.intelligence.temperature = 0.7
cfg.intelligence.max_tokens = 1024
cfg.agent.context_from_memory = False
result = CliRunner().invoke(cli, ["ask", "Hello"])
assert result.exit_code == 0