nikeshn commited on
Commit
3ea7743
Β·
verified Β·
1 Parent(s): c29d798

Update src/api/agent.py

Browse files
Files changed (1) hide show
  1. src/api/agent.py +619 -2
src/api/agent.py CHANGED
@@ -234,10 +234,107 @@ DATABASE_RECOMMEND_RE = re.compile(
234
  r"|\be.?resources?\s+(available|subscri)\b"
235
  r"|\baccess\s+to\s+databases?\b"
236
  r"|\blist\s+of\s+databases?\b"
 
 
 
 
 
237
  r")",
238
  re.IGNORECASE,
239
  )
240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  MEDICAL_KEYWORDS = [
242
  "medicine", "medical", "health", "clinical", "nursing", "pharmacy", "biomedical",
243
  "anatomy", "physiology", "epidemiology", "oncology", "cardiology", "neuroscience",
@@ -1877,6 +1974,208 @@ def _database_recommendation_answer(question: str) -> str:
1877
  return answer
1878
 
1879
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1880
  # ── Research Snapshot ─────────────────────────────────────────────────────────
1881
 
1882
  async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple[str, List[dict], List[dict]]:
@@ -1999,12 +2298,22 @@ def _parse_refinement_action(question: str) -> Optional[str]:
1999
  return "last_5_years"
2000
  if re.search(r"\b(last|past)\s+10\s+years?\b|\bpast decade\b", q):
2001
  return "last_10_years"
 
 
 
 
2002
  if re.search(r"\bbooks? instead\b|\bbooks? only\b|\bfind books?\b|\bshow books?\b", q):
2003
  return "books_only"
2004
  if re.search(r"\barticles? instead\b|\barticles? only\b|\bpapers? only\b", q):
2005
  return "articles_only"
2006
  if re.search(r"\b(?:both|articles and books|books and articles)\b", q):
2007
  return "both_resources"
 
 
 
 
 
 
2008
  if re.search(r"\b(summar(y|ize|ise)|overview|brief|what does the literature say|research snapshot)\b", q):
2009
  return "summarize_topic"
2010
  if re.search(r"\bpubmed\b", q):
@@ -2069,12 +2378,32 @@ def _apply_follow_up_action(base_context: SearchContextPayload, action: Optional
2069
  elif action == "last_10_years":
2070
  context.year_from = str(CURRENT_YEAR - 9)
2071
  context.year_to = str(CURRENT_YEAR)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2072
  elif action == "books_only":
2073
  context.resource_type = "books"
2074
  elif action == "articles_only":
2075
  context.resource_type = "articles"
2076
  elif action == "both_resources":
2077
  context.resource_type = "both"
 
 
 
 
 
 
2078
  elif action == "search_pubmed":
2079
  context.source = "pubmed"
2080
  context.intent = "search_medical"
@@ -2560,6 +2889,184 @@ async def agent_query(request: Request, req: AgentRequest):
2560
  is_follow_up=True,
2561
  )
2562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2563
  # FIX: _llm_classify always falls back to rule-based on any exception
2564
  cls_result = await _llm_classify(question, history, model)
2565
  intent = cls_result.get("intent", "general")
@@ -2628,9 +3135,115 @@ async def agent_query(request: Request, req: AgentRequest):
2628
  )
2629
 
2630
  if intent in ("search_academic", "search_medical"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2631
  topic = await _extract_topic(question, model)
2632
  topic = _title_case_topic(topic)
2633
  year_from, year_to = _parse_year_filters(question)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2634
  context = SearchContextPayload(
2635
  context_id=str(uuid.uuid4()),
2636
  topic=topic,
@@ -2650,13 +3263,14 @@ async def agent_query(request: Request, req: AgentRequest):
2650
  r"\b(deep research|deep dive|systematic review|full literature review|exhaustive)\b",
2651
  question, re.IGNORECASE,
2652
  ))
 
2653
 
2654
  if summary_mode or deep_research_mode:
2655
  answer, search_results, sources = await _research_snapshot(context, model)
2656
- # _research_snapshot already includes _search_trace_block and _ai_tools_footer
2657
- # Only append extra deep-research guidance if not already present
2658
  if deep_research_mode and "Research guide" not in answer and "AI tools" not in answer:
2659
  answer += f"<br><br>{_ai_tools_footer(context)}"
 
 
2660
  follow_up_question, follow_up_suggestions = await _search_follow_up(context, model, summary_mode=True)
2661
  _safe_metrics_increment("search_handoffs")
2662
  return AgentResponse(
@@ -2681,6 +3295,9 @@ async def agent_query(request: Request, req: AgentRequest):
2681
  )
2682
 
2683
  answer, search_results, sources, source_url = await _run_search_mode(question, context, model, False)
 
 
 
2684
  follow_up_question, follow_up_suggestions = await _search_follow_up(context, model)
2685
  return AgentResponse(
2686
  answer=answer,
 
234
  r"|\be.?resources?\s+(available|subscri)\b"
235
  r"|\baccess\s+to\s+databases?\b"
236
  r"|\blist\s+of\s+databases?\b"
237
+ # comparison phrasing ← NEW
238
+ r"|\b(compare|comparison|difference|differences)\s+(between\s+)?(\w+\s+)?(and\s+)?\w*\s*database"
239
+ r"|\bdifference\s+between.{0,60}database"
240
+ r"|\bscopus\s+(vs|versus|or)\s+(web of science|wos|google scholar)\b"
241
+ r"|\b(web of science|wos)\s+(vs|versus|or)\s+(scopus|google scholar)\b"
242
  r")",
243
  re.IGNORECASE,
244
  )
245
 
