feat: initial commit of Agentic ICD-10-CM Autonomous Code Matcher with 10-node LangGraph pipeline, deterministic guardrails, and professional documentation
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
"""Model exports for offline GGUF inference, LangChain integration, and lifecycle management."""
|
||||
|
||||
from medical_coding.models.base import BaseLocalEmbeddings, BaseLocalLLM
|
||||
from medical_coding.models.exceptions import (
|
||||
LLMError,
|
||||
LLMInferenceError,
|
||||
LLMInitializationError,
|
||||
LLMTimeoutError,
|
||||
)
|
||||
from medical_coding.models.factory import (
|
||||
GPT4AllLocalLLM,
|
||||
ModelFactory,
|
||||
SentenceTransformerLocalEmbeddings,
|
||||
)
|
||||
from medical_coding.models.gpt4all_wrapper import GPT4AllWrapper
|
||||
from medical_coding.models.langchain_llm import LocalGPT4AllLangChainLLM
|
||||
from medical_coding.models.lifecycle import (
|
||||
LLMHealthReport,
|
||||
LLMLifecycleManager,
|
||||
check_llm_health,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BaseLocalEmbeddings",
|
||||
"BaseLocalLLM",
|
||||
"GPT4AllLocalLLM",
|
||||
"GPT4AllWrapper",
|
||||
"LLMError",
|
||||
"LLMHealthReport",
|
||||
"LLMInferenceError",
|
||||
"LLMInitializationError",
|
||||
"LLMLifecycleManager",
|
||||
"LLMTimeoutError",
|
||||
"LocalGPT4AllLangChainLLM",
|
||||
"ModelFactory",
|
||||
"SentenceTransformerLocalEmbeddings",
|
||||
"check_llm_health",
|
||||
]
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Abstract interfaces for local LLMs and dense embedding models."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
|
||||
class BaseLocalLLM(ABC):
|
||||
"""Abstract base class for local GGUF / GPT4All model inference."""
|
||||
|
||||
@abstractmethod
|
||||
def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
) -> str:
|
||||
"""Execute text generation against the local offline model.
|
||||
|
||||
Args:
|
||||
prompt: Formatted prompt string.
|
||||
max_tokens: Maximum tokens to generate.
|
||||
temperature: Sampling temperature (0.0 for deterministic output).
|
||||
stop_sequences: Optional tokens where generation should halt.
|
||||
|
||||
Returns:
|
||||
Generated text string.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_model_info(self) -> dict[str, Any]:
|
||||
"""Return diagnostic metadata about the loaded model."""
|
||||
pass
|
||||
|
||||
|
||||
class BaseLocalEmbeddings(ABC):
|
||||
"""Abstract base class for local dense vector embedding models."""
|
||||
|
||||
@abstractmethod
|
||||
def embed_query(self, text: str) -> list[float]:
|
||||
"""Embed a single query string for semantic vector search."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
||||
"""Embed a batch of document descriptions."""
|
||||
pass
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Exceptions for local LLM lifecycle, initialization, and inference."""
|
||||
|
||||
|
||||
class LLMError(Exception):
|
||||
"""Base exception for local LLM failures."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class LLMInitializationError(LLMError):
|
||||
"""Raised when local GGUF model fails to initialize or weight file is missing."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class LLMInferenceError(LLMError):
|
||||
"""Raised when model inference fails during generation."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class LLMTimeoutError(LLMError):
|
||||
"""Raised when model generation exceeds configured timeout."""
|
||||
|
||||
pass
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Factory and lifecycle coordination for local offline GGUF and embedding models."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.models.base import BaseLocalEmbeddings, BaseLocalLLM
|
||||
from medical_coding.models.langchain_llm import LocalGPT4AllLangChainLLM
|
||||
from medical_coding.models.lifecycle import LLMHealthReport, LLMLifecycleManager
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class GPT4AllLocalLLM(BaseLocalLLM):
|
||||
"""Local GGUF model wrapper delegating execution to the singleton LLMLifecycleManager."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Settings | None = None,
|
||||
model_path: Path | None = None,
|
||||
model_type: str = "llama",
|
||||
n_threads: int = 4,
|
||||
max_tokens: int = 1024,
|
||||
temperature: float = 0.0,
|
||||
) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self.model_path = (
|
||||
Path(model_path) if model_path else self.settings.get_resolved_model_path()
|
||||
)
|
||||
self.model_type = model_type
|
||||
self.n_threads = n_threads
|
||||
self.max_tokens = max_tokens
|
||||
self.temperature = temperature
|
||||
|
||||
def load_model(self) -> None:
|
||||
"""Trigger one-time loading of the local GGUF weights via lifecycle manager."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=self.settings)
|
||||
manager.get_or_load_wrapper()
|
||||
|
||||
def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
) -> str:
|
||||
"""Generate text from the local GGUF model using thread-safe execution."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=self.settings)
|
||||
return manager.generate_sync(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens if max_tokens is not None else self.max_tokens,
|
||||
temperature=temperature if temperature is not None else self.temperature,
|
||||
stop_sequences=stop_sequences,
|
||||
)
|
||||
|
||||
def get_model_info(self) -> dict[str, Any]:
|
||||
"""Return diagnostic health and status metadata."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=self.settings)
|
||||
report = manager.check_health()
|
||||
return {
|
||||
"model_name": report.model_name,
|
||||
"resolved_path": report.resolved_path,
|
||||
"file_exists": report.file_exists,
|
||||
"is_loaded": report.is_loaded,
|
||||
"load_count": report.load_count,
|
||||
"inference_count": report.inference_count,
|
||||
"n_threads": report.configured_threads,
|
||||
"max_llm_concurrency": report.max_llm_concurrency,
|
||||
"max_document_concurrency": report.max_document_concurrency,
|
||||
"offline_only": True,
|
||||
}
|
||||
|
||||
|
||||
class FastLocalEmbeddings(BaseLocalEmbeddings):
|
||||
"""Deterministic, zero-network offline dense embedding generator.
|
||||
|
||||
Uses subword and token feature hashing with L2-normalized dense projections.
|
||||
Ideal for test fixtures, air-gapped environments, and rapid local evaluation.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int = 384) -> None:
|
||||
self.dim = dim
|
||||
|
||||
def _hash_token(self, token: str) -> tuple[int, float]:
|
||||
import hashlib
|
||||
|
||||
h = int(hashlib.md5(token.encode("utf-8")).hexdigest()[:8], 16)
|
||||
idx = h % self.dim
|
||||
sign = 1.0 if (h & 1) == 0 else -1.0
|
||||
return idx, sign
|
||||
|
||||
def _embed_single(self, text: str) -> list[float]:
|
||||
import numpy as np
|
||||
|
||||
vec = np.zeros(self.dim, dtype=np.float32)
|
||||
words = text.lower().split()
|
||||
if not words:
|
||||
return vec.tolist()
|
||||
|
||||
for w in words:
|
||||
idx, sign = self._hash_token(f"w_{w}")
|
||||
vec[idx] += sign * 1.5
|
||||
if len(w) >= 3:
|
||||
for i in range(len(w) - 2):
|
||||
trigram = w[i : i + 3]
|
||||
t_idx, t_sign = self._hash_token(f"c_{trigram}")
|
||||
vec[t_idx] += t_sign * 0.5
|
||||
|
||||
norm = np.linalg.norm(vec)
|
||||
if norm > 1e-9:
|
||||
vec = vec / norm
|
||||
return vec.tolist()
|
||||
|
||||
def embed_query(self, text: str) -> list[float]:
|
||||
return self._embed_single(text)
|
||||
|
||||
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
||||
return [self._embed_single(t) for t in texts]
|
||||
|
||||
|
||||
class SentenceTransformerLocalEmbeddings(BaseLocalEmbeddings):
|
||||
"""Local offline dense embedding generator using SentenceTransformers."""
|
||||
|
||||
def __init__(self, model_path: Path, device: str = "cpu") -> None:
|
||||
self.model_path = Path(model_path)
|
||||
self.device = device
|
||||
self._model: Any = None
|
||||
|
||||
if not self.model_path.exists():
|
||||
logger.warning(
|
||||
"Local embedding directory not found at %s. FastLocalEmbeddings will be used as fallback.",
|
||||
self.model_path,
|
||||
)
|
||||
|
||||
def load_model(self) -> None:
|
||||
"""Load local sentence transformer model from disk without remote network calls."""
|
||||
if self._model is not None:
|
||||
return
|
||||
|
||||
if not self.model_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Local embedding model not found at '{self.model_path}'. "
|
||||
"Ensure local sentence transformer weights are present offline."
|
||||
)
|
||||
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
logger.info("Loading offline SentenceTransformer weights from %s", self.model_path)
|
||||
self._model = SentenceTransformer(
|
||||
str(self.model_path),
|
||||
device=self.device,
|
||||
local_files_only=True,
|
||||
)
|
||||
|
||||
def embed_query(self, text: str) -> list[float]:
|
||||
self.load_model()
|
||||
vec = self._model.encode(text, normalize_embeddings=True, show_progress_bar=False)
|
||||
return vec.tolist()
|
||||
|
||||
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
||||
self.load_model()
|
||||
vecs = self._model.encode(texts, normalize_embeddings=True, show_progress_bar=False)
|
||||
return [v.tolist() for v in vecs]
|
||||
|
||||
|
||||
class ModelFactory:
|
||||
"""Factory creating and providing local offline models configured via Settings."""
|
||||
|
||||
@staticmethod
|
||||
def create_llm(settings: Settings | None = None) -> BaseLocalLLM:
|
||||
"""Create a local GGUF/GPT4All LLM wrapper instance adhering to BaseLocalLLM."""
|
||||
cfg = settings or get_settings()
|
||||
return GPT4AllLocalLLM(settings=cfg)
|
||||
|
||||
@staticmethod
|
||||
def create_langchain_llm(settings: Settings | None = None) -> LocalGPT4AllLangChainLLM:
|
||||
"""Create a LangChain-compatible LLM instance bound to the lifecycle manager."""
|
||||
cfg = settings or get_settings()
|
||||
return LocalGPT4AllLangChainLLM(settings=cfg)
|
||||
|
||||
@staticmethod
|
||||
def get_llm_manager(settings: Settings | None = None) -> LLMLifecycleManager:
|
||||
"""Return the singleton LLMLifecycleManager instance."""
|
||||
return LLMLifecycleManager.get_instance(settings=settings)
|
||||
|
||||
@staticmethod
|
||||
def check_llm_health(settings: Settings | None = None) -> LLMHealthReport:
|
||||
"""Execute diagnostic health assessment of local LLM infrastructure."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=settings)
|
||||
return manager.check_health()
|
||||
|
||||
@staticmethod
|
||||
def create_embeddings(
|
||||
settings: Settings | None = None,
|
||||
force_local_fast: bool = False,
|
||||
) -> BaseLocalEmbeddings:
|
||||
"""Create a local dense embedding wrapper instance.
|
||||
|
||||
If force_local_fast is True or the configured embedding path does not exist on disk,
|
||||
returns FastLocalEmbeddings for deterministic, zero-network local operation.
|
||||
"""
|
||||
cfg = settings or get_settings()
|
||||
if force_local_fast or not cfg.embedding_model_path.exists():
|
||||
return FastLocalEmbeddings(dim=384)
|
||||
return SentenceTransformerLocalEmbeddings(
|
||||
model_path=cfg.embedding_model_path,
|
||||
device=cfg.embedding_device,
|
||||
)
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Local GPT4All model wrapper executing strictly offline inference."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from gpt4all import GPT4All
|
||||
|
||||
from medical_coding.models.exceptions import LLMInferenceError, LLMInitializationError
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class GPT4AllWrapper:
|
||||
"""Wrapper around gpt4all.GPT4All with offline enforcement and parameter binding."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_name: str,
|
||||
model_path: Path,
|
||||
model_type: str = "llama",
|
||||
n_threads: int = 4,
|
||||
n_ctx: int = 2048,
|
||||
temperature: float = 0.0,
|
||||
max_tokens: int = 1024,
|
||||
top_k: int = 40,
|
||||
top_p: float = 0.4,
|
||||
repeat_penalty: float = 1.18,
|
||||
) -> None:
|
||||
self.model_name = model_name
|
||||
self.model_path = Path(model_path)
|
||||
self.model_type = model_type
|
||||
self.n_threads = n_threads
|
||||
self.n_ctx = n_ctx
|
||||
self.temperature = temperature
|
||||
self.max_tokens = max_tokens
|
||||
self.top_k = top_k
|
||||
self.top_p = top_p
|
||||
self.repeat_penalty = repeat_penalty
|
||||
|
||||
self._resolved_file = self._resolve_file_path()
|
||||
self._model: GPT4All | None = None
|
||||
|
||||
def _resolve_file_path(self) -> Path:
|
||||
"""Resolve the exact filesystem path to the GGUF file."""
|
||||
if self.model_path.suffix.lower() == ".gguf" or self.model_path.is_file():
|
||||
return self.model_path
|
||||
return self.model_path / self.model_name
|
||||
|
||||
@property
|
||||
def resolved_file_path(self) -> Path:
|
||||
return self._resolved_file
|
||||
|
||||
def is_weight_file_present(self) -> bool:
|
||||
"""Check whether the configured GGUF model file exists on disk."""
|
||||
return self._resolved_file.exists() and self._resolved_file.is_file()
|
||||
|
||||
def get_file_size_bytes(self) -> int:
|
||||
"""Return the byte size of the model file on disk, or 0 if missing."""
|
||||
if self.is_weight_file_present():
|
||||
try:
|
||||
return self._resolved_file.stat().st_size
|
||||
except OSError:
|
||||
return 0
|
||||
return 0
|
||||
|
||||
def load(self) -> None:
|
||||
"""Load GGUF model into memory offline.
|
||||
|
||||
CRITICAL ARCHITECTURAL GUARANTEE:
|
||||
allow_download is unconditionally False. No network download will ever be attempted.
|
||||
"""
|
||||
if self._model is not None:
|
||||
return
|
||||
|
||||
if not self.is_weight_file_present():
|
||||
raise LLMInitializationError(
|
||||
f"Local GGUF model not found at '{self._resolved_file}'. "
|
||||
"Per offline architectural constraints, automatic download is disabled. "
|
||||
"Ensure the required GGUF weights are placed in the configured directory."
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Loading local GGUF model '%s' from '%s' (threads=%d, ctx=%d, device=cpu)...",
|
||||
self.model_name,
|
||||
self._resolved_file.parent,
|
||||
self.n_threads,
|
||||
self.n_ctx,
|
||||
)
|
||||
|
||||
try:
|
||||
# GPT4All expects model_path as directory and model_name as filename
|
||||
search_dir = str(self._resolved_file.parent)
|
||||
file_name = self._resolved_file.name
|
||||
|
||||
self._model = GPT4All(
|
||||
model_name=file_name,
|
||||
model_path=search_dir,
|
||||
model_type=self.model_type,
|
||||
allow_download=False, # STRICT OFFLINE ENFORCEMENT
|
||||
n_threads=self.n_threads,
|
||||
n_ctx=self.n_ctx,
|
||||
device="cpu",
|
||||
verbose=False,
|
||||
)
|
||||
logger.info("Successfully loaded local GGUF model into memory.")
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to initialize GPT4All backend: %s", exc)
|
||||
raise LLMInitializationError(f"Failed to initialize GPT4All runtime: {exc}") from exc
|
||||
|
||||
def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""Generate response text from local GGUF model synchronously.
|
||||
|
||||
Args:
|
||||
prompt: Text prompt for generation.
|
||||
max_tokens: Override max tokens (defaults to configured max_tokens).
|
||||
temperature: Override temperature (defaults to configured temperature).
|
||||
stop_sequences: List of strings where generation must stop.
|
||||
**kwargs: Additional parameters passed to GPT4All.generate().
|
||||
|
||||
Returns:
|
||||
Generated response string.
|
||||
"""
|
||||
if self._model is None:
|
||||
self.load()
|
||||
|
||||
assert self._model is not None, "Model must be loaded before generation"
|
||||
|
||||
tokens_to_gen = max_tokens if max_tokens is not None else self.max_tokens
|
||||
temp_val = temperature if temperature is not None else self.temperature
|
||||
|
||||
try:
|
||||
raw_output = self._model.generate(
|
||||
prompt=prompt,
|
||||
max_tokens=tokens_to_gen,
|
||||
temp=temp_val,
|
||||
top_k=kwargs.get("top_k", self.top_k),
|
||||
top_p=kwargs.get("top_p", self.top_p),
|
||||
repeat_penalty=kwargs.get("repeat_penalty", self.repeat_penalty),
|
||||
streaming=False,
|
||||
)
|
||||
|
||||
result_text = str(raw_output)
|
||||
|
||||
# Apply stop sequences if requested
|
||||
if stop_sequences:
|
||||
for stop_token in stop_sequences:
|
||||
if stop_token in result_text:
|
||||
result_text = result_text.split(stop_token)[0]
|
||||
|
||||
return result_text.strip()
|
||||
|
||||
except Exception as exc:
|
||||
logger.error("Error during GPT4All inference generation: %s", exc)
|
||||
raise LLMInferenceError(f"GPT4All generation failed: {exc}") from exc
|
||||
|
||||
def get_diagnostic_info(self) -> dict[str, Any]:
|
||||
"""Return diagnostic state of the wrapper."""
|
||||
return {
|
||||
"model_name": self.model_name,
|
||||
"model_path": str(self.model_path),
|
||||
"resolved_file": str(self._resolved_file),
|
||||
"file_exists": self.is_weight_file_present(),
|
||||
"file_size_bytes": self.get_file_size_bytes(),
|
||||
"is_loaded": self._model is not None,
|
||||
"threads": self.n_threads,
|
||||
"context_size": self.n_ctx,
|
||||
"temperature": self.temperature,
|
||||
"max_tokens": self.max_tokens,
|
||||
"offline_only": True,
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
"""LangChain-compatible local LLM interface wrapping GPT4All with controlled concurrency."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from langchain_core.callbacks.manager import (
|
||||
AsyncCallbackManagerForLLMRun,
|
||||
CallbackManagerForLLMRun,
|
||||
)
|
||||
from langchain_core.language_models.llms import LLM
|
||||
from pydantic import Field, PrivateAttr
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.models.lifecycle import LLMLifecycleManager
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class LocalGPT4AllLangChainLLM(LLM):
|
||||
"""LangChain-compatible LLM wrapping local offline GPT4All inference.
|
||||
|
||||
Features:
|
||||
- Thread-safe and shared memory: delegates to the singleton LLMLifecycleManager.
|
||||
- Concurrency-controlled: prevents multi-thread C++ crashes on CPU inference.
|
||||
- Native async support (_acall) for LangChain and LangGraph workflows.
|
||||
- Zero cloud dependencies: 100% offline local execution.
|
||||
"""
|
||||
|
||||
model_name: str = Field(
|
||||
default="",
|
||||
description="Name of the GGUF model file.",
|
||||
)
|
||||
model_path: str = Field(
|
||||
default="",
|
||||
description="Path to local GGUF model directory or file.",
|
||||
)
|
||||
temperature: float = Field(
|
||||
default=0.0,
|
||||
description="Sampling temperature for generation.",
|
||||
)
|
||||
max_tokens: int = Field(
|
||||
default=1024,
|
||||
description="Maximum tokens to generate.",
|
||||
)
|
||||
threads: int = Field(
|
||||
default=4,
|
||||
description="CPU execution threads allocated.",
|
||||
)
|
||||
context_size: int = Field(
|
||||
default=2048,
|
||||
description="Context window size (n_ctx).",
|
||||
)
|
||||
timeout_seconds: float = Field(
|
||||
default=120.0,
|
||||
description="Generation timeout ceiling.",
|
||||
)
|
||||
|
||||
_settings: Settings | None = PrivateAttr(default=None)
|
||||
|
||||
def __init__(self, settings: Settings | None = None, **kwargs: Any) -> None:
|
||||
cfg = settings or get_settings()
|
||||
kwargs.setdefault("model_name", cfg.model_name)
|
||||
kwargs.setdefault("model_path", str(cfg.model_path))
|
||||
kwargs.setdefault("temperature", cfg.model_temperature)
|
||||
kwargs.setdefault("max_tokens", cfg.model_max_tokens)
|
||||
kwargs.setdefault("threads", cfg.model_threads)
|
||||
kwargs.setdefault("context_size", cfg.model_context_size)
|
||||
kwargs.setdefault("timeout_seconds", cfg.llm_timeout_seconds)
|
||||
super().__init__(**kwargs)
|
||||
self._settings = cfg
|
||||
|
||||
@property
|
||||
def _llm_type(self) -> str:
|
||||
"""Return type identifier for LangChain telemetry."""
|
||||
return "gpt4all_local"
|
||||
|
||||
@property
|
||||
def _identifying_params(self) -> dict[str, Any]:
|
||||
"""Return identifying parameters for tracking and serialization."""
|
||||
return {
|
||||
"model_name": self.model_name,
|
||||
"model_path": self.model_path,
|
||||
"temperature": self.temperature,
|
||||
"max_tokens": self.max_tokens,
|
||||
"threads": self.threads,
|
||||
"context_size": self.context_size,
|
||||
"timeout_seconds": self.timeout_seconds,
|
||||
"offline_only": True,
|
||||
}
|
||||
|
||||
def _call(
|
||||
self,
|
||||
prompt: str,
|
||||
stop: list[str] | None = None,
|
||||
run_manager: CallbackManagerForLLMRun | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""Synchronously execute local generation through the lifecycle manager."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=self._settings)
|
||||
max_tokens = kwargs.get("max_tokens", self.max_tokens)
|
||||
temperature = kwargs.get("temperature", self.temperature)
|
||||
|
||||
return manager.generate_sync(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
stop_sequences=stop,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
async def _acall(
|
||||
self,
|
||||
prompt: str,
|
||||
stop: list[str] | None = None,
|
||||
run_manager: AsyncCallbackManagerForLLMRun | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""Asynchronously execute local generation through the concurrency gate."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=self._settings)
|
||||
max_tokens = kwargs.get("max_tokens", self.max_tokens)
|
||||
temperature = kwargs.get("temperature", self.temperature)
|
||||
|
||||
return await manager.generate_async(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
stop_sequences=stop,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -0,0 +1,267 @@
|
||||
"""Thread-safe lifecycle management, caching, and controlled concurrency for local LLM inference."""
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.models.exceptions import LLMInferenceError, LLMTimeoutError
|
||||
from medical_coding.models.gpt4all_wrapper import GPT4AllWrapper
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LLMHealthReport:
|
||||
"""Diagnostic health assessment of local LLM infrastructure."""
|
||||
|
||||
status: Literal["healthy", "degraded", "unhealthy"]
|
||||
model_name: str
|
||||
model_path: str
|
||||
resolved_path: str
|
||||
file_exists: bool
|
||||
file_size_bytes: int
|
||||
is_loaded: bool
|
||||
load_count: int
|
||||
inference_count: int
|
||||
max_llm_concurrency: int
|
||||
max_document_concurrency: int
|
||||
configured_threads: int
|
||||
context_size: int
|
||||
details: str
|
||||
|
||||
|
||||
class LLMLifecycleManager:
|
||||
"""Singleton managing offline GGUF model lifecycle, single-load caching, and concurrency gates.
|
||||
|
||||
ARCHITECTURAL PRINCIPLES:
|
||||
1. Single-Load Guarantee: The GGUF weights are loaded exactly once into RAM.
|
||||
2. Concurrency Separation:
|
||||
- Document-level concurrency (e.g. 10 PDFs) is handled by the async event loop / batch processor.
|
||||
- Model-level concurrency is strictly gated by an async semaphore and thread lock to protect
|
||||
CPU cache lines and avoid C++ llama.cpp context corruption.
|
||||
3. Thread-Safe: Uses double-checked reentrant locking across concurrent threads.
|
||||
"""
|
||||
|
||||
_instance: "LLMLifecycleManager | None" = None
|
||||
_singleton_lock: threading.RLock = threading.RLock()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Settings | None = None,
|
||||
custom_wrapper: GPT4AllWrapper | None = None,
|
||||
) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self._load_lock = threading.RLock()
|
||||
self._inference_thread_lock = threading.Lock()
|
||||
|
||||
# Concurrency gates
|
||||
self._async_semaphore: asyncio.Semaphore | None = None
|
||||
self._async_semaphore_lock = threading.Lock()
|
||||
|
||||
# Lifecycle state
|
||||
self._wrapper: GPT4AllWrapper | None = custom_wrapper
|
||||
self._load_count: int = 1 if custom_wrapper is not None else 0
|
||||
self._inference_count: int = 0
|
||||
self._total_inference_time_ms: float = 0.0
|
||||
|
||||
@classmethod
|
||||
def get_instance(
|
||||
cls,
|
||||
settings: Settings | None = None,
|
||||
custom_wrapper: GPT4AllWrapper | None = None,
|
||||
) -> "LLMLifecycleManager":
|
||||
"""Retrieve or create the singleton lifecycle manager instance."""
|
||||
if cls._instance is None:
|
||||
with cls._singleton_lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = cls(settings=settings, custom_wrapper=custom_wrapper)
|
||||
return cls._instance
|
||||
|
||||
@classmethod
|
||||
def reset_instance(cls) -> None:
|
||||
"""Reset the singleton instance (used for testing or clean restarts)."""
|
||||
with cls._singleton_lock:
|
||||
if cls._instance is not None:
|
||||
logger.info("Resetting LLMLifecycleManager singleton instance.")
|
||||
cls._instance._wrapper = None
|
||||
cls._instance = None
|
||||
|
||||
def _get_async_semaphore(self) -> asyncio.Semaphore:
|
||||
"""Lazy-initialize asyncio.Semaphore bound to the active event loop."""
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
loop = None
|
||||
|
||||
if self._async_semaphore is None or (
|
||||
loop is not None and getattr(self._async_semaphore, "_loop", None) is not loop
|
||||
):
|
||||
with self._async_semaphore_lock:
|
||||
if self._async_semaphore is None or (
|
||||
loop is not None and getattr(self._async_semaphore, "_loop", None) is not loop
|
||||
):
|
||||
limit = self.settings.max_llm_concurrency
|
||||
self._async_semaphore = asyncio.Semaphore(limit)
|
||||
return self._async_semaphore
|
||||
|
||||
def get_or_load_wrapper(self) -> GPT4AllWrapper:
|
||||
"""Return the loaded model wrapper, loading it once if not already initialized."""
|
||||
if self._wrapper is not None:
|
||||
return self._wrapper
|
||||
|
||||
with self._load_lock:
|
||||
if self._wrapper is not None:
|
||||
return self._wrapper
|
||||
|
||||
logger.info("Initializing model wrapper for '%s'...", self.settings.model_name)
|
||||
wrapper = GPT4AllWrapper(
|
||||
model_name=self.settings.model_name,
|
||||
model_path=self.settings.model_path,
|
||||
model_type=self.settings.llm_model_type,
|
||||
n_threads=self.settings.model_threads,
|
||||
n_ctx=self.settings.model_context_size,
|
||||
temperature=self.settings.model_temperature,
|
||||
max_tokens=self.settings.model_max_tokens,
|
||||
top_k=self.settings.llm_top_k,
|
||||
top_p=self.settings.llm_top_p,
|
||||
repeat_penalty=self.settings.llm_repeat_penalty,
|
||||
)
|
||||
|
||||
wrapper.load()
|
||||
self._wrapper = wrapper
|
||||
self._load_count += 1
|
||||
logger.info("Model loaded successfully (load_count=%d).", self._load_count)
|
||||
return self._wrapper
|
||||
|
||||
def generate_sync(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""Execute synchronous model generation protected by the inference thread lock."""
|
||||
wrapper = self.get_or_load_wrapper()
|
||||
|
||||
# Thread lock ensures llama.cpp C++ context is accessed sequentially
|
||||
with self._inference_thread_lock:
|
||||
start_time = time.perf_counter()
|
||||
self._inference_count += 1
|
||||
|
||||
logger.debug(
|
||||
"Starting sync LLM inference (call #%d, prompt_chars=%d)...",
|
||||
self._inference_count,
|
||||
len(prompt),
|
||||
)
|
||||
|
||||
result = wrapper.generate(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
stop_sequences=stop_sequences,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
||||
self._total_inference_time_ms += elapsed_ms
|
||||
|
||||
logger.debug("Completed sync LLM inference in %.2f ms", elapsed_ms)
|
||||
return result
|
||||
|
||||
async def generate_async(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""Execute asynchronous inference with concurrency gating and timeout handling.
|
||||
|
||||
Protects CPU by queuing calls through the async semaphore (max_llm_concurrency)
|
||||
and offloading execution to worker threads without blocking the asyncio loop.
|
||||
"""
|
||||
semaphore = self._get_async_semaphore()
|
||||
timeout_seconds = self.settings.llm_timeout_seconds
|
||||
|
||||
async with semaphore:
|
||||
try:
|
||||
# Offload CPU execution to background thread while enforcing timeout
|
||||
result = await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
self.generate_sync,
|
||||
prompt,
|
||||
max_tokens,
|
||||
temperature,
|
||||
stop_sequences,
|
||||
**kwargs,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
return result
|
||||
except TimeoutError as exc:
|
||||
logger.error(
|
||||
"LLM inference timed out after %.1f seconds for prompt (%d chars)",
|
||||
timeout_seconds,
|
||||
len(prompt),
|
||||
)
|
||||
raise LLMTimeoutError(f"LLM inference timed out after {timeout_seconds}s") from exc
|
||||
except Exception as exc:
|
||||
if isinstance(exc, LLMInferenceError | LLMTimeoutError):
|
||||
raise
|
||||
logger.exception("Unexpected error during async LLM inference: %s", exc)
|
||||
raise LLMInferenceError(f"Async LLM inference failed: {exc}") from exc
|
||||
|
||||
def check_health(self) -> LLMHealthReport:
|
||||
"""Run non-destructive diagnostic health check on local LLM infrastructure."""
|
||||
resolved = self.settings.get_resolved_model_path()
|
||||
file_exists = resolved.exists() and resolved.is_file()
|
||||
file_size = 0
|
||||
if file_exists:
|
||||
try:
|
||||
file_size = resolved.stat().st_size
|
||||
except OSError:
|
||||
file_size = 0
|
||||
|
||||
is_loaded = self._wrapper is not None
|
||||
|
||||
if file_exists and is_loaded:
|
||||
status = "healthy"
|
||||
details = "Local GGUF model is present on disk and loaded in memory."
|
||||
elif file_exists:
|
||||
status = "healthy"
|
||||
details = "Local GGUF model is present on disk and ready for on-demand loading."
|
||||
else:
|
||||
status = "degraded"
|
||||
details = (
|
||||
f"Model file not found at '{resolved}'. Offline mode is active; "
|
||||
"inference calls will raise FileNotFoundError until weights are placed on disk."
|
||||
)
|
||||
|
||||
return LLMHealthReport(
|
||||
status=status,
|
||||
model_name=self.settings.model_name,
|
||||
model_path=str(self.settings.model_path),
|
||||
resolved_path=str(resolved),
|
||||
file_exists=file_exists,
|
||||
file_size_bytes=file_size,
|
||||
is_loaded=is_loaded,
|
||||
load_count=self._load_count,
|
||||
inference_count=self._inference_count,
|
||||
max_llm_concurrency=self.settings.max_llm_concurrency,
|
||||
max_document_concurrency=self.settings.max_document_concurrency,
|
||||
configured_threads=self.settings.model_threads,
|
||||
context_size=self.settings.model_context_size,
|
||||
details=details,
|
||||
)
|
||||
|
||||
|
||||
def check_llm_health(settings: Settings | None = None) -> LLMHealthReport:
|
||||
"""Convenience functional interface for LLM health check."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=settings)
|
||||
return manager.check_health()
|
||||
Reference in New Issue
Block a user