Adam Cseresznye commited on
Commit
ddda2b6
·
1 Parent(s): 41c5b98

Refactor ranking agent to hybrid multi-stage model

Browse files
agents/quality_gate.py CHANGED
@@ -30,7 +30,6 @@ def validate_quality(
30
  - Minimum paper count (>=25)
31
  - Embedding coverage (>=60% have SPECTER2 embeddings)
32
  - Abstract coverage (>=60% have abstracts)
33
- - Median semantic similarity (>=0.75 against query embedding) [Week 2+ only]
34
 
35
  Args:
36
  papers: List of paper dictionaries from Semantic Scholar API.
@@ -40,7 +39,7 @@ def validate_quality(
40
  Returns:
41
  Dict with keys:
42
  - passed: bool indicating if all criteria met
43
- - metrics: Dict with paper_count, embedding_coverage, abstract_coverage, median_similarity
44
  - reason: Human-readable explanation (empty string if passed)
45
 
46
  Raises:
@@ -56,11 +55,10 @@ def validate_quality(
56
  # Log metrics for monitoring
57
  logger.info(
58
  "Quality gate metrics computed: paper_count={}, embedding_coverage={:.2%}, "
59
- "abstract_coverage={:.2%}, median_similarity={:.3f}",
60
  metrics["paper_count"],
61
  metrics["embedding_coverage"],
62
  metrics["abstract_coverage"],
63
- metrics["median_similarity"],
64
  )
65
 
66
  # Check against thresholds
@@ -123,7 +121,7 @@ def _compute_metrics(papers: List[Dict], query_embedding: np.ndarray) -> Dict:
123
  for p in papers:
124
  emb_dict = p.get("embedding")
125
  if emb_dict is not None and isinstance(emb_dict, dict):
126
- emb = emb_dict.get("specter_v2")
127
  if emb is not None and isinstance(emb, (list, np.ndarray)):
128
  try:
129
  emb_array = np.array(emb, dtype=np.float32)
@@ -139,44 +137,13 @@ def _compute_metrics(papers: List[Dict], query_embedding: np.ndarray) -> Dict:
139
  embedding_count = len(embeddings)
140
  embedding_coverage = embedding_count / paper_count if paper_count > 0 else 0.0
141
 
142
- # Compute median similarity
143
- median_similarity = _compute_median_similarity(embeddings, query_embedding)
144
-
145
  return {
146
  "paper_count": paper_count,
147
  "embedding_coverage": embedding_coverage,
148
  "abstract_coverage": abstract_coverage,
149
- "median_similarity": median_similarity,
150
  }
151
 
152
 
153
- def _compute_median_similarity(
154
- embeddings: List[np.ndarray], query_embedding: np.ndarray | None
155
- ) -> float:
156
- """Compute median cosine similarity between paper embeddings and query embedding.
157
-
158
- Uses NumPy vectorized operations for performance. Handles empty embeddings gracefully.
159
- For Week 1: Returns 1.0 if query_embedding is None (skips semantic similarity check).
160
- """
161
- if query_embedding is None:
162
- # Week 1: No local embedding model, skip semantic similarity check
163
- return 1.0
164
-
165
- if not embeddings:
166
- return 0.0
167
-
168
- # Stack embeddings into 2D array for batch computation
169
- emb_array = np.stack(embeddings) # Shape: (n_embeddings, 384)
170
-
171
- # Compute cosine similarities (dot product since SPECTER2 embeddings are normalized)
172
- similarities = np.dot(emb_array, query_embedding) # Shape: (n_embeddings,)
173
-
174
- # Clip to valid cosine range for safety
175
- similarities = np.clip(similarities, -1.0, 1.0)
176
-
177
- return float(np.median(similarities))
178
-
179
-
180
  def _check_thresholds(metrics: Dict) -> Tuple[bool, str]:
181
  """Check metrics against quality thresholds and return pass/fail with reason."""
182
  thresholds = {
@@ -191,12 +158,6 @@ def _check_thresholds(metrics: Dict) -> Tuple[bool, str]:
191
  0.6,
192
  "low abstract coverage ({value:.2%} < {threshold:.0%})",
193
  ),
194
- # Week 1: median_similarity always 1.0 (query_embedding is None)
195
- # Week 2+: will use 0.75 threshold with local embeddings
196
- "median_similarity": (
197
- 0.75,
198
- "low median similarity ({value:.3f} < {threshold:.3f})",
199
- ),
200
  }
201
 
202
  failures = []
 
30
  - Minimum paper count (>=25)
31
  - Embedding coverage (>=60% have SPECTER2 embeddings)
32
  - Abstract coverage (>=60% have abstracts)
 
33
 
34
  Args:
35
  papers: List of paper dictionaries from Semantic Scholar API.
 
39
  Returns:
40
  Dict with keys:
41
  - passed: bool indicating if all criteria met
42
+ - metrics: Dict with paper_count, embedding_coverage, abstract_coverage
43
  - reason: Human-readable explanation (empty string if passed)
44
 
45
  Raises:
 
55
  # Log metrics for monitoring
56
  logger.info(
57
  "Quality gate metrics computed: paper_count={}, embedding_coverage={:.2%}, "
58
+ "abstract_coverage={:.2%}",
59
  metrics["paper_count"],
60
  metrics["embedding_coverage"],
61
  metrics["abstract_coverage"],
 
62
  )
63
 
64
  # Check against thresholds
 
121
  for p in papers:
122
  emb_dict = p.get("embedding")
123
  if emb_dict is not None and isinstance(emb_dict, dict):
124
+ emb = emb_dict.get("specter")
125
  if emb is not None and isinstance(emb, (list, np.ndarray)):
126
  try:
127
  emb_array = np.array(emb, dtype=np.float32)
 
137
  embedding_count = len(embeddings)
138
  embedding_coverage = embedding_count / paper_count if paper_count > 0 else 0.0
139
 
 
 
 
140
  return {
141
  "paper_count": paper_count,
142
  "embedding_coverage": embedding_coverage,
143
  "abstract_coverage": abstract_coverage,
 
144
  }
145
 
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  def _check_thresholds(metrics: Dict) -> Tuple[bool, str]:
148
  """Check metrics against quality thresholds and return pass/fail with reason."""
149
  thresholds = {
 
158
  0.6,
159
  "low abstract coverage ({value:.2%} < {threshold:.0%})",
160
  ),
 
 
 
 
 
 
161
  }
162
 
163
  failures = []
agents/ranking_agent.py CHANGED
@@ -1,120 +1,304 @@
1
  """Ranking agent for scoring and ranking Semantic Scholar papers.
2
 
3
- Provides multi-factor paper ranking combining semantic similarity, authority,
4
- impact, and recency factors. Returns top 5-10 finalist papers for downstream
5
- PDF processing.
6
-
7
- Usage example:
8
- from agents.ranking_agent import RankingAgent
9
- import numpy as np
10
-
11
- agent = RankingAgent()
12
- papers = [...] # List of paper dicts from Semantic Scholar
13
- query_embedding = np.random.rand(768) # SPECTER2 embedding (768D)
14
-
15
- input_data = {"papers": papers, "query_embedding": query_embedding}
16
- finalists = agent.rank_papers(input_data)
17
-
18
- # Composite scoring formula:
19
- # semantic = cosine_similarity(query_embedding, paper_embedding)
20
- # authority = log(1 + influential_citations) / log(1 + max_influential_citations)
21
- # impact = log(1 + total_citations) / log(1 + max_total_citations)
22
- # recency = (year - 2015) / (2025 - 2015) # Linear normalization
23
- # composite_score = 0.4 * semantic + 0.3 * authority + 0.2 * impact + 0.1 * recency
24
  """
25
 
26
  from typing import Dict, List, Any
27
  import numpy as np
 
 
 
 
 
 
28
  from loguru import logger
29
  from datetime import date
30
 
 
 
 
 
 
 
31
 
32
- class RankingAgent:
33
- """Agent that ranks Semantic Scholar papers using composite scoring.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- Combines four factors with weights:
36
- - Semantic similarity (40%): SPECTER2 cosine similarity
37
- - Authority (30%): Log-normalized influential citations
38
- - Impact (20%): Log-normalized total citations
39
- - Recency (10%): Linear normalization 2015-2025
40
 
41
- Returns top 5-10 papers sorted by composite score descending.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  """
43
 
44
- def rank_papers(self, input_data: Dict[str, Any]) -> List[Dict[str, Any]]:
45
- """Rank papers using composite scoring algorithm.
 
 
46
 
47
  Args:
48
- input_data: Dict with keys:
49
- - papers: List[Dict] of Semantic Scholar papers
50
- - query_embedding: np.ndarray (384D or 768D SPECTER/SPECTER2 embedding)
51
 
52
  Returns:
53
- List[Dict]: Top 5-10 papers with added score fields:
54
- - composite_score: float (0.0-1.0)
55
- - semantic_score: float (0.0-1.0)
56
- - authority_score: float (0.0-1.0)
57
- - impact_score: float (0.0-1.0)
58
- - recency_score: float (0.0-1.0)
59
- Plus all original paper fields.
60
-
61
- Raises:
62
- ValueError: If inputs are invalid.
63
  """
64
- papers = input_data.get("papers", [])
65
- query_embedding = input_data.get("query_embedding")
66
-
67
- self._validate_inputs(papers, query_embedding)
 
68
 
69
  if not papers:
70
  logger.warning("No papers provided for ranking")
71
  return []
72
 
73
- # Compute all sub-scores
74
- semantic_scores = self._compute_semantic_scores(papers, query_embedding)
75
- authority_scores = self._compute_authority_scores(papers)
76
- impact_scores = self._compute_impact_scores(papers)
77
- recency_scores = self._compute_recency_scores(papers)
78
-
79
- # Combine into composite scores
80
- composite_scores = self._compute_composite_scores(
81
- semantic_scores, authority_scores, impact_scores, recency_scores
82
  )
83
 
84
- # Add scores to papers and sort
85
- scored_papers = []
86
- for i, paper in enumerate(papers):
87
- scored_paper = paper.copy()
88
- scored_paper.update(
89
- {
90
- "composite_score": float(composite_scores[i]),
91
- "semantic_score": float(semantic_scores[i]),
92
- "authority_score": float(authority_scores[i]),
93
- "impact_score": float(impact_scores[i]),
94
- "recency_score": float(recency_scores[i]),
95
- }
96
- )
97
- scored_papers.append(scored_paper)
98
-
99
- # Sort by composite score descending and take top 5-10
100
- scored_papers.sort(key=lambda p: p["composite_score"], reverse=True)
101
- finalists = scored_papers[:10] # Take up to 10, but at least 5 if available
102
-
103
- # Log statistics
104
- logger.debug(
105
- "Composite scores: min={:.3f}, max={:.3f}, mean={:.3f}",
106
- float(composite_scores.min()),
107
- float(composite_scores.max()),
108
- float(composite_scores.mean()),
109
  )
110
 
111
- # Log top 3 paper titles
 
 
 
 
 
 
 
 
112
  top_titles = [p.get("title", "Unknown") for p in finalists[:3]]
113
  logger.info(
114
- "Top 3 ranked papers: 1. '{}', 2. '{}', 3. '{}'",
115
- top_titles[0] if len(top_titles) > 0 else "None",
116
- top_titles[1] if len(top_titles) > 1 else "None",
117
- top_titles[2] if len(top_titles) > 2 else "None",
 
 
 
118
  )
119
 
120
  logger.info(
@@ -125,208 +309,5 @@ class RankingAgent:
125
 
126
  return finalists
127
 
128
- def _validate_inputs(self, papers: List[Dict], query_embedding: Any) -> None:
129
- """Validate input parameters.
130
-
131
- Week 1: query_embedding can be None (will use citation+recency only).
132
- Week 2+: query_embedding required for full semantic similarity ranking.
133
- """
134
- if not isinstance(papers, list):
135
- raise ValueError("papers must be a list")
136
-
137
- # Week 1: Allow None query_embedding
138
- if query_embedding is not None:
139
- if not isinstance(query_embedding, np.ndarray):
140
- raise ValueError("query_embedding must be a numpy array")
141
-
142
- if query_embedding.shape not in [(384,), (768,)]:
143
- raise ValueError(
144
- f"query_embedding must be 384 or 768-dimensional, got {query_embedding.shape}"
145
- )
146
-
147
- if not np.isfinite(query_embedding).all():
148
- raise ValueError("query_embedding contains non-finite values")
149
-
150
- def _compute_semantic_scores(
151
- self, papers: List[Dict], query_embedding: np.ndarray | None
152
- ) -> np.ndarray:
153
- """Compute semantic similarity scores using cosine similarity.
154
-
155
- Week 1: If query_embedding is None, returns 0.5 for all papers (neutral score).
156
- Week 2+: Uses actual cosine similarity with query embedding.
157
- """
158
- # Week 1: No query embedding, return neutral scores
159
- if query_embedding is None:
160
- return np.full(len(papers), 0.5, dtype=np.float32)
161
-
162
- embeddings = []
163
- valid_indices = []
164
-
165
- for i, paper in enumerate(papers):
166
- emb_dict = paper.get("embedding")
167
- if emb_dict and isinstance(emb_dict, dict):
168
- emb = emb_dict.get("specter_v2")
169
- if emb is not None:
170
- try:
171
- emb_array = np.array(emb, dtype=np.float32)
172
- # Accept both 384 (older SPECTER) and 768 (SPECTER2) dimensions
173
- if (
174
- emb_array.shape in [(384,), (768,)]
175
- and np.isfinite(emb_array).all()
176
- ):
177
- embeddings.append(emb_array)
178
- valid_indices.append(i)
179
- else:
180
- logger.warning(
181
- "Invalid embedding for paper {}: wrong shape or non-finite",
182
- paper.get("paperId", i),
183
- )
184
- except (ValueError, TypeError):
185
- logger.warning(
186
- "Failed to parse embedding for paper {}",
187
- paper.get("paperId", i),
188
- )
189
- else:
190
- logger.warning(
191
- "Missing specter_v2 embedding for paper {}",
192
- paper.get("paperId", i),
193
- )
194
- else:
195
- logger.warning(
196
- "Missing embedding dict for paper {}", paper.get("paperId", i)
197
- )
198
-
199
- if not embeddings:
200
- logger.warning("No valid embeddings found, all semantic scores will be 0.0")
201
- return np.zeros(len(papers))
202
-
203
- # Batch compute similarities
204
- emb_array = np.stack(embeddings) # (n_valid, 384)
205
- similarities = np.dot(emb_array, query_embedding) # (n_valid,)
206
- similarities = np.clip(similarities, -1.0, 1.0) # Ensure valid cosine range
207
-
208
- # Map back to full array
209
- scores = np.zeros(len(papers))
210
- scores[valid_indices] = similarities
211
-
212
- return scores
213
-
214
- def _compute_authority_scores(self, papers: List[Dict]) -> np.ndarray:
215
- """Compute authority scores from influential citations."""
216
- citations = []
217
- for paper in papers:
218
- cit = paper.get("influentialCitationCount", 0)
219
- if cit is None:
220
- logger.warning(
221
- "Missing influentialCitationCount for paper {}, using 0",
222
- paper.get("paperId", "unknown"),
223
- )
224
- cit = 0
225
- elif not isinstance(cit, (int, float)) or cit < 0:
226
- logger.warning(
227
- "Invalid influentialCitationCount {} for paper {}, using 0",
228
- cit,
229
- paper.get("paperId", "unknown"),
230
- )
231
- cit = 0
232
- citations.append(cit)
233
-
234
- citations = np.array(citations)
235
- if citations.max() == 0:
236
- return np.zeros(len(papers))
237
-
238
- # Log normalization: log(1 + cit) / log(1 + max_cit)
239
- scores = np.log1p(citations) / np.log1p(citations.max())
240
- return scores
241
-
242
- def _compute_impact_scores(self, papers: List[Dict]) -> np.ndarray:
243
- """Compute impact scores from total citations."""
244
- citations = []
245
- for paper in papers:
246
- cit = paper.get("citationCount", 0)
247
- if cit is None:
248
- logger.warning(
249
- "Missing citationCount for paper {}, using 0",
250
- paper.get("paperId", "unknown"),
251
- )
252
- cit = 0
253
- elif not isinstance(cit, (int, float)) or cit < 0:
254
- logger.warning(
255
- "Invalid citationCount {} for paper {}, using 0",
256
- cit,
257
- paper.get("paperId", "unknown"),
258
- )
259
- cit = 0
260
- citations.append(cit)
261
-
262
- citations = np.array(citations)
263
- if citations.max() == 0:
264
- return np.zeros(len(papers))
265
-
266
- # Log normalization: log(1 + cit) / log(1 + max_cit)
267
- scores = np.log1p(citations) / np.log1p(citations.max())
268
- return scores
269
-
270
- def _compute_recency_scores(self, papers: List[Dict]) -> np.ndarray:
271
- """Compute recency scores with linear normalization 2015-date.today().year."""
272
- years = []
273
- for paper in papers:
274
- year = paper.get("year")
275
- if year is None:
276
- logger.warning(
277
- "Missing year for paper {}, using date.today().year (min recency)",
278
- paper.get("paperId", "unknown"),
279
- )
280
- year = date.today().year
281
- elif not isinstance(year, (int, float)):
282
- logger.warning(
283
- "Invalid year {} for paper {}, using date.today().year",
284
- year,
285
- paper.get("paperId", "unknown"),
286
- )
287
- year = date.today().year
288
-
289
- else:
290
- year = float(year)
291
- if year < 2015 or year > date.today().year:
292
- logger.warning(
293
- f"Year {year} outside 2015-{date.today().year} range for paper {paper.get('paperId', 'unknown')}, clamping"
294
- )
295
- year = np.clip(year, 2015, date.today().year)
296
-
297
- years.append(year)
298
-
299
- years = np.array(years)
300
- # Linear normalization: (year - 2015) / (2025 - 2015)
301
- scores = (years - 2015) / (date.today().year - 2015)
302
- return scores
303
-
304
- def _compute_composite_scores(
305
- self,
306
- semantic_scores: np.ndarray,
307
- authority_scores: np.ndarray,
308
- impact_scores: np.ndarray,
309
- recency_scores: np.ndarray,
310
- ) -> np.ndarray:
311
- """Compute composite scores using weighted combination.
312
-
313
- Formula: 0.4 * semantic + 0.3 * authority + 0.2 * impact + 0.1 * recency
314
-
315
- Args:
316
- semantic_scores: Normalized semantic similarity scores (0.0-1.0)
317
- authority_scores: Normalized authority scores (0.0-1.0)
318
- impact_scores: Normalized impact scores (0.0-1.0)
319
- recency_scores: Normalized recency scores (0.0-1.0)
320
-
321
- Returns:
322
- Composite scores array (0.0-1.0)
323
- """
324
- return (
325
- # 0.4 * semantic_scores # 0.4
326
- 0.3 * authority_scores
327
- + 0.2 * impact_scores # 0.2
328
- + 0.1 * recency_scores
329
- )
330
-
331
 
332
  __all__ = ["RankingAgent"]
 
1
  """Ranking agent for scoring and ranking Semantic Scholar papers.
2
 
3
+ Implements a multi-stage hybrid ranking model combining:
4
+ 1. **Relevance (RRF)**:
5
+ - BM25 (Lexical)
6
+ - TF-IDF (Lexical)
7
+ - LSA (Latent Semantic)
8
+ - BM25-SPECTER Centroid (Semantic)
9
+ 2. **Authority**: Log-normalized influential/total citations.
10
+ 3. **Recency**: Exponential decay.
11
+
12
+ This agent accepts a List[Dict] of papers and a query string,
13
+ converts them to a DataFrame for internal processing, and returns
14
+ a List[Dict] of ranked finalists.
 
 
 
 
 
 
 
 
 
15
  """
16
 
17
  from typing import Dict, List, Any
18
  import numpy as np
19
+ import pandas as pd
20
+ import bm25s
21
+ from scipy.stats import rankdata
22
+ from sklearn.feature_extraction.text import TfidfVectorizer
23
+ from sklearn.metrics.pairwise import cosine_similarity
24
+ from sklearn.decomposition import TruncatedSVD
25
  from loguru import logger
26
  from datetime import date
27
 
28
+ # --- Configuration ---
29
+ RRF_K = 60 # Constant for Reciprocal Rank Fusion (RRF)
30
+ LSA_COMPONENTS = 100 # Number of components for LSA
31
+ CENTROID_K = 5 # Number of top BM25 papers to use for centroid
32
+ CURRENT_YEAR = date.today().year
33
+ RECENCY_LAMBDA = 0.1 # Decay rate for recency (0.1 = ~10 year half-life)
34
 
35
+ # Final ranking weights
36
+ W_RELEVANCE = 0.60
37
+ W_AUTHORITY = 0.35
38
+ W_RECENCY = 0.05
39
+
40
+
41
+ # --- Internal Helper Functions (Operating on Pandas Data) ---
42
+
43
+
44
+ def _compute_bm25s_ranks(query: str, corpus: List[str]) -> np.ndarray:
45
+ """Computes BM25 ranks (1 = best) for a query against a corpus."""
46
+ if not corpus:
47
+ return np.array([])
48
+
49
+ try:
50
+ corpus_tokens = bm25s.tokenize(corpus, stopwords="english")
51
+ retriever = bm25s.BM25(method="lucene")
52
+ retriever.index(corpus_tokens)
53
+ query_tokens = bm25s.tokenize(query, stopwords="english")
54
+
55
+ _, scores = retriever.retrieve(query_tokens, k=len(corpus))
56
+ scores = scores.flatten()
57
+
58
+ if scores.max() > 0:
59
+ scores_normalized = scores / scores.max()
60
+ else:
61
+ scores_normalized = np.zeros(len(corpus))
62
+
63
+ return rankdata(-scores_normalized, "dense")
64
+ except Exception as e:
65
+ logger.error(f"Error in BM25S ranking: {e}. Returning empty ranks.")
66
+ return np.full(len(corpus), len(corpus), dtype=int)
67
+
68
+
69
+ def _compute_tfidf_ranks(query: str, corpus: List[str]) -> np.ndarray:
70
+ """Computes TF-IDF cosine similarity ranks (1 = best)."""
71
+ if not corpus:
72
+ return np.array([])
73
+
74
+ try:
75
+ full_corpus = [query] + corpus
76
+ vectorizer = TfidfVectorizer(stop_words="english")
77
+ tfidf_matrix = vectorizer.fit_transform(full_corpus)
78
+
79
+ similarities = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:]).flatten()
80
+
81
+ scores_normalized = similarities / (similarities.max() or 1)
82
+ return rankdata(-scores_normalized, "dense")
83
+ except Exception as e:
84
+ logger.error(f"Error in TF-IDF ranking: {e}. Returning empty ranks.")
85
+ return np.full(len(corpus), len(corpus), dtype=int)
86
+
87
+
88
+ def _compute_lsa_ranks(query: str, corpus: List[str], n_components: int) -> np.ndarray:
89
+ """Computes LSA ranks (1 = best). Inefficiently re-builds index per query."""
90
+ if not corpus:
91
+ return np.array([])
92
+
93
+ try:
94
+ vectorizer = TfidfVectorizer(stop_words="english", max_df=0.8, min_df=5)
95
+ tfidf_matrix = vectorizer.fit_transform(corpus)
96
+
97
+ effective_components = min(n_components, tfidf_matrix.shape[1] - 1)
98
+ if effective_components <= 0:
99
+ logger.warning("LSA: Not enough features for SVD. Skipping.")
100
+ return np.full(len(corpus), len(corpus), dtype=int)
101
+
102
+ svd_model = TruncatedSVD(n_components=effective_components, random_state=42)
103
+ lsa_matrix = svd_model.fit_transform(tfidf_matrix)
104
+
105
+ query_tfidf = vectorizer.transform([query])
106
+ query_lsa = svd_model.transform(query_tfidf)
107
+
108
+ scores = cosine_similarity(query_lsa, lsa_matrix).flatten()
109
+ return rankdata(-scores, "dense")
110
+ except ValueError as e:
111
+ logger.warning(f"Error in LSA ranking: {e}. Returning empty ranks.")
112
+ return np.full(len(corpus), len(corpus), dtype=int)
113
+
114
+
115
+ def _compute_bm25_centroid_ranks(df: pd.DataFrame, centroid_k: int) -> np.ndarray:
116
+ """Ranks papers by similarity to the centroid of the top 'k' BM25 papers."""
117
+ df["specter_vector"] = df["embedding"].apply(
118
+ lambda x: x.get("specter") if isinstance(x, dict) else None
119
+ )
120
+ df_clean = df.dropna(subset=["specter_vector"]).copy()
121
+
122
+ if df_clean.empty:
123
+ logger.warning("No SPECTER embeddings found for centroid ranking.")
124
+ return np.full(len(df), len(df), dtype=int)
125
+
126
+ try:
127
+ embeddings_clean_all = np.stack(df_clean["specter_vector"].values)
128
+ except ValueError as e:
129
+ logger.error(f"Error stacking embeddings (mismatched dimensions?): {e}")
130
+ return np.full(len(df), len(df), dtype=int)
131
+
132
+ top_k_papers = df_clean.sort_values(by="bm25_rank", ascending=True).head(centroid_k)
133
+
134
+ if top_k_papers.empty:
135
+ logger.warning("No top BM25 papers found to create centroid.")
136
+ return np.full(len(df), len(df), dtype=int)
137
+
138
+ top_k_ilocs = df_clean.index.get_indexer(top_k_papers.index)
139
+ top_k_vectors = embeddings_clean_all[top_k_ilocs]
140
+ centroid_query_vector = np.mean(top_k_vectors, axis=0).reshape(1, -1)
141
+
142
+ scores = cosine_similarity(centroid_query_vector, embeddings_clean_all).flatten()
143
+
144
+ ranked_scores_series = pd.Series(scores, index=df_clean.index)
145
+ full_scores_series = ranked_scores_series.reindex(df.index).fillna(-np.inf)
146
+
147
+ return rankdata(-full_scores_series.values, "dense")
148
+
149
+
150
+ def _compute_rrf_score(df: pd.DataFrame) -> pd.Series:
151
+ """Computes the Reciprocal Rank Fusion (RRF) score for relevance."""
152
+ return (
153
+ 1 / (df["bm25_rank"] + RRF_K)
154
+ + 1 / (df["tfid_rank"] + RRF_K)
155
+ + 1 / (df["lsa_rank"] + RRF_K)
156
+ + 1 / (df["pseudo_specter_rank"] + RRF_K)
157
+ )
158
+
159
+
160
+ def _compute_authority_ranks(df: pd.DataFrame) -> np.ndarray:
161
+ """Computes authority ranks (1 = best) based on citations."""
162
+
163
+ def get_authority(row):
164
+ icc = row.get("influentialCitationCount", 0) or 0
165
+ cc = row.get("citationCount", 0) or 0
166
+ return np.log10(max(icc, cc * 0.3) + 1)
167
+
168
+ authority_raw = df.apply(get_authority, axis=1)
169
+ return rankdata(-authority_raw.values, method="dense")
170
+
171
+
172
+ def _compute_recency_ranks(
173
+ df: pd.DataFrame, current_year: int, lambda_decay: float
174
+ ) -> np.ndarray:
175
+ """Computes recency ranks (1 = best) using exponential decay."""
176
+
177
+ def get_recency(year):
178
+ if pd.isna(year):
179
+ return 0
180
+ return np.exp(-lambda_decay * (current_year - year))
181
+
182
+ recency_raw = df["year"].apply(get_recency)
183
+ return rankdata(-recency_raw.values, method="dense")
184
 
 
 
 
 
 
185
 
