nikeshn commited on
Commit
ef033e9
·
verified ·
1 Parent(s): 518ed98

Upload 15 files

Browse files
src/agentcore/constants.py CHANGED
@@ -844,6 +844,7 @@ _DB_SUBJECTS: Dict[str, List[Tuple[str, str, str]]] = {
844
  ("Knovel", _openathens_url("https://app.knovel.com"), "Engineering reference and handbooks."),
845
  ("Scopus", _openathens_url("https://www.scopus.com"), "Discovery and citation tracking."),
846
  ("Web of Science", _openathens_url("https://www.webofscience.com"), "Broad citation discovery."),
 
847
  ],
848
  "quantum_computing": [
849
  ("IEEE Xplore", _openathens_url("https://ieeexplore.ieee.org"), "Quantum computing engineering implementations."),
@@ -879,6 +880,7 @@ _DB_SUBJECTS: Dict[str, List[Tuple[str, str, str]]] = {
879
  ("Emerald Insight", _openathens_url("https://www.emerald.com/insight"), "Management, strategy, and leadership journals."),
880
  ("ProQuest Databases", _openathens_url("https://search.proquest.com"), "Broad business and interdisciplinary discovery."),
881
  ("JSTOR", _openathens_url("https://www.jstor.org"), "Business, economics, and policy literature."),
 
882
  ("Scopus", _openathens_url("https://www.scopus.com"), "Broad discovery and citation tracking."),
883
  ],
884
  "earth_science": [
@@ -887,11 +889,13 @@ _DB_SUBJECTS: Dict[str, List[Tuple[str, str, str]]] = {
887
  ("ScienceDirect", _openathens_url("https://www.sciencedirect.com"), "Full text for geoscience and planetary topics."),
888
  ("Scopus", _openathens_url("https://www.scopus.com"), "Discovery and citation tracking."),
889
  ("Web of Science", _openathens_url("https://www.webofscience.com"), "Broad citation discovery."),
 
890
  ],
891
  "environment": [
892
  ("ScienceDirect", _openathens_url("https://www.sciencedirect.com"), "Strong sustainability and environmental full text."),
893
  ("ProQuest Databases", _openathens_url("https://search.proquest.com"), "Environmental policy and interdisciplinary discovery."),
894
  ("Web of Science", _openathens_url("https://www.webofscience.com"), "Broad citation discovery."),
 
895
  ("Scopus", _openathens_url("https://www.scopus.com"), "Broad discovery and citation tracking."),
896
  ("Business Source Complete", _openathens_url("https://search.ebscohost.com"), "Sustainability, policy, and corporate responsibility."),
897
  ],
@@ -920,6 +924,7 @@ _DB_GENERAL: List[Tuple[str, str, str]] = [
920
  ("PRIMO (KU Library Discovery)", "https://khalifa.primo.exlibrisgroup.com/discovery/search?vid=971KUOSTAR_INST:KU", "Best starting point — search all KU books, articles, and journals."),
921
  ("Scopus", _openathens_url("https://www.scopus.com"), "Largest abstract and citation database — all disciplines."),
922
  ("Web of Science", _openathens_url("https://www.webofscience.com"), "Premier citation index — all disciplines."),
 
923
  ("ScienceDirect", _openathens_url("https://www.sciencedirect.com"), "Large full-text platform across science, engineering, and medicine."),
924
  ("SpringerLink", _openathens_url("https://link.springer.com"), "Springer journals and books across all disciplines."),
925
  ("ProQuest Databases", _openathens_url("https://search.proquest.com"), "Broad multidisciplinary discovery."),
 
844
  ("Knovel", _openathens_url("https://app.knovel.com"), "Engineering reference and handbooks."),
845
  ("Scopus", _openathens_url("https://www.scopus.com"), "Discovery and citation tracking."),
846
  ("Web of Science", _openathens_url("https://www.webofscience.com"), "Broad citation discovery."),
847
+ ("Wiley Online Library", _openathens_url("https://onlinelibrary.wiley.com"), "Wiley journals and books across science, engineering and social sciences."),
848
  ],
849
  "quantum_computing": [
850
  ("IEEE Xplore", _openathens_url("https://ieeexplore.ieee.org"), "Quantum computing engineering implementations."),
 
880
  ("Emerald Insight", _openathens_url("https://www.emerald.com/insight"), "Management, strategy, and leadership journals."),
881
  ("ProQuest Databases", _openathens_url("https://search.proquest.com"), "Broad business and interdisciplinary discovery."),
882
  ("JSTOR", _openathens_url("https://www.jstor.org"), "Business, economics, and policy literature."),
883
+ ("Wiley Online Library", _openathens_url("https://onlinelibrary.wiley.com"), "Business, management and economics journals."),
884
  ("Scopus", _openathens_url("https://www.scopus.com"), "Broad discovery and citation tracking."),
885
  ],
886
  "earth_science": [
 
889
  ("ScienceDirect", _openathens_url("https://www.sciencedirect.com"), "Full text for geoscience and planetary topics."),
890
  ("Scopus", _openathens_url("https://www.scopus.com"), "Discovery and citation tracking."),
891
  ("Web of Science", _openathens_url("https://www.webofscience.com"), "Broad citation discovery."),
892
+ ("Wiley Online Library", _openathens_url("https://onlinelibrary.wiley.com"), "Wiley journals and books across science, engineering and social sciences."),
893
  ],
894
  "environment": [
895
  ("ScienceDirect", _openathens_url("https://www.sciencedirect.com"), "Strong sustainability and environmental full text."),
896
  ("ProQuest Databases", _openathens_url("https://search.proquest.com"), "Environmental policy and interdisciplinary discovery."),
897
  ("Web of Science", _openathens_url("https://www.webofscience.com"), "Broad citation discovery."),
898
+ ("Wiley Online Library", _openathens_url("https://onlinelibrary.wiley.com"), "Wiley journals and books across science, engineering and social sciences."),
899
  ("Scopus", _openathens_url("https://www.scopus.com"), "Broad discovery and citation tracking."),
900
  ("Business Source Complete", _openathens_url("https://search.ebscohost.com"), "Sustainability, policy, and corporate responsibility."),
901
  ],
 
924
  ("PRIMO (KU Library Discovery)", "https://khalifa.primo.exlibrisgroup.com/discovery/search?vid=971KUOSTAR_INST:KU", "Best starting point — search all KU books, articles, and journals."),
925
  ("Scopus", _openathens_url("https://www.scopus.com"), "Largest abstract and citation database — all disciplines."),
926
  ("Web of Science", _openathens_url("https://www.webofscience.com"), "Premier citation index — all disciplines."),
927
+ ("Wiley Online Library", _openathens_url("https://onlinelibrary.wiley.com"), "Wiley journals and books across science, engineering and social sciences."),
928
  ("ScienceDirect", _openathens_url("https://www.sciencedirect.com"), "Large full-text platform across science, engineering, and medicine."),
929
  ("SpringerLink", _openathens_url("https://link.springer.com"), "Springer journals and books across all disciplines."),
930
  ("ProQuest Databases", _openathens_url("https://search.proquest.com"), "Broad multidisciplinary discovery."),
src/agentcore/intents_general.py CHANGED
@@ -1,390 +1,396 @@
1
- """general / social intents: web-search answers, general LLM answers, casual persona replies."""
2
- import asyncio
3
- import html
4
- import json
5
- import logging
6
- import os
7
- import re
8
- import time
9
- import uuid
10
- from datetime import datetime
11
- from typing import Any, Dict, List, Literal, Optional, Tuple
12
- from urllib.parse import quote, urlsplit
13
-
14
- import httpx
15
- from pydantic import BaseModel, ConfigDict, Field
16
-
17
- from src.config import get_settings, LIBBEE_VERSION
18
-
19
- from src.agentcore.models import ChatMessage
20
- from src.agentcore.constants import (
21
- ASK_LIBRARIAN_URL, KU_MAIN_URL, KU_WEB_DOMAINS, _GUARDRAIL, _URL_INSTRUCTION,
22
- )
23
- from src.agentcore.utils import _build_history_messages, _get_llm, _get_runtime_config
24
-
25
- logger = logging.getLogger(__name__)
26
-
27
- async def _libbee_casual_response(question: str, history: List[ChatMessage], model: str, hint: str = "") -> str:
28
- """LLM #1 — casual social response. v3.8.1: appends _GUARDRAIL + _URL_INSTRUCTION."""
29
- if hint and len(hint.strip()) > 20:
30
- return hint.strip()
31
- settings = get_settings()
32
- if not settings.openai_api_key and not settings.anthropic_api_key:
33
- return "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant — always happy to help!"
34
- try:
35
- llm = _get_llm(model, temperature=0.6, max_tokens=160, task="casual")
36
- msgs = [{"role": "system", "content": (
37
- "You are LibBee, the Khalifa University Library AI Assistant. "
38
- "Respond warmly and naturally in 1-3 sentences as a friendly librarian. "
39
- "No markdown, no bullet points. "
40
- + _GUARDRAIL + "\n\n" + _URL_INSTRUCTION
41
- )}]
42
- _cfg = _get_runtime_config()
43
- _ci = _cfg.get("custom_instructions", "").strip()
44
- if _ci:
45
- msgs[0]["content"] += " " + _ci
46
- msgs.extend(_build_history_messages(history))
47
- msgs.append({"role": "user", "content": question})
48
- response = await llm.ainvoke(msgs)
49
- return response.content.strip()
50
- except Exception:
51
- return "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant — always happy to help!"
52
-
53
-
54
- async def _llm_general_answer(question: str, history: List[ChatMessage], model: str) -> str:
55
- """LLM #3 — general factual answer. v3.8.1: appends _GUARDRAIL + _URL_INSTRUCTION."""
56
- settings = get_settings()
57
- if not settings.openai_api_key and not settings.anthropic_api_key:
58
- return (
59
- "I'm <strong>LibBee</strong>, the KU Library AI Assistant. "
60
- f'For general university information, visit <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a>.'
61
- )
62
- system = (
63
- "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
64
- "Answer factually and concisely in 3-5 sentences. Use HTML <br> for line breaks. "
65
- "KU means Khalifa University. If the topic is academic, briefly offer to help find library resources. "
66
- "When referencing KU Library services, include these verified links where relevant: "
67
- "Library homepage: https://library.ku.ac.ae | "
68
- "Ask a Librarian: https://library.ku.ac.ae/AskUs | "
69
- "Library hours: https://library.ku.ac.ae/hours | "
70
- "ILL requests: https://library.ku.ac.ae/ill/ | "
71
- "Study rooms: https://library.ku.ac.ae/rooms/ | "
72
- "E-resources: https://library.ku.ac.ae/eresources | "
73
- "Khazna repository: https://khazna.ku.ac.ae | "
74
- "PRIMO discovery: https://khalifa.primo.exlibrisgroup.com/discovery/search?vid=971KUOSTAR_INST:KU. "
75
- "Only use these exact URLs — never invent others. "
76
- + _GUARDRAIL + "\n\n" + _URL_INSTRUCTION
77
- )
78
- _cfg = _get_runtime_config()
79
- _ci = _cfg.get("custom_instructions", "").strip()
80
- if _ci:
81
- system += " " + _ci
82
- try:
83
- llm = _get_llm(model, temperature=0.3, max_tokens=360, task="answer")
84
- msgs = [{"role": "system", "content": system}]
85
- msgs.extend(_build_history_messages(history))
86
- msgs.append({"role": "user", "content": question})
87
- response = await llm.ainvoke(msgs)
88
- return response.content.strip()
89
- except Exception as e:
90
- logger.error(f"_llm_general_answer error: {e}")
91
- return f'Having trouble right now. Visit <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a>.'
92
-
93
-
94
- def _response_field(value: Any, name: str, default: Any = None) -> Any:
95
- """Read SDK objects and dictionaries without depending on a provider SDK."""
96
- return value.get(name, default) if isinstance(value, dict) else getattr(value, name, default)
97
-
98
-
99
- def _citation_source(citation: Any) -> Optional[dict]:
100
- url = str(_response_field(citation, "url", "") or "").strip()
101
- try:
102
- parsed = urlsplit(url)
103
- if (parsed.scheme not in ("http", "https") or not parsed.hostname
104
- or parsed.username or parsed.password or any(ord(c) < 32 for c in url)):
105
- return None
106
- except ValueError:
107
- return None
108
- return {"title": str(_response_field(citation, "title", "") or parsed.hostname),
109
- "url": url, "source": "web_search"}
110
-
111
-
112
- def _host_allowed(url: str, domains) -> bool:
113
- """True when the URL's host is one of the domains or a subdomain of one."""
114
- try:
115
- host = (urlsplit(url).hostname or "").lower()
116
- except ValueError:
117
- return False
118
- return any(host == d or host.endswith("." + d) for d in domains)
119
-
120
-
121
- def _render_web_text(block: Any, sources: List[dict], anthropic: bool = False, domains=None) -> str:
122
- """Escape provider prose and attach real, clickable citations at their source span.
123
-
124
- With ``domains`` set, citations to any other site are dropped in code, so a
125
- scoped answer can never link outside the allowed sites.
126
- """
127
- raw = str(_response_field(block, "text", "") or "")
128
- if not raw:
129
- return ""
130
- citations = _response_field(block, "citations" if anthropic else "annotations", []) or []
131
- insertions: Dict[int, List[str]] = {}
132
- for citation in citations:
133
- kind = _response_field(citation, "type", "")
134
- if kind != ("web_search_result_location" if anthropic else "url_citation"):
135
- continue
136
- source = _citation_source(citation)
137
- if not source:
138
- continue
139
- if domains and not _host_allowed(source["url"], domains):
140
- continue
141
- existing = next((i for i, item in enumerate(sources) if item["url"] == source["url"]), None)
142
- if existing is None:
143
- sources.append(source)
144
- existing = len(sources) - 1
145
- position = len(raw) if anthropic else _response_field(citation, "end_index", len(raw))
146
- if not isinstance(position, int) or not 0 <= position <= len(raw):
147
- position = len(raw)
148
- link = (f' <a href="{html.escape(source["url"], quote=True)}" target="_blank" '
149
- f'rel="noopener noreferrer" title="{html.escape(source["title"], quote=True)}">'
150
- f'[{existing + 1}]</a>')
151
- if link not in insertions.setdefault(position, []):
152
- insertions[position].append(link)
153
-
154
- def escaped(segment: str) -> str:
155
- # SDK citation tokens have no meaning to a browser; links above replace them.
156
- segment = re.sub(r"\ue200cite[^\ue201]*\ue201", "", segment)
157
- return html.escape(segment).replace("\n", "<br>")
158
-
159
- answer, previous = [], 0
160
- for position in sorted(insertions):
161
- answer.append(escaped(raw[previous:position]))
162
- answer.extend(insertions[position])
163
- previous = position
164
- answer.append(escaped(raw[previous:]))
165
- return "".join(answer)
166
-
167
-
168
- def _parse_web_response(response: Any, provider: str, domains=None) -> dict:
169
- """Only label an answer live when a search completed and returned cited sources."""
170
- sources: List[dict] = []
171
- parts: List[str] = []
172
- searched = False
173
- if provider == "claude":
174
- for block in _response_field(response, "content", []) or []:
175
- kind = _response_field(block, "type", "")
176
- if kind == "web_search_tool_result":
177
- # API search errors are objects inside a successful HTTP response.
178
- result = _response_field(block, "content")
179
- searched = searched or isinstance(result, list)
180
- elif kind == "text":
181
- parts.append(_render_web_text(block, sources, anthropic=True, domains=domains))
182
- finished = _response_field(response, "stop_reason", "end_turn") == "end_turn"
183
- else:
184
- for item in _response_field(response, "output", []) or []:
185
- if (_response_field(item, "type", "") == "web_search_call"
186
- and _response_field(item, "status", "") == "completed"):
187
- searched = True
188
- for block in _response_field(item, "content", []) or []:
189
- if _response_field(block, "type", "") == "output_text":
190
- parts.append(_render_web_text(block, sources, domains=domains))
191
- finished = _response_field(response, "status", "completed") == "completed"
192
- live = searched and finished and bool(sources)
193
- return {"answer": "".join(parts).strip(), "sources": sources,
194
- "tools_used": ["web_search"] if searched else [],
195
- "live_search": live, "model_used": provider}
196
-
197
-
198
- _COURTESY_NOTE = (
199
- '<p class="lb-courtesy">This is outside the library\'s services, '
200
- "so I looked it up on the web as a courtesy.</p>"
201
- )
202
- _KU_CHECK_NOTE = (
203
- '<p class="lb-muted">Fees, dates and requirements change. '
204
- "Please confirm the details on the linked page.</p>"
205
- )
206
- # Known-good configuration used when the routed web model is unavailable.
207
- _LEGACY_WEB_MODEL = "gpt-4.1-mini"
208
-
209
-
210
- def _ku_not_found() -> dict:
211
- """University facts are never answered from model memory."""
212
- return {
213
- "answer": (
214
- "I searched Khalifa University's web pages but could not find a reliable answer to that. "
215
- f'Please check <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a> directly, or '
216
- f'<a href="{ASK_LIBRARIAN_URL}" target="_blank">ask a librarian</a> and we will point you '
217
- "to the right office."
218
- ),
219
- "sources": [], "tools_used": ["ku_web_search"], "live_search": False,
220
- "model_used": "gpt", "scope": "ku",
221
- }
222
-
223
-
224
- def _web_system_prompt(scope: str) -> str:
225
- base = "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
226
- if scope == "ku":
227
- return (
228
- base
229
- + "The user is asking about Khalifa University. Search and answer ONLY from pages on "
230
- "ku.ac.ae (including khazna.ku.ac.ae). Give figures, dates, names and requirements exactly "
231
- "as the page states them. If the pages you find do not answer the question, say that you "
232
- "could not find it on the university's website; do not answer from prior knowledge. "
233
- "Be concise and factual. Use plain text with paragraph breaks, no HTML or Markdown. "
234
- "Cite every factual claim with the search tool's citations; never invent sources or URLs. "
235
- "The application renders citation links, so do not write links yourself. "
236
- + _GUARDRAIL
237
- )
238
- return (
239
- base
240
- + "Search the web and answer using current sources. Be concise and factual. "
241
- "Use plain text with paragraph breaks, no HTML or Markdown. "
242
- "Cite factual claims using the search tool's citations; never invent sources or URLs. "
243
- "The application renders citation links, so do not write HTML links yourself. "
244
- + _GUARDRAIL
245
- )
246
-
247
-
248
- async def _openai_web_attempt(client: Any, model_name: str, legacy: bool, system: str,
249
- messages: List[dict], domains) -> Any:
250
- """One Responses API call. ``legacy`` uses the preview tool, which has no domain filter."""
251
- if legacy:
252
- tools: List[dict] = [{"type": "web_search_preview"}]
253
- tool_choice: Any = {"type": "web_search_preview"}
254
- else:
255
- tool: Dict[str, Any] = {"type": "web_search"}
256
- if domains:
257
- tool["filters"] = {"allowed_domains": list(domains)}
258
- tools, tool_choice = [tool], "required"
259
- kwargs: Dict[str, Any] = dict(
260
- model=model_name, tools=tools, tool_choice=tool_choice, instructions=system,
261
- input=messages, max_output_tokens=620, store=False,
262
- )
263
- if re.match(r"(?:gpt-[5-9]|o\d)", model_name):
264
- # Reasoning tokens are billed against max_output_tokens.
265
- kwargs["reasoning"] = {"effort": os.getenv("LIBBEE_WEB_REASONING_EFFORT", "low")}
266
- kwargs["max_output_tokens"] = 1600
267
- return await asyncio.wait_for(client.responses.create(**kwargs), timeout=18.0)
268
-
269
-
270
- async def _web_search_result(question: str, history: List[ChatMessage], model: str,
271
- scope: str = "open", courtesy: bool = False) -> dict:
272
- """Return source evidence alongside text, with bounded calls and honest fallback metadata.
273
-
274
- scope="ku" restricts the search and every citation to Khalifa University sites and
275
- never falls back to model memory. ``courtesy`` prefixes a short note for everyday
276
- questions that are outside the library's services.
277
- """
278
- settings = get_settings()
279
- ku = scope == "ku"
280
- domains = tuple(KU_WEB_DOMAINS) if ku else None
281
- system = _web_system_prompt(scope) if (ku or settings.openai_api_key or settings.anthropic_api_key) else ""
282
- messages = _build_history_messages(history)
283
- messages.append({"role": "user", "content": question})
284
-
285
- def finish(result: dict) -> dict:
286
- result["scope"] = scope
287
- if ku:
288
- result["tools_used"] = ["ku_web_search"]
289
- result["answer"] += _KU_CHECK_NOTE
290
- elif courtesy:
291
- result["answer"] = _COURTESY_NOTE + result["answer"]
292
- return result
293
-
294
- if settings.anthropic_api_key and (model == "claude" or not settings.openai_api_key):
295
- try:
296
- import anthropic
297
- tool: Dict[str, Any] = {"type": "web_search_20250305", "name": "web_search", "max_uses": 2}
298
- if domains:
299
- tool["allowed_domains"] = list(domains)
300
- async with anthropic.AsyncAnthropic(
301
- api_key=settings.anthropic_api_key, timeout=16.0, max_retries=0
302
- ) as client:
303
- response = await asyncio.wait_for(client.messages.create(
304
- model=os.getenv("ANTHROPIC_WEB_MODEL", "claude-haiku-4-5-20251001"),
305
- max_tokens=620,
306
- system=system,
307
- tools=[tool],
308
- messages=messages,
309
- ), timeout=18.0)
310
- result = _parse_web_response(response, "claude", domains)
311
- if result["answer"] and result["live_search"]:
312
- return finish(result)
313
- logger.info("Claude web response had no complete cited search answer")
314
- except Exception as exc:
315
- logger.warning("Claude web search failed (%s)", type(exc).__name__)
316
- if settings.openai_api_key:
317
- primary = os.getenv("OPENAI_WEB_MODEL", "gpt-6.1-terra").strip() or _LEGACY_WEB_MODEL
318
- attempts = [(primary, False)]
319
- if primary != _LEGACY_WEB_MODEL:
320
- attempts.append((_LEGACY_WEB_MODEL, True))
321
- try:
322
- from openai import AsyncOpenAI
323
- async with AsyncOpenAI(
324
- api_key=settings.openai_api_key, timeout=16.0, max_retries=0
325
- ) as client:
326
- for model_name, legacy in attempts:
327
- try:
328
- response = await _openai_web_attempt(
329
- client, model_name, legacy, system, messages, domains)
330
- except Exception as exc:
331
- logger.warning("GPT web search failed on %s (%s)", model_name, type(exc).__name__)
332
- continue
333
- result = _parse_web_response(response, "gpt", domains)
334
- if result["answer"] and result["live_search"]:
335
- return finish(result)
336
- logger.info("GPT web response had no complete cited search answer")
337
- break
338
- except Exception as exc:
339
- logger.warning("GPT web search failed (%s)", type(exc).__name__)
340
- if ku:
341
- return _ku_not_found()
342
- fallback = await _llm_general_answer(question, history, model)
343
- provider = "claude" if settings.anthropic_api_key and (model == "claude" or not settings.openai_api_key) else "gpt"
344
- answer = "<em>I couldn’t verify current web information. The following is general guidance and may be out of date.</em><br><br>" + fallback
345
- if courtesy:
346
- answer = _COURTESY_NOTE + answer
347
- return {
348
- "answer": answer,
349
- "sources": [], "tools_used": ["general_knowledge"], "live_search": False,
350
- "model_used": provider, "scope": scope,
351
- }
352
-
353
-
354
- async def _web_search_answer(question: str, history: List[ChatMessage], model: str) -> str:
355
- """Compatibility wrapper; orchestration uses _web_search_result for source metadata."""
356
- return (await _web_search_result(question, history, model))["answer"]
357
-
358
-
359
- def _general_follow_up(question: str) -> Tuple[str, List[dict]]:
360
- return (
361
- "Would you like a brief explanation, current web information, or KU Library resources on this topic?",
362
- [
363
- {"label": "Shorter explanation", "question": f"Give me a shorter explanation of {question}"},
364
- {"label": "Current web information", "question": f"Show current web information on {question}"},
365
- {"label": "Find KU Library resources", "question": f"Find KU Library resources on {question}"},
366
- ],
367
- )
368
-
369
-
370
- def _ku_follow_up(question: str) -> Tuple[str, List[dict]]:
371
- return (
372
- "",
373
- [
374
- {"label": "Find library resources on this", "question": f"Find KU Library resources on {question}"},
375
- {"label": "Contact a librarian", "question": "Contact a librarian"},
376
- ],
377
- )
378
-
379
-
380
- def _social_follow_up() -> Tuple[str, List[dict]]:
381
- return (
382
- "What would you like help with next?",
383
- [
384
- {"label": "Find articles on a topic", "question": "Find articles on a topic"},
385
- {"label": "Check a library service", "question": "Check a library service"},
386
- {"label": "Contact a librarian", "question": "Contact a librarian"},
387
- ],
388
- )
389
-
390
-
 
 
 
 
 
 
 
1
+ """general / social intents: web-search answers, general LLM answers, casual persona replies."""
2
+ import asyncio
3
+ import html
4
+ import json
5
+ import logging
6
+ import os
7
+ import re
8
+ import time
9
+ import uuid
10
+ from datetime import datetime
11
+ from typing import Any, Dict, List, Literal, Optional, Tuple
12
+ from urllib.parse import quote, urlsplit
13
+
14
+ import httpx
15
+ from pydantic import BaseModel, ConfigDict, Field
16
+
17
+ from src.config import get_settings, LIBBEE_VERSION
18
+
19
+ from src.agentcore.models import ChatMessage
20
+ from src.agentcore.constants import (
21
+ ASK_LIBRARIAN_URL, KU_MAIN_URL, KU_WEB_DOMAINS, _GUARDRAIL, _URL_INSTRUCTION,
22
+ )
23
+ from src.agentcore.utils import (
24
+ DEFAULT_OPENAI_WEB_MODEL,
25
+ _build_history_messages,
26
+ _claude_model,
27
+ _get_llm,
28
+ _get_runtime_config,
29
+ )
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ async def _libbee_casual_response(question: str, history: List[ChatMessage], model: str, hint: str = "") -> str:
34
+ """LLM #1 — casual social response. v3.8.1: appends _GUARDRAIL + _URL_INSTRUCTION."""
35
+ if hint and len(hint.strip()) > 20:
36
+ return hint.strip()
37
+ settings = get_settings()
38
+ if not settings.openai_api_key and not settings.anthropic_api_key:
39
+ return "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant — always happy to help!"
40
+ try:
41
+ llm = _get_llm(model, temperature=0.6, max_tokens=160, task="casual")
42
+ msgs = [{"role": "system", "content": (
43
+ "You are LibBee, the Khalifa University Library AI Assistant. "
44
+ "Respond warmly and naturally in 1-3 sentences as a friendly librarian. "
45
+ "No markdown, no bullet points. "
46
+ + _GUARDRAIL + "\n\n" + _URL_INSTRUCTION
47
+ )}]
48
+ _cfg = _get_runtime_config()
49
+ _ci = _cfg.get("custom_instructions", "").strip()
50
+ if _ci:
51
+ msgs[0]["content"] += " " + _ci
52
+ msgs.extend(_build_history_messages(history))
53
+ msgs.append({"role": "user", "content": question})
54
+ response = await llm.ainvoke(msgs)
55
+ return response.content.strip()
56
+ except Exception:
57
+ return "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant — always happy to help!"
58
+
59
+
60
+ async def _llm_general_answer(question: str, history: List[ChatMessage], model: str) -> str:
61
+ """LLM #3 — general factual answer. v3.8.1: appends _GUARDRAIL + _URL_INSTRUCTION."""
62
+ settings = get_settings()
63
+ if not settings.openai_api_key and not settings.anthropic_api_key:
64
+ return (
65
+ "I'm <strong>LibBee</strong>, the KU Library AI Assistant. "
66
+ f'For general university information, visit <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a>.'
67
+ )
68
+ system = (
69
+ "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
70
+ "Answer factually and concisely in 3-5 sentences. Use HTML <br> for line breaks. "
71
+ "KU means Khalifa University. If the topic is academic, briefly offer to help find library resources. "
72
+ "When referencing KU Library services, include these verified links where relevant: "
73
+ "Library homepage: https://library.ku.ac.ae | "
74
+ "Ask a Librarian: https://library.ku.ac.ae/AskUs | "
75
+ "Library hours: https://library.ku.ac.ae/hours | "
76
+ "ILL requests: https://library.ku.ac.ae/ill/ | "
77
+ "Study rooms: https://library.ku.ac.ae/rooms/ | "
78
+ "E-resources: https://library.ku.ac.ae/eresources | "
79
+ "Khazna repository: https://khazna.ku.ac.ae | "
80
+ "PRIMO discovery: https://khalifa.primo.exlibrisgroup.com/discovery/search?vid=971KUOSTAR_INST:KU. "
81
+ "Only use these exact URLs — never invent others. "
82
+ + _GUARDRAIL + "\n\n" + _URL_INSTRUCTION
83
+ )
84
+ _cfg = _get_runtime_config()
85
+ _ci = _cfg.get("custom_instructions", "").strip()
86
+ if _ci:
87
+ system += " " + _ci
88
+ try:
89
+ llm = _get_llm(model, temperature=0.3, max_tokens=360, task="answer")
90
+ msgs = [{"role": "system", "content": system}]
91
+ msgs.extend(_build_history_messages(history))
92
+ msgs.append({"role": "user", "content": question})
93
+ response = await llm.ainvoke(msgs)
94
+ return response.content.strip()
95
+ except Exception as e:
96
+ logger.error(f"_llm_general_answer error: {e}")
97
+ return f'Having trouble right now. Visit <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a>.'
98
+
99
+
100
+ def _response_field(value: Any, name: str, default: Any = None) -> Any:
101
+ """Read SDK objects and dictionaries without depending on a provider SDK."""
102
+ return value.get(name, default) if isinstance(value, dict) else getattr(value, name, default)
103
+
104
+
105
+ def _citation_source(citation: Any) -> Optional[dict]:
106
+ url = str(_response_field(citation, "url", "") or "").strip()
107
+ try:
108
+ parsed = urlsplit(url)
109
+ if (parsed.scheme not in ("http", "https") or not parsed.hostname
110
+ or parsed.username or parsed.password or any(ord(c) < 32 for c in url)):
111
+ return None
112
+ except ValueError:
113
+ return None
114
+ return {"title": str(_response_field(citation, "title", "") or parsed.hostname),
115
+ "url": url, "source": "web_search"}
116
+
117
+
118
+ def _host_allowed(url: str, domains) -> bool:
119
+ """True when the URL's host is one of the domains or a subdomain of one."""
120
+ try:
121
+ host = (urlsplit(url).hostname or "").lower()
122
+ except ValueError:
123
+ return False
124
+ return any(host == d or host.endswith("." + d) for d in domains)
125
+
126
+
127
+ def _render_web_text(block: Any, sources: List[dict], anthropic: bool = False, domains=None) -> str:
128
+ """Escape provider prose and attach real, clickable citations at their source span.
129
+
130
+ With ``domains`` set, citations to any other site are dropped in code, so a
131
+ scoped answer can never link outside the allowed sites.
132
+ """
133
+ raw = str(_response_field(block, "text", "") or "")
134
+ if not raw:
135
+ return ""
136
+ citations = _response_field(block, "citations" if anthropic else "annotations", []) or []
137
+ insertions: Dict[int, List[str]] = {}
138
+ for citation in citations:
139
+ kind = _response_field(citation, "type", "")
140
+ if kind != ("web_search_result_location" if anthropic else "url_citation"):
141
+ continue
142
+ source = _citation_source(citation)
143
+ if not source:
144
+ continue
145
+ if domains and not _host_allowed(source["url"], domains):
146
+ continue
147
+ existing = next((i for i, item in enumerate(sources) if item["url"] == source["url"]), None)
148
+ if existing is None:
149
+ sources.append(source)
150
+ existing = len(sources) - 1
151
+ position = len(raw) if anthropic else _response_field(citation, "end_index", len(raw))
152
+ if not isinstance(position, int) or not 0 <= position <= len(raw):
153
+ position = len(raw)
154
+ link = (f' <a href="{html.escape(source["url"], quote=True)}" target="_blank" '
155
+ f'rel="noopener noreferrer" title="{html.escape(source["title"], quote=True)}">'
156
+ f'[{existing + 1}]</a>')
157
+ if link not in insertions.setdefault(position, []):
158
+ insertions[position].append(link)
159
+
160
+ def escaped(segment: str) -> str:
161
+ # SDK citation tokens have no meaning to a browser; links above replace them.
162
+ segment = re.sub(r"\ue200cite[^\ue201]*\ue201", "", segment)
163
+ return html.escape(segment).replace("\n", "<br>")
164
+
165
+ answer, previous = [], 0
166
+ for position in sorted(insertions):
167
+ answer.append(escaped(raw[previous:position]))
168
+ answer.extend(insertions[position])
169
+ previous = position
170
+ answer.append(escaped(raw[previous:]))
171
+ return "".join(answer)
172
+
173
+
174
+ def _parse_web_response(response: Any, provider: str, domains=None) -> dict:
175
+ """Only label an answer live when a search completed and returned cited sources."""
176
+ sources: List[dict] = []
177
+ parts: List[str] = []
178
+ searched = False
179
+ if provider == "claude":
180
+ for block in _response_field(response, "content", []) or []:
181
+ kind = _response_field(block, "type", "")
182
+ if kind == "web_search_tool_result":
183
+ # API search errors are objects inside a successful HTTP response.
184
+ result = _response_field(block, "content")
185
+ searched = searched or isinstance(result, list)
186
+ elif kind == "text":
187
+ parts.append(_render_web_text(block, sources, anthropic=True, domains=domains))
188
+ finished = _response_field(response, "stop_reason", "end_turn") == "end_turn"
189
+ else:
190
+ for item in _response_field(response, "output", []) or []:
191
+ if (_response_field(item, "type", "") == "web_search_call"
192
+ and _response_field(item, "status", "") == "completed"):
193
+ searched = True
194
+ for block in _response_field(item, "content", []) or []:
195
+ if _response_field(block, "type", "") == "output_text":
196
+ parts.append(_render_web_text(block, sources, domains=domains))
197
+ finished = _response_field(response, "status", "completed") == "completed"
198
+ live = searched and finished and bool(sources)
199
+ return {"answer": "".join(parts).strip(), "sources": sources,
200
+ "tools_used": ["web_search"] if searched else [],
201
+ "live_search": live, "model_used": provider}
202
+
203
+
204
+ _COURTESY_NOTE = (
205
+ '<p class="lb-courtesy">This is outside the library\'s services, '
206
+ "so I looked it up on the web as a courtesy.</p>"
207
+ )
208
+ _KU_CHECK_NOTE = (
209
+ '<p class="lb-muted">Fees, dates and requirements change. '
210
+ "Please confirm the details on the linked page.</p>"
211
+ )
212
+ # Known-good configuration used when the routed web model is unavailable.
213
+ _LEGACY_WEB_MODEL = "gpt-4.1-mini"
214
+
215
+
216
+ def _ku_not_found() -> dict:
217
+ """University facts are never answered from model memory."""
218
+ return {
219
+ "answer": (
220
+ "I searched Khalifa University's web pages but could not find a reliable answer to that. "
221
+ f'Please check <a href="{KU_MAIN_URL}" target="_blank">ku.ac.ae</a> directly, or '
222
+ f'<a href="{ASK_LIBRARIAN_URL}" target="_blank">ask a librarian</a> and we will point you '
223
+ "to the right office."
224
+ ),
225
+ "sources": [], "tools_used": ["ku_web_search"], "live_search": False,
226
+ "model_used": "gpt", "scope": "ku",
227
+ }
228
+
229
+
230
+ def _web_system_prompt(scope: str) -> str:
231
+ base = "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
232
+ if scope == "ku":
233
+ return (
234
+ base
235
+ + "The user is asking about Khalifa University. Search and answer ONLY from pages on "
236
+ "ku.ac.ae (including khazna.ku.ac.ae). Give figures, dates, names and requirements exactly "
237
+ "as the page states them. If the pages you find do not answer the question, say that you "
238
+ "could not find it on the university's website; do not answer from prior knowledge. "
239
+ "Be concise and factual. Use plain text with paragraph breaks, no HTML or Markdown. "
240
+ "Cite every factual claim with the search tool's citations; never invent sources or URLs. "
241
+ "The application renders citation links, so do not write links yourself. "
242
+ + _GUARDRAIL
243
+ )
244
+ return (
245
+ base
246
+ + "Search the web and answer using current sources. Be concise and factual. "
247
+ "Use plain text with paragraph breaks, no HTML or Markdown. "
248
+ "Cite factual claims using the search tool's citations; never invent sources or URLs. "
249
+ "The application renders citation links, so do not write HTML links yourself. "
250
+ + _GUARDRAIL
251
+ )
252
+
253
+
254
+ async def _openai_web_attempt(client: Any, model_name: str, legacy: bool, system: str,
255
+ messages: List[dict], domains) -> Any:
256
+ """One Responses API call. ``legacy`` uses the preview tool, which has no domain filter."""
257
+ if legacy:
258
+ tools: List[dict] = [{"type": "web_search_preview"}]
259
+ tool_choice: Any = {"type": "web_search_preview"}
260
+ else:
261
+ tool: Dict[str, Any] = {"type": "web_search"}
262
+ if domains:
263
+ tool["filters"] = {"allowed_domains": list(domains)}
264
+ tools, tool_choice = [tool], "required"
265
+ kwargs: Dict[str, Any] = dict(
266
+ model=model_name, tools=tools, tool_choice=tool_choice, instructions=system,
267
+ input=messages, max_output_tokens=620, store=False,
268
+ )
269
+ if re.match(r"(?:gpt-[5-9]|o\d)", model_name):
270
+ # Reasoning tokens are billed against max_output_tokens.
271
+ kwargs["reasoning"] = {"effort": os.getenv("LIBBEE_WEB_REASONING_EFFORT", "low")}
272
+ kwargs["max_output_tokens"] = 1600
273
+ return await asyncio.wait_for(client.responses.create(**kwargs), timeout=18.0)
274
+
275
+
276
+ async def _web_search_result(question: str, history: List[ChatMessage], model: str,
277
+ scope: str = "open", courtesy: bool = False) -> dict:
278
+ """Return source evidence alongside text, with bounded calls and honest fallback metadata.
279
+
280
+ scope="ku" restricts the search and every citation to Khalifa University sites and
281
+ never falls back to model memory. ``courtesy`` prefixes a short note for everyday
282
+ questions that are outside the library's services.
283
+ """
284
+ settings = get_settings()
285
+ ku = scope == "ku"
286
+ domains = tuple(KU_WEB_DOMAINS) if ku else None
287
+ system = _web_system_prompt(scope) if (ku or settings.openai_api_key or settings.anthropic_api_key) else ""
288
+ messages = _build_history_messages(history)
289
+ messages.append({"role": "user", "content": question})
290
+
291
+ def finish(result: dict) -> dict:
292
+ result["scope"] = scope
293
+ if ku:
294
+ result["tools_used"] = ["ku_web_search"]
295
+ result["answer"] += _KU_CHECK_NOTE
296
+ elif courtesy:
297
+ result["answer"] = _COURTESY_NOTE + result["answer"]
298
+ return result
299
+
300
+ if settings.anthropic_api_key and (model == "claude" or not settings.openai_api_key):
301
+ try:
302
+ import anthropic
303
+ tool: Dict[str, Any] = {"type": "web_search_20250305", "name": "web_search", "max_uses": 2}
304
+ if domains:
305
+ tool["allowed_domains"] = list(domains)
306
+ async with anthropic.AsyncAnthropic(
307
+ api_key=settings.anthropic_api_key, timeout=16.0, max_retries=0
308
+ ) as client:
309
+ response = await asyncio.wait_for(client.messages.create(
310
+ model=os.getenv("ANTHROPIC_WEB_MODEL", "").strip() or _claude_model(),
311
+ max_tokens=620,
312
+ system=system,
313
+ tools=[tool],
314
+ messages=messages,
315
+ ), timeout=18.0)
316
+ result = _parse_web_response(response, "claude", domains)
317
+ if result["answer"] and result["live_search"]:
318
+ return finish(result)
319
+ logger.info("Claude web response had no complete cited search answer")
320
+ except Exception as exc:
321
+ logger.warning("Claude web search failed (%s)", type(exc).__name__)
322
+ if settings.openai_api_key:
323
+ primary = os.getenv("OPENAI_WEB_MODEL", DEFAULT_OPENAI_WEB_MODEL).strip() or _LEGACY_WEB_MODEL
324
+ attempts = [(primary, False)]
325
+ if primary != _LEGACY_WEB_MODEL:
326
+ attempts.append((_LEGACY_WEB_MODEL, True))
327
+ try:
328
+ from openai import AsyncOpenAI
329
+ async with AsyncOpenAI(
330
+ api_key=settings.openai_api_key, timeout=16.0, max_retries=0
331
+ ) as client:
332
+ for model_name, legacy in attempts:
333
+ try:
334
+ response = await _openai_web_attempt(
335
+ client, model_name, legacy, system, messages, domains)
336
+ except Exception as exc:
337
+ logger.warning("GPT web search failed on %s (%s)", model_name, type(exc).__name__)
338
+ continue
339
+ result = _parse_web_response(response, "gpt", domains)
340
+ if result["answer"] and result["live_search"]:
341
+ return finish(result)
342
+ logger.info("GPT web response had no complete cited search answer")
343
+ break
344
+ except Exception as exc:
345
+ logger.warning("GPT web search failed (%s)", type(exc).__name__)
346
+ if ku:
347
+ return _ku_not_found()
348
+ fallback = await _llm_general_answer(question, history, model)
349
+ provider = "claude" if settings.anthropic_api_key and (model == "claude" or not settings.openai_api_key) else "gpt"
350
+ answer = "<em>I couldn’t verify current web information. The following is general guidance and may be out of date.</em><br><br>" + fallback
351
+ if courtesy:
352
+ answer = _COURTESY_NOTE + answer
353
+ return {
354
+ "answer": answer,
355
+ "sources": [], "tools_used": ["general_knowledge"], "live_search": False,
356
+ "model_used": provider, "scope": scope,
357
+ }
358
+
359
+
360
+ async def _web_search_answer(question: str, history: List[ChatMessage], model: str) -> str:
361
+ """Compatibility wrapper; orchestration uses _web_search_result for source metadata."""
362
+ return (await _web_search_result(question, history, model))["answer"]
363
+
364
+
365
+ def _general_follow_up(question: str) -> Tuple[str, List[dict]]:
366
+ return (
367
+ "Would you like a brief explanation, current web information, or KU Library resources on this topic?",
368
+ [
369
+ {"label": "Shorter explanation", "question": f"Give me a shorter explanation of {question}"},
370
+ {"label": "Current web information", "question": f"Show current web information on {question}"},
371
+ {"label": "Find KU Library resources", "question": f"Find KU Library resources on {question}"},
372
+ ],
373
+ )
374
+
375
+
376
+ def _ku_follow_up(question: str) -> Tuple[str, List[dict]]:
377
+ return (
378
+ "",
379
+ [
380
+ {"label": "Find library resources on this", "question": f"Find KU Library resources on {question}"},
381
+ {"label": "Contact a librarian", "question": "Contact a librarian"},
382
+ ],
383
+ )
384
+
385
+
386
+ def _social_follow_up() -> Tuple[str, List[dict]]:
387
+ return (
388
+ "What would you like help with next?",
389
+ [
390
+ {"label": "Find articles on a topic", "question": "Find articles on a topic"},
391
+ {"label": "Check a library service", "question": "Check a library service"},
392
+ {"label": "Contact a librarian", "question": "Contact a librarian"},
393
+ ],
394
+ )
395
+
396
+
src/agentcore/intents_search.py CHANGED
@@ -18,7 +18,7 @@ from src.config import get_settings, LIBBEE_VERSION
18
 
19
  from src.agentcore.models import ClientStatePayload, SearchContextPayload
20
  from src.agentcore.scholarly import fetch_evidence_panel
21
- from src.agentcore.primo_chat import fetch_primo_panel
22
  from src.agentcore.constants import (
23
  ALT_TERMS_RE,
24
  CURRENT_YEAR,
@@ -511,7 +511,6 @@ def _database_guidance_for_topic(context: SearchContextPayload) -> str:
511
  ai_tools = (
512
  f'<a href="{urls["leapspace"]}" target="_blank" style="color:#9a3412;font-weight:700;text-decoration:none">LeapSpace</a> · '
513
  f'<a href="{urls["scopus_ai"]}" target="_blank" style="color:#1e40af;font-weight:700;text-decoration:none">Scopus AI</a> · '
514
- f'<a href="{urls["ebsco_ai"]}" target="_blank" style="color:#9d174d;font-weight:700;text-decoration:none">EBSCO AI</a> · '
515
  f'<a href="{urls["primo_ai"]}" target="_blank" style="color:#5b21b6;font-weight:700;text-decoration:none">PRIMO AI Assistant</a> · '
516
  f'<a href="{urls["consensus"]}" target="_blank" style="color:#86198f;font-weight:700;text-decoration:none">Consensus</a>'
517
  )
@@ -667,7 +666,6 @@ async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple
667
  if context.clarification_needed:
668
  return context.clarification_message or "Please describe the research topic.", [], []
669
  topic = context.topic
670
- source_name = "PRIMO" if context.source == "primo" else "PubMed"
671
  # Records first: a broadened PRIMO retry replaces the query used by the link.
672
  if context.source == "primo":
673
  papers, panel_html = await fetch_primo_panel(context, topic)
@@ -683,10 +681,11 @@ async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple
683
  "Click any platform below to search instantly, or use the boolean search tip "
684
  "to search directly in any KU database."
685
  )
686
- if context.source == "primo":
687
- answer += f'<br><br><strong>PRIMO query:</strong><br><code>{_escape(context.primo_boolean_query or "")}</code>'
688
- answer += (f'<br><br><a href="{_escape(source_url)}" target="_blank" rel="noopener noreferrer" '
689
- f'style="color:#003366;font-weight:700">Search {source_name} for: {_escape(topic)} →</a>')
 
690
 
691
  # Catalogue hits use the same prepared query as the link immediately above.
692
  answer += panel_html
@@ -963,6 +962,106 @@ def _search_answer_intro(context: SearchContextPayload, is_follow_up: bool) -> s
963
  return action
964
 
965
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
966
  async def _topic_explanation(question: str, topic: str, model: str) -> str:
967
  """Explain-mode answer: a short, direct explanation before the search link."""
968
  settings = get_settings()
@@ -991,8 +1090,9 @@ async def _topic_explanation(question: str, topic: str, model: str) -> str:
991
  async def _run_search_mode(
992
  question: str, context: SearchContextPayload, model: str, is_follow_up: bool,
993
  explain: bool = False,
994
- ) -> Tuple[str, List[dict], List[dict], str]:
995
- """Prepared query, matching source link, and bounded genuine catalogue hits.
 
996
 
997
  explain=True leads with a short explanation of the topic (the patron asked
998
  to understand it); otherwise a three-sentence introduction precedes the search.
@@ -1001,11 +1101,9 @@ async def _run_search_mode(
1001
 
1002
  # Clarification gate
1003
  if context.clarification_needed and context.clarification_message:
1004
- return context.clarification_message, [], [], ""
1005
 
1006
- source_name = "PubMed" if context.source == "pubmed" else "PRIMO Library Discovery"
1007
  topic_text = context.display_topic or context.topic
1008
- topic = _escape(topic_text)
1009
 
1010
  async def optional_intro():
1011
  if explain:
@@ -1030,20 +1128,22 @@ async def _run_search_mode(
1030
  if intro:
1031
  answer += f'<div class="lb-intro" style="margin-bottom:12px;color:#374151;font-size:.88rem;line-height:1.7">{intro}</div>'
1032
  answer += _search_answer_intro(context, is_follow_up)
1033
- if context.source == "primo":
1034
- answer += f'<br><br><strong>PRIMO query:</strong><br><code>{_escape(context.primo_boolean_query or "")}</code>'
1035
- answer += (
1036
- f'<br><br>'
1037
- f'<a class="lb-cta" href="{_escape(source_url)}" target="_blank" rel="noopener noreferrer" '
1038
- f'style="display:inline-block;padding:9px 18px;background:#003366;color:#fff;'
1039
- f'border-radius:8px;font-weight:700;text-decoration:none;font-size:.88rem">'
1040
- f'🔍 Search {source_name} for: {topic} →</a>'
1041
  )
1042
- if context.source == "primo" and _asks_for_books(question):
1043
- answer += f'<p class="lb-tip">{BOOKS_FILTER_TIP}</p>'
1044
  # Keep this block adjacent to the primary search link: no tools, article
1045
  # recommendations or filter guidance inserted between link and records.
1046
  answer += panel_html
 
 
 
 
 
 
 
1047
  if context.source == "pubmed":
1048
  answer += '<p>Inside PubMed you can filter by publication date, article type, and free full text.</p>'
1049
  if context.peer_reviewed:
@@ -1055,7 +1155,7 @@ async def _run_search_mode(
1055
  "doi": paper.get("doi", ""), "provider": paper.get("_source", "")}
1056
  for paper in papers
1057
  ]
1058
- return answer, papers, sources, source_url
1059
 
1060
 
1061
  def _sort_and_trim_contexts(contexts: List[SearchContextPayload]) -> List[SearchContextPayload]:
 
18
 
19
  from src.agentcore.models import ClientStatePayload, SearchContextPayload
20
  from src.agentcore.scholarly import fetch_evidence_panel
21
+ from src.agentcore.primo_chat import fetch_primo_panel, primo_panel_is_empty
22
  from src.agentcore.constants import (
23
  ALT_TERMS_RE,
24
  CURRENT_YEAR,
 
511
  ai_tools = (
512
  f'<a href="{urls["leapspace"]}" target="_blank" style="color:#9a3412;font-weight:700;text-decoration:none">LeapSpace</a> · '
513
  f'<a href="{urls["scopus_ai"]}" target="_blank" style="color:#1e40af;font-weight:700;text-decoration:none">Scopus AI</a> · '
 
514
  f'<a href="{urls["primo_ai"]}" target="_blank" style="color:#5b21b6;font-weight:700;text-decoration:none">PRIMO AI Assistant</a> · '
515
  f'<a href="{urls["consensus"]}" target="_blank" style="color:#86198f;font-weight:700;text-decoration:none">Consensus</a>'
516
  )
 
666
  if context.clarification_needed:
667
  return context.clarification_message or "Please describe the research topic.", [], []
668
  topic = context.topic
 
669
  # Records first: a broadened PRIMO retry replaces the query used by the link.
670
  if context.source == "primo":
671
  papers, panel_html = await fetch_primo_panel(context, topic)
 
681
  "Click any platform below to search instantly, or use the boolean search tip "
682
  "to search directly in any KU database."
683
  )
684
+ answer += _catalogue_cta(
685
+ context.source, source_url,
686
+ query=(context.primo_boolean_query or "") if context.source == "primo" else "",
687
+ **_ebsco_args(context),
688
+ )
689
 
690
  # Catalogue hits use the same prepared query as the link immediately above.
691
  answer += panel_html
 
962
  return action
963
 
964
 
965
+ CTA_LEAD = {
966
+ "primo": "Your search is ready. Click here to see all the results in the KU Library catalogue (PRIMO).",
967
+ "pubmed": "Your search is ready. Click here to see all the results in PubMed.",
968
+ }
969
+ CTA_LEAD_WITH_EBSCO = {
970
+ "primo": ("Your search is ready. Click a button below to see all the results in the "
971
+ "KU Library catalogue (PRIMO) or in EBSCO Discovery."),
972
+ "pubmed": "Your search is ready. Click a button below to see all the results in PubMed or in EBSCO Discovery.",
973
+ }
974
+ CTA_BUTTON = {"primo": "Open my results in PRIMO", "pubmed": "Open my results in PubMed"}
975
+ EBSCO_BUTTON = "Open my results in EBSCO Discovery"
976
+
977
+
978
+ def _catalogue_cta(source: str, url: str, query: str = "", books_tip: bool = False,
979
+ ebsco_url: str = "", ebsco_query: str = "") -> str:
980
+ """The catalogue call to action.
981
+
982
+ A "click here" line, then the catalogue button (and the EBSCO Discovery
983
+ button beside it), each with its own drawn down arrow, then the queries
984
+ actually used. The LibGuides page styles these classes.
985
+ """
986
+ source = "pubmed" if source == "pubmed" else "primo"
987
+ href = _escape(url)
988
+ link = f'href="{href}" target="_blank" rel="noopener noreferrer"'
989
+ lead = CTA_LEAD_WITH_EBSCO[source] if ebsco_url else CTA_LEAD[source]
990
+ html_out = (
991
+ '<div class="lb-cta-block">'
992
+ f'<p class="lb-cta-lead"><a class="lb-cta-lead-link" {link}>{lead}</a></p>'
993
+ )
994
+ main_button = f'<a class="lb-cta lb-cta--primary" {link}>{CTA_BUTTON[source]}</a>'
995
+ if ebsco_url:
996
+ ebsco_link = f'href="{_escape(ebsco_url)}" target="_blank" rel="noopener noreferrer"'
997
+ html_out += (
998
+ '<div class="lb-cta-row">'
999
+ f'<div class="lb-cta-col"><span class="lb-cta-arrow"></span>{main_button}</div>'
1000
+ '<div class="lb-cta-col"><span class="lb-cta-arrow"></span>'
1001
+ f'<a class="lb-cta lb-cta--primary lb-cta--ebsco" {ebsco_link}>{EBSCO_BUTTON}</a></div>'
1002
+ '</div>'
1003
+ )
1004
+ else:
1005
+ html_out += '<span class="lb-cta-arrow"></span>' + main_button
1006
+ label = "PRIMO search" if ebsco_url else "Search used"
1007
+ if query:
1008
+ html_out += f'<p class="lb-query-line">{label}: <code>{_escape(query)}</code></p>'
1009
+ if ebsco_url and ebsco_query:
1010
+ html_out += f'<p class="lb-query-line">EBSCO search: <code>{_escape(ebsco_query)}</code></p>'
1011
+ if books_tip:
1012
+ html_out += f'<p class="lb-tip">{BOOKS_FILTER_TIP}</p>'
1013
+ return html_out + "</div>"
1014
+
1015
+
1016
+ def _ebsco_args(context: SearchContextPayload) -> dict:
1017
+ """EBSCO Discovery button arguments: the full natural-language question."""
1018
+ return {
1019
+ "ebsco_url": _tool_urls(context).get("ebsco_discovery", ""),
1020
+ "ebsco_query": context.ai_tool_query or context.display_topic or context.topic or "",
1021
+ }
1022
+
1023
+
1024
+ async def _alternative_search_queries(topic: str, boolean: str, model: str) -> List[str]:
1025
+ """Three broader or differently worded searches, offered when PRIMO found nothing."""
1026
+ settings = get_settings()
1027
+ if not settings.openai_api_key and not settings.anthropic_api_key:
1028
+ return []
1029
+ try:
1030
+ llm = _get_llm(model, temperature=0.3, max_tokens=120, task="extract")
1031
+ response = await asyncio.wait_for(llm.ainvoke([
1032
+ {"role": "system", "content": (
1033
+ "A library catalogue search returned no results. Suggest exactly 3 alternative "
1034
+ "searches likely to find scholarly material on the same subject: a broader term, "
1035
+ "a synonym or the standard technical term, and a related narrower angle. "
1036
+ "Each is a plain topic of 2 to 5 words with no quotes, no Boolean operators and no years. "
1037
+ 'Return only JSON: {"queries": ["...", "...", "..."]}'
1038
+ )},
1039
+ {"role": "user", "content": f"Topic: {topic}\nQuery that found nothing: {boolean}"},
1040
+ ]), timeout=5.0)
1041
+ raw = (response.content or "").strip()
1042
+ start, end = raw.find("{"), raw.rfind("}")
1043
+ data = json.loads(raw[start:end + 1]) if start != -1 and end > start else {}
1044
+ seen, queries = {(topic or "").strip().lower()}, []
1045
+ for value in data.get("queries", []) if isinstance(data, dict) else []:
1046
+ value = re.sub(r'["()]|\b(?:AND|OR|NOT)\b', " ", str(value))
1047
+ value = _normalize_whitespace(value)[:60]
1048
+ if 2 <= len(value) and value.lower() not in seen:
1049
+ seen.add(value.lower())
1050
+ queries.append(value)
1051
+ return queries[:3]
1052
+ except Exception as e:
1053
+ logger.warning(f"_alternative_search_queries failed: {type(e).__name__}")
1054
+ return []
1055
+
1056
+
1057
+ def alternative_search_suggestions(queries: List[str], context: SearchContextPayload) -> List[dict]:
1058
+ """Buttons that run each alternative as a fresh search (no clarifying question)."""
1059
+ material = "articles and books" if context.resource_type == "both" else (
1060
+ "books" if context.resource_type == "books" else "articles")
1061
+ return [{"label": f"Try: {q}", "question": f"Find {material} on {q}", "action": "mode_find"}
1062
+ for q in queries]
1063
+
1064
+
1065
  async def _topic_explanation(question: str, topic: str, model: str) -> str:
1066
  """Explain-mode answer: a short, direct explanation before the search link."""
1067
  settings = get_settings()
 
1090
  async def _run_search_mode(
1091
  question: str, context: SearchContextPayload, model: str, is_follow_up: bool,
1092
  explain: bool = False,
1093
+ ) -> Tuple[str, List[dict], List[dict], str, List[dict]]:
1094
+ """Prepared query, matching source link, bounded genuine catalogue hits, and
1095
+ alternative-search buttons when PRIMO found nothing.
1096
 
1097
  explain=True leads with a short explanation of the topic (the patron asked
1098
  to understand it); otherwise a three-sentence introduction precedes the search.
 
1101
 
1102
  # Clarification gate
1103
  if context.clarification_needed and context.clarification_message:
1104
+ return context.clarification_message, [], [], "", []
1105
 
 
1106
  topic_text = context.display_topic or context.topic
 
1107
 
1108
  async def optional_intro():
1109
  if explain:
 
1128
  if intro:
1129
  answer += f'<div class="lb-intro" style="margin-bottom:12px;color:#374151;font-size:.88rem;line-height:1.7">{intro}</div>'
1130
  answer += _search_answer_intro(context, is_follow_up)
1131
+ answer += _catalogue_cta(
1132
+ context.source, source_url,
1133
+ query=(context.primo_boolean_query or "") if context.source == "primo" else "",
1134
+ books_tip=context.source == "primo" and _asks_for_books(question),
1135
+ **_ebsco_args(context),
 
 
 
1136
  )
 
 
1137
  # Keep this block adjacent to the primary search link: no tools, article
1138
  # recommendations or filter guidance inserted between link and records.
1139
  answer += panel_html
1140
+ alternatives: List[dict] = []
1141
+ if context.source == "primo" and primo_panel_is_empty(panel_html):
1142
+ queries = await _alternative_search_queries(topic_text, context.primo_boolean_query or "", model)
1143
+ alternatives = alternative_search_suggestions(queries, context)
1144
+ if alternatives:
1145
+ from src.agentcore.primo_chat import _count
1146
+ _count("alternative_suggestions")
1147
  if context.source == "pubmed":
1148
  answer += '<p>Inside PubMed you can filter by publication date, article type, and free full text.</p>'
1149
  if context.peer_reviewed:
 
1155
  "doi": paper.get("doi", ""), "provider": paper.get("_source", "")}
1156
  for paper in papers
1157
  ]
