nikeshn commited on
Commit
038ad63
Β·
verified Β·
1 Parent(s): 169fbd2

Upload 5 files

Browse files
Files changed (4) hide show
  1. src/api/admin.py +0 -0
  2. src/api/agent.py +19 -50
  3. src/api/feedback.py +11 -11
  4. src/api/search.py +9 -8
src/api/admin.py CHANGED
The diff for this file is too large to render. See raw diff
 
src/api/agent.py CHANGED
@@ -1,35 +1,15 @@
1
- """
2
- LibBee /agent endpoint - thin FastAPI router.
3
 
4
- The pipeline itself lives in ``src/agentcore`` split by stage:
5
-
6
- models.py Stage 0 Pydantic I/O contracts
7
- constants.py regexes, URLs, prompts (no logic)
8
- utils.py shared helpers, LLM factory, URL builders
9
- classify.py Stage 2-3 rule pre-classifier + LLM intent classifier
10
- libcal.py live hours/events via Cloudflare Worker proxy
11
- scholarly.py Semantic Scholar / OpenAlex / Crossref / Unpaywall
12
- rendering.py HTML fragments (badges, trace, AI-tools footer)
13
- intents_library.py Stage 4 library_info handlers
14
- intents_search.py Stage 4 search_academic / search_medical machinery
15
- intents_general.py Stage 4 general / social handlers
16
- orchestrator.py Stage 1+4 injection gate, routing pipeline, D1 logging
17
-
18
- This file only wires HTTP to the orchestrator.
19
- """
20
  import time
 
21
 
22
  from fastapi import APIRouter, Request
23
 
24
  from src.agentcore.models import AgentRequest, AgentResponse
25
  from src.agentcore.orchestrator import _agent_query_inner, _log_agent_query
26
- from src.agentcore.utils import (
27
- _get_runtime_config,
28
- _normalize_whitespace,
29
- _safe_metrics_increment,
30
- _sanitize_llm_response,
31
- )
32
- from src.services.staff_service import STAFF_DIRECTORY
33
 
34
  router = APIRouter()
35
 
@@ -37,41 +17,30 @@ router = APIRouter()
37
  @router.post("", response_model=AgentResponse)
38
  async def agent_query(request: Request, req: AgentRequest):
39
  start_time = time.time()
 
40
  question = _normalize_whitespace(req.question)
41
- history = req.history
42
- model = req.model
43
- client_state = req.client_state
44
- # Canary requests (X-LibBee-Canary header, sent by the Worker's daily
45
- # health probe) run the full pipeline but are EXCLUDED from analytics:
46
- # synthetic traffic must never contaminate the D1 usage data that the
47
- # research evaluation reports. Canary results live in the Worker's own
48
- # canary_runs table instead.
49
  is_canary = request.headers.get("x-libbee-canary") == "1"
50
  if not is_canary:
51
  _safe_metrics_increment("agent_requests")
52
- response = await _agent_query_inner(question, history, model, client_state, start_time)
 
53
  response.answer = _sanitize_llm_response(response.answer)
 
 
 
 
 
54
  if not is_canary:
55
  _log_agent_query(question, response, start_time)
56
- _rcfg = _get_runtime_config()
57
- _ann = _rcfg.get("announcement", "").strip()
58
- if _ann and response.intent not in ("social_greeting", "social"):
59
- _ann_html = (
60
- '<div style="margin-top:14px;padding:10px 14px;border-radius:10px;'
61
- 'background:#fffbeb;border:1px solid #fde68a;font-size:.82rem;color:#92400e">'
62
- f'πŸ“’ {_ann}</div>'
63
- )
64
- response.answer = response.answer + _ann_html
65
  return response
66
 
67
 
68
  @router.get("/test")
69
  async def test():
70
- return {
71
- "status": "ok",
72
- "message": "Agent endpoint is working!",
73
- "staff_loaded": len(STAFF_DIRECTORY),
74
- }
75
 
76
 
77
  @router.get("/rag-status")
@@ -79,5 +48,5 @@ async def rag_status():
79
  try:
80
  from app import get_rag_service
81
  return get_rag_service().get_stats()
82
- except Exception as e:
83
- return {"error": str(e), "ready": False}
 
1
+ """Authenticated agent endpoint; Cloudflare is the only intended caller."""
 
2
 
3
+ import html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  import time
5
+ import uuid
6
 
7
  from fastapi import APIRouter, Request
8
 
9
  from src.agentcore.models import AgentRequest, AgentResponse
10
  from src.agentcore.orchestrator import _agent_query_inner, _log_agent_query
11
+ from src.agentcore.utils import _get_runtime_config, _normalize_whitespace, _safe_metrics_increment, _sanitize_llm_response
12
+ from src.services.html_sanitizer import sanitize_answer_html
 
 
 
 
 
13
 
14
  router = APIRouter()
15
 
 
17
  @router.post("", response_model=AgentResponse)
18
  async def agent_query(request: Request, req: AgentRequest):
19
  start_time = time.time()
20
+ request_id = request.headers.get("x-request-id", "")[:80] or str(uuid.uuid4())
21
  question = _normalize_whitespace(req.question)
22
+ history = list(req.history)
23
+ if history and history[-1].role == "user" and _normalize_whitespace(history[-1].content) == question:
24
+ history.pop()
 
 
 
 
 
25
  is_canary = request.headers.get("x-libbee-canary") == "1"
26
  if not is_canary:
27
  _safe_metrics_increment("agent_requests")
