nikeshn commited on
Commit
ac309db
Β·
verified Β·
1 Parent(s): 1f2b8d7

Update src/api/agent.py

Browse files
Files changed (1) hide show
  1. src/api/agent.py +205 -147
src/api/agent.py CHANGED
@@ -119,14 +119,25 @@ MEDICAL_SEARCH_RE = re.compile(
119
  r"|clinical trial|biomedical literature|medical literature)\b",
120
  re.IGNORECASE,
121
  )
122
-
123
- # FIX: removed "president" β€” was incorrectly catching KU leadership questions
124
  CURRENT_INFO_RE = re.compile(
125
  r"\b(current|currently|latest|today|recent|recently|now|this week|this month"
126
  r"|news|update|updated|prime minister|ceo|minister|king|ruler|who won)\b",
127
  re.IGNORECASE,
128
  )
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  MEDICAL_KEYWORDS = [
131
  "medicine", "medical", "health", "clinical", "nursing", "pharmacy", "biomedical",
132
  "anatomy", "physiology", "epidemiology", "oncology", "cardiology", "neuroscience",
@@ -138,7 +149,7 @@ MEDICAL_KEYWORDS = [
138
  "crispr", "gene therapy", "gene editing", "genomic medicine", "precision medicine",
139
  ]
140
 
141
- # ── LLM Classifier System Prompt ──────────────────────────────────────────────
142
 
143
  _CLASSIFIER_SYSTEM = """You are the routing brain of LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE).
144
  Your only job: read the user message and return a single JSON object routing it to the right handler.
@@ -146,10 +157,10 @@ Your only job: read the user message and return a single JSON object routing it
146
  INTENTS β€” pick exactly one:
147
  "social" β€” casual chat, greetings, emotions, compliments, complaints, vague help requests
148
  "library_info" β€” questions about KU Library services, hours, rooms, borrowing, fines, ILL, staff, databases, ORCID, RefWorks, open access, APC, account, printing, remote access, LibKey, acquisitions, Khazna, thesis submission, library policies, alumni access
149
- "search_academic"β€” user wants to FIND articles / papers / books / literature on a specific academic topic
150
  "search_medical" β€” same as search_academic but topic is medical/clinical/nursing/pharmacy/health sciences
151
- "general_recent" β€” questions about TRULY live/real-time data: breaking news, live sports scores, today's weather, current stock prices, events happening right now
152
- "general" β€” ALL other factual questions: university info, people, history, science, technology, definitions, explanations, stable facts like who holds a position
153
 
154
  RULES:
155
  1. When in doubt between library_info and social, choose library_info if ANY library keyword is present.
@@ -157,9 +168,9 @@ RULES:
157
  3. "I am fed up with searching" alone = social.
158
  4. "I need help finding articles on diabetes" = search_medical.
159
  5. KU = Khalifa University. Do NOT confuse with Kuwait University.
160
- 6. ANY question about advances, approaches, methods, effectiveness, impact, trends on a specific academic topic = search_academic or search_medical.
161
- 7. Questions about people, university leadership, presidents, provosts, history, science, technology = general.
162
- 8. Only use general_recent for truly live data that changes by the minute/hour.
163
 
164
  For "social" intent ONLY: include "casual_answer" β€” a warm 1-3 sentence LibBee response (no markdown, no bullets).
165
  For all other intents: omit "casual_answer".
@@ -177,10 +188,29 @@ Examples:
177
 
178
  # ── Helper Functions ───────────────────────────────────────────────────────────
179
 
 
 
 
 
 
180
  def _extract_topic(question: str) -> str:
181
- """Strip search boilerplate to get the core topic for PRIMO."""
182
  q = question.strip()
183
  prefixes = [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  "find articles on ", "find papers on ", "find books on ",
185
  "find articles about ", "find papers about ", "find books about ",
186
  "search for articles on ", "search for papers on ",
@@ -190,13 +220,15 @@ def _extract_topic(question: str) -> str:
190
  "get me articles on ", "look for articles on ",
191
  "articles on ", "papers on ", "books on ",
192
  "research on ", "literature on ",
193
- "find ", "search for ", "i need ", "give me ", "show me ", "get me ",
 
194
  ]
195
  lower = q.lower()
196
  for prefix in prefixes:
197
  if lower.startswith(prefix):
198
  q = q[len(prefix):]
199
  break
 
200
  return q.strip()
201
 
202
 
@@ -249,7 +281,7 @@ def _rule_based_classify(question: str) -> Dict:
249
  }
250
  if _looks_medical_search(question):
251
  return {"intent": "search_medical"}
252
- if _looks_research_question(question):
253
  return {"intent": "search_academic"}
254
  if LIBRARY_CUE_RE.search(q):
255
  return {"intent": "library_info"}
@@ -331,7 +363,6 @@ def _build_history_messages(history: List[ChatMessage]) -> List[dict]:
331
 
332
  async def _llm_classify(question: str, history: List[ChatMessage], model: str) -> Dict:
333
  settings = get_settings()
334
-
335
  if not settings.openai_api_key:
336
  return _rule_based_classify(question)
337
 
@@ -371,16 +402,14 @@ async def _libbee_casual_response(
371
  ) -> str:
372
  if hint and len(hint.strip()) > 25:
373
  return hint.strip()
374
-
375
  settings = get_settings()
376
  if not settings.openai_api_key:
377
- return "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant β€” always happy to help! What can I find for you today?"
378
-
379
  try:
380
  llm = _get_llm(model, temperature=0.6, max_tokens=200)
381
  msgs = [{"role": "system", "content": (
382
  "You are LibBee, the Khalifa University Library AI Assistant. "
383
- "Respond warmly and naturally in 1-3 sentences as a friendly, knowledgeable librarian. "
384
  "No markdown, no bullet points."
385
  )}]
386
  msgs.extend(_build_history_messages(history))
@@ -388,14 +417,11 @@ async def _libbee_casual_response(
388
  response = await llm.ainvoke(msgs)
389
  return response.content.strip()
390
  except Exception:
391
- return "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant β€” always happy to help! What can I find for you today?"
392
 
393
 
394
  async def _rag_answer(
395
- question: str,
396
- rag_results: List[dict],
397
- history: List[ChatMessage],
398
- model: str,
399
  ) -> str:
400
  settings = get_settings()
401
  if not settings.openai_api_key:
@@ -406,12 +432,11 @@ async def _rag_answer(
406
  "You are LibBee, the Khalifa University Library AI Assistant. "
407
  "Answer the user's question using ONLY the context provided below. "
408
  "Be concise, friendly, and use HTML <br> for line breaks where needed. "
409
- "If the context does not contain enough information, say so honestly and suggest "
410
- "the user contact Ask a Librarian at https://library.ku.ac.ae/AskUs. "
411
  "Never invent facts or URLs.\n\n"
412
  f"CONTEXT:\n{context}"
413
  )
414
-
415
  try:
416
  llm = _get_llm(model, temperature=0.2, max_tokens=400)
417
  msgs = [{"role": "system", "content": system}]
@@ -420,120 +445,88 @@ async def _rag_answer(
420
  response = await llm.ainvoke(msgs)
421
  return response.content.strip()
422
  except Exception as e:
423
- logger.error(f"_rag_answer LLM error: {e}")
424
  return (
425
- "I'm having trouble generating an answer right now. Please try "
426
- '<a href="https://library.ku.ac.ae/AskUs" target="_blank">Ask a Librarian</a> '
427
- 'or email <a href="mailto:libse@ku.ac.ae">libse@ku.ac.ae</a>.'
428
  )
429
 
430
 
431
  async def _web_search_answer(
432
- question: str,
433
- history: List[ChatMessage],
434
- model: str,
435
  ) -> str:
436
- """
437
- Answer using live web search for BOTH models.
438
- Claude β†’ Anthropic web search tool
439
- GPT β†’ OpenAI Responses API with web_search_preview
440
- Falls back to _llm_general_answer() if both fail.
441
- """
442
  settings = get_settings()
443
 
444
- # ── Claude web search ──────────────────────────────────────────────────
445
  if model == "claude" and settings.anthropic_api_key:
446
  try:
447
  import anthropic
448
  client = anthropic.Anthropic(api_key=settings.anthropic_api_key)
449
-
450
  response = client.messages.create(
451
  model="claude-3-haiku-20240307",
452
  max_tokens=600,
453
  system=(
454
  "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
455
- "Answer the question using current web search results. "
456
- "Be concise and factual. Use HTML <br> for line breaks. "
457
- "KU = Khalifa University. "
458
- "If the topic is academic, briefly mention you can help find scholarly articles."
459
  ),
460
  tools=[{"type": "web_search_20250305", "name": "web_search"}],
461
  messages=[{"role": "user", "content": question}],
462
  )
463
-
464
- text = ""
465
- for block in response.content:
466
- if hasattr(block, "text"):
467
- text += block.text
468
-
469
  if text.strip():
470
- logger.info("Claude web search succeeded")
471
  return text.strip()
472
-
473
  except Exception as e:
474
  logger.warning(f"Claude web search failed: {e}")
475
 
476
- # ── GPT: OpenAI Responses API ──────────────────────────────────────────
477
  if settings.openai_api_key:
478
  try:
479
  from openai import OpenAI
480
  client = OpenAI(api_key=settings.openai_api_key)
481
-
482
  response = client.responses.create(
483
  model="gpt-4o-mini",
484
  tools=[{"type": "web_search_preview"}],
485
  instructions=(
486
  "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
487
- "Answer the question using current web search results. "
488
- "Be concise and factual. Use HTML <br> for line breaks. "
489
- "KU = Khalifa University β€” do NOT confuse with Kuwait University. "
490
- "If the topic is academic, briefly mention you can help find scholarly articles."
491
  ),
492
  input=question,
493
  )
494
-
495
  text = ""
496
  for item in response.output:
497
  if hasattr(item, "content"):
498
  for block in item.content:
499
  if hasattr(block, "text"):
500
  text += block.text
501
-
502
  if text.strip():
503
- logger.info("GPT web search succeeded")
504
  return text.strip()
505
-
506
  except Exception as e:
507
  logger.warning(f"GPT web search failed: {e}")
508
 
509
- # ── Fallback: LLM training knowledge ──────────────────────────────────
510
- logger.warning("Both web search tools failed β€” answering from LLM training knowledge")
511
  return await _llm_general_answer(question, history, model)
512
 
513
 
514
  async def _llm_general_answer(
515
- question: str,
516
- history: List[ChatMessage],
517
- model: str,
518
  ) -> str:
519
- """Fallback: answer from LLM training knowledge when web search unavailable."""
520
  settings = get_settings()
521
  if not settings.openai_api_key:
522
  return (
523
- "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant. "
524
- f'For general questions, please visit <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a>.'
525
  )
526
-
527
  system = (
528
  "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
529
- "Answer the user's question factually and concisely in 3-5 sentences. "
530
- "Use HTML <br> for line breaks. "
531
- "KU means Khalifa University β€” do NOT confuse with Kuwait University. "
532
- "Note: your training data has a cutoff β€” mention this only if the question involves "
533
- "frequently changing facts. "
534
- "If the topic is academic, add one short sentence offering to find library resources."
535
  )
536
-
537
  try:
538
  llm = _get_llm(model, temperature=0.3, max_tokens=400)
539
  msgs = [{"role": "system", "content": system}]
@@ -543,30 +536,21 @@ async def _llm_general_answer(
543
  return response.content.strip()
544
  except Exception as e:
545
  logger.error(f"_llm_general_answer error: {e}")
546
- return (
547
- "I'm having trouble answering that right now. "
548
- f'For general questions, please visit <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a>.'
549
- )
550
 
551
 
552
- async def _primo_inline_search(topic: str, limit: int = 5) -> List[dict]:
553
- """
554
- Run a PRIMO search directly from the agent for inline chat results.
555
- Uses the same API key approach as search.py (key in URL param).
556
- """
557
  settings = get_settings()
558
  if not settings.primo_api_key:
559
- logger.warning("PRIMO_API_KEY not set β€” skipping inline search")
560
  return []
561
 
562
  query_encoded = quote(topic)
563
  url = (
564
  f"https://api-eu.hosted.exlibrisgroup.com/primo/v1/search"
565
- f"?vid=971KUOSTAR_INST:KU"
566
- f"&tab=Everything"
567
- f"&scope=MyInst_and_CI"
568
- f"&q=any,contains,{query_encoded}"
569
- f"&lang=en&sort=rank"
570
  f"&limit={limit}&offset=0&mode=advanced"
571
  f"&apikey={settings.primo_api_key}"
572
  )
@@ -575,9 +559,8 @@ async def _primo_inline_search(topic: str, limit: int = 5) -> List[dict]:
575
  async with httpx.AsyncClient(timeout=15) as client:
576
  r = await client.get(url, headers={"Accept": "application/json"})
577
  if r.status_code != 200:
578
- logger.warning(f"Inline PRIMO search returned {r.status_code}")
579
  return []
580
-
581
  data = r.json()
582
  results = []
583
  for doc in data.get("docs", [])[:limit]:
@@ -595,14 +578,106 @@ async def _primo_inline_search(topic: str, limit: int = 5) -> List[dict]:
595
  ),
596
  "_source": "PRIMO",
597
  })
598
- logger.info(f"Inline PRIMO: {len(results)} results for '{topic}'")
599
  return results
600
-
601
  except Exception as e:
602
- logger.error(f"Inline PRIMO search failed: {e}")
603
  return []
604
 
605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
606
  # ── Main Endpoint ──────────────────────────────────────────────────────────────
607
 
608
  @router.post("", response_model=AgentResponse)
@@ -622,7 +697,6 @@ async def agent_query(request: Request, req: AgentRequest):
622
 
623
  # ── LAYER 0: Instant rule-based handlers ─────────────────────────────
624
 
625
- # 1. Pure greeting
626
  if PURE_GREETING_RE.match(question):
627
  return AgentResponse(
628
  answer=(
@@ -636,7 +710,6 @@ async def agent_query(request: Request, req: AgentRequest):
636
  response_time=time.time() - start_time,
637
  )
638
 
639
- # 2. Staff name match
640
  staff_match = match_staff_name(question)
641
  if staff_match:
642
  return AgentResponse(
@@ -647,7 +720,6 @@ async def agent_query(request: Request, req: AgentRequest):
647
  response_time=time.time() - start_time,
648
  )
649
 
650
- # 3. Staff role match
651
  staff_role_match = match_staff_role(question)
652
  if staff_role_match:
653
  return AgentResponse(
@@ -658,7 +730,6 @@ async def agent_query(request: Request, req: AgentRequest):
658
  response_time=time.time() - start_time,
659
  )
660
 
661
- # 4. Greeting menu followup
662
  if _is_greeting_menu_followup(question, history):
663
  return AgentResponse(
664
  answer=_greeting_menu_clarify_answer(),
@@ -668,7 +739,6 @@ async def agent_query(request: Request, req: AgentRequest):
668
  response_time=time.time() - start_time,
669
  )
670
 
671
- # 5. Library hours
672
  if _looks_library_hours_question(question):
673
  return AgentResponse(
674
  answer=_hours_answer(),
@@ -679,7 +749,6 @@ async def agent_query(request: Request, req: AgentRequest):
679
  response_time=time.time() - start_time,
680
  )
681
 
682
- # 6. Campus/location
683
  if _looks_campus_question(question):
684
  return AgentResponse(
685
  answer=_campus_answer(),
@@ -731,8 +800,7 @@ async def agent_query(request: Request, req: AgentRequest):
731
  tools_used = ["rag_hybrid_search"]
732
  sources = [
733
  {"title": r["title"], "url": r["source"]}
734
- for r in rag_results
735
- if r.get("source")
736
  ]
737
 
738
  return AgentResponse(
@@ -746,56 +814,48 @@ async def agent_query(request: Request, req: AgentRequest):
746
  )
747
 
748
  elif intent in ("search_academic", "search_medical"):
749
- # ── Step 1: Extract clean topic ───────────────────────────────────
750
  topic = _extract_topic(question)
751
- label = "medical" if intent == "search_medical" else "academic"
752
  is_medical = intent == "search_medical"
753
 
754
- # ── Step 2: Web search for context about the topic ────────────────
755
- context_answer = await _web_search_answer(
756
- f"Brief overview of {topic} (2-3 sentences, academic context)",
757
- history,
758
- model,
759
- )
760
-
761
- # ── Step 3: Inline PRIMO search ───────────────────────────────────
762
- search_results = await _primo_inline_search(topic, limit=5)
763
-
764
- # ── Step 4: Build the combined answer ─────────────────────────────
765
- answer = context_answer + "<br><br>"
766
-
767
- if search_results:
768
- answer += (
769
- f"<strong>πŸ“š Here are some resources I found in the KU Library catalogue:</strong>"
770
- )
771
  else:
772
- primo_url = (
773
- f"https://khalifa.primo.exlibrisgroup.com/discovery/search"
774
- f"?query=any,contains,{quote(topic)}&vid=971KUOSTAR_INST:KU"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
775
  )
776
  answer += (
777
- f"I didn't find results in the KU catalogue for <em>{topic}</em> right now. "
778
- f'Try searching directly in <a href="{primo_url}" target="_blank">PRIMO</a>.'
 
 
 
 
779
  )
780
-
781
- # ── Step 5: Follow-up offer ───────────────────────────────────────
782
- pubmed_offer = (
783
- "<br>β€’ πŸ₯ <strong>Search PubMed</strong> for medical/clinical literature?"
784
- if is_medical else ""
785
- )
786
- answer += (
787
- "<br><br>πŸ’‘ <strong>Want me to refine this?</strong><br>"
788
- "β€’ Narrow to <strong>peer reviewed</strong> only?<br>"
789
- "β€’ Limit to a specific <strong>year range</strong>?<br>"
790
- "β€’ Find <strong>books</strong> instead of articles?"
791
- + pubmed_offer +
792
- "<br><br>Just tell me what you need!"
793
- )
794
 
795
  return AgentResponse(
796
  answer=answer,
797
  intent=intent,
798
- tools_used=["web_search", "primo_inline"],
799
  search_results=search_results,
800
  corrected_query=topic,
801
  natural_query=topic,
@@ -805,7 +865,6 @@ async def agent_query(request: Request, req: AgentRequest):
805
  )
806
 
807
  elif intent == "general_recent":
808
- # Truly live/real-time β†’ web search
809
  answer = await _web_search_answer(question, history, model)
810
  return AgentResponse(
811
  answer=answer,
@@ -816,7 +875,6 @@ async def agent_query(request: Request, req: AgentRequest):
816
  )
817
 
818
  else: # general
819
- # Factual questions β†’ web search for current accurate answers
820
  answer = await _web_search_answer(question, history, model)
821
  return AgentResponse(
822
  answer=answer,
 
119
  r"|clinical trial|biomedical literature|medical literature)\b",
120
  re.IGNORECASE,
121
  )
 
 
122
  CURRENT_INFO_RE = re.compile(
123
  r"\b(current|currently|latest|today|recent|recently|now|this week|this month"
124
  r"|news|update|updated|prime minister|ceo|minister|king|ruler|who won)\b",
125
  re.IGNORECASE,
126
  )
127
 
128
+ # Detects summary/overview/explain requests
129
+ SUMMARY_RE = re.compile(
130
+ r"\b(summar(y|ize|ise|izing|ising)|overview|explain|what is|what are|describe"
131
+ r"|tell me about|give me a summary|give me an overview|give me a brief"
132
+ r"|brief (summary|overview|explanation|description)"
133
+ r"|research (overview|summary|landscape|state)"
134
+ r"|state of (the art|research|the field)"
135
+ r"|recent (advances?|developments?|progress|trends?)"
136
+ r"|current (state|trends?|advances?|research)"
137
+ r"|review of|literature review)\b",
138
+ re.IGNORECASE,
139
+ )
140
+
141
  MEDICAL_KEYWORDS = [
142
  "medicine", "medical", "health", "clinical", "nursing", "pharmacy", "biomedical",
143
  "anatomy", "physiology", "epidemiology", "oncology", "cardiology", "neuroscience",
 
149
  "crispr", "gene therapy", "gene editing", "genomic medicine", "precision medicine",
150
  ]
151
 
152
+ # ── Classifier Prompt ─────────────────────────────────────────────────────────
153
 
154
  _CLASSIFIER_SYSTEM = """You are the routing brain of LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE).
