Files
DeepTutor/tests/services/test_task_model_call_sites.py
Bingxi Zhao (Frank) a9f67eb3aa feat(settings): connections layer + per-task model pinning
Model configuration was one layer replicated seven times: every service
stored its own profile with its own credentials, so a single OpenRouter
key had to be pasted into five separate pages. Every comparable product
(Dify, Open WebUI, Cherry Studio, RAGFlow) splits this in two — a
credential entered once, then a per-purpose assignment — so this adds
that split without disturbing what already works.

Connections
  A connection holds one vendor credential (api_key / api_version /
  extra_headers, plus an optional endpoint override). Linking creates one
  ordinary profile per service that can use it, and the credential is
  mirrored down on save rather than resolved on read — so every consumer
  of the catalog keeps reading self-contained profiles and a linked
  profile resolves exactly like a hand-typed one. Rotating the key in one
  place reaches every linked profile; deleting a connection unlinks
  rather than wipes. Anyone wanting a different key per service simply
  never makes a connection.

  Which services a vendor can serve is derived from the six provider
  tables that already exist (new `connection_targets` in GET /settings),
  so the web app keeps no second copy and adding a vendor to a service
  table is enough to make it connectable.

Task models
  Naming a conversation and writing the three home-screen starting points
  are LLM calls nobody asked for — short, frequent, and fine on a small
  fast model. Both can now be pinned to their own configured model from
  Settings > Models > Task models. Unpinned is the default and a true
  no-op: the title still follows the turn's own model and the starters
  the active one, exactly as before. A pin at a deleted profile reverts
  to inheriting rather than stranding the call.
2026-08-29 11:50:10 +08:00

207 lines
6.4 KiB
Python

"""The two task call sites actually run inside the scope they claim to.
Pinning a task model is only worth anything if the LLM call at the other end
resolves the pinned config. Both tests assert the model *observed from inside
the call*: a scope wrapped around the wrong statement, or a call site that was
never wired at all, still looks correct from the outside.
"""
from __future__ import annotations
import asyncio
from pathlib import Path
from typing import Any
import pytest
from deeptutor.services.config import model_catalog as model_catalog_module
from deeptutor.services.config.model_catalog import ModelCatalogService
from deeptutor.services.llm.config import clear_llm_config_cache, get_llm_config
class _FakePathService:
def __init__(self, root: Path) -> None:
self._root = root
def get_settings_file(self, name: str) -> Path:
return self._root / "settings" / f"{name}.json"
def _pin(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, tasks: dict[str, Any]) -> None:
"""Point every catalog reader at a tmp catalog with *tasks* pinned.
Patching the path service rather than ``get_model_catalog_service`` is
deliberate: several modules import that function by value, so patching it
in one place would leave the others resolving the real user's catalog.
"""
fake = _FakePathService(tmp_path)
monkeypatch.setattr(model_catalog_module, "get_path_service", lambda: fake)
service = ModelCatalogService(path=fake.get_settings_file("model_catalog"))
catalog = service.load()
catalog["services"]["llm"]["profiles"] = [
{
"id": "llm-1",
"name": "OpenAI",
"binding": "openai",
"base_url": "https://api.openai.com/v1",
"api_key": "sk-test",
"models": [
{"id": "model-default", "model": "gpt-5"},
{"id": "model-task", "model": "gpt-5-mini"},
],
}
]
catalog["services"]["llm"]["active_profile_id"] = "llm-1"
catalog["services"]["llm"]["active_model_id"] = "model-default"
catalog["services"]["llm"]["tasks"] = tasks
service.save(catalog)
# get_instance memoizes per resolved path; every reader must land on the
# instance holding this tmp file rather than a cached admin-scope one.
monkeypatch.setattr(
ModelCatalogService, "get_instance", classmethod(lambda cls, path=None: service)
)
clear_llm_config_cache()
@pytest.fixture(autouse=True)
def _clear_llm_cache() -> Any:
clear_llm_config_cache()
yield
clear_llm_config_cache()
def test_starter_generation_calls_the_pinned_model(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_pin(tmp_path, monkeypatch, {"starters": {"profile_id": "llm-1", "model_id": "model-task"}})
from deeptutor.services import suggestions
import deeptutor.services.llm as llm
observed: list[str] = []
async def _complete(prompt: str, **kwargs: Any) -> str:
observed.append(get_llm_config().model)
return "[]"
monkeypatch.setattr(llm, "complete", _complete)
material = suggestions._Material(
profile="A learner.",
topics=[suggestions._Topic(surface="chat", label="Agentic RAG", days_ago=1)],
)
asyncio.run(suggestions._generate("en", material))
assert observed == ["gpt-5-mini"]
def test_starter_generation_inherits_when_unpinned(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_pin(tmp_path, monkeypatch, {})
from deeptutor.services import suggestions
import deeptutor.services.llm as llm
observed: list[str] = []
async def _complete(prompt: str, **kwargs: Any) -> str:
observed.append(get_llm_config().model)
return "[]"
monkeypatch.setattr(llm, "complete", _complete)
material = suggestions._Material(
profile="A learner.",
topics=[suggestions._Topic(surface="chat", label="Agentic RAG", days_ago=1)],
)
asyncio.run(suggestions._generate("en", material))
assert observed == ["gpt-5"]
class _Store:
def __init__(self) -> None:
self.title = ""
async def get_session(self, session_id: str) -> dict[str, Any]:
return {"id": session_id, "title": "New conversation"}
async def get_messages(self, session_id: str) -> list[dict[str, Any]]:
return [
{"role": "user", "content": "Explain the chain rule."},
{"role": "assistant", "content": "It composes derivatives."},
]
async def update_session_title(self, session_id: str, title: str) -> None:
self.title = title
class _Runtime:
def __init__(self) -> None:
self.store = _Store()
async def _publish_live_event(self, execution: Any, event: Any) -> Any:
return event
def _run_title(monkeypatch: pytest.MonkeyPatch, observed: list[str]) -> _Runtime:
import deeptutor.services.llm as llm
from deeptutor.services.session import turn_runtime as turn_runtime_module
async def _stream(**kwargs: Any):
observed.append(get_llm_config().model)
yield "Chain rule basics"
monkeypatch.setattr(llm, "stream", _stream)
runtime = _Runtime()
asyncio.run(
turn_runtime_module.TurnRuntimeManager._maybe_generate_session_title(
runtime,
execution=object(),
session_id="session-1",
ui_language="en",
)
)
return runtime
def test_title_generation_calls_the_pinned_model(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_pin(
tmp_path, monkeypatch, {"session_title": {"profile_id": "llm-1", "model_id": "model-task"}}
)
observed: list[str] = []
runtime = _run_title(monkeypatch, observed)
assert observed == ["gpt-5-mini"]
assert runtime.store.title == "Chain rule basics"
def test_title_generation_inherits_the_turn_model_when_unpinned(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_pin(tmp_path, monkeypatch, {})
from deeptutor.services.llm.config import (
LLMConfig,
reset_scoped_llm_config,
set_scoped_llm_config,
)
# Stand in for the turn's own scope: unpinned must keep resolving whatever
# the conversation is already running on, not the global default.
token = set_scoped_llm_config(LLMConfig(model="turn-model", api_key="sk-test"))
try:
observed: list[str] = []
_run_title(monkeypatch, observed)
finally:
reset_scoped_llm_config(token)
assert observed == ["turn-model"]