from __future__ import annotations import json import httpx import pytest from volve_dia import m34_v2 as mv from volve_dia.m34_qa import ACTION, ANSWER V2 = {"inference": {"temperature": 0.2, "max_tokens": 320, "attempts_per_call": 3, "chat_template_kwargs": {"enable_thinking": False}}} SPEC = {"id": "vai-x", "api_model": "DeepSeek-V4.1-Flash-1017"} GOOD = json.dumps({"answer": 5, "unit": "m", "citations": ["reports:1"]}) def completion(text, finish="stop"): return {"id": "resp_1", "model": "DeepSeek-V4.1-Flash-1017", "choices": [{"message": {"content": text}, "finish_reason": finish}], "usage": {"prompt_tokens": 1000, "completion_tokens": 50}} def caller(tmp_path, responses, budget=None, seed=1): seen = [] def handler(request): seen.append(json.loads(request.content)) out = responses.pop(0) return out if isinstance(out, httpx.Response) else httpx.Response(200, json=out) client = httpx.Client(base_url="https://example.invalid/v1/", transport=httpx.MockTransport(handler)) store = mv.open_store(tmp_path / "c.sqlite", {"a": 1}) c = mv.ApiCaller(client, SPEC, V2, store, budget, seed) c.bind("rag", "xml", "q1") return c, store, seen def test_call_sends_v1_sampling_and_logs_usage(tmp_path): c, store, seen = caller(tmp_path, [completion(GOOD)]) assert c([{"role": "system", "content": "s"}, {"role": "user", "content": "u"}], ANSWER)["answer"] == 5 sent = seen[0] assert sent["model"] == "DeepSeek-V4.1-Flash-1017" and sent["temperature"] == 0.2 and sent["seed"] == 1 assert sent["chat_template_kwargs"] == {"enable_thinking": False} assert store.execute("SELECT ok, input_tokens, output_tokens, request_id FROM calls").fetchone() == \ (1, 1000, 50, "resp_1") def test_invalid_output_is_retried_then_fails(tmp_path, monkeypatch): monkeypatch.setattr(mv.time, "sleep", lambda s: None) c, store, _ = caller(tmp_path, [completion("not json"), completion(json.dumps({"answer": 1})), completion(GOOD, "length")]) with pytest.raises(ValueError, match="Completion failed"): c([{"role": "user", "content": "u"}], ANSWER) assert store.execute("SELECT COUNT(*), SUM(ok) FROM calls").fetchone() == (3, 0) def test_access_errors_stop_without_fallback(tmp_path): for code in (401, 403, 404, 400): c, _, seen = caller(tmp_path, [httpx.Response(code)]) with pytest.raises(mv.ModelAccessError): c([{"role": "user", "content": "u"}], ANSWER) assert len(seen) == 1 def test_token_budget_stops_after_logging(tmp_path): c, store, _ = caller(tmp_path, [completion(GOOD)], budget=1000) with pytest.raises(mv.BudgetExceeded): c([{"role": "user", "content": "u"}], ANSWER) assert store.execute("SELECT COUNT(*) FROM calls").fetchone()[0] == 1 def test_resume_keeps_spend_and_rejects_changed_provenance(tmp_path): c, store, _ = caller(tmp_path, [completion(GOOD)]) c([{"role": "user", "content": "u"}], ANSWER) store.close() again, _, _ = caller(tmp_path, []) assert again.spent == 1050 with pytest.raises(ValueError, match="provenance"): mv.open_store(tmp_path / "c.sqlite", {"a": 2}) def test_validation_rejects_bad_shapes(): for body in ({"answer": {"x": 1}, "unit": "", "citations": []}, {"answer": 1, "unit": 3, "citations": []}, {"answer": 1, "unit": "", "citations": ["a"] * 9}, {"tool": "drop", "arguments": {}}): with pytest.raises(ValueError): mv.validate(body, ACTION if "tool" in body else ANSWER) def test_endpoint_needs_env_and_only_one_model(monkeypatch): for name in ("VOLVE_DIA_M34_API_BASE", "VOLVE_DIA_M34_API_KEY"): monkeypatch.delenv(name, raising=False) with pytest.raises(mv.ModelAccessError): mv.endpoint() v2 = {"baselines": {"api": [{"id": "vai-x", "tasks": ["t4"]}]}} assert mv.model_spec(v2, "vai-x", "t4")["id"] == "vai-x" with pytest.raises(ValueError): mv.model_spec(v2, "vai-x", "t2_zero_shot") with pytest.raises(ValueError): mv.model_spec(v2, "claude-opus-5-5", "t4") def test_protocol_v2_extends_the_locked_v1(): protocol, _, v2 = mv.configuration_v2() assert protocol["version"] == 1 and v2["version"] == 2 assert [m["id"] for m in v2["baselines"]["api"]] == ["vai-deepseek-v4-1-flash"]