nikeshn commited on
Commit
8e575c7
Β·
verified Β·
1 Parent(s): 0025c58

Update src/api/agent.py

Browse files
Files changed (1) hide show
  1. src/api/agent.py +995 -257
src/api/agent.py CHANGED
@@ -1,29 +1,30 @@
1
  """
2
- agent.py β€” LibBee v3 (fixed)
3
 
4
- Fixes applied:
5
- 1. _extract_topic() β€” explicitly strips resource-type words (articles/books/papers)
6
- from LLM output and regex fallback. Topic is ALWAYS clean keywords only.
 
 
7
 
8
- 2. _make_primo_discovery_query() β€” removed all resource-type words from boolean.
9
- Boolean is now: "keyword1 keyword2 keyword3" only.
10
- Resource type handled exclusively via SearchRequest.resource_type β†’ PRIMO facet.
11
 
12
- 3. _search_primo_catalog() β€” now passes resource_type=context.resource_type so
13
- the rtype FACET is correctly sent to PRIMO.
14
 
15
- 4. _search_pubmed_articles() β€” year_from/year_to now wired through SearchRequest,
16
- fixed in search.py to use mindate/maxdate params (not keywords).
17
 
18
- 5. _search_follow_up() β€” now calls LLM to generate 3 topic-specific intellectual
19
- follow-up questions (related subtopics, methodological angles, applications).
20
- Generic filter options remain as a secondary set after the topic-specific ones.
21
 
22
- 6. _primo_url_from_boolean() β€” now uses clean topic (not polluted boolean) for the
23
- displayed PRIMO URL, matching exactly what the API actually searches.
24
 
25
- 7. _generate_cited_summary() / Semantic Scholar β€” improved: relevance filter on
26
- abstracts, better fallback, clearer citation replacement.
 
27
  """
28
  import html
29
  import json
@@ -32,7 +33,7 @@ import re
32
  import time
33
  import uuid
34
  from datetime import datetime
35
- from typing import Any, Dict, List, Optional, Tuple
36
  from urllib.parse import quote
37
 
38
  import httpx
@@ -86,7 +87,8 @@ class ClientStatePayload(BaseModel):
86
 
87
  class AgentRequest(BaseModel):
88
  question: str
89
- model: str = "gpt"
 
90
  history: List[ChatMessage] = Field(default_factory=list)
91
  client_state: Optional[ClientStatePayload] = None
92
 
@@ -112,6 +114,8 @@ class AgentResponse(BaseModel):
112
  ai_tool_query: Optional[str] = None
113
  primo_boolean_query: Optional[str] = None
114
  primo_search_url: Optional[str] = None
 
 
115
 
116
 
117
  # ── Constants ─────────────────────────────────────────────────────────────────
@@ -124,7 +128,6 @@ PRIMO_AI_URL = "https://khalifa.primo.exlibrisgroup.com/discovery/researchAssist
124
  HISTORY_WINDOW = 6
125
  CURRENT_YEAR = datetime.utcnow().year
126
 