1158
+ return answer, papers, sources, source_url, alternatives
1159
 
1160
 
1161
  def _sort_and_trim_contexts(contexts: List[SearchContextPayload]) -> List[SearchContextPayload]:
src/agentcore/models.py CHANGED
@@ -1,83 +1,85 @@
1
- """Strict request and response contracts for the LibBee agent."""
2
-
3
- import time
4
- from typing import Literal, Optional
5
-
6
- from pydantic import BaseModel, ConfigDict, Field, field_validator
7
-
8
-
9
- class ChatMessage(BaseModel):
10
- model_config = ConfigDict(extra="forbid")
11
- role: Literal["user", "assistant"]
12
- content: str = Field(min_length=1, max_length=4000)
13
-
14
-
15
- class SearchContextPayload(BaseModel):
16
- model_config = ConfigDict(extra="ignore")
17
- context_id: str = Field(min_length=1, max_length=80)
18
- topic: str = Field(min_length=1, max_length=500)
19
- display_topic: Optional[str] = Field(default=None, max_length=500)
20
- intent: Literal["search_academic", "search_medical"] = "search_academic"
21
- source: Literal["primo", "pubmed"] = "primo"
22
  resource_type: Literal["articles", "books", "both"] = "articles"
23
  query_field: Literal["any", "title", "creator", "sub"] = "any"
