nikeshn commited on
Commit
27a578e
·
verified ·
1 Parent(s): 07009ca

Upload 10 files

Browse files
Files changed (9) hide show
  1. .dockerignore +8 -8
  2. .env.example +17 -13
  3. .gitignore +7 -7
  4. DEPLOYMENT_GUIDE.md +103 -0
  5. Dockerfile +26 -23
  6. README.md +22 -25
  7. app.py +263 -189
  8. requirements-dev.txt +3 -3
  9. requirements.txt +16 -16
.dockerignore CHANGED
@@ -1,8 +1,8 @@
1
- .git
2
- .pytest_cache
3
- __pycache__
4
- *.py[cod]
5
- .env
6
- .venv
7
- tests
8
- data/knowledge_raw_archive
 
1
+ .git
2
+ .pytest_cache
3
+ __pycache__
4
+ *.py[cod]
5
+ .env
6
+ .venv
7
+ tests
8
+ data/knowledge_raw_archive
.env.example CHANGED
@@ -1,15 +1,19 @@
1
- ENVIRONMENT=production
2
- ORIGIN_TOKEN=replace-with-the-same-random-value-as-worker-HF_ORIGIN_TOKEN
3
- OPENAI_API_KEY=
4
- ANTHROPIC_API_KEY=
5
  PRIMO_API_KEY=
6
- ADMIN_PASSWORD=replace-with-a-strong-admin-password
7
- CLOUDFLARE_WORKER_URL=https://steep-haze-e1f8.nikeshn.workers.dev
8
- CLOUDFLARE_ADMIN_TOKEN=replace-with-the-same-random-value-as-worker-ADMIN_TOKEN
9
- LIBCAL_CLIENT_ID=
10
- LIBCAL_CLIENT_SECRET=
11
- LIBCAL_EVENTS_CLIENT_ID=
12
- LIBCAL_EVENTS_CLIENT_SECRET=
13
- CONTACT_EMAIL=libse@ku.ac.ae
14
- RUNTIME_DIR=./libbee_runtime
 
 
 
15
  ALLOWED_CORS_ORIGINS=
 
 
1
+ ENVIRONMENT=production
2
+ ORIGIN_TOKEN=replace-with-the-same-random-value-as-worker-HF_ORIGIN_TOKEN
3
+ OPENAI_API_KEY=
4
+ ANTHROPIC_API_KEY=
5
  PRIMO_API_KEY=
6
+ OPENALEX_API_KEY=
7
+ ADMIN_PASSWORD=replace-with-a-strong-admin-password
8
+ CLOUDFLARE_WORKER_URL=https://steep-haze-e1f8.nikeshn.workers.dev
9
+ CLOUDFLARE_ADMIN_TOKEN=replace-with-the-same-random-value-as-worker-ADMIN_TOKEN
10
+ LIBCAL_CLIENT_ID=
11
+ LIBCAL_CLIENT_SECRET=
12
+ LIBCAL_EVENTS_CLIENT_ID=
13
+ LIBCAL_EVENTS_CLIENT_SECRET=
14
+ CONTACT_EMAIL=libse@ku.ac.ae
15
+ # Use the writable persistent mount configured for this Space. For local
16
+ # development use RUNTIME_DIR=./libbee_runtime and ENVIRONMENT=development.
17
+ RUNTIME_DIR=/data/libbee_runtime
18
  ALLOWED_CORS_ORIGINS=
19
+ MAX_REQUEST_BODY_BYTES=524288
.gitignore CHANGED
@@ -1,7 +1,7 @@
1
- .env
2
- .venv/
3
- .pytest_cache/
4
- __pycache__/
5
- *.py[cod]
6
- data/rag_cache/
7
- libbee_runtime/
 