155
  Your only job: read the user message and return a single JSON object routing it to the right handler.
 
157
  INTENTS β€” pick exactly one:
158
  "social" β€” casual chat, greetings, emotions, compliments, complaints, vague help requests
159
  "library_info" β€” questions about KU Library services, hours, rooms, borrowing, fines, ILL, staff, databases, ORCID, RefWorks, open access, APC, account, printing, remote access, LibKey, acquisitions, Khazna, thesis submission, library policies, alumni access
160
+ "search_academic"β€” user wants to FIND / GET / RETRIEVE articles / papers / books on a specific academic topic, OR wants a SUMMARY/OVERVIEW grounded in academic literature
161
  "search_medical" β€” same as search_academic but topic is medical/clinical/nursing/pharmacy/health sciences
162
+ "general_recent" β€” questions about TRULY live/real-time data: breaking news, live sports scores, today's weather, current stock prices
163
+ "general" β€” ALL other factual questions: university info, people, history, science, technology, definitions
164
 
165
  RULES:
166
  1. When in doubt between library_info and social, choose library_info if ANY library keyword is present.
 
168
  3. "I am fed up with searching" alone = social.
169
  4. "I need help finding articles on diabetes" = search_medical.
170
  5. KU = Khalifa University. Do NOT confuse with Kuwait University.
