nikeshn commited on
Commit
1a79bfe
·
verified ·
1 Parent(s): dcbd978

Update src/agent.py

Browse files
Files changed (1) hide show
  1. src/agent.py +28 -179
src/agent.py CHANGED
@@ -1,18 +1,30 @@
1
- from fastapi import APIRouter, HTTPException, Request
 
2
  from pydantic import BaseModel
3
- from typing import List, Optional, Dict
4
  import time
5
  import os
6
  import re
7
  import json
 
8
  from datetime import datetime
9
 
10
- # Import OpenAI for classification
 
 
 
 
 
 
 
 
 
11
  try:
12
- from langchain_openai import ChatOpenAI
13
  from langchain_anthropic import ChatAnthropic
 
14
  except ImportError:
15
- pass
16
 
17
  router = APIRouter()
18
 
@@ -33,180 +45,17 @@ class AgentResponse(BaseModel):
33
  sources: List[dict] = []
34
  model_used: str = "gpt"
35
  response_time: float = 0
 
 
 
 
36
 
37
- # ========== STAFF DIRECTORY DATA (from app81.py) ==========
38
- STAFF_DIRECTORY = [
39
- {
40
- "full_name": "Dr. Abdulla Al Hefeiti",
41
- "role": "Library Director / Assistant Provost, Libraries",
42
- "details": "He can help with strategic and institutional matters, library leadership, and partnerships. Email: abdulla.alhefeiti@ku.ac.ae | Phone: +971 2 312 3331",
43
- "tokens": ["abdulla", "hefeiti", "abdulla al hefeiti", "al hefeiti"],
44
- },
45
- {
46
- "full_name": "Nikesh Narayanan",
47
- "role": "Research & Access Services Librarian",
48
- "details": "He can help with research support, Khazna institutional repository, ORCID, SciVal, Scopus, research impact, AI tools for research, bibliometrics, scholarly communication, and LibGuides. Email: nikesh.narayanan@ku.ac.ae | Phone: +971 2 312 3980",
49
- "tokens": ["nikesh", "narayanan", "nikesh narayanan"],
50
- },
51
- {
52
- "full_name": "Jason Fetty",
53
- "role": "Medical Librarian",
54
- "details": "He can help with medical and health sciences research, systematic reviews, PubMed, Embase, CINAHL, UpToDate, and clinical databases. Email: jason.fetty@ku.ac.ae | Phone: +971 2 312 4722",
55
- "tokens": ["jason", "fetty", "jason fetty"],
56
- },
57
- {
58
- "full_name": "Walter Brian Hall",
59
- "role": "Digital & Technology Services Librarian / Systems Librarian",
60
- "details": "He can help with library website, systems, technology, digital infrastructure, ORCID, STEAM, coding, Open Access publishing, APC funding, general library services, and public services. Email: walter.hall@ku.ac.ae | Phone: +971 2 312 3163",
61
- "tokens": ["walter", "brian", "hall", "walter brian hall"],
62
- },
63
- ]
64
 
65
- # ========== REGEX PATTERNS (from app81.py) ==========
66
- SOCIAL_RE = re.compile(r"^(hi|hello|hey|good morning|good afternoon|good evening|how are you|who are you|what can you do|thanks|thank you|bye|goodbye)\b", re.IGNORECASE)
67
  PURE_GREETING_RE = re.compile(r"^(hi|hello|hey|good morning|good afternoon|good evening)[!.\s]*$", re.IGNORECASE)