24
  sort: Literal["rank", "date_d", "date_a"] = "rank"
25
- peer_reviewed: bool = False
26
- open_access: bool = False
27
- year_from: Optional[str] = Field(default=None, pattern=r"^\d{4}$")
28
- year_to: Optional[str] = Field(default=None, pattern=r"^\d{4}$")
29
- ai_tool_query: Optional[str] = Field(default=None, max_length=1000)
30
- primo_boolean_query: Optional[str] = Field(default=None, max_length=1500)
31
- created_at: float = Field(default_factory=time.time)
32
- clarification_needed: bool = False
33
- clarification_message: Optional[str] = Field(default=None, max_length=500)
34
-
35
- @field_validator("year_to")
36
- @classmethod
37
- def years_in_order(cls, value: Optional[str], info):
38
- start = info.data.get("year_from")
39
- if value and start and int(value) < int(start):
40
- raise ValueError("year_to must not be earlier than year_from")
41
- return value
42
-
43
-
44
- class ClientStatePayload(BaseModel):
45
- model_config = ConfigDict(extra="ignore")
46
- session_id: Optional[str] = Field(default=None, pattern=r"^[A-Za-z0-9_-]{8,80}$")
47
- active_search_context_id: Optional[str] = Field(default=None, max_length=80)
48
- recent_search_contexts: list[SearchContextPayload] = Field(default_factory=list, max_length=5)
49
- follow_up_action: Optional[str] = Field(default=None, max_length=80)
50
- follow_up_context_id: Optional[str] = Field(default=None, max_length=80)
51
-
52
-
53
- class AgentRequest(BaseModel):
54
- model_config = ConfigDict(extra="forbid")
55
- question: str = Field(min_length=1, max_length=2000)
56
- model: Literal["gpt", "claude"] = "gpt"
57
- history: list[ChatMessage] = Field(default_factory=list, max_length=12)
58
- client_state: Optional[ClientStatePayload] = None
59
-
60
-
61
- class AgentResponse(BaseModel):
62
- model_config = ConfigDict(extra="ignore")
63
- request_id: str = ""
64
- answer: str
65
- intent: str = "general"
66
- tools_used: list[str] = Field(default_factory=list)
67
- search_results: list[dict] = Field(default_factory=list)
68
- sources: list[dict] = Field(default_factory=list)
69
- model_used: str = "gpt"
70
- response_time: float = 0
71
- corrected_query: Optional[str] = None
72
- natural_query: Optional[str] = None
73
- database_query: Optional[str] = None
74
- ask_librarian: Optional[bool] = None
75
- is_follow_up: bool = False
76
- follow_up_question: Optional[str] = None
77
- follow_up_suggestions: list[dict] = Field(default_factory=list)
78
- search_context: Optional[dict] = None
79
- ai_tool_query: Optional[str] = None
80
- primo_boolean_query: Optional[str] = None
81
- primo_search_url: Optional[str] = None
82
- primo_ai_url: Optional[str] = None
83
- pubmed_search_url: Optional[str] = None
 
 
 
