Spaces:
Sleeping
Sleeping
File size: 10,112 Bytes
6d74c84 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | """
groundlens REST API
Lightweight HTTP wrapper around the groundlens library.
Deploy on Hugging Face Spaces (Docker SDK), Railway, Fly.io, or any container host.
Endpoints:
POST /v1/check β auto-selects SGI or DGI based on whether context is provided
POST /v1/sgi β explicit context-based grounding check
POST /v1/dgi β explicit context-free grounding check
GET /health β liveness + model status
"""
from __future__ import annotations
import time
from contextlib import asynccontextmanager
from typing import Optional
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field, ConfigDict
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Model preloading
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_model_ready = False
_model_load_time: float = 0.0
def _load_model() -> None:
"""Import groundlens to trigger model download + warm the embedding cache."""
global _model_ready, _model_load_time
if _model_ready:
return
t0 = time.monotonic()
from groundlens import compute_dgi # noqa: F401
# Warm up β first call loads the sentence-transformer model
compute_dgi(question="warmup", response="warmup")
_model_load_time = round(time.monotonic() - t0, 2)
_model_ready = True
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Load model at startup so first request is fast."""
_load_model()
yield
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# App
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(
title="groundlens API",
description=(
"LLM hallucination detection using embedding geometry. "
"No second LLM. Deterministic. Same inputs β same scores."
),
version="2026.5.12",
docs_url="/docs",
redoc_url="/redoc",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["*"],
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Request / Response models
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class CheckRequest(BaseModel):
"""Auto-select SGI or DGI based on whether context is provided."""
model_config = ConfigDict(str_strip_whitespace=True)
question: str = Field(
...,
description="The question asked to the LLM",
min_length=1,
max_length=10_000,
)
response: str = Field(
...,
description="The LLM's response to evaluate",
min_length=1,
max_length=50_000,
)
context: Optional[str] = Field(
default=None,
description=(
"Source material (document, RAG chunks, reference text). "
"If provided β SGI. If omitted β DGI."
),
max_length=100_000,
)
class SGIRequest(BaseModel):
"""Explicit context-based grounding check."""
model_config = ConfigDict(str_strip_whitespace=True)
question: str = Field(..., min_length=1, max_length=10_000)
context: str = Field(..., min_length=1, max_length=100_000)
response: str = Field(..., min_length=1, max_length=50_000)
class DGIRequest(BaseModel):
"""Explicit context-free grounding check."""
model_config = ConfigDict(str_strip_whitespace=True)
question: str = Field(..., min_length=1, max_length=10_000)
response: str = Field(..., min_length=1, max_length=50_000)
class SGIDetail(BaseModel):
q_dist: float
ctx_dist: float
interpretation: str
class DGIDetail(BaseModel):
interpretation: str
class GroundingResult(BaseModel):
verdict: str = Field(description="GROUNDED or HALLUCINATION RISK")
flagged: bool = Field(description="True if hallucination risk detected")
method: str = Field(description="SGI or DGI")
score: float = Field(description="Grounding score")
threshold: float = Field(description="Score threshold for flagging")
explanation: str = Field(description="Plain-language explanation")
detail: SGIDetail | DGIDetail
latency_ms: int = Field(description="Processing time in milliseconds")
class HealthResponse(BaseModel):
status: str
model_loaded: bool
model_load_time_s: float
version: str
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Helpers
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _run_sgi(question: str, context: str, response: str) -> GroundingResult:
from groundlens import compute_sgi
t0 = time.monotonic()
result = compute_sgi(question=question, context=context, response=response)
latency = int((time.monotonic() - t0) * 1000)
return GroundingResult(
verdict="GROUNDED" if not result.flagged else "HALLUCINATION RISK",
flagged=result.flagged,
method="SGI (Semantic Grounding Index)",
score=round(result.value, 4),
threshold=0.95,
explanation=(
"The response appears grounded in the source material."
if not result.flagged
else "The response may not be based on the source material provided."
),
detail=SGIDetail(
q_dist=round(result.q_dist, 4),
ctx_dist=round(result.ctx_dist, 4),
interpretation=result.explanation,
),
latency_ms=latency,
)
def _run_dgi(question: str, response: str) -> GroundingResult:
from groundlens import compute_dgi
t0 = time.monotonic()
result = compute_dgi(question=question, response=response)
latency = int((time.monotonic() - t0) * 1000)
return GroundingResult(
verdict="GROUNDED" if not result.flagged else "HALLUCINATION RISK",
flagged=result.flagged,
method="DGI (Directional Grounding Index)",
score=round(result.value, 4),
threshold=0.30,
explanation=(
"The response follows patterns typical of grounded answers."
if not result.flagged
else "The response shows geometric patterns associated with hallucination."
),
detail=DGIDetail(
interpretation=result.explanation,
),
latency_ms=latency,
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Endpoints
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/health", response_model=HealthResponse, tags=["system"])
async def health():
"""Liveness check. Returns model load status."""
return HealthResponse(
status="ok" if _model_ready else "loading",
model_loaded=_model_ready,
model_load_time_s=_model_load_time,
version="2026.5.12",
)
@app.post("/v1/check", response_model=GroundingResult, tags=["grounding"])
async def check(req: CheckRequest):
"""Check whether an LLM response is hallucinated.
Auto-selects the right method:
- Context provided β SGI (checks if the response used the source material)
- No context β DGI (checks geometric grounding patterns)
"""
if not _model_ready:
raise HTTPException(503, "Model is still loading. Try again in a few seconds.")
has_context = req.context is not None and req.context.strip() != ""
if has_context:
return _run_sgi(req.question, req.context, req.response)
else:
return _run_dgi(req.question, req.response)
@app.post("/v1/sgi", response_model=GroundingResult, tags=["grounding"])
async def sgi(req: SGIRequest):
"""SGI β check if the response is grounded in a source document.
Use for RAG pipelines, document Q&A, or any case where you have
the source material the LLM was given.
"""
if not _model_ready:
raise HTTPException(503, "Model is still loading. Try again in a few seconds.")
return _run_sgi(req.question, req.context, req.response)
@app.post("/v1/dgi", response_model=GroundingResult, tags=["grounding"])
async def dgi(req: DGIRequest):
"""DGI β check grounding patterns without source context.
Use for open-ended chat, general Q&A, or any case where you just
have a question and the LLM's answer.
"""
if not _model_ready:
raise HTTPException(503, "Model is still loading. Try again in a few seconds.")
return _run_dgi(req.question, req.response)
|