Update src/api/agent.py
Browse files389 unmodified lines390391392393394395315 unmodified lines71171271371471571615 unmodified lines73273373473573673721 unmodified lines7597607617627637641749 unmodified lines2514251525162517251825192520403 unmodified lines2924292529262927292829292930113 unmodified lines30443045304630473048304920 unmodified lines307030713072307330743075307630773078389 unmodified lines# ββ Utilities βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _escape(text: str) -> str:return html.escape(text or "")315 unmodified lines"Respond warmly and naturally in 1-3 sentences as a friendly librarian. ""No markdown, no bullet points.")}]msgs.extend(_build_history_messages(history))msgs.append({"role": "user", "content": question})response = await llm.ainvoke(msgs)15 unmodified lines"Never invent facts or URLs.\n\n"f"CONTEXT:\n{context}")try:llm = _get_llm(model, temperature=0.2, max_tokens=380)msgs = [{"role": "system", "content": system}]21 unmodified lines"Answer factually and concisely in 3-5 sentences. Use HTML <br> for line breaks. ""KU means Khalifa University. If the topic is academic, briefly offer to help find library resources.")try:llm = _get_llm(model, temperature=0.3, max_tokens=360)msgs = [{"role": "system", "content": system}]1749 unmodified linesimport asyncio as _asynciotopic = context.topicreferences: List[dict] = []papers = await _openalex_search(context.ai_tool_query or context.topic, limit=8)if not papers:logger.info(f"OpenAlex returned nothing for '{topic}' β trying Semantic Scholar")papers = await _semantic_scholar_search(topic, limit=8)403 unmodified linesr["_source"] = "PubMed"else:# PRIMO API removed β OpenAlex for articles, PRIMO link shown to useroa_papers = await _openalex_search(context.ai_tool_query or context.topic, limit=8) if use_openalex else []source_name, source_url = "openalex", _primo_clean_url(context)search_results, total = [], 0# Tag OpenAlex results113 unmodified lines_safe_metrics_increment("agent_requests")response = await _agent_query_inner(question, history, model, client_state, start_time)_log_agent_query(question, response, start_time)return response20 unmodified linesfollow_up_question, follow_up_suggestions = _social_follow_up()return AgentResponse(answer=("Hi! I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant.<br><br>""I can help you find articles and books, search databases, access full text, request Interlibrary Loan (ILL), ""and answer questions about library services and staff."+ _source_badge("libbee")),intent="social_greeting",389 unmodified lines390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420315 unmodified lines73673773873974074174274374474515 unmodified lines76176276376476576676776876977021 unmodified lines7927937947957967977987998008011749 unmodified lines2551255225532554255525562557403 unmodified lines2961296229632964296529662967113 unmodified lines308130823083308430853086308730883089309030913092309330943095309620 unmodified lines31173118311931203121312231233124312531263127389 unmodified lines# ββ Utilities βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# ββ Runtime config helper ββββββββββββββββββββββββββββββββββββββββββββββββββββdef _get_runtime_config() -> dict:"""Load the admin runtime config (welcome_message, custom_instructions,announcement, max_results, maintenance_mode) from the JsonRuntimeStore.Returns defaults silently if the file does not exist yet."""try:from src.services.runtime_store import JsonRuntimeStoresettings = get_settings()store = JsonRuntimeStore(settings.config_path, default={"max_results": 5,"maintenance_mode": False,"welcome_message": "","custom_instructions": "","announcement": "","maintenance_message": "",})return store.load()except Exception:return {}def _escape(text: str) -> str:return html.escape(text or "")315 unmodified lines"Respond warmly and naturally in 1-3 sentences as a friendly librarian. ""No markdown, no bullet points.")}]_cfg = _get_runtime_config()_ci = _cfg.get("custom_instructions", "").strip()if _ci:msgs[0]["content"] += " " + _cimsgs.extend(_build_history_messages(history))msgs.append({"role": "user", "content": question})response = await llm.ainvoke(msgs)15 unmodified lines"Never invent facts or URLs.\n\n"f"CONTEXT:\n{context}")_cfg = _get_runtime_config()_ci = _cfg.get("custom_instructions", "").strip()if _ci:system += "\n\nAdditional instructions: " + _citry:llm = _get_llm(model, temperature=0.2, max_tokens=380)msgs = [{"role": "system", "content": system}]21 unmodified lines"Answer factually and concisely in 3-5 sentences. Use HTML <br> for line breaks. ""KU means Khalifa University. If the topic is academic, briefly offer to help find library resources.")_cfg = _get_runtime_config()_ci = _cfg.get("custom_instructions", "").strip()if _ci:system += " " + _citry:llm = _get_llm(model, temperature=0.3, max_tokens=360)msgs = [{"role": "system", "content": system}]1749 unmodified linesimport asyncio as _asynciotopic = context.topicreferences: List[dict] = []papers = await _openalex_search(context.ai_tool_query or context.topic, limit=max(3, min(10, _get_runtime_config().get("max_results", 8))))if not papers:logger.info(f"OpenAlex returned nothing for '{topic}' β trying Semantic Scholar")papers = await _semantic_scholar_search(topic, limit=8)403 unmodified linesr["_source"] = "PubMed"else:# PRIMO API removed β OpenAlex for articles, PRIMO link shown to useroa_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 []source_name, source_url = "openalex", _primo_clean_url(context)search_results, total = [], 0# Tag OpenAlex results113 unmodified lines_safe_metrics_increment("agent_requests")response = await _agent_query_inner(question, history, model, client_state, start_time)_log_agent_query(question, response, start_time)# Append announcement banner if set in admin config_rcfg = _get_runtime_config()_ann = _rcfg.get("announcement", "").strip()if _ann and response.intent not in ("social_greeting", "social"):_ann_html = ('<div style="margin-top:14px;padding:10px 14px;border-radius:10px;''background:#fffbeb;border:1px solid #fde68a;font-size:.82rem;color:#92400e">'f'π’ {_ann}</div>')response.answer = response.answer + _ann_htmlreturn response20 unmodified linesfollow_up_question, follow_up_suggestions = _social_follow_up()return AgentResponse(answer=((lambda _c: _c.get("welcome_message") or ("Hi! I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant.<br><br>""I can help you find articles and books, search databases, access full text, ""request Interlibrary Loan (ILL), and answer questions about library services and staff."))(_get_runtime_config())+ _source_badge("libbee")),intent="social_greeting",
src/api/agent.py+54-5