171
+ 6. ANY question asking for a summary, overview, review, or explanation of an academic/research topic = search_academic or search_medical (will be answered using library catalogue).
172
+ 7. Questions about people, university leadership, history, science definitions = general.
173
+ 8. Only use general_recent for truly live data changing by the minute.
174
 
175
  For "social" intent ONLY: include "casual_answer" β€” a warm 1-3 sentence LibBee response (no markdown, no bullets).
176
  For all other intents: omit "casual_answer".
 
188
 
189
  # ── Helper Functions ───────────────────────────────────────────────────────────
190
 
191
+ def _is_summary_request(question: str) -> bool:
192
+ """Returns True if the question is asking for a summary/overview of a topic."""
193
+ return bool(SUMMARY_RE.search(question))
194
+
195
+
196
  def _extract_topic(question: str) -> str:
197
+ """Strip search/summary boilerplate to get the core topic."""
198
  q = question.strip()
199
  prefixes = [
200
+ "give me a summary of ", "give me a summary on ", "give me a summary about ",
201
+ "give me an overview of ", "give me an overview on ",
202
+ "give me a brief overview of ", "give me a brief summary of ",
203
+ "summarize ", "summarise ",
204
+ "summary of ", "summary on ", "summary about ",
205
+ "overview of ", "overview on ",
206
+ "brief overview of ", "brief summary of ",
207
+ "explain ", "tell me about ",
208
+ "what is ", "what are ",
209
+ "describe ",
210
+ "review of ", "literature review on ",
211
+ "recent advances in ", "recent developments in ",
212
+ "state of the art in ", "state of research on ",
213
+ "research overview of ", "research summary of ",
214
  "find articles on ", "find papers on ", "find books on ",
215
  "find articles about ", "find papers about ", "find books about ",
216
  "search for articles on ", "search for papers on ",
 
220
  "get me articles on ", "look for articles on ",
221
  "articles on ", "papers on ", "books on ",
222
  "research on ", "literature on ",
223
+ "find ", "search for ", "i need ", "give me ",
224
+ "show me ", "get me ",
225
  ]