1
+ """Strict request and response contracts for the LibBee agent."""
2
+
3
+ import time
4
+ from typing import Literal, Optional
5
+
6
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
7
+
8
+
9
+ class ChatMessage(BaseModel):
10
+ model_config = ConfigDict(extra="forbid")
11
+ role: Literal["user", "assistant"]
12
+ content: str = Field(min_length=1, max_length=4000)
13
+
14
+
15
+ class SearchContextPayload(BaseModel):
16
+ model_config = ConfigDict(extra="ignore")
17
+ context_id: str = Field(min_length=1, max_length=80)
18
+ topic: str = Field(min_length=1, max_length=500)
19
+ display_topic: Optional[str] = Field(default=None, max_length=500)
20
+ intent: Literal["search_academic", "search_medical"] = "search_academic"
21
+ source: Literal["primo", "pubmed"] = "primo"
22
  resource_type: Literal["articles", "books", "both"] = "articles"
23
  query_field: Literal["any", "title", "creator", "sub"] = "any"
24
  sort: Literal["rank", "date_d", "date_a"] = "rank"
25
+ peer_reviewed: bool = False
26
+ open_access: bool = False
27
+ year_from: Optional[str] = Field(default=None, pattern=r"^\d{4}$")
28
+ year_to: Optional[str] = Field(default=None, pattern=r"^\d{4}$")
29
+ ai_tool_query: Optional[str] = Field(default=None, max_length=1000)
30
+ primo_boolean_query: Optional[str] = Field(default=None, max_length=1500)
31
+ created_at: float = Field(default_factory=time.time)
32
+ clarification_needed: bool = False
33
+ clarification_message: Optional[str] = Field(default=None, max_length=500)
34
+
35
+ @field_validator("year_to")
36
+ @classmethod
37
+ def years_in_order(cls, value: Optional[str], info):
38
+ start = info.data.get("year_from")
39
+ if value and start and int(value) < int(start):
40
+ raise ValueError("year_to must not be earlier than year_from")
41
+ return value
42
+
43
+
44
+ class ClientStatePayload(BaseModel):
45
+ model_config = ConfigDict(extra="ignore")
46
+ session_id: Optional[str] = Field(default=None, pattern=r"^[A-Za-z0-9_-]{8,80}$")
47
+ active_search_context_id: Optional[str] = Field(default=None, max_length=80)
48
+ recent_search_contexts: list[SearchContextPayload] = Field(default_factory=list, max_length=5)
49
+ follow_up_action: Optional[str] = Field(default=None, max_length=80)
50
+ follow_up_context_id: Optional[str] = Field(default=None, max_length=80)
51
+
52
+
53
+ class AgentRequest(BaseModel):
54
+ model_config = ConfigDict(extra="forbid")
55
+ question: str = Field(min_length=1, max_length=2000)
56
+ model: Literal["gpt", "claude"] = "gpt"
57
+ history: list[ChatMessage] = Field(default_factory=list, max_length=12)
58
+ client_state: Optional[ClientStatePayload] = None
59
+
60
+
61
+ class AgentResponse(BaseModel):
62
+ model_config = ConfigDict(extra="ignore")
63
+ request_id: str = ""
64
+ answer: str
65
+ intent: str = "general"
66
+ tools_used: list[str] = Field(default_factory=list)
67
+ search_results: list[dict] = Field(default_factory=list)
68
+ sources: list[dict] = Field(default_factory=list)
69
+ model_used: str = "gpt"
70
+ response_time: float = 0
71
+ corrected_query: Optional[str] = None
72
+ natural_query: Optional[str] = None
73
+ database_query: Optional[str] = None
74
+ ask_librarian: Optional[bool] = None
75
+ is_follow_up: bool = False
76
+ follow_up_question: Optional[str] = None
77
+ follow_up_suggestions: list[dict] = Field(default_factory=list)
78
+ search_context: Optional[dict] = None
79
+ ai_tool_query: Optional[str] = None
80
+ primo_boolean_query: Optional[str] = None
81
+ primo_search_url: Optional[str] = None
82
+ primo_ai_url: Optional[str] = None
83
+ pubmed_search_url: Optional[str] = None
84
+ # Service version that produced the answer (also sent as X-LibBee-Version).
85
+ version: str = ""
src/agentcore/orchestrator.py CHANGED
@@ -7,12 +7,10 @@ import os
7
  import re
8
  import time
9
  import uuid
10
- from collections import deque
11
  from datetime import datetime
12
  from typing import Any, Dict, List, Literal, Optional, Tuple
13
  from urllib.parse import quote
14
 
15
- import httpx
16
  from pydantic import BaseModel, ConfigDict, Field
17
 
18
  from src.config import get_settings, LIBBEE_VERSION
@@ -162,125 +160,6 @@ def _answer_excerpt(answer_html: str, max_len: int = 800) -> str:
162
  return _redact_for_analytics(text, max_len)
163
 
164
 