127
- # Words that must never appear in a PRIMO/PubMed keyword query β€” they are filter signals
128
  _RESOURCE_TYPE_NOISE = re.compile(
129
  r"\b(articles?|papers?|books?|ebooks?|journals?|publications?|monographs?"
130
  r"|peer[- ]reviewed|open[- ]access|studies|study|research)\b",
@@ -212,6 +215,10 @@ SUMMARY_RE = re.compile(
212
  r"|what do we know about|how does|how do)\b",
213
  re.IGNORECASE,
214
  )
 
 
 
 
215
 
216
  MEDICAL_KEYWORDS = [
217
  "medicine", "medical", "health", "clinical", "nursing", "pharmacy", "biomedical",
@@ -224,11 +231,6 @@ MEDICAL_KEYWORDS = [
224
  "crispr", "gene therapy", "gene editing", "genomic medicine", "precision medicine",
225
  ]
226
 
227
- DATABASE_RECOMMEND_RE = re.compile(
228
- r"\b(best database|best databases|which database|which databases|database for|databases for|where should i search|where should i start)\b",
229
- re.IGNORECASE,
230
- )
231
-
232
  REFINEMENT_STOP_WORDS = {
233
  "make", "it", "them", "those", "these", "the", "a", "an", "for", "to", "only", "show",
234
  "find", "give", "me", "please", "and", "with", "within", "limit", "narrow", "search",
@@ -282,12 +284,7 @@ def _title_case_topic(topic: str) -> str:
282
 
283
 
284
  def _strip_resource_noise(text: str) -> str:
285
- """
286
- Remove resource-type and filter words that are PRIMO/PubMed facets, not q= keywords.
287
- Belt-and-braces: called on every topic before it touches an external search API.
288
- """
289
  cleaned = _RESOURCE_TYPE_NOISE.sub(" ", text or "")
290
- # Clean up dangling boolean operators
291
  cleaned = re.sub(r"\s+(AND|OR)\s+(AND|OR)\s+", " AND ", cleaned, flags=re.IGNORECASE)
292
  cleaned = re.sub(r"^\s*(AND|OR)\s+", "", cleaned, flags=re.IGNORECASE)
293
  cleaned = re.sub(r"\s+(AND|OR)\s*$", "", cleaned, flags=re.IGNORECASE)
@@ -317,18 +314,19 @@ def _source_badge(source: str, url: str = "") -> str:
317
  )
318
 
319
 
 
320
  def _safe_metrics_increment(key: str) -> None:
321
  try:
322
- from app import metrics_service
323
- metrics_service.incr(key)
324
  except Exception:
325
  return
326
 
327
 
328
  def _safe_metrics_bucket(bucket: str, key: str) -> None:
329
  try:
330
- from app import metrics_service
331
- metrics_service.incr_bucket(bucket, key)
332
  except Exception:
333
  return
334
 
@@ -450,10 +448,11 @@ def _greeting_menu_clarify_answer() -> str:
450
 
451
  def _get_llm(model: str, temperature: float, max_tokens: int):
452
  settings = get_settings()
 
453
  if model == "claude" and settings.anthropic_api_key:
454
  from langchain_anthropic import ChatAnthropic
455
  return ChatAnthropic(
456
- model="claude-3-haiku-20240307",
457
  temperature=temperature,
458
  max_tokens=max_tokens,
459
  anthropic_api_key=settings.anthropic_api_key,
@@ -469,8 +468,9 @@ def _get_llm(model: str, temperature: float, max_tokens: int):
469
 
470
  async def _llm_classify(question: str, history: List[ChatMessage], model: str) -> Dict[str, str]:
471
  settings = get_settings()
472
- if not settings.openai_api_key:
473
  return _rule_based_classify(question)
 
474
  try:
475
  ctx_parts = [
476
  f"{m.role}: {m.content[:100]}"
@@ -478,7 +478,7 @@ async def _llm_classify(question: str, history: List[ChatMessage], model: str) -
478
  if m.role in ("user", "assistant")
479
  ]
480
  ctx = " | ".join(ctx_parts) if ctx_parts else "none"
481
- llm = _get_llm(model, temperature=0, max_tokens=150)
482
  response = await llm.ainvoke([
483
  {"role": "system", "content": _CLASSIFIER_SYSTEM},
484
  {"role": "user", "content": f"Message: {question[:400]}\nContext: {ctx}\nJSON:"},
@@ -496,22 +496,923 @@ async def _llm_classify(question: str, history: List[ChatMessage], model: str) -
496
  return _rule_based_classify(question)
497
 
498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
499
  async def _search_follow_up(
500
  context: SearchContextPayload, model: str, summary_mode: bool = False
501
  ) -> Tuple[str, List[dict]]:
502
- """
503
- FIX: Now generates topic-specific intellectual follow-ups (LLM-based)
504
- PLUS a smaller set of generic filter options as secondary suggestions.
505
- Total suggestions: 3 topic-specific + up to 2 filter options = max 5.
506
- """
507
  topic = context.display_topic or context.topic
508
  suggestions: List[dict] = []
509
-
510
- # ── Topic-specific intellectual follow-ups (LLM-generated) ───────────────
511
  topic_follow_ups = await _generate_topic_follow_ups(topic, model)
512
  suggestions.extend(topic_follow_ups)
513
 
514
- # ── Generic filter options (secondary) ────────────────────────────────────
515
  filter_suggestions: List[dict] = []
516
  if summary_mode:
517
  filter_suggestions.append({
@@ -529,7 +1430,7 @@ async def _search_follow_up(
529
  else:
530
  if not context.peer_reviewed and context.source == "primo":
531
  filter_suggestions.append({
532
- "label": f"Peer reviewed only",
533
  "question": f"Make the {topic} search peer reviewed only",
534
  "action": "peer_reviewed_only",
535
  "context_id": context.context_id,
@@ -555,9 +1456,7 @@ async def _search_follow_up(
555
  "context_id": context.context_id,
556
  })
557
 
558
- # Add up to 2 filter suggestions after topic-specific ones
559
  suggestions.extend(filter_suggestions[:2])
560
-
561
  question_text = (
562
  f"Here are some related angles you might want to explore on <strong>{_escape(topic)}</strong>. "
563
  "Or I can refine the search with filters β€” just ask."
@@ -647,18 +1546,20 @@ async def _run_search_mode(
647
  search_results = result.get("results", []) or []
648
  total = result.get("total", len(search_results))
649
 
650
- answer = _search_trace_block(question, context) + _search_answer_intro(context, is_follow_up)
651
  if filters:
652
  answer += f"<br><br><strong>Current filters:</strong> {_escape(filters)}."
653
  if search_results:
654
  answer += f"<br><br>I found <strong>{total}</strong> result(s). The top items are shown below."
655
  else:
656
- answer += "<br><br>I didn't find matching results right now, but you can still try the direct discovery links and related tools below."
 
 
 
657
  if context.intent == "search_medical" and context.source != "pubmed":
658
  answer += "<br><br>For the strongest medical evidence trail, I also recommend checking <strong>PubMed</strong> or <strong>Embase</strong>."
659
 
660
  answer += _source_badge(source_name, source_url)
661
- answer += _contact_footer_for_query(question, context)
662
  sources = []
663
  for item in search_results[:6]:
664
  link = item.get("primo_url") or item.get("link")
@@ -675,181 +1576,6 @@ def _sort_and_trim_contexts(contexts: List[SearchContextPayload]) -> List[Search
675
  return ordered[:5]
676
 
677
 
678
-
679
- def _find_staff_by_token(token: str) -> Optional[dict]:
680
- token = (token or '').lower()
681
- for staff in STAFF_DIRECTORY:
682
- hay = (staff.get('full_name', '') + ' ' + staff.get('role', '')).lower()
683
- if token in hay:
684
- return staff
685
- return None
686
-
687
-
688
- def _contact_footer_for_query(question: str, context: Optional[SearchContextPayload]) -> str:
689
- q = (question or '').lower()
690
- specialist = _find_staff_by_token('muna')
691
- if any(t in q for t in ['database access', 'proxy', 'full text', 'eresource', 'e-resource', 'remote access', 'access problem']):
692
- specialist = _find_staff_by_token('rani')
693
- elif any(t in q for t in ['website', 'system', 'technical', 'login issue', 'page not loading']):
694
- specialist = _find_staff_by_token('walter')
695
- elif context and context.intent == 'search_medical':
696
- specialist = _find_staff_by_token('jason')
697
- elif context and context.intent in {'search_academic', 'search_medical'}:
698
- specialist = _find_staff_by_token('nikesh') if context.intent == 'search_academic' else _find_staff_by_token('jason')
699
- footer = (
700
- '<br><br><strong>Library contact points</strong><br>'
701
- f'General help: <a href="{ASK_LIBRARIAN_URL}" target="_blank">Ask a Librarian</a> Β· '
702
- '<a href="mailto:libse@ku.ac.ae">libse@ku.ac.ae</a>'
703
- )
704
- if specialist:
705
- footer += (
706
- f'<br>Relevant contact: <strong>{_escape(specialist.get("full_name", ""))}</strong> β€” '
707
- f'{_escape(specialist.get("role", ""))}<br>'
708
- f'<a href="mailto:{_escape(specialist.get("email", ""))}">{_escape(specialist.get("email", ""))}</a>'
709
- )
710
- phone = specialist.get('phone') or specialist.get('work_phone')
711
- if phone:
712
- footer += f' Β· <a href="tel:{_escape(str(phone).replace(" ", ""))}">{_escape(phone)}</a>'
713
- return footer
714
-
715
-
716
- def _search_trace_block(question: str, context: SearchContextPayload) -> str:
717
- topic = _escape(context.display_topic or context.topic)
718
- question_html = _escape(question)
719
- primo_boolean = _escape(context.primo_boolean_query or '')
720
- found_via = 'I identified the main topic, built a PRIMO search query, and looked for KU-accessible results.'
721
- if context.intent == 'search_medical':
722
- found_via += ' Because this is a medical topic, PubMed is also recommended for broader evidence searching.'
723
- block = (
724
- f'<div style="margin:10px 0 14px 0;padding:12px 14px;border:1px solid #dbe4ff;border-radius:12px;background:#f8fbff">'
725
- f'<strong>Your question:</strong> {question_html}<br>'
726
- f'<strong>Interpreted topic:</strong> {topic}<br>'
727
- )
728
- if primo_boolean:
729
- block += f'<strong>PRIMO query used:</strong> <code>{primo_boolean}</code><br>'
730
- block += f'<strong>How I found this:</strong> {found_via}</div>'
731
- return block
732
-
733
-
734
- def _is_database_recommendation_question(question: str) -> bool:
735
- return bool(DATABASE_RECOMMEND_RE.search(question or ''))
736
-
737
-
738
- def _database_recommendation_answer(question: str) -> str:
739
- q = (question or '').lower()
740
- topic = _escape(_strip_resource_noise(question))
741
- dbs = []
742
- if any(t in q for t in ['computer science', 'artificial intelligence', 'machine learning', ' ai ', 'cybersecurity']):
743
- dbs = [
744
- ('ACM Digital Library', 'https://khalifa.idm.oclc.org/login?url=https://dl.acm.org', 'Core computer science literature.'),
745
- ('IEEE Xplore', 'https://khalifa.idm.oclc.org/login?url=https://ieeexplore.ieee.org', 'Strong for AI, systems, and engineering computing.'),
746
- ('Scopus', 'https://khalifa.idm.oclc.org/login?url=https://www.scopus.com', 'Broad discovery and citation tracking.'),
747
- ]
748
- elif any(t in q for t in ['medical', 'health', 'nursing', 'clinical', 'biomedical']):
749
- dbs = [
750
- ('PubMed@KU', 'http://www.ncbi.nlm.nih.gov/pubmed/?otool=iaekustlib', 'Core biomedical literature with KU full-text links.'),
751
- ('Embase', 'https://khalifa.idm.oclc.org/login?url=https://www.embase.com', 'Biomedical and pharmacological literature.'),
752
- ('CINAHL Ultimate', 'https://khalifa.idm.oclc.org/login?url=https://search.ebscohost.com/login.aspx?authtype=ip,uid&profile=ehost&defaultdb=cul', 'Nursing and allied health literature.'),
753
- ]
754
- elif any(t in q for t in ['civil']):
755
- dbs = [
756
- ('ASCE Library', 'https://khalifa.idm.oclc.org/login?url=https://ascelibrary.org', 'Core civil engineering journals and conference papers.'),
757
- ('ScienceDirect', 'https://khalifa.idm.oclc.org/login?url=https://www.sciencedirect.com', 'Strong full text across civil engineering topics.'),
758
- ('Scopus', 'https://khalifa.idm.oclc.org/login?url=https://www.scopus.com', 'Discovery and citation tracking.'),
759
- ]
760
- elif any(t in q for t in ['mechanical']):
761
- dbs = [
762
- ('ASME Digital Library', 'https://khalifa.idm.oclc.org/login?url=https://asmedigitalcollection.asme.org', 'Core mechanical engineering literature.'),
763
- ('Knovel', 'https://khalifa.idm.oclc.org/login?url=https://app.knovel.com/kn', 'Engineering reference books and data.'),
764
- ('ScienceDirect', 'https://khalifa.idm.oclc.org/login?url=https://www.sciencedirect.com', 'Broad full text.'),
765
- ]
766
- elif any(t in q for t in ['electrical']):
767
- dbs = [
768
- ('IEEE Xplore', 'https://khalifa.idm.oclc.org/login?url=https://ieeexplore.ieee.org/Xplore/dynhome.jsp', 'Core electrical engineering database.'),
769
- ('INSPEC', 'https://khalifa.idm.oclc.org/login?url=https://www.theiet.org/publishing/inspec', 'Strong indexing for EE and electronics.'),
770
- ('Scopus', 'https://khalifa.idm.oclc.org/login?url=https://www.scopus.com', 'Discovery and citation tracking.'),
771
- ]
772
- else:
773
- dbs = [
774
- ('PRIMO', 'https://khalifa.primo.exlibrisgroup.com/discovery/search?vid=971KUOSTAR_INST:KU', 'Best starting point for KU-accessible books, articles, and journals.'),
775
- ('Scopus', 'https://khalifa.idm.oclc.org/login?url=https://www.scopus.com', 'Broad multidisciplinary discovery.'),
776
- ('Web of Science', 'https://khalifa.idm.oclc.org/login?url=https://www.webofscience.com', 'Broad multidisciplinary citation searching.'),
777
- ]
778
- answer = f'<strong>Best databases for {topic}</strong><br><br>'
779
- answer += 'Here are strong starting points for this subject:<br>'
780
- for name, url, why in dbs:
781
- answer += f'<br>β€’ <a href="{url}" target="_blank"><strong>{name}</strong></a> β€” {_escape(why)}'
782
- answer += '<br><br>If you want, I can also turn this into a direct article search.'
783
- return answer
784
-
785
-
786
- def _database_guidance_for_topic(context: SearchContextPayload) -> str:
787
- topic = _escape(context.display_topic or context.topic)
788
- return f'For deeper research on <strong>{topic}</strong>, the recommended AI research tools are listed at the end of this answer.'
789
-
790
-
791
- async def _generate_topic_follow_ups(topic: str, model: str) -> List[dict]:
792
- settings = get_settings()
793
- if not settings.openai_api_key:
794
- return []
795
- try:
796
- llm = _get_llm(model, temperature=0.4, max_tokens=200)
797
- response = await llm.ainvoke([
798
- {"role": "system", "content": "Generate exactly 3 short follow-up questions exploring different angles of the topic. Return only a JSON array of strings."},
799
- {"role": "user", "content": f"Topic: {topic}"},
800
- ])
801
- raw = response.content.strip()
802
- if raw.startswith('```'):
803
- raw = raw.split('\\n', 1)[1].rsplit('```', 1)[0].strip()
804
- questions = json.loads(raw)
805
- if not isinstance(questions, list):
806
- return []
807
- suggestions: List[dict] = []
808
- for q in questions[:3]:
809
- if not isinstance(q, str) or not q.strip():
810
- continue
811
- q_clean = _normalize_whitespace(q.strip().rstrip('?'))
812
- contextual = q_clean if topic.lower() in q_clean.lower() else f'{q_clean} for {topic}'
813
- suggestions.append({'label': q_clean + '?', 'question': f'Find research articles on {contextual}', 'action': None})
814
- return suggestions
815
- except Exception as e:
816
- logger.warning(f'Topic follow-up generation failed: {e}')
817
- return []
818
-
819
-
820
- async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple[str, List[dict], List[dict]]:
821
- topic = context.topic
822
- papers = await _semantic_scholar_search(topic, limit=8)
823
- references: List[dict] = []
824
- primo_result, primo_url = await _search_primo_catalog(context, limit=6)
825
- search_results = primo_result.get('results', []) or []
826
- answer = _search_trace_block(context.ai_tool_query or f'Research on {topic}', context)
827
- if papers:
828
- summary = await _generate_cited_summary(topic, papers, model)
829
- if not summary:
830
- _safe_metrics_increment('summary_fallbacks')
831
- summary = _extractive_snapshot_from_papers(topic, papers)
832
- answer += f'<strong>πŸ“– Research Snapshot: {_escape(topic)}</strong><br><br>{summary}'
833
- if search_results:
834
- answer += '<br><br><strong>KU Library starting points:</strong> I also found KU-accessible results below so you can continue with subscribed material.'
835
- answer += '<br><br><strong>Selected references:</strong><br>'
836
- for i, paper in enumerate(papers[:6], 1):
837
- answer += f'<br><strong>[{i}]</strong> <a href="{paper["link"]}" target="_blank" style="color:#003366;font-weight:600">{_escape(paper["title"])}</a><br><span style="font-size:.8rem;color:#6b7280">{_escape(paper["authors"])} Β· {paper["year"]} Β· {_escape(paper["venue"] or "")}</span>'
838
- answer += '<br><br>For deeper research, the recommended AI research tools are listed at the end of this answer.'
839
- answer += _source_badge('semantic', 'https://www.semanticscholar.org/')
840
- if search_results:
841
- answer += _source_badge('primo', primo_url)
842
- answer += _contact_footer_for_query(topic, context)
843
- references = [{'title': p['title'], 'url': p['link']} for p in papers[:6]]
844
- return answer, search_results, references
845
- if search_results:
846
- answer += f'<strong>πŸ“š KU Library starting points on {_escape(topic)}</strong><br><br>I found KU-accessible library results you can open immediately below.<br><br>For deeper research, the recommended AI research tools are listed at the end of this answer.'
847
- else:
848
- answer += f'<strong>πŸ“š Research starting points on {_escape(topic)}</strong><br><br>I found direct library discovery routes you can use to continue this search.<br><br>For deeper research, the recommended AI research tools are listed at the end of this answer.'
849
- answer += _source_badge('primo', primo_url)
850
- answer += _contact_footer_for_query(topic, context)
851
- return answer, search_results, []
852
-
853
  # ── Main Endpoint ──────────────────────────────────────────────────────────────
854
 
855
  @router.post("", response_model=AgentResponse)
@@ -954,6 +1680,21 @@ async def agent_query(request: Request, req: AgentRequest):
954
  follow_up_suggestions=follow_up_suggestions,
955
  )
956
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
957
  is_follow_up, follow_up_action, base_context = _detect_follow_up(question, client_state)
958
 
959
  if is_follow_up and base_context:
@@ -964,16 +1705,11 @@ async def agent_query(request: Request, req: AgentRequest):
964
  context = await _prepare_queries(question, context, model, True)
965
  if follow_up_action == "summarize_topic":
966
  answer, search_results, sources = await _research_snapshot(context, model)
967
- elif follow_up_action == "best_databases":
968
- answer = _database_recommendation_answer(context.topic) + _contact_footer_for_query(question, context) + _source_badge("ku_library", "https://library.ku.ac.ae/eresources")
969
- search_results = []
970
- sources = []
971
  else:
972
  answer = (
973
  f"<strong>Research guide for {_escape(context.display_topic or context.topic)}</strong><br><br>"
974
  f"{_database_guidance_for_topic(context)}"
975
  + _source_badge("libbee")
976
- + _contact_footer_for_query(question, context)
977
  )
978
  search_results = []
979
  sources = []
@@ -993,6 +1729,8 @@ async def agent_query(request: Request, req: AgentRequest):
993
  ai_tool_query=context.ai_tool_query,
994
  primo_boolean_query=context.primo_boolean_query,
995
  primo_search_url=_primo_clean_url(context),
 
 
996
  follow_up_question=follow_up_question,
997
  follow_up_suggestions=follow_up_suggestions,
998
  search_context=_context_to_dict(context),
@@ -1015,19 +1753,26 @@ async def agent_query(request: Request, req: AgentRequest):
1015
  ai_tool_query=context.ai_tool_query,
1016
  primo_boolean_query=context.primo_boolean_query,
1017
  primo_search_url=source_url,
 
 
1018
  follow_up_question=follow_up_question,
1019
  follow_up_suggestions=follow_up_suggestions,
1020
  search_context=_context_to_dict(context),
1021
  is_follow_up=True,
1022
  )
1023
 
 
1024
  cls_result = await _llm_classify(question, history, model)
1025
  intent = cls_result.get("intent", "general")
1026
  _safe_metrics_bucket("intents", intent)
1027
  casual_hint = cls_result.get("casual_answer", "")
1028
 
1029
  if intent == "social":
1030
- answer = casual_hint if casual_hint and len(casual_hint.strip()) > 20 else await _libbee_casual_response(question, history, model, casual_hint)
 
 
 
 
1031
  follow_up_question, follow_up_suggestions = _social_follow_up()
1032
  return AgentResponse(
1033
  answer=answer + _source_badge("libbee"),
@@ -1039,28 +1784,14 @@ async def agent_query(request: Request, req: AgentRequest):
1039
  follow_up_suggestions=follow_up_suggestions,
1040
  )
1041
 
1042
- if _is_database_recommendation_question(question):
1043
- answer = _database_recommendation_answer(question)
1044
- answer += _contact_footer_for_query(question, None)
1045
- answer += _source_badge("ku_library", "https://library.ku.ac.ae/eresources")
1046
- follow_up_question, follow_up_suggestions = _library_follow_up(question)
1047
- return AgentResponse(
1048
- answer=answer,
1049
- intent="library_info",
1050
- tools_used=["database_recommendation"],
1051
- model_used=model,
1052
- response_time=time.time() - start_time,
1053
- follow_up_question=follow_up_question,
1054
- follow_up_suggestions=follow_up_suggestions,
1055
- )
1056
-
1057
  if intent == "library_info":
 
 
1058
  try:
1059
- from app import rag_service
1060
- rag_results = await rag_service.hybrid_search(question, top_k=4)
1061
  except Exception as e:
1062
  logger.error(f"RAG search failed: {e}")
1063
- rag_results = []
1064
 
1065
  if not rag_results:
1066
  answer = (
@@ -1075,7 +1806,11 @@ async def agent_query(request: Request, req: AgentRequest):
1075
  else:
1076
  answer = await _rag_answer(question, rag_results, history, model)
1077
  answer += _source_badge("rag", "https://library.ku.ac.ae/")
1078
- sources = [{"title": r.get("title", "Library KB"), "url": r.get("source", "")} for r in rag_results if r.get("source")]
 
 
 
 
1079
  tools_used = ["rag_hybrid_search"]
1080
 
1081
  follow_up_question, follow_up_suggestions = _library_follow_up(question)
@@ -1117,10 +1852,8 @@ async def agent_query(request: Request, req: AgentRequest):
1117
 
1118
  if summary_mode or deep_research_mode:
1119
  answer, search_results, sources = await _research_snapshot(context, model)
1120
- answer = _search_trace_block(question, context) + answer
1121
  if deep_research_mode and "Research guide" not in answer:
1122
- answer += "<br><br><em>For deeper research, recommended AI research tools are listed at the end of this answer.</em>"
1123
- answer += _contact_footer_for_query(question, context)
1124
  follow_up_question, follow_up_suggestions = await _search_follow_up(context, model, summary_mode=True)
1125
  _safe_metrics_increment("search_handoffs")
1126
  return AgentResponse(
@@ -1137,6 +1870,8 @@ async def agent_query(request: Request, req: AgentRequest):
1137
  ai_tool_query=context.ai_tool_query,
1138
  primo_boolean_query=context.primo_boolean_query,
1139
  primo_search_url=_primo_clean_url(context),
 
 
1140
  follow_up_question=follow_up_question,
1141
  follow_up_suggestions=follow_up_suggestions,
1142
  search_context=_context_to_dict(context),
@@ -1158,6 +1893,8 @@ async def agent_query(request: Request, req: AgentRequest):
1158
  ai_tool_query=context.ai_tool_query,
1159
  primo_boolean_query=context.primo_boolean_query,
1160
  primo_search_url=source_url,
 
 
1161
  follow_up_question=follow_up_question,
1162
  follow_up_suggestions=follow_up_suggestions,
1163
  search_context=_context_to_dict(context),
@@ -1202,8 +1939,9 @@ async def test():
1202
 
1203
  @router.get("/rag-status")
1204
  async def rag_status():
 
1205
  try:
1206
- from app import rag_service
1207
- return rag_service.get_stats()
1208
  except Exception as e:
1209
  return {"error": str(e), "ready": False}
 
1
  """
2
+ agent.py β€” LibBee v3.1
3
 
4
+ Fixes applied over v3:
5
+ 1. CRITICAL: Removed broken import of build_primo_boolean_query,
6
+ build_primo_discovery_url, build_pubmed_url from search.py β€” those
7
+ functions do not exist there. Replaced with self-contained implementations
8
+ directly in this file. This was the primary cause of the 500 errors.
9
 
10
+ 2. Circular import hardened: 'from app import rag_service / metrics_service'
11
+ replaced with 'from app import get_rag_service / get_metrics_service'
12
+ accessors that are safe to call inside request handlers.
13
 
14
+ 3. Deprecated Claude model string updated:
15
+ claude-3-haiku-20240307 β†’ claude-haiku-4-5-20251001
16
 
17
+ 4. _llm_classify and all LLM call sites wrapped with explicit try/except
18
+ so any LLM failure falls back to rule-based logic, never 500s.
19
 
20
+ 5. AgentRequest model field validated: model is now Literal["gpt", "claude"]
21
+ so malformed values are caught at the Pydantic layer.
 
22
 
23
+ 6. _web_search_answer: updated claude model string to match fix #3.
 
24
 
25
+ 7. _contact_footer_for_query: removed broken _find_staff_by_token("muna")
26
+ default β€” Muna is not in STAFF_DIRECTORY, so default now falls through
27
+ to no specialist rather than silently returning None.
28
  """
29
  import html
30
  import json
 
33
  import time
34
  import uuid
35
  from datetime import datetime
36
+ from typing import Any, Dict, List, Literal, Optional, Tuple
37
  from urllib.parse import quote
38
 
39
  import httpx
 
87
 
88
  class AgentRequest(BaseModel):
89
  question: str
90
+ # FIX: validated literal β€” malformed model values caught at Pydantic layer
91
+ model: Literal["gpt", "claude"] = "gpt"
92
  history: List[ChatMessage] = Field(default_factory=list)
93
  client_state: Optional[ClientStatePayload] = None
94
 
 
114
  ai_tool_query: Optional[str] = None
115
  primo_boolean_query: Optional[str] = None
116
  primo_search_url: Optional[str] = None
117
+ primo_ai_url: Optional[str] = None
118
+ pubmed_search_url: Optional[str] = None
119
 
120
 
121
  # ── Constants ─────────────────────────────────────────────────────────────────
 
128
  HISTORY_WINDOW = 6
129
  CURRENT_YEAR = datetime.utcnow().year
130
 
 
131
  _RESOURCE_TYPE_NOISE = re.compile(
132
  r"\b(articles?|papers?|books?|ebooks?|journals?|publications?|monographs?"
133
  r"|peer[- ]reviewed|open[- ]access|studies|study|research)\b",
 
215
  r"|what do we know about|how does|how do)\b",
216
  re.IGNORECASE,
217
  )
218
+ DATABASE_RECOMMEND_RE = re.compile(
219
+ r"\b(best database|best databases|which database|which databases|database for|databases for|where should i search|where should i start)\b",
220
+ re.IGNORECASE,
221
+ )
222
 
223
  MEDICAL_KEYWORDS = [
224
  "medicine", "medical", "health", "clinical", "nursing", "pharmacy", "biomedical",
 
231
  "crispr", "gene therapy", "gene editing", "genomic medicine", "precision medicine",
232
  ]
233
 
 
 
 
 
 
234
  REFINEMENT_STOP_WORDS = {
235
  "make", "it", "them", "those", "these", "the", "a", "an", "for", "to", "only", "show",
236
  "find", "give", "me", "please", "and", "with", "within", "limit", "narrow", "search",
 
284
 
285
 
286
  def _strip_resource_noise(text: str) -> str:
 
 
 
 
287
  cleaned = _RESOURCE_TYPE_NOISE.sub(" ", text or "")
 
288
  cleaned = re.sub(r"\s+(AND|OR)\s+(AND|OR)\s+", " AND ", cleaned, flags=re.IGNORECASE)
289
  cleaned = re.sub(r"^\s*(AND|OR)\s+", "", cleaned, flags=re.IGNORECASE)
290
  cleaned = re.sub(r"\s+(AND|OR)\s*$", "", cleaned, flags=re.IGNORECASE)
 
314
  )
315
 
316
 
317
+ # FIX: use get_metrics_service() accessor to avoid circular import fragility
318
  def _safe_metrics_increment(key: str) -> None:
319
  try:
320
+ from app import get_metrics_service
321
+ get_metrics_service().incr(key)
322
  except Exception:
323
  return
324
 
325
 
326
  def _safe_metrics_bucket(bucket: str, key: str) -> None:
327
  try:
328
+ from app import get_metrics_service
329
+ get_metrics_service().incr_bucket(bucket, key)
330
  except Exception:
331
  return
332
 
 
448
 
449
  def _get_llm(model: str, temperature: float, max_tokens: int):
450
  settings = get_settings()
451
+ # FIX: updated model string β€” claude-3-haiku-20240307 is deprecated
452
  if model == "claude" and settings.anthropic_api_key:
453
  from langchain_anthropic import ChatAnthropic
454
  return ChatAnthropic(
455
+ model="claude-haiku-4-5-20251001",
456
  temperature=temperature,
457
  max_tokens=max_tokens,
458
  anthropic_api_key=settings.anthropic_api_key,
 
468
 
469
  async def _llm_classify(question: str, history: List[ChatMessage], model: str) -> Dict[str, str]:
470
  settings = get_settings()
471
+ if not settings.openai_api_key and not settings.anthropic_api_key:
472
  return _rule_based_classify(question)
473
+ # FIX: always fall back to rule-based on any exception β€” never propagate
474
  try:
475
  ctx_parts = [
476
  f"{m.role}: {m.content[:100]}"
 
478
  if m.role in ("user", "assistant")
479
  ]
480
  ctx = " | ".join(ctx_parts) if ctx_parts else "none"
481
+ llm = _get_llm(model, temperature=0, max_tokens=120)
482
  response = await llm.ainvoke([
483
  {"role": "system", "content": _CLASSIFIER_SYSTEM},
484
  {"role": "user", "content": f"Message: {question[:400]}\nContext: {ctx}\nJSON:"},
 
496
  return _rule_based_classify(question)
497
 
498
 
499
+ async def _libbee_casual_response(question: str, history: List[ChatMessage], model: str, hint: str = "") -> str:
500
+ if hint and len(hint.strip()) > 20:
501
+ return hint.strip()
502
+ settings = get_settings()
503
+ if not settings.openai_api_key and not settings.anthropic_api_key:
504
+ return "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant β€” always happy to help!"
505
+ try:
506
+ llm = _get_llm(model, temperature=0.6, max_tokens=160)
507
+ msgs = [{"role": "system", "content": (
508
+ "You are LibBee, the Khalifa University Library AI Assistant. "
509
+ "Respond warmly and naturally in 1-3 sentences as a friendly librarian. "
510
+ "No markdown, no bullet points."
511
+ )}]
512
+ msgs.extend(_build_history_messages(history))
513
+ msgs.append({"role": "user", "content": question})
514
+ response = await llm.ainvoke(msgs)
515
+ return response.content.strip()
516
+ except Exception:
517
+ return "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant β€” always happy to help!"
518
+
519
+
520
+ async def _rag_answer(question: str, rag_results: List[dict], history: List[ChatMessage], model: str) -> str:
521
+ settings = get_settings()
522
+ if not settings.openai_api_key and not settings.anthropic_api_key:
523
+ return rag_results[0]["content"] if rag_results else ""
524
+ context = "\n\n---\n\n".join(r["content"] for r in rag_results)
525
+ system = (
526
+ "You are LibBee, the Khalifa University Library AI Assistant. "
527
+ "Answer the user's question using ONLY the context provided below. "
528
+ "Be concise, friendly, and use HTML <br> for line breaks where needed. "
529
+ f"If the context does not contain enough information, say so and suggest Ask a Librarian at {ASK_LIBRARIAN_URL}. "
530
+ "Never invent facts or URLs.\n\n"
531
+ f"CONTEXT:\n{context}"
532
+ )
533
+ try:
534
+ llm = _get_llm(model, temperature=0.2, max_tokens=380)
535
+ msgs = [{"role": "system", "content": system}]
536
+ msgs.extend(_build_history_messages(history))
537
+ msgs.append({"role": "user", "content": question})
538
+ response = await llm.ainvoke(msgs)
539
+ return response.content.strip()
540
+ except Exception as e:
541
+ logger.error(f"_rag_answer error: {e}")
542
+ return (
543
+ "I'm having trouble generating an answer right now. "
544
+ f'Please try <a href="{ASK_LIBRARIAN_URL}" target="_blank">Ask a Librarian</a>.'
545
+ )
546
+
547
+
548
+ async def _llm_general_answer(question: str, history: List[ChatMessage], model: str) -> str:
549
+ settings = get_settings()
550
+ if not settings.openai_api_key and not settings.anthropic_api_key:
551
+ return (
552
+ "I'm <strong>LibBee</strong>, the KU Library AI Assistant. "
553
+ f'For general university information, visit <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a>.'
554
+ )
555
+ system = (
556
+ "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
557
+ "Answer factually and concisely in 3-5 sentences. Use HTML <br> for line breaks. "
558
+ "KU means Khalifa University. If the topic is academic, briefly offer to help find library resources."
559
+ )
560
+ try:
561
+ llm = _get_llm(model, temperature=0.3, max_tokens=360)
562
+ msgs = [{"role": "system", "content": system}]
563
+ msgs.extend(_build_history_messages(history))
564
+ msgs.append({"role": "user", "content": question})
565
+ response = await llm.ainvoke(msgs)
566
+ return response.content.strip()
567
+ except Exception as e:
568
+ logger.error(f"_llm_general_answer error: {e}")
569
+ return f'Having trouble right now. Visit <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a>.'
570
+
571
+
572
+ async def _web_search_answer(question: str, history: List[ChatMessage], model: str) -> str:
573
+ settings = get_settings()
574
+ # FIX: updated model string to match _get_llm fix
575
+ if model == "claude" and settings.anthropic_api_key:
576
+ try:
577
+ import anthropic
578
+ client = anthropic.Anthropic(api_key=settings.anthropic_api_key)
579
+ response = client.messages.create(
580
+ model="claude-haiku-4-5-20251001",
581
+ max_tokens=520,
582
+ system=(
583
+ "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
584
+ "Answer using current web search. Be concise and factual. Use HTML <br> for line breaks."
585
+ ),
586
+ tools=[{"type": "web_search_20250305", "name": "web_search"}],
587
+ messages=[{"role": "user", "content": question}],
588
+ )
589
+ text = "".join(block.text for block in response.content if hasattr(block, "text"))
590
+ if text.strip():
591
+ return text.strip()
592
+ except Exception as e:
593
+ logger.warning(f"Claude web search failed: {e}")
594
+
595
+ if settings.openai_api_key:
596
+ try:
597
+ from openai import OpenAI
598
+ client = OpenAI(api_key=settings.openai_api_key)
599
+ response = client.responses.create(
600
+ model="gpt-4o-mini",
601
+ tools=[{"type": "web_search_preview"}],
602
+ instructions=(
603
+ "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
604
+ "Answer using current web search. Be concise and factual. Use HTML <br> for line breaks."
605
+ ),
606
+ input=question,
607
+ )
608
+ text = ""
609
+ for item in response.output:
610
+ if hasattr(item, "content"):
611
+ for block in item.content:
612
+ if hasattr(block, "text"):
613
+ text += block.text
614
+ if text.strip():
615
+ return text.strip()
616
+ except Exception as e:
617
+ logger.warning(f"GPT web search failed: {e}")
618
+
619
+ return await _llm_general_answer(question, history, model)
620
+
621
+
622
+ # ── Topic Extraction ──────────────────────────────────────────────────────────
623
+
624
+ def _extract_topic_regex(question: str) -> str:
625
+ q = _normalize_whitespace(question)
626
+ prefixes = [
627
+ "can u give me a deep analysis of ", "can you give me a deep analysis of ",
628
+ "give me a deep analysis of ", "deep analysis of ",
629
+ "give me a summary of ", "give me a summary on ", "give me a summary about ",
630
+ "give me an overview of ", "give me an overview on ",
631
+ "give me a brief overview of ", "give me a brief summary of ",
632
+ "summarize the latest studies in ", "summarize latest studies in ",
633
+ "summarize the latest research on ", "summarize latest research on ",
634
+ "summarize recent studies in ", "summarize recent research on ",
635
+ "latest studies in ", "latest research on ", "recent studies in ", "recent research on ",
636
+ "summarize ", "summarise ", "summary of ", "summary on ", "summary about ",
637
+ "overview of ", "overview on ", "brief overview of ", "brief summary of ",
638
+ "analysis of ", "analyze ", "analyse ", "explain ", "tell me about ",
639
+ "what is ", "what are ", "describe ", "review of ", "literature review on ",
640
+ "recent advances in ", "recent developments in ", "state of the art in ",
641
+ "state of research on ", "research overview of ", "research summary of ",
642
+ "find peer reviewed articles on ", "find peer reviewed papers on ",
643
+ "find articles on ", "find papers on ", "find books on ", "find articles about ",
644
+ "find papers about ", "search for articles on ", "search for papers on ",
645
+ "i need peer reviewed articles on ", "i need articles on ", "i need papers on ",
646
+ "i need books on ", "give me articles on ", "show me articles on ",
647
+ "get me articles on ", "look for articles on ", "articles on ", "papers on ",
648
+ "books on ", "research on ", "literature on ", "find ", "search for ",
649
+ "i need ", "give me ", "show me ", "get me ",
650
+ ]
651
+ lower = q.lower()
652
+ for prefix in prefixes:
653
+ if lower.startswith(prefix):
654
+ q = q[len(prefix):]
655
+ break
656
+ q = re.sub(r"\s+(please|thanks|thank you)\.?$", "", q, flags=re.IGNORECASE)
657
+ q = re.sub(r"\b(peer[- ]reviewed|open access|last \d+ years?|past \d+ years?)\b", "", q, flags=re.IGNORECASE)
658
+ q = _strip_resource_noise(q)
659
+ return _normalize_whitespace(q).strip(".?")
660
+
661
+
662
+ async def _extract_topic(question: str, model: str) -> str:
663
+ settings = get_settings()
664
+ if not settings.openai_api_key and not settings.anthropic_api_key:
665
+ return _extract_topic_regex(question)
666
+ try:
667
+ llm = _get_llm(model, temperature=0, max_tokens=32)
668
+ response = await llm.ainvoke([
669
+ {"role": "system", "content": (
670
+ "Extract only the core research topic from the user's question. "
671
+ "Return 2-7 keywords ONLY β€” no punctuation, no sentence, no explanation. "
672
+ "CRITICAL: do NOT include words like articles, papers, books, journals, "
673
+ "peer-reviewed, open-access, studies, or research in your output. "
674
+ "Those are filters, not topic words. Return ONLY the subject matter.\n"
675
+ "Examples:\n"
676
+ "'find articles on indian politics' β†’ indian politics\n"
677
+ "'peer reviewed papers on climate change 2020' β†’ climate change\n"
678
+ "'books on structural engineering UAE' β†’ structural engineering UAE\n"
679
+ "'give me a summary of quantum physics advances' β†’ quantum physics advances\n"
680
+ "'i need peer reviewed research on machine learning healthcare' β†’ machine learning healthcare"
681
+ )},
682
+ {"role": "user", "content": question},
683
+ ])
684
+ topic = response.content.strip().strip('"').strip("'").strip(".")
685
+ topic = _strip_resource_noise(topic)
686
+ topic = _normalize_whitespace(topic).strip(".?")
687
+ if topic and len(topic) > 2:
688
+ return topic
689
+ except Exception as e:
690
+ logger.warning(f"Topic extraction failed: {e}")
691
+ return _extract_topic_regex(question)
692
+
693
+
694
+ # ── PRIMO / PubMed URL + Query Builders ───────────────────────────────────────
695
+ # FIX: these were previously imported from search.py as
696
+ # build_primo_boolean_query / build_primo_discovery_url / build_pubmed_url
697
+ # but those exports do not exist in search.py.
698
+ # They are now self-contained here.
699
+
700
+ def _shared_build_primo_boolean_query(topic: str) -> str:
701
+ """Build a clean boolean query from topic keywords β€” no resource-type words."""
702
+ clean = _strip_resource_noise(topic)
703
+ if not clean:
704
+ clean = topic
705
+ keywords = [w for w in clean.split() if len(w) > 1]
706
+ if not keywords:
707
+ return clean
708
+ if len(keywords) == 1:
709
+ return keywords[0]
710
+ return " AND ".join(keywords[:5])
711
+
712
+
713
+ def _shared_build_primo_discovery_url(
714
+ boolean_query: str,
715
+ resource_type: str = "articles",
716
+ peer_reviewed: bool = False,
717
+ open_access: bool = False,
718
+ year_from: Optional[str] = None,
719
+ year_to: Optional[str] = None,
720
+ ) -> str:
721
+ """Build a full PRIMO discovery URL with facets."""
722
+ base = (
723
+ "https://khalifa.primo.exlibrisgroup.com/discovery/search"
724
+ f"?vid=971KUOSTAR_INST:KU&tab=Everything&scope=MyInst_and_CI"
725
+ f"&query=any,contains,{quote(boolean_query)}"
726
+ f"&lang=en&search_scope=MyInst_and_CI&sortby=rank&mode=advanced"
727
+ )
728
+ facets = []
729
+ if resource_type == "articles":
730
+ facets.append("facet_rtype,include,articles")
731
+ elif resource_type == "books":
732
+ facets.append("facet_rtype,include,books")
733
+ if peer_reviewed:
734
+ facets.append("facet_tlevel,include,peer_reviewed")
735
+ if open_access:
736
+ facets.append("facet_tlevel,include,online_resources")
737
+ if year_from or year_to:
738
+ yf = year_from or "0001"
739
+ yt = year_to or "9999"
740
+ facets.append(f"facet_searchcreationdate,include,{yf}|,|{yt}")
741
+ for facet in facets:
742
+ base += f"&multiFacets={quote(facet)}"
743
+ return base
744
+
745
+
746
+ def _shared_build_pubmed_url(
747
+ topic: str,
748
+ year_from: Optional[str] = None,
749
+ year_to: Optional[str] = None,
750
+ peer_reviewed: bool = False,
751
+ ) -> str:
752
+ """Build a PubMed search URL."""
753
+ clean = _strip_resource_noise(topic)
754
+ term = clean or topic
755
+ if peer_reviewed:
756
+ term = f"({term}) AND Journal Article[pt]"
757
+ url = f"https://pubmed.ncbi.nlm.nih.gov/?term={quote(term)}"
758
+ if year_from or year_to:
759
+ yf = year_from or "1900"
760
+ yt = year_to or str(CURRENT_YEAR)
761
+ url += f"&filter=datesearch.y_{yf}-{yt}"
762
+ return url
763
+
764
+
765
+ # ── Query Building ────────────────────────────────────────────────────────────
766
+
767
+ def _derive_resource_type(question: str, existing: Optional[str] = None) -> str:
768
+ q = (question or "").lower()
769
+ if any(token in q for token in ["book", "books", "ebook", "ebooks"]):
770
+ return "books"
771
+ if any(token in q for token in ["article", "articles", "paper", "papers", "study", "studies", "journal", "journals"]):
772
+ return "articles"
773
+ return existing or "articles"
774
+
775
+
776
+ def _parse_year_filters(question: str) -> Tuple[Optional[str], Optional[str]]:
777
+ q = (question or "").lower()
778
+ match = re.search(r"\b(last|past)\s+(\d{1,2})\s+years?\b", q)
779
+ if match:
780
+ years = int(match.group(2))
781
+ return str(CURRENT_YEAR - years + 1), str(CURRENT_YEAR)
782
+ between = re.search(r"\b(?:from|between)\s+(20\d{2}|19\d{2})\s+(?:to|and|-)\s+(20\d{2}|19\d{2})\b", q)
783
+ if between:
784
+ return between.group(1), between.group(2)
785
+ years = re.findall(r"\b(19\d{2}|20\d{2})\b", q)
786
+ if len(years) >= 2:
787
+ return min(years), max(years)
788
+ if len(years) == 1 and any(word in q for word in ["since", "from", "after"]):
789
+ return years[0], str(CURRENT_YEAR)
790
+ return None, None
791
+
792
+
793
+ def _make_primo_boolean_query(context: SearchContextPayload) -> str:
794
+ topic = _title_case_topic(context.display_topic or context.topic)
795
+ topic = _strip_resource_noise(topic) or (context.topic or "library search")
796
+ return _shared_build_primo_boolean_query(topic)
797
+
798
+
799
+ def _primo_clean_url(context: SearchContextPayload) -> str:
800
+ boolean_query = context.primo_boolean_query or _make_primo_boolean_query(context)
801
+ return _shared_build_primo_discovery_url(
802
+ boolean_query,
803
+ resource_type=context.resource_type,
804
+ peer_reviewed=context.peer_reviewed,
805
+ open_access=context.open_access,
806
+ year_from=context.year_from,
807
+ year_to=context.year_to,
808
+ )
809
+
810
+
811
+ def _compose_ai_tool_query(question: str, context: SearchContextPayload, is_follow_up: bool) -> str:
812
+ topic = context.display_topic or context.topic
813
+ topic = _title_case_topic(topic)
814
+ scope = context.resource_type
815
+ filters = []
816
+ if context.peer_reviewed:
817
+ filters.append("peer-reviewed")
818
+ if context.open_access:
819
+ filters.append("open-access")
820
+ if context.year_from and context.year_to:
821
+ filters.append(f"published between {context.year_from} and {context.year_to}")
822
+ elif context.year_from:
823
+ filters.append(f"published from {context.year_from} onward")
824
+
825
+ if is_follow_up:
826
+ if scope == "books":
827
+ base = f"Find books on {topic}"
828
+ elif scope == "both":
829
+ base = f"Find articles and books on {topic}"
830
+ else:
831
+ base = f"Find research articles on {topic}"
832
+ else:
833
+ base = _normalize_whitespace(question).strip(".?")
834
+ if len(base.split()) < 4:
835
+ base = f"Find research on {topic}"
836
+
837
+ if filters:
838
+ return f"{base} with {', '.join(filters)}."
839
+ return base.rstrip(".") + "."
840
+
841
+
842
+ async def _grammar_refine_query(text: str, model: str) -> str:
843
+ settings = get_settings()
844
+ if not settings.openai_api_key and not settings.anthropic_api_key:
845
+ return _normalize_whitespace(text)
846
+ try:
847
+ llm = _get_llm(model, temperature=0, max_tokens=60)
848
+ response = await llm.ainvoke([
849
+ {"role": "system", "content": "Rewrite the user's search question in clear grammatical English. Keep the meaning exactly the same. Return one sentence only."},
850
+ {"role": "user", "content": text},
851
+ ])
852
+ refined = _normalize_whitespace(response.content)
853
+ return refined or _normalize_whitespace(text)
854
+ except Exception:
855
+ return _normalize_whitespace(text)
856
+
857
+
858
+ def _context_to_dict(context: SearchContextPayload) -> dict:
859
+ return context.model_dump()
860
+
861
+
862
+ async def _prepare_queries(question: str, context: SearchContextPayload, model: str, is_follow_up: bool) -> SearchContextPayload:
863
+ natural = _compose_ai_tool_query(question, context, is_follow_up)
864
+ natural = await _grammar_refine_query(natural, model)
865
+ context.ai_tool_query = natural
866
+ context.primo_boolean_query = _make_primo_boolean_query(context)
867
+ return context
868
+
869
+
870
+ # ── Semantic Scholar + Summary ────────────────────────────────────────────────
871
+
872
+ async def _semantic_scholar_search(topic: str, limit: int = 8) -> List[dict]:
873
+ clean_topic = _strip_resource_noise(topic)
874
+ if not clean_topic:
875
+ clean_topic = topic
876
+ try:
877
+ params = {
878
+ "query": clean_topic,
879
+ "limit": limit,
880
+ "fields": "title,authors,year,venue,abstract,externalIds,openAccessPdf",
881
+ }
882
+ async with httpx.AsyncClient(timeout=15) as client:
883
+ r = await client.get("https://api.semanticscholar.org/graph/v1/paper/search", params=params)
884
+ if r.status_code != 200:
885
+ logger.warning(f"Semantic Scholar {r.status_code} for '{clean_topic}'")
886
+ return []
887
+ data = r.json()
888
+ results = []
889
+ for paper in data.get("data", []):
890
+ abstract = paper.get("abstract") or ""
891
+ if not abstract or len(abstract) < 50:
892
+ continue
893
+ author_list = paper.get("authors") or []
894
+ first_author_last = author_list[0].get("name", "Unknown").split()[-1] if author_list else "Unknown"
895
+ year = paper.get("year") or "n.d."
896
+ paper_id = paper.get("paperId", "")
897
+ doi = (paper.get("externalIds") or {}).get("DOI", "")
898
+ pdf_url = (paper.get("openAccessPdf") or {}).get("url", "")
899
+ link = (
900
+ pdf_url
901
+ or (f"https://doi.org/{doi}" if doi else "")
902
+ or (f"https://www.semanticscholar.org/paper/{paper_id}" if paper_id else "#")
903
+ )
904
+ results.append({
905
+ "title": paper.get("title", "Untitled"),
906
+ "authors": (
907
+ ", ".join(a.get("name", "") for a in author_list[:3])
908
+ + (" et al." if len(author_list) > 3 else "")
909
+ ),
910
+ "first_author": first_author_last,
911
+ "year": year,
912
+ "citation_key": f"{first_author_last}, {year}",
913
+ "venue": paper.get("venue", ""),
914
+ "abstract": abstract[:700],
915
+ "link": link,
916
+ "_source": "Semantic Scholar",
917
+ })
918
+ return results
919
+ except Exception as e:
920
+ logger.error(f"Semantic Scholar search failed: {e}")
921
+ return []
922
+
923
+
924
+ async def _generate_cited_summary(topic: str, papers: List[dict], model: str) -> str:
925
+ settings = get_settings()
926
+ if not settings.openai_api_key and not settings.anthropic_api_key:
927
+ return ""
928
+ if not papers:
929
+ return ""
930
+ context_text = ""
931
+ for i, paper in enumerate(papers, 1):
932
+ context_text += (
933
+ f"[{i}] {paper['citation_key']}: {paper['title']}\n"
934
+ f"Abstract: {paper['abstract']}\n\n"
935
+ )
936
+ system = (
937
+ "You are a research librarian writing a concise academic literature snapshot. "
938
+ "Using ONLY the numbered references provided, write a 4-6 sentence summary on the given topic. "
939
+ "Use in-text citations as [1], [2], [3] etc. referring to the numbered references. "
940
+ "Cite at least 4 different references. "
941
+ "Use HTML <br><br> for paragraph breaks. Do not use bullet points or markdown. "
942
+ "Only state what is explicitly supported by the abstracts. "
943
+ "Do NOT invent content."
944
+ )
945
+ try:
946
+ llm = _get_llm(model, temperature=0.2, max_tokens=560)
947
+ response = await llm.ainvoke([
948
+ {"role": "system", "content": system},
949
+ {"role": "user", "content": f"Topic: {topic}\n\nReferences:\n{context_text}\nWrite the summary."},
950
+ ])
951
+ summary = response.content.strip()
952
+ for i in range(len(papers), 0, -1):
953
+ paper = papers[i - 1]
954
+ title_escaped = _escape(paper["title"])
955
+ cite_html = (
956
+ f'<a href="{paper["link"]}" target="_blank" '
957
+ f'title="{title_escaped}" '
958
+ f'style="color:#1e40af;font-weight:600;text-decoration:none">'
959
+ f'[{paper["citation_key"]}]</a>'
960
+ )
961
+ summary = summary.replace(f"[{i}]", cite_html)
962
+ return summary
963
+ except Exception as e:
964
+ logger.error(f"Summary generation failed: {e}")
965
+ return ""
966
+
967
+
968
+ def _extractive_snapshot_from_papers(topic: str, papers: List[dict]) -> str:
969
+ if not papers:
970
+ return ""
971
+ statements: List[str] = []
972
+ for paper in papers[:4]:
973
+ sentences = re.split(r"(?<=[.!?])\s+", paper.get("abstract", ""))
974
+ lead = sentences[0].strip() if sentences else ""
975
+ if not lead:
976
+ continue
977
+ citation = (
978
+ f'<a href="{paper["link"]}" target="_blank" '
979
+ f'style="color:#1e40af;font-weight:600;text-decoration:none">'
980
+ f'[{_escape(paper["citation_key"])}]</a>'
981
+ )
982
+ statements.append(f"{_escape(lead)} {citation}")
983
+ if not statements:
984
+ return f"Recent literature on <strong>{_escape(topic)}</strong> is available in the cited papers below."
985
+ intro = f"Recent literature on <strong>{_escape(topic)}</strong>:<br><br>"
986
+ return intro + "<br><br>".join(statements[:4])
987
+
988
+
989
+ # ── PRIMO / PubMed Search Wrappers ────────────────────────────────────────────
990
+
991
+ async def _search_primo_catalog(context: SearchContextPayload, limit: int = 5) -> Tuple[dict, str]:
992
+ from src.api.search import SearchRequest, search_primo
993
+ settings = get_settings()
994
+ clean_topic = _strip_resource_noise(context.topic)
995
+ if not clean_topic:
996
+ clean_topic = context.topic
997
+ result = await search_primo(
998
+ SearchRequest(
999
+ query=clean_topic,
1000
+ source="primo",
1001
+ limit=limit,
1002
+ peer_reviewed=context.peer_reviewed,
1003
+ open_access=context.open_access,
1004
+ year_from=context.year_from,
1005
+ year_to=context.year_to,
1006
+ resource_type=context.resource_type,
1007
+ ),
1008
+ settings.primo_api_key,
1009
+ )
1010
+ source_url = _primo_clean_url(context)
1011
+ return result, source_url
1012
+
1013
+
1014
+ async def _search_pubmed_articles(context: SearchContextPayload, limit: int = 5) -> Tuple[dict, str]:
1015
+ from src.api.search import SearchRequest, search_pubmed
1016
+ clean_topic = _strip_resource_noise(context.topic)
1017
+ if not clean_topic:
1018
+ clean_topic = context.topic
1019
+ result = await search_pubmed(
1020
+ SearchRequest(
1021
+ query=clean_topic,
1022
+ source="pubmed",
1023
+ limit=limit,
1024
+ peer_reviewed=context.peer_reviewed,
1025
+ year_from=context.year_from,
1026
+ year_to=context.year_to,
1027
+ )
1028
+ )
1029
+ pubmed_url = _shared_build_pubmed_url(
1030
+ clean_topic, context.year_from, context.year_to, context.peer_reviewed
1031
+ )
1032
+ return result, pubmed_url
1033
+
1034
+
1035
+ # ── AI Tools / Database Guidance ─────────────────────────────────────────────
1036
+
1037
+ def _tool_urls(context: SearchContextPayload) -> Dict[str, str]:
1038
+ ai_query = quote(context.ai_tool_query or context.display_topic or context.topic)
1039
+ primo_ai_query = quote(context.ai_tool_query or context.display_topic or context.topic)
1040
+ urls: Dict[str, str] = {
1041
+ "leapspace": f"https://www.sciencedirect.com/leapspace?query={ai_query}",
1042
+ "scopus_ai": f"https://www-scopus-com.khalifa.idm.oclc.org/pages/ai?query={ai_query}",
1043
+ "ebsco_ai": f"https://research-ebsco-com.khalifa.idm.oclc.org/c/ntdlkp/search?q={ai_query}",
1044
+ "primo_ai": f"{PRIMO_AI_URL}{primo_ai_query}",
1045
+ "consensus": f"https://consensus.app/results/?q={ai_query}",
1046
+ "primo_discovery": _primo_clean_url(context),
1047
+ }
1048
+ if context.intent == "search_medical":
1049
+ urls["pubmed"] = _shared_build_pubmed_url(
1050
+ context.topic, context.year_from, context.year_to, context.peer_reviewed
1051
+ )
1052
+ return urls
1053
+
1054
+
1055
+ def _database_guidance_for_topic(context: SearchContextPayload) -> str:
1056
+ topic = _escape(context.display_topic or context.topic)
1057
+ urls = _tool_urls(context)
1058
+ ai_tools = (
1059
+ f'<a href="{urls["leapspace"]}" target="_blank" style="color:#9a3412;font-weight:700;text-decoration:none">LeapSpace</a> Β· '
1060
+ f'<a href="{urls["scopus_ai"]}" target="_blank" style="color:#1e40af;font-weight:700;text-decoration:none">Scopus AI</a> Β· '
1061
+ f'<a href="{urls["ebsco_ai"]}" target="_blank" style="color:#9d174d;font-weight:700;text-decoration:none">EBSCO AI</a> Β· '
1062
+ f'<a href="{urls["primo_ai"]}" target="_blank" style="color:#5b21b6;font-weight:700;text-decoration:none">PRIMO AI Assistant</a> Β· '
1063
+ f'<a href="{urls["consensus"]}" target="_blank" style="color:#86198f;font-weight:700;text-decoration:none">Consensus</a>'
1064
+ )
1065
+ more_results = f'<a href="{urls["primo_discovery"]}" target="_blank" style="color:#5b21b6;font-weight:700;text-decoration:none">PRIMO Library Discovery</a>'
1066
+ if context.intent == "search_medical" and urls.get("pubmed"):
1067
+ more_results += f' Β· <a href="{urls["pubmed"]}" target="_blank" style="color:#065f46;font-weight:700;text-decoration:none">PubMed</a>'
1068
+ return (
1069
+ f"For deeper work on <strong>{topic}</strong>, continue with these AI research tools: {ai_tools}. "
1070
+ f"For more results, use {more_results}. Medical topics are strongest in PubMed, Embase, and CINAHL."
1071
+ )
1072
+ return (
1073
+ f"For deeper work on <strong>{topic}</strong>, continue with these AI research tools: {ai_tools}. "
1074
+ f"For more results, use {more_results}."
1075
+ )
1076
+
1077
+
1078
+ def _find_staff_by_token(token: str) -> Optional[dict]:
1079
+ token = (token or "").lower()
1080
+ for staff in STAFF_DIRECTORY:
1081
+ hay = (staff.get("full_name", "") + " " + staff.get("role", "")).lower()
1082
+ if token in hay:
1083
+ return staff
1084
+ return None
1085
+
1086
+
1087
+ def _contact_footer_for_query(question: str, context: Optional[SearchContextPayload]) -> str:
1088
+ q = (question or "").lower()
1089
+ # FIX: removed broken default to _find_staff_by_token("muna") β€” Muna is not in STAFF_DIRECTORY
1090
+ specialist: Optional[dict] = None
1091
+ if any(t in q for t in ["database access", "proxy", "full text", "eresource", "e-resource", "remote access", "access problem"]):
1092
+ specialist = _find_staff_by_token("rani")
1093
+ elif any(t in q for t in ["website", "system", "technical", "login issue", "page not loading"]):
1094
+ specialist = _find_staff_by_token("walter")
1095
+ elif context and context.intent == "search_medical":
1096
+ specialist = _find_staff_by_token("jason")
1097
+ elif context and context.intent == "search_academic":
1098
+ specialist = _find_staff_by_token("nikesh")
1099
+
1100
+ footer = (
1101
+ "<br><br><strong>Library contact points</strong><br>"
1102
+ f'General help: <a href="{ASK_LIBRARIAN_URL}" target="_blank">Ask a Librarian</a> Β· '
1103
+ '<a href="mailto:libse@ku.ac.ae">libse@ku.ac.ae</a>'
1104
+ )
1105
+ if specialist:
1106
+ footer += (
1107
+ f'<br>Relevant contact: <strong>{_escape(specialist.get("full_name", ""))}</strong> β€” '
1108
+ f'{_escape(specialist.get("role", ""))}<br>'
1109
+ f'<a href="mailto:{_escape(specialist.get("email", ""))}">{_escape(specialist.get("email", ""))}</a>'
1110
+ )
1111
+ phone = specialist.get("phone") or specialist.get("work_phone")
1112
+ if phone:
1113
+ footer += f' Β· <a href="tel:{_escape(str(phone).replace(" ", ""))}">{_escape(phone)}</a>'
1114
+ return footer
1115
+
1116
+
1117
+ def _search_trace_block(question: str, context: SearchContextPayload) -> str:
1118
+ topic = _escape(context.display_topic or context.topic)
1119
+ question_html = _escape(question)
1120
+ primo_boolean = _escape(context.primo_boolean_query or "")
1121
+ found_via = "I identified the main topic, built a PRIMO search query, and looked for KU-accessible results."
1122
+ if context.intent == "search_medical":
1123
+ found_via += " Because this is a medical topic, PubMed is also recommended for broader evidence searching."
1124
+ block = (
1125
+ f'<div style="margin:10px 0 14px 0;padding:12px 14px;border:1px solid #dbe4ff;border-radius:12px;background:#f8fbff">'
1126
+ f"<strong>Your question:</strong> {question_html}<br>"
1127
+ f"<strong>Interpreted topic:</strong> {topic}<br>"
1128
+ )
1129
+ if primo_boolean:
1130
+ block += f"<strong>PRIMO query used:</strong> <code>{primo_boolean}</code><br>"
1131
+ block += f"<strong>How I found this:</strong> {found_via}</div>"
1132
+ return block
1133
+
1134
+
1135
+ def _is_database_recommendation_question(question: str) -> bool:
1136
+ return bool(DATABASE_RECOMMEND_RE.search(question or ""))
1137
+
1138
+
1139
+ def _database_recommendation_answer(question: str) -> str:
1140
+ q = (question or "").lower()
1141
+ topic = _escape(_strip_resource_noise(question))
1142
+ dbs = []
1143
+ if any(t in q for t in ["computer science", "artificial intelligence", "machine learning", " ai ", "cybersecurity"]):
1144
+ dbs = [
1145
+ ("ACM Digital Library", "https://khalifa.idm.oclc.org/login?url=https://dl.acm.org", "Core computer science literature."),
1146
+ ("IEEE Xplore", "https://khalifa.idm.oclc.org/login?url=https://ieeexplore.ieee.org", "Strong for AI, systems, and engineering computing."),
1147
+ ("Scopus", "https://khalifa.idm.oclc.org/login?url=https://www.scopus.com", "Broad discovery and citation tracking."),
1148
+ ]
1149
+ elif any(t in q for t in ["medical", "health", "nursing", "clinical", "biomedical"]):
1150
+ dbs = [
1151
+ ("PubMed@KU", "http://www.ncbi.nlm.nih.gov/pubmed/?otool=iaekustlib", "Core biomedical literature with KU full-text links."),
1152
+ ("Embase", "https://khalifa.idm.oclc.org/login?url=https://www.embase.com", "Biomedical and pharmacological literature."),
1153
+ ("CINAHL Ultimate", "https://khalifa.idm.oclc.org/login?url=https://search.ebscohost.com/login.aspx?authtype=ip,uid&profile=ehost&defaultdb=cul", "Nursing and allied health literature."),
1154
+ ]
1155
+ elif "civil" in q:
1156
+ dbs = [
1157
+ ("ASCE Library", "https://khalifa.idm.oclc.org/login?url=https://ascelibrary.org", "Core civil engineering journals and conference papers."),
1158
+ ("ScienceDirect", "https://khalifa.idm.oclc.org/login?url=https://www.sciencedirect.com", "Strong full text across civil engineering topics."),
1159
+ ("Scopus", "https://khalifa.idm.oclc.org/login?url=https://www.scopus.com", "Discovery and citation tracking."),
1160
+ ]
1161
+ elif "mechanical" in q:
1162
+ dbs = [
1163
+ ("ASME Digital Library", "https://khalifa.idm.oclc.org/login?url=https://asmedigitalcollection.asme.org", "Core mechanical engineering literature."),
1164
+ ("Knovel", "https://khalifa.idm.oclc.org/login?url=https://app.knovel.com/kn", "Engineering reference books and data."),
1165
+ ("ScienceDirect", "https://khalifa.idm.oclc.org/login?url=https://www.sciencedirect.com", "Broad full text."),
1166
+ ]
1167
+ elif "electrical" in q:
1168
+ dbs = [
1169
+ ("IEEE Xplore", "https://khalifa.idm.oclc.org/login?url=https://ieeexplore.ieee.org/Xplore/dynhome.jsp", "Core electrical engineering database."),
1170
+ ("INSPEC", "https://khalifa.idm.oclc.org/login?url=https://www.theiet.org/publishing/inspec", "Strong indexing for EE and electronics."),
1171
+ ("Scopus", "https://khalifa.idm.oclc.org/login?url=https://www.scopus.com", "Discovery and citation tracking."),
1172
+ ]
1173
+ else:
1174
+ dbs = [
1175
+ ("PRIMO", "https://khalifa.primo.exlibrisgroup.com/discovery/search?vid=971KUOSTAR_INST:KU", "Best starting point for KU-accessible books, articles, and journals."),
1176
+ ("Scopus", "https://khalifa.idm.oclc.org/login?url=https://www.scopus.com", "Broad multidisciplinary discovery."),
1177
+ ("Web of Science", "https://khalifa.idm.oclc.org/login?url=https://www.webofscience.com", "Broad multidisciplinary citation searching."),
1178
+ ]
1179
+ answer = f"<strong>Best databases for {topic}</strong><br><br>"
1180
+ answer += "Here are strong starting points for this subject:<br>"
1181
+ for name, url, why in dbs:
1182
+ answer += f'<br>β€’ <a href="{url}" target="_blank"><strong>{name}</strong></a> β€” {_escape(why)}'
1183
+ answer += "<br><br>If you want, I can also turn this into a direct article search."
1184
+ return answer
1185
+
1186
+
1187
+ # ── Research Snapshot ─────────────────────────────────────────────────────────
1188
+
1189
+ async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple[str, List[dict], List[dict]]:
1190
+ topic = context.topic
1191
+ papers = await _semantic_scholar_search(topic, limit=8)
1192
+ references: List[dict] = []
1193
+ primo_result, primo_url = await _search_primo_catalog(context, limit=6)
1194
+ search_results = primo_result.get("results", []) or []
1195
+
1196
+ if papers:
1197
+ summary = await _generate_cited_summary(topic, papers, model)
1198
+ if not summary:
1199
+ _safe_metrics_increment("summary_fallbacks")
1200
+ summary = _extractive_snapshot_from_papers(topic, papers)
1201
+
1202
+ answer = f"<strong>πŸ“– Research Snapshot: {_escape(topic)}</strong><br><br>{summary}"
1203
+ if search_results:
1204
+ answer += (
1205
+ "<br><br><strong>KU Library starting points:</strong> "
1206
+ "I also pulled KU-accessible results below so you can move directly from the snapshot to subscribed material."
1207
+ )
1208
+ answer += f"<br><br><strong>AI sources:</strong> {_database_guidance_for_topic(context)}"
1209
+ answer += "<br><br><strong>Selected references:</strong><br>"
1210
+ for i, paper in enumerate(papers[:6], 1):
1211
+ answer += (
1212
+ f'<br><strong>[{i}]</strong> '
1213
+ f'<a href="{paper["link"]}" target="_blank" style="color:#003366;font-weight:600">{_escape(paper["title"])}</a><br>'
1214
+ f'<span style="font-size:.8rem;color:#6b7280">'
1215
+ f'{_escape(paper["authors"])} Β· {paper["year"]} Β· {_escape(paper["venue"] or "")}'
1216
+ f"</span>"
1217
+ )
1218
+ answer += _source_badge("semantic", "https://www.semanticscholar.org/")
1219
+ if search_results:
1220
+ answer += _source_badge("primo", primo_url)
1221
+ references = [{"title": p["title"], "url": p["link"]} for p in papers[:6]]
1222
+ return answer, search_results, references
1223
+
1224
+ if search_results:
1225
+ answer = (
1226
+ f"<strong>πŸ“š KU Library starting points on {_escape(topic)}</strong><br><br>"
1227
+ "I couldn't build a Semantic Scholar snapshot right now, but here are KU-accessible library results you can open immediately. "
1228
+ f"<br><br><strong>AI sources:</strong> {_database_guidance_for_topic(context)}"
1229
+ )
1230
+ else:
1231
+ answer = (
1232
+ f"I couldn't retrieve a research snapshot for <strong>{_escape(topic)}</strong> right now.<br><br>"
1233
+ f"<strong>AI sources:</strong> {_database_guidance_for_topic(context)}"
1234
+ )
1235
+ answer += _source_badge("primo", primo_url)
1236
+ return answer, search_results, []
1237
+
1238
+
1239
+ # ── Follow-up System ──────────────────────────────────────────────────────────
1240
+
1241
+ def _filters_summary(context: SearchContextPayload) -> str:
1242
+ filters: List[str] = []
1243
+ if context.peer_reviewed:
1244
+ filters.append("peer reviewed only")
1245
+ if context.open_access:
1246
+ filters.append("open access")
1247
+ if context.year_from and context.year_to:
1248
+ filters.append(f"{context.year_from}–{context.year_to}")
1249
+ elif context.year_from:
1250
+ filters.append(f"from {context.year_from}")
1251
+ if context.resource_type == "books":
1252
+ filters.append("books")
1253
+ elif context.resource_type == "articles":
1254
+ filters.append("articles")
1255
+ elif context.resource_type == "both":
1256
+ filters.append("articles and books")
1257
+ return ", ".join(filters)
1258
+
1259
+
1260
+ def _question_has_new_topic(question: str, base_topic: str) -> bool:
1261
+ q = (question or "").lower()
1262
+ cleaned = re.sub(
1263
+ r"\b(peer[- ]reviewed|open access|last \d+ years?|past \d+ years?|books? instead|articles? instead|"
1264
+ r"summari[sz]e( this topic)?|overview|brief|use pubmed|search pubmed|search primo|best databases?|deep research tools?)\b",
1265
+ " ", q,
1266
+ )
1267
+ tokens = [t for t in re.findall(r"[a-z0-9]+", cleaned) if t not in REFINEMENT_STOP_WORDS and len(t) > 2]
1268
+ if len(tokens) < 3:
1269
+ return False
1270
+ base_tokens = {t for t in re.findall(r"[a-z0-9]+", (base_topic or "").lower()) if t not in REFINEMENT_STOP_WORDS}
1271
+ overlap = sum(1 for t in tokens if t in base_tokens)
1272
+ return overlap <= max(1, min(2, len(base_tokens)))
1273
+
1274
+
1275
+ def _parse_refinement_action(question: str) -> Optional[str]:
1276
+ q = (question or "").lower().strip()
1277
+ if re.search(r"\b(peer[- ]reviewed|peer reviewed only|peer reviewd|peer review only)\b", q):
1278
+ return "peer_reviewed_only"
1279
+ if re.search(r"\b(open access|oa only|only open access)\b", q):
1280
+ return "open_access_only"
1281
+ if re.search(r"\b(last|past)\s+5\s+years?\b", q):
1282
+ return "last_5_years"
1283
+ if re.search(r"\b(last|past)\s+10\s+years?\b|\bpast decade\b", q):
1284
+ return "last_10_years"
1285
+ if re.search(r"\bbooks? instead\b|\bbooks? only\b|\bfind books?\b|\bshow books?\b", q):
1286
+ return "books_only"
1287
+ if re.search(r"\barticles? instead\b|\barticles? only\b|\bpapers? only\b", q):
1288
+ return "articles_only"
1289
+ if re.search(r"\b(?:both|articles and books|books and articles)\b", q):
1290
+ return "both_resources"
1291
+ if re.search(r"\b(summar(y|ize|ise)|overview|brief|what does the literature say|research snapshot)\b", q):
1292
+ return "summarize_topic"
1293
+ if re.search(r"\bpubmed\b", q):
1294
+ return "search_pubmed"
1295
+ if re.search(r"\bprimo\b", q):
1296
+ return "search_primo"
1297
+ if re.search(r"\b(best database|best databases|which database|which databases)\b", q):
1298
+ return "best_databases"
1299
+ if re.search(r"\b(deep research|deep dive|full literature review|exhaustive)\b", q):
1300
+ return "deep_research_tools"
1301
+ return None
1302
+
1303
+
1304
+ def _resolve_base_context(client_state: Optional[ClientStatePayload]) -> Optional[SearchContextPayload]:
1305
+ if not client_state or not client_state.recent_search_contexts:
1306
+ return None
1307
+ contexts = list(client_state.recent_search_contexts)
1308
+ if client_state.follow_up_context_id:
1309
+ for ctx in contexts:
1310
+ if ctx.context_id == client_state.follow_up_context_id:
1311
+ return ctx
1312
+ if client_state.active_search_context_id:
1313
+ for ctx in contexts:
1314
+ if ctx.context_id == client_state.active_search_context_id:
1315
+ return ctx
1316
+ contexts.sort(key=lambda c: c.created_at, reverse=True)
1317
+ return contexts[0]
1318
+
1319
+
1320
+ def _detect_follow_up(
1321
+ question: str, client_state: Optional[ClientStatePayload]
1322
+ ) -> Tuple[bool, Optional[str], Optional[SearchContextPayload]]:
1323
+ base_context = _resolve_base_context(client_state)
1324
+ if not base_context:
1325
+ return False, None, None
1326
+ explicit_action = (client_state.follow_up_action if client_state else None) or None
1327
+ if explicit_action:
1328
+ return True, explicit_action, base_context
1329
+ action = _parse_refinement_action(question)
1330
+ if not action:
1331
+ return False, None, None
1332
+ if _question_has_new_topic(question, base_context.topic):
1333
+ return False, None, None
1334
+ return True, action, base_context
1335
+
1336
+
1337
+ def _clone_context(base_context: SearchContextPayload) -> SearchContextPayload:
1338
+ return SearchContextPayload.model_validate(base_context.model_dump())
1339
+
1340
+
1341
+ def _apply_follow_up_action(base_context: SearchContextPayload, action: Optional[str]) -> SearchContextPayload:
1342
+ context = _clone_context(base_context)
1343
+ context.context_id = str(uuid.uuid4())
1344
+ context.created_at = time.time()
1345
+ if action == "peer_reviewed_only":
1346
+ context.peer_reviewed = True
1347
+ elif action == "open_access_only":
1348
+ context.open_access = True
1349
+ elif action == "last_5_years":
1350
+ context.year_from = str(CURRENT_YEAR - 4)
1351
+ context.year_to = str(CURRENT_YEAR)
1352
+ elif action == "last_10_years":
1353
+ context.year_from = str(CURRENT_YEAR - 9)
1354
+ context.year_to = str(CURRENT_YEAR)
1355
+ elif action == "books_only":
1356
+ context.resource_type = "books"
1357
+ elif action == "articles_only":
1358
+ context.resource_type = "articles"
1359
+ elif action == "both_resources":
1360
+ context.resource_type = "both"
1361
+ elif action == "search_pubmed":
1362
+ context.source = "pubmed"
1363
+ context.intent = "search_medical"
1364
+ context.resource_type = "articles"
1365
+ elif action == "search_primo":
1366
+ context.source = "primo"
1367
+ return context
1368
+
1369
+
1370
+ async def _generate_topic_follow_ups(topic: str, model: str) -> List[dict]:
1371
+ settings = get_settings()
1372
+ if not settings.openai_api_key and not settings.anthropic_api_key:
1373
+ return []
1374
+ try:
1375
+ llm = _get_llm(model, temperature=0.5, max_tokens=200)
1376
+ response = await llm.ainvoke([
1377
+ {"role": "system", "content": (
1378
+ "You are a research librarian helping a user explore a topic more deeply. "
1379
+ "Given a research topic, generate exactly 3 short follow-up questions that explore "
1380
+ "DIFFERENT ASPECTS of the topic β€” such as subtopics, methodological angles, "
1381
+ "applications, comparisons, or related fields. "
1382
+ "Do NOT suggest filter actions like peer-reviewed, date ranges, or format changes. "
1383
+ "Return ONLY a JSON array of 3 strings, each under 12 words. "
1384
+ "No explanation, no preamble, no markdown.\n"
1385
+ "Example for 'quantum computing':\n"
1386
+ '[\"What are the main hardware approaches in quantum computing?\", '
1387
+ '"How does quantum error correction work?\", '
1388
+ '"Applications of quantum computing in cryptography\"]'
1389
+ )},
1390
+ {"role": "user", "content": f"Topic: {topic}"},
1391
+ ])
1392
+ raw = response.content.strip()
1393
+ if raw.startswith("```"):
1394
+ raw = raw.split("\n", 1)[1].rsplit("```", 1)[0].strip()
1395
+ questions = json.loads(raw)
1396
+ if not isinstance(questions, list):
1397
+ return []
1398
+ return [
1399
+ {"label": q.strip("?") + "?", "question": q.strip("?") + "?"}
1400
+ for q in questions[:3]
1401
+ if isinstance(q, str) and q.strip()
1402
+ ]
1403
+ except Exception as e:
1404
+ logger.warning(f"Topic follow-up generation failed: {e}")
1405
+ return []
1406
+
1407
+
1408
  async def _search_follow_up(
1409
  context: SearchContextPayload, model: str, summary_mode: bool = False
1410
  ) -> Tuple[str, List[dict]]:
 
 
 
 
 
1411
  topic = context.display_topic or context.topic
1412
  suggestions: List[dict] = []
 
 
1413
  topic_follow_ups = await _generate_topic_follow_ups(topic, model)
1414
  suggestions.extend(topic_follow_ups)
1415
 
 
1416
  filter_suggestions: List[dict] = []
1417
  if summary_mode:
1418
  filter_suggestions.append({
 
1430
  else:
1431
  if not context.peer_reviewed and context.source == "primo":
1432
  filter_suggestions.append({
1433
+ "label": "Peer reviewed only",
1434
  "question": f"Make the {topic} search peer reviewed only",
1435
  "action": "peer_reviewed_only",
1436
  "context_id": context.context_id,
 
1456
  "context_id": context.context_id,
1457
  })
1458
 
 
1459
  suggestions.extend(filter_suggestions[:2])
 
1460
  question_text = (
1461
  f"Here are some related angles you might want to explore on <strong>{_escape(topic)}</strong>. "
1462
  "Or I can refine the search with filters β€” just ask."
 
1546
  search_results = result.get("results", []) or []
1547
  total = result.get("total", len(search_results))
1548
 
1549
+ answer = _search_answer_intro(context, is_follow_up)
1550
  if filters:
1551
  answer += f"<br><br><strong>Current filters:</strong> {_escape(filters)}."
1552
  if search_results:
1553
  answer += f"<br><br>I found <strong>{total}</strong> result(s). The top items are shown below."
1554
  else:
1555
+ answer += (
1556
+ "<br><br>I couldn't retrieve matching results right now. "
1557
+ "You can still try the direct library links and AI research tools below."
1558
+ )
1559
  if context.intent == "search_medical" and context.source != "pubmed":
1560
  answer += "<br><br>For the strongest medical evidence trail, I also recommend checking <strong>PubMed</strong> or <strong>Embase</strong>."
1561
 
1562
  answer += _source_badge(source_name, source_url)
 
1563
  sources = []
1564
  for item in search_results[:6]:
1565
  link = item.get("primo_url") or item.get("link")
 
1576
  return ordered[:5]
1577
 
1578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1579
  # ── Main Endpoint ──────────────────────────────────────────────────────────────
1580
 
1581
  @router.post("", response_model=AgentResponse)
 
1680
  follow_up_suggestions=follow_up_suggestions,
1681
  )
1682
 
1683
+ if _is_database_recommendation_question(question):
1684
+ answer = _database_recommendation_answer(question)
1685
+ answer += _contact_footer_for_query(question, None)
1686
+ answer += _source_badge("ku_library", "https://library.ku.ac.ae/eresources")
1687
+ follow_up_question, follow_up_suggestions = _library_follow_up(question)
1688
+ return AgentResponse(
1689
+ answer=answer,
1690
+ intent="library_info",
1691
+ tools_used=["database_recommendation"],
1692
+ model_used=model,
1693
+ response_time=time.time() - start_time,
1694
+ follow_up_question=follow_up_question,
1695
+ follow_up_suggestions=follow_up_suggestions,
1696
+ )
1697
+
1698
  is_follow_up, follow_up_action, base_context = _detect_follow_up(question, client_state)
1699
 
1700
  if is_follow_up and base_context:
 
1705
  context = await _prepare_queries(question, context, model, True)
1706
  if follow_up_action == "summarize_topic":
1707
  answer, search_results, sources = await _research_snapshot(context, model)
 
 
 
 
1708
  else:
1709
  answer = (
1710
  f"<strong>Research guide for {_escape(context.display_topic or context.topic)}</strong><br><br>"
1711
  f"{_database_guidance_for_topic(context)}"
1712
  + _source_badge("libbee")
 
1713
  )
1714
  search_results = []
1715
  sources = []
 
1729
  ai_tool_query=context.ai_tool_query,
1730
  primo_boolean_query=context.primo_boolean_query,
1731
  primo_search_url=_primo_clean_url(context),
1732
+ primo_ai_url=_tool_urls(context).get("primo_ai"),
1733
+ pubmed_search_url=_tool_urls(context).get("pubmed"),
1734
  follow_up_question=follow_up_question,
1735
  follow_up_suggestions=follow_up_suggestions,
1736
  search_context=_context_to_dict(context),
 
1753
  ai_tool_query=context.ai_tool_query,
1754
  primo_boolean_query=context.primo_boolean_query,
1755
  primo_search_url=source_url,
1756
+ primo_ai_url=_tool_urls(context).get("primo_ai"),
1757
+ pubmed_search_url=_tool_urls(context).get("pubmed"),
1758
  follow_up_question=follow_up_question,
1759
  follow_up_suggestions=follow_up_suggestions,
1760
  search_context=_context_to_dict(context),
1761
  is_follow_up=True,
1762
  )
1763
 
1764
+ # FIX: _llm_classify always falls back to rule-based on any exception
1765
  cls_result = await _llm_classify(question, history, model)
1766
  intent = cls_result.get("intent", "general")
1767
  _safe_metrics_bucket("intents", intent)
1768
  casual_hint = cls_result.get("casual_answer", "")
1769
 
1770
  if intent == "social":
1771
+ answer = (
1772
+ casual_hint
1773
+ if casual_hint and len(casual_hint.strip()) > 20
1774
+ else await _libbee_casual_response(question, history, model, casual_hint)
1775
+ )
1776
  follow_up_question, follow_up_suggestions = _social_follow_up()
1777
  return AgentResponse(
1778
  answer=answer + _source_badge("libbee"),
 
1784
  follow_up_suggestions=follow_up_suggestions,
1785
  )
1786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1787
  if intent == "library_info":
1788
+ # FIX: use get_rag_service() accessor β€” safe against circular import failures
1789
+ rag_results = []
1790
  try:
1791
+ from app import get_rag_service
1792
+ rag_results = await get_rag_service().hybrid_search(question, top_k=4)
1793
  except Exception as e:
1794
  logger.error(f"RAG search failed: {e}")
 
1795
 
1796
  if not rag_results:
1797
  answer = (
 
1806
  else:
1807
  answer = await _rag_answer(question, rag_results, history, model)
1808
  answer += _source_badge("rag", "https://library.ku.ac.ae/")
1809
+ sources = [
1810
+ {"title": r.get("title", "Library KB"), "url": r.get("source", "")}
1811
+ for r in rag_results
1812
+ if r.get("source")
1813
+ ]
1814
  tools_used = ["rag_hybrid_search"]
1815
 
1816
  follow_up_question, follow_up_suggestions = _library_follow_up(question)
 
1852
 
1853
  if summary_mode or deep_research_mode:
1854
  answer, search_results, sources = await _research_snapshot(context, model)
 
1855
  if deep_research_mode and "Research guide" not in answer:
1856
+ answer += f"<br><br><strong>Research guide:</strong> {_database_guidance_for_topic(context)}"
 
1857
  follow_up_question, follow_up_suggestions = await _search_follow_up(context, model, summary_mode=True)
1858
  _safe_metrics_increment("search_handoffs")
1859
  return AgentResponse(
 
1870
  ai_tool_query=context.ai_tool_query,
1871
  primo_boolean_query=context.primo_boolean_query,
1872
  primo_search_url=_primo_clean_url(context),
1873
+ primo_ai_url=_tool_urls(context).get("primo_ai"),
1874
+ pubmed_search_url=_tool_urls(context).get("pubmed"),
1875
  follow_up_question=follow_up_question,
1876
  follow_up_suggestions=follow_up_suggestions,
1877
  search_context=_context_to_dict(context),
 
1893
  ai_tool_query=context.ai_tool_query,
1894
  primo_boolean_query=context.primo_boolean_query,
1895
  primo_search_url=source_url,
1896
+ primo_ai_url=_tool_urls(context).get("primo_ai"),
1897
+ pubmed_search_url=_tool_urls(context).get("pubmed"),
1898
  follow_up_question=follow_up_question,
1899
  follow_up_suggestions=follow_up_suggestions,
1900
  search_context=_context_to_dict(context),
 
1939
 
1940
  @router.get("/rag-status")
1941
  async def rag_status():
1942
+ # FIX: use get_rag_service() accessor
1943
  try:
1944
+ from app import get_rag_service
1945
+ return get_rag_service().get_stats()
1946
  except Exception as e:
1947
  return {"error": str(e), "ready": False}