226
  lower = q.lower()
227
  for prefix in prefixes:
228
  if lower.startswith(prefix):
229
  q = q[len(prefix):]
230
  break
231
+ q = re.sub(r'\s+(please|thanks|thank you)\.?$', '', q, flags=re.IGNORECASE)
232
  return q.strip()
233
 
234
 
 
281
  }
282
  if _looks_medical_search(question):
283
  return {"intent": "search_medical"}
284
+ if _looks_research_question(question) or _is_summary_request(question):
285
  return {"intent": "search_academic"}
286
  if LIBRARY_CUE_RE.search(q):
287
  return {"intent": "library_info"}
 
363
 
364
  async def _llm_classify(question: str, history: List[ChatMessage], model: str) -> Dict:
365
  settings = get_settings()
 
366
  if not settings.openai_api_key:
367
  return _rule_based_classify(question)
368
 
 
402
  ) -> str:
403
  if hint and len(hint.strip()) > 25:
404
  return hint.strip()
 
405
  settings = get_settings()
406
  if not settings.openai_api_key:
407
+ return "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant β€” always happy to help!"
 
408
  try:
409
  llm = _get_llm(model, temperature=0.6, max_tokens=200)
410
  msgs = [{"role": "system", "content": (
411
  "You are LibBee, the Khalifa University Library AI Assistant. "
412
+ "Respond warmly and naturally in 1-3 sentences as a friendly librarian. "
413
  "No markdown, no bullet points."
414
  )}]
