From b10c457f5b7fc300dba5bda15e0507fc1b876fdf Mon Sep 17 00:00:00 2001 From: stone16 <12712299+stone16@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:04:17 +0800 Subject: [PATCH 1/4] feat(core): add stateless OpenAI-compatible vision parser helper --- packages/invoice-core/pyproject.toml | 5 + .../invoice-core/src/invoice_core/__init__.py | 10 + .../src/invoice_core/parsers/__init__.py | 16 + .../src/invoice_core/parsers/vision.py | 292 +++++++++++++++++ .../invoice-core/tests/test_import_guard.py | 1 + packages/invoice-core/tests/test_vision.py | 306 ++++++++++++++++++ 6 files changed, 630 insertions(+) create mode 100644 packages/invoice-core/src/invoice_core/parsers/vision.py create mode 100644 packages/invoice-core/tests/test_vision.py diff --git a/packages/invoice-core/pyproject.toml b/packages/invoice-core/pyproject.toml index 056b750..2211fc6 100644 --- a/packages/invoice-core/pyproject.toml +++ b/packages/invoice-core/pyproject.toml @@ -13,5 +13,10 @@ dependencies = [ "Pillow>=10.0,<13", ] +[project.optional-dependencies] +vision = [ + "httpx>=0.26,<1.0", +] + [tool.setuptools.packages.find] where = ["src"] diff --git a/packages/invoice-core/src/invoice_core/__init__.py b/packages/invoice-core/src/invoice_core/__init__.py index b11a6e0..80f536f 100644 --- a/packages/invoice-core/src/invoice_core/__init__.py +++ b/packages/invoice-core/src/invoice_core/__init__.py @@ -8,6 +8,12 @@ parse_json_response, ) from invoice_core.parsers.pdf_text import extract_pdf_text_layer, render_pdf_pages +from invoice_core.parsers.vision import ( + VisionAPIError, + build_vision_messages, + build_vision_payload, + parse_invoice_with_vision, +) from invoice_core.prompts import ( INVOICE_JSON_SCHEMA, INVOICE_VISION_PROMPT, @@ -49,4 +55,8 @@ "INVOICE_VISION_PROMPT", "extract_pdf_text_layer", "render_pdf_pages", + "VisionAPIError", + "build_vision_messages", + "build_vision_payload", + "parse_invoice_with_vision", ] diff --git a/packages/invoice-core/src/invoice_core/parsers/__init__.py b/packages/invoice-core/src/invoice_core/parsers/__init__.py index dc0facd..0a806d6 100644 --- a/packages/invoice-core/src/invoice_core/parsers/__init__.py +++ b/packages/invoice-core/src/invoice_core/parsers/__init__.py @@ -1,8 +1,24 @@ """Document parsers for invoice-core.""" from invoice_core.parsers.pdf_text import extract_pdf_text_layer, render_pdf_pages +from invoice_core.parsers.vision import ( + VisionAPIError, + build_chat_completions_url, + build_vision_messages, + build_vision_payload, + extract_chat_completion_text, + parse_invoice_with_vision, + uses_max_completion_tokens, +) __all__ = [ "extract_pdf_text_layer", "render_pdf_pages", + "VisionAPIError", + "build_chat_completions_url", + "build_vision_messages", + "build_vision_payload", + "extract_chat_completion_text", + "parse_invoice_with_vision", + "uses_max_completion_tokens", ] diff --git a/packages/invoice-core/src/invoice_core/parsers/vision.py b/packages/invoice-core/src/invoice_core/parsers/vision.py new file mode 100644 index 0000000..f1e6ded --- /dev/null +++ b/packages/invoice-core/src/invoice_core/parsers/vision.py @@ -0,0 +1,292 @@ +"""Stateless OpenAI-compatible vision invoice parsing helpers. + +Pure Python with no global configuration or web/DB/OCR dependencies. +Uses ``httpx`` when installed (via the ``[vision]`` optional extra) and falls +back to ``urllib.request`` from the standard library otherwise. +""" + +from __future__ import annotations + +import base64 +import json +import urllib.error +import urllib.request +from typing import Any, Mapping, Optional + +from invoice_core.llm_json import parse_json_response +from invoice_core.prompts import INVOICE_VISION_PROMPT, INVOICE_VISION_SYSTEM_PROMPT + +DEFAULT_USER_AGENT = "python-httpx/0.26.0" + + +class VisionAPIError(RuntimeError): + """Raised when an OpenAI-compatible vision API request fails or returns an invalid payload.""" + + def __init__(self, message: str, status_code: Optional[int] = None, response_body: str = ""): + super().__init__(message) + self.status_code = status_code + self.response_body = response_body + + +def uses_max_completion_tokens(model: str) -> bool: + """Return True if the model expects ``max_completion_tokens`` instead of ``max_tokens``.""" + lowered = model.strip().lower() + # Handle both native IDs (e.g. "o1-mini") and gateway-prefixed IDs (e.g. "openai/gpt-5-mini") + short_name = lowered.split("/")[-1] + return any(short_name.startswith(prefix) for prefix in ("o1", "o3", "gpt-5")) + + +def build_chat_completions_url(base_url: str) -> str: + """Normalize an OpenAI-compatible base URL into a chat completions endpoint URL.""" + cleaned = base_url.strip().rstrip("/") + if not cleaned: + raise ValueError("base_url must not be empty") + if cleaned.endswith("/chat/completions"): + return cleaned + return f"{cleaned}/chat/completions" + + +def build_vision_messages( + image_bytes: bytes, + mime_type: str = "image/png", + system_prompt: str = INVOICE_VISION_SYSTEM_PROMPT, + user_prompt: str = INVOICE_VISION_PROMPT, +) -> list[dict[str, Any]]: + """Build OpenAI-compatible chat messages containing a base64-encoded invoice image.""" + if not image_bytes: + raise ValueError("image_bytes must not be empty") + + encoded = base64.b64encode(image_bytes).decode("ascii") + return [ + {"role": "system", "content": system_prompt}, + { + "role": "user", + "content": [ + {"type": "text", "text": user_prompt}, + { + "type": "image_url", + "image_url": {"url": f"data:{mime_type};base64,{encoded}"}, + }, + ], + }, + ] + + +def build_vision_payload( + image_bytes: bytes, + model: str, + *, + mime_type: str = "image/png", + system_prompt: str = INVOICE_VISION_SYSTEM_PROMPT, + user_prompt: str = INVOICE_VISION_PROMPT, + temperature: float = 0.1, + max_tokens: int = 1500, +) -> dict[str, Any]: + """Build the full JSON request payload for an OpenAI-compatible vision chat completion.""" + if not model or not model.strip(): + raise ValueError("model must not be empty") + + token_key = "max_completion_tokens" if uses_max_completion_tokens(model) else "max_tokens" + return { + "model": model.strip(), + "messages": build_vision_messages( + image_bytes=image_bytes, + mime_type=mime_type, + system_prompt=system_prompt, + user_prompt=user_prompt, + ), + "temperature": temperature, + token_key: max_tokens, + } + + +def extract_chat_completion_text(response_data: Mapping[str, Any]) -> str: + """Extract assistant text content from an OpenAI-compatible chat completion JSON response.""" + choices = response_data.get("choices") + if not isinstance(choices, list) or not choices: + raise VisionAPIError("Vision API response missing non-empty 'choices'") + + first_choice = choices[0] + if not isinstance(first_choice, Mapping): + raise VisionAPIError("Vision API response choice is not an object") + + message = first_choice.get("message") + if not isinstance(message, Mapping): + raise VisionAPIError("Vision API response choice missing 'message'") + + content = message.get("content") + if isinstance(content, str): + text = content.strip() + if text: + return text + raise VisionAPIError("Vision API response message content is empty") + + if isinstance(content, list): + parts: list[str] = [] + for item in content: + if isinstance(item, Mapping) and item.get("type") == "text" and isinstance(item.get("text"), str): + parts.append(item["text"]) + elif isinstance(item, str): + parts.append(item) + text = "".join(parts).strip() + if text: + return text + raise VisionAPIError("Vision API response content blocks contained no text") + + raise VisionAPIError("Vision API response message content has unsupported type") + + +def _post_json_with_httpx( + url: str, + payload: dict[str, Any], + headers: dict[str, str], + timeout: float, + http_client: Any = None, +) -> dict[str, Any]: + httpx_errors: tuple[type[BaseException], ...] = () + try: + import httpx + except ImportError: + httpx = None # type: ignore[assignment] + else: + httpx_errors = (httpx.RequestError,) + + try: + if http_client is not None: + response = http_client.post(url, json=payload, headers=headers, timeout=timeout) + else: + if httpx is None: + raise RuntimeError("httpx is required when http_client is not provided") + with httpx.Client(timeout=timeout) as client: + response = client.post(url, json=payload, headers=headers) + except (*httpx_errors, TimeoutError, OSError) as exc: + raise VisionAPIError(f"Vision API request failed: {exc}") from exc + + status_code = getattr(response, "status_code", None) + body_text = getattr(response, "text", "") + if status_code is None or status_code < 200 or status_code >= 300: + raise VisionAPIError( + f"Vision API request failed with HTTP {status_code}: {body_text[:200]}", + status_code=status_code, + response_body=body_text, + ) + + try: + data = response.json() + except Exception as exc: + raise VisionAPIError( + f"Vision API returned non-JSON body: {body_text[:200]}", + status_code=status_code, + response_body=body_text, + ) from exc + + if not isinstance(data, dict): + raise VisionAPIError( + "Vision API JSON response must be an object", + status_code=status_code, + response_body=body_text, + ) + return data + + +def _post_json_with_urllib( + url: str, + payload: dict[str, Any], + headers: dict[str, str], + timeout: float, +) -> dict[str, Any]: + encoded_body = json.dumps(payload, ensure_ascii=False).encode("utf-8") + req = urllib.request.Request(url, data=encoded_body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + status_code = getattr(resp, "status", 200) + body_text = resp.read().decode("utf-8", errors="replace") + except urllib.error.HTTPError as exc: + err_body = exc.read().decode("utf-8", errors="replace") if exc.fp else "" + raise VisionAPIError( + f"Vision API request failed with HTTP {exc.code}: {err_body[:200]}", + status_code=exc.code, + response_body=err_body, + ) from exc + except urllib.error.URLError as exc: + raise VisionAPIError(f"Vision API connection error: {exc.reason}") from exc + except (TimeoutError, OSError) as exc: + raise VisionAPIError(f"Vision API connection error: {exc}") from exc + + try: + data = json.loads(body_text) + except json.JSONDecodeError as exc: + raise VisionAPIError( + f"Vision API returned non-JSON body: {body_text[:200]}", + status_code=status_code, + response_body=body_text, + ) from exc + + if not isinstance(data, dict): + raise VisionAPIError( + "Vision API JSON response must be an object", + status_code=status_code, + response_body=body_text, + ) + return data + + +def _post_json( + url: str, + payload: dict[str, Any], + headers: dict[str, str], + timeout: float, + http_client: Any = None, +) -> dict[str, Any]: + if http_client is not None: + return _post_json_with_httpx(url, payload, headers, timeout, http_client=http_client) + + try: + import httpx # noqa: F401 + except ImportError: + return _post_json_with_urllib(url, payload, headers, timeout) + + return _post_json_with_httpx(url, payload, headers, timeout, http_client=None) + + +def parse_invoice_with_vision( + image_bytes: bytes, + base_url: str, + api_key: str, + model: str, + *, + mime_type: str = "image/png", + system_prompt: str = INVOICE_VISION_SYSTEM_PROMPT, + user_prompt: str = INVOICE_VISION_PROMPT, + timeout: float = 60.0, + provider_name: str = "vision", + headers: Optional[Mapping[str, str]] = None, + http_client: Any = None, +) -> dict[str, Optional[str]]: + """Call an OpenAI-compatible vision endpoint and normalize the extracted invoice JSON.""" + if not api_key or not api_key.strip(): + raise ValueError("api_key must not be empty") + + url = build_chat_completions_url(base_url) + payload = build_vision_payload( + image_bytes=image_bytes, + model=model, + mime_type=mime_type, + system_prompt=system_prompt, + user_prompt=user_prompt, + ) + req_headers: dict[str, str] = { + "Authorization": f"Bearer {api_key.strip()}", + "Content-Type": "application/json", + "User-Agent": DEFAULT_USER_AGENT, + } + if headers: + req_headers.update(headers) + + response_data = _post_json(url, payload, req_headers, timeout=timeout, http_client=http_client) + content = extract_chat_completion_text(response_data) + return parse_json_response(content, provider_name=provider_name) + + +# Short alias matching architecture spec (vision.parse) +parse = parse_invoice_with_vision diff --git a/packages/invoice-core/tests/test_import_guard.py b/packages/invoice-core/tests/test_import_guard.py index 8981f4e..e819850 100644 --- a/packages/invoice-core/tests/test_import_guard.py +++ b/packages/invoice-core/tests/test_import_guard.py @@ -75,4 +75,5 @@ def test_runtime_sys_modules_forbids_backend_and_heavy_imports(): assert "invoice_core.llm_json" in result["loaded"] assert "invoice_core.prompts" in result["loaded"] assert "invoice_core.parsers.pdf_text" in result["loaded"] + assert "invoice_core.parsers.vision" in result["loaded"] assert result["hits"] == [], f"Forbidden modules loaded at runtime: {result['hits']}" diff --git a/packages/invoice-core/tests/test_vision.py b/packages/invoice-core/tests/test_vision.py new file mode 100644 index 0000000..4e97c0a --- /dev/null +++ b/packages/invoice-core/tests/test_vision.py @@ -0,0 +1,306 @@ +"""Pure unit tests for invoice_core.parsers.vision.""" + +from __future__ import annotations + +import base64 +import io +import json +import sys +import types +import urllib.error +import urllib.request +from typing import Any + +import pytest + +from invoice_core.parsers import vision +from invoice_core.parsers.vision import ( + VisionAPIError, + build_chat_completions_url, + build_vision_messages, + build_vision_payload, + extract_chat_completion_text, + parse_invoice_with_vision, + uses_max_completion_tokens, +) + +SYNTH_INV_NUM = "0" * 16 + "0042" +SYNTH_BUYER_TAX = "TESTBUYER000001" +SYNTH_SELLER_TAX = "TESTSELLER00001" + + +class _FakeResponse: + def __init__(self, status_code: int, payload: Any = None, text: str = ""): + self.status_code = status_code + self._payload = payload + self.text = text or (json.dumps(payload, ensure_ascii=False) if payload is not None else "") + + def json(self): + if isinstance(self._payload, Exception): + raise self._payload + return self._payload + + +class _FakeClient: + def __init__(self, response: _FakeResponse): + self.response = response + self.calls: list[dict[str, Any]] = [] + + def post(self, url: str, *, json: dict[str, Any], headers: dict[str, str], timeout: float): + self.calls.append({"url": url, "json": json, "headers": headers, "timeout": timeout}) + return self.response + + +def test_build_chat_completions_url_normalizes_trailing_slash_and_suffix(): + assert build_chat_completions_url("https://api.example.com/v1") == "https://api.example.com/v1/chat/completions" + assert build_chat_completions_url("https://api.example.com/v1/") == "https://api.example.com/v1/chat/completions" + assert ( + build_chat_completions_url("https://api.example.com/v1/chat/completions") + == "https://api.example.com/v1/chat/completions" + ) + with pytest.raises(ValueError): + build_chat_completions_url(" ") + + +def test_build_vision_messages_and_payload_token_param(): + raw_img = b"\x89PNG\r\n\x1a\nfake-image" + messages = build_vision_messages(raw_img, mime_type="image/jpeg", system_prompt="SYS", user_prompt="USR") + assert messages[0] == {"role": "system", "content": "SYS"} + user_parts = messages[1]["content"] + assert user_parts[0] == {"type": "text", "text": "USR"} + expected_b64 = base64.b64encode(raw_img).decode("ascii") + assert user_parts[1] == {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{expected_b64}"}} + + payload_std = build_vision_payload(raw_img, model="vendor/vision-pro") + assert payload_std["model"] == "vendor/vision-pro" + assert payload_std["max_tokens"] == 1500 + assert "max_completion_tokens" not in payload_std + + payload_new = build_vision_payload(raw_img, model="openai/gpt-5-mini") + assert payload_new["max_completion_tokens"] == 1500 + assert "max_tokens" not in payload_new + assert uses_max_completion_tokens("o1-mini") is True + assert uses_max_completion_tokens("o3") is True + assert uses_max_completion_tokens("gpt-4o-mini") is False + + +def test_parse_invoice_with_vision_success_via_http_client(): + raw_img = b"fake-png-bytes" + llm_json = { + "invoice_number": f" {SYNTH_INV_NUM} ", + "invoice_code": "1234-5678-9012", + "issue_date": "2026年05月06日", + "buyer_name": " 示例买方有限公司 ", + "buyer_tax_id": SYNTH_BUYER_TAX.lower(), + "seller_name": "示例卖方有限公司", + "seller_tax_id": SYNTH_SELLER_TAX, + "item_name": "*技术服务*云资源", + "total_with_tax": "¥1,234.50", + "amount": 1164.62, + "tax_amount": "69.88", + "tax_rate": "6%", + } + fake_client = _FakeClient( + _FakeResponse( + 200, + { + "choices": [ + {"message": {"content": f"```json\n{json.dumps(llm_json, ensure_ascii=False)}\n```"}} + ] + }, + ) + ) + + result = parse_invoice_with_vision( + raw_img, + base_url="https://gateway.example.com/v1/", + api_key="sk-test-token", + model="vendor/vision-pro", + mime_type="image/png", + provider_name="custom", + headers={"X-Custom": "1"}, + http_client=fake_client, + ) + + assert len(fake_client.calls) == 1 + call = fake_client.calls[0] + assert call["url"] == "https://gateway.example.com/v1/chat/completions" + assert call["headers"]["Authorization"] == "Bearer sk-test-token" + assert call["headers"]["X-Custom"] == "1" + assert call["json"]["model"] == "vendor/vision-pro" + + assert result["invoice_number"] == SYNTH_INV_NUM + assert result["invoice_code"] == "123456789012" + assert result["issue_date"] == "2026-05-06" + assert result["buyer_tax_id"] == SYNTH_BUYER_TAX + assert result["seller_tax_id"] == SYNTH_SELLER_TAX + assert result["total_with_tax"] == "1234.50" + assert result["tax_rate"] == "6%" + + +def test_parse_invoice_with_vision_handles_content_blocks_and_urllib_fallback(monkeypatch): + llm_json = { + "invoice_number": "12345678", + "invoice_code": None, + "issue_date": "2026-03-01", + "buyer_name": "测试买方", + "buyer_tax_id": SYNTH_BUYER_TAX, + "seller_name": "测试卖方", + "seller_tax_id": SYNTH_SELLER_TAX, + "item_name": "办公用品", + "total_with_tax": "100.00", + "amount": "94.34", + "tax_amount": "5.66", + "tax_rate": "6%", + } + response_body = json.dumps( + { + "choices": [ + { + "message": { + "content": [ + {"type": "text", "text": json.dumps(llm_json, ensure_ascii=False)} + ] + } + } + ] + }, + ensure_ascii=False, + ).encode("utf-8") + + class _UrllibResp(io.BytesIO): + status = 200 + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + captured: dict[str, Any] = {} + + def _fake_urlopen(req, timeout=None): + captured["url"] = req.full_url + captured["auth"] = req.get_header("Authorization") + captured["timeout"] = timeout + return _UrllibResp(response_body) + + monkeypatch.setattr(urllib.request, "urlopen", _fake_urlopen) + + # Exercise urllib fallback directly + result_data = vision._post_json_with_urllib( + "https://api.example.com/v1/chat/completions", + {"model": "m"}, + {"Authorization": "Bearer sk-1", "Content-Type": "application/json"}, + timeout=12.0, + ) + assert captured["url"] == "https://api.example.com/v1/chat/completions" + assert captured["auth"] == "Bearer sk-1" + assert captured["timeout"] == 12.0 + assert extract_chat_completion_text(result_data) == json.dumps(llm_json, ensure_ascii=False) + + +def test_parse_invoice_with_vision_error_handling(monkeypatch): + with pytest.raises(ValueError, match="api_key"): + parse_invoice_with_vision(b"img", "https://api.example.com/v1", "", "m") + + with pytest.raises(ValueError, match="image_bytes"): + parse_invoice_with_vision(b"", "https://api.example.com/v1", "sk-1", "m") + + with pytest.raises(ValueError, match="model"): + parse_invoice_with_vision(b"img", "https://api.example.com/v1", "sk-1", "") + + # HTTP 401 -> VisionAPIError + err_client = _FakeClient(_FakeResponse(401, {"error": "unauthorized"})) + with pytest.raises(VisionAPIError) as exc_info: + parse_invoice_with_vision(b"img", "https://api.example.com/v1", "sk-bad", "m", http_client=err_client) + assert exc_info.value.status_code == 401 + + # Missing choices -> VisionAPIError + empty_client = _FakeClient(_FakeResponse(200, {"choices": []})) + with pytest.raises(VisionAPIError, match="choices"): + parse_invoice_with_vision(b"img", "https://api.example.com/v1", "sk-1", "m", http_client=empty_client) + + # Non-JSON LLM content -> JSONDecodeError propagated from parse_json_response + bad_json_client = _FakeClient(_FakeResponse(200, {"choices": [{"message": {"content": "not json"}}]})) + with pytest.raises(json.JSONDecodeError): + parse_invoice_with_vision(b"img", "https://api.example.com/v1", "sk-1", "m", http_client=bad_json_client) + + # urllib HTTPError -> VisionAPIError + def _raise_http_error(req, timeout=None): + raise urllib.error.HTTPError(req.full_url, 502, "Bad Gateway", {}, io.BytesIO(b"upstream error")) + + monkeypatch.setattr(urllib.request, "urlopen", _raise_http_error) + with pytest.raises(VisionAPIError) as url_exc: + vision._post_json_with_urllib("https://api.example.com/v1/chat/completions", {}, {}, timeout=5.0) + assert url_exc.value.status_code == 502 + + +@pytest.mark.parametrize( + "exc_factory", + [ + lambda: urllib.error.URLError("dns resolution failed"), + lambda: TimeoutError("read timed out"), + lambda: OSError("network unreachable"), + ], +) +def test_urllib_transport_and_timeout_errors_raise_vision_api_error(monkeypatch, exc_factory): + """All urllib network/timeout failures must be normalized into VisionAPIError.""" + + def _raise_err(req, timeout=None): + raise exc_factory() + + monkeypatch.setattr(urllib.request, "urlopen", _raise_err) + with pytest.raises(VisionAPIError) as exc_info: + vision._post_json_with_urllib("https://api.example.com/v1/chat/completions", {}, {}, timeout=5.0) + assert exc_info.value.__cause__ is not None + + +def test_httpx_request_and_timeout_errors_raise_vision_api_error(monkeypatch): + """httpx.RequestError subclasses and injected-client transport errors must raise VisionAPIError.""" + + class _FakeRequestError(Exception): + pass + + class _FakeReadTimeout(_FakeRequestError): + pass + + class _FakeHttpxClient: + def __init__(self, timeout=None): + self.timeout = timeout + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def post(self, url, *, json=None, headers=None, timeout=None): + raise _FakeReadTimeout("simulated httpx timeout") + + fake_httpx = types.SimpleNamespace( + RequestError=_FakeRequestError, + Client=_FakeHttpxClient, + ) + monkeypatch.setitem(sys.modules, "httpx", fake_httpx) + + # Default httpx client path (http_client=None) wraps httpx.RequestError -> VisionAPIError + with pytest.raises(VisionAPIError, match="simulated httpx timeout") as exc_info: + parse_invoice_with_vision(b"img", "https://api.example.com/v1", "sk-1", "m") + assert isinstance(exc_info.value.__cause__, _FakeReadTimeout) + + # Injected http_client path also normalizes httpx.RequestError, TimeoutError, and OSError + for err in (_FakeRequestError("conn reset"), TimeoutError("timed out"), OSError("broken pipe")): + class _FailingClient: + def post(self, url, *, json, headers, timeout): + raise err + + with pytest.raises(VisionAPIError) as injected_exc: + parse_invoice_with_vision( + b"img", + "https://api.example.com/v1", + "sk-1", + "m", + http_client=_FailingClient(), + ) + assert injected_exc.value.__cause__ is err From fe86065b2f817d76c98bc9d9da3de8b6379e7f0e Mon Sep 17 00:00:00 2001 From: stone16 <12712299+stone16@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:04:17 +0800 Subject: [PATCH 2/4] feat(settings): unify provider presets, explicit vision switch, and async model registry --- backend/app/config.py | 168 ++++- backend/app/routers/settings.py | 550 +++++++------- backend/app/services/llm_service.py | 722 ++++++++----------- backend/app/services/model_registry.py | 374 +++++----- backend/app/services/provider_presets.py | 291 ++++++++ backend/tests/test_config.py | 16 + backend/tests/test_providers_and_settings.py | 561 ++++++++++++++ 7 files changed, 1782 insertions(+), 900 deletions(-) create mode 100644 backend/app/services/provider_presets.py create mode 100644 backend/tests/test_providers_and_settings.py diff --git a/backend/app/config.py b/backend/app/config.py index 5484840..040ea85 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -1,8 +1,16 @@ import os from functools import lru_cache -from typing import Optional +from typing import Any, Optional + +from pydantic import field_validator from pydantic_settings import BaseSettings, SettingsConfigDict +from app.services.provider_presets import ( + PRESET_BY_ID, + PROVIDER_PRESETS, + resolve_provider_id, +) + def get_env_file_path() -> str: """Return the configured .env file path (defaults to '.env').""" @@ -17,41 +25,71 @@ class Settings(BaseSettings): database_url: str = "postgresql+asyncpg://postgres:postgres@db:5432/invoice_db" # LLM Provider Configuration - # Supported providers: openai, anthropic, google, qwen, deepseek, zhipu + # Supported canonical providers: + # openai, anthropic, google, qwen, deepseek, zhipu, kimi, doubao, siliconflow, openrouter, openai_compatible + # Legacy aliases (gemini, claude, custom, etc.) are resolved automatically. llm_provider: str = "" # Active provider (empty = not configured) + # Explicit vision override; None = infer from preset/model defaults + llm_supports_vision: Optional[bool] = None + # Optional admin token for /api/settings/llm/configure llm_config_token: str = "" # OpenAI openai_api_key: str = "" openai_model: str = "gpt-4o-mini" - openai_base_url: str = "" # Custom base URL (for OpenAI-compatible APIs) + openai_base_url: str = "" # Custom base URL (empty = official https://api.openai.com/v1) # Anthropic (Claude) anthropic_api_key: str = "" - anthropic_model: str = "claude-3-haiku-20240307" - anthropic_base_url: str = "" # Custom base URL (e.g., for proxy) + anthropic_model: str = "claude-sonnet-4-20250514" + anthropic_base_url: str = "https://api.anthropic.com/v1" - # Google (Gemini) + # Google (Gemini via official OpenAI-compatible endpoint) google_api_key: str = "" - google_model: str = "gemini-1.5-flash" - google_base_url: str = "" # Custom base URL (e.g., for proxy) + google_model: str = "gemini-2.5-flash" + google_base_url: str = "https://generativelanguage.googleapis.com/v1beta/openai/" - # Qwen (Alibaba) + # Qwen (Alibaba DashScope) qwen_api_key: str = "" - qwen_model: str = "qwen-turbo" + qwen_model: str = "qwen-vl-plus" qwen_base_url: str = "https://dashscope.aliyuncs.com/compatible-mode/v1" # DeepSeek deepseek_api_key: str = "" deepseek_model: str = "deepseek-chat" - deepseek_base_url: str = "https://api.deepseek.com" + deepseek_base_url: str = "https://api.deepseek.com/v1" # Zhipu (GLM) zhipu_api_key: str = "" - zhipu_model: str = "glm-4-flash" - zhipu_base_url: str = "" # Custom base URL (e.g., for proxy) + zhipu_model: str = "glm-4v-plus" + zhipu_base_url: str = "https://open.bigmodel.cn/api/paas/v4" + + # Kimi / Moonshot + kimi_api_key: str = "" + kimi_model: str = "moonshot-v1-8k-vision-preview" + kimi_base_url: str = "https://api.moonshot.cn/v1" + + # Doubao (Volcengine Ark) + doubao_api_key: str = "" + doubao_model: str = "doubao-1-5-vision-pro-32k-250115" + doubao_base_url: str = "https://ark.cn-beijing.volces.com/api/v3" + + # SiliconFlow + siliconflow_api_key: str = "" + siliconflow_model: str = "Qwen/Qwen2.5-VL-72B-Instruct" + siliconflow_base_url: str = "https://api.siliconflow.cn/v1" + + # OpenRouter + openrouter_api_key: str = "" + openrouter_model: str = "openai/gpt-4o-mini" + openrouter_base_url: str = "https://openrouter.ai/api/v1" + + # Custom OpenAI-compatible / Aggregator endpoint + openai_compatible_api_key: str = "" + openai_compatible_model: str = "" + openai_compatible_base_url: str = "" # File upload max_file_size: int = 10 * 1024 * 1024 # 10MB @@ -69,31 +107,99 @@ class Settings(BaseSettings): model_config = SettingsConfigDict(env_file=ENV_FILE, extra="ignore") + @field_validator("llm_supports_vision", mode="before") + @classmethod + def _parse_optional_bool(cls, value: Any) -> Optional[bool]: + if value is None: + return None + if isinstance(value, bool): + return value + if isinstance(value, str): + cleaned = value.strip().lower() + if cleaned == "": + return None + if cleaned in ("true", "1", "yes", "on"): + return True + if cleaned in ("false", "0", "no", "off"): + return False + return value + + def get_provider_credentials(self, provider_id: str) -> tuple[str, str, str]: + """Return ``(api_key, model, base_url)`` for a canonical provider ID or alias.""" + canonical = resolve_provider_id(provider_id) + preset = PRESET_BY_ID.get(canonical) + attr_map: dict[str, tuple[str, str, str]] = { + "openai": (self.openai_api_key, self.openai_model, self.openai_base_url), + "anthropic": (self.anthropic_api_key, self.anthropic_model, self.anthropic_base_url), + "google": (self.google_api_key, self.google_model, self.google_base_url), + "qwen": (self.qwen_api_key, self.qwen_model, self.qwen_base_url), + "deepseek": (self.deepseek_api_key, self.deepseek_model, self.deepseek_base_url), + "zhipu": (self.zhipu_api_key, self.zhipu_model, self.zhipu_base_url), + "kimi": (self.kimi_api_key, self.kimi_model, self.kimi_base_url), + "doubao": (self.doubao_api_key, self.doubao_model, self.doubao_base_url), + "siliconflow": ( + self.siliconflow_api_key, + self.siliconflow_model, + self.siliconflow_base_url, + ), + "openrouter": ( + self.openrouter_api_key, + self.openrouter_model, + self.openrouter_base_url, + ), + "openai_compatible": ( + self.openai_compatible_api_key, + self.openai_compatible_model, + self.openai_compatible_base_url, + ), + } + api_key, model, base_url = attr_map.get(canonical, ("", "", "")) + if preset is not None: + if not model: + model = preset.default_model + if not base_url: + base_url = preset.base_url + return api_key, model, base_url + + def is_provider_configured(self, provider_id: str) -> bool: + """Return True if the specified provider has required credentials configured.""" + canonical = resolve_provider_id(provider_id) + api_key, _model, base_url = self.get_provider_credentials(canonical) + if not api_key: + return False + if canonical == "openai_compatible": + return bool(base_url.strip()) + return True + def get_active_llm_provider(self) -> Optional[str]: - """Get the active LLM provider based on configuration.""" - # If explicitly set, use that + """Get the canonical active LLM provider based on configuration.""" if self.llm_provider: - return self.llm_provider - - # Auto-detect based on available API keys - if self.openai_api_key: - return "openai" - if self.anthropic_api_key: - return "anthropic" - if self.google_api_key: - return "google" - if self.qwen_api_key: - return "qwen" - if self.deepseek_api_key: - return "deepseek" - if self.zhipu_api_key: - return "zhipu" + return resolve_provider_id(self.llm_provider) + + # Auto-detect based on available API keys (preserve historical priority order first) + priority_order = ( + "openai", + "anthropic", + "google", + "qwen", + "deepseek", + "zhipu", + *(p.id for p in PROVIDER_PRESETS if p.id not in { + "openai", "anthropic", "google", "qwen", "deepseek", "zhipu" + }), + ) + for provider_id in priority_order: + if self.is_provider_configured(provider_id): + return provider_id return None def is_llm_configured(self) -> bool: """Check if any LLM provider is configured.""" - return self.get_active_llm_provider() is not None + active = self.get_active_llm_provider() + if not active: + return False + return self.is_provider_configured(active) @lru_cache diff --git a/backend/app/routers/settings.py b/backend/app/routers/settings.py index 71b0599..6ba4a3d 100644 --- a/backend/app/routers/settings.py +++ b/backend/app/routers/settings.py @@ -1,14 +1,44 @@ """Settings and configuration API endpoints.""" +from __future__ import annotations + import logging import os import tempfile +import time from pathlib import Path -from typing import Optional, List +from typing import Any, List, Optional + +import httpx +from fastapi import APIRouter, Header, HTTPException from pydantic import BaseModel -from fastapi import APIRouter, HTTPException, Header from app import config as app_config +from app.services.llm_service import ( + ANTHROPIC_API_VERSION, + PROVIDERS, + _get_max_tokens_param, + build_anthropic_messages_url, + extract_anthropic_text, + get_llm_service, + reset_llm_service, +) +from app.services.model_registry import ( + get_all_models_with_fallback_async, + get_models_with_fallback_async, +) +from app.services.provider_presets import ( + PRESET_BY_ID, + PROVIDER_ENV_VARS, + PROVIDER_PRESETS, + list_presets, + resolve_provider_id, +) +from invoice_core.parsers.vision import ( + DEFAULT_USER_AGENT, + build_chat_completions_url, + extract_chat_completion_text, +) logger = logging.getLogger(__name__) @@ -41,7 +71,6 @@ def _update_env_file(updates: dict[str, str]) -> None: if stripped and not stripped.startswith("#") and "=" in stripped: key = stripped.split("=", 1)[0].strip() if key in updates: - # Replace this line with updated value new_lines.append(f"{key}={updates[key]}\n") updated_keys.add(key) else: @@ -81,7 +110,7 @@ def _update_env_file(updates: dict[str, str]) -> None: pass raise - logger.info(f"Updated .env file ({env_path}) with keys: {list(updates.keys())}") + logger.info("Updated .env file (%s) with keys: %s", env_path, list(updates.keys())) def _require_llm_config_token( @@ -104,93 +133,138 @@ def _require_llm_config_token( if not candidate or candidate != required_token: raise HTTPException(status_code=401, detail="未授权") -from app.services.llm_service import get_llm_service, reset_llm_service, PROVIDERS -from app.services.model_registry import get_models_with_fallback + +def _validate_no_newlines(*values: Optional[str]) -> None: + for value in values: + if value is not None and ("\r" in value or "\n" in value): + raise HTTPException(status_code=400, detail="配置项不能包含换行符") + router = APIRouter() +class PresetModelInfo(BaseModel): + """Static model item inside a provider preset.""" + + id: str + name: str + vision: bool + + +class ProviderPresetInfo(BaseModel): + """Preset metadata returned to frontend settings and onboarding.""" + + id: str + name: str + category: str + protocol: str + base_url: str + docs_url: str + default_model: str + models: List[PresetModelInfo] = [] + supports_vision: bool + recommended: bool = False + description: str = "" + + class LLMProviderInfo(BaseModel): - """Information about an LLM provider.""" + """Backward-compatible provider status entry.""" + name: str display_name: str is_configured: bool model: Optional[str] = None base_url: Optional[str] = None + category: Optional[str] = None + supports_vision: Optional[bool] = None + docs_url: Optional[str] = None class LLMStatusResponse(BaseModel): """Response for LLM status check.""" + is_configured: bool active_provider: Optional[str] = None active_provider_display: Optional[str] = None + active_model: Optional[str] = None + active_base_url: Optional[str] = None + supports_vision: bool = False configured_providers: List[str] = [] available_providers: List[LLMProviderInfo] = [] + presets: List[ProviderPresetInfo] = [] class LLMConfigRequest(BaseModel): """Request to configure an LLM provider.""" + provider: str api_key: str model: Optional[str] = None base_url: Optional[str] = None + supports_vision: Optional[bool] = None class LLMConfigResponse(BaseModel): """Response after configuring LLM.""" + success: bool message: str provider: Optional[str] = None -# Display names for providers -PROVIDER_DISPLAY_NAMES = { - "openai": "OpenAI (GPT)", - "anthropic": "Anthropic (Claude)", - "google": "Google (Gemini)", - "qwen": "阿里云 (通义千问)", - "deepseek": "DeepSeek", - "zhipu": "智谱 (GLM)", -} - -# Default models for providers -DEFAULT_MODELS = { - "openai": "gpt-4o-mini", - "anthropic": "claude-3-haiku-20240307", - "google": "gemini-1.5-flash", - "qwen": "qwen-turbo", - "deepseek": "deepseek-chat", - "zhipu": "glm-4-flash", -} +# Display names derived from single static preset table +PROVIDER_DISPLAY_NAMES: dict[str, str] = {preset.id: preset.name for preset in PROVIDER_PRESETS} +DEFAULT_MODELS: dict[str, str] = {preset.id: preset.default_model for preset in PROVIDER_PRESETS} @router.get("/llm/status", response_model=LLMStatusResponse) async def get_llm_status(): - """Get LLM configuration status.""" + """Get LLM configuration status and full static provider presets.""" settings = app_config.get_settings() llm_service = get_llm_service() active_provider = settings.get_active_llm_provider() + is_configured = settings.is_llm_configured() configured_providers = llm_service.get_configured_providers() - # Build available providers list - available_providers = [] - for name in PROVIDERS.keys(): - provider_info = LLMProviderInfo( - name=name, - display_name=PROVIDER_DISPLAY_NAMES.get(name, name), - is_configured=name in configured_providers, - model=_get_provider_model(name) if name in configured_providers else DEFAULT_MODELS.get(name), - base_url=_get_provider_base_url(name) if name in configured_providers else None, + active_model: Optional[str] = None + active_base_url: Optional[str] = None + if active_provider and is_configured: + _key, model, base_url = settings.get_provider_credentials(active_provider) + active_model = model or None + active_base_url = base_url or None + + available_providers: List[LLMProviderInfo] = [] + for preset in PROVIDER_PRESETS: + is_prov_configured = preset.id in configured_providers + _key, prov_model, prov_base_url = settings.get_provider_credentials(preset.id) + available_providers.append( + LLMProviderInfo( + name=preset.id, + display_name=preset.name, + is_configured=is_prov_configured, + model=prov_model if is_prov_configured else (preset.default_model or None), + base_url=prov_base_url if is_prov_configured else (preset.base_url or None), + category=preset.category, + supports_vision=preset.supports_vision, + docs_url=preset.docs_url or None, + ) ) - available_providers.append(provider_info) return LLMStatusResponse( - is_configured=settings.is_llm_configured(), - active_provider=active_provider, - active_provider_display=PROVIDER_DISPLAY_NAMES.get(active_provider, active_provider) if active_provider else None, + is_configured=is_configured, + active_provider=active_provider if is_configured else None, + active_provider_display=( + PROVIDER_DISPLAY_NAMES.get(active_provider, active_provider) + if (active_provider and is_configured) + else None + ), + active_model=active_model, + active_base_url=active_base_url, + supports_vision=llm_service.supports_vision() if is_configured else False, configured_providers=configured_providers, available_providers=available_providers, + presets=[ProviderPresetInfo(**item) for item in list_presets()], ) @@ -200,61 +274,58 @@ async def configure_llm( x_llm_config_token: Optional[str] = Header(default=None, alias="X-LLM-Config-Token"), authorization: Optional[str] = Header(default=None), ): - """Configure an LLM provider and persist to .env file.""" - provider = request.provider.lower() - + """Configure an LLM provider and persist atomically to the env file.""" _require_llm_config_token( app_config.get_settings().llm_config_token, x_llm_config_token, authorization, ) - for value in (request.provider, request.api_key, request.model, request.base_url): - if value is not None and ("\r" in value or "\n" in value): - raise HTTPException(status_code=400, detail="配置项不能包含换行符") + _validate_no_newlines(request.provider, request.api_key, request.model, request.base_url) - if provider not in PROVIDERS: + provider = resolve_provider_id(request.provider) + if provider not in PROVIDERS or provider not in PROVIDER_ENV_VARS: raise HTTPException( status_code=400, - detail=f"不支持的LLM提供商: {provider}。支持的提供商: {', '.join(PROVIDERS.keys())}" + detail=f"不支持的LLM提供商: {request.provider}。支持的提供商: {', '.join(PROVIDERS.keys())}", ) - if not request.api_key: + api_key = request.api_key.strip() + if not api_key: raise HTTPException(status_code=400, detail="API密钥不能为空") + preset = PRESET_BY_ID[provider] + base_url = request.base_url.strip() if request.base_url is not None else "" + effective_base_url = base_url or preset.base_url + if provider == "openai_compatible" and not effective_base_url: + raise HTTPException(status_code=400, detail="自定义服务必须填写 API 地址 (Base URL)") + + model = (request.model or "").strip() or preset.default_model + try: - # Build env updates for both os.environ and .env file - env_updates: dict[str, str] = {"LLM_PROVIDER": provider} - - # Provider-specific configuration - provider_config = { - "openai": ("OPENAI_API_KEY", "OPENAI_MODEL", "OPENAI_BASE_URL"), - "anthropic": ("ANTHROPIC_API_KEY", "ANTHROPIC_MODEL", "ANTHROPIC_BASE_URL"), - "google": ("GOOGLE_API_KEY", "GOOGLE_MODEL", "GOOGLE_BASE_URL"), - "qwen": ("QWEN_API_KEY", "QWEN_MODEL", "QWEN_BASE_URL"), - "deepseek": ("DEEPSEEK_API_KEY", "DEEPSEEK_MODEL", "DEEPSEEK_BASE_URL"), - "zhipu": ("ZHIPU_API_KEY", "ZHIPU_MODEL", "ZHIPU_BASE_URL"), + key_name, model_name, base_url_name = PROVIDER_ENV_VARS[provider] + env_updates: dict[str, str] = { + "LLM_PROVIDER": provider, + key_name: api_key, } + if model: + env_updates[model_name] = model + if effective_base_url: + env_updates[base_url_name] = effective_base_url + if request.supports_vision is not None: + env_updates["LLM_SUPPORTS_VISION"] = "true" if request.supports_vision else "false" + else: + # Clear stale explicit override when switching providers without an explicit toggle + env_updates["LLM_SUPPORTS_VISION"] = "" - key_name, model_name, base_url_name = provider_config[provider] - env_updates[key_name] = request.api_key - if request.model: - env_updates[model_name] = request.model - if request.base_url and base_url_name: - env_updates[base_url_name] = request.base_url - - # Set environment variables for current process for key, value in env_updates.items(): os.environ[key] = value - # Persist to .env file for restart persistence _update_env_file(env_updates) - # Clear caches to reload settings app_config.clear_settings_cache() reset_llm_service() - # Verify configuration new_settings = app_config.get_settings() if not new_settings.is_llm_configured(): raise HTTPException(status_code=500, detail="配置失败,请检查API密钥是否正确") @@ -268,13 +339,13 @@ async def configure_llm( except HTTPException: raise except Exception as e: - logger.error(f"LLM configuration failed: {e}") + logger.error("LLM configuration failed: %s", e) raise HTTPException(status_code=500, detail="配置失败,请检查配置参数是否正确") from e @router.post("/llm/test") async def test_llm_connection(): - """Test the current LLM configuration with a simple request.""" + """Test the current saved LLM configuration with a simple request.""" llm_service = get_llm_service() if not llm_service.is_available: @@ -285,196 +356,188 @@ async def test_llm_connection(): if not provider: raise HTTPException(status_code=500, detail="无法获取LLM提供商实例") - # Simple test prompt response = provider.chat_completion( "You are a helpful assistant.", - "Reply with exactly: OK" + "Reply with exactly: OK", ) return { "success": True, "provider": provider.get_provider_name(), - "provider_display": PROVIDER_DISPLAY_NAMES.get(provider.get_provider_name(), provider.get_provider_name()), + "provider_display": PROVIDER_DISPLAY_NAMES.get( + provider.get_provider_name(), provider.get_provider_name() + ), "message": "LLM连接测试成功", - "response": response[:100], # Limit response length + "response": response[:100], } except Exception as e: - logger.error(f"LLM connection test failed: {e}") + logger.error("LLM connection test failed: %s", e) raise HTTPException( status_code=500, - detail="LLM连接测试失败,请检查API密钥和网络连接" + detail="LLM连接测试失败,请检查API密钥和网络连接", ) from e -def _get_provider_model(provider_name: str) -> Optional[str]: - """Get the configured model for a provider.""" - settings = app_config.get_settings() - model_map = { - "openai": settings.openai_model, - "anthropic": settings.anthropic_model, - "google": settings.google_model, - "qwen": settings.qwen_model, - "deepseek": settings.deepseek_model, - "zhipu": settings.zhipu_model, - } - return model_map.get(provider_name) - - -def _get_provider_base_url(provider_name: str) -> Optional[str]: - """Get the configured base URL for a provider.""" - settings = app_config.get_settings() - url_map = { - "openai": settings.openai_base_url, - "anthropic": settings.anthropic_base_url, - "google": settings.google_base_url, - "qwen": settings.qwen_base_url, - "deepseek": settings.deepseek_base_url, - "zhipu": settings.zhipu_base_url, - } - return url_map.get(provider_name) or None - - class ConfigTestRequest(BaseModel): """Request to test LLM config before saving.""" + provider: str api_key: str model: Optional[str] = None base_url: Optional[str] = None + supports_vision: Optional[bool] = None class ConfigTestResponse(BaseModel): """Response for config test.""" + success: bool message: str response_time_ms: Optional[int] = None -# Default base URLs for providers that require them -_DEFAULT_BASE_URLS = { - "qwen": "https://dashscope.aliyuncs.com/compatible-mode/v1", - "deepseek": "https://api.deepseek.com", -} - +def _format_test_error(exc: Exception) -> str: + error_msg = str(exc) + if isinstance(exc, httpx.HTTPStatusError): + status = exc.response.status_code + body = exc.response.text or "" + if status == 401: + return "API密钥无效或未授权" + if status == 403: + return "API密钥权限不足或访问被拒绝" + if status == 404: + return "API地址无效,请检查URL是否正确(对于OpenAI兼容接口,base_url通常需要包含 /v1 路径)" + if " str: + url = build_chat_completions_url(base_url) + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json", + "User-Agent": DEFAULT_USER_AGENT, + } + payload = { + "model": model, + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Reply with exactly: OK"}, + ], + "temperature": 0.1, + **_get_max_tokens_param(model, 16), + } -def _test_openai_compatible(client, model: str) -> str: - """Test an OpenAI-compatible client, with fallback to Responses API.""" - try: - # Try Chat Completions API first (standard OpenAI) - stream = client.chat.completions.create( - model=model, - messages=[ - {"role": "system", "content": "You are a helpful assistant."}, - {"role": "user", "content": "Reply with exactly: OK"}, - ], - temperature=0.1, - max_tokens=10, - stream=True, - ) - parts = [] - for chunk in stream: - if chunk.choices and chunk.choices[0].delta.content: - parts.append(chunk.choices[0].delta.content) - return "".join(parts).strip() - except Exception as e: - err_msg = str(e) - # If proxy doesn't support Chat Completions, try Responses API - if "Unsupported parameter" not in err_msg and "messages" not in err_msg.lower(): - raise - # Fall back to Responses API (used by Codex-compatible proxies) - if not hasattr(client, 'responses'): - raise RuntimeError( - "此代理使用 Responses API,但当前 openai SDK 版本不支持。" - "请升级: pip install -U openai" - ) from e - stream = client.responses.create( - model=model, - input=[{"role": "user", "content": "Reply with exactly: OK"}], - stream=True, - ) - parts = [] - for event in stream: - if getattr(event, 'type', '') == 'response.output_text.delta': - parts.append(event.delta) - return "".join(parts).strip() + async with httpx.AsyncClient(timeout=15.0) as client: + response = await client.post(url, json=payload, headers=headers) + if response.status_code >= 400: + body_lower = (response.text or "").lower() + if "unsupported parameter" in body_lower or "responses" in body_lower: + responses_url = f"{base_url.strip().rstrip('/')}/responses" + resp2 = await client.post( + responses_url, + json={ + "model": model, + "input": [{"role": "user", "content": "Reply with exactly: OK"}], + }, + headers=headers, + ) + resp2.raise_for_status() + data2 = resp2.json() + return str(data2.get("output_text") or "OK").strip() + response.raise_for_status() + + data = response.json() + if not isinstance(data, dict): + raise RuntimeError("API返回了非JSON对象响应") + return extract_chat_completion_text(data) + + +async def _test_anthropic_async( + base_url: str, + api_key: str, + model: str, +) -> str: + url = build_anthropic_messages_url(base_url) + headers = { + "x-api-key": api_key, + "anthropic-version": ANTHROPIC_API_VERSION, + "content-type": "application/json", + } + payload = { + "model": model, + "max_tokens": 16, + "system": "You are a helpful assistant.", + "messages": [{"role": "user", "content": "Reply with exactly: OK"}], + } + async with httpx.AsyncClient(timeout=15.0) as client: + response = await client.post(url, json=payload, headers=headers) + response.raise_for_status() + data = response.json() + if not isinstance(data, dict): + raise RuntimeError("API返回了非JSON对象响应") + return extract_anthropic_text(data) @router.post("/llm/test-config", response_model=ConfigTestResponse) async def test_llm_config(request: ConfigTestRequest): - """Test LLM configuration before saving using the actual provider client library.""" - import time + """Test LLM configuration before saving using async httpx requests.""" + _validate_no_newlines(request.provider, request.api_key, request.model, request.base_url) - provider = request.provider.lower() - if provider not in PROVIDERS: + provider = resolve_provider_id(request.provider) + if provider not in PRESET_BY_ID: raise HTTPException( status_code=400, - detail=f"不支持的LLM提供商: {provider}。支持的提供商: {', '.join(PROVIDERS.keys())}" + detail=f"不支持的LLM提供商: {request.provider}。支持的提供商: {', '.join(PROVIDERS.keys())}", ) - if not request.api_key: + api_key = request.api_key.strip() + if not api_key: raise HTTPException(status_code=400, detail="API密钥不能为空") - model = request.model or DEFAULT_MODELS.get(provider, "") - base_url = request.base_url.strip().rstrip("/") if request.base_url else None + preset = PRESET_BY_ID[provider] + model = (request.model or "").strip() or preset.default_model + base_url = (request.base_url or "").strip() or preset.base_url + + if provider == "openai_compatible" and not base_url: + raise HTTPException(status_code=400, detail="自定义服务必须填写 API 地址 (Base URL)") + if not model: + raise HTTPException(status_code=400, detail="请填写要测试的模型名称") start = time.monotonic() try: - if provider in ("openai", "qwen", "deepseek"): - from openai import OpenAI - kwargs = {"api_key": request.api_key} - effective_url = base_url or _DEFAULT_BASE_URLS.get(provider) - if effective_url: - kwargs["base_url"] = effective_url - # Override User-Agent for custom base URLs to avoid Cloudflare WAF - # blocking the default "OpenAI/Python" user agent - if base_url: - kwargs["default_headers"] = {"User-Agent": "python-httpx/0.27.0"} - client = OpenAI(**kwargs) - result_text = _test_openai_compatible(client, model) - - elif provider == "anthropic": - import anthropic - kwargs = {"api_key": request.api_key} - if base_url: - kwargs["base_url"] = base_url - client = anthropic.Anthropic(**kwargs) - response = client.messages.create( - model=model, - max_tokens=10, - system="You are a helpful assistant.", - messages=[{"role": "user", "content": "Reply with exactly: OK"}], - ) - result_text = response.content[0].text.strip() - - elif provider == "google": - import google.generativeai as genai - configure_kwargs = {"api_key": request.api_key} - if base_url: - configure_kwargs["client_options"] = {"api_endpoint": base_url} - genai.configure(**configure_kwargs) - gmodel = genai.GenerativeModel(model) - response = gmodel.generate_content("Reply with exactly: OK") - result_text = response.text.strip() - - elif provider == "zhipu": - from zhipuai import ZhipuAI - kwargs = {"api_key": request.api_key} - if base_url: - kwargs["base_url"] = base_url - client = ZhipuAI(**kwargs) - response = client.chat.completions.create( - model=model, - messages=[ - {"role": "system", "content": "You are a helpful assistant."}, - {"role": "user", "content": "Reply with exactly: OK"}, - ], - temperature=0.1, - max_tokens=10, - ) - result_text = response.choices[0].message.content.strip() - + if preset.protocol == "anthropic": + result_text = await _test_anthropic_async(base_url, api_key, model) else: - raise HTTPException(status_code=400, detail=f"不支持的LLM提供商: {provider}") + result_text = await _test_openai_compatible_async(base_url, api_key, model) elapsed_ms = int((time.monotonic() - start) * 1000) return ConfigTestResponse( @@ -482,41 +545,26 @@ async def test_llm_config(request: ConfigTestRequest): message=f"连接成功,响应: {result_text[:50]}", response_time_ms=elapsed_ms, ) - except Exception as e: elapsed_ms = int((time.monotonic() - start) * 1000) - error_msg = str(e) - if "401" in error_msg or "Unauthorized" in error_msg or "authentication" in error_msg.lower(): - msg = "API密钥无效或未授权" - elif "403" in error_msg or "Forbidden" in error_msg: - msg = "API密钥权限不足或访问被拒绝" - elif "404" in error_msg or "Not Found" in error_msg: - msg = "API地址无效,请检查URL是否正确(对于OpenAI兼容接口,base_url通常需要包含 /v1 路径)" - elif "connect" in error_msg.lower() or "timeout" in error_msg.lower(): - msg = "无法连接到该地址,请检查URL和网络连接" - elif " bool: - """Check if a model name matches any vision pattern. - - Uses exact match or prefix match with separator to avoid false positives. - For example, "gpt-4o" matches "gpt-4o" and "gpt-4o-mini" but not "gpt-4o-audio". - Args: - model_name: The configured model name - vision_patterns: List of known vision model patterns +def _model_matches_vision_pattern(model_name: str, vision_patterns: list[str]) -> bool: + """Check if a model name matches any vision pattern.""" + cleaned = model_name.strip().lower() + if not cleaned: + return False + candidates = [cleaned] + if "/" in cleaned: + candidates.append(cleaned.split("/")[-1]) - Returns: - True if the model supports vision - """ - for pattern in vision_patterns: - # Exact match - if model_name == pattern: - return True - # Prefix match: pattern must be followed by a separator (-) or end - if model_name.startswith(pattern + "-") or model_name.startswith(pattern + "."): + for candidate in candidates: + if "vision" in candidate or "-vl" in candidate: return True + for pattern in vision_patterns: + pat = pattern.lower() + if candidate == pat: + return True + if candidate.startswith(pat + "-") or candidate.startswith(pat + "."): + return True return False def _model_uses_new_token_param(model_name: str) -> bool: - """Check if a model uses max_completion_tokens instead of max_tokens. + """Check if a model uses max_completion_tokens instead of max_tokens.""" + return uses_max_completion_tokens(model_name) - Newer OpenAI models (o1, o3, gpt-5.x) require max_completion_tokens parameter. - Args: - model_name: The model name +def _get_max_tokens_param(model_name: str, value: int) -> dict[str, int]: + """Get the correct max tokens parameter for a model.""" + if _model_uses_new_token_param(model_name): + return {"max_completion_tokens": value} + return {"max_tokens": value} + + +def resolve_supports_vision( + provider_id: str, + model: str, + explicit_override: Optional[bool] = None, +) -> bool: + """Determine whether vision parsing should be enabled. - Returns: - True if the model uses max_completion_tokens + Precedence: + 1. Explicit ``LLM_SUPPORTS_VISION`` setting (True or False) always wins. + 2. Matching entry in the preset's static model list. + 3. Legacy model-name vision pattern heuristic. + 4. Preset default ``supports_vision`` value. """ - new_format_prefixes = ["o1", "o3", "gpt-5"] - return any(model_name.startswith(prefix) for prefix in new_format_prefixes) + if explicit_override is not None: + return bool(explicit_override) + canonical = resolve_provider_id(provider_id) + preset = PRESET_BY_ID.get(canonical) + model_lower = (model or "").strip().lower() -def _get_max_tokens_param(model_name: str, value: int) -> dict: - """Get the correct max tokens parameter for a model. + if preset is not None and model_lower: + for entry in preset.models: + if entry["id"].lower() == model_lower: + return bool(entry.get("vision", preset.supports_vision)) - Args: - model_name: The model name - value: The max tokens value + if model_lower and _model_matches_vision_pattern(model_lower, LEGACY_VISION_PATTERNS): + return True - Returns: - Dict with the appropriate parameter name and value - """ - if _model_uses_new_token_param(model_name): - return {"max_completion_tokens": value} - return {"max_tokens": value} + if preset is not None: + return bool(preset.supports_vision) + + return False + + +def build_anthropic_messages_url(base_url: str) -> str: + """Normalize an Anthropic base URL into the ``/v1/messages`` endpoint.""" + cleaned = (base_url or "https://api.anthropic.com/v1").strip().rstrip("/") + if cleaned.endswith("/messages"): + return cleaned + if cleaned.endswith("/v1"): + return f"{cleaned}/messages" + return f"{cleaned}/v1/messages" + + +def extract_anthropic_text(response_data: dict[str, Any]) -> str: + """Extract assistant text from an Anthropic Messages API JSON payload.""" + content = response_data.get("content") + if not isinstance(content, list) or not content: + raise VisionAPIError("Anthropic API response missing non-empty 'content'") + parts = [ + block.get("text", "") + for block in content + if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("text"), str) + ] + text = "".join(parts).strip() + if not text: + raise VisionAPIError("Anthropic API response contained no text blocks") + return text class BaseLLMProvider(ABC): @@ -80,158 +173,168 @@ class BaseLLMProvider(ABC): @abstractmethod def is_configured(self) -> bool: """Check if provider is configured.""" - pass @abstractmethod def get_provider_name(self) -> str: - """Get provider name.""" - pass + """Get canonical provider name.""" @abstractmethod def chat_completion(self, system_prompt: str, user_prompt: str) -> str: """Send chat completion request and return response content.""" - pass def supports_vision(self) -> bool: """Check if provider supports vision/image input.""" return False - def vision_completion(self, system_prompt: str, user_prompt: str, image_data: bytes, mime_type: str = "image/png") -> str: - """Send vision completion request with image and return response content. - - Args: - system_prompt: System prompt for the model - user_prompt: User prompt/instructions - image_data: Raw image bytes - mime_type: MIME type of the image (image/png, image/jpeg, etc.) - - Returns: - Response content from the model - """ + def vision_completion( + self, + system_prompt: str, + user_prompt: str, + image_data: bytes, + mime_type: str = "image/png", + ) -> str: + """Send vision completion request with image and return response content.""" raise NotImplementedError("Vision not supported by this provider") -class OpenAIProvider(BaseLLMProvider): - """OpenAI/OpenAI-compatible provider.""" +class OpenAICompatibleProvider(BaseLLMProvider): + """Unified OpenAI-compatible HTTP provider backed by httpx + invoice_core.parsers.vision.""" - # Models that support vision - # Note: gpt-5 and o-series models also support vision/multimodal input - VISION_MODELS = ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "gpt-4-vision-preview", "gpt-5", "o1", "o3"] + provider_id: str = "openai_compatible" - def __init__(self): - self._client = None - self._lock = threading.Lock() + def __init__(self, provider_id: Optional[str] = None, timeout: float = 60.0): + if provider_id: + self.provider_id = resolve_provider_id(provider_id) + self.timeout = timeout - @property - def client(self): - if self._client is None: - with self._lock: - if self._client is None: - from openai import OpenAI - kwargs = {"api_key": settings.openai_api_key} - if settings.openai_base_url: - kwargs["base_url"] = settings.openai_base_url - # Override User-Agent for custom base URLs to avoid - # Cloudflare WAF blocking "OpenAI/Python" user agent - kwargs["default_headers"] = {"User-Agent": "python-httpx/0.27.0"} - self._client = OpenAI(**kwargs) - return self._client + def _credentials(self) -> tuple[str, str, str]: + return get_settings().get_provider_credentials(self.provider_id) def is_configured(self) -> bool: - return bool(settings.openai_api_key) + return get_settings().is_provider_configured(self.provider_id) def get_provider_name(self) -> str: - return "openai" + return self.provider_id def supports_vision(self) -> bool: - return _model_matches_vision_pattern(settings.openai_model, self.VISION_MODELS) + current = get_settings() + _api_key, model, _base_url = current.get_provider_credentials(self.provider_id) + return resolve_supports_vision(self.provider_id, model, current.llm_supports_vision) + + def _headers(self, api_key: str) -> dict[str, str]: + return { + "Authorization": f"Bearer {api_key.strip()}", + "Content-Type": "application/json", + "User-Agent": DEFAULT_USER_AGENT, + } def chat_completion(self, system_prompt: str, user_prompt: str) -> str: - model = settings.openai_model - response = self.client.chat.completions.create( - model=model, - messages=[ + api_key, model, base_url = self._credentials() + if not api_key: + raise ValueError(f"Provider '{self.provider_id}' is missing api_key") + url = build_chat_completions_url(base_url) + payload = { + "model": model, + "messages": [ {"role": "system", "content": system_prompt}, - {"role": "user", "content": user_prompt} + {"role": "user", "content": user_prompt}, ], - temperature=0.1, + "temperature": 0.1, **_get_max_tokens_param(model, 1000), - ) - return response.choices[0].message.content.strip() - - def vision_completion(self, system_prompt: str, user_prompt: str, image_data: bytes, mime_type: str = "image/png") -> str: - model = settings.openai_model - base64_image = base64.b64encode(image_data).decode("utf-8") - response = self.client.chat.completions.create( + } + with httpx.Client(timeout=self.timeout) as client: + response = client.post(url, json=payload, headers=self._headers(api_key)) + response.raise_for_status() + return extract_chat_completion_text(response.json()) + + def vision_completion( + self, + system_prompt: str, + user_prompt: str, + image_data: bytes, + mime_type: str = "image/png", + ) -> str: + api_key, model, base_url = self._credentials() + if not api_key: + raise ValueError(f"Provider '{self.provider_id}' is missing api_key") + url = build_chat_completions_url(base_url) + payload = build_vision_payload( + image_bytes=image_data, model=model, - messages=[ - {"role": "system", "content": system_prompt}, - { - "role": "user", - "content": [ - {"type": "text", "text": user_prompt}, - { - "type": "image_url", - "image_url": {"url": f"data:{mime_type};base64,{base64_image}"} - } - ] - } - ], + mime_type=mime_type, + system_prompt=system_prompt, + user_prompt=user_prompt, temperature=0.1, - **_get_max_tokens_param(model, 1500), + max_tokens=1500, ) - return response.choices[0].message.content.strip() + with httpx.Client(timeout=self.timeout) as client: + response = client.post(url, json=payload, headers=self._headers(api_key)) + response.raise_for_status() + return extract_chat_completion_text(response.json()) class AnthropicProvider(BaseLLMProvider): - """Anthropic Claude provider.""" + """Anthropic Claude provider via native REST over httpx (zero SDK dependency).""" - # All Claude 3 models support vision - VISION_MODELS = ["claude-3", "claude-3.5"] + provider_id: str = "anthropic" - def __init__(self): - self._client = None - self._lock = threading.Lock() + def __init__(self, timeout: float = 60.0): + self.timeout = timeout - @property - def client(self): - if self._client is None: - with self._lock: - if self._client is None: - import anthropic - kwargs = {"api_key": settings.anthropic_api_key} - if settings.anthropic_base_url: - kwargs["base_url"] = settings.anthropic_base_url - self._client = anthropic.Anthropic(**kwargs) - return self._client + def _credentials(self) -> tuple[str, str, str]: + return get_settings().get_provider_credentials("anthropic") def is_configured(self) -> bool: - return bool(settings.anthropic_api_key) + return get_settings().is_provider_configured("anthropic") def get_provider_name(self) -> str: return "anthropic" def supports_vision(self) -> bool: - return _model_matches_vision_pattern(settings.anthropic_model, self.VISION_MODELS) + current = get_settings() + _api_key, model, _base_url = current.get_provider_credentials("anthropic") + return resolve_supports_vision("anthropic", model, current.llm_supports_vision) - def chat_completion(self, system_prompt: str, user_prompt: str) -> str: - response = self.client.messages.create( - model=settings.anthropic_model, - max_tokens=1000, - system=system_prompt, - messages=[ - {"role": "user", "content": user_prompt} - ], - ) - return response.content[0].text.strip() + def _headers(self, api_key: str) -> dict[str, str]: + return { + "x-api-key": api_key.strip(), + "anthropic-version": ANTHROPIC_API_VERSION, + "content-type": "application/json", + } - def vision_completion(self, system_prompt: str, user_prompt: str, image_data: bytes, mime_type: str = "image/png") -> str: - base64_image = base64.b64encode(image_data).decode("utf-8") - response = self.client.messages.create( - model=settings.anthropic_model, - max_tokens=1500, - system=system_prompt, - messages=[ + def chat_completion(self, system_prompt: str, user_prompt: str) -> str: + api_key, model, base_url = self._credentials() + if not api_key: + raise ValueError("Provider 'anthropic' is missing api_key") + url = build_anthropic_messages_url(base_url) + payload = { + "model": model, + "max_tokens": 1000, + "system": system_prompt, + "messages": [{"role": "user", "content": user_prompt}], + } + with httpx.Client(timeout=self.timeout) as client: + response = client.post(url, json=payload, headers=self._headers(api_key)) + response.raise_for_status() + return extract_anthropic_text(response.json()) + + def vision_completion( + self, + system_prompt: str, + user_prompt: str, + image_data: bytes, + mime_type: str = "image/png", + ) -> str: + api_key, model, base_url = self._credentials() + if not api_key: + raise ValueError("Provider 'anthropic' is missing api_key") + url = build_anthropic_messages_url(base_url) + base64_image = base64.b64encode(image_data).decode("ascii") + payload = { + "model": model, + "max_tokens": 1500, + "system": system_prompt, + "messages": [ { "role": "user", "content": [ @@ -240,257 +343,74 @@ def vision_completion(self, system_prompt: str, user_prompt: str, image_data: by "source": { "type": "base64", "media_type": mime_type, - "data": base64_image - } + "data": base64_image, + }, }, - {"type": "text", "text": user_prompt} - ] + {"type": "text", "text": user_prompt}, + ], } ], - ) - return response.content[0].text.strip() - - -class GoogleProvider(BaseLLMProvider): - """Google Gemini provider.""" - - # Gemini models with vision support - VISION_MODELS = ["gemini-1.5", "gemini-2", "gemini-pro-vision"] - - def __init__(self): - self._model = None - self._genai = None - self._lock = threading.Lock() - - @property - def genai(self): - if self._genai is None: - with self._lock: - if self._genai is None: - import google.generativeai as genai - configure_kwargs = {"api_key": settings.google_api_key} - if settings.google_base_url: - configure_kwargs["client_options"] = { - "api_endpoint": settings.google_base_url - } - genai.configure(**configure_kwargs) - self._genai = genai - return self._genai - - @property - def model(self): - if self._model is None: - with self._lock: - if self._model is None: - self._model = self.genai.GenerativeModel(settings.google_model) - return self._model - - def is_configured(self) -> bool: - return bool(settings.google_api_key) - - def get_provider_name(self) -> str: - return "google" - - def supports_vision(self) -> bool: - return _model_matches_vision_pattern(settings.google_model, self.VISION_MODELS) - - def chat_completion(self, system_prompt: str, user_prompt: str) -> str: - # Gemini combines system and user prompts - full_prompt = f"{system_prompt}\n\n{user_prompt}" - response = self.model.generate_content(full_prompt) - return response.text.strip() - - def vision_completion(self, system_prompt: str, user_prompt: str, image_data: bytes, mime_type: str = "image/png") -> str: - from PIL import Image - from io import BytesIO - - # Convert bytes to PIL Image for Gemini - image = Image.open(BytesIO(image_data)) - - # Combine system and user prompts - full_prompt = f"{system_prompt}\n\n{user_prompt}" - - response = self.model.generate_content([full_prompt, image]) - return response.text.strip() - - -class QwenProvider(BaseLLMProvider): - """Alibaba Qwen provider (OpenAI-compatible).""" + } + with httpx.Client(timeout=self.timeout) as client: + response = client.post(url, json=payload, headers=self._headers(api_key)) + response.raise_for_status() + return extract_anthropic_text(response.json()) - # Qwen-VL models support vision - VISION_MODELS = ["qwen-vl", "qwen2-vl"] - def __init__(self): - self._client = None - self._lock = threading.Lock() - - @property - def client(self): - if self._client is None: - with self._lock: - if self._client is None: - from openai import OpenAI - self._client = OpenAI( - api_key=settings.qwen_api_key, - base_url=settings.qwen_base_url, - ) - return self._client - - def is_configured(self) -> bool: - return bool(settings.qwen_api_key) - - def get_provider_name(self) -> str: - return "qwen" - - def supports_vision(self) -> bool: - return _model_matches_vision_pattern(settings.qwen_model, self.VISION_MODELS) +# Thin named subclasses preserve backward compatibility with existing imports +class OpenAIProvider(OpenAICompatibleProvider): + provider_id = "openai" - def chat_completion(self, system_prompt: str, user_prompt: str) -> str: - response = self.client.chat.completions.create( - model=settings.qwen_model, - messages=[ - {"role": "system", "content": system_prompt}, - {"role": "user", "content": user_prompt} - ], - temperature=0.1, - max_tokens=1000, - ) - return response.choices[0].message.content.strip() - - def vision_completion(self, system_prompt: str, user_prompt: str, image_data: bytes, mime_type: str = "image/png") -> str: - base64_image = base64.b64encode(image_data).decode("utf-8") - response = self.client.chat.completions.create( - model=settings.qwen_model, - messages=[ - {"role": "system", "content": system_prompt}, - { - "role": "user", - "content": [ - {"type": "text", "text": user_prompt}, - { - "type": "image_url", - "image_url": {"url": f"data:{mime_type};base64,{base64_image}"} - } - ] - } - ], - temperature=0.1, - max_tokens=1500, - ) - return response.choices[0].message.content.strip() +class GoogleProvider(OpenAICompatibleProvider): + provider_id = "google" -class DeepSeekProvider(BaseLLMProvider): - """DeepSeek provider (OpenAI-compatible).""" - def __init__(self): - self._client = None - self._lock = threading.Lock() +class QwenProvider(OpenAICompatibleProvider): + provider_id = "qwen" - @property - def client(self): - if self._client is None: - with self._lock: - if self._client is None: - from openai import OpenAI - self._client = OpenAI( - api_key=settings.deepseek_api_key, - base_url=settings.deepseek_base_url, - ) - return self._client - def is_configured(self) -> bool: - return bool(settings.deepseek_api_key) +class DeepSeekProvider(OpenAICompatibleProvider): + provider_id = "deepseek" - def get_provider_name(self) -> str: - return "deepseek" - def chat_completion(self, system_prompt: str, user_prompt: str) -> str: - response = self.client.chat.completions.create( - model=settings.deepseek_model, - messages=[ - {"role": "system", "content": system_prompt}, - {"role": "user", "content": user_prompt} - ], - temperature=0.1, - max_tokens=1000, - ) - return response.choices[0].message.content.strip() +class ZhipuProvider(OpenAICompatibleProvider): + provider_id = "zhipu" -class ZhipuProvider(BaseLLMProvider): - """Zhipu GLM provider.""" +class KimiProvider(OpenAICompatibleProvider): + provider_id = "kimi" - # GLM-4V models support vision - VISION_MODELS = ["glm-4v", "glm-4v-plus"] - def __init__(self): - self._client = None - self._lock = threading.Lock() +class DoubaoProvider(OpenAICompatibleProvider): + provider_id = "doubao" - @property - def client(self): - if self._client is None: - with self._lock: - if self._client is None: - from zhipuai import ZhipuAI - kwargs = {"api_key": settings.zhipu_api_key} - if settings.zhipu_base_url: - kwargs["base_url"] = settings.zhipu_base_url - self._client = ZhipuAI(**kwargs) - return self._client - def is_configured(self) -> bool: - return bool(settings.zhipu_api_key) +class SiliconFlowProvider(OpenAICompatibleProvider): + provider_id = "siliconflow" - def get_provider_name(self) -> str: - return "zhipu" - def supports_vision(self) -> bool: - return _model_matches_vision_pattern(settings.zhipu_model, self.VISION_MODELS) +class OpenRouterProvider(OpenAICompatibleProvider): + provider_id = "openrouter" - def chat_completion(self, system_prompt: str, user_prompt: str) -> str: - response = self.client.chat.completions.create( - model=settings.zhipu_model, - messages=[ - {"role": "system", "content": system_prompt}, - {"role": "user", "content": user_prompt} - ], - temperature=0.1, - max_tokens=1000, - ) - return response.choices[0].message.content.strip() - def vision_completion(self, system_prompt: str, user_prompt: str, image_data: bytes, mime_type: str = "image/png") -> str: - base64_image = base64.b64encode(image_data).decode("utf-8") - response = self.client.chat.completions.create( - model=settings.zhipu_model, - messages=[ - { - "role": "user", - "content": [ - {"type": "text", "text": f"{system_prompt}\n\n{user_prompt}"}, - { - "type": "image_url", - "image_url": {"url": f"data:{mime_type};base64,{base64_image}"} - } - ] - } - ], - temperature=0.1, - max_tokens=1500, - ) - return response.choices[0].message.content.strip() +class CustomOpenAICompatibleProvider(OpenAICompatibleProvider): + provider_id = "openai_compatible" -# Provider registry -PROVIDERS: Dict[str, type] = { +# Provider registry keyed by canonical preset ID +PROVIDERS: Dict[str, type[BaseLLMProvider]] = { "openai": OpenAIProvider, "anthropic": AnthropicProvider, "google": GoogleProvider, "qwen": QwenProvider, "deepseek": DeepSeekProvider, "zhipu": ZhipuProvider, + "kimi": KimiProvider, + "doubao": DoubaoProvider, + "siliconflow": SiliconFlowProvider, + "openrouter": OpenRouterProvider, + "openai_compatible": CustomOpenAICompatibleProvider, } @@ -502,43 +422,39 @@ def __init__(self): self._active_provider: Optional[BaseLLMProvider] = None def _get_provider(self, provider_name: str) -> Optional[BaseLLMProvider]: - """Get or create a provider instance.""" - if provider_name not in self._providers: - if provider_name in PROVIDERS: - self._providers[provider_name] = PROVIDERS[provider_name]() - return self._providers.get(provider_name) + """Get or create a provider instance (resolving aliases automatically).""" + canonical = resolve_provider_id(provider_name) + if canonical not in self._providers and canonical in PROVIDERS: + self._providers[canonical] = PROVIDERS[canonical]() + return self._providers.get(canonical) @property def active_provider(self) -> Optional[BaseLLMProvider]: - """Get the active LLM provider. - - Always fetch fresh settings to ensure config changes are reflected. - """ - if self._active_provider is None: - provider_name = get_settings().get_active_llm_provider() - if provider_name: - self._active_provider = self._get_provider(provider_name) + """Get the active LLM provider based on current settings.""" + provider_name = get_settings().get_active_llm_provider() + if not provider_name: + self._active_provider = None + return None + if self._active_provider is None or self._active_provider.get_provider_name() != provider_name: + self._active_provider = self._get_provider(provider_name) return self._active_provider @property def is_available(self) -> bool: - """Check if any LLM provider is available. - - Always fetch fresh settings to ensure config changes are reflected. - """ + """Check if any LLM provider is available.""" return get_settings().is_llm_configured() def get_configured_providers(self) -> list[str]: - """Get list of configured provider names.""" + """Get list of configured canonical provider IDs.""" configured = [] - for name, provider_class in PROVIDERS.items(): - provider = self._get_provider(name) + for preset in PROVIDER_PRESETS: + provider = self._get_provider(preset.id) if provider and provider.is_configured(): - configured.append(name) + configured.append(preset.id) return configured def get_active_provider_name(self) -> Optional[str]: - """Get the name of the active provider.""" + """Get the canonical name of the active provider.""" return get_settings().get_active_llm_provider() def supports_vision(self) -> bool: @@ -546,16 +462,12 @@ def supports_vision(self) -> bool: provider = self.active_provider return provider.supports_vision() if provider else False - def parse_invoice_from_image(self, image_data: bytes, mime_type: str = "image/png") -> Dict[str, Any]: - """Parse invoice directly from image using vision capabilities. - - Args: - image_data: Raw image bytes - mime_type: MIME type of the image - - Returns: - Dictionary of extracted fields - """ + def parse_invoice_from_image( + self, + image_data: bytes, + mime_type: str = "image/png", + ) -> Dict[str, Any]: + """Parse invoice directly from image using vision capabilities.""" if not self.is_available: logger.warning("No LLM provider configured, skipping vision parsing") return {} @@ -574,11 +486,9 @@ def parse_invoice_from_image(self, image_data: bytes, mime_type: str = "image/pn INVOICE_VISION_SYSTEM_PROMPT, INVOICE_VISION_PROMPT, image_data, - mime_type + mime_type, ) - return self._parse_json_response(content, provider.get_provider_name()) - except json.JSONDecodeError as e: logger.error(f"Failed to parse LLM vision response as JSON: {e}") return {} @@ -604,20 +514,14 @@ def get_llm_service() -> LLMService: global _llm_service if _llm_service is None: with _llm_lock: - # Double-check after acquiring lock if _llm_service is None: _llm_service = LLMService() return _llm_service def reset_llm_service(): - """Reset the LLM service singleton (useful after config changes). - - Also refreshes the module-level settings to ensure providers - see the updated configuration. - """ + """Reset the LLM service singleton and refresh module-level settings.""" global _llm_service, settings with _llm_lock: _llm_service = None - # Refresh module-level settings so providers see new config settings = get_settings() diff --git a/backend/app/services/model_registry.py b/backend/app/services/model_registry.py index 6e048dd..43e046a 100644 --- a/backend/app/services/model_registry.py +++ b/backend/app/services/model_registry.py @@ -1,141 +1,141 @@ -"""Model registry service using OpenRouter API for dynamic model lists.""" +"""Async model registry with in-memory TTL caching and static preset fallback.""" +from __future__ import annotations + +import asyncio import logging -from datetime import datetime, timedelta -from typing import Optional +import time +import weakref +from typing import Any, Optional + import httpx +from app.services.provider_presets import ( + PRESET_BY_ID, + PROVIDER_PRESETS, + resolve_provider_id, +) + logger = logging.getLogger(__name__) OPENROUTER_MODELS_URL = "https://openrouter.ai/api/v1/models" -CACHE_TTL = timedelta(hours=24) - -# Cache storage -_models_cache: dict = {"data": None, "timestamp": None} - - -def _fetch_models_from_openrouter() -> list[dict]: - """Fetch models from OpenRouter API. - - Returns: - List of model data dictionaries - """ - try: - response = httpx.get(OPENROUTER_MODELS_URL, timeout=10) - response.raise_for_status() - return response.json().get("data", []) - except httpx.TimeoutException: - logger.warning("OpenRouter API request timed out") - return [] - except httpx.HTTPStatusError as e: - logger.warning(f"OpenRouter API returned error: {e.response.status_code}") - return [] - except Exception as e: - logger.error(f"Failed to fetch models from OpenRouter: {e}") - return [] - - -def get_available_models(force_refresh: bool = False) -> list[dict]: - """Get all models from OpenRouter, cached for 24 hours. - - Args: - force_refresh: If True, bypass cache and fetch fresh data - - Returns: - List of model data dictionaries - """ - global _models_cache - - # Check cache validity - if not force_refresh and _models_cache["data"] is not None: - if _models_cache["timestamp"] and datetime.now() - _models_cache["timestamp"] < CACHE_TTL: - return _models_cache["data"] - - # Fetch fresh data - models = _fetch_models_from_openrouter() - - if models: - _models_cache["data"] = models - _models_cache["timestamp"] = datetime.now() - - return models or _models_cache.get("data", []) - - -def get_vision_models() -> list[dict]: - """Get models that support image input. - - Returns: - List of vision-capable model data dictionaries - """ - models = get_available_models() - vision_models = [] +OPENROUTER_TIMEOUT_SECONDS = 4.0 +CACHE_TTL_SECONDS = 600.0 # 10 minutes +NEGATIVE_CACHE_TTL_SECONDS = 60.0 # 60 seconds backoff after upstream failure + +# In-memory TTL cache using monotonic timestamps (positive + negative) +_models_cache: dict[str, Any] = { + "data": None, + "fetched_at": None, + "failed_at": None, +} +_fetch_locks: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock] = ( + weakref.WeakKeyDictionary() +) + +# Providers that benefit from dynamic OpenRouter catalog lookups +_OPENROUTER_PREFIXES: dict[str, tuple[str, ...]] = { + "openai": ("openai/",), + "anthropic": ("anthropic/",), + "google": ("google/",), +} - for model in models: - input_modalities = model.get("architecture", {}).get("input_modalities", []) - if "image" in input_modalities: - vision_models.append(model) - return vision_models +def clear_models_cache() -> None: + """Clear the in-memory OpenRouter models cache (positive and negative entries).""" + _models_cache["data"] = None + _models_cache["fetched_at"] = None + _models_cache["failed_at"] = None + _fetch_locks.clear() -def get_models_by_provider(provider: str) -> list[dict]: - """Get models filtered by provider prefix. +def _get_fetch_lock() -> asyncio.Lock: + """Return a per-event-loop asyncio.Lock for single-flight OpenRouter fetches.""" + loop = asyncio.get_running_loop() + lock = _fetch_locks.get(loop) + if lock is None: + lock = asyncio.Lock() + _fetch_locks[loop] = lock + return lock - Args: - provider: Provider name (openai, anthropic, google, etc.) - Returns: - List of model data dictionaries for the specified provider - """ - models = get_available_models() - provider_lower = provider.lower() +def _read_cache(now: float, *, force_refresh: bool) -> Optional[list[dict[str, Any]]]: + """Read positive or negative cache entry if still within TTL; return None on miss.""" + if force_refresh: + return None - # Provider prefix mapping for OpenRouter model IDs - provider_prefixes = { - "openai": ["openai/"], - "anthropic": ["anthropic/"], - "google": ["google/"], - "qwen": ["qwen/"], - "deepseek": ["deepseek/"], - "zhipu": ["z-ai/"], # Zhipu GLM models are under "z-ai" on OpenRouter - } + cached_data = _models_cache["data"] + fetched_at = _models_cache["fetched_at"] + if ( + cached_data is not None + and fetched_at is not None + and (now - fetched_at) < CACHE_TTL_SECONDS + ): + return cached_data - prefixes = provider_prefixes.get(provider_lower, [f"{provider_lower}/"]) + failed_at = _models_cache["failed_at"] + if failed_at is not None and (now - failed_at) < NEGATIVE_CACHE_TTL_SECONDS: + return cached_data or [] - return [m for m in models if any(m.get("id", "").startswith(prefix) for prefix in prefixes)] + return None -def get_vision_models_by_provider(provider: str) -> list[dict]: - """Get vision-capable models for a specific provider. +async def _fetch_models_from_openrouter_async() -> list[dict[str, Any]]: + """Fetch model catalog from OpenRouter asynchronously without blocking the event loop.""" + try: + async with httpx.AsyncClient(timeout=OPENROUTER_TIMEOUT_SECONDS) as client: + response = await client.get(OPENROUTER_MODELS_URL) + response.raise_for_status() + payload = response.json() + data = payload.get("data", []) + return data if isinstance(data, list) else [] + except httpx.TimeoutException: + logger.warning("OpenRouter models API request timed out after %.1fs", OPENROUTER_TIMEOUT_SECONDS) + return [] + except httpx.HTTPStatusError as e: + logger.warning("OpenRouter models API returned HTTP %s", e.response.status_code) + return [] + except Exception as e: + logger.warning("Failed to fetch models from OpenRouter: %s", e) + return [] - Args: - provider: Provider name (openai, anthropic, google, etc.) - Returns: - List of vision-capable model data dictionaries for the provider - """ - provider_models = get_models_by_provider(provider) +async def get_available_models_async(force_refresh: bool = False) -> list[dict[str, Any]]: + """Return OpenRouter models with TTL caching, negative caching, and single-flight coalescing.""" + cached = _read_cache(time.monotonic(), force_refresh=force_refresh) + if cached is not None: + return cached - return [ - m for m in provider_models - if "image" in m.get("architecture", {}).get("input_modalities", []) - ] + async with _get_fetch_lock(): + # Re-check cache after acquiring lock so concurrent callers share one in-flight fetch + cached = _read_cache(time.monotonic(), force_refresh=force_refresh) + if cached is not None: + return cached + models = await _fetch_models_from_openrouter_async() + finished_at = time.monotonic() + if models: + _models_cache["data"] = models + _models_cache["fetched_at"] = finished_at + _models_cache["failed_at"] = None + return models -def format_model_for_api(model: dict) -> dict: - """Format OpenRouter model data for API response. + # Record failure timestamp for short negative-cache backoff + _models_cache["failed_at"] = finished_at + return _models_cache["data"] or [] - Args: - model: Raw model data from OpenRouter - Returns: - Formatted model dictionary for API response - """ +def format_model_for_api(model: dict[str, Any], strip_prefix: Optional[str] = None) -> dict[str, Any]: + """Format an OpenRouter model entry for the API response.""" input_modalities = model.get("architecture", {}).get("input_modalities", []) + raw_id = str(model.get("id", "")) + model_id = raw_id + if strip_prefix and raw_id.startswith(strip_prefix): + model_id = raw_id[len(strip_prefix):] return { - "id": model.get("id", ""), - "name": model.get("name", model.get("id", "")), + "id": model_id, + "name": model.get("name", model_id), "vision": "image" in input_modalities, "context_length": model.get("context_length"), "pricing": { @@ -145,100 +145,70 @@ def format_model_for_api(model: dict) -> dict: } -def get_formatted_models_for_provider( - provider: str, - vision_only: bool = False -) -> list[dict]: - """Get formatted model list for a provider. - - Args: - provider: Provider name (openai, anthropic, google, etc.) - vision_only: If True, only return vision-capable models - - Returns: - List of formatted model dictionaries ready for API response - """ +def _static_preset_models(provider_id: str, vision_only: bool = False) -> list[dict[str, Any]]: + preset = PRESET_BY_ID.get(resolve_provider_id(provider_id)) + if not preset: + return [] + models = [dict(m) for m in preset.models] if vision_only: - models = get_vision_models_by_provider(provider) - else: - models = get_models_by_provider(provider) - - return [format_model_for_api(m) for m in models] - - -# Fallback hardcoded models for when OpenRouter is unavailable -FALLBACK_MODELS = { - "openai": [ - {"id": "openai/gpt-4o", "name": "GPT-4o", "vision": True}, - {"id": "openai/gpt-4o-mini", "name": "GPT-4o Mini", "vision": True}, - {"id": "openai/gpt-4-turbo", "name": "GPT-4 Turbo", "vision": True}, - {"id": "openai/o1", "name": "o1", "vision": True}, - {"id": "openai/o1-mini", "name": "o1 Mini", "vision": True}, - ], - "anthropic": [ - {"id": "anthropic/claude-sonnet-4", "name": "Claude Sonnet 4", "vision": True}, - {"id": "anthropic/claude-3.5-sonnet", "name": "Claude 3.5 Sonnet", "vision": True}, - {"id": "anthropic/claude-3.5-haiku", "name": "Claude 3.5 Haiku", "vision": True}, - {"id": "anthropic/claude-3-opus", "name": "Claude 3 Opus", "vision": True}, - ], - "google": [ - {"id": "google/gemini-2.0-flash-001", "name": "Gemini 2.0 Flash", "vision": True}, - {"id": "google/gemini-1.5-pro", "name": "Gemini 1.5 Pro", "vision": True}, - {"id": "google/gemini-1.5-flash", "name": "Gemini 1.5 Flash", "vision": True}, - ], - "qwen": [ - {"id": "qwen/qwen2.5-vl-72b-instruct", "name": "Qwen 2.5 VL 72B", "vision": True}, - {"id": "qwen/qwen-vl-plus", "name": "Qwen VL Plus", "vision": True}, - {"id": "qwen/qwen-turbo", "name": "Qwen Turbo", "vision": False}, - ], - "deepseek": [ - {"id": "deepseek/deepseek-chat", "name": "DeepSeek Chat", "vision": False}, - {"id": "deepseek/deepseek-r1", "name": "DeepSeek R1", "vision": False}, - ], - # Zhipu uses native SDK, so model IDs are Zhipu's native format (not OpenRouter) - "zhipu": [ - {"id": "glm-4v-plus", "name": "GLM-4V Plus (视觉增强)", "vision": True}, - {"id": "glm-4v", "name": "GLM-4V (视觉)", "vision": True}, - {"id": "glm-4-plus", "name": "GLM-4 Plus (增强)", "vision": False}, - {"id": "glm-4-flash", "name": "GLM-4 Flash (快速)", "vision": False}, - {"id": "glm-4-air", "name": "GLM-4 Air (经济)", "vision": False}, - {"id": "glm-4", "name": "GLM-4 (标准)", "vision": False}, - ], -} + models = [m for m in models if m.get("vision", False)] + return models -def get_models_with_fallback( +async def get_models_with_fallback_async( provider: str, - vision_only: bool = False -) -> list[dict]: - """Get models for a provider, with fallback to hardcoded list. - - Args: - provider: Provider name - vision_only: If True, only return vision-capable models - - Returns: - List of model dictionaries - """ - provider_lower = provider.lower() - - # Zhipu uses native SDK with different model IDs than OpenRouter - # Always use the hardcoded list for Zhipu - if provider_lower == "zhipu": - fallback = FALLBACK_MODELS.get(provider_lower, []) - if vision_only: - return [m for m in fallback if m.get("vision", False)] - return fallback - - # Try OpenRouter first for other providers - models = get_formatted_models_for_provider(provider, vision_only) - - # Fall back to hardcoded list if OpenRouter returns nothing - if not models: - fallback = FALLBACK_MODELS.get(provider_lower, []) - if vision_only: - models = [m for m in fallback if m.get("vision", False)] + vision_only: bool = False, +) -> tuple[list[dict[str, Any]], str]: + """Return ``(models, source)`` asynchronously, falling back cleanly to static presets.""" + canonical = resolve_provider_id(provider) + + # Domestic & custom providers use their native static preset lists directly + if canonical not in ("openrouter", "openai", "anthropic", "google"): + return _static_preset_models(canonical, vision_only=vision_only), "fallback" + + catalog = await get_available_models_async() + if catalog: + formatted: list[dict[str, Any]] = [] + if canonical == "openrouter": + for item in catalog: + entry = format_model_for_api(item) + if not vision_only or entry["vision"]: + formatted.append(entry) else: - models = fallback - - return models + prefixes = _OPENROUTER_PREFIXES.get(canonical, ()) + for item in catalog: + raw_id = str(item.get("id", "")) + matched_prefix = next((p for p in prefixes if raw_id.startswith(p)), None) + if matched_prefix is None: + continue + entry = format_model_for_api(item, strip_prefix=matched_prefix) + if not vision_only or entry["vision"]: + formatted.append(entry) + + if formatted: + return formatted, "openrouter" + + return _static_preset_models(canonical, vision_only=vision_only), "fallback" + + +async def get_all_models_with_fallback_async( + vision_only: bool = False, +) -> tuple[list[dict[str, Any]], str]: + """Return models for all configured presets.""" + all_models: list[dict[str, Any]] = [] + used_openrouter = False + for preset in PROVIDER_PRESETS: + models, source = await get_models_with_fallback_async(preset.id, vision_only=vision_only) + all_models.extend(models) + if source == "openrouter": + used_openrouter = True + return all_models, ("openrouter" if used_openrouter else "fallback") + + +# Backward-compatible synchronous static fallback helper +def get_models_with_fallback( + provider: str, + vision_only: bool = False, +) -> list[dict[str, Any]]: + """Return static preset models synchronously (legacy compatibility helper).""" + return _static_preset_models(provider, vision_only=vision_only) diff --git a/backend/app/services/provider_presets.py b/backend/app/services/provider_presets.py new file mode 100644 index 0000000..9f85aef --- /dev/null +++ b/backend/app/services/provider_presets.py @@ -0,0 +1,291 @@ +"""Static LLM provider presets and backward-compatible alias mapping. + +Single source of truth for provider endpoints, recommended models, protocol types, +default vision capability, and the optional ``recommended`` slot (currently all False). +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Literal, Optional + +ProviderCategory = Literal["recommended", "domestic", "global", "custom"] +ProviderProtocol = Literal["openai_compatible", "anthropic"] + + +@dataclass(frozen=True) +class ProviderPreset: + """Static definition of an LLM provider preset.""" + + id: str + name: str + category: ProviderCategory + protocol: ProviderProtocol + base_url: str + docs_url: str + default_model: str + models: tuple[dict[str, Any], ...] + supports_vision: bool + recommended: bool = False + description: str = "" + + def to_dict(self) -> dict[str, Any]: + return { + "id": self.id, + "name": self.name, + "category": self.category, + "protocol": self.protocol, + "base_url": self.base_url, + "docs_url": self.docs_url, + "default_model": self.default_model, + "models": [dict(m) for m in self.models], + "supports_vision": self.supports_vision, + "recommended": self.recommended, + "description": self.description, + } + + +# Single static preset registry. +# NOTE: ``recommended`` MUST remain False for all entries until a recommended gateway is launched. +PROVIDER_PRESETS: tuple[ProviderPreset, ...] = ( + # --- Domestic (国内常用) --- + ProviderPreset( + id="qwen", + name="通义千问 DashScope", + category="domestic", + protocol="openai_compatible", + base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", + docs_url="https://dashscope.console.aliyun.com/", + default_model="qwen-vl-plus", + models=( + {"id": "qwen-vl-plus", "name": "Qwen VL Plus (视觉推荐)", "vision": True}, + {"id": "qwen-vl-max", "name": "Qwen VL Max (视觉旗舰)", "vision": True}, + {"id": "qwen2.5-vl-72b-instruct", "name": "Qwen 2.5 VL 72B", "vision": True}, + {"id": "qwen-plus", "name": "Qwen Plus (文本)", "vision": False}, + {"id": "qwen-turbo", "name": "Qwen Turbo (文本)", "vision": False}, + ), + supports_vision=True, + recommended=False, + description="阿里云百炼 OpenAI 兼容接口,中文发票视觉识别稳定", + ), + ProviderPreset( + id="deepseek", + name="DeepSeek", + category="domestic", + protocol="openai_compatible", + base_url="https://api.deepseek.com/v1", + docs_url="https://platform.deepseek.com/", + default_model="deepseek-chat", + models=( + {"id": "deepseek-chat", "name": "DeepSeek Chat (文本)", "vision": False}, + {"id": "deepseek-reasoner", "name": "DeepSeek Reasoner (文本)", "vision": False}, + ), + supports_vision=False, + recommended=False, + description="官方 API 默认为纯文本模型(视觉开关默认关闭)", + ), + ProviderPreset( + id="zhipu", + name="智谱 GLM", + category="domestic", + protocol="openai_compatible", + base_url="https://open.bigmodel.cn/api/paas/v4", + docs_url="https://open.bigmodel.cn/", + default_model="glm-4v-plus", + models=( + {"id": "glm-4v-plus", "name": "GLM-4V Plus (视觉推荐)", "vision": True}, + {"id": "glm-4v-flash", "name": "GLM-4V Flash (视觉免费/快速)", "vision": True}, + {"id": "glm-4.5v", "name": "GLM-4.5V (视觉)", "vision": True}, + {"id": "glm-4-flash", "name": "GLM-4 Flash (文本)", "vision": False}, + {"id": "glm-4-plus", "name": "GLM-4 Plus (文本)", "vision": False}, + ), + supports_vision=True, + recommended=False, + description="智谱开放平台 OpenAI 兼容端点,支持 GLM-4V 视觉系列", + ), + ProviderPreset( + id="kimi", + name="Kimi / Moonshot", + category="domestic", + protocol="openai_compatible", + base_url="https://api.moonshot.cn/v1", + docs_url="https://platform.moonshot.cn/", + default_model="moonshot-v1-8k-vision-preview", + models=( + {"id": "moonshot-v1-8k-vision-preview", "name": "Moonshot v1 8K Vision", "vision": True}, + {"id": "moonshot-v1-32k-vision-preview", "name": "Moonshot v1 32K Vision", "vision": True}, + {"id": "kimi-latest", "name": "Kimi Latest (视觉)", "vision": True}, + {"id": "moonshot-v1-8k", "name": "Moonshot v1 8K (文本)", "vision": False}, + ), + supports_vision=True, + recommended=False, + description="月之暗面开放平台 OpenAI 兼容端点", + ), + ProviderPreset( + id="doubao", + name="火山方舟豆包", + category="domestic", + protocol="openai_compatible", + base_url="https://ark.cn-beijing.volces.com/api/v3", + docs_url="https://console.volcengine.com/ark", + default_model="doubao-1-5-vision-pro-32k-250115", + models=( + {"id": "doubao-1-5-vision-pro-32k-250115", "name": "豆包 1.5 Vision Pro", "vision": True}, + {"id": "doubao-1-5-pro-32k-250115", "name": "豆包 1.5 Pro (文本)", "vision": False}, + ), + supports_vision=True, + recommended=False, + description="火山方舟 OpenAI 兼容端点(也可填写推理接入点 ID)", + ), + ProviderPreset( + id="siliconflow", + name="硅基流动 SiliconFlow", + category="domestic", + protocol="openai_compatible", + base_url="https://api.siliconflow.cn/v1", + docs_url="https://cloud.siliconflow.cn/", + default_model="Qwen/Qwen2.5-VL-72B-Instruct", + models=( + {"id": "Qwen/Qwen2.5-VL-72B-Instruct", "name": "Qwen 2.5 VL 72B (视觉)", "vision": True}, + {"id": "Qwen/Qwen2.5-VL-32B-Instruct", "name": "Qwen 2.5 VL 32B (视觉)", "vision": True}, + {"id": "deepseek-ai/DeepSeek-V3", "name": "DeepSeek-V3 (文本)", "vision": False}, + ), + supports_vision=True, + recommended=False, + description="国内多模型托管平台,支持主流开源视觉模型", + ), + # --- Global (海外) --- + ProviderPreset( + id="openai", + name="OpenAI (GPT)", + category="global", + protocol="openai_compatible", + base_url="https://api.openai.com/v1", + docs_url="https://platform.openai.com/api-keys", + default_model="gpt-4o-mini", + models=( + {"id": "gpt-4o-mini", "name": "GPT-4o Mini (视觉推荐)", "vision": True}, + {"id": "gpt-4o", "name": "GPT-4o (视觉)", "vision": True}, + {"id": "gpt-4.1-mini", "name": "GPT-4.1 Mini (视觉)", "vision": True}, + {"id": "gpt-4.1", "name": "GPT-4.1 (视觉)", "vision": True}, + ), + supports_vision=True, + recommended=False, + description="OpenAI 官方接口", + ), + ProviderPreset( + id="openrouter", + name="OpenRouter", + category="global", + protocol="openai_compatible", + base_url="https://openrouter.ai/api/v1", + docs_url="https://openrouter.ai/keys", + default_model="openai/gpt-4o-mini", + models=( + {"id": "openai/gpt-4o-mini", "name": "OpenAI GPT-4o Mini", "vision": True}, + {"id": "openai/gpt-4o", "name": "OpenAI GPT-4o", "vision": True}, + {"id": "anthropic/claude-sonnet-4", "name": "Anthropic Claude Sonnet 4", "vision": True}, + {"id": "google/gemini-2.5-flash", "name": "Google Gemini 2.5 Flash", "vision": True}, + ), + supports_vision=True, + recommended=False, + description="海外多模型聚合网关,使用 vendor/model 格式", + ), + ProviderPreset( + id="google", + name="Google Gemini", + category="global", + protocol="openai_compatible", + base_url="https://generativelanguage.googleapis.com/v1beta/openai/", + docs_url="https://aistudio.google.com/apikey", + default_model="gemini-2.5-flash", + models=( + {"id": "gemini-2.5-flash", "name": "Gemini 2.5 Flash (视觉推荐)", "vision": True}, + {"id": "gemini-2.0-flash", "name": "Gemini 2.0 Flash (视觉)", "vision": True}, + {"id": "gemini-1.5-pro", "name": "Gemini 1.5 Pro (视觉)", "vision": True}, + {"id": "gemini-1.5-flash", "name": "Gemini 1.5 Flash (视觉)", "vision": True}, + ), + supports_vision=True, + recommended=False, + description="通过 Google 官方 OpenAI 兼容端点访问,无需额外 SDK", + ), + ProviderPreset( + id="anthropic", + name="Anthropic Claude", + category="global", + protocol="anthropic", + base_url="https://api.anthropic.com/v1", + docs_url="https://console.anthropic.com/", + default_model="claude-sonnet-4-20250514", + models=( + {"id": "claude-sonnet-4-20250514", "name": "Claude Sonnet 4 (视觉)", "vision": True}, + {"id": "claude-3-5-sonnet-20241022", "name": "Claude 3.5 Sonnet (视觉)", "vision": True}, + {"id": "claude-3-5-haiku-20241022", "name": "Claude 3.5 Haiku (视觉)", "vision": True}, + ), + supports_vision=True, + recommended=False, + description="通过原生 Anthropic REST API 直接调用,无需额外 SDK", + ), + # --- Custom (自定义) --- + ProviderPreset( + id="openai_compatible", + name="自定义 OpenAI 兼容 / 聚合服务", + category="custom", + protocol="openai_compatible", + base_url="", + docs_url="", + default_model="", + models=(), + supports_vision=True, + recommended=False, + description="适用于任意兼容 OpenAI Chat Completions 的自建或第三方聚合服务", + ), +) + +PRESET_BY_ID: dict[str, ProviderPreset] = {preset.id: preset for preset in PROVIDER_PRESETS} + +# Backward-compatible provider ID aliases +PROVIDER_ALIASES: dict[str, str] = { + "gemini": "google", + "claude": "anthropic", + "dashscope": "qwen", + "moonshot": "kimi", + "ark": "doubao", + "volcengine": "doubao", + "custom": "openai_compatible", +} + +# Mapping from canonical provider ID to (API_KEY_ENV, MODEL_ENV, BASE_URL_ENV) +PROVIDER_ENV_VARS: dict[str, tuple[str, str, str]] = { + "openai": ("OPENAI_API_KEY", "OPENAI_MODEL", "OPENAI_BASE_URL"), + "anthropic": ("ANTHROPIC_API_KEY", "ANTHROPIC_MODEL", "ANTHROPIC_BASE_URL"), + "google": ("GOOGLE_API_KEY", "GOOGLE_MODEL", "GOOGLE_BASE_URL"), + "qwen": ("QWEN_API_KEY", "QWEN_MODEL", "QWEN_BASE_URL"), + "deepseek": ("DEEPSEEK_API_KEY", "DEEPSEEK_MODEL", "DEEPSEEK_BASE_URL"), + "zhipu": ("ZHIPU_API_KEY", "ZHIPU_MODEL", "ZHIPU_BASE_URL"), + "kimi": ("KIMI_API_KEY", "KIMI_MODEL", "KIMI_BASE_URL"), + "doubao": ("DOUBAO_API_KEY", "DOUBAO_MODEL", "DOUBAO_BASE_URL"), + "siliconflow": ("SILICONFLOW_API_KEY", "SILICONFLOW_MODEL", "SILICONFLOW_BASE_URL"), + "openrouter": ("OPENROUTER_API_KEY", "OPENROUTER_MODEL", "OPENROUTER_BASE_URL"), + "openai_compatible": ( + "OPENAI_COMPATIBLE_API_KEY", + "OPENAI_COMPATIBLE_MODEL", + "OPENAI_COMPATIBLE_BASE_URL", + ), +} + + +def resolve_provider_id(provider: str) -> str: + """Resolve legacy or alias provider IDs to canonical preset IDs.""" + key = provider.strip().lower() + return PROVIDER_ALIASES.get(key, key) + + +def get_preset(provider: str) -> Optional[ProviderPreset]: + """Return the static preset for a provider ID or alias, or None if unknown.""" + return PRESET_BY_ID.get(resolve_provider_id(provider)) + + +def list_presets() -> list[dict[str, Any]]: + """Return all static presets serialized as dictionaries.""" + return [preset.to_dict() for preset in PROVIDER_PRESETS] diff --git a/backend/tests/test_config.py b/backend/tests/test_config.py index 3569fc7..be42326 100644 --- a/backend/tests/test_config.py +++ b/backend/tests/test_config.py @@ -16,6 +16,7 @@ _LLM_ENV_KEYS = ( "INVOICE_ENV_FILE", "LLM_PROVIDER", + "LLM_SUPPORTS_VISION", "LLM_CONFIG_TOKEN", "OPENAI_API_KEY", "OPENAI_MODEL", @@ -35,6 +36,21 @@ "ZHIPU_API_KEY", "ZHIPU_MODEL", "ZHIPU_BASE_URL", + "KIMI_API_KEY", + "KIMI_MODEL", + "KIMI_BASE_URL", + "DOUBAO_API_KEY", + "DOUBAO_MODEL", + "DOUBAO_BASE_URL", + "SILICONFLOW_API_KEY", + "SILICONFLOW_MODEL", + "SILICONFLOW_BASE_URL", + "OPENROUTER_API_KEY", + "OPENROUTER_MODEL", + "OPENROUTER_BASE_URL", + "OPENAI_COMPATIBLE_API_KEY", + "OPENAI_COMPATIBLE_MODEL", + "OPENAI_COMPATIBLE_BASE_URL", ) diff --git a/backend/tests/test_providers_and_settings.py b/backend/tests/test_providers_and_settings.py new file mode 100644 index 0000000..ebe85d2 --- /dev/null +++ b/backend/tests/test_providers_and_settings.py @@ -0,0 +1,561 @@ +"""Unit tests for M2-A provider presets, explicit vision switch, protocol routing, and async model registry.""" + +from __future__ import annotations + +import asyncio +import json +import os +import stat +from pathlib import Path +from typing import Any + +import httpx +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +import app.config as config_module +from app.routers import settings as settings_router +from app.services import model_registry +from app.services.llm_service import get_llm_service, reset_llm_service +from app.services.provider_presets import ( + PRESET_BY_ID, + PROVIDER_ENV_VARS, + PROVIDER_PRESETS, + resolve_provider_id, +) + +_ALL_ENV_KEYS = ( + "INVOICE_ENV_FILE", + "LLM_PROVIDER", + "LLM_SUPPORTS_VISION", + "LLM_CONFIG_TOKEN", + *(key for triple in PROVIDER_ENV_VARS.values() for key in triple), +) + + +@pytest.fixture(autouse=True) +def _isolate_env_and_caches(): + saved = {k: os.environ[k] for k in _ALL_ENV_KEYS if k in os.environ} + for k in _ALL_ENV_KEYS: + os.environ.pop(k, None) + config_module.clear_settings_cache() + reset_llm_service() + model_registry.clear_models_cache() + try: + yield + finally: + for k in _ALL_ENV_KEYS: + os.environ.pop(k, None) + for k, v in saved.items(): + os.environ[k] = v + config_module.clear_settings_cache() + reset_llm_service() + model_registry.clear_models_cache() + + +def _make_client() -> TestClient: + app = FastAPI() + app.include_router(settings_router.router, prefix="/api/settings") + return TestClient(app) + + +# --- (a) Presets completeness & empty recommended slot --- + + +def test_presets_complete_and_zero_recommended_entries(): + """All required domestic/global/custom presets must exist and zero entries may be recommended=True.""" + expected_domestic = {"qwen", "deepseek", "zhipu", "kimi", "doubao", "siliconflow"} + expected_global = {"openai", "openrouter", "google", "anthropic"} + expected_custom = {"openai_compatible"} + + domestic_ids = {p.id for p in PROVIDER_PRESETS if p.category == "domestic"} + global_ids = {p.id for p in PROVIDER_PRESETS if p.category == "global"} + custom_ids = {p.id for p in PROVIDER_PRESETS if p.category == "custom"} + + assert expected_domestic.issubset(domestic_ids) + assert expected_global.issubset(global_ids) + assert expected_custom.issubset(custom_ids) + + # Recommended slot MUST stay empty (recommended=False everywhere) + recommended = [p for p in PROVIDER_PRESETS if p.recommended] + assert recommended == [] + assert all(p.category != "recommended" for p in PROVIDER_PRESETS) + + # Protocol contracts & required URLs + assert PRESET_BY_ID["qwen"].base_url == "https://dashscope.aliyuncs.com/compatible-mode/v1" + assert PRESET_BY_ID["deepseek"].base_url == "https://api.deepseek.com/v1" + assert PRESET_BY_ID["deepseek"].supports_vision is False + assert PRESET_BY_ID["zhipu"].base_url == "https://open.bigmodel.cn/api/paas/v4" + assert PRESET_BY_ID["kimi"].base_url == "https://api.moonshot.cn/v1" + assert PRESET_BY_ID["doubao"].base_url == "https://ark.cn-beijing.volces.com/api/v3" + assert PRESET_BY_ID["siliconflow"].base_url == "https://api.siliconflow.cn/v1" + assert PRESET_BY_ID["openai"].base_url == "https://api.openai.com/v1" + assert PRESET_BY_ID["openrouter"].base_url == "https://openrouter.ai/api/v1" + assert PRESET_BY_ID["google"].base_url == "https://generativelanguage.googleapis.com/v1beta/openai/" + assert PRESET_BY_ID["google"].protocol == "openai_compatible" + assert PRESET_BY_ID["anthropic"].base_url == "https://api.anthropic.com/v1" + assert PRESET_BY_ID["anthropic"].protocol == "anthropic" + assert PRESET_BY_ID["openai_compatible"].base_url == "" + assert PRESET_BY_ID["openai_compatible"].protocol == "openai_compatible" + + # Legacy alias compatibility + assert resolve_provider_id("gemini") == "google" + assert resolve_provider_id("claude") == "anthropic" + assert resolve_provider_id("custom") == "openai_compatible" + + +# --- (b) Explicit supports_vision replaces whitelist --- + + +def test_custom_openai_compatible_vendor_model_with_explicit_vision_does_not_degrade( + tmp_path: Path, + monkeypatch, +): + """openai_compatible + vendor/model + supports_vision=True must enable vision and call endpoint.""" + env_file = tmp_path / ".env" + monkeypatch.setenv("INVOICE_ENV_FILE", str(env_file)) + client = _make_client() + + resp = client.post( + "/api/settings/llm/configure", + json={ + "provider": "openai_compatible", + "api_key": "sk-custom-key", + "base_url": "https://gateway.example.com/v1", + "model": "vendor/opaque-model-id", + "supports_vision": True, + }, + ) + assert resp.status_code == 200 + assert resp.json()["success"] is True + + # Status exposes persisted custom config + explicit vision + status = client.get("/api/settings/llm/status").json() + assert status["is_configured"] is True + assert status["active_provider"] == "openai_compatible" + assert status["active_model"] == "vendor/opaque-model-id" + assert status["active_base_url"] == "https://gateway.example.com/v1" + assert status["supports_vision"] is True + assert all(p["recommended"] is False for p in status["presets"]) + + # Mock httpx.Client.post to verify vision_completion actually fires (no silent OCR-only fallback) + captured: list[dict[str, Any]] = [] + fake_invoice_json = json.dumps( + { + "invoice_number": "12345678", + "invoice_code": None, + "issue_date": "2026-04-01", + "buyer_name": "示例买方", + "buyer_tax_id": "TESTBUYER000001", + "seller_name": "示例卖方", + "seller_tax_id": "TESTSELLER00001", + "item_name": "技术服务费", + "total_with_tax": "500.00", + "amount": "471.70", + "tax_amount": "28.30", + "tax_rate": "6%", + }, + ensure_ascii=False, + ) + + def _fake_post(self, url, *, json=None, headers=None, **kwargs): + captured.append({"url": url, "json": json, "headers": headers}) + return httpx.Response( + 200, + json={"choices": [{"message": {"content": fake_invoice_json}}]}, + request=httpx.Request("POST", url), + ) + + with monkeypatch.context() as m: + m.setattr(httpx.Client, "post", _fake_post) + + llm_service = get_llm_service() + assert llm_service.supports_vision() is True + parsed = llm_service.parse_invoice_from_image(b"fake-png-data", "image/png") + assert parsed["invoice_number"] == "12345678" + assert parsed["total_with_tax"] == "500.00" + assert len(captured) == 1 + assert captured[0]["url"] == "https://gateway.example.com/v1/chat/completions" + assert captured[0]["json"]["model"] == "vendor/opaque-model-id" + + # Explicit supports_vision=False must disable vision even for gpt-4o and never POST image bytes + resp_off = client.post( + "/api/settings/llm/configure", + json={ + "provider": "openai", + "api_key": "sk-openai-key", + "model": "gpt-4o", + "supports_vision": False, + }, + ) + assert resp_off.status_code == 200 + assert get_llm_service().supports_vision() is False + + off_calls: list[dict[str, Any]] = [] + + def _forbid_post(self, url, *, json=None, headers=None, **kwargs): + off_calls.append({"url": url, "json": json, "headers": headers}) + raise AssertionError("httpx.Client.post must not be called when supports_vision=False") + + with monkeypatch.context() as m: + m.setattr(httpx.Client, "post", _forbid_post) + result_off = get_llm_service().parse_invoice_from_image(b"fake-png-data", "image/png") + + assert result_off == {} + assert len(off_calls) == 0 + + +# --- (c) DeepSeek / Zhipu / Gemini / Anthropic protocol routing without missing SDKs --- + + +@pytest.mark.parametrize( + "provider_input,expected_url,expected_protocol,expected_model", + [ + ("deepseek", "https://api.deepseek.com/v1/chat/completions", "openai_compatible", "deepseek-chat"), + ("zhipu", "https://open.bigmodel.cn/api/paas/v4/chat/completions", "openai_compatible", "glm-4v-plus"), + ("gemini", "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions", "openai_compatible", "gemini-2.5-flash"), + ("claude", "https://api.anthropic.com/v1/messages", "anthropic", "claude-sonnet-4-20250514"), + ], +) +def test_provider_test_config_routes_without_missing_sdk_errors( + monkeypatch, + provider_input: str, + expected_url: str, + expected_protocol: str, + expected_model: str, +): + """DeepSeek, Zhipu, Gemini, and Anthropic must succeed via httpx REST with zero missing SDK crashes.""" + captured: list[dict[str, Any]] = [] + + async def _fake_async_post(self, url, *, json=None, headers=None, **kwargs): + captured.append({"url": url, "json": json, "headers": headers}) + if expected_protocol == "anthropic": + body = {"content": [{"type": "text", "text": "OK"}]} + else: + body = {"choices": [{"message": {"content": "OK"}}]} + return httpx.Response(200, json=body, request=httpx.Request("POST", url)) + + monkeypatch.setattr(httpx.AsyncClient, "post", _fake_async_post) + + client = _make_client() + resp = client.post( + "/api/settings/llm/test-config", + json={"provider": provider_input, "api_key": "sk-test-123"}, + ) + assert resp.status_code == 200 + data = resp.json() + assert data["success"] is True + assert "OK" in data["message"] + + assert len(captured) == 1 + assert captured[0]["url"] == expected_url + assert captured[0]["json"]["model"] == expected_model + if expected_protocol == "anthropic": + assert captured[0]["headers"]["x-api-key"] == "sk-test-123" + assert "anthropic-version" in captured[0]["headers"] + else: + assert captured[0]["headers"]["Authorization"] == "Bearer sk-test-123" + + +def test_anthropic_vision_uses_native_rest_over_httpx(tmp_path: Path, monkeypatch): + """Anthropic vision parsing sends native base64 image block over httpx without anthropic SDK.""" + env_file = tmp_path / ".env" + monkeypatch.setenv("INVOICE_ENV_FILE", str(env_file)) + client = _make_client() + assert ( + client.post( + "/api/settings/llm/configure", + json={ + "provider": "claude", + "api_key": "sk-ant-test", + "model": "claude-sonnet-4-20250514", + "supports_vision": True, + }, + ).status_code + == 200 + ) + + captured: list[dict[str, Any]] = [] + + def _fake_post(self, url, *, json=None, headers=None, **kwargs): + captured.append({"url": url, "json": json, "headers": headers}) + payload = { + "content": [ + { + "type": "text", + "text": '{"invoice_number":"87654321","invoice_code":null,"issue_date":"2026-05-01","buyer_name":"A","buyer_tax_id":"TESTBUYER000001","seller_name":"B","seller_tax_id":"TESTSELLER00001","item_name":"X","total_with_tax":"88.00","amount":"83.02","tax_amount":"4.98","tax_rate":"6%"}', + } + ] + } + return httpx.Response(200, json=payload, request=httpx.Request("POST", url)) + + with monkeypatch.context() as m: + m.setattr(httpx.Client, "post", _fake_post) + fields = get_llm_service().parse_invoice_from_image(b"png-bytes", "image/png") + + assert fields["invoice_number"] == "87654321" + assert captured[0]["url"] == "https://api.anthropic.com/v1/messages" + assert captured[0]["headers"]["x-api-key"] == "sk-ant-test" + msg_content = captured[0]["json"]["messages"][0]["content"] + assert msg_content[0]["type"] == "image" + assert msg_content[0]["source"]["media_type"] == "image/png" + + +# --- (d) Persistence of supports_vision & base_url + newline injection defense --- + + +def test_configure_persists_supports_vision_and_base_url_with_0600_and_blocks_newlines( + tmp_path: Path, + monkeypatch, +): + """configure persists base_url + supports_vision with 0o600 and rejects CRLF on both endpoints.""" + env_file = tmp_path / "data" / ".env" + monkeypatch.setenv("INVOICE_ENV_FILE", str(env_file)) + client = _make_client() + + # test-config rejects newline injection + bad_test = client.post( + "/api/settings/llm/test-config", + json={ + "provider": "openai_compatible", + "api_key": "sk-1", + "base_url": "https://api.example.com/v1\nEVIL=1", + "model": "vendor/m", + }, + ) + assert bad_test.status_code == 400 + + # configure rejects newline injection + bad_cfg = client.post( + "/api/settings/llm/configure", + json={ + "provider": "openai_compatible", + "api_key": "sk-1", + "base_url": "https://api.example.com/v1\rEVIL=1", + "model": "vendor/m", + "supports_vision": True, + }, + ) + assert bad_cfg.status_code == 400 + assert not env_file.exists() + + # Valid configure writes 0o600 file and survives cache clear (simulating container restart) + ok_cfg = client.post( + "/api/settings/llm/configure", + json={ + "provider": "openai_compatible", + "api_key": "sk-persisted", + "base_url": "https://api.example.com/v1", + "model": "vendor/vision-pro", + "supports_vision": True, + }, + ) + assert ok_cfg.status_code == 200 + assert stat.S_IMODE(env_file.stat().st_mode) == 0o600 + + content = env_file.read_text(encoding="utf-8") + assert "LLM_PROVIDER=openai_compatible" in content + assert "OPENAI_COMPATIBLE_BASE_URL=https://api.example.com/v1" in content + assert "OPENAI_COMPATIBLE_MODEL=vendor/vision-pro" in content + assert "LLM_SUPPORTS_VISION=true" in content + + # Simulate process restart: drop env vars, keep only INVOICE_ENV_FILE, clear caches + for k in _ALL_ENV_KEYS: + if k != "INVOICE_ENV_FILE": + os.environ.pop(k, None) + config_module.clear_settings_cache() + reset_llm_service() + + status_after = client.get("/api/settings/llm/status").json() + assert status_after["is_configured"] is True + assert status_after["active_provider"] == "openai_compatible" + assert status_after["active_model"] == "vendor/vision-pro" + assert status_after["active_base_url"] == "https://api.example.com/v1" + assert status_after["supports_vision"] is True + + +# --- (e) Async /api/settings/models caching and timeout fallback --- + + +def test_models_endpoint_async_ttl_cache_and_timeout_fallback(monkeypatch): + """/api/settings/models caches OpenRouter responses and falls back smoothly on timeout.""" + client = _make_client() + call_count = 0 + + async def _fake_get_success(self, url, **kwargs): + nonlocal call_count + call_count += 1 + return httpx.Response( + 200, + json={ + "data": [ + { + "id": "openai/gpt-4o-mini", + "name": "GPT-4o Mini Live", + "architecture": {"input_modalities": ["text", "image"]}, + "context_length": 128000, + "pricing": {"prompt": "0.00015", "completion": "0.0006"}, + }, + { + "id": "anthropic/claude-sonnet-4", + "name": "Claude Sonnet 4 Live", + "architecture": {"input_modalities": ["text", "image"]}, + }, + ] + }, + request=httpx.Request("GET", url), + ) + + monkeypatch.setattr(httpx.AsyncClient, "get", _fake_get_success) + + # First call fetches OpenRouter + r1 = client.get("/api/settings/models?provider=openrouter") + assert r1.status_code == 200 + body1 = r1.json() + assert body1["source"] == "openrouter" + assert any(m["id"] == "openai/gpt-4o-mini" for m in body1["models"]) + assert call_count == 1 + + # Second call within TTL hits in-memory cache (no additional HTTP GET) + r2 = client.get("/api/settings/models?provider=openai") + assert r2.status_code == 200 + body2 = r2.json() + assert body2["source"] == "openrouter" + # Native openai strips "openai/" prefix so model ID is directly usable with api.openai.com + assert body2["models"][0]["id"] == "gpt-4o-mini" + assert call_count == 1 + + # Clear cache and simulate timeout -> smooth fallback to static preset models + model_registry.clear_models_cache() + + async def _fake_get_timeout(self, url, **kwargs): + raise httpx.TimeoutException("simulated timeout") + + monkeypatch.setattr(httpx.AsyncClient, "get", _fake_get_timeout) + + r3 = client.get("/api/settings/models?provider=openrouter") + assert r3.status_code == 200 + body3 = r3.json() + assert body3["source"] == "fallback" + assert len(body3["models"]) == len(PRESET_BY_ID["openrouter"].models) + + # Domestic providers return static presets immediately without calling OpenRouter + r4 = client.get("/api/settings/models?provider=deepseek") + assert r4.status_code == 200 + body4 = r4.json() + assert body4["source"] == "fallback" + assert any(m["id"] == "deepseek-chat" for m in body4["models"]) + + +def test_models_negative_cache_suppresses_repeated_timeouts_within_ttl(monkeypatch): + """After an OpenRouter failure, subsequent calls within NEGATIVE_CACHE_TTL_SECONDS must not refetch.""" + clock = {"now": 1000.0} + monkeypatch.setattr(model_registry.time, "monotonic", lambda: clock["now"]) + + fetch_count = 0 + should_fail = {"value": True} + + async def _fake_get(self, url, **kwargs): + nonlocal fetch_count + fetch_count += 1 + if should_fail["value"]: + raise httpx.TimeoutException("simulated timeout") + return httpx.Response( + 200, + json={ + "data": [ + { + "id": "openai/gpt-4o-mini", + "name": "GPT-4o Mini Recovered", + "architecture": {"input_modalities": ["text", "image"]}, + } + ] + }, + request=httpx.Request("GET", url), + ) + + monkeypatch.setattr(httpx.AsyncClient, "get", _fake_get) + client = _make_client() + + # 1st failure records negative cache + r1 = client.get("/api/settings/models?provider=openrouter") + assert r1.status_code == 200 + assert r1.json()["source"] == "fallback" + assert fetch_count == 1 + + # Repeated requests across global providers (and full catalog) within 60s must NOT hit OpenRouter again + clock["now"] += 30.0 + r2 = client.get("/api/settings/models?provider=openai") + r3 = client.get("/api/settings/models?provider=anthropic") + r4 = client.get("/api/settings/models") + assert r2.status_code == 200 and r2.json()["source"] == "fallback" + assert r3.status_code == 200 and r3.json()["source"] == "fallback" + assert r4.status_code == 200 and r4.json()["source"] == "fallback" + assert fetch_count == 1 + + # Once negative TTL expires, upstream is retried and recovers cleanly + should_fail["value"] = False + clock["now"] += model_registry.NEGATIVE_CACHE_TTL_SECONDS + r5 = client.get("/api/settings/models?provider=openai") + assert r5.status_code == 200 + body5 = r5.json() + assert body5["source"] == "openrouter" + assert body5["models"][0]["id"] == "gpt-4o-mini" + assert fetch_count == 2 + + +def test_models_single_flight_coalesces_concurrent_fetches(monkeypatch): + """Concurrent requests on cache miss must share a single OpenRouter fetch (both success & failure).""" + + async def _run_single_flight(fail: bool) -> tuple[int, list[str]]: + model_registry.clear_models_cache() + fetch_count = 0 + + async def _slow_get(self, url, **kwargs): + nonlocal fetch_count + fetch_count += 1 + await asyncio.sleep(0.05) + if fail: + raise httpx.TimeoutException("concurrent timeout") + return httpx.Response( + 200, + json={ + "data": [ + { + "id": "openai/gpt-4o-mini", + "name": "GPT-4o Mini", + "architecture": {"input_modalities": ["text", "image"]}, + }, + { + "id": "anthropic/claude-sonnet-4", + "name": "Claude Sonnet 4", + "architecture": {"input_modalities": ["text", "image"]}, + }, + { + "id": "google/gemini-2.5-flash", + "name": "Gemini 2.5 Flash", + "architecture": {"input_modalities": ["text", "image"]}, + }, + ] + }, + request=httpx.Request("GET", url), + ) + + monkeypatch.setattr(httpx.AsyncClient, "get", _slow_get) + results = await asyncio.gather( + model_registry.get_models_with_fallback_async("openrouter"), + model_registry.get_models_with_fallback_async("openai"), + model_registry.get_models_with_fallback_async("anthropic"), + model_registry.get_models_with_fallback_async("google"), + model_registry.get_models_with_fallback_async("openrouter"), + ) + return fetch_count, [source for _models, source in results] + + ok_fetches, ok_sources = asyncio.run(_run_single_flight(fail=False)) + assert ok_fetches == 1 + assert ok_sources == ["openrouter"] * 5 + + fail_fetches, fail_sources = asyncio.run(_run_single_flight(fail=True)) + assert fail_fetches == 1 + assert fail_sources == ["fallback"] * 5 From 10f0b711b3de99f0a432436132bb2606fb5ec424 Mon Sep 17 00:00:00 2001 From: stone16 <12712299+stone16@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:04:17 +0800 Subject: [PATCH 3/4] feat(ui): refactor settings modal, add 3-step onboarding, and remove Google Fonts --- README.md | 1 + frontend/src/App.tsx | 118 +++- frontend/src/components/LLMConfigModal.tsx | 499 ++++++++++------ frontend/src/components/OnboardingGuide.tsx | 539 ++++++++++++++++++ .../components/layout/MainLayout.module.css | 2 + frontend/src/services/api.ts | 5 +- frontend/src/styles/global.css | 3 - frontend/src/styles/variables.css | 6 +- frontend/src/types/invoice.ts | 36 ++ 9 files changed, 1019 insertions(+), 190 deletions(-) create mode 100644 frontend/src/components/OnboardingGuide.tsx diff --git a/README.md b/README.md index ec21399..6a024a9 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,7 @@ docker compose up -d --build | API 文档 | `http://:15173/docs` | `http://localhost:18080/docs` | Swagger UI | | 后端直连 | (同源 `/api`) | `http://localhost:18080` | 开发调试用 REST API | + ### 配置 LLM | Configure LLM 系统支持 **6 种 LLM 提供商**,可在界面中实时切换: diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 3aa6b2c..cd8f851 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,49 +1,121 @@ -import { useState, useEffect } from 'react'; -import { BrowserRouter, Routes, Route } from 'react-router-dom'; +import { useState, useEffect, useCallback } from 'react'; +import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom'; +import { message } from 'antd'; import UploadPage from './pages/UploadPage'; import InvoiceListPage from './pages/InvoiceListPage'; import InvoiceDetailPage from './pages/InvoiceDetailPage'; import LLMConfigModal from './components/LLMConfigModal'; +import OnboardingGuide from './components/OnboardingGuide'; import { MainLayout } from './components/layout'; -import { getLLMStatus } from './services/api'; +import { getLLMStatus, listInvoices } from './services/api'; +import type { LLMStatusResponse } from './types/invoice'; + +const ONBOARDING_DISMISSED_KEY = 'invoice_onboarding_dismissed'; + +function readOnboardingDismissed(): boolean { + try { + return window.localStorage.getItem(ONBOARDING_DISMISSED_KEY) === 'true'; + } catch { + return false; + } +} function AppContent() { + const location = useLocation(); const [llmConfigOpen, setLlmConfigOpen] = useState(false); const [llmConfigured, setLlmConfigured] = useState(null); + const [llmStatus, setLlmStatus] = useState(null); + const [backendConnected, setBackendConnected] = useState(false); + const [onboardingDismissed, setOnboardingDismissed] = useState(() => + readOnboardingDismissed() + ); + const [onboardingActive, setOnboardingActive] = useState(false); const [showLlmPromo, setShowLlmPromo] = useState(false); - // Check LLM status on app load + const refreshBootstrapState = useCallback(async () => { + try { + const [status, invoicesResp] = await Promise.all([ + getLLMStatus(), + listInvoices({ page: 1, page_size: 1 }), + ]); + setBackendConnected(true); + setLlmStatus(status); + setLlmConfigured(status.is_configured); + + const dismissed = readOnboardingDismissed(); + setOnboardingDismissed(dismissed); + // Show lightweight promo banner only when user already has invoices (not in first-time onboarding) + // and hasn't dismissed onboarding/OCR-only preference + const willShowOnboarding = + !status.is_configured && invoicesResp.total === 0 && !dismissed; + setOnboardingActive(willShowOnboarding); + setShowLlmPromo(!status.is_configured && !willShowOnboarding && !dismissed); + } catch (error) { + console.error('Failed to check initial backend status:', error); + setBackendConnected(false); + setLlmConfigured(false); + } + }, []); + useEffect(() => { - const checkLLMStatus = async () => { - try { - const status = await getLLMStatus(); - setLlmConfigured(status.is_configured); - // Show promotion banner if LLM is not configured (non-blocking) - if (!status.is_configured) { - setShowLlmPromo(true); + void refreshBootstrapState(); + }, [refreshBootstrapState]); + + const handleLLMConfigured = async (closeOnboarding: boolean) => { + try { + const status = await getLLMStatus(); + setLlmStatus(status); + setLlmConfigured(status.is_configured); + if (status.is_configured) { + setShowLlmPromo(false); + if (closeOnboarding) { + setOnboardingActive(false); } - } catch (error) { - console.error('Failed to check LLM status:', error); - // If check fails, assume not configured - setLlmConfigured(false); - setShowLlmPromo(true); } - }; - checkLLMStatus(); - }, []); + } catch { + setLlmConfigured(true); + setShowLlmPromo(false); + if (closeOnboarding) { + setOnboardingActive(false); + } + } + }; - const handleLLMConfigured = () => { - setLlmConfigured(true); + const handleSkipOcrOnly = () => { + try { + window.localStorage.setItem(ONBOARDING_DISMISSED_KEY, 'true'); + } catch { + // Ignore storage failures in restricted browsers + } + setOnboardingDismissed(true); + setOnboardingActive(false); setShowLlmPromo(false); + message.info('已切换为纯本地 OCR 模式,可随时在左侧「设置」中配置模型服务'); }; + const shouldShowOnboarding = + location.pathname === '/' && + backendConnected && + llmStatus !== null && + onboardingActive && + !onboardingDismissed; + return ( setLlmConfigOpen(true)} onCloseLLMPromo={() => setShowLlmPromo(false)} > + {shouldShowOnboarding && ( + handleLLMConfigured(false)} + onSkipOcrOnly={handleSkipOcrOnly} + onFinish={() => setOnboardingActive(false)} + /> + )} + } /> } /> @@ -53,7 +125,7 @@ function AppContent() { setLlmConfigOpen(false)} - onConfigured={handleLLMConfigured} + onConfigured={() => handleLLMConfigured(true)} /> ); diff --git a/frontend/src/components/LLMConfigModal.tsx b/frontend/src/components/LLMConfigModal.tsx index 93758ce..73f4fa0 100644 --- a/frontend/src/components/LLMConfigModal.tsx +++ b/frontend/src/components/LLMConfigModal.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef, useMemo } from 'react'; import { Modal, Form, @@ -13,6 +13,8 @@ import { Divider, Tooltip, AutoComplete, + Switch, + Typography, } from 'antd'; import { SettingOutlined, @@ -20,9 +22,16 @@ import { ExclamationCircleOutlined, ApiOutlined, EyeOutlined, + LinkOutlined, } from '@ant-design/icons'; import { getLLMStatus, configureLLM, testLLMConfig, getAvailableModels } from '../services/api'; -import type { LLMStatusResponse, LLMProviderInfo, ModelInfo } from '../types/invoice'; +import type { + LLMStatusResponse, + ModelInfo, + ProviderPresetInfo, +} from '../types/invoice'; + +const { Text } = Typography; interface LLMConfigModalProps { open: boolean; @@ -30,35 +39,11 @@ interface LLMConfigModalProps { onConfigured?: () => void; } -// Fallback models for each provider (used when API fails) -const FALLBACK_MODELS: Record = { - openai: [ - { id: 'gpt-4o', name: 'GPT-4o', vision: true }, - { id: 'gpt-4o-mini', name: 'GPT-4o Mini', vision: true }, - { id: 'gpt-4-turbo', name: 'GPT-4 Turbo', vision: true }, - ], - anthropic: [ - { id: 'claude-sonnet-4-20250514', name: 'Claude Sonnet 4', vision: true }, - { id: 'claude-3-5-sonnet-20241022', name: 'Claude 3.5 Sonnet', vision: true }, - { id: 'claude-3-5-haiku-20241022', name: 'Claude 3.5 Haiku', vision: true }, - ], - google: [ - { id: 'gemini-2.0-flash', name: 'Gemini 2.0 Flash', vision: true }, - { id: 'gemini-1.5-pro', name: 'Gemini 1.5 Pro', vision: true }, - { id: 'gemini-1.5-flash', name: 'Gemini 1.5 Flash', vision: true }, - ], - qwen: [ - { id: 'qwen2.5-vl-72b-instruct', name: 'Qwen 2.5 VL 72B', vision: true }, - { id: 'qwen-turbo', name: 'Qwen Turbo', vision: false }, - ], - deepseek: [ - { id: 'deepseek-chat', name: 'DeepSeek Chat', vision: false }, - ], - zhipu: [ - { id: 'glm-4v', name: 'GLM-4V', vision: true }, - { id: 'glm-4-flash', name: 'GLM-4 Flash', vision: false }, - ], -}; +interface TestFeedback { + success: boolean; + message: string; + responseTimeMs?: number; +} function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { const [loading, setLoading] = useState(true); @@ -69,80 +54,173 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { const [models, setModels] = useState([]); const [modelsLoading, setModelsLoading] = useState(false); const [modelsSource, setModelsSource] = useState<'openrouter' | 'fallback'>('fallback'); + const [testFeedback, setTestFeedback] = useState(null); + const latestProviderRef = useRef(''); const [form] = Form.useForm(); - const fetchStatus = async () => { - setLoading(true); - try { - const data = await getLLMStatus(); - setStatus(data); - if (data.active_provider) { - setSelectedProvider(data.active_provider); - // Fetch models for the active provider - await fetchModels(data.active_provider); - } - } catch (error) { - console.error('Failed to fetch LLM status:', error); - } finally { - setLoading(false); + const presets: ProviderPresetInfo[] = useMemo(() => status?.presets || [], [status]); + + const recommendedPresets = useMemo( + () => presets.filter((p) => p.recommended), + [presets] + ); + + const selectedPreset = useMemo( + () => presets.find((p) => p.id === selectedProvider) || null, + [presets, selectedProvider] + ); + + const groupedSelectOptions = useMemo(() => { + const groups: Array<{ + label: string; + options: Array<{ label: string; value: string }>; + }> = []; + + // Recommended group is ONLY rendered when at least one preset has recommended=true + if (recommendedPresets.length > 0) { + groups.push({ + label: '推荐', + options: recommendedPresets.map((p) => ({ label: p.name, value: p.id })), + }); } - }; - const fetchModels = async (provider: string) => { + const domestic = presets.filter((p) => !p.recommended && p.category === 'domestic'); + if (domestic.length > 0) { + groups.push({ + label: '国内常用', + options: domestic.map((p) => ({ label: p.name, value: p.id })), + }); + } + + const global = presets.filter((p) => !p.recommended && p.category === 'global'); + if (global.length > 0) { + groups.push({ + label: '海外服务', + options: global.map((p) => ({ label: p.name, value: p.id })), + }); + } + + const custom = presets.filter((p) => !p.recommended && p.category === 'custom'); + if (custom.length > 0) { + groups.push({ + label: '自定义', + options: custom.map((p) => ({ label: p.name, value: p.id })), + }); + } + + return groups; + }, [presets, recommendedPresets]); + + const enrichModelsAsync = async (providerId: string, presetModels: ModelInfo[]) => { + setModels(presetModels); + setModelsSource('fallback'); setModelsLoading(true); try { - const response = await getAvailableModels(provider, false); + const response = await getAvailableModels(providerId, false); + // Guard against race conditions if the user already switched providers + if (latestProviderRef.current !== providerId) { + return; + } if (response.models && response.models.length > 0) { setModels(response.models); setModelsSource(response.source); - } else { - // Fall back to hardcoded models - setModels(FALLBACK_MODELS[provider] || []); - setModelsSource('fallback'); } } catch (error) { + if (latestProviderRef.current === providerId) { + setModels(presetModels); + setModelsSource('fallback'); + } console.error('Failed to fetch models:', error); - // Fall back to hardcoded models - setModels(FALLBACK_MODELS[provider] || []); - setModelsSource('fallback'); } finally { - setModelsLoading(false); + if (latestProviderRef.current === providerId) { + setModelsLoading(false); + } } }; - useEffect(() => { - if (open) { - fetchStatus(); - form.resetFields(); - } - }, [open]); + const applyPresetToForm = (providerId: string, statusData: LLMStatusResponse) => { + latestProviderRef.current = providerId; + setSelectedProvider(providerId); + setTestFeedback(null); + + const preset = (statusData.presets || []).find((p) => p.id === providerId); + const savedProvider = statusData.available_providers.find((p) => p.name === providerId); + const isActive = statusData.is_configured && statusData.active_provider === providerId; + + const nextModel = isActive + ? (statusData.active_model ?? preset?.default_model ?? '') + : savedProvider?.is_configured + ? (savedProvider.model ?? preset?.default_model ?? '') + : (preset?.default_model ?? ''); + + const nextBaseUrl = isActive + ? (statusData.active_base_url ?? preset?.base_url ?? '') + : savedProvider?.is_configured + ? (savedProvider.base_url ?? preset?.base_url ?? '') + : (preset?.base_url ?? ''); - const handleProviderChange = async (provider: string) => { - setSelectedProvider(provider); - // Fetch models for the new provider - await fetchModels(provider); - // Set default model from fetched list - const providerModels = FALLBACK_MODELS[provider] || []; - // Pre-populate base_url from saved config if available - const savedProvider = status?.available_providers.find(p => p.name === provider); + const matchedPresetModel = (preset?.models || []).find((m) => m.id === nextModel); + const nextSupportsVision = isActive + ? Boolean(statusData.supports_vision) + : matchedPresetModel + ? matchedPresetModel.vision + : Boolean(preset?.supports_vision); + + // Unconditionally reset all form fields for the chosen provider (prevents model/base_url bleed) form.setFieldsValue({ - provider, - model: providerModels[0]?.id || '', + provider: providerId, + model: nextModel, + base_url: nextBaseUrl, + supports_vision: nextSupportsVision, api_key: '', - base_url: savedProvider?.base_url || '', config_token: '', }); + + const staticModels: ModelInfo[] = (preset?.models || []).map((m) => ({ + id: m.id, + name: m.name, + vision: m.vision, + })); + void enrichModelsAsync(providerId, staticModels); + }; + + const fetchStatus = async (preferredProvider?: string) => { + setLoading(true); + try { + const data = await getLLMStatus(); + setStatus(data); + const targetProvider = + preferredProvider || + (data.is_configured && data.active_provider) || + data.presets?.[0]?.id || + 'qwen'; + applyPresetToForm(targetProvider, data); + } catch (error) { + console.error('Failed to fetch LLM status:', error); + } finally { + setLoading(false); + } }; - // Update form model when models are fetched (only if empty) useEffect(() => { - if (models.length > 0 && selectedProvider) { - const currentModel = form.getFieldValue('model'); - if (!currentModel) { - form.setFieldsValue({ model: models[0].id }); - } + if (open) { + setTestFeedback(null); + form.resetFields(); + void fetchStatus(); } - }, [models, selectedProvider]); + }, [open]); + + const handleProviderChange = (providerId: string) => { + if (!status) return; + applyPresetToForm(providerId, status); + }; + + const handleModelSelect = (modelId: string) => { + const matched = models.find((m) => m.id === modelId); + if (matched) { + form.setFieldValue('supports_vision', matched.vision); + } + }; const handleConfigure = async () => { try { @@ -151,16 +229,17 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { const config = { provider: values.provider, - api_key: values.api_key, - model: values.model || undefined, - base_url: values.base_url || undefined, + api_key: values.api_key.trim(), + model: values.model?.trim() || undefined, + base_url: values.base_url?.trim() || undefined, + supports_vision: Boolean(values.supports_vision), }; const configToken = values.config_token?.trim(); const result = await configureLLM(config, configToken || undefined); if (result.success) { message.success(result.message); - await fetchStatus(); + await fetchStatus(result.provider || values.provider); onConfigured?.(); } } catch (error: unknown) { @@ -172,7 +251,6 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { } } if (error && typeof error === 'object' && 'errorFields' in error) { - // Form validation error, ignore return; } message.error('配置失败'); @@ -184,72 +262,72 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { const handleTestConfig = async () => { const values = form.getFieldsValue(); if (!values.provider) { - message.warning('请先选择LLM提供商'); + message.warning('请先选择模型服务商'); return; } if (!values.api_key?.trim()) { - message.warning('请先输入API密钥'); + message.warning('请先输入 API 密钥'); + return; + } + if (selectedPreset?.category === 'custom' && !values.base_url?.trim()) { + message.warning('自定义服务请先填写 API 地址 (Base URL)'); return; } + setTestingConfig(true); + setTestFeedback(null); try { const result = await testLLMConfig({ provider: values.provider, api_key: values.api_key.trim(), - model: values.model || undefined, + model: values.model?.trim() || undefined, base_url: values.base_url?.trim() || undefined, + supports_vision: Boolean(values.supports_vision), + }); + setTestFeedback({ + success: result.success, + message: result.message, + responseTimeMs: result.response_time_ms, }); if (result.success) { - message.success(`${result.message} (${result.response_time_ms}ms)`); + message.success( + result.response_time_ms != null + ? `${result.message} (${result.response_time_ms}ms)` + : result.message + ); } else { message.error(result.message); } } catch (error: unknown) { + let detail = '配置测试失败'; if (error && typeof error === 'object' && 'response' in error) { const axiosError = error as { response?: { data?: { detail?: string } } }; if (axiosError.response?.data?.detail) { - message.error(axiosError.response.data.detail); - return; + detail = axiosError.response.data.detail; } } - message.error('配置测试失败'); + setTestFeedback({ success: false, message: detail }); + message.error(detail); } finally { setTestingConfig(false); } }; - const renderProviderStatus = (provider: LLMProviderInfo) => { - const isActive = status?.active_provider === provider.name; - return ( -
- {provider.display_name} - {provider.is_configured && ( - }> - 已配置 - - )} - {isActive && ( - 当前使用 - )} - {provider.model && provider.is_configured && ( - {provider.model} - )} -
- ); - }; + const isCustomProvider = selectedPreset?.category === 'custom'; return ( - LLM 服务配置 + 模型服务配置 } open={open} onCancel={onClose} footer={null} - width={600} + width={640} + destroyOnClose={false} > {loading ? (
@@ -257,13 +335,17 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) {
) : ( <> - {/* Current Status */} + {/* Current Status Banner */} {status?.is_configured ? ( + 当前使用: {status.active_provider_display} + {status.active_model && {status.active_model}} + + {status.supports_vision ? '视觉看图:已开启' : '视觉看图:未开启'} + } type="success" @@ -272,8 +354,8 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { /> ) : ( } @@ -281,49 +363,113 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { /> )} - {/* Provider List */} -
-
可用的LLM提供商:
-
- {status?.available_providers.map(renderProviderStatus)} + {/* Recommended Preset Card — ONLY rendered when recommended presets exist */} + {recommendedPresets.length > 0 && ( +
+ {recommendedPresets.map((preset) => ( + + 推荐 + {preset.name} + {preset.docs_url && ( + + 获取 Key + + )} + + } + description={preset.description} + style={{ marginBottom: 8 }} + /> + ))}
-
- - - - {/* Configuration Form */} -
+ )} + + {/* Configured Providers Summary */} + {status && status.configured_providers.length > 0 && ( +
+ + 已保存密钥的服务商: + + + {status.available_providers + .filter((p) => p.is_configured) + .map((p) => ( + handleProviderChange(p.name)} + > + {p.display_name} + {p.model ? ` · ${p.model}` : ''} + + ))} + +
+ )} + + + + @@ -331,23 +477,37 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { name="model" label={ - 模型 + 模型名称 {modelsSource === 'openrouter' && ( - 来自 OpenRouter + + 实时目录 + )} } + rules={ + isCustomProvider + ? [{ required: true, message: '请填写模型 ID(如 vendor/vision-pro)' }] + : undefined + } > ({ label: ( {m.name || m.id} {m.vision && ( - - + + )} @@ -357,38 +517,59 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { filterOption={(input, option) => (option?.value as string)?.toLowerCase().includes(input.toLowerCase()) } + data-testid="model-input" /> - + - + - + {testFeedback && ( + + )} + + diff --git a/frontend/src/components/OnboardingGuide.tsx b/frontend/src/components/OnboardingGuide.tsx new file mode 100644 index 0000000..d6d2b74 --- /dev/null +++ b/frontend/src/components/OnboardingGuide.tsx @@ -0,0 +1,539 @@ +import { useState, useMemo } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { + Card, + Steps, + Button, + Space, + Form, + Input, + AutoComplete, + Switch, + Tag, + Alert, + Result, + Typography, + message, +} from 'antd'; +import { + ApiOutlined, + CheckCircleOutlined, + EyeOutlined, + LinkOutlined, + RocketOutlined, + UploadOutlined, + ArrowLeftOutlined, +} from '@ant-design/icons'; +import { configureLLM, testLLMConfig } from '../services/api'; +import type { ProviderPresetInfo } from '../types/invoice'; + +const { Text, Title } = Typography; + +interface OnboardingGuideProps { + presets: ProviderPresetInfo[]; + onConfigured: () => Promise | void; + onSkipOcrOnly: () => void; + onFinish: () => void; +} + +interface OnboardingTestFeedback { + success: boolean; + message: string; + responseTimeMs?: number; +} + +export default function OnboardingGuide({ + presets, + onConfigured, + onSkipOcrOnly, + onFinish, +}: OnboardingGuideProps) { + const navigate = useNavigate(); + const [step, setStep] = useState(0); + const [selectedPresetId, setSelectedPresetId] = useState( + presets[0]?.id || 'qwen' + ); + const [submitting, setSubmitting] = useState(false); + const [savingDirect, setSavingDirect] = useState(false); + const [testFeedback, setTestFeedback] = useState(null); + const [savedSummary, setSavedSummary] = useState<{ + providerName: string; + model: string; + supportsVision: boolean; + } | null>(null); + const [form] = Form.useForm(); + + const recommendedPresets = useMemo( + () => presets.filter((p) => p.recommended), + [presets] + ); + const domesticPresets = useMemo( + () => presets.filter((p) => !p.recommended && p.category === 'domestic'), + [presets] + ); + const globalAndCustomPresets = useMemo( + () => + presets.filter( + (p) => !p.recommended && (p.category === 'global' || p.category === 'custom') + ), + [presets] + ); + + const selectedPreset = useMemo( + () => presets.find((p) => p.id === selectedPresetId) || presets[0] || null, + [presets, selectedPresetId] + ); + + const goToStepTwo = (presetId: string) => { + const preset = presets.find((p) => p.id === presetId); + setSelectedPresetId(presetId); + setTestFeedback(null); + form.setFieldsValue({ + api_key: '', + base_url: preset?.base_url || '', + model: preset?.default_model || '', + supports_vision: Boolean(preset?.supports_vision), + config_token: '', + }); + setStep(1); + }; + + const handleModelSelect = (modelId: string) => { + const matched = selectedPreset?.models.find((m) => m.id === modelId); + if (matched) { + form.setFieldValue('supports_vision', matched.vision); + } + }; + + const handleTestAndSave = async () => { + if (!selectedPreset) return; + try { + const values = await form.validateFields(); + setSubmitting(true); + setTestFeedback(null); + + const payload = { + provider: selectedPreset.id, + api_key: values.api_key.trim(), + base_url: values.base_url?.trim() || undefined, + model: values.model?.trim() || undefined, + supports_vision: Boolean(values.supports_vision), + }; + + const testResult = await testLLMConfig(payload); + setTestFeedback({ + success: testResult.success, + message: testResult.message, + responseTimeMs: testResult.response_time_ms, + }); + + if (!testResult.success) { + message.error(testResult.message); + return; + } + + const configToken = values.config_token?.trim() || undefined; + const saveResult = await configureLLM(payload, configToken); + if (saveResult.success) { + message.success(saveResult.message); + setSavedSummary({ + providerName: selectedPreset.name, + model: payload.model || selectedPreset.default_model || '-', + supportsVision: payload.supports_vision, + }); + await onConfigured(); + setStep(2); + } + } catch (error: unknown) { + if (error && typeof error === 'object' && 'errorFields' in error) { + return; + } + let detail = '测试或保存配置失败'; + if (error && typeof error === 'object' && 'response' in error) { + const axiosError = error as { response?: { data?: { detail?: string } } }; + if (axiosError.response?.data?.detail) { + detail = axiosError.response.data.detail; + } + } + setTestFeedback({ success: false, message: detail }); + message.error(detail); + } finally { + setSubmitting(false); + } + }; + + const handleSaveWithoutTest = async () => { + if (!selectedPreset) return; + try { + const values = await form.validateFields(); + setSavingDirect(true); + const payload = { + provider: selectedPreset.id, + api_key: values.api_key.trim(), + base_url: values.base_url?.trim() || undefined, + model: values.model?.trim() || undefined, + supports_vision: Boolean(values.supports_vision), + }; + const configToken = values.config_token?.trim() || undefined; + const saveResult = await configureLLM(payload, configToken); + if (saveResult.success) { + message.success(saveResult.message); + setSavedSummary({ + providerName: selectedPreset.name, + model: payload.model || selectedPreset.default_model || '-', + supportsVision: payload.supports_vision, + }); + await onConfigured(); + setStep(2); + } + } catch (error: unknown) { + if (error && typeof error === 'object' && 'errorFields' in error) { + return; + } + if (error && typeof error === 'object' && 'response' in error) { + const axiosError = error as { response?: { data?: { detail?: string } } }; + if (axiosError.response?.data?.detail) { + message.error(axiosError.response.data.detail); + return; + } + } + message.error('保存配置失败'); + } finally { + setSavingDirect(false); + } + }; + + const renderPresetGrid = (items: ProviderPresetInfo[]) => ( +
+ {items.map((preset) => { + const isSelected = preset.id === selectedPresetId; + return ( + + ); + })} +
+ ); + + const isCustom = selectedPreset?.category === 'custom'; + + return ( + +
+ + +
+ + 欢迎使用发票管理系统 · 3 步快速开始 + + + 配置视觉大模型可与本地 OCR 双源交叉核对,也可直接跳过先用纯本地 OCR + +
+
+ + +
+ + + + {/* Step 1: Choose Provider */} + {step === 0 && ( +
+ {recommendedPresets.length > 0 && ( +
+ + 推荐服务 + + {renderPresetGrid(recommendedPresets)} +
+ )} + + {domesticPresets.length > 0 && ( +
+ + 国内常用(无需代理) + + {renderPresetGrid(domesticPresets)} +
+ )} + + {globalAndCustomPresets.length > 0 && ( +
+ + 海外服务与自定义聚合端点 + + {renderPresetGrid(globalAndCustomPresets)} +
+ )} + +
+ +
+
+ )} + + {/* Step 2: Fill API Key, Test & Save */} + {step === 1 && selectedPreset && ( +
+
+ + + {selectedPreset.name} + {selectedPreset.docs_url && ( + + 获取 API Key + + )} + + + {selectedPreset.supports_vision ? '默认支持看图' : '默认纯文本'} + +
+ + + + } + /> + + +
+ + + + + + ({ + label: ( + + {m.name} + {m.vision && } + + ), + value: m.id, + }))} + /> + +
+ + + + + + + + + + {testFeedback && ( + + )} + +
+ + + + + +
+ +
+ )} + + {/* Step 3: Done */} + {step === 2 && ( + } + title="模型服务已就绪" + subTitle={ + savedSummary + ? `已启用 ${savedSummary.providerName}(模型:${savedSummary.model},视觉看图:${savedSummary.supportsVision ? '已开启' : '未开启'})` + : '现在可以上传发票体验 OCR + LLM 双源比对' + } + style={{ padding: '12px 0' }} + extra={[ + , + , + ]} + /> + )} +
+ ); +} diff --git a/frontend/src/components/layout/MainLayout.module.css b/frontend/src/components/layout/MainLayout.module.css index 5359689..a5a61d3 100644 --- a/frontend/src/components/layout/MainLayout.module.css +++ b/frontend/src/components/layout/MainLayout.module.css @@ -8,6 +8,7 @@ /* Main Content Area */ .mainContent { flex: 1; + min-width: 0; margin-left: var(--sidebar-width); min-height: 100vh; display: flex; @@ -17,6 +18,7 @@ /* Content Wrapper */ .contentWrapper { flex: 1; + min-width: 0; padding: var(--content-padding-y) var(--content-padding-x); } diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 6894e47..36786ee 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -7,6 +7,7 @@ import type { UploadResponse, LLMStatusResponse, LLMConfigRequest, + LLMConfigTestRequest, LLMConfigResponse, LLMTestResponse, ModelsResponse, @@ -190,9 +191,9 @@ export const testLLMConnection = async (): Promise => { return response.data; }; -// Test LLM config before saving (uses actual provider client library) +// Test LLM config before saving export const testLLMConfig = async ( - config: { provider: string; api_key: string; model?: string; base_url?: string } + config: LLMConfigTestRequest ): Promise<{ success: boolean; message: string; response_time_ms?: number }> => { const response = await api.post('/settings/llm/test-config', config); return response.data; diff --git a/frontend/src/styles/global.css b/frontend/src/styles/global.css index c0b6967..ecf79ef 100644 --- a/frontend/src/styles/global.css +++ b/frontend/src/styles/global.css @@ -1,6 +1,3 @@ -/* Google Fonts Import */ -@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap'); - /* Global Reset & Base Styles */ *, *::before, diff --git a/frontend/src/styles/variables.css b/frontend/src/styles/variables.css index 35e51e4..d53c0c1 100644 --- a/frontend/src/styles/variables.css +++ b/frontend/src/styles/variables.css @@ -22,9 +22,9 @@ --info: #3B82F6; --info-dark: #2563EB; - /* Typography - Font Families */ - --font-primary: 'Space Grotesk', -apple-system, BlinkMacSystemFont, sans-serif; - --font-secondary: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; + /* Typography - System Font Families (zero external font requests) */ + --font-primary: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; + --font-secondary: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; /* Typography - Font Sizes */ --font-size-xs: 12px; diff --git a/frontend/src/types/invoice.ts b/frontend/src/types/invoice.ts index ba1e4d0..af2d8f1 100644 --- a/frontend/src/types/invoice.ts +++ b/frontend/src/types/invoice.ts @@ -115,20 +115,47 @@ export interface UploadResponse { } // LLM Configuration Types +export interface PresetModelInfo { + id: string; + name: string; + vision: boolean; +} + +export interface ProviderPresetInfo { + id: string; + name: string; + category: 'recommended' | 'domestic' | 'global' | 'custom' | string; + protocol: 'openai_compatible' | 'anthropic' | string; + base_url: string; + docs_url: string; + default_model: string; + models: PresetModelInfo[]; + supports_vision: boolean; + recommended: boolean; + description?: string; +} + export interface LLMProviderInfo { name: string; display_name: string; is_configured: boolean; model: string | null; base_url: string | null; + category?: string | null; + supports_vision?: boolean | null; + docs_url?: string | null; } export interface LLMStatusResponse { is_configured: boolean; active_provider: string | null; active_provider_display: string | null; + active_model?: string | null; + active_base_url?: string | null; + supports_vision?: boolean; configured_providers: string[]; available_providers: LLMProviderInfo[]; + presets?: ProviderPresetInfo[]; } export interface LLMConfigRequest { @@ -136,6 +163,15 @@ export interface LLMConfigRequest { api_key: string; model?: string; base_url?: string; + supports_vision?: boolean; +} + +export interface LLMConfigTestRequest { + provider: string; + api_key: string; + model?: string; + base_url?: string; + supports_vision?: boolean; } export interface LLMConfigResponse { From 52d2616f8483ba3d477821972aaa7189160dd8d2 Mon Sep 17 00:00:00 2001 From: stone16 <12712299+stone16@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:20:04 +0800 Subject: [PATCH 4/4] fix(core,settings,ui): address CodeRabbit security, protocol, and race-condition review findings --- backend/app/config.py | 2 +- backend/app/routers/settings.py | 56 ++-- backend/app/services/llm_service.py | 10 +- backend/app/services/model_registry.py | 31 ++- backend/tests/test_providers_and_settings.py | 244 +++++++++++++++++- frontend/src/components/LLMConfigModal.tsx | 61 +++-- frontend/src/components/OnboardingGuide.tsx | 67 +++-- frontend/src/services/api.ts | 7 +- .../src/invoice_core/parsers/vision.py | 27 +- packages/invoice-core/tests/test_vision.py | 93 ++++++- 10 files changed, 511 insertions(+), 87 deletions(-) diff --git a/backend/app/config.py b/backend/app/config.py index 040ea85..b33dec0 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -165,7 +165,7 @@ def is_provider_configured(self, provider_id: str) -> bool: """Return True if the specified provider has required credentials configured.""" canonical = resolve_provider_id(provider_id) api_key, _model, base_url = self.get_provider_credentials(canonical) - if not api_key: + if not api_key.strip(): return False if canonical == "openai_compatible": return bool(base_url.strip()) diff --git a/backend/app/routers/settings.py b/backend/app/routers/settings.py index 6ba4a3d..fc8ebc9 100644 --- a/backend/app/routers/settings.py +++ b/backend/app/routers/settings.py @@ -18,6 +18,7 @@ ANTHROPIC_API_VERSION, PROVIDERS, _get_max_tokens_param, + _get_temperature_param, build_anthropic_messages_url, extract_anthropic_text, get_llm_service, @@ -301,6 +302,8 @@ async def configure_llm( raise HTTPException(status_code=400, detail="自定义服务必须填写 API 地址 (Base URL)") model = (request.model or "").strip() or preset.default_model + if not model: + raise HTTPException(status_code=400, detail="请填写模型名称") try: key_name, model_name, base_url_name = PROVIDER_ENV_VARS[provider] @@ -402,34 +405,36 @@ def _format_test_error(exc: Exception) -> str: if isinstance(exc, httpx.HTTPStatusError): status = exc.response.status_code body = exc.response.text or "" + body_lower = body.lower() if status == 401: return "API密钥无效或未授权" if status == 403: return "API密钥权限不足或访问被拒绝" + if "model" in body_lower and ("not found" in body_lower or "does not exist" in body_lower): + return "模型不存在,请检查模型名称是否正确" + if "= 400: - body_lower = (response.text or "").lower() - if "unsupported parameter" in body_lower or "responses" in body_lower: - responses_url = f"{base_url.strip().rstrip('/')}/responses" - resp2 = await client.post( - responses_url, - json={ - "model": model, - "input": [{"role": "user", "content": "Reply with exactly: OK"}], - }, - headers=headers, - ) - resp2.raise_for_status() - data2 = resp2.json() - return str(data2.get("output_text") or "OK").strip() - response.raise_for_status() - + response.raise_for_status() data = response.json() if not isinstance(data, dict): raise RuntimeError("API返回了非JSON对象响应") @@ -508,8 +497,17 @@ async def _test_anthropic_async( @router.post("/llm/test-config", response_model=ConfigTestResponse) -async def test_llm_config(request: ConfigTestRequest): +async def test_llm_config( + request: ConfigTestRequest, + x_llm_config_token: Optional[str] = Header(default=None, alias="X-LLM-Config-Token"), + authorization: Optional[str] = Header(default=None), +): """Test LLM configuration before saving using async httpx requests.""" + _require_llm_config_token( + app_config.get_settings().llm_config_token, + x_llm_config_token, + authorization, + ) _validate_no_newlines(request.provider, request.api_key, request.model, request.base_url) provider = resolve_provider_id(request.provider) diff --git a/backend/app/services/llm_service.py b/backend/app/services/llm_service.py index ed96d38..cea23b6 100644 --- a/backend/app/services/llm_service.py +++ b/backend/app/services/llm_service.py @@ -34,6 +34,7 @@ build_chat_completions_url, build_vision_payload, extract_chat_completion_text, + supports_temperature, uses_max_completion_tokens, ) @@ -107,6 +108,13 @@ def _get_max_tokens_param(model_name: str, value: int) -> dict[str, int]: return {"max_tokens": value} +def _get_temperature_param(model_name: str, value: float = 0.1) -> dict[str, float]: + """Return ``temperature`` only for models that accept custom sampling temperature.""" + if supports_temperature(model_name): + return {"temperature": value} + return {} + + def resolve_supports_vision( provider_id: str, model: str, @@ -239,7 +247,7 @@ def chat_completion(self, system_prompt: str, user_prompt: str) -> str: {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ], - "temperature": 0.1, + **_get_temperature_param(model, 0.1), **_get_max_tokens_param(model, 1000), } with httpx.Client(timeout=self.timeout) as client: diff --git a/backend/app/services/model_registry.py b/backend/app/services/model_registry.py index 43e046a..6b34707 100644 --- a/backend/app/services/model_registry.py +++ b/backend/app/services/model_registry.py @@ -33,10 +33,11 @@ weakref.WeakKeyDictionary() ) -# Providers that benefit from dynamic OpenRouter catalog lookups +# Providers that benefit from dynamic OpenRouter catalog lookups. +# Anthropic native endpoints use dated/native IDs (e.g. claude-sonnet-4-20250514) that differ from +# OpenRouter slugs (e.g. anthropic/claude-haiku-4.5), so native "anthropic" stays on verified presets. _OPENROUTER_PREFIXES: dict[str, tuple[str, ...]] = { "openai": ("openai/",), - "anthropic": ("anthropic/",), "google": ("google/",), } @@ -81,15 +82,29 @@ def _read_cache(now: float, *, force_refresh: bool) -> Optional[list[dict[str, A async def _fetch_models_from_openrouter_async() -> list[dict[str, Any]]: - """Fetch model catalog from OpenRouter asynchronously without blocking the event loop.""" - try: + """Fetch and validate model catalog from OpenRouter within a total deadline.""" + + async def _do_fetch() -> list[dict[str, Any]]: async with httpx.AsyncClient(timeout=OPENROUTER_TIMEOUT_SECONDS) as client: response = await client.get(OPENROUTER_MODELS_URL) response.raise_for_status() payload = response.json() + if not isinstance(payload, dict): + return [] data = payload.get("data", []) - return data if isinstance(data, list) else [] - except httpx.TimeoutException: + if not isinstance(data, list): + return [] + return [ + item + for item in data + if isinstance(item, dict) + and isinstance(item.get("id"), str) + and item["id"].strip() + ] + + try: + return await asyncio.wait_for(_do_fetch(), timeout=OPENROUTER_TIMEOUT_SECONDS) + except (httpx.TimeoutException, asyncio.TimeoutError): logger.warning("OpenRouter models API request timed out after %.1fs", OPENROUTER_TIMEOUT_SECONDS) return [] except httpx.HTTPStatusError as e: @@ -162,8 +177,8 @@ async def get_models_with_fallback_async( """Return ``(models, source)`` asynchronously, falling back cleanly to static presets.""" canonical = resolve_provider_id(provider) - # Domestic & custom providers use their native static preset lists directly - if canonical not in ("openrouter", "openai", "anthropic", "google"): + # Domestic, custom, and native Anthropic providers use verified static preset lists directly + if canonical not in ("openrouter", "openai", "google"): return _static_preset_models(canonical, vision_only=vision_only), "fallback" catalog = await get_available_models_async() diff --git a/backend/tests/test_providers_and_settings.py b/backend/tests/test_providers_and_settings.py index ebe85d2..c868330 100644 --- a/backend/tests/test_providers_and_settings.py +++ b/backend/tests/test_providers_and_settings.py @@ -546,7 +546,6 @@ async def _slow_get(self, url, **kwargs): results = await asyncio.gather( model_registry.get_models_with_fallback_async("openrouter"), model_registry.get_models_with_fallback_async("openai"), - model_registry.get_models_with_fallback_async("anthropic"), model_registry.get_models_with_fallback_async("google"), model_registry.get_models_with_fallback_async("openrouter"), ) @@ -554,8 +553,247 @@ async def _slow_get(self, url, **kwargs): ok_fetches, ok_sources = asyncio.run(_run_single_flight(fail=False)) assert ok_fetches == 1 - assert ok_sources == ["openrouter"] * 5 + assert ok_sources == ["openrouter"] * 4 fail_fetches, fail_sources = asyncio.run(_run_single_flight(fail=True)) assert fail_fetches == 1 - assert fail_sources == ["fallback"] * 5 + assert fail_sources == ["fallback"] * 4 + + +def test_anthropic_models_stay_on_verified_native_ids_while_openrouter_keeps_slugs(monkeypatch): + """Native anthropic endpoint must NOT receive OpenRouter slugs like claude-haiku-4.5.""" + fetch_count = 0 + + async def _fake_get(self, url, **kwargs): + nonlocal fetch_count + fetch_count += 1 + return httpx.Response( + 200, + json={ + "data": [ + { + "id": "anthropic/claude-haiku-4.5", + "name": "Claude Haiku 4.5 (OpenRouter)", + "architecture": {"input_modalities": ["text", "image"]}, + }, + { + "id": "openai/gpt-4o-mini", + "name": "GPT-4o Mini", + "architecture": {"input_modalities": ["text", "image"]}, + }, + ] + }, + request=httpx.Request("GET", url), + ) + + monkeypatch.setattr(httpx.AsyncClient, "get", _fake_get) + client = _make_client() + + # Native anthropic uses verified static preset IDs without calling OpenRouter + r_anth = client.get("/api/settings/models?provider=anthropic") + assert r_anth.status_code == 200 + body_anth = r_anth.json() + assert body_anth["source"] == "fallback" + assert fetch_count == 0 + anth_ids = [m["id"] for m in body_anth["models"]] + assert "claude-sonnet-4-20250514" in anth_ids + assert "claude-haiku-4.5" not in anth_ids + + # OpenRouter still exposes the full anthropic/claude-haiku-4.5 OpenRouter ID + r_or = client.get("/api/settings/models?provider=openrouter") + assert r_or.status_code == 200 + body_or = r_or.json() + assert body_or["source"] == "openrouter" + assert any(m["id"] == "anthropic/claude-haiku-4.5" for m in body_or["models"]) + + +def test_models_catalog_filters_invalid_entries_and_falls_back(monkeypatch): + """Malformed catalog entries must be filtered before caching; empty validated list falls back.""" + async def _fake_get_bad(self, url, **kwargs): + return httpx.Response( + 200, + json={"data": ["bad-entry", {"name": "missing-id"}, {"id": " "}]}, + request=httpx.Request("GET", url), + ) + + monkeypatch.setattr(httpx.AsyncClient, "get", _fake_get_bad) + client = _make_client() + + resp = client.get("/api/settings/models?provider=openrouter") + assert resp.status_code == 200 + body = resp.json() + assert body["source"] == "fallback" + assert len(body["models"]) == len(PRESET_BY_ID["openrouter"].models) + + +def test_configure_rejects_blank_model_for_openai_compatible(tmp_path: Path, monkeypatch): + """Saving openai_compatible without a non-empty model must fail with HTTP 400.""" + env_file = tmp_path / ".env" + monkeypatch.setenv("INVOICE_ENV_FILE", str(env_file)) + client = _make_client() + + resp = client.post( + "/api/settings/llm/configure", + json={ + "provider": "openai_compatible", + "api_key": "sk-custom-key", + "base_url": "https://gateway.example.com/v1", + "model": " ", + }, + ) + assert resp.status_code == 400 + assert not env_file.exists() + + +def test_test_config_enforces_llm_config_token(tmp_path: Path, monkeypatch): + """When LLM_CONFIG_TOKEN is set, /llm/test-config must require matching token just like /configure.""" + monkeypatch.setenv("LLM_CONFIG_TOKEN", "admin-secret-token") + config_module.clear_settings_cache() + + called = 0 + + async def _fake_async_post(self, url, *, json=None, headers=None, **kwargs): + nonlocal called + called += 1 + return httpx.Response( + 200, + json={"choices": [{"message": {"content": "OK"}}]}, + request=httpx.Request("POST", url), + ) + + monkeypatch.setattr(httpx.AsyncClient, "post", _fake_async_post) + client = _make_client() + payload = {"provider": "openai", "api_key": "sk-test", "model": "gpt-4o-mini"} + + # Missing token -> 401 and no outbound request made + r_missing = client.post("/api/settings/llm/test-config", json=payload) + assert r_missing.status_code == 401 + assert called == 0 + + # Wrong token -> 401 and no outbound request made + r_wrong = client.post( + "/api/settings/llm/test-config", + json=payload, + headers={"X-LLM-Config-Token": "wrong"}, + ) + assert r_wrong.status_code == 401 + assert called == 0 + + # Correct token -> 200 and outbound probe executes + r_ok = client.post( + "/api/settings/llm/test-config", + json=payload, + headers={"X-LLM-Config-Token": "admin-secret-token"}, + ) + assert r_ok.status_code == 200 + assert r_ok.json()["success"] is True + assert called == 1 + + +def test_test_config_no_responses_fallback_and_omits_temperature_for_gpt5(monkeypatch): + """test-config must stay on /chat/completions, omit temperature for gpt-5, and reject empty content.""" + captured: list[dict[str, Any]] = [] + + async def _fake_post_gpt5_ok(self, url, *, json=None, headers=None, **kwargs): + captured.append({"url": url, "json": json}) + return httpx.Response( + 200, + json={"choices": [{"message": {"content": "OK"}}]}, + request=httpx.Request("POST", url), + ) + + monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post_gpt5_ok) + client = _make_client() + + r_ok = client.post( + "/api/settings/llm/test-config", + json={"provider": "openai", "api_key": "sk-test", "model": "gpt-5-mini"}, + ) + assert r_ok.status_code == 200 + assert r_ok.json()["success"] is True + assert len(captured) == 1 + assert captured[0]["url"].endswith("/chat/completions") + assert "temperature" not in captured[0]["json"] + assert captured[0]["json"]["max_completion_tokens"] == 16 + + # HTTP 400 mentioning "responses" must fail directly without falling back to /responses + urls_called: list[str] = [] + + async def _fake_post_responses_only(self, url, *, json=None, headers=None, **kwargs): + urls_called.append(url) + return httpx.Response( + 400, + text='{"error":{"message":"use /responses endpoint instead"}}', + request=httpx.Request("POST", url), + ) + + monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post_responses_only) + r_fail = client.post( + "/api/settings/llm/test-config", + json={"provider": "openai", "api_key": "sk-test", "model": "gpt-5-mini"}, + ) + assert r_fail.status_code == 200 + assert r_fail.json()["success"] is False + assert urls_called == ["https://api.openai.com/v1/chat/completions"] + + # Empty completion content must NOT synthesize "OK" + async def _fake_post_empty_content(self, url, *, json=None, headers=None, **kwargs): + return httpx.Response( + 200, + json={"choices": [{"message": {"content": ""}}]}, + request=httpx.Request("POST", url), + ) + + monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post_empty_content) + r_empty = client.post( + "/api/settings/llm/test-config", + json={"provider": "openai", "api_key": "sk-test", "model": "gpt-4o-mini"}, + ) + assert r_empty.status_code == 200 + assert r_empty.json()["success"] is False + + +def test_gpt5_chat_completion_omits_temperature_and_whitespace_key_is_unconfigured( + tmp_path: Path, + monkeypatch, +): + """OpenAICompatibleProvider.chat_completion omits temperature for gpt-5; whitespace key is unconfigured.""" + monkeypatch.setenv("OPENAI_API_KEY", " ") + config_module.clear_settings_cache() + assert config_module.get_settings().is_provider_configured("openai") is False + + # 404 with model-not-found body reports model error rather than generic URL error + req = httpx.Request("POST", "https://api.openai.com/v1/chat/completions") + resp_404_model = httpx.Response( + 404, + text='{"error":{"message":"The model `bad-model` does not exist"}}', + request=req, + ) + err_msg = settings_router._format_test_error( + httpx.HTTPStatusError("404", request=req, response=resp_404_model) + ) + assert "模型不存在" in err_msg + + # Verify runtime chat_completion payload for gpt-5-mini omits temperature + monkeypatch.setenv("OPENAI_API_KEY", "sk-real-key") + monkeypatch.setenv("OPENAI_MODEL", "gpt-5-mini") + monkeypatch.setenv("LLM_PROVIDER", "openai") + config_module.clear_settings_cache() + reset_llm_service() + + sent_payloads: list[dict[str, Any]] = [] + + def _fake_sync_post(self, url, *, json=None, headers=None, **kwargs): + sent_payloads.append(json) + return httpx.Response( + 200, + json={"choices": [{"message": {"content": "OK"}}]}, + request=httpx.Request("POST", url), + ) + + monkeypatch.setattr(httpx.Client, "post", _fake_sync_post) + reply = get_llm_service().active_provider.chat_completion("sys", "usr") + assert reply == "OK" + assert len(sent_payloads) == 1 + assert "temperature" not in sent_payloads[0] + assert sent_payloads[0]["max_completion_tokens"] == 1000 diff --git a/frontend/src/components/LLMConfigModal.tsx b/frontend/src/components/LLMConfigModal.tsx index 73f4fa0..fd67f87 100644 --- a/frontend/src/components/LLMConfigModal.tsx +++ b/frontend/src/components/LLMConfigModal.tsx @@ -55,7 +55,8 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { const [modelsLoading, setModelsLoading] = useState(false); const [modelsSource, setModelsSource] = useState<'openrouter' | 'fallback'>('fallback'); const [testFeedback, setTestFeedback] = useState(null); - const latestProviderRef = useRef(''); + const modelsRequestSeqRef = useRef(0); + const testRequestSeqRef = useRef(0); const [form] = Form.useForm(); const presets: ProviderPresetInfo[] = useMemo(() => status?.presets || [], [status]); @@ -112,13 +113,14 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { }, [presets, recommendedPresets]); const enrichModelsAsync = async (providerId: string, presetModels: ModelInfo[]) => { + const reqId = ++modelsRequestSeqRef.current; setModels(presetModels); setModelsSource('fallback'); setModelsLoading(true); try { const response = await getAvailableModels(providerId, false); - // Guard against race conditions if the user already switched providers - if (latestProviderRef.current !== providerId) { + // Guard against stale async callbacks from an earlier request + if (modelsRequestSeqRef.current !== reqId) { return; } if (response.models && response.models.length > 0) { @@ -126,20 +128,21 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { setModelsSource(response.source); } } catch (error) { - if (latestProviderRef.current === providerId) { + if (modelsRequestSeqRef.current === reqId) { setModels(presetModels); setModelsSource('fallback'); } console.error('Failed to fetch models:', error); } finally { - if (latestProviderRef.current === providerId) { + if (modelsRequestSeqRef.current === reqId) { setModelsLoading(false); } } }; const applyPresetToForm = (providerId: string, statusData: LLMStatusResponse) => { - latestProviderRef.current = providerId; + testRequestSeqRef.current += 1; + setTestingConfig(false); setSelectedProvider(providerId); setTestFeedback(null); @@ -204,9 +207,16 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { useEffect(() => { if (open) { + modelsRequestSeqRef.current += 1; + testRequestSeqRef.current += 1; + setTestingConfig(false); setTestFeedback(null); form.resetFields(); void fetchStatus(); + } else { + modelsRequestSeqRef.current += 1; + testRequestSeqRef.current += 1; + setTestingConfig(false); } }, [open]); @@ -274,16 +284,24 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { return; } + const reqId = ++testRequestSeqRef.current; setTestingConfig(true); setTestFeedback(null); try { - const result = await testLLMConfig({ - provider: values.provider, - api_key: values.api_key.trim(), - model: values.model?.trim() || undefined, - base_url: values.base_url?.trim() || undefined, - supports_vision: Boolean(values.supports_vision), - }); + const configToken = values.config_token?.trim() || undefined; + const result = await testLLMConfig( + { + provider: values.provider, + api_key: values.api_key.trim(), + model: values.model?.trim() || undefined, + base_url: values.base_url?.trim() || undefined, + supports_vision: Boolean(values.supports_vision), + }, + configToken + ); + if (testRequestSeqRef.current !== reqId) { + return; + } setTestFeedback({ success: result.success, message: result.message, @@ -299,6 +317,9 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { message.error(result.message); } } catch (error: unknown) { + if (testRequestSeqRef.current !== reqId) { + return; + } let detail = '配置测试失败'; if (error && typeof error === 'object' && 'response' in error) { const axiosError = error as { response?: { data?: { detail?: string } } }; @@ -309,7 +330,9 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { setTestFeedback({ success: false, message: detail }); message.error(detail); } finally { - setTestingConfig(false); + if (testRequestSeqRef.current === reqId) { + setTestingConfig(false); + } } }; @@ -414,7 +437,15 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) { -
+ { + testRequestSeqRef.current += 1; + setTestingConfig(false); + setTestFeedback(null); + }} + > (null); + const actionSeqRef = useRef(0); const [form] = Form.useForm(); const recommendedPresets = useMemo( @@ -84,8 +85,16 @@ export default function OnboardingGuide({ [presets, selectedPresetId] ); + const goToStepOne = () => { + if (submitting || savingDirect) return; + actionSeqRef.current += 1; + setTestFeedback(null); + setStep(0); + }; + const goToStepTwo = (presetId: string) => { const preset = presets.find((p) => p.id === presetId); + actionSeqRef.current += 1; setSelectedPresetId(presetId); setTestFeedback(null); form.setFieldsValue({ @@ -106,9 +115,11 @@ export default function OnboardingGuide({ }; const handleTestAndSave = async () => { - if (!selectedPreset) return; + if (!selectedPreset || submitting || savingDirect) return; + const seq = ++actionSeqRef.current; try { const values = await form.validateFields(); + if (actionSeqRef.current !== seq) return; setSubmitting(true); setTestFeedback(null); @@ -119,8 +130,10 @@ export default function OnboardingGuide({ model: values.model?.trim() || undefined, supports_vision: Boolean(values.supports_vision), }; + const configToken = values.config_token?.trim() || undefined; - const testResult = await testLLMConfig(payload); + const testResult = await testLLMConfig(payload, configToken); + if (actionSeqRef.current !== seq) return; setTestFeedback({ success: testResult.success, message: testResult.message, @@ -132,8 +145,8 @@ export default function OnboardingGuide({ return; } - const configToken = values.config_token?.trim() || undefined; const saveResult = await configureLLM(payload, configToken); + if (actionSeqRef.current !== seq) return; if (saveResult.success) { message.success(saveResult.message); setSavedSummary({ @@ -142,9 +155,11 @@ export default function OnboardingGuide({ supportsVision: payload.supports_vision, }); await onConfigured(); + if (actionSeqRef.current !== seq) return; setStep(2); } } catch (error: unknown) { + if (actionSeqRef.current !== seq) return; if (error && typeof error === 'object' && 'errorFields' in error) { return; } @@ -158,14 +173,18 @@ export default function OnboardingGuide({ setTestFeedback({ success: false, message: detail }); message.error(detail); } finally { - setSubmitting(false); + if (actionSeqRef.current === seq) { + setSubmitting(false); + } } }; const handleSaveWithoutTest = async () => { - if (!selectedPreset) return; + if (!selectedPreset || submitting || savingDirect) return; + const seq = ++actionSeqRef.current; try { const values = await form.validateFields(); + if (actionSeqRef.current !== seq) return; setSavingDirect(true); const payload = { provider: selectedPreset.id, @@ -176,6 +195,7 @@ export default function OnboardingGuide({ }; const configToken = values.config_token?.trim() || undefined; const saveResult = await configureLLM(payload, configToken); + if (actionSeqRef.current !== seq) return; if (saveResult.success) { message.success(saveResult.message); setSavedSummary({ @@ -184,9 +204,11 @@ export default function OnboardingGuide({ supportsVision: payload.supports_vision, }); await onConfigured(); + if (actionSeqRef.current !== seq) return; setStep(2); } } catch (error: unknown) { + if (actionSeqRef.current !== seq) return; if (error && typeof error === 'object' && 'errorFields' in error) { return; } @@ -199,7 +221,9 @@ export default function OnboardingGuide({ } message.error('保存配置失败'); } finally { - setSavingDirect(false); + if (actionSeqRef.current === seq) { + setSavingDirect(false); + } } }; @@ -292,12 +316,15 @@ export default function OnboardingGuide({
- + {step !== 2 && ( + + )} } - onClick={() => setStep(0)} + onClick={goToStepOne} + disabled={submitting || savingDirect} style={{ padding: 0 }} > 返回重选 @@ -485,15 +513,22 @@ export default function OnboardingGuide({ )}
- + -