246
+ # ── New pattern detection regexes ────────────────────────────────────────────
247
+
248
+ HIGHLY_CITED_RE = re.compile(
249
+ r"\b(highly cited|most cited|top cited|citation count|most influential"
250
+ r"|most referenced|high impact papers?|most downloaded)\b",
251
+ re.IGNORECASE,
252
+ )
253
+
254
+ BOOLEAN_STRATEGY_RE = re.compile(
255
+ r"\b(search strategy|boolean (search|operator|query|logic)"
256
+ r"|build.{0,20}search|help.{0,20}search strategy"
257
+ r"|how.{0,30}search.{0,30}(database|boolean|keyword)"
258
+ r"|refine.{0,30}(topic|question|research question|searchable)"
259
+ r"|turn.{0,30}(topic|question).{0,20}search"
260
+ r"|keywords? for.{0,30}search|search terms?"
261
+ r"|explain.{0,20}keyword|why.{0,20}(chose|choose|selected|pick).{0,20}keyword)\b",
262
+ re.IGNORECASE,
263
+ )
264
+
265
+ FULLTEXT_REQUEST_RE = re.compile(
266
+ r"\b(full.?text|full text|get.{0,15}article|access.{0,15}article"
267
+ r"|pdf.{0,20}(not available|unavailable|can.t find)"
268
+ r"|(can.t|cannot|don.t have).{0,30}(access|pdf|full.?text)"
269
+ r"|found.{0,30}citation.{0,30}(but|not).{0,20}(pdf|full.?text)"
270
+ r"|article.{0,20}(behind|paywall|not available|no access)"
271
+ r"|ku.{0,20}(doesn.t|does not|no).{0,20}(have|access)"
272
+ r"|interlibrary loan|ill request|borrow from another)\b",
273
+ re.IGNORECASE,
274
+ )
275
+
276
+ PARTIAL_TITLE_RE = re.compile(
277
+ r"\b(only (remember|recall|know).{0,20}(title|name)"
278
+ r"|title (starts?|begins?).{0,15}with"
279
+ r"|article.{0,20}(called|titled|named|starts? with)"
280
+ r"|find.{0,20}(article|paper).{0,20}(called|titled|named)"
281
+ r"|looking for.{0,20}(paper|article).{0,20}(about|called))\b",
282
+ re.IGNORECASE,
283
+ )
284
+
285
+ DUAL_RESOURCE_RE = re.compile(
286
+ r"\b(articles?.{0,30}(and|as well as|plus).{0,30}books?"
287
+ r"|books?.{0,30}(and|as well as|plus).{0,30}articles?"
288
+ r"|papers?.{0,30}(and|as well as|plus).{0,30}textbooks?"
289
+ r"|textbooks?.{0,30}(and|as well as|plus).{0,30}papers?"
290
+ r"|(literature review|articles?).{0,50}(background|textbook|introductory book)"
291
+ r"|(textbook|book).{0,50}(literature review|research articles?))\b",
292
+ re.IGNORECASE,
293
+ )
294
+
295
+ THESES_RE = re.compile(
296
+ r"\b(thes(is|es)|dissertation|doctoral|phd thesis|master.s thesis"
297
+ r"|khazna|ku repository|institutional repository"
298
+ r"|proquest dissertations?)\b",
299
+ re.IGNORECASE,
300
+ )
301
+
302
+ PREDATORY_RE = re.compile(
303
+ r"\b(predatory (journal|publisher|publication)"
304
+ r"|how.{0,20}(know|tell|check).{0,30}(peer.?reviewed|scholarly|legitimate|reputable)"
305
+ r"|is.{0,30}(journal|article).{0,30}(legitimate|reputable|trusted|peer.?reviewed)"
306
+ r"|peer.?reviewed vs|distinguish.{0,20}(peer|scholarly|predatory)"
307
+ r"|journal (quality|credibility|ranking|whitelist|blacklist)"
308
+ r"|beall.s list|doaj|cabells|think.check.submit)\b",
309
+ re.IGNORECASE,
310
+ )
311
+
312
+ CITATION_CHAIN_RE = re.compile(
313
+ r"\b(cited by|forward citation|backward citation|reference.{0,15}(chain|mining)"
314
+ r"|trace.{0,30}(reference|citation)|who cited|papers? that cite"
315
+ r"|related (articles?|papers?).{0,20}(paper|article)"
316
+ r"|find similar.{0,20}(paper|article))\b",
317
+ re.IGNORECASE,
318
+ )
319
+
320
+ REVIEW_ONLY_RE = re.compile(
321
+ r"\b(review (articles?|papers?|only)|only (review|systematic review)"
322
+ r"|limit.{0,20}review|show.{0,20}review|filter.{0,20}review"
323
+ r"|systematic reviews? only|literature reviews? only)\b",
324
+ re.IGNORECASE,
325
+ )
326
+
327
+ ALT_TERMS_RE = re.compile(
328
+ r"\b(alternative (search terms?|keywords?|terms?)"
329
+ r"|other (search terms?|keywords?|ways? to search)"
330
+ r"|more (keywords?|search terms?)|suggest.{0,20}keywords?"
331
+ r"|related (terms?|keywords?|synonyms?)|synonyms? for.{0,20}search"
332
+ r"|different (keywords?|terms?|search))\b",
333
+ re.IGNORECASE,
334
+ )
335
+
336
+ # ─────────────────────────────────────────────────────────────────────────────
337
+
338
  MEDICAL_KEYWORDS = [
339
  "medicine", "medical", "health", "clinical", "nursing", "pharmacy", "biomedical",
340
  "anatomy", "physiology", "epidemiology", "oncology", "cardiology", "neuroscience",
 
1974
  return answer
1975
 
1976
 
1977
+ # ── Full-text access chain ────────────────────────────────────────────────────
1978
+
1979
+ def _fulltext_chain_answer(question: str) -> str:
1980
+ """Step-by-step guide for getting full text when PDF is unavailable."""
1981
+ return (
1982
+ "<strong>πŸ“„ How to get full text for an article</strong><br><br>"
1983
+ "Follow this chain in order β€” each step is faster than the next:<br><br>"
1984
+ "<strong>Step 1 β€” Search KU PRIMO</strong><br>"
1985
+ "Find the article in <a href=\"https://khalifa.primo.exlibrisgroup.com/discovery/search"
1986
+ "?vid=971KUOSTAR_INST:KU\" target=\"_blank\">KU Library Discovery</a>. "
1987
+ "If KU subscribes, you'll see a <em>Full Text Available</em> or <em>Online Access</em> link. "
1988
+ "Click it β€” it passes through the IDM proxy automatically when on campus or logged in.<br><br>"
1989
+ "<strong>Step 2 β€” Try LibKey Nomad (browser extension)</strong><br>"
1990
+ "<a href=\"https://libkey.io/libraries/3025/\" target=\"_blank\">LibKey Nomad</a> is a free browser "
1991
+ "extension that detects articles you're viewing and fetches KU's full text automatically. "
1992
+ "Install it once and it works on every publisher site.<br><br>"
1993
+ "<strong>Step 3 β€” Try the publisher or open access</strong><br>"
1994
+ "Visit the DOI link directly. Many authors post their accepted manuscript on "
1995
+ "<a href=\"https://arxiv.org\" target=\"_blank\">arXiv</a>, "
1996
+ "<a href=\"https://www.researchgate.net\" target=\"_blank\">ResearchGate</a>, or their institutional page. "
1997
+ "<a href=\"https://openalex.org\" target=\"_blank\">OpenAlex</a> also links to many legal open-access PDFs.<br><br>"
1998
+ "<strong>Step 4 β€” Submit an Interlibrary Loan (ILL) request</strong><br>"
1999
+ "If none of the above work, KU Library can borrow the article from another library β€” usually within 1–5 working days. "
2000
+ "Submit here: <a href=\"https://library.ku.ac.ae/ill/\" target=\"_blank\">library.ku.ac.ae/ill/</a><br>"
2001
+ "Contact: <strong>Suaad Al Jneibi</strong> Β· "
2002
+ "<a href=\"mailto:suaad.aljneibi@ku.ac.ae\">suaad.aljneibi@ku.ac.ae</a> Β· +971 2 312 4278"
2003
+ )
2004
+
2005
+
2006
+ # ── Search strategy / Boolean explanation ─────────────────────────────────────
2007
+
2008
+ async def _search_strategy_answer(question: str, model: str) -> Tuple[str, dict]:
2009
+ """
2010
+ Build a search plan AND explain it step by step.
2011
+ Returns (explanation_html, plan_dict).
2012
+ """
2013
+ plan = await _build_search_plan(question, model)
2014
+ topic = _escape(_light_strip_retrieval_boilerplate(question) or question)
2015
+ boolean = _escape(plan.get("boolean", ""))
2016
+ natural = _escape(plan.get("natural", ""))
2017
+
2018
+ explanation = (
2019
+ f"<strong>πŸ” Search strategy for: {topic}</strong><br><br>"
2020
+ f"<strong>1. Identify your key concepts</strong><br>"
2021
+ f"Break the topic into 2–3 core concepts. For your question, I identified these concepts "
2022
+ f"and suggested synonyms for each using OR, then joined concepts with AND:<br><br>"
2023
+ f'<code style="display:block;padding:8px 12px;background:#1a1a2e;color:#C8A951;'
2024
+ f'border-radius:8px;font-size:.82rem;word-break:break-all">{boolean}</code><br>'
2025
+ f"<strong>Why AND and OR?</strong> AND narrows β€” both concepts must appear. "
2026
+ f"OR broadens β€” any synonym counts. Quoting phrases like "
2027
+ f"<code>\"machine learning\"</code> keeps them together as an exact phrase.<br><br>"
2028
+ f"<strong>2. Apply filters</strong><br>"
2029
+ f"Use database facets to limit by: peer-reviewed, date range, document type (article / review / book), "
2030
+ f"language, or open access. In PRIMO, these appear in the left sidebar after you search.<br><br>"
2031
+ f"<strong>3. Natural language query for AI tools</strong><br>"
2032
+ f"For AI-powered tools (LeapSpace, Scopus AI, Consensus), use a conversational query:<br>"
2033
+ f'<em style="color:var(--color-text-secondary)">{natural}</em><br><br>'
2034
+ f"<strong>4. Iterate</strong><br>"
2035
+ f"Too many results β†’ add more AND terms or apply filters. "
2036
+ f"Too few β†’ remove an AND group or use broader synonyms. "
2037
+ f"You can ask me to refine: <em>\"narrow to peer-reviewed only\"</em>, "
2038
+ f"<em>\"limit to last 5 years\"</em>, or <em>\"suggest alternative keywords\"</em>."
2039
+ )
2040
+ return explanation, plan
2041
+
2042
+
2043
+ # ── Alternative search terms ──────────────────────────────────────────────────
2044
+
2045
+ async def _alternative_terms_answer(question: str, context: Optional[SearchContextPayload], model: str) -> str:
2046
+ """Generate alternative keywords/synonyms for the current topic without re-running the search."""
2047
+ topic = (context.display_topic or context.topic) if context else question
2048
+ settings = get_settings()
2049
+ if not settings.openai_api_key and not settings.anthropic_api_key:
2050
+ return (
2051
+ f"<strong>Alternative search terms for: {_escape(topic)}</strong><br><br>"
2052
+ "Try combining these broader, narrower, and related terms:<br>"
2053
+ "β€’ Use broader terms if too few results<br>"
2054
+ "β€’ Use narrower/specific terms if too many results<br>"
2055
+ "β€’ Try acronyms and full forms (e.g. AI / Artificial Intelligence)<br>"
2056
+ "β€’ Include British and American spellings (e.g. organisation/organization)"
2057
+ )
2058
+ try:
2059
+ llm = _get_llm(model, temperature=0.4, max_tokens=300)
2060
+ response = await llm.ainvoke([
2061
+ {"role": "system", "content": (
2062
+ "You are an academic librarian. Given a research topic, generate a structured list of alternative "
2063
+ "search terms. Group them as: Broader terms, Narrower/specific terms, Related concepts, Acronyms/abbreviations. "
2064
+ "Format as HTML using <strong> for group labels and <br> for line breaks. "
2065
+ "Keep it concise β€” 3-4 terms per group maximum. No bullet points, use β€’ instead."
2066
+ )},
2067
+ {"role": "user", "content": f"Research topic: {topic}"},
2068
+ ])
2069
+ terms = response.content.strip()
2070
+ return (
2071
+ f"<strong>πŸ’‘ Alternative search terms for: {_escape(topic)}</strong><br><br>"
2072
+ f"{terms}<br><br>"
2073
+ f"<strong>Tip:</strong> In PRIMO or databases, use OR between synonyms within a concept group, "
2074
+ f"and AND between different concept groups. Ask me to run a new search with any of these."
2075
+ )
2076
+ except Exception as e:
2077
+ logger.warning(f"_alternative_terms_answer failed: {e}")
2078
+ return f"<strong>Alternative terms for {_escape(topic)}</strong><br><br>Try synonyms, acronyms, broader/narrower terms, and related concepts in your search."
2079
+
2080
+
2081
+ # ── Citation chaining guide ───────────────────────────────────────────────────
2082
+
2083
+ def _citation_chain_answer() -> str:
2084
+ return (
2085
+ "<strong>πŸ”— How to trace citations forward and backward from a paper</strong><br><br>"
2086
+ "<strong>Backward citation (who does this paper cite?)</strong><br>"
2087
+ "Read the paper's reference list β€” every source it cites is a potential lead. "
2088
+ "This gives you foundational and seminal works on the topic.<br><br>"
2089
+ "<strong>Forward citation (who has cited this paper since publication?)</strong><br>"
2090
+ "Use these tools β€” paste in the DOI or title:<br>"
2091
+ 'β€’ <a href="https://www-scopus-com.khalifa.idm.oclc.org/pages/ai" target="_blank"><strong>Scopus</strong></a> '
2092
+ 'β€” search the article, then click "Cited by N documents"<br>'
2093
+ 'β€’ <a href="https://www.webofscience.com" target="_blank"><strong>Web of Science</strong></a> '
2094
+ 'β€” search the article, click "Times Cited"<br>'
2095
+ 'β€’ <a href="https://www.semanticscholar.org" target="_blank"><strong>Semantic Scholar</strong></a> '
2096
+ 'β€” free, excellent for CS and engineering, shows "Citations" tab<br>'
2097
+ 'β€’ <a href="https://openalex.org" target="_blank"><strong>OpenAlex</strong></a> '
2098
+ 'β€” fully open, API-accessible citation graph<br><br>'
2099
+ "<strong>Lateral search (similar papers)</strong><br>"
2100
+ "In PRIMO, use <em>\"Find Similar\"</em>. In Semantic Scholar, use <em>\"Recommended Papers\"</em>. "
2101
+ "In Scopus, use <em>\"Related Documents\"</em>.<br><br>"
2102
+ "<strong>Tip:</strong> Start with one highly cited foundational paper, trace forward to find the newest "
2103
+ "work, and backward to understand the theoretical roots."
2104
+ )
2105
+
2106
+
2107
+ # ── Predatory / peer-review evaluation guide ─────────────────────────────────
2108
+
2109
+ def _predatory_eval_answer() -> str:
2110
+ return (
2111
+ "<strong>βœ… How to tell if an article or journal is peer-reviewed, scholarly, or predatory</strong><br><br>"
2112
+ "<strong>Is it peer-reviewed?</strong><br>"
2113
+ "β€’ Check the journal's website for a peer-review statement or editorial process description<br>"
2114
+ "β€’ In PRIMO, tick the <em>Peer-reviewed</em> filter in the left sidebar<br>"
2115
+ "β€’ Check if the journal is indexed in "
2116
+ '<a href="https://www-scopus-com.khalifa.idm.oclc.org" target="_blank">Scopus</a> or '
2117
+ '<a href="https://www.webofscience.com" target="_blank">Web of Science</a> β€” '
2118
+ "indexed = generally peer-reviewed<br><br>"
2119
+ "<strong>Is it a legitimate journal?</strong><br>"
2120
+ "β€’ <a href=\"https://doaj.org\" target=\"_blank\"><strong>DOAJ</strong></a> "
2121
+ "β€” Directory of Open Access Journals (vetted, legitimate OA)<br>"
2122
+ "β€’ <a href=\"https://mjl.clarivate.com\" target=\"_blank\"><strong>Web of Science Master Journal List</strong></a><br>"
2123
+ "β€’ <a href=\"https://www.scopus.com/sources\" target=\"_blank\"><strong>Scopus Source List</strong></a><br>"
2124
+ "β€’ Think Β· Check Β· Submit: <a href=\"https://thinkchecksubmit.org\" target=\"_blank\">thinkchecksubmit.org</a> "
2125
+ "β€” a checklist to assess any journal<br><br>"
2126
+ "<strong>Warning signs of predatory journals</strong><br>"
2127
+ "β€’ Unsolicited email invitation to submit<br>"
2128
+ "β€’ No clear peer-review process or very fast acceptance (days)<br>"
2129
+ "β€’ High article processing charges (APCs) with no clear metrics<br>"
2130
+ "β€’ Not indexed in Scopus or Web of Science<br>"
2131
+ "β€’ Generic or misleading journal name ('International Journal of...')<br><br>"
2132
+ "<strong>Need help checking a specific journal?</strong> Ask our E-Resources Librarian: "
2133
+ "<strong>Rani Anand</strong> Β· <a href=\"mailto:rani.anand@ku.ac.ae\">rani.anand@ku.ac.ae</a>"
2134
+ )
2135
+
2136
+
2137
+ # ── Theses / dissertations guide ─────────────────────────────────────────────
2138
+
2139
+ def _theses_answer() -> str:
2140
+ return (
2141
+ "<strong>πŸ“˜ Finding KU theses, dissertations, and institutional research</strong><br><br>"
2142
+ "<strong>Khalifa University Khazna Repository</strong><br>"
2143
+ "Khazna is KU's institutional repository β€” it holds KU theses, dissertations, "
2144
+ "faculty publications, conference papers, and open-access research outputs.<br>"
2145
+ 'πŸ”— <a href="https://khazna.ku.ac.ae" target="_blank">khazna.ku.ac.ae</a><br><br>'
2146
+ "<strong>ProQuest Dissertations &amp; Theses Global</strong><br>"
2147
+ "KU subscribes to ProQuest D&T Global β€” the world's largest database of "
2148
+ "theses and dissertations from universities worldwide.<br>"
2149
+ 'πŸ”— <a href="https://khalifa.idm.oclc.org/login?url=https://www.proquest.com/pqdtglobal" target="_blank">'
2150
+ "Access via KU Library</a><br><br>"
2151
+ "<strong>Other sources</strong><br>"
2152
+ 'β€’ <a href="https://ethos.bl.uk" target="_blank">EThOS</a> β€” UK theses (British Library)<br>'
2153
+ 'β€’ <a href="https://www.dart-europe.org" target="_blank">DART-Europe</a> β€” European theses<br>'
2154
+ 'β€’ <a href="https://ndltd.org" target="_blank">NDLTD</a> β€” Global networked digital library of theses<br><br>'
2155
+ "For help with Khazna deposits or ORCID integration, contact: "
2156
+ "<strong>Nikesh Narayanan</strong> Β· "
2157
+ "<a href=\"mailto:nikesh.narayanan@ku.ac.ae\">nikesh.narayanan@ku.ac.ae</a>"
2158
+ )
2159
+
2160
+
2161
+ # ── Highly-cited papers guide ─────────────────────────────────────────────────
2162
+
2163
+ def _highly_cited_note(topic_escaped: str) -> str:
2164
+ """Append to a standard search answer when highly-cited filter is detected."""
2165
+ return (
2166
+ f"<br><br><strong>πŸ“Š Finding highly cited papers on {topic_escaped}</strong><br>"
2167
+ "PRIMO doesn't sort by citation count, but these tools do:<br>"
2168
+ 'β€’ <a href="https://www-scopus-com.khalifa.idm.oclc.org" target="_blank"><strong>Scopus</strong></a> '
2169
+ 'β€” search your topic β†’ Sort by <em>Cited by (highest)</em><br>'
2170
+ 'β€’ <a href="https://www.webofscience.com" target="_blank"><strong>Web of Science</strong></a> '
2171
+ 'β€” search β†’ Sort by <em>Times Cited</em><br>'
2172
+ 'β€’ <a href="https://www.semanticscholar.org" target="_blank"><strong>Semantic Scholar</strong></a> '
2173
+ 'β€” free, sort by <em>Citation Count</em><br>'
2174
+ 'β€’ <a href="https://scholar.google.com" target="_blank"><strong>Google Scholar</strong></a> '
2175
+ 'β€” sort by <em>Cited by</em> (broader but includes grey literature)'
2176
+ )
2177
+
2178
+
2179
  # ── Research Snapshot ─────────────────────────────────────────────────────────
2180
 
2181
  async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple[str, List[dict], List[dict]]:
 
2298
  return "last_5_years"
2299
  if re.search(r"\b(last|past)\s+10\s+years?\b|\bpast decade\b", q):
2300
  return "last_10_years"
2301
+ # "last 3 years", "last 2 years" etc.
2302
+ m = re.search(r"\b(last|past)\s+(\d{1,2})\s+years?\b", q)
2303
+ if m:
2304
+ return f"last_{m.group(2)}_years"
2305
  if re.search(r"\bbooks? instead\b|\bbooks? only\b|\bfind books?\b|\bshow books?\b", q):
2306
  return "books_only"
2307
  if re.search(r"\barticles? instead\b|\barticles? only\b|\bpapers? only\b", q):
2308
  return "articles_only"
2309
  if re.search(r"\b(?:both|articles and books|books and articles)\b", q):
2310
  return "both_resources"
2311
+ # Review articles only β€” NEW
2312
+ if REVIEW_ONLY_RE.search(q):
2313
+ return "review_articles_only"
2314
+ # Alternative search terms β€” NEW
2315
+ if ALT_TERMS_RE.search(q):
2316
+ return "alt_terms"
2317
  if re.search(r"\b(summar(y|ize|ise)|overview|brief|what does the literature say|research snapshot)\b", q):
2318
  return "summarize_topic"
2319
  if re.search(r"\bpubmed\b", q):
 
2378
  elif action == "last_10_years":
2379
  context.year_from = str(CURRENT_YEAR - 9)
2380
  context.year_to = str(CURRENT_YEAR)
2381
+ elif action == "last_3_years":
2382
+ context.year_from = str(CURRENT_YEAR - 2)
2383
+ context.year_to = str(CURRENT_YEAR)
2384
+ elif action == "last_2_years":
2385
+ context.year_from = str(CURRENT_YEAR - 1)
2386
+ context.year_to = str(CURRENT_YEAR)
2387
+ elif action and action.startswith("last_") and action.endswith("_years"):
2388
+ # Generic "last N years" β€” parse N
2389
+ try:
2390
+ n = int(action.split("_")[1])
2391
+ context.year_from = str(CURRENT_YEAR - n + 1)
2392
+ context.year_to = str(CURRENT_YEAR)
2393
+ except (IndexError, ValueError):
2394
+ pass
2395
  elif action == "books_only":
2396
  context.resource_type = "books"
2397
  elif action == "articles_only":
2398
  context.resource_type = "articles"
2399
  elif action == "both_resources":
2400
  context.resource_type = "both"
2401
+ elif action == "review_articles_only":
2402
+ # Map to PRIMO facet for review articles β€” stored as resource_type hint
2403
+ context.resource_type = "articles"
2404
+ context.peer_reviewed = True # reviews are implicitly peer-reviewed
2405
+ # Store the review filter flag in the context notes field if available
2406
+ # The PRIMO query will add facet_rtype=reviews
2407
  elif action == "search_pubmed":
2408
  context.source = "pubmed"
2409
  context.intent = "search_medical"
 
2889
  is_follow_up=True,
2890
  )
