- New /models page: LLM cards (type tag, agent-default badge, test state with latency/consecutive failures), add/edit form (OpenAI-compatible segment, mono base URL/model, masked key with sk-****tail, timeout dropdown, save gated on a passing test), agent default-model panel for the five AIGC agents, dashed server-connectivity notice, disabled image/video tabs as future placeholders; responsive 1440/1024/768 breakpoints per spec-v2 §9. - Scoped A darkroom design tokens in app.css (.a-darkroom) + Noto Sans SC. - Top nav: add Agents and Models entries before Settings. - Backend: add 'style' agent role, llm-test timeout_sec (5-60, default 10), api_key_tail (last 4 chars) in public profiles; 4 new tests. - i18n: 84 models.* keys + nav.agents/nav.models in all 7 dictionaries. Co-authored-by: multica-agent <github@multica.ai>
261 lines
8.0 KiB
Python
261 lines
8.0 KiB
Python
"""LLM connection test endpoint: probe an OpenAI-compatible endpoint without paid keys."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import socket
|
|
import threading
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
import pytest
|
|
|
|
from calliope.config import settings
|
|
|
|
|
|
class _FakeOpenAIHandler(BaseHTTPRequestHandler):
|
|
server_version = "FakeOpenAI/1.0"
|
|
|
|
def do_POST(self):
|
|
length = int(self.headers.get("Content-Length") or 0)
|
|
body = json.loads(self.rfile.read(length) or b"{}")
|
|
auth = self.headers.get("Authorization") or ""
|
|
seen = {"path": self.path, "auth": auth, "body": body}
|
|
self.server.requests.append(seen)
|
|
if self.path != "/v1/chat/completions":
|
|
self._send(404, {"error": "not found"})
|
|
return
|
|
if self.server.require_auth and auth != f"Bearer {self.server.api_key}":
|
|
self._send(401, {"error": {"message": "Incorrect API key"}})
|
|
return
|
|
self._send(
|
|
200,
|
|
{
|
|
"id": "chatcmpl-test",
|
|
"object": "chat.completion",
|
|
"model": body.get("model", "fake"),
|
|
"choices": [
|
|
{"index": 0, "message": {"role": "assistant", "content": "pong"}, "finish_reason": "stop"}
|
|
],
|
|
},
|
|
)
|
|
|
|
def _send(self, status: int, payload: dict) -> None:
|
|
data = json.dumps(payload).encode("utf-8")
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def log_message(self, format, *args):
|
|
pass
|
|
|
|
|
|
@pytest.fixture
|
|
def fake_openai():
|
|
server = ThreadingHTTPServer(("127.0.0.1", 0), _FakeOpenAIHandler)
|
|
server.requests = []
|
|
server.require_auth = False
|
|
server.api_key = ""
|
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
thread.start()
|
|
try:
|
|
yield server
|
|
finally:
|
|
server.shutdown()
|
|
server.server_close()
|
|
|
|
|
|
def _url(server) -> str:
|
|
return f"http://127.0.0.1:{server.server_address[1]}/v1"
|
|
|
|
|
|
def _snapshot() -> dict:
|
|
return {
|
|
"llm_profiles": [dict(p) for p in (settings.llm_profiles or [])],
|
|
"llm_active_id": settings.llm_active_id,
|
|
"llm_base_url": settings.llm_base_url,
|
|
"llm_model": settings.llm_model,
|
|
"llm_api_key": settings.llm_api_key,
|
|
}
|
|
|
|
|
|
def _restore(prev: dict) -> None:
|
|
for key, value in prev.items():
|
|
setattr(settings, key, value)
|
|
|
|
|
|
def test_llm_test_success(client, fake_openai):
|
|
r = client.post(
|
|
"/api/settings/llm-test",
|
|
json={"base_url": _url(fake_openai), "model": "fake-model", "api_key": "sk-test"},
|
|
)
|
|
assert r.status_code == 200
|
|
body = r.json()
|
|
assert body["ok"] is True
|
|
assert isinstance(body["elapsed_ms"], int)
|
|
assert fake_openai.requests[0]["path"] == "/v1/chat/completions"
|
|
assert fake_openai.requests[0]["auth"] == "Bearer sk-test"
|
|
assert fake_openai.requests[0]["body"]["model"] == "fake-model"
|
|
|
|
|
|
def test_llm_test_uses_saved_profile_secret(client, fake_openai):
|
|
prev = _snapshot()
|
|
fake_openai.require_auth = True
|
|
fake_openai.api_key = "sk-saved-secret"
|
|
try:
|
|
pid = "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
|
r = client.post(
|
|
"/api/settings",
|
|
json={
|
|
"llm_profiles": [
|
|
{
|
|
"id": pid,
|
|
"name": "Fake",
|
|
"base_url": _url(fake_openai),
|
|
"model": "fake-model",
|
|
"api_key": "sk-saved-secret",
|
|
}
|
|
],
|
|
"llm_active_id": pid,
|
|
},
|
|
)
|
|
assert r.status_code == 200
|
|
assert r.json()["llm_profiles"][0]["api_key"] is True
|
|
|
|
r = client.post("/api/settings/llm-test", json={"profile_id": pid})
|
|
assert r.status_code == 200
|
|
assert r.json()["ok"] is True
|
|
assert fake_openai.requests[-1]["auth"] == "Bearer sk-saved-secret"
|
|
finally:
|
|
_restore(prev)
|
|
|
|
|
|
def test_llm_test_auth_rejected(client, fake_openai):
|
|
fake_openai.require_auth = True
|
|
fake_openai.api_key = "sk-right-one"
|
|
r = client.post(
|
|
"/api/settings/llm-test",
|
|
json={"base_url": _url(fake_openai), "model": "fake-model", "api_key": "sk-wrong-one"},
|
|
)
|
|
assert r.status_code == 200
|
|
body = r.json()
|
|
assert body["ok"] is False
|
|
assert body["error"] == "auth"
|
|
assert "401" in body["detail"]
|
|
|
|
|
|
def test_llm_test_connection_refused(client):
|
|
sock = socket.socket()
|
|
sock.bind(("127.0.0.1", 0))
|
|
port = sock.getsockname()[1]
|
|
sock.close()
|
|
r = client.post(
|
|
"/api/settings/llm-test",
|
|
json={"base_url": f"http://127.0.0.1:{port}/v1", "model": "fake-model"},
|
|
)
|
|
assert r.status_code == 200
|
|
body = r.json()
|
|
assert body["ok"] is False
|
|
assert body["error"] == "connect"
|
|
assert body["detail"]
|
|
|
|
|
|
def test_llm_test_validation(client):
|
|
r = client.post("/api/settings/llm-test", json={"model": "only-model"})
|
|
assert r.status_code == 400
|
|
r = client.post("/api/settings/llm-test", json={"profile_id": "does-not-exist"})
|
|
assert r.status_code == 404
|
|
|
|
|
|
def test_llm_test_accepts_timeout_sec(client, fake_openai):
|
|
r = client.post(
|
|
"/api/settings/llm-test",
|
|
json={
|
|
"base_url": _url(fake_openai),
|
|
"model": "fake-model",
|
|
"api_key": "sk-test",
|
|
"timeout_sec": 10,
|
|
},
|
|
)
|
|
assert r.status_code == 200
|
|
assert r.json()["ok"] is True
|
|
|
|
|
|
def test_llm_test_timeout_sec_bounds(client):
|
|
for bad in (0, 4, 61):
|
|
r = client.post(
|
|
"/api/settings/llm-test",
|
|
json={"base_url": "http://127.0.0.1:1/v1", "model": "m", "timeout_sec": bad},
|
|
)
|
|
assert r.status_code == 422, bad
|
|
|
|
|
|
def test_settings_hide_key_but_expose_tail(client, fake_openai):
|
|
prev = _snapshot()
|
|
try:
|
|
pid = "dddddddd-dddd-dddd-dddd-dddddddddddd"
|
|
r = client.post(
|
|
"/api/settings",
|
|
json={
|
|
"llm_profiles": [
|
|
{
|
|
"id": pid,
|
|
"name": "Tail",
|
|
"base_url": _url(fake_openai),
|
|
"model": "fake-model",
|
|
"api_key": "sk-tail-3f2a",
|
|
}
|
|
],
|
|
"llm_active_id": pid,
|
|
},
|
|
)
|
|
assert r.status_code == 200
|
|
profile = r.json()["llm_profiles"][0]
|
|
assert profile["api_key"] is True
|
|
assert profile["api_key_tail"] == "3f2a"
|
|
assert "sk-tail" not in r.text
|
|
finally:
|
|
_restore(prev)
|
|
|
|
|
|
def test_style_role_assignment_round_trip(client, fake_openai):
|
|
"""视觉设计 (style) is one of the five AIGC agents on the models page."""
|
|
prev = _snapshot()
|
|
prev_assign = dict(settings.agent_llm_assignments or {})
|
|
try:
|
|
pid = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"
|
|
r = client.post(
|
|
"/api/settings",
|
|
json={
|
|
"llm_profiles": [
|
|
{
|
|
"id": pid,
|
|
"name": "StyleLLM",
|
|
"base_url": _url(fake_openai),
|
|
"model": "fake-model",
|
|
}
|
|
],
|
|
"llm_active_id": pid,
|
|
"agent_llm_assignments": {
|
|
"main": None,
|
|
"planner": None,
|
|
"story": pid,
|
|
"style": pid,
|
|
"script": None,
|
|
"assets": None,
|
|
"video": None,
|
|
},
|
|
},
|
|
)
|
|
assert r.status_code == 200
|
|
body = r.json()
|
|
assert body["agent_llm_assignments"]["style"] == pid
|
|
assert body["agent_llm_assignments"]["story"] == pid
|
|
|
|
resolved = settings.resolve_llm_for_role("style")
|
|
assert resolved["id"] == pid
|
|
finally:
|
|
_restore(prev)
|
|
settings.agent_llm_assignments = prev_assign
|