186
+ def _normalize_ranks(df: pd.DataFrame, rank_columns: List[str]) -> pd.DataFrame:
187
+ """Applies min-max normalization to rank columns (where 1 is best)."""
188
+ for col in rank_columns:
189
+ min_val = df[col].min()
190
+ max_val = df[col].max()
191
+
192
+ if max_val - min_val > 0:
193
+ df[f"{col}_norm"] = (df[col] - min_val) / (max_val - min_val)
194
+ else:
195
+ df[f"{col}_norm"] = 0.5
196
+ return df
197
+
198
+
199
+ def _compute_final_ranking(df: pd.DataFrame) -> pd.DataFrame:
200
+ """Computes the final weighted score from all signals."""
201
+ df["rrf_relevance_score"] = _compute_rrf_score(df)
202
+ df["rrf_relevance_rank"] = rankdata(
203
+ -df["rrf_relevance_score"].values, method="dense"
204
+ )
205
+ df["authority_rank"] = _compute_authority_ranks(df)
206
+ df["recency_rank"] = _compute_recency_ranks(df, CURRENT_YEAR, RECENCY_LAMBDA)
207
+
208
+ rank_cols = ["rrf_relevance_rank", "authority_rank", "recency_rank"]
209
+ df = _normalize_ranks(df, rank_cols)
210
+
211
+ df["relevance_score"] = 1.0 - df["rrf_relevance_rank_norm"]
212
+ df["authority_score"] = 1.0 - df["authority_rank_norm"]
213
+ df["recency_score"] = 1.0 - df["recency_rank_norm"]
214
+
215
+ df["final_score"] = (
216
+ W_RELEVANCE * df["relevance_score"]
217
+ + W_AUTHORITY * df["authority_score"]
218
+ + W_RECENCY * df["recency_score"]
219
+ )
220
+
221
+ return df.sort_values("final_score", ascending=False)
222
+
223
+
224
+ class RankingAgent:
225
+ """
226
+ Agent that ranks Semantic Scholar papers using a hybrid, multi-stage
227
+ scoring model based on Relevance (RRF), Authority, and Recency.
228
  """
