initial commit
This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
Pluggable local AI provider layer for AI Reports.
|
||||
|
||||
Supports:
|
||||
- none (default): deterministic rule-based summaries only; raises ProviderUnavailable.
|
||||
- ollama: POST {base}/api/chat with format="json", stream=False, temperature=0.1.
|
||||
- openai_compatible: POST {base}/v1/chat/completions with response_format={"type": "json_object"}, temperature=0.1.
|
||||
|
||||
No hosted cloud provider is configured or required. Prompts and responses are never
|
||||
logged at INFO level.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
import httpx
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.config import Settings, settings as app_settings
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
|
||||
class ProviderUnavailable(Exception):
|
||||
"""Raised when no AI provider is enabled or the provider cannot be reached."""
|
||||
|
||||
|
||||
class AIProvider(ABC):
|
||||
provider_name: str = "none"
|
||||
model_name: str = ""
|
||||
|
||||
@abstractmethod
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Call the model and return a parsed JSON object."""
|
||||
|
||||
@abstractmethod
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
"""Quick reachability check that never blocks longer than `timeout` seconds."""
|
||||
|
||||
|
||||
class NoneProvider(AIProvider):
|
||||
provider_name = "none"
|
||||
model_name = ""
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
raise ProviderUnavailable("AI provider is disabled (AI_PROVIDER=none).")
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class OllamaProvider(AIProvider):
|
||||
provider_name = "ollama"
|
||||
|
||||
def __init__(self, base_url: str, model: str, timeout_seconds: int = 300) -> None:
|
||||
self.base_url = (base_url or "http://localhost:11434").rstrip("/")
|
||||
self.model_name = (model or "").strip()
|
||||
self.timeout_seconds = max(1, int(timeout_seconds or 300))
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
if not self.model_name:
|
||||
raise ProviderUnavailable("AI_MODEL is not configured for Ollama.")
|
||||
url = f"{self.base_url}/api/chat"
|
||||
payload = {
|
||||
"model": self.model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": json.dumps(user_json, ensure_ascii=False)},
|
||||
],
|
||||
"format": "json",
|
||||
"stream": False,
|
||||
"options": {"temperature": 0.1},
|
||||
}
|
||||
try:
|
||||
with httpx.Client(timeout=float(self.timeout_seconds)) as client:
|
||||
resp = client.post(url, json=payload)
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
except httpx.TimeoutException as exc:
|
||||
raise ProviderUnavailable(f"AI engine request timed out after {self.timeout_seconds}s.") from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise ProviderUnavailable(f"AI engine HTTP error: {exc.__class__.__name__}") from exc
|
||||
except ValueError as exc:
|
||||
raise ValueError("AI engine returned invalid JSON envelope.") from exc
|
||||
|
||||
content = (body.get("message") or {}).get("content")
|
||||
if isinstance(content, dict):
|
||||
return content
|
||||
if not isinstance(content, str) or not content.strip():
|
||||
raise ValueError("Ollama returned empty message content.")
|
||||
parsed = json.loads(content)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("Ollama JSON response must be an object.")
|
||||
return parsed
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
cap = min(float(timeout), 3.0)
|
||||
url = f"{self.base_url}/api/tags"
|
||||
try:
|
||||
with httpx.Client(timeout=cap) as client:
|
||||
resp = client.get(url)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class OpenAICompatibleProvider(AIProvider):
|
||||
provider_name = "openai_compatible"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
model: str,
|
||||
api_key: str = "",
|
||||
timeout_seconds: int = 25,
|
||||
) -> None:
|
||||
raw = (base_url or "http://localhost:8001").rstrip("/")
|
||||
self.base_url = raw[:-3] if raw.endswith("/v1") else raw
|
||||
self.model_name = (model or "").strip()
|
||||
self.api_key = (api_key or "").strip()
|
||||
self.timeout_seconds = max(1, int(timeout_seconds or 25))
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.api_key:
|
||||
headers["Authorization"] = f"Bearer {self.api_key}"
|
||||
return headers
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
if not self.model_name:
|
||||
raise ProviderUnavailable("AI_MODEL is not configured for OpenAI-compatible provider.")
|
||||
url = f"{self.base_url}/v1/chat/completions"
|
||||
payload = {
|
||||
"model": self.model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": json.dumps(user_json, ensure_ascii=False)},
|
||||
],
|
||||
"response_format": {"type": "json_object"},
|
||||
"temperature": 0.1,
|
||||
}
|
||||
try:
|
||||
with httpx.Client(timeout=float(self.timeout_seconds)) as client:
|
||||
resp = client.post(url, headers=self._headers(), json=payload)
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
except httpx.TimeoutException as exc:
|
||||
raise ProviderUnavailable(
|
||||
f"OpenAI-compatible request timed out after {self.timeout_seconds}s."
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise ProviderUnavailable(f"OpenAI-compatible HTTP error: {exc.__class__.__name__}") from exc
|
||||
except ValueError as exc:
|
||||
raise ValueError("OpenAI-compatible server returned invalid JSON envelope.") from exc
|
||||
|
||||
choices = body.get("choices") or []
|
||||
if not choices or not isinstance(choices, list):
|
||||
raise ValueError("OpenAI-compatible response contained no choices.")
|
||||
content = (choices[0].get("message") or {}).get("content")
|
||||
if isinstance(content, dict):
|
||||
return content
|
||||
if not isinstance(content, str) or not content.strip():
|
||||
raise ValueError("OpenAI-compatible response contained empty content.")
|
||||
parsed = json.loads(content)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("OpenAI-compatible JSON response must be an object.")
|
||||
return parsed
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
cap = min(float(timeout), 3.0)
|
||||
url = f"{self.base_url}/v1/models"
|
||||
try:
|
||||
with httpx.Client(timeout=cap) as client:
|
||||
resp = client.get(url, headers=self._headers())
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def get_ai_provider(cfg: Optional[Settings] = None) -> AIProvider:
|
||||
conf = cfg or app_settings
|
||||
name = (conf.AI_PROVIDER or "none").strip().lower()
|
||||
if name == "ollama":
|
||||
return OllamaProvider(
|
||||
base_url=conf.AI_BASE_URL,
|
||||
model=conf.AI_MODEL,
|
||||
timeout_seconds=conf.AI_TIMEOUT_SECONDS,
|
||||
)
|
||||
if name == "openai_compatible":
|
||||
return OpenAICompatibleProvider(
|
||||
base_url=conf.AI_BASE_URL,
|
||||
model=conf.AI_MODEL,
|
||||
api_key=conf.AI_API_KEY,
|
||||
timeout_seconds=conf.AI_TIMEOUT_SECONDS,
|
||||
)
|
||||
return NoneProvider()
|
||||
|
||||
|
||||
def get_ai_status(
|
||||
db: Session,
|
||||
cfg: Optional[Settings] = None,
|
||||
provider_override: Optional[AIProvider] = None,
|
||||
) -> dict[str, Any]:
|
||||
conf = cfg or app_settings
|
||||
provider = provider_override or get_ai_provider(conf)
|
||||
ai_enabled_setting = bool(get_setting_value(db, "ai_enabled", False))
|
||||
provider_name = provider.provider_name
|
||||
model_name = provider.model_name or ""
|
||||
reachable = provider.check_reachable(timeout=2.5) if provider_name != "none" else False
|
||||
return {
|
||||
"enabled": ai_enabled_setting and provider_name != "none",
|
||||
"ai_enabled_setting": ai_enabled_setting,
|
||||
"provider": provider_name,
|
||||
"model": model_name,
|
||||
"reachable": reachable,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user