68
- HOURS_RE = re.compile(r"\b(library hours?|opening hours?|when.*open|when.*close|open today|closed today)\b", re.IGNORECASE)
69
- LIBRARY_CUE_RE = re.compile(r"\b(library|librarian|borrow|primo|database|article|book|ill|interlibrary|full text)\b", re.IGNORECASE)
70
- MEDICAL_KEYWORDS = ['medicine','medical','health','clinical','nursing','pharmacy','pubmed','embase']
71
-
72
- _CLASSIFIER_SYSTEM = """You are the routing brain of LibBee...""" # [Truncated for brevity - copy from app81.py lines ~875-915]
73
-
74
- # ========== HELPER FUNCTIONS ==========
75
- def _normalize_name_query(text: str):
76
- return [t for t in re.sub(r"[^a-z0-9 ]+", " ", (text or "").lower()).split() if t]
77
-
78
- def _match_staff_name(question: str) -> Optional[Dict]:
79
- tokens = _normalize_name_query(question)
80
- if not tokens:
81
- return None
82
- for staff in STAFF_DIRECTORY:
83
- staff_tokens = set()
84
- for tok in staff.get("tokens", []):
85
- staff_tokens.update(_normalize_name_query(tok))
86
- if all(tok in staff_tokens for tok in tokens):
87
- return staff
88
- return None
89
-
90
- def _staff_name_answer(staff: dict) -> str:
91
- return f"Did you mean <strong>{staff['full_name']}</strong>?<br><br><strong>{staff['full_name']}</strong> is the <strong>{staff['role']}</strong>. {staff['details']}"
92
-
93
- def _looks_library_hours_question(question: str) -> bool:
94
- return bool(HOURS_RE.search(question.lower()))
95
-
96
- def _hours_redirect_answer() -> str:
97
- return """
98
- Here are the current <strong>Khalifa University Library</strong> hours:<br><br>
99
- <strong>Habshan Library (SAN Campus):</strong><br>
100
- Sunday – Wednesday: 8:00 AM – 7:00 PM<br>
101
- Thursday: 8:00 AM – 4:00 PM<br>
102
- Friday: Closed<br>
103
- Saturday: 12:00 PM – 8:00 PM<br><br>
104
- ⚠️ Check official page for latest times: <a href="https://library.ku.ac.ae/hours">library.ku.ac.ae/hours</a>
105
- """
106
-
107
- async def _llm_classify(question: str, history: list, model: str = "gpt"):
108
- """Copy this function from app81.py lines ~918-960"""
109
- # Simplified version for now:
110
- q = question.lower()
111
- if SOCIAL_RE.match(q):
112
- return {"intent": "social", "casual_answer": "Hello! I'm LibBee, the KU Library AI Assistant."}
113
- elif any(k in q for k in MEDICAL_KEYWORDS):
114
- return {"intent": "search_medical"}
115
- elif LIBRARY_CUE_RE.search(q):
116
- return {"intent": "library_info"}
117
- else:
118
- return {"intent": "general"}
119
-
120
- # ========== MAIN ENDPOINT ==========
121
- @router.post("", response_model=AgentResponse)
122
- async def agent_query(request: Request, req: AgentRequest):
123
- start = time.time()
124
-
125
- question = req.question.strip()
126
-
127
- # 1. Instant handlers (from app81.py Layer 0)
128
-
129
- # Staff name match
130
- staff_match = _match_staff_name(question)
131
- if staff_match:
132
- return AgentResponse(
133
- answer=_staff_name_answer(staff_match),
134
- intent="library_info",
135
- tools_used=["staff_name_match"],
136
- model_used=req.model,
137
- response_time=time.time() - start
138
- )
139
-
140
- # Hours question
141
- if _looks_library_hours_question(question):
142
- return AgentResponse(
143
- answer=_hours_redirect_answer(),
144
- intent="library_info",
145
- tools_used=["hours_hardcoded"],
146
- model_used=req.model,
147
- response_time=time.time() - start
148
- )
149
-
150
- # Greeting
151
- if PURE_GREETING_RE.match(question):
152
- return AgentResponse(
153
- answer="Hi! I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant. I can help you find articles and books, search databases, and answer library questions. What would you like help with?",
154
- intent="social_greeting",
155
- tools_used=[],
156
- model_used=req.model,
157
- response_time=time.time() - start
158
- )
159
-
160
- # 2. LLM Classification (Layer 1)
161
- try:
162
- classification = await _llm_classify(question, req.history, req.model)
163
- intent = classification.get("intent", "general")
164
-
165
- # 3. Route by intent
166
- if intent == "social":
167
- return AgentResponse(
168
- answer=classification.get("casual_answer", "Hello! How can I help?"),
169
- intent="social",
170
- model_used=req.model,
171
- response_time=time.time() - start
172
- )
173
-
174
- elif intent == "library_info":
175
- # For now, return generic library info response
176
- # Later: Add RAG here
177
- return AgentResponse(
178
- answer="I can help with library information. This is where your RAG logic will go.",
179
- intent="library_info",
180
- tools_used=["get_library_info"],
181
- model_used=req.model,
182
- response_time=time.time() - start
183
- )
184
-
185
- elif intent in ["search_academic", "search_medical"]:
186
- return AgentResponse(
187
- answer=f"I'll help you search for {'medical' if intent == 'search_medical' else 'academic'} literature on: {question}",
188
- intent=intent,
189
- tools_used=["search_primo"],
190
- model_used=req.model,
191
- response_time=time.time() - start
192
- )
193
-
194
- else:
195
- return AgentResponse(
196
- answer="I'm the KU Library AI Assistant. I can help you find articles, books, and answer library questions.",
197
- intent="general",
198
- model_used=req.model,
199
- response_time=time.time() - start
200
- )
201
-
202
- except Exception as e:
203
- return AgentResponse(
204
- answer=f"Error processing request: {str(e)}",
205
- intent="error",
206
- model_used=req.model,
207
- response_time=time.time() - start
208
- )
209
-
210
- @router.get("/test")
211
- async def test():
212
- return {"status": "ok", "message": "Agent is working!"}
 