415
  msgs.extend(_build_history_messages(history))
 
417
  response = await llm.ainvoke(msgs)
418
  return response.content.strip()
419
  except Exception:
420
+ return "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant β€” always happy to help!"
421
 
422
 
423
  async def _rag_answer(
424
+ question: str, rag_results: List[dict], history: List[ChatMessage], model: str
 
 
 
425
  ) -> str:
426
  settings = get_settings()
427
  if not settings.openai_api_key:
 
432
  "You are LibBee, the Khalifa University Library AI Assistant. "
433
  "Answer the user's question using ONLY the context provided below. "
434
  "Be concise, friendly, and use HTML <br> for line breaks where needed. "
435
+ "If the context does not contain enough information, say so and suggest "
436
+ "Ask a Librarian at https://library.ku.ac.ae/AskUs. "
437
  "Never invent facts or URLs.\n\n"
438
  f"CONTEXT:\n{context}"
439
  )
 
440
  try:
441
  llm = _get_llm(model, temperature=0.2, max_tokens=400)
442
  msgs = [{"role": "system", "content": system}]
 
445
  response = await llm.ainvoke(msgs)
446
  return response.content.strip()
447
  except Exception as e:
448
+ logger.error(f"_rag_answer error: {e}")
449
  return (
450
+ "I'm having trouble generating an answer. Please try "
451
+ '<a href="https://library.ku.ac.ae/AskUs" target="_blank">Ask a Librarian</a>.'
 
452
  )