2891
 
2892
+ if is_follow_up and base_context:
2893
+ _safe_metrics_increment("follow_up_hits")
2894
+ context = _apply_follow_up_action(base_context, follow_up_action)
2895
+
2896
+ # ── Follow-up: alternative search terms (no new search) ───────────────
2897
+ if follow_up_action == "alt_terms":
2898
+ alt_answer = await _alternative_terms_answer(question, base_context, model)
2899
+ follow_up_question, follow_up_suggestions = await _search_follow_up(base_context, model)
2900
+ return AgentResponse(
2901
+ answer=_thought_block("library_info", "alt_terms", question) + alt_answer + _source_badge("libbee"),
2902
+ intent="library_info",
2903
+ tools_used=["alt_terms"],
2904
+ model_used=model,
2905
+ response_time=time.time() - start_time,
2906
+ follow_up_question=follow_up_question,
2907
+ follow_up_suggestions=follow_up_suggestions,
2908
+ search_context=_context_to_dict(base_context),
2909
+ is_follow_up=True,
2910
+ )
2911
+
2912
+ if follow_up_action in {"summarize_topic", "deep_research_tools", "best_databases"}:
2913
+ context = await _prepare_queries(question, context, model, True)
2914
+ if follow_up_action == "summarize_topic":
2915
+ answer, search_results, sources = await _research_snapshot(context, model)
2916
+ else:
2917
+ # deep_research_tools / best_databases follow-up
2918
+ answer = (
2919
+ f"{_search_trace_block(question, context)}"
2920
+ f"<strong>Research guide for {_escape(context.display_topic or context.topic)}</strong><br><br>"
2921
+ f"Here are the best AI tools and resources for a deep dive on this topic."
2922
+ + _source_badge("libbee")
2923
+ + _ai_tools_footer(context)
2924
+ )
2925
+ search_results = []
2926
+ sources = []
2927
+ follow_up_question, follow_up_suggestions = await _search_follow_up(context, model, summary_mode=True)
2928
+ _safe_metrics_increment("search_handoffs")
2929
+ return AgentResponse(
2930
+ answer=answer,
2931
+ intent=context.intent,
2932
+ tools_used=["follow_up_resolution", follow_up_action],
2933
+ search_results=search_results,
2934
+ sources=sources,
2935
+ model_used=model,
2936
+ response_time=time.time() - start_time,
2937
+ corrected_query=context.topic,
2938
+ natural_query=context.ai_tool_query,
2939
+ database_query=context.primo_boolean_query,
2940
+ ai_tool_query=context.ai_tool_query,
2941
+ primo_boolean_query=context.primo_boolean_query,
2942
+ primo_search_url=_primo_clean_url(context),
2943
+ primo_ai_url=_tool_urls(context).get("primo_ai"),
2944
+ pubmed_search_url=_tool_urls(context).get("pubmed"),
2945
+ follow_up_question=follow_up_question,
2946
+ follow_up_suggestions=follow_up_suggestions,
2947
+ search_context=_context_to_dict(context),
2948
+ is_follow_up=True,
2949
+ )
2950
+
2951
+ answer, search_results, sources, source_url = await _run_search_mode(question, context, model, True)
2952
+ follow_up_question, follow_up_suggestions = await _search_follow_up(context, model)
2953
+ return AgentResponse(
2954
+ answer=answer,
2955
+ intent=context.intent,
2956
+ tools_used=["follow_up_resolution", follow_up_action or "contextual_refinement"],
2957
+ search_results=search_results,
2958
+ sources=sources,
2959
+ model_used=model,
2960
+ response_time=time.time() - start_time,
2961
+ corrected_query=context.topic,
2962
+ natural_query=context.ai_tool_query,
2963
+ database_query=context.primo_boolean_query,
2964
+ ai_tool_query=context.ai_tool_query,
2965
+ primo_boolean_query=context.primo_boolean_query,
2966
+ primo_search_url=source_url,
2967
+ primo_ai_url=_tool_urls(context).get("primo_ai"),
2968
+ pubmed_search_url=_tool_urls(context).get("pubmed"),
2969
+ follow_up_question=follow_up_question,
2970
+ follow_up_suggestions=follow_up_suggestions,
2971
+ search_context=_context_to_dict(context),
2972
+ is_follow_up=True,
2973
+ )
2974
+
2975
+ # ── Pre-classifier specialist handlers ───────────────────────────────────
2976
+ # These fire BEFORE the LLM classifier for patterns the classifier handles
2977
+ # poorly (too often routes to search_academic for library-service questions).
2978
+
2979
+ # Full-text / ILL chain
2980
+ if FULLTEXT_REQUEST_RE.search(question):
2981
+ ft_answer = _fulltext_chain_answer(question)
2982
+ follow_up_question, follow_up_suggestions = _library_follow_up(question)
2983
+ return AgentResponse(
2984
+ answer=_thought_block("library_info", "fulltext_chain", question,
2985
+ "Identified a full-text access request. Returning the KU full-text access chain.") + ft_answer + _source_badge("ku_library", "https://library.ku.ac.ae/ill/"),
2986
+ intent="library_info",
2987
+ tools_used=["fulltext_chain"],
2988
+ model_used=model,
2989
+ response_time=time.time() - start_time,
2990
+ follow_up_question=follow_up_question,
2991
+ follow_up_suggestions=follow_up_suggestions,
2992
+ )
2993
+
2994
+ # Theses / dissertations / Khazna
2995
+ if THESES_RE.search(question):
2996
+ th_answer = _theses_answer()
2997
+ follow_up_question, follow_up_suggestions = _library_follow_up(question)
2998
+ return AgentResponse(
2999
+ answer=_thought_block("library_info", "theses_guide", question,
3000
+ "Identified a theses/repository question.") + th_answer + _source_badge("ku_library", "https://khazna.ku.ac.ae"),
3001
+ intent="library_info",
3002
+ tools_used=["theses_guide"],
3003
+ model_used=model,
3004
+ response_time=time.time() - start_time,
3005
+ follow_up_question=follow_up_question,
3006
+ follow_up_suggestions=follow_up_suggestions,
3007
+ )
3008
+
3009
+ # Predatory / peer-review evaluation
3010
+ if PREDATORY_RE.search(question):
3011
+ pr_answer = _predatory_eval_answer()
3012
+ follow_up_question, follow_up_suggestions = _library_follow_up(question)
3013
+ return AgentResponse(
3014
+ answer=_thought_block("library_info", "predatory_eval", question,
3015
+ "Identified a question about evaluating journals/peer review.") + pr_answer + _source_badge("ku_library", "https://library.ku.ac.ae/eresources"),
3016
+ intent="library_info",
3017
+ tools_used=["predatory_eval"],
3018
+ model_used=model,
3019
+ response_time=time.time() - start_time,
3020
+ follow_up_question=follow_up_question,
3021
+ follow_up_suggestions=follow_up_suggestions,
3022
+ )
3023
+
3024
+ # Citation chaining
3025
+ if CITATION_CHAIN_RE.search(question):
3026
+ cc_answer = _citation_chain_answer()
3027
+ follow_up_question, follow_up_suggestions = _library_follow_up(question)
3028
+ return AgentResponse(
3029
+ answer=_thought_block("library_info", "citation_chain", question,
3030
+ "Identified a citation tracing / forward-backward search question.") + cc_answer + _source_badge("ku_library", "https://library.ku.ac.ae/eresources"),
3031
+ intent="library_info",
3032
+ tools_used=["citation_chain"],
3033
+ model_used=model,
3034
+ response_time=time.time() - start_time,
3035
+ follow_up_question=follow_up_question,
3036
+ follow_up_suggestions=follow_up_suggestions,
3037
+ )
3038
+
3039
+ # Search strategy / boolean explanation
3040
+ if BOOLEAN_STRATEGY_RE.search(question):
3041
+ strategy_answer, _plan = await _search_strategy_answer(question, model)
3042
+ follow_up_question, follow_up_suggestions = _library_follow_up(question)
3043
+ return AgentResponse(
3044
+ answer=_thought_block("library_info", "search_strategy", question,
3045
+ "Identified a search strategy / boolean building request.") + strategy_answer + _source_badge("libbee"),
3046
+ intent="library_info",
3047
+ tools_used=["search_strategy_explain"],
3048
+ model_used=model,
3049
+ response_time=time.time() - start_time,
3050
+ database_query=_plan.get("boolean"),
3051
+ natural_query=_plan.get("natural"),
3052
+ follow_up_question=follow_up_question,
3053
+ follow_up_suggestions=follow_up_suggestions,
3054
+ )
3055
+
3056
+ # Alternative search terms (standalone, not follow-up)
3057
+ if ALT_TERMS_RE.search(question):
3058
+ alt_answer = await _alternative_terms_answer(question, None, model)
3059
+ follow_up_question, follow_up_suggestions = _library_follow_up(question)
3060
+ return AgentResponse(
3061
+ answer=_thought_block("library_info", "alt_terms", question) + alt_answer + _source_badge("libbee"),
3062
+ intent="library_info",
3063
+ tools_used=["alt_terms"],
3064
+ model_used=model,
3065
+ response_time=time.time() - start_time,
3066
+ follow_up_question=follow_up_question,
3067
+ follow_up_suggestions=follow_up_suggestions,
3068
+ )
3069
+
3070
  # FIX: _llm_classify always falls back to rule-based on any exception