1
+ .env
2
+ .venv/
3
+ .pytest_cache/
4
+ __pycache__/
5
+ *.py[cod]
6
+ data/rag_cache/
7
+ libbee_runtime/
DEPLOYMENT_GUIDE.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deployment and loading-speed guide
2
+
3
+ If using the standalone HF zip, its root already contains the HF application; omit the `cd hf` step below. Frontend/assets are in the complete package.
4
+
5
+ ## 1. Keep a rollback copy
6
+
7
+ Export the current HF Space files, keep the current LibGuides source block, and back up any runtime configuration/feedback/metrics you need. Never place real secrets in the replacement archive, LibGuides JavaScript, or a public repository.
8
+
9
+ ## 2. Upload the HF source
10
+
11
+ Copy the **contents of `hf/`** into the root of the existing Docker Space. Preserve the Space's settings and secrets. `app.py`, `Dockerfile`, `requirements.txt`, `README.md`, and `src/` must be at the repository root, not nested under an extra `hf/` folder.
12
+
13
+ Use the complete supplied knowledge directory. Duplicate `(1).txt` variants have been merged into their canonical files; remove those old duplicate files from the destination so they are not indexed again. Empty placeholder files and git/test caches are not deployment inputs.
14
+
15
+ The container runs as UID 1000 on port 7860. `Dockerfile` uses the liveness endpoint for its health check. Initial semantic-index creation happens in the background; local keyword retrieval becomes available first.
16
+
17
+ ## 3. Check configuration
18
+
19
+ | Secret/variable | Required use |
20
+ |---|---|
21
+ | `ENVIRONMENT` | `production` for the deployed Space. |
22
+ | `ORIGIN_TOKEN` | Must match your Worker's `HF_ORIGIN_TOKEN`. Protected origin routes reject missing/wrong tokens. |
23
+ | `OPENAI_API_KEY` | Needed for the configured GPT answers, classification and semantic embeddings. Without it, some deterministic library responses/local retrieval can still work, but the model service is degraded. |
24
+ | `ADMIN_PASSWORD` | Required to log in to the HF admin page. |
25
+ | `CLOUDFLARE_WORKER_URL` | Existing gateway URL; keep it consistent with frontend `API_URL`. |
26
+ | `CLOUDFLARE_ADMIN_TOKEN` | Must match Worker `ADMIN_TOKEN`; used for the existing admin/analytics token contract. |
27
+ | `LIBCAL_CLIENT_ID`, `LIBCAL_CLIENT_SECRET` | Required for live library hours. |
28
+ | `LIBCAL_EVENTS_CLIENT_ID`, `LIBCAL_EVENTS_CLIENT_SECRET` | Optional separate events credentials; otherwise main LibCal credentials are reused. |
29
+ | `PRIMO_API_KEY` | Enables your existing direct PRIMO API integration where configured. |
30
+ | `ANTHROPIC_API_KEY` | Optional; needed if you enable Claude. |
31
+ | `OPENALEX_API_KEY` | Optional server-side key for the existing scholarly fallback. Basic anonymous usage remains supported. |
32
+ | `CONTACT_EMAIL` | Institutional contact for scholarly API requests. |
33
+ | `RUNTIME_DIR` | A writable runtime directory; use `/data/libbee_runtime` only if that path is your configured durable mount. |
34
+ | `ALLOWED_CORS_ORIGINS` | Explicit browser origins if directly calling permitted HF endpoints from a separate site; the intended student chat path remains through the Worker. |
35
+
36
+ See `hf/.env.example` for supported examples and request limits. It contains placeholders, not credentials. Do not upload a filled `.env` to a public repository.
37
+
38
+ Creating `/data` in a Docker build does **not** make it persistent. Verify your Space's actual mounted durable storage and its UID-1000 permissions. On ephemeral disk, restarts lose cache/runtime data. Current HF Docker documentation describes runtime persistence options and permissions: [Docker Spaces](https://huggingface.co/docs/hub/spaces-sdks-docker).
39
+
40
+ ## 4. Check the existing Worker contract
41
+
42
+ The Worker code was not supplied. Confirm these against it before live rollout:
43
+
44
+ - Browser requests use `/agent`, `/feedback`, and `/config` at `API_URL`; JSON chat/feedback requests include the existing `X-LibBee-Session` header.
45
+ - The Worker adds `X-LibBee-Origin-Token` only on its server-to-HF calls. The permanent origin and admin secrets must never appear in student JavaScript.
46
+ - Forward the HF agent JSON fields expected by the frontend: `answer`, `request_id`, intent/tools, source links, search context, and follow-up suggestions.
47
+ - Preserve useful HTTP status codes for malformed requests, busy/maintenance states and provider failures. Do not cache chat or feedback responses.
48
+ - The Worker owns persistent analytics and session enforcement. Confirm feedback ownership, analytics writes, rate limits and D1 schema using its actual source.
49
+ - Allow the actual KU LibGuides origin in Worker CORS, including JSON requests and the session header.
50
+ - Verify that the current Worker accepts the HF admin's existing short-lived signed `analytics:read` token format. The permanent secret remains server-side.
51
+ - If `/config` reaches a sleeping HF Space, the revised front end still renders and permits typing without waiting for configuration to return.
52
+
53
+ ## 5. Replace the LibGuides block
54
+
55
+ On a staging page, replace the old source block with all of `frontend/libbee-libguides.html`. The block contains its own CSS, HTML, JavaScript and small embedded images; no image hosting setup is needed. Keep the normal LibGuides page wrapper.
56
+
57
+ The default `API_URL` remains the gateway found in your supplied files. Change this one configuration value only if you are moving to a different gateway. Add the staging/production page origins to the Worker's CORS allowlist as needed.
58
+
59
+ Do not paste both the old and new blocks into one page. Duplicate IDs or event handlers can submit a question twice. The revised layout stays within the chatbot container and does not force the whole LibGuides page to become full width.
60
+
61
+ ## 6. Validate before switching users
62
+
63
+ In an environment with package/network access:
64
+
65
+ ```bash
66
+ cd hf
67
+ python -m pip install -r requirements-dev.txt
68
+ python -m pip check
69
+ python -m compileall -q app.py src tests
70
+ pytest -q
71
+ ```
72
+
73
+ Run a current dependency-vulnerability scan against the resolved environment, then lock and retest compatible patched packages. This review retained the supplied dependency pins to avoid an untested framework migration; it does not certify that those old pins or their transitive resolution are current or vulnerability-free.
74
+
75
+ Start the container/Space and check:
76
+
77
+ | Check | Expected result |
78
+ |---|---|
79
+ | `/health/live` | HTTP 200 once the application is listening; version 4.1.1. |
80
+ | `/config` while embeddings are initializing | Responds without waiting for semantic index construction. |
81
+ | `/health/ready` | HTTP 503 while retrieval is unavailable or origin configuration is invalid; reports readiness/degraded state honestly once local retrieval is available. |
82
+ | Direct `/agent` request without the origin token | Rejected in production. |
83
+ | Gateway chat | Greeting, opening hours, staff, database help, article search, books, PubMed, and follow-ups work using real credentials. |
84
+ | Cancel/Clear/Home during a slow answer | No late answer appears in a new/cleared conversation. |
85
+ | Unavailable gateway/slow request | Visible progress/error/retry controls; no silent frozen composer. |
86
+ | Feedback | Save one up/down vote through the Worker and confirm the expected analytics ownership. |
87
+ | Admin login/logout | Logged-out session stays invalid, including after reloading persisted sessions. |
88
+ | Maintenance | Normal submission, suggested questions and follow-ups respect maintenance. |
89
+ | Real browser | Desktop + narrow mobile; keyboard focus; sources/copy/expand controls; no console errors or page-wide style changes. |
90
+
91
+ Admin's write canary is now an explicit POST action. Read-only health GETs do not run paid/write diagnostics. Verify the actual Worker canary endpoint separately if used.
92
+
93
+ ## 7. Understand what still controls loading speed
94
+
95
+ The revised front end is smaller and does not wait for configuration before displaying the interface. HF no longer waits for remote embeddings to finish before serving basic endpoints. Stable content hashes let the semantic cache survive ordinary rebuilds **when stored on a durable mount**. The new cache schema forces one rebuild of older cache files.
96
+
97
+ A sleeping HF Space still needs to wake. HF documents that CPU Basic sleeps after inactivity and upgraded hardware can remain running. Check the current Space hardware/sleep settings if the first visit after a long idle period remains slow; changing hardware was not performed during this review. [HF sleep settings](https://huggingface.co/docs/hub/spaces-gpus#set-a-custom-sleep-time).
98
+
99
+ Measure the warm and idle-first-visit cases separately in browser Network tools: document download, `/config`, first `/agent` request, and later `/agent` requests. No production latency reduction in seconds is claimed by this package because deployed timing data was not available.
100
+
101
+ ## Rollback
102
+
103
+ Restore the previous HF source and the previous LibGuides source block together, retaining the matching Worker tokens and endpoint URL. Restore runtime-data backups if needed. New signed caches can be discarded and rebuilt; never accept an unsigned pickle/index file to make rollback appear faster.
Dockerfile CHANGED
@@ -1,24 +1,27 @@
1
- FROM python:3.12-slim
2
-
3
- ENV PYTHONDONTWRITEBYTECODE=1 \
4
- PYTHONUNBUFFERED=1 \
5
- PIP_NO_CACHE_DIR=1
6
-
7
- WORKDIR /app
8
-
9
- RUN addgroup --system libbee \
10
- && adduser --system --ingroup libbee --home /app libbee \
11
- && mkdir -p /data/libbee_runtime \
12
- && chown -R libbee:libbee /app /data/libbee_runtime
13
-
14
- COPY --chown=libbee:libbee requirements.txt ./
15
- RUN pip install --no-cache-dir --requirement requirements.txt
16
-
17
- COPY --chown=libbee:libbee . .
18
- USER libbee
19
-
20
- EXPOSE 7860
21
- HEALTHCHECK --interval=30s --timeout=8s --start-period=90s --retries=3 \
22
- CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:7860/health/live', timeout=5)"
23
-
 
 
 
24
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--proxy-headers", "--forwarded-allow-ips", "*"]
 
1
+ FROM python:3.12-slim
2
+
3
+ ENV PYTHONDONTWRITEBYTECODE=1 \
4
+ PYTHONUNBUFFERED=1 \
5
+ PIP_NO_CACHE_DIR=1
6
+
7
+ WORKDIR /app
8
+
9
+ # HF Docker Spaces execute as uid 1000. Match that identity so copied code
10
+ # and writable runtime mounts are usable after the build container is gone.
11
+ RUN groupadd --gid 1000 libbee \
12
+ && useradd --uid 1000 --gid 1000 --create-home libbee \
13
+ && chown libbee:libbee /app
14
+
15
+ COPY --chown=libbee:libbee requirements.txt ./
16
+ RUN pip install --no-cache-dir --requirement requirements.txt
17
+
18
+ COPY --chown=libbee:libbee . .
19
+ USER libbee
20
+
21
+ EXPOSE 7860
22
+ HEALTHCHECK --interval=30s --timeout=8s --start-period=90s --retries=3 \
23
+ CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:7860/health/live', timeout=5)"
24
+
25
+ # Keep one process: the local session/metrics stores are not a shared database.
26
+ # HF supplies the public address through its trusted reverse proxy.
27
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--proxy-headers", "--forwarded-allow-ips", "*"]
README.md CHANGED
@@ -4,45 +4,42 @@ emoji: 🐝
4
  colorFrom: blue
5
  colorTo: yellow
6
  sdk: docker
7
- app_file: app.py
8
  pinned: false
9
  ---
10
 
11
- # LibBee private origin v4.1 — no custom domain
12
 
13
- This Hugging Face Space is the private application origin behind the Cloudflare Worker. Browsers must not call `/agent`, `/search`, or `/feedback` directly. Those routes require `X-LibBee-Origin-Token`, which the Worker adds server-side.
14
 
15
- ## Required Space secrets
16
 
17
- - `ORIGIN_TOKEN`: a new random secret; must match the Worker's `HF_ORIGIN_TOKEN`.
18
- - `OPENAI_API_KEY`: required for the default model, classification, embeddings, and RAG.
19
- - `ADMIN_PASSWORD`: strong password for `/admin`.
20
- - `CLOUDFLARE_WORKER_URL`: `https://steep-haze-e1f8.nikeshn.workers.dev`; returned only to an authenticated admin browser with a short-lived token.
21
- - `CLOUDFLARE_ADMIN_TOKEN`: must match the Worker's `ADMIN_TOKEN`; used to sign 90-second read-only browser tokens. The permanent value is never returned to JavaScript.
22
- - `LIBCAL_CLIENT_ID` and `LIBCAL_CLIENT_SECRET`: used by HF to fetch live hours directly.
23
 
24
- If events use separate credentials, also set `LIBCAL_EVENTS_CLIENT_ID` and `LIBCAL_EVENTS_CLIENT_SECRET`; otherwise the main LibCal credentials are reused.
25
 
26
- Optional secrets: `ANTHROPIC_API_KEY` and `PRIMO_API_KEY`.
27
 
28
- Use persistent HF storage and keep `RUNTIME_DIR=/data/libbee_runtime` so runtime configuration, metrics, feedback fallback data, and the signed RAG cache survive restarts.
29
 
30
- ## Security properties
 
 
 
 
 
 
 
31
 
32
- - Protected origin routes fail closed if `ORIGIN_TOKEN` is absent or incorrect.
33
- - Request models have strict size and enum limits.
34
- - Answer HTML is sanitized with a tag and attribute allow-list before it leaves the origin; the LibGuides client sanitizes it again.
35
- - The signed FAISS/BM25 cache is ignored if it was modified or if no origin secret is configured.
36
- - Raw scrape dumps are kept in `data/knowledge_raw_archive` but excluded from indexing. Curated, review-dated files are indexed.
37
- - Persistent analytics is written by the Worker, not by the browser or the HF origin.
38
- - A logged-in admin browser receives only an HMAC-signed `analytics:read` token that expires after 90 seconds; Worker write endpoints reject it.
39
- - Live LibCal requests originate from HF, avoiding the unavailable HF-to-`workers.dev` loop.
40
-
41
- ## Local checks
42
 
43
  ```bash
 
 
44
  python -m compileall -q app.py src tests
45
  pytest -q
46
  ```
47
 
48
- See the complete package `DEPLOYMENT_GUIDE.md` for coordinated HF, Worker, D1, and LibGuides deployment.
 
 
 
4
  colorFrom: blue
5
  colorTo: yellow
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # LibBee 4.1.1 — KU Library Assistant
12
 
13
+ FastAPI origin for the existing Cloudflare gateway and KU LibGuides chatbot.
14
 
15
+ ## Configuration
16
 
17
+ Set real credentials in Space secrets. `.env.example` documents placeholders and optional settings. Keep `ORIGIN_TOKEN` equal to the Worker's `HF_ORIGIN_TOKEN`, and `CLOUDFLARE_ADMIN_TOKEN` equal to its `ADMIN_TOKEN`.
 
 
 
 
 
18
 
19
+ `OPENAI_API_KEY` enables GPT and semantic embeddings. `ANTHROPIC_API_KEY`, `PRIMO_API_KEY`, and `OPENALEX_API_KEY` are optional integration keys. Live hours/events need LibCal credentials; separate events credentials are optional. `ADMIN_PASSWORD` protects the admin dashboard.
20
 
21
+ The Docker runtime uses UID 1000 and port 7860. Set `RUNTIME_DIR` to a writable durable mount if configuration, metrics, feedback and signed embeddings should survive restarts. A folder named `/data` alone does not guarantee persistent storage.
22
 
23
+ ## Startup and request behavior
24
 
25
+ - `/health/live` and `/config` can respond while knowledge initialization runs in the background.
26
+ - Keyword retrieval initializes locally first; semantic retrieval joins when a valid cache loads or embeddings finish. Semantic failure leaves local retrieval available.
27
+ - `/health/ready` returns 503 when retrieval is unavailable, maintenance is on, or the production origin token is missing. It distinguishes missing model credentials from a fully configured service.
28
+ - `/agent` and its diagnostic subpaths, `/search`, and `/feedback` require the origin token in production. Student browsers call the Worker; the Worker adds this token server-side.
29
+ - The 512 KiB default whole-body limit covers bounded Unicode histories and search contexts; request models still enforce individual field limits.
30
+ - Generated answer HTML is sanitized. Credentials stay out of student HTML, provider request URLs and operational query logs.
31
+ - Signed semantic caches are invalidated by KB content and indexing settings. Older cache schemas rebuild once; modified or unsigned caches are ignored.
32
+ - Admin logout revokes persisted sessions; write diagnostics are explicit POST actions. The Worker analytics token contract remains unchanged and needs verification against your Worker source.
33
 
34
+ ## Validation
 
 
 
 
 
 
 
 
 
35
 
36
  ```bash
37
+ python -m pip install -r requirements-dev.txt
38
+ python -m pip check
39
  python -m compileall -q app.py src tests
40
  pytest -q
41
  ```
42
 
43
+ The supplied offline tests/harnesses document their mocks and skipped integration checks. They do not replace full dependency, browser, or live-provider testing. This review did not update the supplied dependency pins; validate compatible security updates and freeze the resolved dependency set in staging.
44
+
45
+ See `DEPLOYMENT_GUIDE.md` and the complete package's `AUDIT_REPORT.md` for rollout instructions and limitations. The supplied files do not include the actual Worker or D1 schema.
app.py CHANGED
@@ -1,209 +1,283 @@
1
- """LibBee FastAPI application for the private Hugging Face origin."""
2
-
3
- import asyncio
4
- import hmac
5
- import logging
6
- from contextlib import asynccontextmanager
7
-
8
- from fastapi import FastAPI, Request
9
- from fastapi.middleware.cors import CORSMiddleware
10
- from fastapi.responses import JSONResponse, Response
11
-
12
- from src.config import LIBBEE_VERSION, get_settings
13
- from src.services.metrics_service import MetricsService
14
- from src.services.rag_service import RAGService
15
-
16
  logging.basicConfig(level=logging.INFO)
17
- logger = logging.getLogger(__name__)
18
- settings = get_settings()
19
- rag_service = RAGService()
20
- metrics_service = MetricsService(settings.metrics_path)
 
 
 
21
  _agent_slots = asyncio.Semaphore(settings.max_concurrent_agent_requests)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- # Hugging Face displays a Space inside an iframe whose parent is
24
- # huggingface.co. Only the public status pages may be framed there. Admin and
25
- # API routes remain protected against framing/clickjacking.
26
- _HF_PREVIEW_PATHS = {"/", "/health/live", "/health/ready"}
27
- _HF_FRAME_ANCESTORS = "frame-ancestors 'self' https://huggingface.co https://*.huggingface.co"
28
-
29
-
30
- def get_rag_service() -> RAGService:
31
- return rag_service
32
-
33
-
34
- def get_metrics_service() -> MetricsService:
35
- return metrics_service
36
-
37
-
38
- def _runtime_config() -> dict:
39
- from src.services.runtime_store import JsonRuntimeStore
40
-
41
- defaults = {
42
- "maintenance_mode": settings.maintenance_mode,
43
- "maintenance_message": settings.maintenance_message,
44
- "welcome_message": "Hi! I'm LibBee, the Khalifa University Library AI Assistant.",
45
- "announcement": "",
46
- "max_results": settings.max_results,
47
- }
48
  try:
49
- return JsonRuntimeStore(settings.config_path, default=defaults).load()
50
- except Exception:
51
- return defaults
52
-
53
-
54
- async def _metrics_flush_loop() -> None:
55
- while True:
56
- await asyncio.sleep(30)
57
- try:
58
- await metrics_service.flush()
59
- except Exception as exc:
60
- logger.warning("Metrics flush error: %s", exc)
 
61
 
62
 
63
  @asynccontextmanager
64
  async def lifespan(_app: FastAPI):
65
- from src.services.staff_service import build_staff_index
66
-
 
 
67
  try:
68
- build_staff_index()
69
- except Exception as exc:
70
- logger.error("Staff index build failed: %s", exc)
71
- if settings.openai_api_key:
 
 
 
72
  try:
73
- await rag_service.initialize(openai_api_key=settings.openai_api_key)
74
  except Exception as exc:
75
- logger.error("RAG initialization failed: %s", exc, exc_info=True)
76
- else:
77
- logger.warning("OPENAI_API_KEY not set; RAG is disabled")
78
- flush_task = asyncio.create_task(_metrics_flush_loop())
79
- yield
80
- flush_task.cancel()
81
- try:
82
- await metrics_service.flush()
83
- except Exception:
84
- pass
85
-
86
-
87
- app = FastAPI(
88
- title="LibBee - KU Library AI",
89
- description="Private origin API for the Khalifa University Library AI Assistant",
90
- version=LIBBEE_VERSION,
91
- lifespan=lifespan,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  docs_url=None if settings.environment == "production" else "/docs",
93
- redoc_url=None,
94
- )
95
-
96
- app.add_middleware(
97
- CORSMiddleware,
98
- allow_origins=settings.cors_origins,
99
- allow_credentials=False,
100
- allow_methods=["GET", "POST", "OPTIONS"],
101
- allow_headers=["Content-Type", "X-LibBee-Origin-Token", "X-Request-ID", "X-LibBee-Canary"],
 
102
  max_age=3600,
103
  )
104
-
105
-
106
- @app.middleware("http")
107
- async def secure_origin(request: Request, call_next):
108
- path = request.url.path
109
- protected = path in {"/agent", "/agent/rag-status", "/search", "/feedback"}
110
- acquired = False
111
-
112
- if path.startswith("/admin") and request.method not in {"GET", "HEAD", "OPTIONS"}:
113
- fetch_site = request.headers.get("sec-fetch-site", "")
114
- if fetch_site and fetch_site not in {"same-origin", "none"}:
115
- return JSONResponse(status_code=403, content={"detail": "Cross-site admin request denied."})
116
-
117
- if request.method in {"POST", "PUT", "PATCH"}:
118
- length = request.headers.get("content-length")
119
- if length and length.isdigit() and int(length) > 32_768:
120
- return JSONResponse(status_code=413, content={"detail": "Request body too large."})
121
-
122
- if protected:
123
- supplied = request.headers.get("x-libbee-origin-token", "")
124
- configured = settings.origin_token
125
- local_insecure = settings.environment in {"development", "test"} and not configured
126
- if not local_insecure and (not configured or not hmac.compare_digest(supplied, configured)):
127
- return JSONResponse(status_code=401, content={"detail": "Origin authentication required."})
128
-
129
- runtime = _runtime_config()
130
- if runtime.get("maintenance_mode") and request.headers.get("x-libbee-canary") != "1":
131
- return JSONResponse(
132
- status_code=503,
133
- content={"detail": str(runtime.get("maintenance_message") or settings.maintenance_message)[:300]},
134
- )
135
-
136
- if path == "/agent":
137
- try:
138
- await asyncio.wait_for(_agent_slots.acquire(), timeout=0.25)
139
- acquired = True
140
- except TimeoutError:
141
- return JSONResponse(status_code=503, content={"detail": "LibBee is busy. Please retry shortly."})
142
-
143
- try:
144
- response = await call_next(request)
145
- except Exception as exc:
146
- logger.exception("Unhandled application error: %s", exc)
147
- metrics_service.incr_bucket("errors", "unhandled_exception")
148
- response = JSONResponse(status_code=500, content={"detail": "Unexpected server error."})
149
- finally:
150
- if acquired:
151
- _agent_slots.release()
152
-
153
- response.headers["X-Content-Type-Options"] = "nosniff"
154
- response.headers["Referrer-Policy"] = "no-referrer"
155
- response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=(), payment=()"
156
- if path in _HF_PREVIEW_PATHS:
157
- # X-Frame-Options cannot express an allowlist. Omit it only on these
158
- # harmless GET endpoints and use CSP's exact parent-origin allowlist.
159
- response.headers["Content-Security-Policy"] = _HF_FRAME_ANCESTORS
160
- else:
161
- response.headers["X-Frame-Options"] = "SAMEORIGIN" if path.startswith("/admin") else "DENY"
162
- response.headers["Content-Security-Policy"] = (
163
- "frame-ancestors 'self'" if path.startswith("/admin") else "frame-ancestors 'none'"
164
- )
165
- if protected or path.startswith("/admin"):
166
- response.headers["Cache-Control"] = "no-store"
167
- return response
168
-
169
-
170
- from src.api import admin, agent, feedback, search # noqa: E402
171
-
172
- app.include_router(agent.router, prefix="/agent", tags=["Agent"])
173
- app.include_router(search.router, prefix="/search", tags=["Search"])
174
- app.include_router(admin.router, prefix="/admin", tags=["Admin"])
175
- app.include_router(feedback.router, prefix="/feedback", tags=["Feedback"])
176
-
177
-
178
- @app.get("/")
179
- @app.get("/health/live")
180
- def health_live():
181
- return {"status": "ok", "version": LIBBEE_VERSION, "service": "LibBee private origin"}
182
-
183
-
184
- @app.get("/health/ready")
185
  def health_ready():
186
  runtime = _runtime_config()
187
- return {
188
- "status": "ok" if not runtime.get("maintenance_mode") else "maintenance",
 
 
 
 
 
 
 
 
 
 
 
 
189
  "version": LIBBEE_VERSION,
190
- "rag_ready": rag_service.is_ready(),
 
 
191
  "maintenance_mode": bool(runtime.get("maintenance_mode")),
192
- }
193
-
194
-
195
  @app.get("/config")
196
- @app.get("/admin/public-config")
197
  def public_config():
198
- runtime = _runtime_config()
199
- return {
200
- "welcome_message": str(runtime.get("welcome_message", ""))[:500],
201
- "announcement": str(runtime.get("announcement", ""))[:500],
202
- "maintenance_mode": bool(runtime.get("maintenance_mode")),
203
- "maintenance_message": str(runtime.get("maintenance_message", ""))[:300],
204
- }
205
-
206
-
207
- @app.get("/favicon.ico", include_in_schema=False)
208
- def favicon():
209
- return Response(status_code=204)
 
1
+ """LibBee FastAPI application for the private Hugging Face origin."""
2
+
3
+ import asyncio
4
+ import hmac
5
+ import logging
6
+ from contextlib import asynccontextmanager, suppress
7
+
8
+ from fastapi import FastAPI, Request
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from fastapi.responses import JSONResponse, Response
11
+
12
+ from src.config import LIBBEE_VERSION, get_settings
13
+ from src.services.metrics_service import MetricsService
14
+ from src.services.rag_service import RAGService
15
+
16
  logging.basicConfig(level=logging.INFO)
17
+ # HTTPX INFO logs include complete request URLs, including research queries.
18
+ logging.getLogger("httpx").setLevel(logging.WARNING)
19
+ logging.getLogger("httpcore").setLevel(logging.WARNING)
20
+ logger = logging.getLogger(__name__)
21
+ settings = get_settings()
22
+ rag_service = RAGService()
23
+ metrics_service = MetricsService(settings.metrics_path)
24
  _agent_slots = asyncio.Semaphore(settings.max_concurrent_agent_requests)
25
+ _startup_state = "initializing"
26
+
27
+ # Hugging Face displays a Space inside an iframe whose parent is
28
+ # huggingface.co. Only the public status pages may be framed there. Admin and
29
+ # API routes remain protected against framing/clickjacking.
30
+ _HF_PREVIEW_PATHS = {"/", "/health/live", "/health/ready"}
31
+ _HF_FRAME_ANCESTORS = "frame-ancestors 'self' https://huggingface.co https://*.huggingface.co"
32
+
33
+
34
+ def get_rag_service() -> RAGService:
35
+ return rag_service
36
+
37
+
38
+ def get_metrics_service() -> MetricsService:
39
+ return metrics_service
40
+
41
+
42
+ def _runtime_config() -> dict:
43
+ from src.services.runtime_store import JsonRuntimeStore
44
+
45
+ defaults = settings.runtime_defaults
46
+ try:
47
+ return JsonRuntimeStore(settings.config_path, default=defaults).load()
48
+ except Exception:
49
+ return defaults
50
+
51
+
52
+ async def _metrics_flush_loop() -> None:
53
+ while True:
54
+ await asyncio.sleep(30)
55
+ try:
56
+ await metrics_service.flush()
57
+ except Exception as exc:
58
+ logger.warning("Metrics flush error: %s", exc)
59
+
60
+
61
+ async def _initialize_services() -> None:
62
+ global _startup_state
63
+ from src.services.staff_service import build_staff_index
64
 
65
+ _startup_state = "initializing"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  try:
67
+ await asyncio.to_thread(build_staff_index)
68
+ except Exception as exc:
69
+ logger.error("Staff index build failed: %s", exc)
70
+ try:
71
+ # Local lexical retrieval can initialize without model credentials;
72
+ # the RAG service upgrades to dense retrieval when they are available.
73
+ await rag_service.initialize(openai_api_key=settings.openai_api_key)
74
+ _startup_state = "ready" if rag_service.is_ready() else "failed"
75
+ except asyncio.CancelledError:
76
+ raise
77
+ except Exception as exc:
78
+ _startup_state = "failed"
79
+ logger.error("RAG initialization failed: %s", exc, exc_info=True)
80
 
81
 
82
  @asynccontextmanager
83
  async def lifespan(_app: FastAPI):
84
+ # Do not hold the HTTP listener closed while fetching remote embeddings.
85
+ # /health/ready reports actual readiness independently of /health/live.
86
+ startup_task = asyncio.create_task(_initialize_services())
87
+ flush_task = asyncio.create_task(_metrics_flush_loop())
88
  try:
89
+ yield
90
+ finally:
91
+ for task in (startup_task, flush_task):
92
+ task.cancel()
93
+ for task in (startup_task, flush_task):
94
+ with suppress(asyncio.CancelledError):
95
+ await task
96
  try:
97
+ await metrics_service.flush()
98
  except Exception as exc:
99
+ logger.warning("Final metrics flush failed: %s", exc)
100
+
101
+
102
+ class RequestBodyLimitMiddleware:
103
+ """Bound received bytes, including chunked bodies without Content-Length."""
104
+
105
+ def __init__(self, app, max_bytes: int):
106
+ self.app = app
107
+ self.max_bytes = max_bytes
108
+
109
+ async def __call__(self, scope, receive, send):
110
+ if scope["type"] != "http" or scope.get("method") not in {"POST", "PUT", "PATCH"}:
111
+ await self.app(scope, receive, send)
112
+ return
113
+
114
+ async def reject():
115
+ response = JSONResponse(status_code=413, content={"detail": "Request body too large."})
116
+ await response(scope, receive, send)
117
+
118
+ lengths = [value for name, value in scope.get("headers", []) if name.lower() == b"content-length"]
119
+ if any(value.isdigit() and int(value) > self.max_bytes for value in lengths):
120
+ await reject()
121
+ return
122
+ chunks = []
123
+ total = 0
124
+ while True:
125
+ message = await receive()
126
+ if message["type"] == "http.disconnect":
127
+ return
128
+ chunk = message.get("body", b"")
129
+ total += len(chunk)
130
+ if total > self.max_bytes:
131
+ await reject()
132
+ return
133
+ chunks.append(chunk)
134
+ if not message.get("more_body", False):
135
+ break
136
+ body = b"".join(chunks)
137
+ delivered = False
138
+
139
+ async def replay():
140
+ nonlocal delivered
141
+ if not delivered:
142
+ delivered = True
143
+ return {"type": "http.request", "body": body, "more_body": False}
144
+ return await receive()
145
+
146
+ await self.app(scope, replay, send)
147
+
148
+
149
+ app = FastAPI(
150
+ title="LibBee - KU Library AI",
151
+ description="Private origin API for the Khalifa University Library AI Assistant",
152
+ version=LIBBEE_VERSION,
153
+ lifespan=lifespan,
154
  docs_url=None if settings.environment == "production" else "/docs",
155
+ openapi_url=None if settings.environment == "production" else "/openapi.json",
156
+ redoc_url=None,
157
+ )
158
+
159
+ app.add_middleware(
160
+ CORSMiddleware,
161
+ allow_origins=settings.cors_origins,
162
+ allow_credentials=False,
163
+ allow_methods=["GET", "POST", "OPTIONS"],
164
+ allow_headers=["Content-Type", "X-LibBee-Origin-Token", "X-Request-ID", "X-LibBee-Canary"],
165
  max_age=3600,
166
  )
167
+ app.add_middleware(RequestBodyLimitMiddleware, max_bytes=settings.max_request_body_bytes)
168
+
169
+
170
+ @app.middleware("http")
171
+ async def secure_origin(request: Request, call_next):
172
+ path = request.url.path
173
+ protected = any(path == prefix or path.startswith(prefix + "/") for prefix in ("/agent", "/search", "/feedback"))
174
+ acquired = False
175
+
176
+ if path.startswith("/admin") and request.method not in {"GET", "HEAD", "OPTIONS"}:
177
+ fetch_site = request.headers.get("sec-fetch-site", "")
178
+ if fetch_site and fetch_site not in {"same-origin", "none"}:
179
+ return JSONResponse(status_code=403, content={"detail": "Cross-site admin request denied."})
180
+
181
+ # CORS preflight contains no credentials or application body. The CORS
182
+ # middleware checks allowed origins, methods and headers before responding.
183
+ if protected and request.method != "OPTIONS":
184
+ supplied = request.headers.get("x-libbee-origin-token", "")
185
+ configured = settings.origin_token
186
+ local_insecure = settings.environment in {"development", "test"} and not configured
187
+ if not local_insecure and (not configured or not hmac.compare_digest(supplied.encode("utf-8"), configured.encode("utf-8"))):
188
+ return JSONResponse(status_code=401, content={"detail": "Origin authentication required."})
189
+
190
+ runtime = _runtime_config()
191
+ if runtime.get("maintenance_mode") and request.headers.get("x-libbee-canary") != "1":
192
+ return JSONResponse(
193
+ status_code=503,
194
+ content={"detail": str(runtime.get("maintenance_message") or settings.maintenance_message)[:300]},
195
+ )
196
+
197
+ if path == "/agent":
198
+ try:
199
+ await asyncio.wait_for(_agent_slots.acquire(), timeout=0.25)
200
+ acquired = True
201
+ except TimeoutError:
202
+ return JSONResponse(status_code=503, content={"detail": "LibBee is busy. Please retry shortly."})
203
+
204
+ try:
205
+ response = await call_next(request)
206
+ except Exception as exc:
207
+ logger.exception("Unhandled application error: %s", exc)
208
+ metrics_service.incr_bucket("errors", "unhandled_exception")
209
+ response = JSONResponse(status_code=500, content={"detail": "Unexpected server error."})
210
+ finally:
211
+ if acquired:
212
+ _agent_slots.release()
213
+
214
+ response.headers["X-Content-Type-Options"] = "nosniff"
215
+ response.headers["Referrer-Policy"] = "no-referrer"
216
+ response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=(), payment=()"
217
+ if path in _HF_PREVIEW_PATHS:
218
+ # X-Frame-Options cannot express an allowlist. Omit it only on these
219
+ # harmless GET endpoints and use CSP's exact parent-origin allowlist.
220
+ response.headers["Content-Security-Policy"] = _HF_FRAME_ANCESTORS
221
+ else:
222
+ response.headers["X-Frame-Options"] = "SAMEORIGIN" if path.startswith("/admin") else "DENY"
223
+ response.headers["Content-Security-Policy"] = (
224
+ "frame-ancestors 'self'" if path.startswith("/admin") else "frame-ancestors 'none'"
225
+ )
226
+ if protected or path.startswith("/admin"):
227
+ response.headers["Cache-Control"] = "no-store"
228
+ return response
229
+
230
+
231
+ from src.api import admin, agent, feedback, search # noqa: E402
232
+
233
+ app.include_router(agent.router, prefix="/agent", tags=["Agent"])
234
+ app.include_router(search.router, prefix="/search", tags=["Search"])
235
+ app.include_router(admin.router, prefix="/admin", tags=["Admin"])
236
+ app.include_router(feedback.router, prefix="/feedback", tags=["Feedback"])
237
+
238
+
239
+ @app.get("/")
240
+ @app.get("/health/live")
241
+ def health_live():
242
+ return {"status": "ok", "version": LIBBEE_VERSION, "service": "LibBee private origin"}
243
+
244
+
245
+ @app.get("/health/ready")
 
 
246
  def health_ready():
247
  runtime = _runtime_config()
248
+ rag_ready = rag_service.is_ready()
249
+ origin_ready = bool(settings.origin_token) or settings.environment in {"development", "test"}
250
+ if runtime.get("maintenance_mode"):
251
+ status = "maintenance"
252
+ elif not origin_ready:
253
+ status = "misconfigured"
254
+ elif not rag_ready:
255
+ status = "initializing" if _startup_state == "initializing" else "unavailable"
256
+ elif not settings.openai_api_key:
257
+ status = "degraded"
258
+ else:
259
+ status = "ok"
260
+ return JSONResponse(status_code=200 if status in {"ok", "degraded"} else 503, content={
261
+ "status": status,
262
  "version": LIBBEE_VERSION,
263
+ "rag_ready": rag_ready,
264
+ "retrieval_mode": rag_service.get_stats().get("retrieval_mode", "unavailable"),
265
+ "model_configured": bool(settings.openai_api_key),
266
  "maintenance_mode": bool(runtime.get("maintenance_mode")),
267
+ })
268
+
269
+
270
  @app.get("/config")
 
271
  def public_config():
272
+ runtime = _runtime_config()
273
+ return {
274
+ "welcome_message": str(runtime.get("welcome_message", ""))[:500],
275
+ "announcement": str(runtime.get("announcement", ""))[:500],
276
+ "maintenance_mode": bool(runtime.get("maintenance_mode")),
277
+ "maintenance_message": str(runtime.get("maintenance_message", ""))[:300],
278
+ }
279
+
280
+
281
+ @app.get("/favicon.ico", include_in_schema=False)
282
+ def favicon():
283
+ return Response(status_code=204)
requirements-dev.txt CHANGED
@@ -1,3 +1,3 @@
1
- -r requirements.txt
2
- pytest==8.3.5
3
- ruff==0.11.8
 
1
+ -r requirements.txt
2
+ pytest==8.3.5
3
+ ruff==0.11.8
requirements.txt CHANGED
@@ -1,16 +1,16 @@
1
- fastapi==0.115.12
2
- uvicorn[standard]==0.34.2
3
- python-multipart==0.0.20
4
- pydantic==2.11.4
5
- pydantic-settings==2.9.1
6
- langchain==0.3.25
7
- langchain-openai==0.3.16
8
- langchain-anthropic==0.3.13
9
- langchain-community==0.3.24
10
- anthropic==0.51.0
11
- faiss-cpu==1.11.0
12
- rank-bm25==0.2.2
13
- httpx==0.28.1
14
- numpy==2.2.5
15
- openai==1.79.0
16
- cachetools==5.5.2
 
1
+ fastapi==0.115.12
2
+ uvicorn[standard]==0.34.2
3
+ python-multipart==0.0.20
4
+ pydantic==2.11.4
5
+ pydantic-settings==2.9.1
6
+ langchain==0.3.25
7
+ langchain-openai==0.3.16
8
+ langchain-anthropic==0.3.13
9
+ langchain-community==0.3.24
10
+ anthropic==0.51.0
11
+ faiss-cpu==1.11.0
12
+ rank-bm25==0.2.2
13
+ httpx==0.28.1
14
+ numpy==2.2.5
15
+ openai==1.79.0
16
+ cachetools==5.5.2