165
- # ── Analytics retry buffer ───────────────────────────────────────────────────
166
- # Transient failures reaching the Worker (rate limiting, connection resets)
167
- # previously meant the row was lost for good. Failed payloads are parked here
168
- # and re-attempted on subsequent queries, so a blocked window costs a delay
169
- # rather than data. Bounded so a long outage cannot grow memory without limit.
170
-
171
- _PENDING_LOGS: "deque" = deque(maxlen=200)
172
- _PENDING_DROPPED = {"count": 0}
173
-
174
- # Rolling record of the last few analytics-write attempts, so the outcome can be
175
- # inspected through /admin/log-status without access to container logs.
176
- _LOG_ATTEMPTS: "deque" = deque(maxlen=15)
177
-
178
-
179
- def _record_attempt(outcome: str, detail: str = "") -> None:
180
- _LOG_ATTEMPTS.append({
181
- "at": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
182
- "outcome": outcome,
183
- "detail": detail[:200],
184
- })
185
-
186
-
187
- def analytics_log_status() -> dict:
188
- """Snapshot of the analytics write path for the admin dashboard."""
189
- return {
190
- "pending_buffered": len(_PENDING_LOGS),
191
- "buffer_capacity": _PENDING_LOGS.maxlen,
192
- "recent_attempts": list(_LOG_ATTEMPTS)[::-1],
193
- }
194
-
195
-
196
- async def _send_with_retry(worker_url: str, token: str, payload: dict,
197
- attempts: int = 2, backoff: float = 2.0):
198
- """_send_log_payload with one retry after a short backoff. Connectivity to
199
- workers.dev from this host drops for short windows; a single immediate
200
- retry recovers a meaningful fraction of those without involving the buffer."""
201
- last_exc = None
202
- for i in range(attempts):
203
- try:
204
- return await _send_log_payload(worker_url, token, payload)
205
- except Exception as exc:
206
- last_exc = exc
207
- if i + 1 < attempts:
208
- await asyncio.sleep(backoff)
209
- raise last_exc
210
-
211
-
212
- async def _send_log_payload(worker_url: str, token: str, payload: dict):
213
- """POST one analytics payload.
214
-
215
- Returns (status_code, report) where report is the Worker's own JSON verdict.
216
- This matters because the Worker answers HTTP 200 even when the D1 INSERT
217
- itself failed, reporting the problem in a 'warning' field - so a status code
218
- alone cannot distinguish a stored row from a dropped one.
219
- """
220
- from src.services.http_client import make_client as _mk
221
- headers = {"Authorization": f"Bearer {token}"} if token else {}
222
- async with _mk(timeout=10) as client:
223
- resp = await client.post(worker_url.rstrip("/") + "/log",
224
- json=payload, headers=headers)
225
- report = {}
226
- try:
227
- body = resp.json()
228
- if isinstance(body, dict):
229
- report = {k: body.get(k) for k in ("status", "logged", "schema", "warning")
230
- if body.get(k) is not None}
231
- except Exception:
232
- report = {"raw": resp.text[:120]}
233
- return resp.status_code, report
234
-
235
-
236
- _FLUSHER_STARTED = {"on": False}
237
-
238
-
239
- def _ensure_periodic_flusher(worker_url: str, token: str) -> None:
240
- """Start (once) a background loop that retries buffered rows every 90s, so
241
- parked writes land as soon as connectivity returns instead of waiting for
242
- the next user query. The task holds a strong reference via _spawn_background.
243
- Lost on container restart - like the buffer itself - which the keep-alive
244
- pings are there to make rare."""
245
- if _FLUSHER_STARTED["on"]:
246
- return
247
-
248
- async def _loop():
249
- while True:
250
- await asyncio.sleep(90)
251
- if _PENDING_LOGS:
252
- try:
253
- n = await _flush_pending(worker_url, token, max_items=10)
254
- if n:
255
- _record_attempt("flushed", f"{n} buffered row(s) delivered")
256
- except Exception:
257
- pass
258
-
259
- if _spawn_background(_loop()):
260
- _FLUSHER_STARTED["on"] = True
261
- logger.info("Analytics flusher started (90s interval)")
262
-
263
-
264
- async def _flush_pending(worker_url: str, token: str, max_items: int = 5):
265
- """Re-attempt parked payloads oldest-first; stop at the first failure so a
266
- still-blocked Worker is not hammered."""
267
- sent = 0
268
- while _PENDING_LOGS and sent < max_items:
269
- payload = _PENDING_LOGS[0]
270
- try:
271
- status, report = await _send_log_payload(worker_url, token, payload)
272
- except Exception:
273
- return sent
274
- if status >= 400 or report.get("logged") is False:
275
- return sent
276
- _PENDING_LOGS.popleft()
277
- sent += 1
278
- if sent:
279
- logger.info(f"D1 logging: flushed {sent} buffered row(s); "
280
- f"{len(_PENDING_LOGS)} still pending")
281
- return sent
282
-
283
-
284
  def _log_agent_query(question: str, response: AgentResponse, start_time: float) -> None:
285
  """Keep only local operational counters.
286
 
@@ -620,8 +499,12 @@ async def _agent_query_inner(
620
  _run_search_mode(question, context, model, True),
621
  _search_follow_up(context, model),
622
  )
623
- answer, search_results, sources, source_url = search_output
624
  follow_up_question, follow_up_suggestions = follow_up_output
 
 
 
 
625
  if follow_up_action == "review_articles_only":
626
  answer += "<br><br>Use the destination database’s publication-type filter to select review articles. A review article and a peer-reviewed article are different categories."
627
  return AgentResponse(
@@ -758,14 +641,14 @@ async def _agent_query_inner(
758
  original_question = question
759
 
760
  if follow_up == "unsure" and not just_clarified:
761
- _safe_metrics_bucket("clarifications", "follow_up")
762
  return _follow_up_clarification(question, standalone, refers_to, model, start_time)
763
 
764
  assumed_note = ""
765
  if follow_up in ("yes", "unsure") and standalone.strip() and standalone.strip().lower() != question.strip().lower():
766
  # "unsure" reaches here only right after a clarifying question: LibBee
767
  # never asks twice in a row, so it takes the most likely reading.
768
- _safe_metrics_increment("assumed_follow_ups")
769
  assumed_note = _assumed_follow_up_note(refers_to)
770
  question = standalone
771
 
@@ -778,7 +661,7 @@ async def _agent_query_inner(
778
  if just_clarified or clarify_action:
779
  search_mode = "find"
780
  else:
781
- _safe_metrics_bucket("clarifications", "search_mode")
782
  return _search_mode_clarification(question, model, start_time,
783
  cls_result.get("intent"), assumed_note)
784
 
@@ -982,8 +865,12 @@ async def _route_classified(
982
  _run_search_mode(question, context, model, False, explain=search_mode == "explain"),
983
  _search_follow_up(context, model),
984
  )
985
- answer, search_results, sources, source_url = search_output
986
  follow_up_question, follow_up_suggestions = follow_up_output
 
 
 
 
987
  if is_highly_cited:
988
  answer += _highly_cited_note(_escape(topic))
989
  return AgentResponse(
 
7
  import re
8
  import time
9
  import uuid
 
10
  from datetime import datetime
11
  from typing import Any, Dict, List, Literal, Optional, Tuple
12
  from urllib.parse import quote
13
 
 
14
  from pydantic import BaseModel, ConfigDict, Field
15
 
16
  from src.config import get_settings, LIBBEE_VERSION
 
160
  return _redact_for_analytics(text, max_len)
161
 
162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  def _log_agent_query(question: str, response: AgentResponse, start_time: float) -> None:
164
  """Keep only local operational counters.
165
 
 
499
  _run_search_mode(question, context, model, True),
500
  _search_follow_up(context, model),
501
  )
502
+ answer, search_results, sources, source_url, *rest = search_output
503
  follow_up_question, follow_up_suggestions = follow_up_output
504
+ alternatives = rest[0] if rest else []
505
+ if alternatives:
506
+ # PRIMO found nothing: the alternative searches come first.
507
+ follow_up_suggestions = (alternatives + list(follow_up_suggestions or []))[:5]
508
  if follow_up_action == "review_articles_only":
509
  answer += "<br><br>Use the destination database’s publication-type filter to select review articles. A review article and a peer-reviewed article are different categories."
510
  return AgentResponse(
 
641
  original_question = question
642
 
643
  if follow_up == "unsure" and not just_clarified:
644
+ _safe_metrics_bucket("behaviour", "follow_up_clarification")
645
  return _follow_up_clarification(question, standalone, refers_to, model, start_time)
646
 
647
  assumed_note = ""
648
  if follow_up in ("yes", "unsure") and standalone.strip() and standalone.strip().lower() != question.strip().lower():
649
  # "unsure" reaches here only right after a clarifying question: LibBee
650
  # never asks twice in a row, so it takes the most likely reading.
651
+ _safe_metrics_bucket("behaviour", "assumed_follow_up")
652
  assumed_note = _assumed_follow_up_note(refers_to)
653
  question = standalone
654
 
 
661
  if just_clarified or clarify_action:
662
  search_mode = "find"
663
  else:
664
+ _safe_metrics_bucket("behaviour", "search_mode_clarification")
665
  return _search_mode_clarification(question, model, start_time,
666
  cls_result.get("intent"), assumed_note)
667
 
 
865
  _run_search_mode(question, context, model, False, explain=search_mode == "explain"),
866
  _search_follow_up(context, model),
867
  )
868
+ answer, search_results, sources, source_url, *rest = search_output
869
  follow_up_question, follow_up_suggestions = follow_up_output
870
+ alternatives = rest[0] if rest else []
871
+ if alternatives:
872
+ # PRIMO found nothing: the alternative searches come first.
873
+ follow_up_suggestions = (alternatives + list(follow_up_suggestions or []))[:5]
874
  if is_highly_cited:
875
  answer += _highly_cited_note(_escape(topic))