229
 
230
+ def rank_papers(
231
+ self, papers: List[Dict[str, Any]], query: str
232
+ ) -> List[Dict[str, Any]]:
233
+ """Rank papers using the hybrid ranking model.
234
 
235
  Args:
236
+ papers: List[Dict] of Semantic Scholar papers
237
+ query: The optimized query string for ranking
 
238
 
239
  Returns:
240
+ List[Dict]: Top 10 papers with all computed rank/score fields added,
241
+ returned as a List of Dictionaries.
 
 
 
 
 
 
 
 
242
  """
243
+ # --- 1. Validate inputs ---
244
+ if not isinstance(papers, list):
245
+ raise ValueError("papers must be a list")
246
+ if not isinstance(query, str) or not query:
247
+ raise ValueError("query must be a non-empty string")
248
 
249
  if not papers:
250
  logger.warning("No papers provided for ranking")
251
  return []
252
 
253
+ logger.info(
254
+ f"RankingAgent starting: {len(papers)} papers for query '{query[:50]}...'"
 
 
 
 
 
 
 
255
  )
256
 
257
+ # --- 2. Convert List[Dict] to DataFrame for internal processing ---
258
+ try:
259
+ df = pd.DataFrame(papers)
260
+
261
+ except Exception as e:
262
+ logger.error(f"Failed to create DataFrame from papers: {e}")
263
+ return []
264
+
265
+ # 3. Clean text fields for lexical search
266
+ df["title"] = df["title"].fillna("")
267
+ df["abstract"] = df["abstract"].apply(lambda x: str(x) if pd.notna(x) else "")
268
+ corpus = (df["title"] + ": " + df["abstract"]).tolist()
269
+ titles_only = df["title"].tolist()
270
+
271
+ # --- 4. Run all ranking steps from notebook ---
272
+ logger.debug("Computing relevance ranks (BM25, TF-IDF, LSA)...")
273
+ df["bm25_rank"] = _compute_bm25s_ranks(query, corpus)
274
+ df["tfid_rank"] = _compute_tfidf_ranks(query, titles_only)
275
+
276
+ logger.debug("Computing LSA ranks (note: inefficient, re-builds index)...")
277
+ df["lsa_rank"] = _compute_lsa_ranks(query, corpus, n_components=LSA_COMPONENTS)
278
+
279
+ logger.debug("Computing BM25-SPECTER centroid ranks...")
280
+ df["pseudo_specter_rank"] = _compute_bm25_centroid_ranks(
281
+ df, centroid_k=CENTROID_K
282
  )
