File size: 9,590 Bytes
b92b744
 
 
 
 
 
 
 
 
 
 
 
 
57a9a08
b92b744
 
 
57a9a08
b92b744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57a9a08
b92b744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cb871f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57a9a08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b92b744
 
 
 
 
 
 
 
 
 
 
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
import asyncio
import json
import logging
from contextlib import asynccontextmanager
from pathlib import Path

from elastic_transport import ConnectionError as ElasticConnectionError
from elasticsearch import ApiError
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles

from app.concepts import ConceptError, ConceptVectorService
from app.config import settings
from app.gapmap_service import GapMapService
from app.llm import LLMService
from app.models import ConceptSearchRequest, MapRequest, NoveltyRequest, SearchRequest
from app.novelty import NoveltyEngine
from app.pipeline import SearchPipeline
from app.repository import ElasticRepository

logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    repo = ElasticRepository()
    llm = LLMService()
    app.state.repository = repo
    app.state.pipeline = SearchPipeline(repo, llm)
    app.state.novelty = NoveltyEngine(llm, repo=repo)
    app.state.gapmap = GapMapService(repo)
    app.state.concepts = ConceptVectorService(repo)
    yield
    await app.state.novelty.fulltext.close()
    await llm.close()
    await repo.close()


app = FastAPI(title="nullMap API", version="1.0.0", lifespan=lifespan)
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/health")
@app.get("/api/health", include_in_schema=False)
def health() -> dict[str, str]:
    return {"status": "ok"}


@app.get("/ready")
@app.get("/api/ready", include_in_schema=False)
async def ready(request: Request):
    try:
        elastic = await request.app.state.repository.health()
    except Exception as exc:
        logger.warning("Elasticsearch readiness: %s", type(exc).__name__)
        return JSONResponse(
            status_code=503,
            content={
                "status": "unavailable",
                "elasticsearch": {"connected": False},
                "message": "Elasticsearch is unavailable. Check ELASTIC_URL and credentials or start the local container.",
            },
        )
    return {
        "status": "ready",
        "elasticsearch": elastic,
        "openaiConfigured": bool(settings.openai_api_key),
        "openalexSource": "public_s3_snapshot",
        "openalexSnapshotManifest": settings.openalex_snapshot_manifest,
        "embeddingsEnabled": settings.embeddings_enabled,
        "compressionEnabled": settings.compression_enabled and settings.compression_validated,
    }


def search_error(exc: Exception) -> str:
    if isinstance(exc, (ApiError, ElasticConnectionError)):
        return "Elasticsearch could not complete the search. Check the backend connection and index setup."
    return "The evidence search could not complete. Please retry or inspect the backend logs."


@app.post("/search")
@app.post("/api/search", include_in_schema=False)
async def search(body: SearchRequest, request: Request):
    try:
        return await request.app.state.pipeline.search(body)
    except Exception as exc:
        logger.error("Search failed: %s", type(exc).__name__)
        raise HTTPException(status_code=503, detail=search_error(exc)) from None


@app.post("/search/stream")
@app.post("/api/search/stream", include_in_schema=False)
async def search_stream(body: SearchRequest, request: Request):
    async def stream():
        queue: asyncio.Queue = asyncio.Queue(maxsize=16)

        async def progress(payload):
            await queue.put(("progress", payload))

        async def run():
            try:
                result = await request.app.state.pipeline.search(body, progress)
                await queue.put(("result", result))
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                logger.error("Streamed search failed: %s", type(exc).__name__)
                await queue.put(("error", {"message": search_error(exc)}))

        task = asyncio.create_task(run())
        try:
            while True:
                if await request.is_disconnected():
                    break
                try:
                    event, payload = await asyncio.wait_for(queue.get(), timeout=10)
                except TimeoutError:
                    yield ": keepalive\n\n"
                    continue
                yield f"event: {event}\ndata: {json.dumps(payload, allow_nan=False)}\n\n"
                if event in ("result", "error"):
                    break
        finally:
            task.cancel()
            try:
                await task
            except asyncio.CancelledError:
                pass

    return StreamingResponse(
        stream(),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )


@app.post("/novelty")
@app.post("/api/novelty", include_in_schema=False)
async def novelty(body: NoveltyRequest, request: Request):
    try:
        return await request.app.state.novelty.assess(body.hypothesis, body.scan, body.read)
    except Exception as exc:
        logger.error("Novelty assessment failed: %s", type(exc).__name__)
        raise HTTPException(
            status_code=503,
            detail="The novelty assessment could not complete. Please retry or inspect the backend logs.",
        ) from None


@app.post("/map")
@app.post("/api/map", include_in_schema=False)
async def gap_map(body: MapRequest, request: Request):
    try:
        return await request.app.state.gapmap.assess(
            idea=body.idea,
            arithmetic=body.arithmetic,
            cutoff_year=body.cutoffYear,
            refresh=body.refresh,
        )
    except Exception as exc:
        logger.error("Gap map failed: %s", type(exc).__name__)
        raise HTTPException(
            status_code=503,
            detail="The evidence map could not be built. Please retry or inspect the backend logs.",
        ) from None


@app.post("/map/stream")
@app.post("/api/map/stream", include_in_schema=False)
async def gap_map_stream(body: MapRequest, request: Request):
    """The map as it is built: the same payload as ``/map``, plus the states on
    the way to it. A cached map arrives as one `result` event with no progress
    before it, which is the honest thing for work that did not happen."""

    async def stream():
        queue: asyncio.Queue = asyncio.Queue(maxsize=32)

        async def progress(payload):
            await queue.put(("progress", payload))

        async def run():
            try:
                result = await request.app.state.gapmap.stream(
                    idea=body.idea,
                    arithmetic=body.arithmetic,
                    cutoff_year=body.cutoffYear,
                    refresh=body.refresh,
                    progress=progress,
                )
                await queue.put(("result", result))
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                logger.error("Streamed gap map failed: %s", type(exc).__name__)
                await queue.put(
                    (
                        "error",
                        {
                            "message": "The evidence map could not be built. "
                            "Please retry or inspect the backend logs."
                        },
                    )
                )

        task = asyncio.create_task(run())
        try:
            while True:
                if await request.is_disconnected():
                    break
                try:
                    event, payload = await asyncio.wait_for(queue.get(), timeout=10)
                except TimeoutError:
                    yield ": keepalive\n\n"
                    continue
                yield f"event: {event}\ndata: {json.dumps(payload, allow_nan=False)}\n\n"
                if event in ("result", "error"):
                    break
        finally:
            task.cancel()
            try:
                await task
            except asyncio.CancelledError:
                pass

    return StreamingResponse(
        stream(),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )


@app.post("/concepts/search")
@app.post("/api/concepts/search", include_in_schema=False)
async def concept_search(body: ConceptSearchRequest, request: Request):
    try:
        return await request.app.state.concepts.search(body)
    except ConceptError as exc:
        raise HTTPException(status_code=exc.status, detail=str(exc)) from None
    except Exception as exc:
        logger.error("Concept search failed: %s", type(exc).__name__)
        raise HTTPException(
            status_code=503,
            detail="Elasticsearch could not complete the concept search. Check the backend connection and index setup.",
        ) from None


@app.get("/studies/{study_id:path}")
@app.get("/api/studies/{study_id:path}", include_in_schema=False)
async def study_detail(study_id: str, request: Request):
    study = await request.app.state.repository.get(study_id)
    if not study or study.get("record_kind") != "study":
        raise HTTPException(status_code=404, detail="Study not found")
    return {k: v for k, v in study.items() if k not in ("embedding", "attachments")}


if Path(settings.frontend_dist).is_dir():
    app.mount("/", StaticFiles(directory=settings.frontend_dist, html=True), name="frontend")