876
  return AgentResponse(
src/agentcore/primo_chat.py CHANGED
@@ -68,7 +68,10 @@ def render_primo_results(payload: dict, context: SearchContextPayload,
68
  if failed:
69
  parts.append('<p class="libbee-primo-results-note">PRIMO results could not load right now. Open the search link above to continue with these filters.</p>')
70
  elif not records:
71
- parts.append('<p class="libbee-primo-results-note">PRIMO returned no results for this search. Open the link above to broaden the keywords or adjust the filters.</p>')
 
 
 
72
  else:
73
  total = payload.get("total")
74
  count = len(records)
@@ -135,6 +138,7 @@ async def fetch_primo_panel(context: SearchContextPayload, question: str = "") -
135
  except Exception as exc:
136
  logger.warning("PRIMO chat results unavailable: %s", type(exc).__name__)
137
  payload = {"status": "unavailable", "results": []}
 
138
  original = context.primo_boolean_query or ""
139
  empty_ok = payload.get("status", "ok") == "ok" and not payload.get("error") and not payload.get("results")
140
  if empty_ok and context.query_field != "title" and '"' in original:
@@ -149,6 +153,19 @@ async def fetch_primo_panel(context: SearchContextPayload, question: str = "") -
149
  payload = retry
150
  context.primo_boolean_query = relaxed
151
  broadened = True
 
152
  except Exception as exc:
153
  logger.warning("PRIMO broadened retry unavailable: %s", type(exc).__name__)
 
 
154
  return render_primo_results(payload, context, broadened=broadened)
 
 
 
 
 
 
 
 
 
 
 
68
  if failed:
69
  parts.append('<p class="libbee-primo-results-note">PRIMO results could not load right now. Open the search link above to continue with these filters.</p>')
70
  elif not records:
71
+ # libbee-primo-empty marks a confirmed empty search for the caller.
72
+ parts.append('<p class="libbee-primo-results-note libbee-primo-empty">PRIMO returned no results for this search, '
73
+ 'even with broader matching. Try one of the alternative searches suggested below, '
74
+ 'or open the link above to change the keywords or filters.</p>')
75
  else:
76
  total = payload.get("total")
77
  count = len(records)
 
138
  except Exception as exc:
139
  logger.warning("PRIMO chat results unavailable: %s", type(exc).__name__)
140
  payload = {"status": "unavailable", "results": []}
141
+ _count("primo_search")
142
  original = context.primo_boolean_query or ""
143
  empty_ok = payload.get("status", "ok") == "ok" and not payload.get("error") and not payload.get("results")
144
  if empty_ok and context.query_field != "title" and '"' in original:
 
153
  payload = retry
154
  context.primo_boolean_query = relaxed
155
  broadened = True
156
+ _count("primo_broadened")
157
  except Exception as exc:
158
  logger.warning("PRIMO broadened retry unavailable: %s", type(exc).__name__)
159
+ if not _has_records(payload) and payload.get("status", "ok") == "ok" and not payload.get("error"):
160
+ _count("primo_still_empty")
161
  return render_primo_results(payload, context, broadened=broadened)
162
+
163
+
164
+ def primo_panel_is_empty(panel_html: str) -> bool:
165
+ """True when PRIMO answered and found nothing, even after broadening."""
166
+ return "libbee-primo-empty" in (panel_html or "")
167
+
168
+
169
+ def _count(key: str) -> None:
170
+ from src.agentcore.utils import _safe_metrics_bucket
171
+ _safe_metrics_bucket("behaviour", key)
src/agentcore/rendering.py CHANGED
@@ -1,423 +1,443 @@
1
- """HTML fragment renderers: source badges, reasoning trace blocks, AI-tools footer, contacts.
2
-
3
- Styling contract: renderers emit class names only. The answer sanitizer
4
- (src/services/html_sanitizer.py) strips every style attribute and every svg element,
5
- so inline styles never reached the browser. Presentation lives in the
6
- frontend stylesheet:
7
- - lb-* classes: LibBee server components (trace, source badge, events, hours, steps)
8
- - kb-* classes: research-answer components already styled by the LibGuides page
9
- (kb-ai-platform-*, kb-search-process*, kb-database-*, kb-boolean-query-*)
10
- """
11
- import asyncio
12
- import html
13
- import json
14
- import logging
15
- import os
16
- import re
17
- import time
18
- import uuid
19
- from datetime import datetime
20
- from typing import Any, Dict, List, Literal, Optional, Tuple
21
- from urllib.parse import quote
22
-
23
- import httpx
24
- from pydantic import BaseModel, ConfigDict, Field
25
-
26
- from src.config import get_settings, LIBBEE_VERSION
27
- from src.services.staff_service import (
28
- STAFF_DIRECTORY,
29
- match_staff_name,
30
- match_staff_role,
31
- should_attempt_staff_lookup,
32
- staff_name_answer,
33
- staff_role_answer,
34
- )
35
-
36
- from src.agentcore.models import SearchContextPayload
37
- from src.agentcore.constants import ASK_LIBRARIAN_URL, PRIMO_AI_URL, _openathens_url
38
- from src.agentcore.utils import (
39
- _escape,
40
- _find_staff_by_token,
41
- _primo_clean_url,
42
- _shared_build_pubmed_url,
43
- )
44
-
45
- logger = logging.getLogger(__name__)
46
-
47
- _SOURCE_BADGES = {
48
- "rag": ("📖", "KU Library Knowledge Base", "kb"),
49
- "primo": ("📚", "KU Library PRIMO", "library"),
50
- "semantic": ("🎓", "Semantic Scholar", "scholarly"),
51
- "consensus_badge": ("🧬", "Consensus", "scholarly"),
52
- "semantic_badge": ("🎓", "Semantic Scholar", "scholarly"),
53
- "pubmed": ("🏥", "PubMed", "scholarly"),
54
- "web": ("🌐", "Web Search", "web"),
55
- "ku_web": ("🏛️", "Khalifa University web pages", "ku"),
56
- "ku_web_none": ("🏛️", "Khalifa University web pages · nothing found", "ku"),
57
- "web_live": ("🌐", "Web Search · Live", "web"),
58
- "libbee": ("🐝", "LibBee", "libbee"),
59
- "ku_library": ("📋", "KU Library", "library"),
60
- "llm": ("🤖", "AI response · web not verified", "llm"),
61
- }
62
-
63
-
64
- def _source_badge(source: str, url: str = "") -> str:
65
- icon, label, variant = _SOURCE_BADGES.get(source, ("ℹ️", source, "llm"))
66
- inner = f"{icon} Source: {_escape(label)}"
67
- if url:
68
- inner = f'<a href="{_escape(url)}" target="_blank">{inner}</a>'
69
- return f'<div class="lb-source lb-source--{variant}">{inner}</div>'
70
-
71
-
72
- def _tool_urls(context: SearchContextPayload) -> Dict[str, str]:
73
- ai_query = quote(context.ai_tool_query or context.display_topic or context.topic)
74
- primo_ai_query = quote(context.ai_tool_query or context.display_topic or context.topic)
75
- urls: Dict[str, str] = {
76
- "leapspace": f"https://www.sciencedirect.com/leapspace?query={ai_query}",
77
- "scopus_ai": _openathens_url(f"https://www.scopus.com/pages/ai?query={ai_query}"),
78
- "ebsco_ai": (
79
- f"https://research.ebsco.com/c/yst6t2/search/results"
80
- f"?q={ai_query}"
81
- f"&autocorrect=y"
82
- f"&expanders=concept"
83
- f"&limiters=None"
84
- f"&searchMode=enhanced"
85
- f"&searchSegment=all-results"
86
- ),
87
- "primo_ai": f"{PRIMO_AI_URL}{primo_ai_query}",
88
- "consensus": f"https://consensus.app/results/?q={ai_query}",
89
- "primo_discovery": _primo_clean_url(context),
90
- }
91
- if context.intent == "search_medical":
92
- urls["pubmed"] = _shared_build_pubmed_url(
93
- context.topic, context.year_from, context.year_to, context.peer_reviewed,
94
- open_access=context.open_access
95
- )
96
- return urls
97
-
98
-
99
- def _contact_footer_for_query(question: str, context: Optional[SearchContextPayload]) -> str:
100
- q = (question or "").lower()
101
- specialist: Optional[dict] = None
102
- if any(t in q for t in ["interlibrary", "ill request", "ill form", "borrow from another",
103
- "request article", "request a book", "not available at ku",
104
- "not in ku library", "inter library", "inter-library"]):
105
- footer = (
106
- "<br><br><strong>Library contact points</strong><br>"
107
- f'General help: <a href="{ASK_LIBRARIAN_URL}" target="_blank">Ask a Librarian</a> · '
108
- '<a href="mailto:libse@ku.ac.ae">libse@ku.ac.ae</a><br>'
109
- 'ILL requests: <a href="mailto:ill@ku.ac.ae">ill@ku.ac.ae</a> · '
110
- '<strong>Zainab Al Ali</strong> · '
111
- '<a href="mailto:zainab.alali@ku.ac.ae">zainab.alali@ku.ac.ae</a> · '
112
- '<a href="tel:+97123124321">+971 2 312 4321</a>'
113
- )
114
- return footer
115
- elif any(t in q for t in [
116
- "apc", "article processing charge", "article processing fee",
117
- "open access fee", "oa fee", "oa fund", "oa publishing",
118
- "publish open access", "open access publish", "how to publish open access",
119
- "open access journal", "open access mandate", "open access policy",
120
- "waiver", "gold open access", "diamond open access", "hybrid journal",
121
- "creative commons", "cc by", "cc licence", "openaccess", "open access",
122
- ]):
123
- # Open Access & APC → Walter Brian Hall (OA lead at KU Library)
124
- specialist = _find_staff_by_token("walter")
125
- elif any(t in q for t in [
126
- "research support", "research service", "research consultation",
127
- "research librarian", "research help", "research advice",
128
- "scholarly communication", "bibliometric", "research impact",
129
- "citation analysis", "h-index", "journal ranking", "impact factor",
130
- "orcid", "khazna", "repository", "scival", "scopus profile",
131
- "author profile", "research data", "data management",
132
- "libguide", "research guide", "ai tool", "ai for research",
133
- "publication advice", "journal selection", "where to publish",
134
- ]):
135
- # Research services → Nikesh Narayanan (Research & Access Services Librarian)
136
- specialist = _find_staff_by_token("nikesh")
137
- elif any(t in q for t in ["database access", "proxy", "eresource",
138
- "e-resource", "remote access", "access problem", "off campus"]):
139
- specialist = _find_staff_by_token("rani")
140
- elif any(t in q for t in ["website", "system", "technical", "login issue", "page not loading"]):
141
- specialist = _find_staff_by_token("walter")
142
- elif context and context.intent == "search_medical":
143
- # Medical/clinical research questions only → Jason Fetty (Medical Librarian)
144
- specialist = _find_staff_by_token("jason")
145
- elif context and context.intent == "search_academic":
146
- specialist = _find_staff_by_token("nikesh")
147
- footer = (
148
- "<br><br><strong>Library contact points</strong><br>"
149
- f'General help: <a href="{ASK_LIBRARIAN_URL}" target="_blank">Ask a Librarian</a> · '
150
- '<a href="mailto:libse@ku.ac.ae">libse@ku.ac.ae</a>'
151
- )
152
- if specialist:
153
- footer += (
154
- f'<br>Relevant contact: <strong>{_escape(specialist.get("full_name", ""))}</strong> — '
155
- f'{_escape(specialist.get("role", ""))}<br>'
156
- f'<a href="mailto:{_escape(specialist.get("email", ""))}">{_escape(specialist.get("email", ""))}</a>'
157
- )
158
- phone = specialist.get("phone") or specialist.get("work_phone")
159
- if phone:
160
- footer += f' · <a href="tel:{_escape(str(phone).replace(" ", ""))}">{_escape(phone)}</a>'
161
- return footer
162
-
163
-
164
- def _thought_block(intent: str, tool: str, question: str, extra: str = "") -> str:
165
- labels = {
166
- "library_info": ("📋", "Library information lookup", "I searched the KU Library knowledge base for relevant content."),
167
- "general": ("🌐", "General knowledge / web search", "I answered using a web search for current information."),
168
- "general_recent": ("🔴", "Live web search", "I ran a live web search for the most up-to-date information."),
169
- "ku_info": ("🏛️", "Khalifa University question", "I searched Khalifa University web pages (ku.ac.ae and Khazna) and answered only from what they say."),
170
- "ku_info_none": ("🏛️", "Khalifa University question", "I searched Khalifa University web pages but found no page that answers this, so I did not guess."),
171
- "off_topic": ("🌐", "Outside library services", "This is not a library or research question, so I answered from a web search as a courtesy."),
172
- "social_greeting": ("🐝", "Conversational response", "I responded directly as LibBee, the KU Library AI Assistant."),
173
- "social": ("🐝", "Conversational response", "I responded directly as LibBee, the KU Library AI Assistant."),
174
- "general_knowledge": ("🤖", "AI response", "Current web information could not be verified for this answer."),
175
- "events": ("📅", "Library events lookup", "I checked the library events service. Available events or the official calendar link appear below."),
176
- "staff_lookup": ("👤", "Staff directory lookup", "I matched your request to the KU Library staff directory."),
177
- "hours": ("⏰", "Library hours lookup", "I checked the library hours service. Available hours or the official schedule link appear below."),
178
- "libcal_live": ("⏰", "Live library hours", "I checked the library hours service. Available hours or the official schedule link appear below."),
179
- "campus": ("📍", "Campus information lookup", "I retrieved KU Library campus information from the knowledge base."),
180
- "database_rec": ("🗄️", "Database recommendation", "I matched your subject to the KU Library e-resources database."),
181
- "rag_search": ("📖", "Knowledge base search", "I searched the supplied KU Library knowledge base."),
182
- }
183
- icon, label, reasoning = labels.get(intent, ("🤖", "AI response", "I processed your question and generated a response."))
184
- if extra:
185
- reasoning += " " + extra
186
- return (
187
- '<details class="lb-trace">'
188
- f'<summary class="lb-trace-summary"><span class="lb-trace-icon">{icon}</span> My approach</summary>'
189
- '<div class="lb-trace-body">'
190
- f'<strong>Question:</strong> {_escape(question)}<br>'
191
- f'<strong>Classified as:</strong> {label}<br>'
192
- f'<strong>How I answered:</strong> {reasoning}'
193
- '</div></details>'
194
- )
195
-
196
-
197
- def _search_trace_block(question: str, context: SearchContextPayload) -> str:
198
- topic = _escape(context.display_topic or context.topic)
199
- primo_boolean = _escape(context.primo_boolean_query or "")
200
- source_label = "PubMed" if context.source == "pubmed" else "KU PRIMO Library Discovery"
201
- intent_label = {
202
- "search_academic": "academic literature search",
203
- "search_medical": "medical / clinical literature search",
204
- }.get(context.intent, "library search")
205
- filters_parts = []
206
- if context.peer_reviewed:
207
- filters_parts.append("peer reviewed requested (verify in PubMed)" if context.source == "pubmed" else "peer reviewed only")
208
- if context.open_access:
209
- filters_parts.append("free full text" if context.source == "pubmed" else "open access")
210
- if context.year_from and context.year_to:
211
- filters_parts.append(f"{context.year_from}–{context.year_to}")
212
- elif context.year_from:
213
- filters_parts.append(f"from {context.year_from}")
214
- rtype = {"articles": "articles", "books": "books", "both": "articles and books"}.get(
215
- context.resource_type, "articles"
216
- )
217
- filters_parts.append(rtype)
218
- filters_str = ", ".join(filters_parts)
219
- reasoning = (
220
- f"I classified this as a <strong>{intent_label}</strong>, "
221
- f"extracted the topic <strong>{topic}</strong>, "
222
- f"prepared a search query and filters, "
223
- f"for <strong>{source_label}</strong>: <strong>{filters_str}</strong>."
224
- )
225
- if context.intent == "search_medical" and context.source != "pubmed":
226
- reasoning += " For medical topics, PubMed and Embase are also recommended."
227
- block = (
228
- '<details class="kb-search-process">'
229
- '<summary class="kb-search-process-summary">'
230
- '<span class="kb-search-process-icon">🔍</span> How I searched'
231
- '</summary>'
232
- '<div class="lb-trace-body">'
233
- f'<strong>Your question:</strong> {_escape(question)}<br>'
234
- f'<strong>Interpreted topic:</strong> {topic}<br>'
235
- )
236
- if primo_boolean:
237
- block += (
238
- f'<strong>Prepared query for {source_label}:</strong><br>'
239
- f'<code class="lb-code">{primo_boolean}</code>'
240
- )
241
- block += f'<strong>Reasoning:</strong> {reasoning}<br>'
242
- block += '<span class="lb-muted">✨ AI research tools for deeper exploration are listed at the end of this answer.</span>'
243
- block += '</div></details>'
244
- return block
245
-
246
-
247
- # Emoji stand-ins for the former SVG mascots (the sanitizer drops svg elements).
248
- _PLATFORM_ICONS = {
249
- "primo": "📚", "leapspace": "🚀", "scopus": "🔎", "ebsco": "📘",
250
- "consensus": "🧬", "semanticscholar": "🎓", "perplexity": "💬", "pubmed": "🏥",
251
- }
252
-
253
- _DB_ICONS = {
254
- "PubMed": "🔬", "PubMed@KU": "🔬", "Embase": "🏥", "CINAHL Ultimate": "🏥",
255
- "Cochrane Library": "🔬", "UpToDate": "🏥",
256
- "IEEE Xplore": "💻", "ACM Digital Library": "💻",
257
- "ScienceDirect": "🔬", "Scopus": "🔬", "Web of Science": "🔬", "SpringerLink": "📚",
258
- "ACS Publications": "⚛️", "APS Journals": "⚛️", "Knovel": "🔧",
259
- "Business Source Complete": "📊", "Emerald Insight": "📊",
260
- "Taylor & Francis": "📚", "EBSCO": "📚",
261
- }
262
-
263
-
264
- def _ai_tools_footer(context):
265
- from urllib.parse import quote as _q
266
-
267
- ai_q = _q(context.ai_tool_query or context.display_topic or context.topic)
268
- bool_q = context.primo_boolean_query or ""
269
- primo_ai = PRIMO_AI_URL + ai_q
270
- is_med = context.intent == "search_medical"
271
- pubmed_url = _shared_build_pubmed_url(
272
- context.topic, context.year_from, context.year_to, context.peer_reviewed,
273
- open_access=context.open_access
274
- ) if is_med else ""
275
-
276
- platforms = [
277
- ("PRIMO AI Assistant", primo_ai, "primo"),
278
- ("LeapSpace", "https://www.sciencedirect.com/leapspace?query=" + ai_q, "leapspace"),
279
- ("Scopus AI", _openathens_url("https://www.scopus.com/pages/ai?query=" + ai_q), "scopus"),
280
- ("EBSCO Research AI",
281
- "https://research.ebsco.com/c/yst6t2/search/results?q=" + ai_q
282
- + "&autocorrect=y&expanders=concept&limiters=None&searchMode=enhanced&searchSegment=all-results", "ebsco"),
283
- ("Consensus", "https://consensus.app/results/?q=" + ai_q, "consensus"),
284
- ("Semantic Scholar", "https://www.semanticscholar.org/search?q=" + ai_q + "&sort=relevance", "semanticscholar"),
285
- ("Perplexity", "https://www.perplexity.ai/search?q=" + ai_q, "perplexity"),
286
- ]
287
- if is_med and pubmed_url:
288
- platforms.append(("PubMed", pubmed_url, "pubmed"))
289
-
290
- def _btn(label, url, icon_key):
291
- icon = _PLATFORM_ICONS.get(icon_key, "🐝")
292
- return (
293
- f'<a class="kb-ai-platform-button" href="{_escape(url)}" target="_blank">'
294
- f'<span class="kb-ai-platform-icon">{icon}</span>{_escape(label)}</a>'
295
- )
296
-
297
- btn_rows = ""
298
- for k in range(0, len(platforms), 2):
299
- pair = platforms[k:k + 2]
300
- cells = "".join(f"<td>{_btn(lbl, url, key)}</td>" for lbl, url, key in pair)
301
- btn_rows += f"<tr>{cells}</tr>"
302
-
303
- platforms_html = (
304
- '<div class="kb-ai-platform-panel">'
305
- '<div class="kb-ai-platform-heading">'
306
- '<span class="kb-ai-platform-heading-icon">🤖</span> Search your query across AI platforms</div>'
307
- '<div class="kb-ai-platform-subtitle">'
308
- 'Your query is pre-loaded. Click any platform to search instantly.</div>'
309
- f'<table class="kb-ai-platform-grid"><tbody>{btn_rows}</tbody></table>'
310
- '</div>'
311
- )
312
-
313
- if bool_q:
314
- and_count = bool_q.upper().count(" AND ")
315
- if and_count >= 1:
316
- bool_label = "Use this in PRIMO Advanced Search or any database for precise results:"
317
- else:
318
- bool_label = "Try adding synonyms with OR to find more relevant results:"
319
- bool_html = (
320
- '<div class="kb-boolean-query-panel">'
321
- '<div class="kb-boolean-query-title">💡 Boolean search tip</div>'
322
- f'<div class="lb-boolean-hint">{bool_label}</div>'
323
- f'<code class="kb-boolean-query-text">{_escape(bool_q)}</code>'
324
- '<div class="lb-boolean-hint">Paste into the Advanced Search box of any database below.</div>'
325
- '</div>'
326
- )
327
- else:
328
- bool_html = ""
329
-
330
- all_lower = ((context.ai_tool_query or "") + " " + (context.topic or "")).lower()
331
-
332
- def _db_row(name, url, desc):
333
- icon = _DB_ICONS.get(name, "🐝")
334
- return (
335
- '<div class="kb-database-row">'
336
- f'<span class="kb-database-icon">{icon}</span>'
337
- f'<a class="kb-database-name" href="{_escape(url)}" target="_blank">{_escape(name)}</a>'
338
- f'<span class="lb-muted"> — {_escape(desc)}</span>'
339
- '</div>'
340
- )
341
-
342
- if any(k in all_lower for k in ["medicine","medical","clinical","nursing","pharmacy","health","pubmed","embase","cinahl","cochrane","uptodate"]):
343
- db_subject = "Medicine & Health Sciences"
344
- dbs = [
345
- ("PubMed","https://pubmed.ncbi.nlm.nih.gov/","Core biomedical literature"),
346
- ("Embase",_openathens_url("https://www.embase.com"),"Biomedical, drugs, devices, clinical medicine"),
347
- ("CINAHL Ultimate",_openathens_url("https://search.ebscohost.com/login.aspx?authtype=ip,uid&profile=ehost&defaultdb=cul"),"Nursing and allied health"),
348
- ("Cochrane Library",_openathens_url("https://www.cochranelibrary.com"),"Systematic reviews and evidence-based medicine"),
349
- ("UpToDate",_openathens_url("https://www.uptodate.com"),"Point-of-care clinical decision support"),
350
- ]
351
- elif any(k in all_lower for k in ["machine learning","deep learning","artificial intelligence","neural network","computer science","software","algorithm","cybersecurity","robotics","nlp"]):
352
- db_subject = "Computer Science & AI"
353
- dbs = [
354
- ("IEEE Xplore",_openathens_url("https://ieeexplore.ieee.org"),"Core CS, AI, electronics and systems"),
355
- ("ACM Digital Library",_openathens_url("https://dl.acm.org"),"Computer science journals, proceedings and books"),
356
- ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Full text across CS and applied computing"),
357
- ("Scopus",_openathens_url("https://www.scopus.com"),"Discovery and citation tracking"),
358
- ("Web of Science",_openathens_url("https://www.webofscience.com"),"Citation index"),
359
- ]
360
- elif any(k in all_lower for k in ["climate","global warming","environment","sustainability","ecology","carbon","emission","renewable","sea level","maldives","island"]):
361
- db_subject = "Environment & Climate"
362
- dbs = [
363
- ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Full text across science, environment and engineering"),
364
- ("Scopus",_openathens_url("https://www.scopus.com"),"Broad discovery and citation tracking"),
365
- ("Web of Science",_openathens_url("https://www.webofscience.com"),"High-impact journal coverage and citation index"),
366
- ("SpringerLink",_openathens_url("https://link.springer.com"),"Springer journals and books"),
367
- ]
368
- elif any(k in all_lower for k in ["engineering","mechanical","civil","electrical","aerospace","structural","petroleum","chemical","materials"]):
369
- db_subject = "Engineering"
370
- dbs = [
371
- ("IEEE Xplore",_openathens_url("https://ieeexplore.ieee.org"),"Electrical, electronics and systems engineering"),
372
- ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Full text across engineering disciplines"),
373
- ("Knovel",_openathens_url("https://app.knovel.com"),"Engineering handbooks and reference data"),
374
- ("Scopus",_openathens_url("https://www.scopus.com"),"Discovery and citation tracking"),
375
- ("Web of Science",_openathens_url("https://www.webofscience.com"),"Citation index"),
376
- ]
377
- elif any(k in all_lower for k in ["business","management","finance","economics","leadership","marketing","strategy","entrepreneurship"]):
378
- db_subject = "Business & Management"
379
- dbs = [
380
- ("Business Source Complete",_openathens_url("https://search.ebscohost.com"),"Core business and management literature"),
381
- ("Emerald Insight",_openathens_url("https://www.emerald.com/insight"),"Management, strategy and leadership"),
382
- ("Scopus",_openathens_url("https://www.scopus.com"),"Broad discovery and citation tracking"),
383
- ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Business and social sciences full text"),
384
- ]
385
- elif any(k in all_lower for k in ["physics","chemistry","quantum","nuclear","materials science","nanotechnology","optics"]):
386
- db_subject = "Physics, Chemistry & Materials"
387
- dbs = [
388
- ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Full text across physical sciences"),
389
- ("ACS Publications",_openathens_url("https://pubs.acs.org"),"Core chemistry and chemical engineering"),
390
- ("APS Journals",_openathens_url("https://journals.aps.org"),"American Physical Society core physics journals"),
391
- ("Scopus",_openathens_url("https://www.scopus.com"),"Discovery and citation tracking"),
392
- ("Web of Science",_openathens_url("https://www.webofscience.com"),"Citation index"),
393
- ]
394
- else:
395
- db_subject = "General"
396
- dbs = [
397
- ("EBSCO",_openathens_url("https://search.ebscohost.com"),"Multidisciplinary full text"),
398
- ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Science, engineering and medicine"),
399
- ("SpringerLink",_openathens_url("https://link.springer.com"),"Journals and books across all disciplines"),
400
- ("Taylor & Francis",_openathens_url("https://www.tandfonline.com"),"Humanities, social sciences and STEM"),
401
- ("Emerald Insight",_openathens_url("https://www.emerald.com/insight"),"Management and social sciences"),
402
- ("Scopus",_openathens_url("https://www.scopus.com"),"Citation discovery, all disciplines"),
403
- ("Web of Science",_openathens_url("https://www.webofscience.com"),"Citation index, all disciplines"),
404
- ]
405
-
406
- dbs_html_rows = "".join(_db_row(name, url, desc) for name, url, desc in dbs)
407
-
408
- db_section = (
409
- '<div class="kb-database-list">'
410
- f'<div class="lb-db-heading">📂 Recommended KU databases — {_escape(db_subject)}</div>'
411
- + dbs_html_rows +
412
- '<div class="lb-db-more">'
413
- '<a href="https://library.ku.ac.ae/eresources" target="_blank">'
414
- '🗄️ Browse the current KU resource directory →</a></div>'
415
- '</div>'
416
- )
417
-
418
- filter_note = ""
419
- if is_med and context.peer_reviewed:
420
- filter_note += '<p><small>PubMed has no peer-review filter. Use PRIMO’s Peer Reviewed facet and verify the journal’s publication process.</small></p>'
421
- if is_med and context.open_access:
422
- filter_note += '<p><small>The PubMed link uses its Free full text filter; free access does not establish an open reuse licence.</small></p>'
423
- return platforms_html + filter_note + bool_html + db_section
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTML fragment renderers: source badges, reasoning trace blocks, AI-tools footer, contacts.
2
+
3
+ Styling contract: renderers emit class names only. The answer sanitizer
4
+ (src/services/html_sanitizer.py) strips every style attribute and every svg element,
5
+ so inline styles never reached the browser. Presentation lives in the
6
+ frontend stylesheet:
7
+ - lb-* classes: LibBee server components (trace, source badge, events, hours, steps)
8
+ - kb-* classes: research-answer components already styled by the LibGuides page
9
+ (kb-ai-platform-*, kb-search-process*, kb-database-*, kb-boolean-query-*)
10
+ """
11
+ import asyncio
12
+ import html
13
+ import json
14
+ import logging
15
+ import os
16
+ import re
17
+ import time
18
+ import uuid
19
+ from datetime import datetime
20
+ from typing import Any, Dict, List, Literal, Optional, Tuple
21
+ from urllib.parse import quote
22
+
23
+ import httpx
24
+ from pydantic import BaseModel, ConfigDict, Field
25
+
26
+ from src.config import get_settings, LIBBEE_VERSION
27
+ from src.services.staff_service import (
28
+ STAFF_DIRECTORY,
29
+ match_staff_name,
30
+ match_staff_role,
31
+ should_attempt_staff_lookup,
32
+ staff_name_answer,
33
+ staff_role_answer,
34
+ )
35
+
36
+ from src.agentcore.models import SearchContextPayload
37
+ from src.agentcore.constants import ASK_LIBRARIAN_URL, PRIMO_AI_URL, _openathens_url
38
+ from src.agentcore.utils import (
39
+ _escape,
40
+ _find_staff_by_token,
41
+ _primo_clean_url,
42
+ _shared_build_pubmed_url,
43
+ )
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+ _SOURCE_BADGES = {
48
+ "rag": ("📖", "KU Library Knowledge Base", "kb"),
49
+ "primo": ("📚", "KU Library PRIMO", "library"),
50
+ "semantic": ("🎓", "Semantic Scholar", "scholarly"),
51
+ "consensus_badge": ("🧬", "Consensus", "scholarly"),
52
+ "semantic_badge": ("🎓", "Semantic Scholar", "scholarly"),
53
+ "pubmed": ("🏥", "PubMed", "scholarly"),
54
+ "web": ("🌐", "Web Search", "web"),
55
+ "ku_web": ("🏛️", "Khalifa University web pages", "ku"),
56
+ "ku_web_none": ("🏛️", "Khalifa University web pages · nothing found", "ku"),
57
+ "web_live": ("🌐", "Web Search · Live", "web"),
58
+ "libbee": ("🐝", "LibBee", "libbee"),
59
+ "ku_library": ("📋", "KU Library", "library"),
60
+ "llm": ("🤖", "AI response · web not verified", "llm"),
61
+ }
62
+
63
+
64
+ def _source_badge(source: str, url: str = "") -> str:
65
+ icon, label, variant = _SOURCE_BADGES.get(source, ("ℹ️", source, "llm"))
66
+ inner = f"{icon} Source: {_escape(label)}"
67
+ if url:
68
+ inner = f'<a href="{_escape(url)}" target="_blank">{inner}</a>'
69
+ return f'<div class="lb-source lb-source--{variant}">{inner}</div>'
70
+
71
+
72
+ def _tool_urls(context: SearchContextPayload) -> Dict[str, str]:
73
+ ai_query = quote(context.ai_tool_query or context.display_topic or context.topic)
74
+ primo_ai_query = quote(context.ai_tool_query or context.display_topic or context.topic)
75
+ urls: Dict[str, str] = {
76
+ "leapspace": f"https://www.sciencedirect.com/leapspace?query={ai_query}",
77
+ "scopus_ai": _openathens_url(f"https://www.scopus.com/pages/ai?query={ai_query}"),
78
+ "ebsco_ai": (
79
+ f"https://research.ebsco.com/c/yst6t2/search/results"
80
+ f"?q={ai_query}"
81
+ f"&autocorrect=y"
82
+ f"&expanders=concept"
83
+ f"&limiters=None"
84
+ f"&searchMode=enhanced"
85
+ f"&searchSegment=all-results"
86
+ ),
87
+ "primo_ai": f"{PRIMO_AI_URL}{primo_ai_query}",
88
+ "consensus": f"https://consensus.app/results/?q={ai_query}",
89
+ "primo_discovery": _primo_clean_url(context),
90
+ }
91
+ # EBSCO Discovery receives the full question, exactly as EBSCO's AI search did.
92
+ urls["ebsco_discovery"] = urls["ebsco_ai"]
93
+ if context.intent == "search_medical":
94
+ urls["pubmed"] = _shared_build_pubmed_url(
95
+ context.topic, context.year_from, context.year_to, context.peer_reviewed,
96
+ open_access=context.open_access
97
+ )
98
+ return urls
99
+
100
+
101
+ def _contact_footer_for_query(question: str, context: Optional[SearchContextPayload]) -> str:
102
+ q = (question or "").lower()
103
+ specialist: Optional[dict] = None
104
+ if any(t in q for t in ["interlibrary", "ill request", "ill form", "borrow from another",
105
+ "request article", "request a book", "not available at ku",
106
+ "not in ku library", "inter library", "inter-library"]):
107
+ footer = (
108
+ "<br><br><strong>Library contact points</strong><br>"
109
+ f'General help: <a href="{ASK_LIBRARIAN_URL}" target="_blank">Ask a Librarian</a> · '
110
+ '<a href="mailto:libse@ku.ac.ae">libse@ku.ac.ae</a><br>'
111
+ 'ILL requests: <a href="mailto:ill@ku.ac.ae">ill@ku.ac.ae</a> · '
112
+ '<strong>Zainab Al Ali</strong> · '
113
+ '<a href="mailto:zainab.alali@ku.ac.ae">zainab.alali@ku.ac.ae</a> · '
114
+ '<a href="tel:+97123124321">+971 2 312 4321</a>'
115
+ )
116
+ return footer
117
+ elif any(t in q for t in [
118
+ "apc", "article processing charge", "article processing fee",
119
+ "open access fee", "oa fee", "oa fund", "oa publishing",
120
+ "publish open access", "open access publish", "how to publish open access",
121
+ "open access journal", "open access mandate", "open access policy",
122
+ "waiver", "gold open access", "diamond open access", "hybrid journal",
123
+ "creative commons", "cc by", "cc licence", "openaccess", "open access",
124
+ ]):
125
+ # Open Access & APC → Walter Brian Hall (OA lead at KU Library)
126
+ specialist = _find_staff_by_token("walter")
127
+ elif any(t in q for t in [
128
+ "research support", "research service", "research consultation",
129
+ "research librarian", "research help", "research advice",
130
+ "scholarly communication", "bibliometric", "research impact",
131
+ "citation analysis", "h-index", "journal ranking", "impact factor",
132
+ "orcid", "khazna", "repository", "scival", "scopus profile",
133
+ "author profile", "research data", "data management",
134
+ "libguide", "research guide", "ai tool", "ai for research",
135
+ "publication advice", "journal selection", "where to publish",
136
+ ]):
137
+ # Research services → Nikesh Narayanan (Research & Access Services Librarian)
138
+ specialist = _find_staff_by_token("nikesh")
139
+ elif any(t in q for t in ["database access", "proxy", "eresource",
140
+ "e-resource", "remote access", "access problem", "off campus"]):
141
+ specialist = _find_staff_by_token("rani")
142
+ elif any(t in q for t in ["website", "system", "technical", "login issue", "page not loading"]):
143
+ specialist = _find_staff_by_token("walter")
144
+ elif context and context.intent == "search_medical":
145
+ # Medical/clinical research questions only → Jason Fetty (Medical Librarian)
146
+ specialist = _find_staff_by_token("jason")
147
+ elif context and context.intent == "search_academic":
148
+ specialist = _find_staff_by_token("nikesh")
149
+ footer = (
150
+ "<br><br><strong>Library contact points</strong><br>"
151
+ f'General help: <a href="{ASK_LIBRARIAN_URL}" target="_blank">Ask a Librarian</a> · '
152
+ '<a href="mailto:libse@ku.ac.ae">libse@ku.ac.ae</a>'
153
+ )
154
+ if specialist:
155
+ footer += (
156
+ f'<br>Relevant contact: <strong>{_escape(specialist.get("full_name", ""))}</strong> — '
157
+ f'{_escape(specialist.get("role", ""))}<br>'
158
+ f'<a href="mailto:{_escape(specialist.get("email", ""))}">{_escape(specialist.get("email", ""))}</a>'
159
+ )
160
+ phone = specialist.get("phone") or specialist.get("work_phone")
161
+ if phone:
162
+ footer += f' · <a href="tel:{_escape(str(phone).replace(" ", ""))}">{_escape(phone)}</a>'
163
+ return footer
164
+
165
+
166
+ def _thought_block(intent: str, tool: str, question: str, extra: str = "") -> str:
167
+ labels = {
168
+ "library_info": ("📋", "Library information lookup", "I searched the KU Library knowledge base for relevant content."),
169
+ "general": ("🌐", "General knowledge / web search", "I answered using a web search for current information."),
170
+ "general_recent": ("🔴", "Live web search", "I ran a live web search for the most up-to-date information."),
171
+ "ku_info": ("🏛️", "Khalifa University question", "I searched Khalifa University web pages (ku.ac.ae and Khazna) and answered only from what they say."),
172
+ "ku_info_none": ("🏛️", "Khalifa University question", "I searched Khalifa University web pages but found no page that answers this, so I did not guess."),
173
+ "off_topic": ("🌐", "Outside library services", "This is not a library or research question, so I answered from a web search as a courtesy."),
174
+ "social_greeting": ("🐝", "Conversational response", "I responded directly as LibBee, the KU Library AI Assistant."),
175
+ "social": ("🐝", "Conversational response", "I responded directly as LibBee, the KU Library AI Assistant."),
176
+ "general_knowledge": ("🤖", "AI response", "Current web information could not be verified for this answer."),
177
+ "events": ("📅", "Library events lookup", "I checked the library events service. Available events or the official calendar link appear below."),
178
+ "staff_lookup": ("👤", "Staff directory lookup", "I matched your request to the KU Library staff directory."),
179
+ "hours": ("⏰", "Library hours lookup", "I checked the library hours service. Available hours or the official schedule link appear below."),
180
+ "libcal_live": ("⏰", "Live library hours", "I checked the library hours service. Available hours or the official schedule link appear below."),
181
+ "campus": ("📍", "Campus information lookup", "I retrieved KU Library campus information from the knowledge base."),
182
+ "database_rec": ("🗄️", "Database recommendation", "I matched your subject to the KU Library e-resources database."),
183
+ "rag_search": ("📖", "Knowledge base search", "I searched the supplied KU Library knowledge base."),
184
+ }
185
+ icon, label, reasoning = labels.get(intent, ("🤖", "AI response", "I processed your question and generated a response."))
186
+ if extra:
187
+ reasoning += " " + extra
188
+ return (
189
+ '<details class="lb-trace">'
190
+ f'<summary class="lb-trace-summary"><span class="lb-trace-icon">{icon}</span> My approach</summary>'
191
+ '<div class="lb-trace-body">'
192
+ f'<strong>Question:</strong> {_escape(question)}<br>'
193
+ f'<strong>Classified as:</strong> {label}<br>'
194
+ f'<strong>How I answered:</strong> {reasoning}'
195
+ '</div></details>'
196
+ )
197
+
198
+
199
+ def _search_trace_block(question: str, context: SearchContextPayload) -> str:
200
+ topic = _escape(context.display_topic or context.topic)
201
+ primo_boolean = _escape(context.primo_boolean_query or "")
202
+ source_label = "PubMed" if context.source == "pubmed" else "KU PRIMO Library Discovery"
203
+ intent_label = {
204
+ "search_academic": "academic literature search",
205
+ "search_medical": "medical / clinical literature search",
206
+ }.get(context.intent, "library search")
207
+ filters_parts = []
208
+ if context.peer_reviewed:
209
+ filters_parts.append("peer reviewed requested (verify in PubMed)" if context.source == "pubmed" else "peer reviewed only")
210
+ if context.open_access:
211
+ filters_parts.append("free full text" if context.source == "pubmed" else "open access")
212
+ if context.year_from and context.year_to:
213
+ filters_parts.append(f"{context.year_from}–{context.year_to}")
214
+ elif context.year_from:
215
+ filters_parts.append(f"from {context.year_from}")
216
+ rtype = {"articles": "articles", "books": "books", "both": "articles and books"}.get(
217
+ context.resource_type, "articles"
218
+ )
219
+ filters_parts.append(rtype)
220
+ filters_str = ", ".join(filters_parts)
221
+ reasoning = (
222
+ f"I classified this as a <strong>{intent_label}</strong>, "
223
+ f"extracted the topic <strong>{topic}</strong>, "
224
+ f"prepared a search query and filters, "
225
+ f"for <strong>{source_label}</strong>: <strong>{filters_str}</strong>."
226
+ )
227
+ if context.intent == "search_medical" and context.source != "pubmed":
228
+ reasoning += " For medical topics, PubMed and Embase are also recommended."
229
+ block = (
230
+ '<details class="kb-search-process">'
231
+ '<summary class="kb-search-process-summary">'
232
+ '<span class="kb-search-process-icon">🔍</span> How I searched'
233
+ '</summary>'
234
+ '<div class="lb-trace-body">'
235
+ f'<strong>Your question:</strong> {_escape(question)}<br>'
236
+ f'<strong>Interpreted topic:</strong> {topic}<br>'
237
+ )
238
+ if primo_boolean:
239
+ block += (
240
+ f'<strong>Prepared query for {source_label}:</strong><br>'
241
+ f'<code class="lb-code">{primo_boolean}</code>'
242
+ )
243
+ block += f'<strong>Reasoning:</strong> {reasoning}<br>'
244
+ block += '<span class="lb-muted">✨ AI research tools for deeper exploration are listed at the end of this answer.</span>'
245
+ block += '</div></details>'
246
+ return block
247
+
248
+
249
+ WILEY_URL = "https://go.openathens.net/redirector/ku.ac.ae?url=https%3A%2F%2Fonlinelibrary.wiley.com"
250
+
251
+ # Emoji stand-ins for the former SVG mascots (the sanitizer drops svg elements).
252
+ _PLATFORM_ICONS = {
253
+ "primo": "📚", "leapspace": "🚀", "scopus": "🔎", "ebsco": "📘",
254
+ "consensus": "🧬", "semanticscholar": "🎓", "perplexity": "💬", "pubmed": "🏥",
255
+ }
256
+
257
+ _DB_ICONS = {
258
+ "PubMed": "🔬", "PubMed@KU": "🔬", "Embase": "🏥", "CINAHL Ultimate": "🏥",
259
+ "Cochrane Library": "🔬", "UpToDate": "🏥",
260
+ "IEEE Xplore": "💻", "ACM Digital Library": "💻",
261
+ "ScienceDirect": "🔬", "Scopus": "🔬", "Web of Science": "🔬", "SpringerLink": "📚",
262
+ "ACS Publications": "⚛️", "APS Journals": "⚛️", "Knovel": "🔧",
263
+ "Business Source Complete": "📊", "Emerald Insight": "📊",
264
+ "Taylor & Francis": "📚", "EBSCO": "📚", "Wiley Online Library": "📚",
265
+ }
266
+
267
+
268
+ def _ai_tools_footer(context):
269
+ from urllib.parse import quote as _q
270
+
271
+ ai_q = _q(context.ai_tool_query or context.display_topic or context.topic)
272
+ bool_q = context.primo_boolean_query or ""
273
+ primo_ai = PRIMO_AI_URL + ai_q
274
+ is_med = context.intent == "search_medical"
275
+ pubmed_url = _shared_build_pubmed_url(
276
+ context.topic, context.year_from, context.year_to, context.peer_reviewed,
277
+ open_access=context.open_access
278
+ ) if is_med else ""
279
+
280
+ topic_q = _q(re.sub(r"[,:;]", " ", context.display_topic or context.topic or ""))
281
+ # KU-subscribed tools first, then free tools (some ask for a free sign-in).
282
+ # Keyword engines get the topic; AI tools get the full natural-language query.
283
+ subscribed = [
284
+ ("PRIMO Research Assistant", primo_ai, "primo"),
285
+ ("LeapSpace", "https://www.sciencedirect.com/leapspace?query=" + ai_q, "leapspace"),
286
+ ("Scopus AI", _openathens_url("https://www.scopus.com/pages/ai?query=" + ai_q), "scopus"),
287
+ ]
288
+ free = [
289
+ ("Consensus", "https://consensus.app/results/?q=" + ai_q, "consensus"),
290
+ ("Semantic Scholar", "https://www.semanticscholar.org/search?q=" + ai_q + "&sort=relevance", "semanticscholar"),
291
+ ("Perplexity", "https://www.perplexity.ai/search?q=" + ai_q, "perplexity"),
292
+ ("SciSpace", "https://scispace.com/search?q=" + ai_q, "scispace"),
293
+ ("Scite", "https://scite.ai/search/citations?q=" + topic_q, "scite"),
294
+ ("OpenAlex", "https://openalex.org/works?filter=default.search:" + topic_q, "openalex"),
295
+ ("Google Scholar", "https://scholar.google.com/scholar?q=" + topic_q, "googlescholar"),
296
+ ]
297
+ if is_med and pubmed_url:
298
+ free.insert(0, ("PubMed", pubmed_url, "pubmed"))
299
+
300
+ def _btn(label, url, tone):
301
+ return (
302
+ f'<a class="kb-ai-platform-button lb-tone-{tone}" href="{_escape(url)}" '
303
+ f'target="_blank" rel="noopener noreferrer">{_escape(label)}</a>'
304
+ )
305
+
306
+ def _grid(items):
307
+ rows = ""
308
+ for k in range(0, len(items), 3):
309
+ rows += "<tr>" + "".join(f"<td>{_btn(*item)}</td>" for item in items[k:k + 3]) + "</tr>"
310
+ return f'<table class="kb-ai-platform-grid"><tbody>{rows}</tbody></table>'
311
+
312
+ platforms_html = (
313
+ '<div class="kb-ai-platform-panel">'
314
+ '<div class="kb-ai-platform-heading">Search your query across AI platforms</div>'
315
+ '<div class="kb-ai-platform-subtitle">'
316
+ 'Your query is pre-loaded. Click any platform to search instantly.</div>'
317
+ '<span class="lb-ai-arrow"></span>'
318
+ '<div class="lb-ai-groups">'
319
+ '<div class="lb-ai-group-title">KU-subscribed AI tools</div>'
320
+ + _grid(subscribed) +
321
+ '<div class="lb-ai-group-title">Free AI tools '
322
+ '<span class="lb-ai-group-note">(some ask you to sign in or create a free account)</span></div>'
323
+ + _grid(free) +
324
+ '</div></div>'
325
+ )
326
+
327
+ if bool_q:
328
+ and_count = bool_q.upper().count(" AND ")
329
+ if and_count >= 1:
330
+ bool_label = "Use this in PRIMO Advanced Search or any database for precise results:"
331
+ else:
332
+ bool_label = "Try adding synonyms with OR to find more relevant results:"
333
+ bool_html = (
334
+ '<div class="kb-boolean-query-panel">'
335
+ '<div class="kb-boolean-query-title">💡 Boolean search tip</div>'
336
+ f'<div class="lb-boolean-hint">{bool_label}</div>'
337
+ f'<code class="kb-boolean-query-text">{_escape(bool_q)}</code>'
338
+ '<div class="lb-boolean-hint">Paste into the Advanced Search box of any database below.</div>'
339
+ '</div>'
340
+ )
341
+ else:
342
+ bool_html = ""
343
+
344
+ all_lower = ((context.ai_tool_query or "") + " " + (context.topic or "")).lower()
345
+
346
+ def _db_row(name, url, desc):
347
+ icon = _DB_ICONS.get(name, "🐝")
348
+ return (
349
+ '<div class="kb-database-row">'
350
+ f'<span class="kb-database-icon">{icon}</span>'
351
+ f'<a class="kb-database-name" href="{_escape(url)}" target="_blank">{_escape(name)}</a>'
352
+ f'<span class="lb-muted"> — {_escape(desc)}</span>'
353
+ '</div>'
354
+ )
355
+
356
+ if any(k in all_lower for k in ["medicine","medical","clinical","nursing","pharmacy","health","pubmed","embase","cinahl","cochrane","uptodate"]):
357
+ db_subject = "Medicine & Health Sciences"
358
+ dbs = [
359
+ ("PubMed","https://pubmed.ncbi.nlm.nih.gov/","Core biomedical literature"),
360
+ ("Embase",_openathens_url("https://www.embase.com"),"Biomedical, drugs, devices, clinical medicine"),
361
+ ("CINAHL Ultimate",_openathens_url("https://search.ebscohost.com/login.aspx?authtype=ip,uid&profile=ehost&defaultdb=cul"),"Nursing and allied health"),
362
+ ("Cochrane Library",_openathens_url("https://www.cochranelibrary.com"),"Systematic reviews and evidence-based medicine"),
363
+ ("UpToDate",_openathens_url("https://www.uptodate.com"),"Point-of-care clinical decision support"),
364
+ ]
365
+ elif any(k in all_lower for k in ["machine learning","deep learning","artificial intelligence","neural network","computer science","software","algorithm","cybersecurity","robotics","nlp"]):
366
+ db_subject = "Computer Science & AI"
367
+ dbs = [
368
+ ("IEEE Xplore",_openathens_url("https://ieeexplore.ieee.org"),"Core CS, AI, electronics and systems"),
369
+ ("ACM Digital Library",_openathens_url("https://dl.acm.org"),"Computer science journals, proceedings and books"),
370
+ ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Full text across CS and applied computing"),
371
+ ("Scopus",_openathens_url("https://www.scopus.com"),"Discovery and citation tracking"),
372
+ ("Web of Science",_openathens_url("https://www.webofscience.com"),"Citation index"),
373
+ ("Wiley Online Library",WILEY_URL,"Wiley journals and books across science, engineering and social sciences"),
374
+ ]
375
+ elif any(k in all_lower for k in ["climate","global warming","environment","sustainability","ecology","carbon","emission","renewable","sea level","maldives","island"]):
376
+ db_subject = "Environment & Climate"
377
+ dbs = [
378
+ ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Full text across science, environment and engineering"),
379
+ ("Scopus",_openathens_url("https://www.scopus.com"),"Broad discovery and citation tracking"),
380
+ ("Web of Science",_openathens_url("https://www.webofscience.com"),"High-impact journal coverage and citation index"),
381
+ ("Wiley Online Library",WILEY_URL,"Wiley journals and books across science, engineering and social sciences"),
382
+ ("SpringerLink",_openathens_url("https://link.springer.com"),"Springer journals and books"),
383
+ ]
384
+ elif any(k in all_lower for k in ["engineering","mechanical","civil","electrical","aerospace","structural","petroleum","chemical","materials"]):
385
+ db_subject = "Engineering"
386
+ dbs = [
387
+ ("IEEE Xplore",_openathens_url("https://ieeexplore.ieee.org"),"Electrical, electronics and systems engineering"),
388
+ ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Full text across engineering disciplines"),
389
+ ("Knovel",_openathens_url("https://app.knovel.com"),"Engineering handbooks and reference data"),
390
+ ("Scopus",_openathens_url("https://www.scopus.com"),"Discovery and citation tracking"),
391
+ ("Web of Science",_openathens_url("https://www.webofscience.com"),"Citation index"),
392
+ ("Wiley Online Library",WILEY_URL,"Wiley journals and books across science, engineering and social sciences"),
393
+ ]
394
+ elif any(k in all_lower for k in ["business","management","finance","economics","leadership","marketing","strategy","entrepreneurship"]):
395
+ db_subject = "Business & Management"
396
+ dbs = [
397
+ ("Business Source Complete",_openathens_url("https://search.ebscohost.com"),"Core business and management literature"),
398
+ ("Emerald Insight",_openathens_url("https://www.emerald.com/insight"),"Management, strategy and leadership"),
399
+ ("Wiley Online Library",WILEY_URL,"Business, management and economics journals"),
400
+ ("Scopus",_openathens_url("https://www.scopus.com"),"Broad discovery and citation tracking"),
401
+ ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Business and social sciences full text"),
402
+ ]
403
+ elif any(k in all_lower for k in ["physics","chemistry","quantum","nuclear","materials science","nanotechnology","optics"]):
404
+ db_subject = "Physics, Chemistry & Materials"
405
+ dbs = [
406
+ ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Full text across physical sciences"),
407
+ ("ACS Publications",_openathens_url("https://pubs.acs.org"),"Core chemistry and chemical engineering"),
408
+ ("APS Journals",_openathens_url("https://journals.aps.org"),"American Physical Society core physics journals"),
409
+ ("Scopus",_openathens_url("https://www.scopus.com"),"Discovery and citation tracking"),
410
+ ("Web of Science",_openathens_url("https://www.webofscience.com"),"Citation index"),
411
+ ("Wiley Online Library",WILEY_URL,"Wiley journals and books across science, engineering and social sciences"),
412
+ ]
413
+ else:
414
+ db_subject = "General"
415
+ dbs = [
416
+ ("EBSCO",_openathens_url("https://search.ebscohost.com"),"Multidisciplinary full text"),
417
+ ("ScienceDirect",_openathens_url("https://www.sciencedirect.com"),"Science, engineering and medicine"),
418
+ ("SpringerLink",_openathens_url("https://link.springer.com"),"Journals and books across all disciplines"),
419
+ ("Taylor & Francis",_openathens_url("https://www.tandfonline.com"),"Humanities, social sciences and STEM"),
420
+ ("Emerald Insight",_openathens_url("https://www.emerald.com/insight"),"Management and social sciences"),
421
+ ("Scopus",_openathens_url("https://www.scopus.com"),"Citation discovery, all disciplines"),
422
+ ("Web of Science",_openathens_url("https://www.webofscience.com"),"Citation index, all disciplines"),
423
+ ("Wiley Online Library",WILEY_URL,"Wiley journals and books across science, engineering and social sciences"),
424
+ ]
425
+
426
+ dbs_html_rows = "".join(_db_row(name, url, desc) for name, url, desc in dbs)
427
+
428
+ db_section = (
429
+ '<div class="kb-database-list">'
430
+ f'<div class="lb-db-heading">📂 Recommended KU databases — {_escape(db_subject)}</div>'
431
+ + dbs_html_rows +
432
+ '<div class="lb-db-more">'
433
+ '<a href="https://library.ku.ac.ae/eresources" target="_blank">'
434
+ '🗄️ Browse the current KU resource directory →</a></div>'
435
+ '</div>'
436
+ )
437
+
438
+ filter_note = ""
439
+ if is_med and context.peer_reviewed:
440
+ filter_note += '<p><small>PubMed has no peer-review filter. Use PRIMO’s Peer Reviewed facet and verify the journal’s publication process.</small></p>'
441
+ if is_med and context.open_access:
442
+ filter_note += '<p><small>The PubMed link uses its Free full text filter; free access does not establish an open reuse licence.</small></p>'
443
+ return platforms_html + filter_note + bool_html + db_section
src/agentcore/utils.py CHANGED
@@ -132,6 +132,27 @@ OPENAI_TASK_MODELS = {
132
  }
133
 
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  def _openai_model_for(task: str) -> str:
136
  if os.getenv("LIBBEE_MODEL_PROFILE", "").strip().lower() == "legacy":
137
  return LEGACY_OPENAI_MODEL
@@ -173,7 +194,7 @@ def _get_llm(model: str, temperature: float, max_tokens: int, task: str = "answe
173
  if settings.anthropic_api_key and (model == "claude" or not settings.openai_api_key):
174
  from langchain_anthropic import ChatAnthropic
175
  return ChatAnthropic(
176
- model="claude-haiku-4-5-20251001",
177
  temperature=temperature,
178
  max_tokens=max_tokens,
179
  anthropic_api_key=settings.anthropic_api_key,
@@ -468,6 +489,11 @@ def _sanitize_boolean_for_primo(boolean: str) -> str:
468
  boolean = re.sub(r"'([^']+)'", r'"\1"', boolean)
469
  boolean = re.sub(r"^\s*(AND|OR)\s*", "", boolean, flags=re.IGNORECASE)
470
  boolean = re.sub(r"\s*(AND|OR)\s*$", "", boolean, flags=re.IGNORECASE)
 
 
 
 
 
471
  boolean = re.sub(r"\b(AND|OR)\s+(AND|OR)\b", r"\1", boolean, flags=re.IGNORECASE)
472
  return re.sub(r"\s+", " ", boolean).strip()
473
 
 
132
  }
133
 
134
 
135
+ DEFAULT_CLAUDE_MODEL = "claude-haiku-4-5-20251001"
136
+ DEFAULT_OPENAI_WEB_MODEL = "gpt-6.1-terra"
137
+
138
+
139
+ def _claude_model() -> str:
140
+ """Claude model for answers (toggle or fallback); Space variable LIBBEE_MODEL_CLAUDE."""
141
+ return os.getenv("LIBBEE_MODEL_CLAUDE", "").strip() or DEFAULT_CLAUDE_MODEL
142
+
143
+
144
+ def model_inventory() -> Dict[str, str]:
145
+ """Every model identifier the service would call right now (admin and audit view)."""
146
+ from src.services.rag_service import EMBEDDING_MODEL
147
+ inventory = {f"openai_{task}": _openai_model_for(task) for task in OPENAI_TASK_MODELS}
148
+ inventory["openai_fallback"] = LEGACY_OPENAI_MODEL
149
+ inventory["openai_web"] = os.getenv("OPENAI_WEB_MODEL", "").strip() or DEFAULT_OPENAI_WEB_MODEL
150
+ inventory["claude"] = _claude_model()
151
+ inventory["claude_web"] = os.getenv("ANTHROPIC_WEB_MODEL", "").strip() or _claude_model()
152
+ inventory["embedding"] = EMBEDDING_MODEL
153
+ return inventory
154
+
155
+
156
  def _openai_model_for(task: str) -> str:
157
  if os.getenv("LIBBEE_MODEL_PROFILE", "").strip().lower() == "legacy":
158
  return LEGACY_OPENAI_MODEL
 
194
  if settings.anthropic_api_key and (model == "claude" or not settings.openai_api_key):
195
  from langchain_anthropic import ChatAnthropic
196
  return ChatAnthropic(
197
+ model=_claude_model(),
198
  temperature=temperature,
199
  max_tokens=max_tokens,
200
  anthropic_api_key=settings.anthropic_api_key,
 
489
  boolean = re.sub(r"'([^']+)'", r'"\1"', boolean)
490
  boolean = re.sub(r"^\s*(AND|OR)\s*", "", boolean, flags=re.IGNORECASE)
491
  boolean = re.sub(r"\s*(AND|OR)\s*$", "", boolean, flags=re.IGNORECASE)
492
+ # Publication years are date filters, never search terms: drop groups that
493
+ # contain only years, e.g. "AND (2019 OR 2020)". Quoted titles are untouched.
494
+ year_group = r"\(\s*(?:19|20)\d{2}(?:\s+OR\s+(?:19|20)\d{2})*\s*\)"
495
+ boolean = re.sub(rf"\s*\b(?:AND|OR)\s+{year_group}", "", boolean, flags=re.IGNORECASE)
496
+ boolean = re.sub(rf"^\s*{year_group}\s*(?:AND|OR)\s+", "", boolean, flags=re.IGNORECASE)
497
  boolean = re.sub(r"\b(AND|OR)\s+(AND|OR)\b", r"\1", boolean, flags=re.IGNORECASE)
498
  return re.sub(r"\s+", " ", boolean).strip()
499