3071
  cls_result = await _llm_classify(question, history, model)
3072
  intent = cls_result.get("intent", "general")
 
3135
  )
3136
 
3137
  if intent in ("search_academic", "search_medical"):
3138
+ # ── Partial title search β€” route to PRIMO title query ─────────────────
3139
+ if PARTIAL_TITLE_RE.search(question):
3140
+ from urllib.parse import quote as _qt
3141
+ # Extract quoted fragment or the whole question as title search
3142
+ _title_frag = (re.search(r'"([^"]{4,80})"', question) or
3143
+ re.search(r'"([^"]{4,80})"', question))
3144
+ _title_q = _title_frag.group(1) if _title_frag else _light_strip_retrieval_boilerplate(question)
3145
+ _title_url = (
3146
+ "https://khalifa.primo.exlibrisgroup.com/discovery/search"
3147
+ f"?query=title,contains,{_qt(_title_q)},AND"
3148
+ "&tab=Everything&search_scope=MyInst_and_CI"
3149
+ "&vid=971KUOSTAR_INST:KU&lang=en&mode=advanced"
3150
+ )
3151
+ follow_up_question, follow_up_suggestions = _library_follow_up(question)
3152
+ return AgentResponse(
3153
+ answer=(
3154
+ _thought_block("library_info", "title_search", question,
3155
+ "Identified a partial title search β€” routing to PRIMO title search.") +
3156
+ f"<strong>πŸ“– Title search in KU Library</strong><br><br>"
3157
+ f"I'll search the KU Library catalogue by title for: <em>{_escape(_title_q)}</em><br><br>"
3158
+ f'<a href="{_title_url}" target="_blank" '
3159
+ f'style="display:inline-block;padding:9px 16px;background:#003366;color:#fff;'
3160
+ f'border-radius:8px;font-weight:700;text-decoration:none;font-size:.88rem">'
3161
+ f"πŸ” Search by title in PRIMO β†’</a><br><br>"
3162
+ "If you only remember part of the title, use PRIMO's advanced search and choose "
3163
+ "<em>Title</em> from the field dropdown β€” it supports partial matches.<br>"
3164
+ "You can also try "
3165
+ '<a href="https://scholar.google.com" target="_blank">Google Scholar</a> '
3166
+ "with the partial title in quotes." +
3167
+ _source_badge("primo", _title_url)
3168
+ ),
3169
+ intent="library_info",
3170
+ tools_used=["title_search"],
3171
+ model_used=model,
3172
+ response_time=time.time() - start_time,
3173
+ follow_up_question=follow_up_question,
3174
+ follow_up_suggestions=follow_up_suggestions,
3175
+ )
3176
+
3177
  topic = await _extract_topic(question, model)