1
+ from fastapi import APIRouter, HTTPException, Request, Response
2
+ from fastapi.responses import JSONResponse
3
  from pydantic import BaseModel
4
+ from typing import List, Optional, Dict, Any
5
  import time
6
  import os
7
  import re
8
  import json
9
+ import secrets
10
  from datetime import datetime
11
 
12
+ # Import services
13
+ from src.config import get_settings
14
+ from src.services.cache_service import CacheService
15
+ from src.services.staff_service import (
16
+ match_staff_name, match_staff_role, staff_name_answer, staff_role_answer,
17
+ build_staff_index, STAFF_DIRECTORY
18
+ )
19
+ from src.services.rag_service import RAGService
20
+
21
+ # Try to import LLM libraries
22
  try:
23
+ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
24
  from langchain_anthropic import ChatAnthropic
25
+ LLM_AVAILABLE = True
26
  except ImportError:
27
+ LLM_AVAILABLE = False
28
 
29
  router = APIRouter()
30
 
 
45
  sources: List[dict] = []
46
  model_used: str = "gpt"
47
  response_time: float = 0
48
+ corrected_query: Optional[str] = None
49
+ natural_query: Optional[str] = None
50
+ database_query: Optional[str] = None
51
+ ask_librarian: Optional[bool] = None
52
 
53
+ # ========== CONSTANTS FROM APP81.PY ==========
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ # Regex patterns
56
+ SOCIAL_RE = re.compile(r"^(hi|hello|hey|good morning|good afternoon|good evening|how are you|hows it going|how are you doing|who are you|what are you|tell me about yourself|what can you do|what do you do|how can you help|what help can you provide|are you a bot|are you a robot|are you ai|are you an ai|thank you|thanks|thx|bye|goodbye|see you|lol|haha|you are silly|are you silly|are you dumb|stupid bot|dumb bot|idiot bot|joke|tell me a joke)\b", re.IGNORECASE)
57
  PURE_GREETING_RE = re.compile(r"^(hi|hello|hey|good morning|good afternoon|good evening)[!.\s]*$", re.IGNORECASE)
58
+ GREETING_FOLLOWUP_RE = re.compile(r"^(yes|yes please|yes check|sure|okay|ok|yeah|yep|please do|go ahead)$", re.IGNORECASE)
59
+ HOURS_RE = re.compile(r"\b(library hours?|opening hours?|closing hours?|open hours?|open today|open tomorrow|open now|open on|open this|closed today|closed tomorrow|closed on|closed this|when.*open|when.*close|when.*does.*library|what time.*open|what time.*close|what time.*library|opening time|closing time|is.*library.*open|is.*campus.*library|is.*habshan.*open|is.*san.*open|is.*library.*closed|will.*library.*open|will.*it.*open|does.*library.*open|library.*open.*today|library.*close.*today|habshan.*open|san.*open|main campus.*open|ramadan hours?|weekend hours?|friday hours?|saturday hours?|sunday hours?|library.*schedule|schedule.*library|what.*hours|till.*when|until.*when|what day.*open|which day.*open|what day.*closed|which day.*closed)\b", re.IGNORECASE)
60
+ KU_CAMPUS_RE = re.compile(r"\b(where is the library|where is.*library|library.*location|location.*library|which building|what building|which floor|main campus library|san campus library|habshan library|sas al nakhl library|library.*address|address.*library|how to get to.*library|how.*reach.*library|how.*find.*library|library.*campus(es)?|campus(es)?.*library|how many.*librar|how many.*branch|library.*branch(es)?|branch(es)?.*library|which campus.*library|library.*which campus|library.*map|map.*library|how many libraries|what libraries|which libraries|(ku|khalifa).*(has|have|got).*(librar|branch)|(librar|branch).*(ku|khalifa).*(has|have)|(all|both|two|2).*(libraries|library|branches)|tell me about.*(campus|libraries|branches)|describe.*(campus|libraries)|(what|where).*(campus|campuses).*(librar))\b", re.IGNORECASE)
61
+ RESEARCH_CUE_RE = re.compile(r"\b(find|search|look for|show me|get me|give me|locate|recommend|suggest|articles?|papers?|books?|journals?|studies|literature|research|systematic review|evidence|sources|database|databases|peer reviewed|open access|advances?|approach(es)?|method(s|ology)?|*