453
 
454
 
455
  async def _web_search_answer(
456
+ question: str, history: List[ChatMessage], model: str
 
 
457
  ) -> str:
458
+ """Web search for both models. Falls back to LLM knowledge if unavailable."""
 
 
 
 
 
459
  settings = get_settings()
460
 
461
+ # Claude web search
462
  if model == "claude" and settings.anthropic_api_key:
463
  try:
464
  import anthropic
465
  client = anthropic.Anthropic(api_key=settings.anthropic_api_key)
 
466
  response = client.messages.create(
467
  model="claude-3-haiku-20240307",
468
  max_tokens=600,
469
  system=(
470
  "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
471
+ "Answer using current web search. Be concise and factual. "
472
+ "Use HTML <br> for line breaks. KU = Khalifa University."
 
 
473
  ),
474
  tools=[{"type": "web_search_20250305", "name": "web_search"}],
475
  messages=[{"role": "user", "content": question}],
476
  )
477
+ text = "".join(
478
+ block.text for block in response.content if hasattr(block, "text")
479
+ )
 
 
 
480
  if text.strip():
 
481
  return text.strip()
 
482
  except Exception as e:
483
  logger.warning(f"Claude web search failed: {e}")
484
 
485
+ # GPT OpenAI Responses API
486
  if settings.openai_api_key:
487
  try:
488
  from openai import OpenAI
489
  client = OpenAI(api_key=settings.openai_api_key)
 
490
  response = client.responses.create(
491
  model="gpt-4o-mini",
492
  tools=[{"type": "web_search_preview"}],
493
  instructions=(
494
  "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
495
+ "Answer using current web search. Be concise and factual. "
496
+ "Use HTML <br> for line breaks. KU = Khalifa University."
 
 
497
  ),
498
  input=question,
499
  )
 
500
  text = ""
501
  for item in response.output:
502
  if hasattr(item, "content"):
503
  for block in item.content:
504
  if hasattr(block, "text"):
505
  text += block.text
 
506
  if text.strip():
 
507
  return text.strip()
 
508
  except Exception as e:
509
  logger.warning(f"GPT web search failed: {e}")
510
 
511
+ # Fallback to LLM knowledge
 
512
  return await _llm_general_answer(question, history, model)
513
 
514
 
515
  async def _llm_general_answer(
516
+ question: str, history: List[ChatMessage], model: str
 
 
517
  ) -> str:
518
+ """Fallback: answer from LLM training knowledge."""
519
  settings = get_settings()
520
  if not settings.openai_api_key:
521
  return (
522
+ "I'm <strong>LibBee</strong>, the KU Library AI Assistant. "
523
+ f'For general questions visit <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a>.'
524
  )
 
525
  system = (
526
  "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
527
+ "Answer factually and concisely in 3-5 sentences. Use HTML <br> for line breaks. "
528
+ "KU = Khalifa University. If the topic is academic, briefly offer to find library resources."
 
 
 
 
529
  )
 
530
  try:
531
  llm = _get_llm(model, temperature=0.3, max_tokens=400)
532
  msgs = [{"role": "system", "content": system}]
 
536
  return response.content.strip()
537
  except Exception as e:
538
  logger.error(f"_llm_general_answer error: {e}")
539
+ return f'Having trouble right now. Visit <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a>.'
 
 
 
540
 
541
 