3178
  topic = _title_case_topic(topic)
3179
  year_from, year_to = _parse_year_filters(question)
3180
+
3181
+ # ── Dual resource type: articles AND books in one question ─────────────
3182
+ if DUAL_RESOURCE_RE.search(question):
3183
+ import asyncio as _aio
3184
+ # Build two contexts: articles and books
3185
+ _ctx_articles = SearchContextPayload(
3186
+ context_id=str(uuid.uuid4()), topic=topic, display_topic=topic,
3187
+ intent=intent, source="primo", resource_type="articles",
3188
+ peer_reviewed=bool(re.search(r"\bpeer[- ]reviewed\b", question, re.IGNORECASE)),
3189
+ open_access=bool(re.search(r"\bopen access\b", question, re.IGNORECASE)),
3190
+ year_from=year_from, year_to=year_to,
3191
+ )
3192
+ _ctx_books = SearchContextPayload(
3193
+ context_id=str(uuid.uuid4()), topic=topic, display_topic=topic,
3194
+ intent=intent, source="primo", resource_type="books",
3195
+ peer_reviewed=False, open_access=False,
3196
+ year_from=year_from, year_to=year_to,
3197
+ )
3198
+ _ctx_articles, _ctx_books = await _aio.gather(
3199
+ _prepare_queries(question, _ctx_articles, model, False),
3200
+ _prepare_queries(question, _ctx_books, model, False),
3201
+ )
3202
+ (_res_a, _src_url_a), (_res_b, _src_url_b) = await _aio.gather(
3203
+ _search_primo_catalog(_ctx_articles, limit=4),
3204
+ _search_primo_catalog(_ctx_books, limit=3),
3205
+ )
3206
+ _results_a = _res_a.get("results", [])
3207
+ _results_b = _res_b.get("results", [])
3208
+ _total_a = _res_a.get("total", len(_results_a))
3209
+ _total_b = _res_b.get("total", len(_results_b))
3210
+
3211
+ _dual_answer = _search_trace_block(question, _ctx_articles)
3212
+ _dual_answer += (
3213
+ f"<strong>πŸ“„ Articles on {_escape(topic)}</strong> "
3214
+ f"β€” {_total_a:,} result(s) found, top {len(_results_a)} shown below.<br>"
3215
+ )
3216
+ if not _results_a:
3217
+ _dual_answer += "<em>No article results found β€” try broadening your search.</em><br>"
3218
+ _dual_answer += _source_badge("primo", _src_url_a)
3219
+
3220
+ _dual_answer += f"<br><br><strong>πŸ“š Books on {_escape(topic)}</strong> "
3221
+ _dual_answer += f"β€” {_total_b:,} result(s) found, top {len(_results_b)} shown below.<br>"
3222
+ if not _results_b:
3223
+ _dual_answer += "<em>No book results found β€” try the KU Library catalogue directly.</em><br>"
3224
+ _dual_answer += _source_badge("primo", _src_url_b)
3225
+ _dual_answer += _ai_tools_footer(_ctx_articles)
3226
+
3227
+ _combined = _results_a + _results_b
3228
+ follow_up_question, follow_up_suggestions = await _search_follow_up(_ctx_articles, model)
3229
+ return AgentResponse(
3230
+ answer=_dual_answer,
3231
+ intent=intent,
3232
+ tools_used=["primo_dual_resource"],
3233
+ search_results=_combined[:8],
3234
+ sources=[{"title": r.get("title", "Result"), "url": r.get("primo_url") or r.get("link", "")}
3235
+ for r in _combined[:6] if r.get("primo_url") or r.get("link")],
3236
+ model_used=model,
3237
+ response_time=time.time() - start_time,
3238
+ corrected_query=topic,
3239
+ natural_query=_ctx_articles.ai_tool_query,
3240
+ primo_boolean_query=_ctx_articles.primo_boolean_query,
3241
+ primo_search_url=_src_url_a,
3242
+ follow_up_question=follow_up_question,
3243
+ follow_up_suggestions=follow_up_suggestions,
3244
+ search_context=_context_to_dict(_ctx_articles),
3245
+ )
3246
+
3247
  context = SearchContextPayload(
3248
  context_id=str(uuid.uuid4()),
3249
  topic=topic,
 
3263
  r"\b(deep research|deep dive|systematic review|full literature review|exhaustive)\b",
3264
  question, re.IGNORECASE,
3265
  ))
3266
+ is_highly_cited = bool(HIGHLY_CITED_RE.search(question))
3267
 
3268
  if summary_mode or deep_research_mode:
3269
  answer, search_results, sources = await _research_snapshot(context, model)
 
 
3270
  if deep_research_mode and "Research guide" not in answer and "AI tools" not in answer:
3271
  answer += f"<br><br>{_ai_tools_footer(context)}"
3272
+ if is_highly_cited:
3273
+ answer += _highly_cited_note(_escape(topic))
3274
  follow_up_question, follow_up_suggestions = await _search_follow_up(context, model, summary_mode=True)
3275
  _safe_metrics_increment("search_handoffs")
3276
  return AgentResponse(
 
3295
  )
3296
 
3297
  answer, search_results, sources, source_url = await _run_search_mode(question, context, model, False)
3298
+ # Append highly-cited guidance if requested
3299
+ if is_highly_cited:
3300
+ answer += _highly_cited_note(_escape(topic))
3301
  follow_up_question, follow_up_suggestions = await _search_follow_up(context, model)
3302
  return AgentResponse(
3303
  answer=answer,