Spaces:
Running
Running
Donne120
Claude Opus 5
Fix generation outage: retired Groq model and anthropic SDK signature
107a904 Download app.py from StudentCompanion/alu-chatbot: direct link, hf CLI and curl.
- Browser
- Download file 33.1 kB
-
https://huggingface.co/spaces/StudentCompanion/alu-chatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/StudentCompanion/alu-chatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/StudentCompanion/alu-chatbot/resolve/main/app.py
33.1 kB
| import os | |
| # Hugging Face model caches must be set BEFORE importing anything that loads | |
| # transformers / sentence-transformers (which happens transitively via main.py). | |
| os.environ["TRANSFORMERS_CACHE"] = "/tmp/model_cache" | |
| os.environ["HF_HOME"] = "/tmp/model_cache" | |
| os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/tmp/model_cache" | |
| os.environ["PYTHONUNBUFFERED"] = "1" | |
| print("=== STARTUP: Beginning application initialization ===") | |
| print(f"=== STARTUP: PORT environment variable: {os.environ.get('PORT')} ===") | |
| # These imports are deliberately late β see env setup above. # noqa: E402 | |
| from main import app # noqa: E402 | |
| from main import ( # noqa: E402 | |
| conversation_memory, | |
| document_processor, | |
| retrieval_engine, | |
| groq_fallback, | |
| ) | |
| from analytics.conversation_analytics import ConversationAnalytics # noqa: E402 | |
| # Phase-2 services | |
| from claude_engine import claude_engine # noqa: E402 | |
| from opportunities_service import opportunities_service # noqa: E402 | |
| from sheet_sync import SheetSync # noqa: E402 | |
| import org_sheet_sync # noqa: E402 (per-organization Sheet sync) | |
| from nvidia_fallback import nvidia_fallback # noqa: E402 (free NVIDIA NIM fallback) | |
| from bedrock_fallback import bedrock_fallback # noqa: E402 (Claude via AWS Bedrock) | |
| # Aurora data layer (structured product data + admin dashboard). Separate from | |
| # the RAG path above; see db.py / admin_routes.py and schema.sql. | |
| import db # noqa: E402 | |
| from admin_routes import ( # noqa: E402,E501 | |
| router as admin_router, | |
| public_router as data_router, | |
| current_org, | |
| current_org_any_user, | |
| ADMIN_ORG_DOMAIN, | |
| _org_id_for_domain, | |
| ) | |
| import org_registry # noqa: E402 | |
| from email_briefing import router as email_router # noqa: E402 | |
| import email_qa # noqa: E402 (chat answers from the student's own inbox) | |
| from fastapi import UploadFile, File, Form, HTTPException, Depends, Request # noqa: E402,E501 | |
| from fastapi.responses import StreamingResponse # noqa: E402 | |
| from pydantic import Field # noqa: E402 | |
| from auth import require_user, require_admin, require_admin_or_token, ADMIN_EMAILS # noqa: E402,E501 | |
| from main import limiter # noqa: E402 (shared slowapi Limiter, keyed by client IP) | |
| from pydantic import BaseModel # noqa: E402 | |
| from typing import Any, Dict, List, Optional # noqa: E402 | |
| import asyncio # noqa: E402 | |
| import json as _json # noqa: E402 | |
| import logging as _logging # noqa: E402 | |
| _sync_logger = _logging.getLogger("sheet_sync") | |
| # --------------------------------------------------------------------------- | |
| # Google Sheet β vector store integration | |
| # --------------------------------------------------------------------------- | |
| # Knowledge entries from the ALU Google Sheet are pulled in via Apps Script | |
| # and upserted into the existing Chroma collection so the Claude RAG path | |
| # treats them like any other indexed document. | |
| sheet_sync = SheetSync(retrieval_engine) | |
| # One-time migration: move the legacy flat ADMIN_EMAILS env var into the new | |
| # per-organization organization_admins table (see db.py's docstring on | |
| # seed_admin_emails_from_env_once). No-ops instantly if that table already | |
| # has any rows, or the data layer isn't configured β safe to leave this call | |
| # here permanently rather than remove it after the first successful deploy. | |
| db.seed_admin_emails_from_env_once(ADMIN_EMAILS, ADMIN_ORG_DOMAIN) | |
| # Mount the Aurora-backed admin/data-layer routes. Self-contained in | |
| # admin_routes.py with its own Firebase-derived tenancy guard. We mount each | |
| # router under BOTH the bare and /api-prefixed base paths because the v0 | |
| # dashboard's exact base URL isn't pinned down β this way it works whether it | |
| # calls /admin/* or /api/admin/*. | |
| # admin_router -> /admin/* and /api/admin/* (console) | |
| # data_router -> /* and /api/db/* (student feed; /api/db avoids | |
| # colliding with the legacy Tavily /api/opportunities) | |
| app.include_router(admin_router, prefix="/admin") | |
| app.include_router(admin_router, prefix="/api/admin") | |
| app.include_router(data_router) | |
| app.include_router(data_router, prefix="/api/db") | |
| # Gmail-powered spoken email briefing (see email_briefing.py). All routes are | |
| # Firebase-authed except the Google OAuth callback, which authenticates via a | |
| # signed state parameter instead. | |
| app.include_router(email_router, prefix="/api/email") | |
| SHEET_POLL_INTERVAL_SECONDS = int(os.getenv("SHEET_POLL_INTERVAL_SECONDS", "900")) # 15 min | |
| SHEET_REFRESH_TOKEN = os.getenv("SHEET_REFRESH_TOKEN", "") | |
| async def _run_all_syncs(force: bool = False) -> None: | |
| """Run the legacy single-Sheet sync and every per-organization sync. | |
| The two are independent on purpose: the legacy KNOWLEDGE_JSON_URL sync | |
| feeds the global collection, while org_sheet_sync gives each university | |
| its own Sheet feeding its own collection. Either can be absent β a | |
| deployment with no KNOWLEDGE_JSON_URL still syncs organizations, and vice | |
| versa. | |
| """ | |
| if sheet_sync.enabled: | |
| try: | |
| result = await asyncio.to_thread(sheet_sync.refresh, force) | |
| _sync_logger.info("[sheet_sync] %s", result.to_dict()) | |
| except Exception as e: | |
| _sync_logger.warning("[sheet_sync] failed: %s", e) | |
| try: | |
| alu_org_id = _org_id_for_domain(ADMIN_ORG_DOMAIN) | |
| except Exception: | |
| alu_org_id = None # Aurora unreachable; per-org sync will report per row | |
| try: | |
| summary = await asyncio.to_thread( | |
| org_sheet_sync.sync_all_organizations, alu_org_id, force | |
| ) | |
| if summary.get("organizations"): | |
| _sync_logger.info( | |
| "[org_sheet_sync] synced=%s failed=%s", | |
| summary.get("synced"), summary.get("failed"), | |
| ) | |
| except Exception as e: | |
| _sync_logger.warning("[org_sheet_sync] failed: %s", e) | |
| async def _initial_sheet_sync() -> None: | |
| await _run_all_syncs(force=False) | |
| async def _poll_loop() -> None: | |
| while True: | |
| await asyncio.sleep(SHEET_POLL_INTERVAL_SECONDS) | |
| # Previously this loop only started when the legacy sync was | |
| # enabled, so a deployment without KNOWLEDGE_JSON_URL would never | |
| # poll at all. It now runs regardless of which syncs are | |
| # configured. | |
| await _run_all_syncs(force=False) | |
| asyncio.create_task(_poll_loop()) | |
| # --------------------------------------------------------------------------- | |
| # Citation helper β shared by streaming and non-streaming chat endpoints. | |
| # Promotes `source_url` (set by sheet_sync) ahead of the legacy `source` | |
| # string so the frontend gets a real ALU link to render. | |
| # --------------------------------------------------------------------------- | |
| def _build_sources(context_docs: Optional[List[Any]]) -> List[Dict[str, Any]]: | |
| sources: List[Dict[str, Any]] = [] | |
| seen: set = set() | |
| for doc in (context_docs or [])[:5]: | |
| meta = getattr(doc, "metadata", None) or {} | |
| url = (meta.get("source_url") or "").strip() | |
| legacy_source = (meta.get("source") or "").strip() | |
| # Prefer a real URL; fall back to the legacy free-text source string. | |
| link = url if url.startswith("http") else ( | |
| legacy_source if legacy_source.startswith("http") else "" | |
| ) | |
| title = (meta.get("title") or "ALU Knowledge Base").strip() | |
| dedupe_key = (title, link or legacy_source) | |
| if dedupe_key in seen: | |
| continue | |
| seen.add(dedupe_key) | |
| sources.append( | |
| { | |
| "title": title, | |
| "source": link or legacy_source or "ALU Knowledge Base", | |
| "url": link, | |
| "department": meta.get("department") or "", | |
| "doc_id": meta.get("doc_id"), | |
| "origin": meta.get("origin") or "uploaded", | |
| } | |
| ) | |
| if len(sources) >= 3: | |
| break | |
| return sources | |
| # --------------------------------------------------------------------------- | |
| # Existing routes from earlier app.py (kept verbatim) | |
| # --------------------------------------------------------------------------- | |
| # NOTE: /api/alu-events is defined in main.py, which registers first and wins | |
| # (app.py does `from main import app`). A handler here would be dead code, so | |
| # it's intentionally omitted. See the analytics-dashboard note in main.py for | |
| # the same first-registered-wins gotcha. | |
| async def get_analytics_dashboard(admin=Depends(require_admin)): | |
| """Get analytics dashboard data (admin only).""" | |
| try: | |
| if not conversation_memory: | |
| raise HTTPException( | |
| status_code=503, detail="Analytics temporarily unavailable" | |
| ) | |
| analytics = ConversationAnalytics(conversation_memory) | |
| dashboard_data = analytics.generate_dashboard_data() | |
| return dashboard_data | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| print(f"Error generating analytics dashboard: {e}") | |
| raise HTTPException( | |
| status_code=500, detail="Could not generate analytics" | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Shared org-engine resolution. | |
| # | |
| # Every path that reads from or writes to the knowledge base must go through | |
| # here, so a request can only ever touch its own organization's collection. | |
| # Ingestion needs this as much as retrieval does: a university admin uploading | |
| # a handbook must write into their own collection, never the shared one. | |
| # --------------------------------------------------------------------------- | |
| def _engine_for_org(org: str): | |
| """Return the retrieval engine owning `org`'s collection. | |
| ALU's UUID maps back to the global engine (unchanged behaviour); every | |
| other organization gets its own. Raises 503 rather than silently falling | |
| back to the shared engine β for a write, a wrong-collection fallback is a | |
| cross-tenant leak, so failing loudly is the safer outcome. | |
| """ | |
| try: | |
| alu_org_id = _org_id_for_domain(ADMIN_ORG_DOMAIN) | |
| except HTTPException: | |
| alu_org_id = None # Aurora unreachable; org_registry handles the fallthrough | |
| try: | |
| engine = org_registry.get_engine_for_org(org, alu_organization_id=alu_org_id) | |
| except Exception as e: | |
| print(f"[FAIL] Could not resolve retrieval engine for org {org}: {e}") | |
| raise HTTPException(status_code=503, detail="Knowledge base unavailable") | |
| if engine is None: | |
| raise HTTPException(status_code=503, detail="Knowledge base unavailable") | |
| return engine | |
| # --------------------------------------------------------------------------- | |
| # Phase 2: Document management routes | |
| # Frontend uploads PDF/DOCX/TXT here. The existing DocumentProcessor + | |
| # RetrievalEngine handle extraction, chunking, embedding, and indexing. | |
| # --------------------------------------------------------------------------- | |
| async def upload_document( | |
| request: Request, | |
| file: UploadFile = File(...), | |
| title: Optional[str] = Form(None), | |
| admin=Depends(require_admin), | |
| org: str = Depends(current_org), | |
| ): | |
| """ | |
| Accept a PDF / DOCX / TXT / MD file, extract text, embed and index it | |
| into the uploading admin's OWN organization's vector store. Returns the | |
| new document id. Admin only β uploads write directly into the knowledge | |
| base students are answered from. | |
| `org` is the one organization this admin is authorized to administer | |
| (admin_routes.current_org). Before this, the route wrote to the global | |
| engine regardless of who called it, so a university admin's handbook | |
| landed in the shared collection and could be used to answer students at | |
| other universities β a cross-tenant leak through the ingestion path. | |
| """ | |
| if document_processor is None: | |
| raise HTTPException(status_code=503, detail="Document pipeline unavailable") | |
| org_engine = _engine_for_org(org) | |
| try: | |
| doc_id = await document_processor.process_document(file, title=title, source="frontend-upload") | |
| org_engine.update_vector_store(doc_id) | |
| return {"id": doc_id, "status": "indexed"} | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| print(f"[FAIL] Document upload error: {e}") | |
| raise HTTPException(status_code=500, detail="Upload failed") | |
| async def list_documents(admin=Depends(require_admin)): | |
| """List all indexed documents (metadata only β no content).""" | |
| if document_processor is None: | |
| return {"documents": []} | |
| docs = document_processor.list_documents() | |
| # Strip filesystem paths before returning to clients. | |
| sanitized: List[Dict[str, Any]] = [] | |
| for d in docs: | |
| sanitized.append( | |
| { | |
| "id": d.get("id"), | |
| "title": d.get("title"), | |
| "filename": d.get("filename"), | |
| "content_type": d.get("content_type"), | |
| "source": d.get("source"), | |
| "length": d.get("length"), | |
| "upload_time": d.get("upload_time"), | |
| } | |
| ) | |
| return {"documents": sanitized} | |
| async def delete_document( | |
| doc_id: str, | |
| admin=Depends(require_admin), | |
| org: str = Depends(current_org), | |
| ): | |
| """Delete a document and remove its chunks from the admin's OWN | |
| organization's vector store. Admin only. | |
| Scoped for the same reason as upload: removing chunks from the global | |
| collection when the caller administers a different organization would | |
| delete another university's content. | |
| """ | |
| if document_processor is None: | |
| raise HTTPException(status_code=503, detail="Document pipeline unavailable") | |
| _engine_for_org(org).remove_document(doc_id) | |
| ok = document_processor.delete_document(doc_id) | |
| if not ok: | |
| raise HTTPException(status_code=404, detail="Document not found") | |
| return {"id": doc_id, "status": "deleted"} | |
| # --------------------------------------------------------------------------- | |
| # Phase 2: Claude-powered chat (RAG over uploaded docs) | |
| # This sits ALONGSIDE the existing /api/chat. The frontend can opt in. | |
| # --------------------------------------------------------------------------- | |
| class ClaudeChatRequest(BaseModel): | |
| # Bounded to keep a single request from running up unbounded LLM cost. | |
| message: str = Field(min_length=1, max_length=4000) | |
| history: List[Dict[str, str]] = Field(default_factory=list, max_length=40) | |
| options: Optional[Dict[str, Any]] = None | |
| async def chat_claude( | |
| request: Request, | |
| body: ClaudeChatRequest, | |
| user=Depends(require_user), | |
| org: str = Depends(current_org_any_user), | |
| ): | |
| """ | |
| RAG-style chat: retrieve from the vector store, then have Claude write | |
| the answer grounded in the retrieved context. | |
| Falls back to Groq if Claude is unavailable, and returns an error string | |
| only as a last resort. | |
| `org` (the caller's organization_id, resolved from their verified email | |
| domain β see admin_routes.current_org_any_user) selects which | |
| organization's retrieval engine answers this request. ALU's UUID maps | |
| back to the same global `retrieval_engine` this route always used, so | |
| ALU's behavior is unchanged; any other organization gets its own engine, | |
| reading only its own documents (see org_registry.py). | |
| """ | |
| # Inbox questions ("what did the registrar send me?") are answered from | |
| # the student's own Gmail instead of the knowledge base. Cheap regex gate | |
| # first; the module falls through (returns None) for non-mailbox questions. | |
| if email_qa.is_email_intent(body.message): | |
| email_answer = await asyncio.to_thread( | |
| email_qa.answer_from_email, user, body.message, body.history | |
| ) | |
| if email_answer: | |
| return email_answer | |
| org_engine = _engine_for_org(org) | |
| try: | |
| context_docs = org_engine.retrieve_context(query=body.message, role="student") | |
| except Exception as e: | |
| print(f"[FAIL] Retrieval error: {e}") | |
| context_docs = [] | |
| sources = _build_sources(context_docs) | |
| # Try Claude first. | |
| if claude_engine.enabled: | |
| answer = claude_engine.generate_response( | |
| query=body.message, | |
| context_docs=context_docs, | |
| history=body.history, | |
| ) | |
| if answer: | |
| return { | |
| "response": answer, | |
| "sources": sources, | |
| "engine": "claude", | |
| "model": claude_engine.model, | |
| } | |
| # Build the SAME rich context Claude got β all retrieved docs formatted with | |
| # titles/urls/departments (not one truncated doc) β shared by every fallback. | |
| alu_context = claude_engine._format_context(context_docs or []) | |
| # Bedrock ahead of the free tiers only when explicitly asked | |
| # (BEDROCK_PRIORITY=high). Default is to spend free capacity first. | |
| if bedrock_fallback and bedrock_fallback.prefer_before_free_tiers: | |
| bedrock_answer = bedrock_fallback.generate_response( | |
| body.message, alu_context, history=body.history | |
| ) | |
| if bedrock_answer: | |
| return { | |
| "response": bedrock_answer, | |
| "sources": sources, | |
| "engine": "bedrock", | |
| "model": bedrock_fallback.model, | |
| } | |
| # First fallback: NVIDIA NIM (stronger free model than Groq/Llama-70B). | |
| if nvidia_fallback and nvidia_fallback.enabled: | |
| nv_answer = nvidia_fallback.generate_response( | |
| body.message, alu_context, history=body.history | |
| ) | |
| if nv_answer: | |
| return { | |
| "response": nv_answer, | |
| "sources": sources, | |
| "engine": "nvidia", | |
| "model": nvidia_fallback.model, | |
| } | |
| # Second fallback: Groq (final backstop) with the same grounded context. | |
| if groq_fallback and groq_fallback.enabled: | |
| groq_answer = groq_fallback.generate_response( | |
| body.message, alu_context, history=body.history | |
| ) | |
| if groq_answer: | |
| return { | |
| "response": groq_answer, | |
| "sources": sources, | |
| "engine": "groq", | |
| # The model Groq actually used β it self-selects when one is | |
| # retired, so a hardcoded id here would misreport. | |
| "model": groq_fallback.model, | |
| } | |
| # Last resort before giving up. Costs money, which is exactly why it runs | |
| # only when every free path has already declined β but a student getting a | |
| # real answer is worth more than the fraction of a cent it costs. | |
| if bedrock_fallback and bedrock_fallback.enabled: | |
| bedrock_answer = bedrock_fallback.generate_response( | |
| body.message, alu_context, history=body.history | |
| ) | |
| if bedrock_answer: | |
| return { | |
| "response": bedrock_answer, | |
| "sources": sources, | |
| "engine": "bedrock", | |
| "model": bedrock_fallback.model, | |
| } | |
| return { | |
| "response": ( | |
| "I'm sorry β the AI service is unavailable right now. " | |
| "Please try again in a moment, or contact ALU Support." | |
| ), | |
| "sources": sources, | |
| "engine": "none", | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Phase 3: Streaming chat β Server-Sent Events | |
| # --------------------------------------------------------------------------- | |
| async def chat_claude_stream( | |
| request: Request, | |
| body: ClaudeChatRequest, | |
| user=Depends(require_user), | |
| org: str = Depends(current_org_any_user), | |
| ): | |
| """ | |
| Streaming version of /api/chat/claude. Returns a Server-Sent Events | |
| (SSE) response. Each event has shape: | |
| data: {"type": "chunk", "text": "..."}\\n\\n | |
| data: {"type": "sources", "sources": [...]}\\n\\n | |
| data: {"type": "done"}\\n\\n | |
| On Claude failure the stream emits a single "error" event and the | |
| client should fall back to /api/chat/claude (non-streaming) which | |
| in turn falls back to Groq. | |
| """ | |
| def sse_one(event: Dict[str, Any]) -> str: | |
| return f"data: {_json.dumps(event, ensure_ascii=False)}\n\n" | |
| # Same inbox interception as the non-streaming endpoint: the answer is | |
| # generated up front and delivered as a single chunk over SSE. | |
| if email_qa.is_email_intent(body.message): | |
| email_answer = await asyncio.to_thread( | |
| email_qa.answer_from_email, user, body.message, body.history | |
| ) | |
| if email_answer: | |
| def email_events(): | |
| yield sse_one({"type": "sources", "sources": email_answer["sources"]}) | |
| yield sse_one({"type": "chunk", "text": email_answer["response"]}) | |
| yield sse_one({"type": "done"}) | |
| return StreamingResponse( | |
| email_events(), | |
| media_type="text/event-stream", | |
| headers={ | |
| "Cache-Control": "no-cache", | |
| "X-Accel-Buffering": "no", | |
| "Connection": "keep-alive", | |
| }, | |
| ) | |
| if not claude_engine.enabled: | |
| raise HTTPException(status_code=503, detail="Claude is not configured") | |
| # Same per-organization scoping as the non-streaming route. Without it a | |
| # student was answered from the global collection regardless of which | |
| # university they belong to. | |
| org_engine = _engine_for_org(org) | |
| # Retrieval is synchronous and happens BEFORE we start streaming so | |
| # we can include sources in the first event the client receives. | |
| try: | |
| context_docs = org_engine.retrieve_context( | |
| query=body.message, role="student" | |
| ) | |
| except Exception as e: | |
| print(f"[FAIL] Retrieval error: {e}") | |
| context_docs = [] | |
| sources = _build_sources(context_docs) | |
| def sse_pack(event: Dict[str, Any]) -> str: | |
| return f"data: {_json.dumps(event, ensure_ascii=False)}\n\n" | |
| def event_generator(): | |
| # Send sources first so the UI can render a 'Reading from...' hint. | |
| yield sse_pack({"type": "sources", "sources": sources}) | |
| emitted_any = False | |
| try: | |
| for chunk in claude_engine.stream_response( | |
| query=body.message, | |
| context_docs=context_docs, | |
| history=body.history, | |
| ): | |
| emitted_any = True | |
| yield sse_pack({"type": "chunk", "text": chunk}) | |
| except Exception as e: | |
| print(f"[FAIL] Stream generator error: {e}") | |
| yield sse_pack({"type": "error", "message": "Stream interrupted"}) | |
| return | |
| if not emitted_any: | |
| yield sse_pack( | |
| {"type": "error", "message": "Claude returned no content"} | |
| ) | |
| return | |
| yield sse_pack({"type": "done"}) | |
| return StreamingResponse( | |
| event_generator(), | |
| media_type="text/event-stream", | |
| headers={ | |
| "Cache-Control": "no-cache", | |
| "X-Accel-Buffering": "no", # disable proxy buffering | |
| "Connection": "keep-alive", | |
| }, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Phase 2: Application essay coach | |
| # --------------------------------------------------------------------------- | |
| class EssayCoachRequest(BaseModel): | |
| essay: str = Field(min_length=1, max_length=12000) | |
| # the essay question being answered, optional | |
| prompt: Optional[str] = Field(default=None, max_length=2000) | |
| async def coach_essay( | |
| request: Request, | |
| body: EssayCoachRequest, | |
| user=Depends(require_user), | |
| ): | |
| """ | |
| Give feedback on an ALU application essay draft. Stateless β does NOT | |
| use chat history or RAG. Each request is independent. | |
| """ | |
| if not claude_engine.enabled: | |
| raise HTTPException( | |
| status_code=503, | |
| detail="Essay coach unavailable β Claude is not configured on the server.", | |
| ) | |
| if len(body.essay.strip()) < 50: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Essay is too short β please share at least a paragraph.", | |
| ) | |
| feedback = claude_engine.coach_essay(body.essay, prompt=body.prompt) | |
| if not feedback: | |
| raise HTTPException(status_code=502, detail="Coach could not produce feedback.") | |
| return {"feedback": feedback, "engine": "claude", "model": claude_engine.model} | |
| # --------------------------------------------------------------------------- | |
| # Phase 2: Opportunities for students (Tavily-backed) | |
| # --------------------------------------------------------------------------- | |
| async def get_opportunities( | |
| request: Request, | |
| refresh: bool = False, | |
| user=Depends(require_user), | |
| ): | |
| """ | |
| Return a list of student opportunities (scholarships, fellowships, | |
| internships, etc.). Tavily-powered; falls back to empty list if the | |
| service is disabled β the frontend has its own curated list as a | |
| secondary fallback. | |
| """ | |
| opportunities = opportunities_service.get_opportunities(force_refresh=refresh) | |
| return { | |
| "opportunities": opportunities, | |
| "source": "tavily" if opportunities_service.enabled else "disabled", | |
| } | |
| async def opportunities_status(): | |
| return opportunities_service.get_status() | |
| # --------------------------------------------------------------------------- | |
| # Google Sheet knowledge-base admin endpoints | |
| # --------------------------------------------------------------------------- | |
| class SheetRefreshRequest(BaseModel): | |
| reason: Optional[str] = None | |
| force: bool = False | |
| async def refresh_sheet( | |
| request: SheetRefreshRequest, | |
| caller=Depends(require_admin_or_token), | |
| ): | |
| """ | |
| Re-ingest the Google Sheet knowledge base into the vector store. | |
| Called by the Apps Script onEdit trigger (static X-Refresh-Token) so | |
| changes propagate within seconds, and also callable by a logged-in | |
| admin (Firebase bearer token). Gated by require_admin_or_token. | |
| """ | |
| result = await asyncio.to_thread(sheet_sync.refresh, request.force) | |
| return result.to_dict() | |
| async def sheet_status(admin=Depends(require_admin)): | |
| """Operational view: counts per department + last sync metadata.""" | |
| info = sheet_sync.status() | |
| info["poll_interval_seconds"] = SHEET_POLL_INTERVAL_SECONDS | |
| # Per-department entry counts so staff can confirm their tab landed. | |
| by_department: Dict[str, int] = {} | |
| collection = getattr(retrieval_engine, "collection", None) | |
| if collection is not None: | |
| try: | |
| existing = collection.get(where={"origin": "sheet"}) | |
| for meta in (existing or {}).get("metadatas") or []: | |
| dept = (meta or {}).get("department") or "(unknown)" | |
| by_department[dept] = by_department.get(dept, 0) + 1 | |
| except Exception as e: | |
| info["department_count_error"] = str(e) | |
| info["by_department"] = by_department | |
| return info | |
| # --------------------------------------------------------------------------- | |
| # Phase 2: extend /health with the new services | |
| # --------------------------------------------------------------------------- | |
| async def check_organization_domain(request: Request, email: str): | |
| """ | |
| Public, unauthenticated: "is this email's domain an onboarded, active | |
| university?" Backs the signup form's domain check β replaces a hardcoded | |
| ALU-only allowlist in the frontend so a newly onboarded university's | |
| students can sign up the moment their organizations row exists, with no | |
| frontend code change or redeploy. | |
| Deliberately public (no Firebase token): this runs BEFORE a Firebase | |
| account exists, so there is no token yet to verify. Rate-limited (not | |
| auth-gated) since it's a cheap, non-sensitive, indexed lookup β the same | |
| one auth.py's require_user already performs for every real request, just | |
| exposed pre-signup so the UI can give an immediate answer instead of | |
| creating a Firebase account it then has to tear down. | |
| """ | |
| domain = email.strip().lower().rsplit("@", 1)[-1] if "@" in email else "" | |
| if not domain: | |
| return {"allowed": False, "organization_name": None} | |
| org = db.get_org_by_domain(domain) | |
| if org is None: | |
| return {"allowed": False, "organization_name": None} | |
| return {"allowed": True, "organization_name": org.get("name")} | |
| async def services_probe(_admin=Depends(require_admin)): | |
| """Actually call each provider and report what happened. | |
| /api/services/status reports configuration β whether a key is set and a | |
| client constructed. That is not the same as working: every generation | |
| outage this project has had looked "enabled: true" right up until a | |
| student asked a question, because an expired key fails at call time, not | |
| at startup. | |
| This makes one tiny real call per provider so an expired key, a missing | |
| Bedrock model grant and a wrong model id are distinguishable instead of | |
| all presenting as "the AI service is unavailable". Admin-only: it burns a | |
| token or two per provider and names the reason a provider is failing. | |
| """ | |
| probe_prompt = "Reply with the single word: ok" | |
| results = {} | |
| def _try(name, fn): | |
| import time as _t | |
| started = _t.time() | |
| try: | |
| answer = fn() | |
| elapsed = round(_t.time() - started, 2) | |
| if answer: | |
| return {"ok": True, "seconds": elapsed, "sample": str(answer)[:80]} | |
| # None is how every fallback reports failure β the real cause was | |
| # logged and swallowed inside the provider. | |
| return { | |
| "ok": False, | |
| "seconds": elapsed, | |
| "reason": "returned no answer β usually an expired/invalid key " | |
| "or a rejected model id; check the Space logs for the " | |
| "provider's own error line", | |
| } | |
| except Exception as e: | |
| return {"ok": False, "error_type": type(e).__name__, "error": str(e)[:300]} | |
| if claude_engine.enabled: | |
| results["claude"] = _try( | |
| "claude", | |
| lambda: claude_engine.generate_response( | |
| query=probe_prompt, context_docs=[], history=[] | |
| ), | |
| ) | |
| else: | |
| results["claude"] = {"ok": False, "reason": "not enabled (no API key set)"} | |
| if nvidia_fallback and nvidia_fallback.enabled: | |
| results["nvidia"] = _try( | |
| "nvidia", lambda: nvidia_fallback.generate_response(probe_prompt, "", []) | |
| ) | |
| else: | |
| results["nvidia"] = {"ok": False, "reason": "not enabled (no NVIDIA_API_KEY set)"} | |
| if groq_fallback and groq_fallback.enabled: | |
| results["groq"] = _try( | |
| "groq", lambda: groq_fallback.generate_response(probe_prompt, "", []) | |
| ) | |
| else: | |
| results["groq"] = {"ok": False, "reason": "not enabled (no GROQ_API_KEY set)"} | |
| # Bedrock reports its own failure causes precisely β access not granted vs | |
| # bad model id vs expired credentials need different fixes. | |
| results["bedrock"] = bedrock_fallback.probe() if bedrock_fallback else { | |
| "ok": False, "reason": "module not loaded" | |
| } | |
| working = [name for name, r in results.items() if r.get("ok")] | |
| return { | |
| "providers": results, | |
| "working": working, | |
| "any_working": bool(working), | |
| "verdict": ( | |
| f"{len(working)} provider(s) responding: {', '.join(working)}" | |
| if working | |
| else "NO provider is responding β students will see the " | |
| "'AI service is unavailable' message." | |
| ), | |
| } | |
| async def services_status(): | |
| return { | |
| "claude": claude_engine.get_status(), | |
| "opportunities": opportunities_service.get_status(), | |
| "nvidia": nvidia_fallback.get_status() if nvidia_fallback else {"enabled": False}, | |
| "groq": groq_fallback.get_status() if groq_fallback else {"enabled": False}, | |
| "bedrock": bedrock_fallback.get_status() if bedrock_fallback else {"enabled": False}, | |
| "sheet_sync": sheet_sync.status(), | |
| "aurora": db.get_status(), | |
| "retrieval_engine": retrieval_engine is not None, | |
| "document_processor": document_processor is not None, | |
| } | |
| # This is needed for Hugging Face Spaces | |
| if __name__ == "__main__": | |
| import uvicorn | |
| port = int(os.environ.get("PORT", 7860)) # Hugging Face uses port 7860 | |
| print(f"Starting server on port {port}") | |
| uvicorn.run(app, host="0.0.0.0", port=port) | |