542
+ async def _primo_inline_search(topic: str, limit: int = 10) -> List[dict]:
543
+ """Search PRIMO and return results. API key in URL param (Ex Libris requirement)."""
 
 
 
544
  settings = get_settings()
545
  if not settings.primo_api_key:
546
+ logger.warning("PRIMO_API_KEY not set")
547
  return []
548
 
549
  query_encoded = quote(topic)
550
  url = (
551
  f"https://api-eu.hosted.exlibrisgroup.com/primo/v1/search"
552
+ f"?vid=971KUOSTAR_INST:KU&tab=Everything&scope=MyInst_and_CI"
553
+ f"&q=any,contains,{query_encoded}&lang=en&sort=rank"
 
 
 
554
  f"&limit={limit}&offset=0&mode=advanced"
555
  f"&apikey={settings.primo_api_key}"
556
  )
 
559
  async with httpx.AsyncClient(timeout=15) as client:
560
  r = await client.get(url, headers={"Accept": "application/json"})
561
  if r.status_code != 200:
562
+ logger.warning(f"PRIMO returned {r.status_code} for '{topic}'")
563
  return []
 
564
  data = r.json()
565
  results = []
566
  for doc in data.get("docs", [])[:limit]:
 
578
  ),
579
  "_source": "PRIMO",
580
  })
581
+ logger.info(f"PRIMO: {len(results)} results for '{topic}'")
582
  return results
 
583
  except Exception as e:
584
+ logger.error(f"PRIMO search failed: {e}")
585
  return []
586
 
587
 
588
+ async def _primo_summary(
589
+ topic: str, question: str, history: List[ChatMessage], model: str
590
+ ) -> tuple[str, List[dict]]:
591
+ """
592
+ Fetch top 10 PRIMO results for a topic, then use LLM to synthesize
593
+ a research summary grounded in those real library resources.
594
+ Returns (answer_html, search_results).
595
+ """
596
+ settings = get_settings()
597
+
598
+ # Step 1: fetch top 10 from PRIMO
599
+ results = await _primo_inline_search(topic, limit=10)
600
+
601
+ if not results:
602
+ # No PRIMO results β€” fall back to web search answer
603
+ primo_url = (
604
+ f"https://khalifa.primo.exlibrisgroup.com/discovery/search"
605
+ f"?query=any,contains,{quote(topic)}&vid=971KUOSTAR_INST:KU"
606
+ )
607
+ answer = (
608
+ f"I couldn't find resources on <em>{topic}</em> in the KU Library catalogue right now.<br><br>"
609
+ f'You can search directly in <a href="{primo_url}" target="_blank">PRIMO</a>, '
610
+ f"or I can give you a general overview from web sources β€” just ask!"
611
+ )
612
+ return answer, []
613
+
614
+ # Step 2: build context from titles, creators, dates, sources
615
+ articles_context = ""
616
+ for i, r in enumerate(results, 1):
617
+ articles_context += (
618
+ f"{i}. Title: {r['title']}\n"
619
+ f" Author(s): {r['creator']}\n"
620
+ f" Year: {r['date']}\n"
621
+ f" Source: {r['source']}\n\n"
622
+ )
623
+
624
+ # Step 3: LLM synthesizes a summary from those articles
625
+ system = (
626
+ "You are LibBee, the Khalifa University Library AI Assistant. "
627
+ "You have been given a list of real academic resources from the KU Library catalogue. "
628
+ "Write a concise research summary (4-6 sentences) on the topic based ONLY on the "
629
+ "titles, authors, and sources listed. Do NOT invent content not implied by the titles. "
630
+ "Focus on what themes and topics appear across these resources. "
631
+ "Use HTML <br><br> between paragraphs. Do not use bullet points or markdown. "
632
+ "End with: 'These resources are available in the KU Library catalogue.'"
633
+ )
634
+
635
+ user_msg = (
636
+ f"Topic: {topic}\n\n"
637
+ f"Resources from KU Library catalogue:\n{articles_context}\n"
638
+ f"Write a research summary of '{topic}' based on these resources."
639
+ )
640
+
641
+ summary = ""
642
+ if settings.openai_api_key:
643
+ try:
644
+ llm = _get_llm(model, temperature=0.3, max_tokens=500)
645
+ response = await llm.ainvoke([
646
+ {"role": "system", "content": system},
647
+ {"role": "user", "content": user_msg},
648
+ ])
649
+ summary = response.content.strip()
650
+ except Exception as e:
651
+ logger.error(f"Summary LLM failed: {e}")
652
+
653
+ if not summary:
654
+ summary = f"Here are the top resources on <strong>{topic}</strong> from the KU Library catalogue:"
655
+
656
+ # Step 4: build final answer with summary + linked article list
657
+ answer = f"<strong>πŸ“– Research Summary: {topic}</strong><br><br>{summary}<br><br>"
658
+ answer += f"<strong>πŸ“š Top {len(results)} resources from KU Library catalogue:</strong><br>"
659
+
660
+ for i, r in enumerate(results, 1):
661
+ safe_title = r["title"].replace("<", "&lt;").replace(">", "&gt;")
662
+ answer += (
663
+ f'<br><strong>{i}.</strong> <a href="{r["primo_url"]}" target="_blank">{safe_title}</a><br>'
664
+ f'<span style="font-size:.8rem;color:#6b7280">'
665
+ f'{r["creator"]} Β· {r["date"]} Β· {r["source"]}'
666
+ f'</span>'
667
+ )
668
+
669
+ # Step 5: refinement offer
670
+ answer += (
671
+ "<br><br>πŸ’‘ Want me to:<br>"
672
+ "β€’ Narrow to <strong>peer reviewed</strong> only?<br>"
673
+ "β€’ Filter by <strong>year range</strong>?<br>"
674
+ "β€’ Find <strong>books</strong> on this topic?<br>"
675
+ "Just tell me!"
676
+ )
677
+
678
+ return answer, results
679
+
680
+
681
  # ── Main Endpoint ──────────────────────────────────────────────────────────────
