Update src/api/agent.py
Browse files- src/api/agent.py +54 -5
src/api/agent.py
CHANGED
|
@@ -390,6 +390,31 @@ Respond ONLY with valid JSON. No preamble, no markdown fences.
|
|
| 390 |
|
| 391 |
# ββ Utilities βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 392 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
def _escape(text: str) -> str:
|
| 394 |
return html.escape(text or "")
|
| 395 |
|
|
@@ -711,6 +736,10 @@ async def _libbee_casual_response(question: str, history: List[ChatMessage], mod
|
|
| 711 |
"Respond warmly and naturally in 1-3 sentences as a friendly librarian. "
|
| 712 |
"No markdown, no bullet points."
|
| 713 |
)}]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 714 |
msgs.extend(_build_history_messages(history))
|
| 715 |
msgs.append({"role": "user", "content": question})
|
| 716 |
response = await llm.ainvoke(msgs)
|
|
@@ -732,6 +761,10 @@ async def _rag_answer(question: str, rag_results: List[dict], history: List[Chat
|
|
| 732 |
"Never invent facts or URLs.\n\n"
|
| 733 |
f"CONTEXT:\n{context}"
|
| 734 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 735 |
try:
|
| 736 |
llm = _get_llm(model, temperature=0.2, max_tokens=380)
|
| 737 |
msgs = [{"role": "system", "content": system}]
|
|
@@ -759,6 +792,10 @@ async def _llm_general_answer(question: str, history: List[ChatMessage], model:
|
|
| 759 |
"Answer factually and concisely in 3-5 sentences. Use HTML <br> for line breaks. "
|
| 760 |
"KU means Khalifa University. If the topic is academic, briefly offer to help find library resources."
|
| 761 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 762 |
try:
|
| 763 |
llm = _get_llm(model, temperature=0.3, max_tokens=360)
|
| 764 |
msgs = [{"role": "system", "content": system}]
|
|
@@ -2514,7 +2551,7 @@ async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple
|
|
| 2514 |
import asyncio as _asyncio
|
| 2515 |
topic = context.topic
|
| 2516 |
references: List[dict] = []
|
| 2517 |
-
papers = await _openalex_search(context.ai_tool_query or context.topic, limit=8)
|
| 2518 |
if not papers:
|
| 2519 |
logger.info(f"OpenAlex returned nothing for '{topic}' β trying Semantic Scholar")
|
| 2520 |
papers = await _semantic_scholar_search(topic, limit=8)
|
|
@@ -2924,7 +2961,7 @@ async def _run_search_mode(
|
|
| 2924 |
r["_source"] = "PubMed"
|
| 2925 |
else:
|
| 2926 |
# PRIMO API removed β OpenAlex for articles, PRIMO link shown to user
|
| 2927 |
-
oa_papers = await _openalex_search(context.ai_tool_query or context.topic, limit=8) if use_openalex else []
|
| 2928 |
source_name, source_url = "openalex", _primo_clean_url(context)
|
| 2929 |
search_results, total = [], 0
|
| 2930 |
# Tag OpenAlex results
|
|
@@ -3044,6 +3081,16 @@ async def agent_query(request: Request, req: AgentRequest):
|
|
| 3044 |
_safe_metrics_increment("agent_requests")
|
| 3045 |
response = await _agent_query_inner(question, history, model, client_state, start_time)
|
| 3046 |
_log_agent_query(question, response, start_time)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3047 |
return response
|
| 3048 |
|
| 3049 |
|
|
@@ -3070,9 +3117,11 @@ async def _agent_query_inner(
|
|
| 3070 |
follow_up_question, follow_up_suggestions = _social_follow_up()
|
| 3071 |
return AgentResponse(
|
| 3072 |
answer=(
|
| 3073 |
-
|
| 3074 |
-
|
| 3075 |
-
|
|
|
|
|
|
|
| 3076 |
+ _source_badge("libbee")
|
| 3077 |
),
|
| 3078 |
intent="social_greeting",
|
|
|
|
| 390 |
|
| 391 |
# ββ Utilities βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 392 |
|
| 393 |
+
|
| 394 |
+
# ββ Runtime config helper ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 395 |
+
|
| 396 |
+
def _get_runtime_config() -> dict:
|
| 397 |
+
"""
|
| 398 |
+
Load the admin runtime config (welcome_message, custom_instructions,
|
| 399 |
+
announcement, max_results, maintenance_mode) from the JsonRuntimeStore.
|
| 400 |
+
Returns defaults silently if the file does not exist yet.
|
| 401 |
+
"""
|
| 402 |
+
try:
|
| 403 |
+
from src.services.runtime_store import JsonRuntimeStore
|
| 404 |
+
settings = get_settings()
|
| 405 |
+
store = JsonRuntimeStore(settings.config_path, default={
|
| 406 |
+
"max_results": 5,
|
| 407 |
+
"maintenance_mode": False,
|
| 408 |
+
"welcome_message": "",
|
| 409 |
+
"custom_instructions": "",
|
| 410 |
+
"announcement": "",
|
| 411 |
+
"maintenance_message": "",
|
| 412 |
+
})
|
| 413 |
+
return store.load()
|
| 414 |
+
except Exception:
|
| 415 |
+
return {}
|
| 416 |
+
|
| 417 |
+
|
| 418 |
def _escape(text: str) -> str:
|
| 419 |
return html.escape(text or "")
|
| 420 |
|
|
|
|
| 736 |
"Respond warmly and naturally in 1-3 sentences as a friendly librarian. "
|
| 737 |
"No markdown, no bullet points."
|
| 738 |
)}]
|
| 739 |
+
_cfg = _get_runtime_config()
|
| 740 |
+
_ci = _cfg.get("custom_instructions", "").strip()
|
| 741 |
+
if _ci:
|
| 742 |
+
msgs[0]["content"] += " " + _ci
|
| 743 |
msgs.extend(_build_history_messages(history))
|
| 744 |
msgs.append({"role": "user", "content": question})
|
| 745 |
response = await llm.ainvoke(msgs)
|
|
|
|
| 761 |
"Never invent facts or URLs.\n\n"
|
| 762 |
f"CONTEXT:\n{context}"
|
| 763 |
)
|
| 764 |
+
_cfg = _get_runtime_config()
|
| 765 |
+
_ci = _cfg.get("custom_instructions", "").strip()
|
| 766 |
+
if _ci:
|
| 767 |
+
system += "\n\nAdditional instructions: " + _ci
|
| 768 |
try:
|
| 769 |
llm = _get_llm(model, temperature=0.2, max_tokens=380)
|
| 770 |
msgs = [{"role": "system", "content": system}]
|
|
|
|
| 792 |
"Answer factually and concisely in 3-5 sentences. Use HTML <br> for line breaks. "
|
| 793 |
"KU means Khalifa University. If the topic is academic, briefly offer to help find library resources."
|
| 794 |
)
|
| 795 |
+
_cfg = _get_runtime_config()
|
| 796 |
+
_ci = _cfg.get("custom_instructions", "").strip()
|
| 797 |
+
if _ci:
|
| 798 |
+
system += " " + _ci
|
| 799 |
try:
|
| 800 |
llm = _get_llm(model, temperature=0.3, max_tokens=360)
|
| 801 |
msgs = [{"role": "system", "content": system}]
|
|
|
|
| 2551 |
import asyncio as _asyncio
|
| 2552 |
topic = context.topic
|
| 2553 |
references: List[dict] = []
|
| 2554 |
+
papers = await _openalex_search(context.ai_tool_query or context.topic, limit=max(3, min(10, _get_runtime_config().get("max_results", 8))))
|
| 2555 |
if not papers:
|
| 2556 |
logger.info(f"OpenAlex returned nothing for '{topic}' β trying Semantic Scholar")
|
| 2557 |
papers = await _semantic_scholar_search(topic, limit=8)
|
|
|
|
| 2961 |
r["_source"] = "PubMed"
|
| 2962 |
else:
|
| 2963 |
# PRIMO API removed β OpenAlex for articles, PRIMO link shown to user
|
| 2964 |
+
oa_papers = await _openalex_search(context.ai_tool_query or context.topic, limit=max(3, min(10, _get_runtime_config().get("max_results", 8)))) if use_openalex else []
|
| 2965 |
source_name, source_url = "openalex", _primo_clean_url(context)
|
| 2966 |
search_results, total = [], 0
|
| 2967 |
# Tag OpenAlex results
|
|
|
|
| 3081 |
_safe_metrics_increment("agent_requests")
|
| 3082 |
response = await _agent_query_inner(question, history, model, client_state, start_time)
|
| 3083 |
_log_agent_query(question, response, start_time)
|
| 3084 |
+
# Append announcement banner if set in admin config
|
| 3085 |
+
_rcfg = _get_runtime_config()
|
| 3086 |
+
_ann = _rcfg.get("announcement", "").strip()
|
| 3087 |
+
if _ann and response.intent not in ("social_greeting", "social"):
|
| 3088 |
+
_ann_html = (
|
| 3089 |
+
'<div style="margin-top:14px;padding:10px 14px;border-radius:10px;'
|
| 3090 |
+
'background:#fffbeb;border:1px solid #fde68a;font-size:.82rem;color:#92400e">'
|
| 3091 |
+
f'π’ {_ann}</div>'
|
| 3092 |
+
)
|
| 3093 |
+
response.answer = response.answer + _ann_html
|
| 3094 |
return response
|
| 3095 |
|
| 3096 |
|
|
|
|
| 3117 |
follow_up_question, follow_up_suggestions = _social_follow_up()
|
| 3118 |
return AgentResponse(
|
| 3119 |
answer=(
|
| 3120 |
+
(lambda _c: _c.get("welcome_message") or (
|
| 3121 |
+
"Hi! I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant.<br><br>"
|
| 3122 |
+
"I can help you find articles and books, search databases, access full text, "
|
| 3123 |
+
"request Interlibrary Loan (ILL), and answer questions about library services and staff."
|
| 3124 |
+
))(_get_runtime_config())
|
| 3125 |
+ _source_badge("libbee")
|
| 3126 |
),
|
| 3127 |
intent="social_greeting",
|