283
 
284
+ logger.debug("Computing final RRF, authority, recency, and weighted score...")
285
+ ranked_df = _compute_final_ranking(df)
286
+
287
+ # --- 5. Convert top 10 back to List[Dict] ---
288
+ finalists_df = ranked_df.head(10)
289
+ # Convert DataFrame to a list of dictionaries
290
+ finalists = finalists_df.to_dict("records")
291
+
292
+ # Log top 3
293
  top_titles = [p.get("title", "Unknown") for p in finalists[:3]]
294
  logger.info(
295
+ "Top 3 ranked papers: 1. '{}' (Score: {:.3f}), 2. '{}' (Score: {:.3f}), 3. '{}' (Score: {:.3f})",
296
+ top_titles[0] if len(finalists) > 0 else "None",
297
+ finalists[0]["final_score"] if len(finalists) > 0 else 0.0,
298
+ top_titles[1] if len(finalists) > 1 else "None",
299
+ finalists[1]["final_score"] if len(finalists) > 1 else 0.0,
300
+ top_titles[2] if len(finalists) > 2 else "None",
301
+ finalists[2]["final_score"] if len(finalists) > 2 else 0.0,
302
  )
303
 
304
  logger.info(
 
309
 
310
  return finalists
311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
 
313
  __all__ = ["RankingAgent"]
agents/semantic_scholar_client.py CHANGED
@@ -269,42 +269,35 @@ class SemanticScholarClient:
269
  if retry_after:
270
  try:
271
  wait = float(retry_after)
272
- logger.info("Received Retry-After=%s, sleeping", wait)
273
  await asyncio.sleep(wait)
274
  except Exception:
275
  pass
276
  text = await resp.text()
277
  logger.error(
278
- "Semantic Scholar rate limited (429) for query=%s: %s",
279
- query,
280
- text,
281
  )
282
  raise RuntimeError("Semantic Scholar API rate limited (429)")
283
  elif resp.status == 503:
284
  text = await resp.text()
285
  logger.error(
286
- "Semantic Scholar service unavailable (503) for query=%s: %s",
287
- query,
288
- text,
289
  )
290
  raise RuntimeError("Semantic Scholar service unavailable (503)")
291
  else:
292
  text = await resp.text()
293
  logger.error(
294
- "Semantic Scholar returned status %s for query=%s: %s",
295
- resp.status,
296
- query,
297
- text,
298
  )
299
  return []
300
  except asyncio.TimeoutError as te:
301
  logger.exception(
302
- "Timeout when calling Semantic Scholar for query=%s", query
303
  )
304
  raise
305
  except aiohttp.ClientError as ce:
306
  logger.exception(
307
- "Network error when calling Semantic Scholar for query=%s", query
308
  )
309
  raise
310
  finally:
 
269
  if retry_after:
270
  try:
271
  wait = float(retry_after)
272
+ logger.info(f"Received Retry-After={wait}, sleeping")
273
  await asyncio.sleep(wait)
274
  except Exception:
275
  pass
276
  text = await resp.text()
277
  logger.error(
278
+ f"Semantic Scholar rate limited (429) for {query}: {text}"
 
 
279
  )
280
  raise RuntimeError("Semantic Scholar API rate limited (429)")
281
  elif resp.status == 503:
282
  text = await resp.text()
283
  logger.error(
284
+ f"Semantic Scholar service unavailable (503) for query={query}: {text}"
 
 
285
  )
286
  raise RuntimeError("Semantic Scholar service unavailable (503)")
287
  else:
288
  text = await resp.text()
289
  logger.error(
290
+ f"Semantic Scholar returned status {resp.status} for query={query}: {text}"
 
 
 
291
  )
292
  return []
293
  except asyncio.TimeoutError as te:
294
  logger.exception(
295
+ f"Timeout when calling Semantic Scholar for query={query}"
296
  )
297
  raise
298
  except aiohttp.ClientError as ce:
299
  logger.exception(
300
+ f"Network error when calling Semantic Scholar for query={query}"
301
  )
302
  raise
303
  finally:
notebooks/Untitled.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
searches/New Tekstdocument.txt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:e73f6d8ba65fe678d451d374224acd890d71bf200bdc9bb85218debab50becec
3
- size 924
 
 
 
 
searches/New folder/climate change mitigation strategies.json DELETED
The diff for this file is too large to render. See raw diff
 
searches/New folder/decarbonization technologies greenhouse gas reduction climate policy.json DELETED
The diff for this file is too large to render. See raw diff
 
searches/New folder/global warming reversal atmospheric carbon capture solutions.json DELETED
The diff for this file is too large to render. See raw diff
 
searches/digital media usage psychiatric symptoms self-esteem.json DELETED
The diff for this file is too large to render. See raw diff
 
searches/social media mental health impact.json DELETED
The diff for this file is too large to render. See raw diff
 
searches/social media psychological well-being depression anxiety adolescent.json DELETED
The diff for this file is too large to render. See raw diff
 
services/query_service.py CHANGED
@@ -213,12 +213,7 @@ class QueryService:
213
  try:
214
  # Week 1: No query embedding needed - quality gate uses paper-level metrics only
215
  # (citations, recency, venue quality)
216
- # Week 2+: Will use local embedding model for semantic similarity
217
  query_embedding = None
218
- if self.embedding_model is not None:
219
- query_embedding = self.embedding_model.encode(query)
220
- query_embedding = np.array(query_embedding, dtype=np.float32)
221
-
222
  quality_result = validate_quality(papers, query_embedding)
223
  timing_breakdown["quality_gate"] = time.perf_counter() - stage_start
224
  logger.info(
@@ -242,8 +237,9 @@ class QueryService:
242
  )
243
  stage_start = time.perf_counter()
244
  try:
245
- input_data = {"papers": papers, "query_embedding": query_embedding}
246
- finalists = self._get_ranker().rank_papers(input_data)
 
247
  timing_breakdown["composite_scoring"] = (
248
  time.perf_counter() - stage_start
249
  )
 
213
  try:
214
  # Week 1: No query embedding needed - quality gate uses paper-level metrics only
215
  # (citations, recency, venue quality)
 
216
  query_embedding = None
 
 
 
 
217
  quality_result = validate_quality(papers, query_embedding)
218
  timing_breakdown["quality_gate"] = time.perf_counter() - stage_start
219
  logger.info(
 
237
  )
238
  stage_start = time.perf_counter()
239
  try:
240
+ finalists = self._get_ranker().rank_papers(
241
+ papers, optimized_queries["final_rephrase"]
242
+ )
243
  timing_breakdown["composite_scoring"] = (
244
  time.perf_counter() - stage_start
245
  )