682
 
683
  @router.post("", response_model=AgentResponse)
 
697
 
698
  # ── LAYER 0: Instant rule-based handlers ─────────────────────────────
699
 
 
700
  if PURE_GREETING_RE.match(question):
701
  return AgentResponse(
702
  answer=(
 
710
  response_time=time.time() - start_time,
711
  )
712
 
 
713
  staff_match = match_staff_name(question)
714
  if staff_match:
715
  return AgentResponse(
 
720
  response_time=time.time() - start_time,
721
  )
722
 
 
723
  staff_role_match = match_staff_role(question)
724
  if staff_role_match:
725
  return AgentResponse(
 
730
  response_time=time.time() - start_time,
731
  )
732
 
 
733
  if _is_greeting_menu_followup(question, history):
734
  return AgentResponse(
735
  answer=_greeting_menu_clarify_answer(),
 
739
  response_time=time.time() - start_time,
740
  )
741
 
 
742
  if _looks_library_hours_question(question):
743
  return AgentResponse(
744
  answer=_hours_answer(),
 
749
  response_time=time.time() - start_time,
750
  )
751
 
 
752
  if _looks_campus_question(question):
753
  return AgentResponse(
754
  answer=_campus_answer(),
 
800
  tools_used = ["rag_hybrid_search"]
801
  sources = [
802
  {"title": r["title"], "url": r["source"]}
803
+ for r in rag_results if r.get("source")
 
804
  ]
805
 
806
  return AgentResponse(
 
814
  )
815
 
816
  elif intent in ("search_academic", "search_medical"):
 
817
  topic = _extract_topic(question)
818
+ is_summary = _is_summary_request(question)
819
  is_medical = intent == "search_medical"
820
 
821
+ if is_summary:
822
+ # ── SUMMARY MODE: fetch 10 articles β†’ synthesize summary β†’ show links ──
823
+ answer, search_results = await _primo_summary(topic, question, history, model)
824
+ tools_used = ["primo_summary"]
 
 
 
 
 
 
 
 
 
 
 
 
 
825
  else:
826
+ # ── FIND MODE: inline PRIMO results + refinement offer ─────────────────
827
+ search_results = await _primo_inline_search(topic, limit=5)
828
+
829
+ if search_results:
830
+ answer = f"<strong>πŸ“š Here are resources on <em>{topic}</em> from the KU Library catalogue:</strong>"
831
+ else:
832
+ primo_url = (
833
+ f"https://khalifa.primo.exlibrisgroup.com/discovery/search"
834
+ f"?query=any,contains,{quote(topic)}&vid=971KUOSTAR_INST:KU"
835
+ )
836
+ answer = (
837
+ f"I didn't find results in the KU catalogue for <em>{topic}</em> right now. "
838
+ f'Try searching directly in <a href="{primo_url}" target="_blank">PRIMO</a>.'
839
+ )
840
+
841
+ pubmed_offer = (
842
+ "<br>β€’ πŸ₯ <strong>Search PubMed</strong> for medical/clinical literature?"
843
+ if is_medical else ""
844
  )
845
  answer += (
846
+ "<br><br>πŸ’‘ <strong>Want me to refine this?</strong><br>"
847
+ "β€’ Narrow to <strong>peer reviewed</strong> only?<br>"
848
+ "β€’ Limit to a specific <strong>year range</strong>?<br>"
849
+ "β€’ Find <strong>books</strong> instead?"
850
+ + pubmed_offer +
851
+ "<br><br>Just tell me what you need!"
852
  )
853
+ tools_used = ["primo_inline"]
 
 
 
 
 
 
 
 
 
 
 
 
 
854
 
855
  return AgentResponse(
856
  answer=answer,
857
  intent=intent,
858
+ tools_used=tools_used,
859
  search_results=search_results,
860
  corrected_query=topic,
861
  natural_query=topic,
 
865
  )
866
 
867
  elif intent == "general_recent":
 
868
  answer = await _web_search_answer(question, history, model)
869
  return AgentResponse(
870
  answer=answer,
 
875
  )
876
 
877
  else: # general
 
878
  answer = await _web_search_answer(question, history, model)
879
  return AgentResponse(
880
  answer=answer,