Upload 5 files
Browse filesFiles changed (4)
12345678910111213141516171819202122232425262728293031323334351 unmodified line37383940414243444546474849505152535455565758596061626364656667686970717273747576771 unmodified line7980818283"""LibBee /agent endpoint - thin FastAPI router.The pipeline itself lives in ``src/agentcore`` split by stage:models.py Stage 0 Pydantic I/O contractsconstants.py regexes, URLs, prompts (no logic)utils.py shared helpers, LLM factory, URL buildersclassify.py Stage 2-3 rule pre-classifier + LLM intent classifierlibcal.py live hours/events via Cloudflare Worker proxyscholarly.py Semantic Scholar / OpenAlex / Crossref / Unpaywallrendering.py HTML fragments (badges, trace, AI-tools footer)intents_library.py Stage 4 library_info handlersintents_search.py Stage 4 search_academic / search_medical machineryintents_general.py Stage 4 general / social handlersorchestrator.py Stage 1+4 injection gate, routing pipeline, D1 loggingThis file only wires HTTP to the orchestrator."""import timefrom fastapi import APIRouter, Requestfrom src.agentcore.models import AgentRequest, AgentResponsefrom src.agentcore.orchestrator import _agent_query_inner, _log_agent_queryfrom src.agentcore.utils import (_get_runtime_config,_normalize_whitespace,_safe_metrics_increment,_sanitize_llm_response,)from src.services.staff_service import STAFF_DIRECTORYrouter = APIRouter()1 unmodified line@router.post("", response_model=AgentResponse)async def agent_query(request: Request, req: AgentRequest):start_time = time.time()question = _normalize_whitespace(req.question)history = req.historymodel = req.modelclient_state = req.client_state# Canary requests (X-LibBee-Canary header, sent by the Worker's daily# health probe) run the full pipeline but are EXCLUDED from analytics:# synthetic traffic must never contaminate the D1 usage data that the# research evaluation reports. Canary results live in the Worker's own# canary_runs table instead.is_canary = request.headers.get("x-libbee-canary") == "1"if not is_canary:_safe_metrics_increment("agent_requests")response = await _agent_query_inner(question, history, model, client_state, start_time)response.answer = _sanitize_llm_response(response.answer)if not is_canary:_log_agent_query(question, response, start_time)_rcfg = _get_runtime_config()_ann = _rcfg.get("announcement", "").strip()if _ann and response.intent not in ("social_greeting", "social"):_ann_html = ('<div style="margin-top:14px;padding:10px 14px;border-radius:10px;''background:#fffbeb;border:1px solid #fde68a;font-size:.82rem;color:#92400e">'f'π’ {_ann}</div>')response.answer = response.answer + _ann_htmlreturn response@router.get("/test")async def test():return {"status": "ok","message": "Agent endpoint is working!","staff_loaded": len(STAFF_DIRECTORY),}@router.get("/rag-status")1 unmodified linetry:from app import get_rag_servicereturn get_rag_service().get_stats()except Exception as e:return {"error": str(e), "ready": False}1234567891011121314151 unmodified line1718192021222324252627282930313233343536373839404142434445461 unmodified line4849505152"""Authenticated agent endpoint; Cloudflare is the only intended caller."""import htmlimport timeimport uuidfrom fastapi import APIRouter, Requestfrom src.agentcore.models import AgentRequest, AgentResponsefrom src.agentcore.orchestrator import _agent_query_inner, _log_agent_queryfrom src.agentcore.utils import _get_runtime_config, _normalize_whitespace, _safe_metrics_increment, _sanitize_llm_responsefrom src.services.html_sanitizer import sanitize_answer_htmlrouter = APIRouter()1 unmodified line@router.post("", response_model=AgentResponse)async def agent_query(request: Request, req: AgentRequest):start_time = time.time()request_id = request.headers.get("x-request-id", "")[:80] or str(uuid.uuid4())question = _normalize_whitespace(req.question)history = list(req.history)if history and history[-1].role == "user" and _normalize_whitespace(history[-1].content) == question:history.pop()is_canary = request.headers.get("x-libbee-canary") == "1"if not is_canary:_safe_metrics_increment("agent_requests")response = await _agent_query_inner(question, history, req.model, req.client_state, start_time)response.request_id = request_idresponse.answer = _sanitize_llm_response(response.answer)runtime_config = _get_runtime_config()announcement = str(runtime_config.get("announcement", "")).strip()if announcement and response.intent not in {"social_greeting", "social"}:response.answer += '<div class="libbee-announcement" role="note"><strong>Announcement:</strong> ' + html.escape(announcement) + "</div>"response.answer = sanitize_answer_html(response.answer)if not is_canary:_log_agent_query(question, response, start_time)return response@router.get("/test")async def test():return {"status": "ok"}@router.get("/rag-status")1 unmodified linetry:from app import get_rag_servicereturn get_rag_service().get_stats()except Exception:return {"ready": False}
12345678910111213141516171819204 unmodified lines25262728293031323334353637import jsonimport timefrom pathlib import Pathfrom typing import Optionalfrom fastapi import APIRouterfrom pydantic import BaseModel, field_validatorfrom src.config import get_settingsrouter = APIRouter()class FeedbackRequest(BaseModel):question: strfeedback: stranswer_excerpt: Optional[str] = ""@field_validator("feedback")@classmethod4 unmodified lines@router.post("")async def save_feedback(req: FeedbackRequest):settings = get_settings()payload = {"timestamp": time.time(),"question": req.question[:1000],"feedback": req.feedback,"answer_excerpt": (req.answer_excerpt or "")[:1500],}settings.feedback_path.parent.mkdir(parents=True, exist_ok=True)with settings.feedback_path.open("a", encoding="utf-8") as handle:12345678910111213141516171819204 unmodified lines25262728293031323334353637import jsonimport timeimport refrom fastapi import APIRouterfrom pydantic import BaseModel, ConfigDict, Field, field_validatorfrom src.config import get_settingsrouter = APIRouter()class FeedbackRequest(BaseModel):model_config = ConfigDict(extra="forbid")request_id: str = Field(pattern=r"^[A-Za-z0-9-]{8,80}$")feedback: strcomment: str = Field(default="", max_length=500)@field_validator("feedback")@classmethod4 unmodified lines@router.post("")async def save_feedback(req: FeedbackRequest):settings = get_settings()payload = {"timestamp": time.time(),"request_id": req.request_id,"feedback": req.feedback,"comment": re.sub(r"[\w.+-]+@[\w-]+\.[\w.-]+", "[email]", req.comment)[:500],}settings.feedback_path.parent.mkdir(parents=True, exist_ok=True)with settings.feedback_path.open("a", encoding="utf-8") as handle:
14 unmodified lines151617181920213 unmodified lines25262728293031323334353637383914 unmodified linesfrom typing import Optionalfrom fastapi import APIRouterfrom pydantic import BaseModelfrom urllib.parse import quotelogger = logging.getLogger(__name__)3 unmodified lines# ββ Models βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass SearchRequest(BaseModel):query: strboolean_query: Optional[str] = None # LLM-built boolean; used for PRIMO if presentsource: str = "primo"limit: int = 5peer_reviewed: bool = Falseopen_access: bool = Falseyear_from: Optional[str] = Noneyear_to: Optional[str] = Noneresource_type: str = "articles" # "articles" | "books" | "both"# ββ PRIMO query builder ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ14 unmodified lines151617181920213 unmodified lines2526272829303132333435363738394014 unmodified linesfrom typing import Optionalfrom fastapi import APIRouterfrom pydantic import BaseModel, ConfigDict, Fieldfrom urllib.parse import quotelogger = logging.getLogger(__name__)3 unmodified lines# ββ Models βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass SearchRequest(BaseModel):model_config = ConfigDict(extra="forbid")query: str = Field(min_length=1, max_length=1000)boolean_query: Optional[str] = Field(default=None, max_length=1500)source: str = Field(default="primo", pattern=r"^(primo|pubmed)$")limit: int = Field(default=5, ge=1, le=20)peer_reviewed: bool = Falseopen_access: bool = Falseyear_from: Optional[str] = Field(default=None, pattern=r"^\d{4}$")year_to: Optional[str] = Field(default=None, pattern=r"^\d{4}$")resource_type: str = Field(default="articles", pattern=r"^(articles|books|both)$")# ββ PRIMO query builder ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
src/api/admin.py
src/api/agent.py+19-50
src/api/feedback.py+11-11
src/api/search.py+9-8