Files
video-analyse/tests/test_llm.py
T
alex d3f518a793 llm+vision+doctor: llama-server facts live in llm (code-review B4)
Issue #6's "alias" criterion was unfinished: vision.llama_server_up was a
one-line pass-through and vision also owned LLAMA_SERVER_COMMAND, which doctor
imported from vision - so the llama-server facts were spread over two modules
and a third consumed the copy.

- llm: owns LLAMA_SERVER_COMMAND next to the local provider name and the
  llama_server_models/llama_server_up health check
- vision: drops the alias and the constant; describe_shots/describe_moment call
  llm.llama_server_up, the actionable hint interpolates llm.LLAMA_SERVER_COMMAND
- doctor: imports the startup command from llm
- tests: the describer health-check stubs target llm.llama_server_up; the
  localhost server stub (path + trailing-slash check) moves to tests/test_llm.py
  with the rest of the llama-server tests; the duplicate closed-port test goes
2026-11-24 12:55:12 +00:00

310 lines
11 KiB
Python

"""llm.build_model wiring (construction only, no network) + llama_server_up."""
from __future__ import annotations
import asyncio
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import ClassVar
import pytest
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai.models.function import AgentInfo
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.models.test import TestModel
from video_analyse.config import Settings
from video_analyse.llm import build_model, llama_server_up, route_model
PROVIDER_ENV = (
"VA_VLM_MODEL",
"VA_LLAMA_SERVER_URL",
"DEEPSEEK_API_KEY",
"OPENROUTER_API_KEY",
"OLLAMA_BASE_URL",
"OLLAMA_API_KEY",
"OPENAI_API_KEY",
)
@pytest.fixture(autouse=True)
def clean_env(monkeypatch: pytest.MonkeyPatch) -> None:
for name in PROVIDER_ENV:
monkeypatch.delenv(name, raising=False)
def test_build_model_bare_name_uses_local_llama_server() -> None:
settings = Settings()
model = build_model("Qwen3-VL-4B-Instruct", settings=settings)
assert isinstance(model, OpenAIChatModel)
assert model.model_name == "Qwen3-VL-4B-Instruct"
assert model.system == "llama-server"
assert str(model.base_url).startswith("http://127.0.0.1:8080/v1")
def test_build_model_local_prefix_uses_settings_url() -> None:
settings = Settings(llama_server_url="http://127.0.0.1:9999/v1")
model = build_model("local:Qwen3-VL-2B-Instruct", settings=settings)
assert isinstance(model, OpenAIChatModel)
assert model.model_name == "Qwen3-VL-2B-Instruct"
assert str(model.base_url).startswith("http://127.0.0.1:9999/v1")
def test_build_model_local_prefix_without_name_raises() -> None:
with pytest.raises(ValueError):
build_model("local:", settings=Settings())
def test_build_model_empty_spec_raises() -> None:
with pytest.raises(ValueError):
build_model(" ", settings=Settings())
def test_build_model_unknown_prefix_is_a_local_model_name() -> None:
"""A "vendor:model" string that is not a known pydantic-ai provider stays local."""
model = build_model("acme:some-model", settings=Settings())
assert isinstance(model, OpenAIChatModel)
assert model.model_name == "acme:some-model"
def test_build_model_deepseek_provider(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key")
model = build_model("deepseek:deepseek-flash", settings=Settings(profile="hosted"))
assert model.model_name == "deepseek-flash"
assert model.system == "deepseek"
assert type(model).__name__ == "OpenAIChatModel"
def test_build_model_openrouter_provider(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")
model = build_model(
"openrouter:deepseek/deepseek-v4.1-flash-1017", settings=Settings(profile="hosted")
)
assert model.model_name == "deepseek/deepseek-v4.1-flash-1017"
assert model.system == "openrouter"
assert type(model).__name__ == "OpenRouterModel"
def test_build_model_ollama_provider(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("OLLAMA_BASE_URL", "http://127.0.0.1:11434")
model = build_model("ollama:qwen3-vl:4b", settings=Settings())
assert model.model_name == "qwen3-vl:4b"
assert model.system == "ollama"
assert type(model).__name__ == "OllamaModel"
def test_build_model_ollama_local_daemon_needs_no_key() -> None:
"""A local Ollama daemon constructs fine without any API key."""
settings = Settings(ollama_base_url="http://127.0.0.1:11434/v1", ollama_api_key=None)
model = build_model("ollama:qwen3-vl:4b", settings=settings)
assert type(model).__name__ == "OllamaModel"
assert model.system == "ollama"
def test_build_model_ollama_cloud_requires_key(monkeypatch: pytest.MonkeyPatch) -> None:
"""The cloud default without a key raises with actionable instructions."""
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
settings = Settings(ollama_base_url=None, ollama_api_key=None)
with pytest.raises(ValueError, match="ollama_api_key"):
build_model("ollama:deepseek-v4.1-flash:1017", settings=settings)
def test_build_model_ollama_cloud_uses_settings_key(monkeypatch: pytest.MonkeyPatch) -> None:
"""A configured key reaches the provider; the cloud endpoint is the default."""
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
settings = Settings(ollama_api_key="sk-test")
model = build_model("ollama:deepseek-v4.1-flash:1017", settings=settings)
assert type(model).__name__ == "OllamaModel"
assert model.model_name == "deepseek-v4.1-flash:1017"
assert model.base_url.rstrip("/").endswith("ollama.com/v1")
def test_build_model_ollama_env_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
"""Plain OLLAMA_* env vars still work when no settings value is set."""
monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:11434/v1")
monkeypatch.setenv("OLLAMA_API_KEY", "env-key")
model = build_model("ollama:deepseek-v4.1-flash:1017", settings=Settings())
assert type(model).__name__ == "OllamaModel"
def test_settings_resolution_feeds_build_model(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key")
hosted = Settings(profile="hosted")
model = build_model(hosted.resolved_vlm(), settings=hosted)
assert model.system == "deepseek"
local = Settings(profile="local")
local_model = build_model(local.resolved_vlm(), settings=local)
assert isinstance(local_model, OpenAIChatModel)
assert local_model.model_name == "Qwen3-VL-4B-Instruct"
def test_build_model_test_spec_returns_test_model() -> None:
assert isinstance(build_model("test", settings=Settings()), TestModel)
def test_agent_with_local_model_constructs() -> None:
"""Agent construction with the local model: no request is made here."""
class Desc(BaseModel):
summary: str
agent = Agent(
build_model("local:Qwen3-VL-4B-Instruct", settings=Settings()),
output_type=Desc,
model_settings={"temperature": 0.1, "max_tokens": 400, "max_retries": 0},
retries={"output": 2},
system_prompt="Describe the frame.",
)
assert agent.output_type is Desc
assert agent.model_settings["temperature"] == 0.1
assert agent.model_settings["max_retries"] == 0
def test_test_model_agent_runs_offline_with_structured_output() -> None:
class Desc(BaseModel):
summary: str
shot_type: str = "other"
agent = Agent(TestModel(), output_type=Desc, system_prompt="describe")
result = asyncio.run(agent.run("describe this frame"))
assert isinstance(result.output, Desc)
def test_function_model_type_is_available() -> None:
"""FunctionModel is importable and usable for scripted offline agents."""
from pydantic_ai.models.function import FunctionModel
def fn(messages, info: AgentInfo):
raise AssertionError("must not be called at construction time")
agent = Agent(FunctionModel(fn))
assert isinstance(agent.model, FunctionModel)
class _ModelsHandler(BaseHTTPRequestHandler):
"""Minimal llama-server stand-in: answers every GET with a 200 JSON model list."""
hits: ClassVar[list[str]] = []
def do_GET(self) -> None:
type(self).hits.append(self.path)
body = b'{"object": "list", "data": [{"id": "Qwen3-VL-4B-Instruct"}]}'
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format: str, *args: object) -> None:
"""Silence the default stderr access log."""
def test_llama_server_up_against_localhost_stub() -> None:
_ModelsHandler.hits = []
server = ThreadingHTTPServer(("127.0.0.1", 0), _ModelsHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
port = server.server_address[1]
settings = Settings(llama_server_url=f"http://127.0.0.1:{port}/v1")
assert asyncio.run(llama_server_up(settings)) is True
assert _ModelsHandler.hits == ["/v1/models"]
# A trailing slash in the configured URL must not produce a double slash.
assert (
asyncio.run(llama_server_up(Settings(llama_server_url=f"http://127.0.0.1:{port}/v1/")))
is True
)
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
def test_llama_server_up_dead_port_is_fast_false() -> None:
import time
settings = Settings(llama_server_url="http://127.0.0.1:9/v1") # discard port: closed
started = time.monotonic()
assert asyncio.run(llama_server_up(settings)) is False
assert time.monotonic() - started < 2.5
def test_llama_server_up_unresolvable_host_is_false() -> None:
settings = Settings(llama_server_url="http://127.0.0.1:1/v1")
assert asyncio.run(llama_server_up(settings)) is False
@pytest.mark.parametrize(
"url",
[
"http://localhost:abc/v1", # httpx.InvalidURL
"http://127.0.0.1:99999/v1", # OverflowError inside the connect attempt
],
)
def test_llama_server_up_treats_malformed_urls_as_down(url: str) -> None:
"""va doctor and describe must warn, never crash, on a bad VA_LLAMA_SERVER_URL."""
assert asyncio.run(llama_server_up(Settings(llama_server_url=url))) is False
# ------------------------------------------------------------------ routing record
@pytest.mark.parametrize(
("spec", "local", "prefix", "provider", "model", "credential"),
[
("Qwen3-VL-4B-Instruct", True, None, None, "Qwen3-VL-4B-Instruct", None),
("local:Qwen3-VL-4B-Instruct", True, "local", None, "Qwen3-VL-4B-Instruct", None),
("qwen3-vl:4b", True, "qwen3-vl", None, "qwen3-vl:4b", None),
(
"deepseek:deepseek-flash",
False,
"deepseek",
"deepseek",
"deepseek-flash",
"DEEPSEEK_API_KEY",
),
(
"openrouter:deepseek/deepseek-v4.1-flash-1017",
False,
"openrouter",
"openrouter",
"deepseek/deepseek-v4.1-flash-1017",
"OPENROUTER_API_KEY",
),
("ollama:qwen3-vl:4b", False, "ollama", "ollama", "qwen3-vl:4b", "OLLAMA_API_KEY"),
("test", False, None, None, "test", None),
],
)
def test_route_model_describes_the_build_model_routing(
spec: str,
local: bool,
prefix: str | None,
provider: str | None,
model: str,
credential: str | None,
) -> None:
route = route_model(spec)
assert route.spec == spec
assert route.local is local
assert route.prefix == prefix
assert route.provider == provider
assert route.model == model
assert route.credential_env == credential
def test_route_model_agrees_with_build_model_for_local_specs() -> None:
for spec in ("Qwen3-VL-4B-Instruct", "local:Qwen3-VL-4B-Instruct", "qwen3-vl:4b"):
model = build_model(spec, settings=Settings())
route = route_model(spec)
assert route.local is True
assert model.model_name == route.model
def test_route_model_marks_the_test_spec_as_no_server() -> None:
assert route_model("test").local is False
assert route_model(" ").local is False