28
+ response = await _agent_query_inner(question, history, req.model, req.client_state, start_time)
29
+ response.request_id = request_id
30
  response.answer = _sanitize_llm_response(response.answer)
31
+ runtime_config = _get_runtime_config()
32
+ announcement = str(runtime_config.get("announcement", "")).strip()
33
+ if announcement and response.intent not in {"social_greeting", "social"}:
34
+ response.answer += '<div class="libbee-announcement" role="note"><strong>Announcement:</strong> ' + html.escape(announcement) + "</div>"
35
+ response.answer = sanitize_answer_html(response.answer)
36
  if not is_canary:
37
  _log_agent_query(question, response, start_time)
 
 
 
 
 
 
 
 
 
38
  return response
39
 
40
 
41
  @router.get("/test")
42
  async def test():
43
+ return {"status": "ok"}
 
 
 
 
44
 
45
 
46
  @router.get("/rag-status")
 
48
  try:
49
  from app import get_rag_service
50
  return get_rag_service().get_stats()
51
+ except Exception:
52
+ return {"ready": False}
src/api/feedback.py CHANGED
@@ -1,20 +1,20 @@
1
  import json
2
  import time
3
- from pathlib import Path
4
- from typing import Optional
5
 
6
  from fastapi import APIRouter
7
- from pydantic import BaseModel, field_validator
8
 
9
  from src.config import get_settings
10
 
11
  router = APIRouter()
12
 
13
 
14
- class FeedbackRequest(BaseModel):
15
- question: str
16
- feedback: str
17
- answer_excerpt: Optional[str] = ""
 
18
 
19
  @field_validator("feedback")
20
  @classmethod
@@ -25,13 +25,13 @@ class FeedbackRequest(BaseModel):
25
 
26
 
27
  @router.post("")
28
- async def save_feedback(req: FeedbackRequest):
29
  settings = get_settings()
30
  payload = {
31
  "timestamp": time.time(),
32
- "question": req.question[:1000],
33
- "feedback": req.feedback,
34
- "answer_excerpt": (req.answer_excerpt or "")[:1500],
35
  }
36
  settings.feedback_path.parent.mkdir(parents=True, exist_ok=True)
37
  with settings.feedback_path.open("a", encoding="utf-8") as handle:
 
1
  import json
2
  import time
3
+ import re
 
4
 
5
  from fastapi import APIRouter
6
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
7
 
8
  from src.config import get_settings
9
 
10
  router = APIRouter()
11
 
12
 
13
+ class FeedbackRequest(BaseModel):
14
+ model_config = ConfigDict(extra="forbid")
15
+ request_id: str = Field(pattern=r"^[A-Za-z0-9-]{8,80}$")
16
+ feedback: str
17
+ comment: str = Field(default="", max_length=500)
18
 
19
  @field_validator("feedback")
20
  @classmethod
 
25
 
26
 
27
  @router.post("")
28
+ async def save_feedback(req: FeedbackRequest):
29
  settings = get_settings()
30
  payload = {
31
  "timestamp": time.time(),
32
+ "request_id": req.request_id,
33
+ "feedback": req.feedback,
34
+ "comment": re.sub(r"[\w.+-]+@[\w-]+\.[\w.-]+", "[email]", req.comment)[:500],
35
  }
36
  settings.feedback_path.parent.mkdir(parents=True, exist_ok=True)
37
  with settings.feedback_path.open("a", encoding="utf-8") as handle:
src/api/search.py CHANGED
@@ -15,7 +15,7 @@ from datetime import datetime
15
  from typing import Optional
16
 
17
  from fastapi import APIRouter
18
- from pydantic import BaseModel
19
  from urllib.parse import quote
20
 
21
  logger = logging.getLogger(__name__)
@@ -25,15 +25,16 @@ router = APIRouter()
25
  # ── Models ─────────────────────────────────────────────────────────────────────
26
 
27
  class SearchRequest(BaseModel):
28
- query: str
29
- boolean_query: Optional[str] = None # LLM-built boolean; used for PRIMO if present
30
- source: str = "primo"
31
- limit: int = 5
 
32
  peer_reviewed: bool = False
33
  open_access: bool = False
34
- year_from: Optional[str] = None
35
- year_to: Optional[str] = None
36
- resource_type: str = "articles" # "articles" | "books" | "both"
37
 
38
 
39
  # ── PRIMO query builder ────────────────────────────────────────────────────────
 
15
  from typing import Optional
16
 
17
  from fastapi import APIRouter
18
+ from pydantic import BaseModel, ConfigDict, Field
19
  from urllib.parse import quote
20
 
21
  logger = logging.getLogger(__name__)
 
25
  # ── Models ─────────────────────────────────────────────────────────────────────
26
 
27
  class SearchRequest(BaseModel):
28
+ model_config = ConfigDict(extra="forbid")
29
+ query: str = Field(min_length=1, max_length=1000)
30
+ boolean_query: Optional[str] = Field(default=None, max_length=1500)
31
+ source: str = Field(default="primo", pattern=r"^(primo|pubmed)$")
32
+ limit: int = Field(default=5, ge=1, le=20)
33
  peer_reviewed: bool = False
34
  open_access: bool = False
35
+ year_from: Optional[str] = Field(default=None, pattern=r"^\d{4}$")
36
+ year_to: Optional[str] = Field(default=None, pattern=r"^\d{4}$")
37
+ resource_type: str = Field(default="articles", pattern=r"^(articles|books|both)$")
38
 
39
 
40
  # ── PRIMO query builder ────────────────────────────────────────────────────────