acseresznye commited on
Commit
5b48ad6
·
1 Parent(s): 6f8a5dc

dict converted to pydantic

Browse files
agents/acquisition_agent.py CHANGED
@@ -9,7 +9,7 @@ from typing import Any, Dict, List, Optional
9
  from curl_cffi.requests import AsyncSession, RequestsError
10
  from loguru import logger
11
 
12
- from models.state import State
13
  from utils.pdf_extractor import PdfExtractionError, extract_text_from_pdf_file
14
 
15
  # UPDATE THIS BLOCK
@@ -55,7 +55,7 @@ class AcquisitionAgent:
55
  - Bonus: Upgrade top 5 accessible papers to full PDF text
56
 
57
  Args:
58
- state: State containing finalists (List[Dict] of papers)
59
 
60
  Returns:
61
  Updated state with passages containing abstract + PDF content
@@ -70,7 +70,7 @@ class AcquisitionAgent:
70
 
71
  TARGET_PDF_COUNT = 5
72
  acquired_pdfs = 0
73
- passages_map: Dict[str, Dict[str, Any]] = {}
74
 
75
  finalists = state.finalists
76
  logger.info(
@@ -84,21 +84,29 @@ class AcquisitionAgent:
84
  async with AsyncSession(impersonate="chrome110", headers=HEADERS) as session:
85
  # 1. First, add abstracts for ALL finalists (fast, synchronous)
86
  for paper in finalists:
87
- paper_id = paper.get("paperId") or paper.get("id")
88
  if not paper_id:
89
  continue
90
 
91
- abstract_text = paper.get("abstract", "")
92
  if abstract_text:
93
- abstract_passage = dict(paper)
94
- abstract_passage.update(
95
- {
96
- "text": abstract_text,
 
97
  "text_source": "abstract",
98
- "extraction_error": None,
99
- }
 
 
 
 
 
 
 
 
100
  )
101
- passages_map[paper_id] = abstract_passage
102
 
103
  # 2. Concurrent PDF acquisition for top candidates
104
  # We try the top 12 candidates to get our target of 5 PDFs
@@ -130,27 +138,34 @@ class AcquisitionAgent:
130
  return None
131
 
132
  # Launch all tasks concurrently
133
- tasks = [fetch_pdf_safe(idx, p) for idx, p in pdf_candidates]
134
- results = await asyncio.gather(*tasks)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- # Collect successful results up to target
137
- for res in results:
138
- # We can restrict the number of acquired PDFs here
139
  if acquired_pdfs >= TARGET_PDF_COUNT:
140
  break
141
 
142
- if res and res.get("text"):
143
- paper_id = res.get("paperId") or res.get("id")
144
- if paper_id:
145
- passages_map[paper_id] = res
146
- acquired_pdfs += 1
147
- paper_title = res.get("title", "Unknown")[:60]
148
- logger.info(
149
- "Upgrading to PDF ({a}/{t}): {title}",
150
- a=acquired_pdfs,
151
- t=TARGET_PDF_COUNT,
152
- title=paper_title,
153
- )
154
 
155
  elapsed = time.monotonic() - start_all
156
 
@@ -172,20 +187,20 @@ class AcquisitionAgent:
172
 
173
  return new_state
174
 
175
- def _has_pdf_url(self, paper: Dict[str, Any]) -> bool:
176
  """Check if paper has a PDF URL available."""
177
- oa_pdf = paper.get("openAccessPdf")
178
  return bool(oa_pdf and isinstance(oa_pdf, dict) and oa_pdf.get("url"))
179
 
180
  async def _process_single(
181
- self, paper: Dict[str, Any], session: AsyncSession
182
- ) -> Optional[Dict[str, Any]]:
183
  """High-level single paper processing: download then extract/validate.
184
 
185
- Returns a passage dict on success or None on failure.
186
  """
187
- paper_id = paper.get("paperId") or paper.get("id") or "unknown"
188
- oa = paper.get("openAccessPdf")
189
  url = oa.get("url") if oa and isinstance(oa, dict) else None
190
 
191
  if not url:
@@ -242,15 +257,19 @@ class AcquisitionAgent:
242
  e=dt_extract,
243
  )
244
 
245
- out = dict(paper)
246
- out.update(
247
- {
248
- "text": text,
 
249
  "text_source": "pdf",
250
- "extraction_error": None,
251
- }
 
 
 
 
252
  )
253
- return out
254
 
255
  async def _download_single_pdf(
256
  self,
 
9
  from curl_cffi.requests import AsyncSession, RequestsError
10
  from loguru import logger
11
 
12
+ from models.state import Paper, Passage, State
13
  from utils.pdf_extractor import PdfExtractionError, extract_text_from_pdf_file
14
 
15
  # UPDATE THIS BLOCK
 
55
  - Bonus: Upgrade top 5 accessible papers to full PDF text
56
 
57
  Args:
58
+ state: State containing finalists (List[Paper])
59
 
60
  Returns:
61
  Updated state with passages containing abstract + PDF content
 
70
 
71
  TARGET_PDF_COUNT = 5
72
  acquired_pdfs = 0
73
+ passages_map: Dict[str, Passage] = {}
74
 
75
  finalists = state.finalists
76
  logger.info(
 
84
  async with AsyncSession(impersonate="chrome110", headers=HEADERS) as session:
85
  # 1. First, add abstracts for ALL finalists (fast, synchronous)
86
  for paper in finalists:
87
+ paper_id = paper.paperId
88
  if not paper_id:
89
  continue
90
 
91
+ abstract_text = paper.abstract
92
  if abstract_text:
93
+ passages_map[paper_id] = Passage(
94
+ paper_id=paper_id,
95
+ text=abstract_text,
96
+ metadata={
97
+ "title": paper.title,
98
  "text_source": "abstract",
99
+ "url": (
100
+ paper.openAccessPdf.get("url")
101
+ if paper.openAccessPdf
102
+ else None
103
+ ),
104
+ "year": paper.year,
105
+ "venue": paper.venue,
106
+ "citationCount": paper.citationCount,
107
+ "influentialCitationCount": paper.influentialCitationCount,
108
+ },
109
  )
 
110
 
111
  # 2. Concurrent PDF acquisition for top candidates
112
  # We try the top 12 candidates to get our target of 5 PDFs
 
138
  return None
139
 
140
  # Launch all tasks concurrently
141
+ tasks = [
142
+ asyncio.create_task(fetch_pdf_safe(idx, p))
143
+ for idx, p in pdf_candidates
144
+ ]
145
+
146
+ # Race tasks to completion using as_completed
147
+ for future in asyncio.as_completed(tasks):
148
+ res = await future
149
+
150
+ if res:
151
+ passages_map[res.paper_id] = res
152
+ acquired_pdfs += 1
153
+ paper_title = res.metadata.get("title", "Unknown")[:60]
154
+ logger.info(
155
+ "Upgrading to PDF ({a}/{t}): {title}",
156
+ a=acquired_pdfs,
157
+ t=TARGET_PDF_COUNT,
158
+ title=paper_title,
159
+ )
160
 
161
+ # Stop early if we hit the target
 
 
162
  if acquired_pdfs >= TARGET_PDF_COUNT:
163
  break
164
 
165
+ # Cancel any remaining tasks to free resources
166
+ for task in tasks:
167
+ if not task.done():
168
+ task.cancel()
 
 
 
 
 
 
 
 
169
 
170
  elapsed = time.monotonic() - start_all
171
 
 
187
 
188
  return new_state
189
 
190
+ def _has_pdf_url(self, paper: Paper) -> bool:
191
  """Check if paper has a PDF URL available."""
192
+ oa_pdf = paper.openAccessPdf
193
  return bool(oa_pdf and isinstance(oa_pdf, dict) and oa_pdf.get("url"))
194
 
195
  async def _process_single(
196
+ self, paper: Paper, session: AsyncSession
197
+ ) -> Optional[Passage]:
198
  """High-level single paper processing: download then extract/validate.
199
 
200
+ Returns a Passage object on success or None on failure.
201
  """
202
+ paper_id = paper.paperId
203
+ oa = paper.openAccessPdf
204
  url = oa.get("url") if oa and isinstance(oa, dict) else None
205
 
206
  if not url:
 
257
  e=dt_extract,
258
  )
259
 
260
+ return Passage(
261
+ paper_id=paper_id,
262
+ text=text,
263
+ metadata={
264
+ "title": paper.title,
265
  "text_source": "pdf",
266
+ "url": url,
267
+ "year": paper.year,
268
+ "venue": paper.venue,
269
+ "citationCount": paper.citationCount,
270
+ "influentialCitationCount": paper.influentialCitationCount,
271
+ },
272
  )
 
273
 
274
  async def _download_single_pdf(
275
  self,
agents/processing_agent.py CHANGED
@@ -58,21 +58,26 @@ class ProcessingAgent:
58
  loop_start = time.perf_counter()
59
 
60
  for idx, passage in enumerate(state.passages):
61
- paper_id = (
62
- passage.get("paperId") or passage.get("paper_id") or f"paper_{idx}"
63
- )
64
- title = passage.get("title", "")
65
- citation_count = passage.get(
66
- "citationCount", passage.get("citation_count", 0)
67
- )
68
- year = passage.get("year") or passage.get("publication_year")
69
- venue = passage.get("venue") or passage.get("journal")
70
- influential = passage.get(
71
- "influentialCitationCount", passage.get("influential_citation_count", 0)
72
- )
73
- oa_pdf = passage.get("openAccessPdf")
74
- pdf_url = oa_pdf.get("url") if oa_pdf and isinstance(oa_pdf, dict) else None
75
- text = passage.get("text", "") or ""
 
 
 
 
 
76
 
77
  if not text.strip():
78
  logger.warning({"event": "empty_passage_skipped", "paper_id": paper_id})
 
58
  loop_start = time.perf_counter()
59
 
60
  for idx, passage in enumerate(state.passages):
61
+ # Refactored to use Passage object attributes
62
+ paper_id = passage.paper_id or f"paper_{idx}"
63
+ text = passage.text or ""
64
+
65
+ # Metadata extraction
66
+ meta = passage.metadata
67
+ title = meta.get("title", "")
68
+ citation_count = meta.get("citationCount", 0)
69
+ year = meta.get("year")
70
+ venue = meta.get("venue")
71
+ influential = meta.get("influentialCitationCount", 0)
72
+
73
+ # Handle PDF URL extraction from metadata
74
+ oa_pdf = meta.get("openAccessPdf")
75
+ pdf_url = None
76
+ if oa_pdf and isinstance(oa_pdf, dict):
77
+ pdf_url = oa_pdf.get("url")
78
+
79
+ if not pdf_url:
80
+ pdf_url = meta.get("url")
81
 
82
  if not text.strip():
83
  logger.warning({"event": "empty_passage_skipped", "paper_id": paper_id})
agents/ranking_agent.py CHANGED
@@ -14,16 +14,19 @@ 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)
@@ -246,18 +249,18 @@ class RankingAgent:
246
  """
247
 
248
  def rank_papers(
249
- self, papers: List[Dict[str, Any]], query: str, top_k: int = 50
250
- ) -> List[Dict[str, Any]]:
251
  """Rank papers using the hybrid ranking model.
252
 
253
  Args:
254
- papers: List[Dict] of Semantic Scholar papers
255
  query: The optimized query string for ranking
256
  top_k: Number of top papers to return (default: 50 for Base+Bonus strategy)
257
 
258
  Returns:
259
- List[Dict]: Top k papers with all computed rank/score fields added,
260
- returned as a List of Dictionaries.
261
  """
262
  # --- 1. Validate inputs ---
263
  if not isinstance(papers, list):
@@ -273,9 +276,11 @@ class RankingAgent:
273
  f"RankingAgent starting: {len(papers)} papers for query '{query[:50]}...'"
274
  )
275
 
276
- # --- 2. Convert List[Dict] to DataFrame for internal processing ---
277
  try:
278
- df = pd.DataFrame(papers)
 
 
279
 
280
  except Exception as e:
281
  logger.error(f"Failed to create DataFrame from papers: {e}")
@@ -303,21 +308,23 @@ class RankingAgent:
303
  logger.debug("Computing final RRF, authority, recency, and weighted score...")
304
  ranked_df = _compute_final_ranking(df)
305
 
306
- # --- 5. Convert top k back to List[Dict] ---
307
  finalists_df = ranked_df.head(top_k)
308
- # Convert DataFrame to a list of dictionaries
309
- finalists = finalists_df.to_dict("records")
 
 
310
 
311
  # Log top 3
312
- top_titles = [p.get("title", "Unknown") for p in finalists[:3]]
313
  logger.info(
314
  "Top 3 ranked papers: 1. '{}' (Score: {:.3f}), 2. '{}' (Score: {:.3f}), 3. '{}' (Score: {:.3f})",
315
- top_titles[0] if len(finalists) > 0 else "None",
316
- finalists[0]["final_score"] if len(finalists) > 0 else 0.0,
317
- top_titles[1] if len(finalists) > 1 else "None",
318
- finalists[1]["final_score"] if len(finalists) > 1 else 0.0,
319
- top_titles[2] if len(finalists) > 2 else "None",
320
- finalists[2]["final_score"] if len(finalists) > 2 else 0.0,
321
  )
322
 
323
  logger.info(
 
14
  a List[Dict] of ranked finalists.
15
  """
16
 
17
+ from datetime import date
18
+ from typing import Any, Dict, List
19
+
20
+ import bm25s
21
  import numpy as np
22
  import pandas as pd
23
+ from loguru import logger
24
  from scipy.stats import rankdata
25
+ from sklearn.decomposition import TruncatedSVD
26
  from sklearn.feature_extraction.text import TfidfVectorizer
27
  from sklearn.metrics.pairwise import cosine_similarity
28
+
29
+ from models.state import Paper
 
30
 
31
  # --- Configuration ---
32
  RRF_K = 60 # Constant for Reciprocal Rank Fusion (RRF)
 
249
  """
250
 
251
  def rank_papers(
252
+ self, papers: List[Paper], query: str, top_k: int = 50
253
+ ) -> List[Paper]:
254
  """Rank papers using the hybrid ranking model.
255
 
256
  Args:
257
+ papers: List[Paper] of Semantic Scholar papers
258
  query: The optimized query string for ranking
259
  top_k: Number of top papers to return (default: 50 for Base+Bonus strategy)
260
 
261
  Returns:
262
+ List[Paper]: Top k papers with all computed rank/score fields added,
263
+ returned as a List of Paper objects.
264
  """
265
  # --- 1. Validate inputs ---
266
  if not isinstance(papers, list):
 
276
  f"RankingAgent starting: {len(papers)} papers for query '{query[:50]}...'"
277
  )
278
 
279
+ # --- 2. Convert List[Paper] to DataFrame for internal processing ---
280
  try:
281
+ # Convert Pydantic models to dicts for DataFrame processing
282
+ papers_data = [p.model_dump() for p in papers]
283
+ df = pd.DataFrame(papers_data)
284
 
285
  except Exception as e:
286
  logger.error(f"Failed to create DataFrame from papers: {e}")
 
308
  logger.debug("Computing final RRF, authority, recency, and weighted score...")
309
  ranked_df = _compute_final_ranking(df)
310
 
311
+ # --- 5. Convert top k back to List[Paper] ---
312
  finalists_df = ranked_df.head(top_k)
313
+ # Convert DataFrame to a list of dictionaries, replacing NaNs with None
314
+ finalists_dicts = finalists_df.replace({np.nan: None}).to_dict("records")
315
+ # Re-validate into Paper objects
316
+ finalists = [Paper(**d) for d in finalists_dicts]
317
 
318
  # Log top 3
319
+ top_titles = [p.get("title", "Unknown") for p in finalists_dicts[:3]]
320
  logger.info(
321
  "Top 3 ranked papers: 1. '{}' (Score: {:.3f}), 2. '{}' (Score: {:.3f}), 3. '{}' (Score: {:.3f})",
322
+ top_titles[0] if len(finalists_dicts) > 0 else "None",
323
+ finalists_dicts[0]["final_score"] if len(finalists_dicts) > 0 else 0.0,
324
+ top_titles[1] if len(finalists_dicts) > 1 else "None",
325
+ finalists_dicts[1]["final_score"] if len(finalists_dicts) > 1 else 0.0,
326
+ top_titles[2] if len(finalists_dicts) > 2 else "None",
327
+ finalists_dicts[2]["final_score"] if len(finalists_dicts) > 2 else 0.0,
328
  )
329
 
330
  logger.info(
main.py CHANGED
@@ -309,4 +309,4 @@ ui.run_with(
309
  if __name__ == "__main__":
310
  import uvicorn
311
 
312
- uvicorn.run("main:app", host="0.0.0.0", port=7860, log_level="info", reload=False)
 
309
  if __name__ == "__main__":
310
  import uvicorn
311
 
312
+ uvicorn.run("main:app", host="0.0.0.0", port=7860, log_level="info", reload=True)
models/state.py CHANGED
@@ -1,10 +1,35 @@
1
  from __future__ import annotations
2
 
3
- from pydantic import BaseModel, Field, ValidationError
4
- from typing import Optional, List, Dict, Any
5
  from datetime import datetime, timezone
 
6
  from uuid import uuid4
 
7
  from loguru import logger
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
 
10
  class State(BaseModel):
@@ -29,14 +54,14 @@ class State(BaseModel):
29
  ss_variants: Optional[Dict[str, str]] = None # {primary, broad, alternative}
30
 
31
  # Paper retrieval (Day 3)
32
- papers: Optional[List[Dict[str, Any]]] = None # Raw Semantic Scholar hits
33
 
34
  # Quality and ranking (Day 4-5)
35
  quality_gate: Optional[Dict[str, Any]] = None
36
- ranked_papers: Optional[List[Dict[str, Any]]] = None
37
- finalists: Optional[List[Dict[str, Any]]] = None # Top 5-10
38
 
39
- passages: Optional[List[Dict[str, Any]]] = None
40
 
41
  # Chunks produced by processing agents (LlamaIndex Documents / node objects)
42
  chunks: Optional[List[Any]] = None
@@ -48,10 +73,10 @@ class State(BaseModel):
48
  errors: List[str] = Field(default_factory=list)
49
 
50
  # Pydantic v2 config style
51
- model_config = {
52
- "arbitrary_types_allowed": True,
53
- "validate_assignment": True,
54
- }
55
 
56
  def __init__(self, **data: Any):
57
  # Keep simple: run BaseModel init then log creation
@@ -87,4 +112,4 @@ class State(BaseModel):
87
  return self.model_dump()
88
 
89
 
90
- __all__ = ["State"]
 
1
  from __future__ import annotations
2
 
 
 
3
  from datetime import datetime, timezone
4
+ from typing import Any, Dict, List, Optional
5
  from uuid import uuid4
6
+
7
  from loguru import logger
8
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
9
+
10
+
11
+ class Paper(BaseModel):
12
+ paperId: str
13
+ title: str
14
+ abstract: Optional[str] = None
15
+ year: Optional[int] = None
16
+ citationCount: int = 0
17
+ influentialCitationCount: int = 0
18
+ openAccessPdf: Optional[Dict[str, Any]] = None
19
+ externalIds: Optional[Dict[str, Any]] = None
20
+ url: Optional[str] = None
21
+ venue: Optional[str] = None
22
+ embedding: Optional[Dict[str, Any]] = None
23
+
24
+ model_config = ConfigDict(extra="allow")
25
+
26
+
27
+ class Passage(BaseModel):
28
+ paper_id: str
29
+ text: str
30
+ score: Optional[float] = None
31
+ metadata: Dict[str, Any] = Field(default_factory=dict)
32
+ embedding: Optional[List[float]] = None
33
 
34
 
35
  class State(BaseModel):
 
54
  ss_variants: Optional[Dict[str, str]] = None # {primary, broad, alternative}
55
 
56
  # Paper retrieval (Day 3)
57
+ papers: List[Paper] = Field(default_factory=list) # Raw Semantic Scholar hits
58
 
59
  # Quality and ranking (Day 4-5)
60
  quality_gate: Optional[Dict[str, Any]] = None
61
+ ranked_papers: List[Paper] = Field(default_factory=list)
62
+ finalists: List[Paper] = Field(default_factory=list) # Top 5-10
63
 
64
+ passages: List[Passage] = Field(default_factory=list)
65
 
66
  # Chunks produced by processing agents (LlamaIndex Documents / node objects)
67
  chunks: Optional[List[Any]] = None
 
73
  errors: List[str] = Field(default_factory=list)
74
 
75
  # Pydantic v2 config style
76
+ model_config = ConfigDict(
77
+ arbitrary_types_allowed=True,
78
+ validate_assignment=True,
79
+ )
80
 
81
  def __init__(self, **data: Any):
82
  # Keep simple: run BaseModel init then log creation
 
112
  return self.model_dump()
113
 
114
 
115
+ __all__ = ["State", "Paper", "Passage"]
services/discovery_service.py CHANGED
@@ -19,6 +19,7 @@ from agents.query_optimization_agent import QueryOptimizationAgent
19
  from agents.ranking_agent import RankingAgent
20
  from agents.semantic_scholar_client import SemanticScholarClient
21
  from config.config import Settings
 
22
  from services.exceptions import (
23
  QualityGateError,
24
  QueryOptimizationError,
@@ -33,7 +34,7 @@ class DiscoveryResult:
33
 
34
  optimized_queries: Dict[str, Any]
35
  quality_gate: Dict[str, Any]
36
- finalists: List[Dict[str, Any]]
37
  timing_breakdown: Dict[str, float]
38
  refinement_count: int
39
 
@@ -226,15 +227,18 @@ class DiscoveryService:
226
  refinement_count + 1,
227
  )
228
 
229
- finalists = []
230
  if quality_result["passed"]:
231
  # Stage 4: Composite Scoring
232
  logger.info("Stage 4: Composite scoring - ranking {} papers", len(papers))
233
  stage_start = time.perf_counter()
234
  try:
 
 
 
235
  finalists = await asyncio.to_thread(
236
  self.ranker.rank_papers,
237
- papers,
238
  optimized_queries["final_rephrase"],
239
  50, # top_k for Base+Bonus strategy
240
  )
 
19
  from agents.ranking_agent import RankingAgent
20
  from agents.semantic_scholar_client import SemanticScholarClient
21
  from config.config import Settings
22
+ from models.state import Paper
23
  from services.exceptions import (
24
  QualityGateError,
25
  QueryOptimizationError,
 
34
 
35
  optimized_queries: Dict[str, Any]
36
  quality_gate: Dict[str, Any]
37
+ finalists: List[Paper]
38
  timing_breakdown: Dict[str, float]
39
  refinement_count: int
40
 
 
227
  refinement_count + 1,
228
  )
229
 
230
+ finalists: List[Paper] = []
231
  if quality_result["passed"]:
232
  # Stage 4: Composite Scoring
233
  logger.info("Stage 4: Composite scoring - ranking {} papers", len(papers))
234
  stage_start = time.perf_counter()
235
  try:
236
+ # Convert dicts to Paper objects
237
+ paper_objects = [Paper(**p) for p in papers]
238
+
239
  finalists = await asyncio.to_thread(
240
  self.ranker.rank_papers,
241
+ paper_objects,
242
  optimized_queries["final_rephrase"],
243
  50, # top_k for Base+Bonus strategy
244
  )
services/ingestion_service.py CHANGED
@@ -20,7 +20,7 @@ from utils.embedding_utils import batched_embed
20
  if TYPE_CHECKING:
21
  from agents.acquisition_agent import AcquisitionAgent
22
  from agents.processing_agent import ProcessingAgent
23
- from models.state import State
24
 
25
 
26
  @dataclass
@@ -64,9 +64,7 @@ class IngestionService:
64
  )
65
  return self._processing_agent
66
 
67
- async def ingest(
68
- self, finalists: List[Dict[str, Any]], query: str
69
- ) -> IngestionResult:
70
  """Execute the ingestion phase (Stages 5-6).
71
 
72
  Args:
@@ -166,11 +164,11 @@ class IngestionService:
166
  timing_breakdown=timing_breakdown,
167
  )
168
 
169
- async def ingest_abstracts(self, papers: List[Dict]) -> List[TextNode]:
170
  """Ingest abstracts from papers in Fast Mode.
171
 
172
  Args:
173
- papers: List of paper dictionaries.
174
 
175
  Returns:
176
  List of TextNodes with embeddings.
@@ -180,16 +178,21 @@ class IngestionService:
180
 
181
  # Create nodes from abstracts
182
  for paper in papers:
183
- abstract = paper.get("abstract")
184
  if not abstract:
185
  continue
186
 
 
 
 
 
 
187
  node = TextNode(text=abstract)
188
  node.metadata = {
189
- "paper_id": paper.get("paperId"),
190
- "paper_title": paper.get("title"),
191
- "url": paper.get("url") or paper.get("openAccessPdf", {}).get("url"),
192
- "year": paper.get("year"),
193
  "section": "Abstract",
194
  }
195
  chunks.append(node)
 
20
  if TYPE_CHECKING:
21
  from agents.acquisition_agent import AcquisitionAgent
22
  from agents.processing_agent import ProcessingAgent
23
+ from models.state import Paper, State
24
 
25
 
26
  @dataclass
 
64
  )
65
  return self._processing_agent
66
 
67
+ async def ingest(self, finalists: List["Paper"], query: str) -> IngestionResult:
 
 
68
  """Execute the ingestion phase (Stages 5-6).
69
 
70
  Args:
 
164
  timing_breakdown=timing_breakdown,
165
  )
166
 
167
+ async def ingest_abstracts(self, papers: List["Paper"]) -> List[TextNode]:
168
  """Ingest abstracts from papers in Fast Mode.
169
 
170
  Args:
171
+ papers: List of Paper objects.
172
 
173
  Returns:
174
  List of TextNodes with embeddings.
 
178
 
179
  # Create nodes from abstracts
180
  for paper in papers:
181
+ abstract = paper.abstract
182
  if not abstract:
183
  continue
184
 
185
+ # Handle URL extraction safely from Pydantic model
186
+ url = paper.url
187
+ if not url and paper.openAccessPdf:
188
+ url = paper.openAccessPdf.get("url")
189
+
190
  node = TextNode(text=abstract)
191
  node.metadata = {
192
+ "paper_id": paper.paperId,
193
+ "paper_title": paper.title,
194
+ "url": url,
195
+ "year": paper.year,
196
  "section": "Abstract",
197
  }
198
  chunks.append(node)
services/query_service.py CHANGED
@@ -27,6 +27,7 @@ from loguru import logger
27
 
28
  from agents.query_optimization_agent import QueryOptimizationAgent
29
  from config.config import Settings
 
30
  from services.discovery_service import DiscoveryService
31
  from services.exceptions import (
32
  AcquisitionError,
@@ -68,13 +69,13 @@ class PipelineResult:
68
  query: str
69
  optimized_queries: Dict[str, Any]
70
  quality_gate: Dict[str, Any]
71
- finalists: List[Dict[str, Any]]
72
  execution_time: float
73
  timing_breakdown: Dict[str, float]
74
  success: bool
75
  error_message: Optional[str] = None
76
  error_stage: Optional[str] = None
77
- passages: List[Any] = field(default_factory=list)
78
  answer: Optional[str] = None
79
  citation_verification: Optional[Dict[str, Any]] = None
80
  refinement_count: int = 0
@@ -269,4 +270,3 @@ class QueryService:
269
  result.error_message = f"Unexpected error: {str(e)}"
270
  result.error_stage = "unknown"
271
  return result
272
- return result
 
27
 
28
  from agents.query_optimization_agent import QueryOptimizationAgent
29
  from config.config import Settings
30
+ from models.state import Paper, Passage
31
  from services.discovery_service import DiscoveryService
32
  from services.exceptions import (
33
  AcquisitionError,
 
69
  query: str
70
  optimized_queries: Dict[str, Any]
71
  quality_gate: Dict[str, Any]
72
+ finalists: List[Paper]
73
  execution_time: float
74
  timing_breakdown: Dict[str, float]
75
  success: bool
76
  error_message: Optional[str] = None
77
  error_stage: Optional[str] = None
78
+ passages: List[Passage] = field(default_factory=list)
79
  answer: Optional[str] = None
80
  citation_verification: Optional[Dict[str, Any]] = None
81
  refinement_count: int = 0
 
270
  result.error_message = f"Unexpected error: {str(e)}"
271
  result.error_stage = "unknown"
272
  return result
 
services/rag_service.py CHANGED
@@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional
16
  from loguru import logger
17
 
18
  from config.config import Settings
 
19
  from services.exceptions import (
20
  RerankingError,
21
  RetrievalError,
@@ -34,7 +35,7 @@ if TYPE_CHECKING:
34
  class RAGResult:
35
  """Result of the RAG phase."""
36
 
37
- passages: List[Any]
38
  answer: Optional[str]
39
  citation_verification: Optional[Dict[str, Any]]
40
  timing_breakdown: Dict[str, float]
@@ -108,11 +109,6 @@ class RAGService:
108
  # Handle NodeWithScore object from llama_index
109
  if hasattr(passage, "node") and hasattr(passage.node, "metadata"):
110
  paper_id = passage.node.metadata.get("paper_id", "unknown")
111
- # Handle dict or other objects
112
- elif hasattr(passage, "metadata"):
113
- paper_id = passage.metadata.get("paper_id", "unknown")
114
- elif isinstance(passage, dict):
115
- paper_id = passage.get("metadata", {}).get("paper_id", "unknown")
116
 
117
  if paper_counts[paper_id] < max_per_paper:
118
  selected_passages.append(passage)
@@ -238,6 +234,18 @@ class RAGService:
238
  logger.exception("Reranking failed")
239
  raise RerankingError(f"Failed to rerank passages: {str(e)}") from e
240
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  # Stage 9: Synthesis
242
  logger.info("🤖 Stage 9: Synthesis - generating answer")
243
  stage_start = time.perf_counter()
@@ -272,7 +280,7 @@ class RAGService:
272
  verification_result = {"error": str(e)}
273
 
274
  return RAGResult(
275
- passages=passages,
276
  answer=answer,
277
  citation_verification=verification_result,
278
  timing_breakdown=timing_breakdown,
 
16
  from loguru import logger
17
 
18
  from config.config import Settings
19
+ from models.state import Passage
20
  from services.exceptions import (
21
  RerankingError,
22
  RetrievalError,
 
35
  class RAGResult:
36
  """Result of the RAG phase."""
37
 
38
+ passages: List[Passage]
39
  answer: Optional[str]
40
  citation_verification: Optional[Dict[str, Any]]
41
  timing_breakdown: Dict[str, float]
 
109
  # Handle NodeWithScore object from llama_index
110
  if hasattr(passage, "node") and hasattr(passage.node, "metadata"):
111
  paper_id = passage.node.metadata.get("paper_id", "unknown")
 
 
 
 
 
112
 
113
  if paper_counts[paper_id] < max_per_paper:
114
  selected_passages.append(passage)
 
234
  logger.exception("Reranking failed")
235
  raise RerankingError(f"Failed to rerank passages: {str(e)}") from e
236
 
237
+ # Convert to Pydantic models for result
238
+ final_passages = []
239
+ for p in passages:
240
+ final_passages.append(
241
+ Passage(
242
+ paper_id=p.node.metadata.get("paper_id", "unknown"),
243
+ text=p.node.get_content(),
244
+ score=p.score,
245
+ metadata=p.node.metadata,
246
+ )
247
+ )
248
+
249
  # Stage 9: Synthesis
250
  logger.info("🤖 Stage 9: Synthesis - generating answer")
251
  stage_start = time.perf_counter()
 
280
  verification_result = {"error": str(e)}
281
 
282
  return RAGResult(
283
+ passages=final_passages,
284
  answer=answer,
285
  citation_verification=verification_result,
286
  timing_breakdown=timing_breakdown,
tests/integration/test_acquisition_pipeline.py CHANGED
@@ -2,13 +2,12 @@ import asyncio
2
  import time
3
  from typing import Dict, List, Tuple
4
 
5
- import pytest
6
  import httpx
 
7
  from loguru import logger
8
 
9
- from models.state import State
10
  from agents.acquisition_agent import AcquisitionAgent
11
-
12
 
13
  # Probe helper with retries for transient network issues (1s,2s,4s)
14
  RETRY_DELAYS = [1.0, 2.0, 4.0]
@@ -161,10 +160,14 @@ def acquisition_agent() -> AcquisitionAgent:
161
  # wrap download
162
  orig_download = agent._download_single_pdf
163
 
164
- async def _download_wrapper(paper_id: str, url: str, session):
 
 
165
  t0 = time.perf_counter()
166
  try:
167
- return await orig_download(paper_id, url, session)
 
 
168
  finally:
169
  dt = time.perf_counter() - t0
170
  metrics.setdefault(paper_id, {})["download_time"] = dt
@@ -206,8 +209,7 @@ async def test_acquisition_success_rate_and_latency(
206
 
207
  # probe all URLs first (concurrent)
208
  urls = [
209
- f.get("openAccessPdf", {}).get("url")
210
- for f in state_with_good_finalists.finalists
211
  ]
212
  urls = [u for u in urls if u]
213
  logger.info("Probing {n} PDF URLs before acquisition", n=len(urls))
@@ -248,8 +250,8 @@ async def test_acquisition_success_rate_and_latency(
248
  sec=elapsed_attempt,
249
  )
250
 
251
- # success criteria: >=9 successes
252
- if success_count >= 9:
253
  break
254
 
255
  # decide whether to retry: only if probe previously found transient issues
@@ -280,19 +282,19 @@ async def test_acquisition_success_rate_and_latency(
280
  sec=total_elapsed,
281
  )
282
 
283
- # success rate requirement: >=9/10
284
- assert success_count >= 9, f"Expected >=9 passages, got {success_count}"
285
 
286
  # end-to-end latency requirement
287
  assert total_elapsed < 4.0, f"Latency {total_elapsed:.2f}s exceeds 4s target"
288
 
289
  # validate passages enrichment
290
  for p in passages:
291
- assert "paperId" in p
292
- assert "text" in p
293
- assert isinstance(p["text"], str)
294
- assert len(p["text"]) >= 500
295
- assert p.get("text_source") == "pdf"
296
 
297
  # Performance profiling: compute per-paper timings from agent.metrics
298
  metrics = getattr(agent, "metrics", {})
@@ -330,9 +332,7 @@ async def test_mixed_urls_skip_invalid(
330
  agent = acquisition_agent
331
 
332
  # probe valid subset
333
- urls = [
334
- f.get("openAccessPdf", {}).get("url") for f in state_with_mixed_urls.finalists
335
- ]
336
  probe_results = await asyncio.gather(*[_probe_url(u) for u in urls if u])
337
  logger.info(
338
  "Probed mixed URLs: {ok}/{t}",
@@ -342,7 +342,7 @@ async def test_mixed_urls_skip_invalid(
342
 
343
  updated = await agent.process(state_with_mixed_urls)
344
  passages = updated.passages or []
345
- paper_ids = {p.get("paperId") for p in passages}
346
 
347
  # Ensure invalid ids are not present
348
  assert "invalid1" not in paper_ids
@@ -394,8 +394,8 @@ async def test_parallel_execution_order_independent(
394
  updated1 = await agent.process(s1)
395
  updated2 = await agent.process(s2)
396
 
397
- ids1 = {p.get("paperId") for p in (updated1.passages or [])}
398
- ids2 = {p.get("paperId") for p in (updated2.passages or [])}
399
 
400
  # sets of acquired paperIds should be equal (order doesn't matter)
401
  assert ids1 == ids2, f"Expected same acquired ids across runs, got {ids1} vs {ids2}"
 
2
  import time
3
  from typing import Dict, List, Tuple
4
 
 
5
  import httpx
6
+ import pytest
7
  from loguru import logger
8
 
 
9
  from agents.acquisition_agent import AcquisitionAgent
10
+ from models.state import State
11
 
12
  # Probe helper with retries for transient network issues (1s,2s,4s)
13
  RETRY_DELAYS = [1.0, 2.0, 4.0]
 
160
  # wrap download
161
  orig_download = agent._download_single_pdf
162
 
163
+ async def _download_wrapper(
164
+ paper_id: str, url: str, session, destination_path: str
165
+ ):
166
  t0 = time.perf_counter()
167
  try:
168
+ return await orig_download(
169
+ paper_id, url, session, destination_path=destination_path
170
+ )
171
  finally:
172
  dt = time.perf_counter() - t0
173
  metrics.setdefault(paper_id, {})["download_time"] = dt
 
209
 
210
  # probe all URLs first (concurrent)
211
  urls = [
212
+ (f.openAccessPdf or {}).get("url") for f in state_with_good_finalists.finalists
 
213
  ]
214
  urls = [u for u in urls if u]
215
  logger.info("Probing {n} PDF URLs before acquisition", n=len(urls))
 
250
  sec=elapsed_attempt,
251
  )
252
 
253
+ # success criteria: >=5 successes
254
+ if success_count >= 5:
255
  break
256
 
257
  # decide whether to retry: only if probe previously found transient issues
 
282
  sec=total_elapsed,
283
  )
284
 
285
+ # success rate requirement: >=5/10
286
+ assert success_count >= 5, f"Expected >=5 passages, got {success_count}"
287
 
288
  # end-to-end latency requirement
289
  assert total_elapsed < 4.0, f"Latency {total_elapsed:.2f}s exceeds 4s target"
290
 
291
  # validate passages enrichment
292
  for p in passages:
293
+ assert p.paper_id
294
+ assert p.text
295
+ assert isinstance(p.text, str)
296
+ assert len(p.text) >= 500
297
+ assert p.metadata.get("text_source") == "pdf"
298
 
299
  # Performance profiling: compute per-paper timings from agent.metrics
300
  metrics = getattr(agent, "metrics", {})
 
332
  agent = acquisition_agent
333
 
334
  # probe valid subset
335
+ urls = [(f.openAccessPdf or {}).get("url") for f in state_with_mixed_urls.finalists]
 
 
336
  probe_results = await asyncio.gather(*[_probe_url(u) for u in urls if u])
337
  logger.info(
338
  "Probed mixed URLs: {ok}/{t}",
 
342
 
343
  updated = await agent.process(state_with_mixed_urls)
344
  passages = updated.passages or []
345
+ paper_ids = {p.paper_id for p in passages}
346
 
347
  # Ensure invalid ids are not present
348
  assert "invalid1" not in paper_ids
 
394
  updated1 = await agent.process(s1)
395
  updated2 = await agent.process(s2)
396
 
397
+ ids1 = {p.paper_id for p in (updated1.passages or [])}
398
+ ids2 = {p.paper_id for p in (updated2.passages or [])}
399
 
400
  # sets of acquired paperIds should be equal (order doesn't matter)
401
  assert ids1 == ids2, f"Expected same acquired ids across runs, got {ids1} vs {ids2}"
tests/integration/test_api_endpoint.py CHANGED
@@ -33,9 +33,10 @@ import sys
33
  # CRITICAL: Set environment variables BEFORE any imports that might use parallel processing
34
  os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
35
 
36
- import pytest
37
  from unittest.mock import AsyncMock, MagicMock, patch
38
- from typing import List, TYPE_CHECKING
 
39
 
40
  # Lazy imports - only for type hints, actual imports happen in fixtures
41
  if TYPE_CHECKING:
@@ -125,9 +126,10 @@ def client(app):
125
  @pytest.fixture
126
  def mock_pipeline_result():
127
  """Create a mock PipelineResult with realistic data."""
128
- from services.query_service import PipelineResult
129
  from llama_index.core.schema import NodeWithScore, TextNode
130
 
 
 
131
  # Create mock passages with NodeWithScore objects
132
  mock_passages: List[NodeWithScore] = []
133
  passage_texts = [
@@ -415,11 +417,11 @@ def test_query_endpoint_unexpected_exception_returns_500(client, app, set_test_e
415
  @pytest.mark.integration
416
  def test_query_endpoint_no_answer_returns_fallback_message(client, app, set_test_env):
417
  """Test that when answer is None, a fallback message is returned."""
 
418
  from services.query_service import PipelineResult
419
- from llama_index.core.schema import NodeWithScore, TextNode
420
 
421
  # Create result with no answer
422
- node = TextNode(text="Some passage text", metadata={"paper_id": "p1"})
423
  result_no_answer = PipelineResult(
424
  query="test query",
425
  optimized_queries={
@@ -433,7 +435,7 @@ def test_query_endpoint_no_answer_returns_fallback_message(client, app, set_test
433
  execution_time=1.0,
434
  timing_breakdown={"query_optimization": 0.5},
435
  success=True,
436
- passages=[NodeWithScore(node=node, score=0.9)],
437
  answer=None, # No answer generated
438
  )
439
 
@@ -498,3 +500,5 @@ def test_query_endpoint_response_time_reasonable(
498
  assert response.status_code == 200
499
  # With mocked pipeline, response should be fast
500
  assert elapsed < 1.0, f"Response took {elapsed:.2f}s, expected < 1s"
 
 
 
33
  # CRITICAL: Set environment variables BEFORE any imports that might use parallel processing
34
  os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
35
 
36
+ from typing import TYPE_CHECKING, List
37
  from unittest.mock import AsyncMock, MagicMock, patch
38
+
39
+ import pytest
40
 
41
  # Lazy imports - only for type hints, actual imports happen in fixtures
42
  if TYPE_CHECKING:
 
126
  @pytest.fixture
127
  def mock_pipeline_result():
128
  """Create a mock PipelineResult with realistic data."""
 
129
  from llama_index.core.schema import NodeWithScore, TextNode
130
 
131
+ from services.query_service import PipelineResult
132
+
133
  # Create mock passages with NodeWithScore objects
134
  mock_passages: List[NodeWithScore] = []
135
  passage_texts = [
 
417
  @pytest.mark.integration
418
  def test_query_endpoint_no_answer_returns_fallback_message(client, app, set_test_env):
419
  """Test that when answer is None, a fallback message is returned."""
420
+ from models.state import Passage
421
  from services.query_service import PipelineResult
 
422
 
423
  # Create result with no answer
424
+ passage = Passage(paper_id="p1", text="Some passage text", score=0.9)
425
  result_no_answer = PipelineResult(
426
  query="test query",
427
  optimized_queries={
 
435
  execution_time=1.0,
436
  timing_breakdown={"query_optimization": 0.5},
437
  success=True,
438
+ passages=[passage],
439
  answer=None, # No answer generated
440
  )
441
 
 
500
  assert response.status_code == 200
501
  # With mocked pipeline, response should be fast
502
  assert elapsed < 1.0, f"Response took {elapsed:.2f}s, expected < 1s"
503
+ # With mocked pipeline, response should be fast
504
+ assert elapsed < 1.0, f"Response took {elapsed:.2f}s, expected < 1s"
tests/integration/test_processing_with_embeddings.py CHANGED
@@ -1,11 +1,11 @@
1
  import time
2
  from typing import List
3
 
4
- import pytest
5
  import numpy as np
 
6
 
7
  from agents.processing_agent import ProcessingAgent
8
- from models.state import State
9
 
10
 
11
  class DummyEmbedModel:
@@ -29,11 +29,11 @@ def test_three_papers_get_384_embeddings():
29
  passages = []
30
  for i in range(3):
31
  passages.append(
32
- {
33
- "paperId": f"p{i}",
34
- "title": f"Paper {i}",
35
- "text": _make_text(600),
36
- }
37
  )
38
 
39
  state = State(query="test", passages=passages)
@@ -54,8 +54,16 @@ def test_three_papers_get_384_embeddings():
54
  @pytest.mark.integration
55
  def test_chunking_failure_skips_embedding(monkeypatch):
56
  passages = [
57
- {"paperId": "bad", "title": "Bad Paper", "text": _make_text(600)},
58
- {"paperId": "good", "title": "Good Paper", "text": _make_text(600)},
 
 
 
 
 
 
 
 
59
  ]
60
 
61
  state = State(query="test2", passages=passages)
@@ -88,7 +96,13 @@ def test_chunking_failure_skips_embedding(monkeypatch):
88
 
89
  @pytest.mark.integration
90
  def test_metadata_preserved_through_embedding():
91
- passages = [{"paperId": "meta1", "title": "Meta Paper", "text": _make_text(300)}]
 
 
 
 
 
 
92
  state = State(query="meta", passages=passages)
93
  agent = ProcessingAgent(chunk_size=100, chunk_overlap=10)
94
 
@@ -107,7 +121,13 @@ def test_metadata_preserved_through_embedding():
107
  def test_end_to_end_timing_for_five_papers_is_fast():
108
  passages = []
109
  for i in range(5):
110
- passages.append({"paperId": f"t{i}", "title": f"T{i}", "text": _make_text(400)})
 
 
 
 
 
 
111
 
112
  state = State(query="timer", passages=passages)
113
  agent = ProcessingAgent(chunk_size=200, chunk_overlap=20)
@@ -137,7 +157,11 @@ def test_embedding_retry_succeeds_after_failures():
137
  return [[0.1 for _ in range(384)] for _ in range(len(texts))]
138
 
139
  passages = [
140
- {"paperId": "r1", "title": "Retry Paper", "text": _make_text(300)}
 
 
 
 
141
  for _ in range(1)
142
  ]
143
  state = State(query="retry", passages=passages)
 
1
  import time
2
  from typing import List
3
 
 
4
  import numpy as np
5
+ import pytest
6
 
7
  from agents.processing_agent import ProcessingAgent
8
+ from models.state import Passage, State
9
 
10
 
11
  class DummyEmbedModel:
 
29
  passages = []
30
  for i in range(3):
31
  passages.append(
32
+ Passage(
33
+ paper_id=f"p{i}",
34
+ text=_make_text(600),
35
+ metadata={"title": f"Paper {i}"},
36
+ )
37
  )
38
 
39
  state = State(query="test", passages=passages)
 
54
  @pytest.mark.integration
55
  def test_chunking_failure_skips_embedding(monkeypatch):
56
  passages = [
57
+ Passage(
58
+ paper_id="bad",
59
+ text=_make_text(600),
60
+ metadata={"title": "Bad Paper"},
61
+ ),
62
+ Passage(
63
+ paper_id="good",
64
+ text=_make_text(600),
65
+ metadata={"title": "Good Paper"},
66
+ ),
67
  ]
68
 
69
  state = State(query="test2", passages=passages)
 
96
 
97
  @pytest.mark.integration
98
  def test_metadata_preserved_through_embedding():
99
+ passages = [
100
+ Passage(
101
+ paper_id="meta1",
102
+ text=_make_text(300),
103
+ metadata={"title": "Meta Paper"},
104
+ )
105
+ ]
106
  state = State(query="meta", passages=passages)
107
  agent = ProcessingAgent(chunk_size=100, chunk_overlap=10)
108
 
 
121
  def test_end_to_end_timing_for_five_papers_is_fast():
122
  passages = []
123
  for i in range(5):
124
+ passages.append(
125
+ Passage(
126
+ paper_id=f"t{i}",
127
+ text=_make_text(400),
128
+ metadata={"title": f"T{i}"},
129
+ )
130
+ )
131
 
132
  state = State(query="timer", passages=passages)
133
  agent = ProcessingAgent(chunk_size=200, chunk_overlap=20)
 
157
  return [[0.1 for _ in range(384)] for _ in range(len(texts))]
158
 
159
  passages = [
160
+ Passage(
161
+ paper_id="r1",
162
+ text=_make_text(300),
163
+ metadata={"title": "Retry Paper"},
164
+ )
165
  for _ in range(1)
166
  ]
167
  state = State(query="retry", passages=passages)
tests/unit/test_acquisition_agent.py CHANGED
@@ -97,12 +97,14 @@ async def test_acquisition_enriches_state_success(monkeypatch):
97
 
98
  assert new_state.passages is not None
99
  assert len(new_state.passages) == 1
100
- pdf_passages = [p for p in new_state.passages if p["text_source"] == "pdf"]
 
 
101
  assert len(pdf_passages) == 1
102
  p = pdf_passages[0]
103
- assert p["paperId"] == "abc123"
104
- assert p["text_source"] == "pdf"
105
- assert len(p["text"]) > 500
106
 
107
 
108
  @pytest.mark.unit
@@ -266,11 +268,11 @@ async def test_acquisition_parallel_10_with_2_failures(monkeypatch):
266
  new_state = await agent.process(state)
267
  elapsed = time.monotonic() - start
268
 
269
- # successful should be 8 PDFs (all successful ones, as limit is currently disabled)
270
  passages = new_state.passages or []
271
- assert len(passages) == 8
272
- pdf_passages = [p for p in passages if p["text_source"] == "pdf"]
273
- assert len(pdf_passages) == 8
274
  # requirement: return in under 4 seconds in real world; here ensure it's fast
275
  assert elapsed < 4.0
276
  assert elapsed < 4.0
 
97
 
98
  assert new_state.passages is not None
99
  assert len(new_state.passages) == 1
100
+ pdf_passages = [
101
+ p for p in new_state.passages if p.metadata.get("text_source") == "pdf"
102
+ ]
103
  assert len(pdf_passages) == 1
104
  p = pdf_passages[0]
105
+ assert p.paper_id == "abc123"
106
+ assert p.metadata["text_source"] == "pdf"
107
+ assert len(p.text) > 500
108
 
109
 
110
  @pytest.mark.unit
 
268
  new_state = await agent.process(state)
269
  elapsed = time.monotonic() - start
270
 
271
+ # successful should be 5 PDFs (target limit)
272
  passages = new_state.passages or []
273
+ assert len(passages) == 5
274
+ pdf_passages = [p for p in passages if p.metadata.get("text_source") == "pdf"]
275
+ assert len(pdf_passages) == 5
276
  # requirement: return in under 4 seconds in real world; here ensure it's fast
277
  assert elapsed < 4.0
278
  assert elapsed < 4.0
tests/unit/test_processing_agent.py CHANGED
@@ -1,7 +1,7 @@
1
  import pytest
2
 
3
  from agents.processing_agent import ProcessingAgent
4
- from models.state import State
5
 
6
 
7
  @pytest.fixture
@@ -17,18 +17,17 @@ def test_processing_enriches_state_single_passage(make_state):
17
  state = make_state(
18
  "test",
19
  [
20
- {
21
- "paperId": "abc123",
22
- "title": "Test Paper",
23
- "text": "# Introduction\n"
24
- + "A " * 5000
25
- + "\n# Methods\n"
26
- + "B " * 5000,
27
- "text_source": "pdf",
28
- "year": 2020,
29
- "venue": "Journal of Testing",
30
- "influentialCitationCount": 2,
31
- }
32
  ],
33
  )
34
 
@@ -51,18 +50,20 @@ def test_processing_multiple_passages_generates_chunks(make_state):
51
  passages = []
52
  for i in range(3):
53
  passages.append(
54
- {
55
- "paperId": f"p{i}",
56
- "title": f"Paper {i}",
57
- "text": "# Introduction\n"
58
  + ("X " * 4000)
59
  + "\n# Results\n"
60
  + ("Y " * 4000),
61
- "text_source": "pdf",
62
- "year": 2019 + i,
63
- "venue": "Conf",
64
- "influentialCitationCount": i,
65
- }
 
 
 
66
  )
67
 
68
  state = make_state("multi", passages)
@@ -75,7 +76,10 @@ def test_processing_multiple_passages_generates_chunks(make_state):
75
 
76
  @pytest.mark.unit
77
  def test_empty_passage_is_skipped(make_state):
78
- state = make_state("empty", [{"paperId": "e1", "text": "", "text_source": "pdf"}])
 
 
 
79
  agent = ProcessingAgent(chunk_size=200, chunk_overlap=20)
80
  updated = agent.process(state)
81
 
@@ -91,7 +95,8 @@ def test_markdown_parser_handles_plain_text(make_state):
91
  # No explicit Markdown headers -> MarkdownNodeParser chunks by size
92
  long_text = "This is a paper without headers. " + ("word " * 3000)
93
  state = make_state(
94
- "plaintext", [{"paperId": "f1", "text": long_text, "text_source": "pdf"}]
 
95
  )
96
  agent = ProcessingAgent(chunk_size=400, chunk_overlap=50)
97
  updated = agent.process(state)
@@ -102,7 +107,7 @@ def test_markdown_parser_handles_plain_text(make_state):
102
 
103
  @pytest.mark.unit
104
  def test_no_passages_triggers_error():
105
- state = State(query="none", passages=None)
106
  agent = ProcessingAgent()
107
  res = agent.process(state)
108
  assert len(res.errors) > 0
 
1
  import pytest
2
 
3
  from agents.processing_agent import ProcessingAgent
4
+ from models.state import Passage, State
5
 
6
 
7
  @pytest.fixture
 
17
  state = make_state(
18
  "test",
19
  [
20
+ Passage(
21
+ paper_id="abc123",
22
+ text="# Introduction\n" + "A " * 5000 + "\n# Methods\n" + "B " * 5000,
23
+ metadata={
24
+ "title": "Test Paper",
25
+ "text_source": "pdf",
26
+ "year": 2020,
27
+ "venue": "Journal of Testing",
28
+ "influentialCitationCount": 2,
29
+ },
30
+ )
 
31
  ],
32
  )
33
 
 
50
  passages = []
51
  for i in range(3):
52
  passages.append(
53
+ Passage(
54
+ paper_id=f"p{i}",
55
+ text="# Introduction\n"
 
56
  + ("X " * 4000)
57
  + "\n# Results\n"
58
  + ("Y " * 4000),
59
+ metadata={
60
+ "title": f"Paper {i}",
61
+ "text_source": "pdf",
62
+ "year": 2019 + i,
63
+ "venue": "Conf",
64
+ "influentialCitationCount": i,
65
+ },
66
+ )
67
  )
68
 
69
  state = make_state("multi", passages)
 
76
 
77
  @pytest.mark.unit
78
  def test_empty_passage_is_skipped(make_state):
79
+ state = make_state(
80
+ "empty",
81
+ [Passage(paper_id="e1", text="", metadata={"text_source": "pdf"})],
82
+ )
83
  agent = ProcessingAgent(chunk_size=200, chunk_overlap=20)
84
  updated = agent.process(state)
85
 
 
95
  # No explicit Markdown headers -> MarkdownNodeParser chunks by size
96
  long_text = "This is a paper without headers. " + ("word " * 3000)
97
  state = make_state(
98
+ "plaintext",
99
+ [Passage(paper_id="f1", text=long_text, metadata={"text_source": "pdf"})],
100
  )
101
  agent = ProcessingAgent(chunk_size=400, chunk_overlap=50)
102
  updated = agent.process(state)
 
107
 
108
  @pytest.mark.unit
109
  def test_no_passages_triggers_error():
110
+ state = State(query="none", passages=[])
111
  agent = ProcessingAgent()
112
  res = agent.process(state)
113
  assert len(res.errors) > 0
tests/unit/test_ranking_agent.py CHANGED
@@ -2,6 +2,7 @@ import numpy as np
2
  import pytest
3
 
4
  from agents.ranking_agent import RankingAgent
 
5
 
6
 
7
  @pytest.fixture
@@ -18,15 +19,15 @@ def mock_paper_high_similarity(sample_query_embedding):
18
  # Create a similar embedding
19
  emb = sample_query_embedding + np.random.rand(384) * 0.1
20
  emb = emb / np.linalg.norm(emb)
21
- return {
22
- "paperId": "paper_high_sim",
23
- "title": "High Similarity Paper",
24
- "abstract": "Abstract high similarity",
25
- "embedding": {"specter": emb}, # High similarity
26
- "influentialCitationCount": 50,
27
- "citationCount": 200,
28
- "year": 2023,
29
- }
30
 
31
 
32
  @pytest.fixture
@@ -36,15 +37,15 @@ def mock_paper_high_citations(sample_query_embedding):
36
  np.random.seed(43)
37
  emb = sample_query_embedding - np.random.rand(384) * 0.5
38
  emb = emb / np.linalg.norm(emb)
39
- return {
40
- "paperId": "paper_high_cit",
41
- "title": "High Citations Paper",
42
- "abstract": "Abstract high citations",
43
- "embedding": {"specter": emb}, # Less similar
44
- "influentialCitationCount": 200,
45
- "citationCount": 1000,
46
- "year": 2015, # Very old to allow recency boost
47
- }
48
 
49
 
50
  @pytest.fixture
@@ -54,28 +55,28 @@ def mock_paper_recent(sample_query_embedding):
54
  np.random.seed(44)
55
  emb = sample_query_embedding + np.random.rand(384) * 0.1 # More similar
56
  emb = emb / np.linalg.norm(emb)
57
- return {
58
- "paperId": "paper_recent",
59
- "title": "Recent Paper",
60
- "abstract": "Abstract recent",
61
- "embedding": {"specter": emb}, # Moderate similarity
62
- "influentialCitationCount": 10,
63
- "citationCount": 50,
64
- "year": 2024,
65
- }
66
 
67
 
68
  @pytest.fixture
69
  def mock_paper_missing_embedding():
70
  """A mock paper missing embedding."""
71
- return {
72
- "paperId": "paper_no_emb",
73
- "title": "No Embedding Paper",
74
- "abstract": "No embedding abstract",
75
- "influentialCitationCount": 20,
76
- "citationCount": 100,
77
- "year": 2020,
78
- }
79
 
80
 
81
  @pytest.fixture
@@ -83,13 +84,13 @@ def mock_paper_missing_citations(sample_query_embedding):
83
  """A mock paper missing citation counts."""
84
  emb = sample_query_embedding + np.random.rand(384) * 0.2
85
  emb = emb / np.linalg.norm(emb)
86
- return {
87
- "paperId": "paper_no_cit",
88
- "title": "No Citations Paper",
89
- "abstract": "No citations abstract",
90
- "embedding": {"specter": emb},
91
- "year": 2022,
92
- }
93
 
94
 
95
  @pytest.fixture
@@ -97,14 +98,14 @@ def mock_paper_missing_year(sample_query_embedding):
97
  """A mock paper missing year."""
98
  emb = sample_query_embedding + np.random.rand(384) * 0.15
99
  emb = emb / np.linalg.norm(emb)
100
- return {
101
- "paperId": "paper_no_year",
102
- "title": "No Year Paper",
103
- "abstract": "No year abstract",
104
- "embedding": {"specter": emb},
105
- "influentialCitationCount": 15,
106
- "citationCount": 75,
107
- }
108
 
109
 
110
  @pytest.mark.unit
@@ -126,13 +127,13 @@ def test_papers_ranked_correctly_by_composite_score(
126
 
127
  # Check that all have the new score fields
128
  for paper in finalists:
129
- assert "final_score" in paper
130
- assert "relevance_score" in paper
131
- assert "authority_score" in paper
132
- assert "recency_score" in paper
133
 
134
  # Expect high similarity paper to be among the top results
135
- assert finalists[0]["paperId"] in {"paper_high_sim", "paper_recent"}
136
 
137
 
138
  @pytest.mark.unit
@@ -142,32 +143,32 @@ def test_high_semantic_similarity_ranks_higher_than_low_similarity_high_citation
142
  """Test case 2: High semantic similarity paper ranks higher than low similarity but high citations."""
143
  agent = RankingAgent()
144
 
145
- paper_sim = {
146
- "paperId": "perfect_sim",
147
- "title": "Perfect Sim",
148
- "abstract": "abstract",
149
- "embedding": {"specter": sample_query_embedding}, # Perfect similarity
150
- "influentialCitationCount": 1,
151
- "citationCount": 5,
152
- "year": 2020,
153
- }
154
-
155
- paper_cit = {
156
- "paperId": "high_cit",
157
- "title": "High Cit",
158
- "abstract": "abstract",
159
- "embedding": {"specter": -sample_query_embedding},
160
- "influentialCitationCount": 100,
161
- "citationCount": 500,
162
- "year": 2020,
163
- }
164
 
165
  papers = [paper_sim, paper_cit]
166
  finalists = agent.rank_papers(papers, query="test")
167
 
168
  # Verify relevance scores reflect similarity ordering (perfect_sim should have >= relevance)
169
  # Find the two papers in the finalists list
170
- scores_by_id = {p["paperId"]: p["relevance_score"] for p in finalists}
171
  assert scores_by_id["perfect_sim"] >= scores_by_id["high_cit"]
172
 
173
 
@@ -176,35 +177,35 @@ def test_recent_paper_gets_recency_boost(sample_query_embedding):
176
  """Test case 3: Recent paper (2024) gets recency boost over older paper (2015)."""
177
  agent = RankingAgent()
178
 
179
- paper_recent = {
180
- "paperId": "recent",
181
- "title": "Recent",
182
- "abstract": "Recent abstract",
183
- "embedding": {"specter": sample_query_embedding},
184
- "influentialCitationCount": 10,
185
- "citationCount": 50,
186
- "year": 2024, # Max recency
187
- }
188
-
189
- paper_old = {
190
- "paperId": "old",
191
- "title": "Old",
192
- "abstract": "Old abstract",
193
- "embedding": {"specter": sample_query_embedding},
194
- "influentialCitationCount": 10,
195
- "citationCount": 50,
196
- "year": 2015, # Min recency
197
- }
198
 
199
  papers = [paper_recent, paper_old]
200
  finalists = agent.rank_papers(papers, query="test")
201
 
202
  # Recent paper should rank at least as high as old paper
203
- assert finalists[0]["paperId"] == "recent"
204
- assert finalists[1]["paperId"] == "old"
205
 
206
  # Recency scores: recent > old
207
- recency_scores = {p["paperId"]: p["recency_score"] for p in finalists}
208
  assert recency_scores["recent"] > recency_scores["old"]
209
 
210
 
@@ -230,8 +231,8 @@ def test_missing_fields_handled_gracefully(
230
 
231
  # Ensure score fields exist and are numeric
232
  for paper in finalists:
233
- assert isinstance(paper.get("final_score"), float)
234
- assert isinstance(paper.get("relevance_score"), float)
235
 
236
 
237
  @pytest.mark.unit
@@ -243,15 +244,15 @@ def test_edge_case_identical_scores(sample_query_embedding):
243
  papers = []
244
  for i in range(5):
245
  papers.append(
246
- {
247
- "paperId": f"identical_{i}",
248
- "title": f"identical_{i}",
249
- "abstract": "a",
250
- "embedding": {"specter": sample_query_embedding},
251
- "influentialCitationCount": 10,
252
- "citationCount": 50,
253
- "year": 2020,
254
- }
255
  )
256
 
257
  finalists = agent.rank_papers(papers, query="identical")
@@ -260,12 +261,12 @@ def test_edge_case_identical_scores(sample_query_embedding):
260
  assert len(finalists) == 5
261
 
262
  # All should have identical scores
263
- scores = [p["final_score"] for p in finalists]
264
  # Scores should be equal (or very close) for identical inputs
265
  assert all(abs(s - scores[0]) < 1e-6 for s in scores)
266
 
267
  # Order should be stable-ish (we accept preserving input order)
268
- assert [p["paperId"] for p in finalists] == [f"identical_{i}" for i in range(5)]
269
 
270
 
271
  @pytest.mark.unit
@@ -301,15 +302,15 @@ def test_more_than_10_papers_returns_top_10(sample_query_embedding):
301
  for i in range(15):
302
  similarity_offset = i * 0.1 # Decreasing similarity
303
  papers.append(
304
- {
305
- "paperId": f"paper_{i}",
306
- "title": f"paper_{i}",
307
- "abstract": "a",
308
- "embedding": {"specter": (sample_query_embedding - similarity_offset)},
309
- "influentialCitationCount": 10,
310
- "citationCount": 50,
311
- "year": 2020,
312
- }
313
  )
314
 
315
  finalists = agent.rank_papers(papers, query="rank", top_k=10)
@@ -318,7 +319,7 @@ def test_more_than_10_papers_returns_top_10(sample_query_embedding):
318
  assert len(finalists) == 10
319
 
320
  # Should be the top 10 (highest similarity first)
321
- returned_ids = [p["paperId"] for p in finalists]
322
  assert len(returned_ids) == 10
323
 
324
 
@@ -328,30 +329,30 @@ def test_log_normalization_handles_zero_citations():
328
  agent = RankingAgent()
329
 
330
  papers = [
331
- {
332
- "paperId": "zero_auth",
333
- "title": "zero_auth",
334
- "abstract": "a",
335
- "embedding": {"specter": np.random.rand(384)},
336
- "influentialCitationCount": 0,
337
- "citationCount": 100,
338
- "year": 2020,
339
- },
340
- {
341
- "paperId": "zero_impact",
342
- "title": "zero_impact",
343
- "abstract": "a",
344
- "embedding": {"specter": np.random.rand(384)},
345
- "influentialCitationCount": 50,
346
- "citationCount": 0,
347
- "year": 2020,
348
- },
349
  ]
350
 
351
  finalists = agent.rank_papers(papers, query="q")
352
 
353
  # At least one paper should show zero authority or impact related component
354
- assert any(p.get("authority_score", 0.0) == 0.0 for p in finalists)
355
 
356
 
357
  @pytest.mark.unit
@@ -360,30 +361,30 @@ def test_year_clamping():
360
  agent = RankingAgent()
361
 
362
  papers = [
363
- {
364
- "paperId": "too_old",
365
- "title": "too_old",
366
- "abstract": "a",
367
- "embedding": {"specter": np.random.rand(384)},
368
- "influentialCitationCount": 10,
369
- "citationCount": 50,
370
- "year": 2000, # Below 2015
371
- },
372
- {
373
- "paperId": "too_new",
374
- "title": "too_new",
375
- "abstract": "a",
376
- "embedding": {"specter": np.random.rand(384)},
377
- "influentialCitationCount": 10,
378
- "citationCount": 50,
379
- "year": 2030, # Above 2025
380
- },
381
  ]
382
 
383
  finalists = agent.rank_papers(papers, query="q")
384
 
385
  # Both should have recency score values within 0..1 after normalization
386
- recency_scores = [paper["recency_score"] for paper in finalists]
387
  assert all(0.0 <= s <= 1.0 for s in recency_scores)
388
 
389
 
@@ -397,15 +398,15 @@ def test_composite_score_calculation():
397
  papers = []
398
  for i in range(3):
399
  papers.append(
400
- {
401
- "paperId": f"p{i}",
402
- "title": "t",
403
- "abstract": "a",
404
- "embedding": {"specter": np.ones(384)},
405
- "influentialCitationCount": 1,
406
- "citationCount": 1,
407
- "year": 2020,
408
- }
409
  )
410
 
411
  finalists = agent.rank_papers(papers, query="q")
@@ -419,41 +420,41 @@ def test_composite_score_ranking_behavior():
419
 
420
  # Create papers with different score profiles
421
  papers = [
422
- {
423
- "paperId": "high_semantic",
424
- "title": "High Semantic",
425
- "abstract": "high semantic abstract",
426
- "embedding": {"specter": np.ones(384)},
427
- "influentialCitationCount": 10,
428
- "citationCount": 20,
429
- "year": 2020,
430
- },
431
- {
432
- "paperId": "high_citations",
433
- "title": "High Citations",
434
- "abstract": "high citations abstract",
435
- "embedding": {"specter": np.zeros(384)},
436
- "influentialCitationCount": 1000,
437
- "citationCount": 5000,
438
- "year": 2015,
439
- },
440
- {
441
- "paperId": "high_recency",
442
- "title": "High Recency",
443
- "abstract": "high recency abstract",
444
- "embedding": {"specter": np.zeros(384)},
445
- "influentialCitationCount": 10,
446
- "citationCount": 20,
447
- "year": 2025,
448
- },
449
  ]
450
 
451
  finalists = agent.rank_papers(papers, query="q")
452
 
453
  # High semantic should rank first (perfect similarity)
454
- assert finalists[0]["paperId"] == "high_semantic"
455
  # High citations and recency follow (order may vary depending on ties)
456
- assert set([finalists[1]["paperId"], finalists[2]["paperId"]]) == {
457
  "high_citations",
458
  "high_recency",
459
  }
@@ -474,18 +475,18 @@ def test_composite_score_recency_boost():
474
  }
475
 
476
  papers = [
477
- {**base_paper, "paperId": "old", "title": "Old Paper", "year": 2015},
478
- {**base_paper, "paperId": "new", "title": "New Paper", "year": 2025},
479
  ]
480
 
481
  finalists = agent.rank_papers(papers, query="q")
482
 
483
  # New paper should rank higher due to recency boost
484
- assert finalists[0]["paperId"] == "new"
485
- assert finalists[1]["paperId"] == "old"
486
 
487
  # Recency scores should be greater for the newer paper
488
- assert finalists[0]["recency_score"] > finalists[1]["recency_score"]
489
 
490
 
491
  @pytest.mark.unit
@@ -500,15 +501,15 @@ def test_composite_score_edge_cases():
500
  papers = []
501
  for i in range(3):
502
  papers.append(
503
- {
504
- "paperId": f"e{i}",
505
- "title": "t",
506
- "abstract": "a",
507
- "embedding": {"specter": np.ones(384)},
508
- "influentialCitationCount": 0,
509
- "citationCount": 0,
510
- "year": 2020,
511
- }
512
  )
513
 
514
  finalists = agent.rank_papers(papers, query="q")
 
2
  import pytest
3
 
4
  from agents.ranking_agent import RankingAgent
5
+ from models.state import Paper
6
 
7
 
8
  @pytest.fixture
 
19
  # Create a similar embedding
20
  emb = sample_query_embedding + np.random.rand(384) * 0.1
21
  emb = emb / np.linalg.norm(emb)
22
+ return Paper(
23
+ paperId="paper_high_sim",
24
+ title="High Similarity Paper",
25
+ abstract="Abstract high similarity",
26
+ embedding={"specter": emb}, # High similarity
27
+ influentialCitationCount=50,
28
+ citationCount=200,
29
+ year=2023,
30
+ )
31
 
32
 
33
  @pytest.fixture
 
37
  np.random.seed(43)
38
  emb = sample_query_embedding - np.random.rand(384) * 0.5
39
  emb = emb / np.linalg.norm(emb)
40
+ return Paper(
41
+ paperId="paper_high_cit",
42
+ title="High Citations Paper",
43
+ abstract="Abstract high citations",
44
+ embedding={"specter": emb}, # Less similar
45
+ influentialCitationCount=200,
46
+ citationCount=1000,
47
+ year=2015, # Very old to allow recency boost
48
+ )
49
 
50
 
51
  @pytest.fixture
 
55
  np.random.seed(44)
56
  emb = sample_query_embedding + np.random.rand(384) * 0.1 # More similar
57
  emb = emb / np.linalg.norm(emb)
58
+ return Paper(
59
+ paperId="paper_recent",
60
+ title="Recent Paper",
61
+ abstract="Abstract recent",
62
+ embedding={"specter": emb}, # Moderate similarity
63
+ influentialCitationCount=10,
64
+ citationCount=50,
65
+ year=2024,
66
+ )
67
 
68
 
69
  @pytest.fixture
70
  def mock_paper_missing_embedding():
71
  """A mock paper missing embedding."""
72
+ return Paper(
73
+ paperId="paper_no_emb",
74
+ title="No Embedding Paper",
75
+ abstract="No embedding abstract",
76
+ influentialCitationCount=20,
77
+ citationCount=100,
78
+ year=2020,
79
+ )
80
 
81
 
82
  @pytest.fixture
 
84
  """A mock paper missing citation counts."""
85
  emb = sample_query_embedding + np.random.rand(384) * 0.2
86
  emb = emb / np.linalg.norm(emb)
87
+ return Paper(
88
+ paperId="paper_no_cit",
89
+ title="No Citations Paper",
90
+ abstract="No citations abstract",
91
+ embedding={"specter": emb},
92
+ year=2022,
93
+ )
94
 
95
 
96
  @pytest.fixture
 
98
  """A mock paper missing year."""
99
  emb = sample_query_embedding + np.random.rand(384) * 0.15
100
  emb = emb / np.linalg.norm(emb)
101
+ return Paper(
102
+ paperId="paper_no_year",
103
+ title="No Year Paper",
104
+ abstract="No year abstract",
105
+ embedding={"specter": emb},
106
+ influentialCitationCount=15,
107
+ citationCount=75,
108
+ )
109
 
110
 
111
  @pytest.mark.unit
 
127
 
128
  # Check that all have the new score fields
129
  for paper in finalists:
130
+ assert hasattr(paper, "final_score")
131
+ assert hasattr(paper, "relevance_score")
132
+ assert hasattr(paper, "authority_score")
133
+ assert hasattr(paper, "recency_score")
134
 
135
  # Expect high similarity paper to be among the top results
136
+ assert finalists[0].paperId in {"paper_high_sim", "paper_recent"}
137
 
138
 
139
  @pytest.mark.unit
 
143
  """Test case 2: High semantic similarity paper ranks higher than low similarity but high citations."""
144
  agent = RankingAgent()
145
 
146
+ paper_sim = Paper(
147
+ paperId="perfect_sim",
148
+ title="Perfect Sim",
149
+ abstract="abstract",
150
+ embedding={"specter": sample_query_embedding}, # Perfect similarity
151
+ influentialCitationCount=1,
152
+ citationCount=5,
153
+ year=2020,
154
+ )
155
+
156
+ paper_cit = Paper(
157
+ paperId="high_cit",
158
+ title="High Cit",
159
+ abstract="abstract",
160
+ embedding={"specter": -sample_query_embedding},
161
+ influentialCitationCount=100,
162
+ citationCount=500,
163
+ year=2020,
164
+ )
165
 
166
  papers = [paper_sim, paper_cit]
167
  finalists = agent.rank_papers(papers, query="test")
168
 
169
  # Verify relevance scores reflect similarity ordering (perfect_sim should have >= relevance)
170
  # Find the two papers in the finalists list
171
+ scores_by_id = {p.paperId: p.relevance_score for p in finalists}
172
  assert scores_by_id["perfect_sim"] >= scores_by_id["high_cit"]
173
 
174
 
 
177
  """Test case 3: Recent paper (2024) gets recency boost over older paper (2015)."""
178
  agent = RankingAgent()
179
 
180
+ paper_recent = Paper(
181
+ paperId="recent",
182
+ title="Recent",
183
+ abstract="Recent abstract",
184
+ embedding={"specter": sample_query_embedding},
185
+ influentialCitationCount=10,
186
+ citationCount=50,
187
+ year=2024, # Max recency
188
+ )
189
+
190
+ paper_old = Paper(
191
+ paperId="old",
192
+ title="Old",
193
+ abstract="Old abstract",
194
+ embedding={"specter": sample_query_embedding},
195
+ influentialCitationCount=10,
196
+ citationCount=50,
197
+ year=2015, # Min recency
198
+ )
199
 
200
  papers = [paper_recent, paper_old]
201
  finalists = agent.rank_papers(papers, query="test")
202
 
203
  # Recent paper should rank at least as high as old paper
204
+ assert finalists[0].paperId == "recent"
205
+ assert finalists[1].paperId == "old"
206
 
207
  # Recency scores: recent > old
208
+ recency_scores = {p.paperId: p.recency_score for p in finalists}
209
  assert recency_scores["recent"] > recency_scores["old"]
210
 
211
 
 
231
 
232
  # Ensure score fields exist and are numeric
233
  for paper in finalists:
234
+ assert isinstance(paper.final_score, float)
235
+ assert isinstance(paper.relevance_score, float)
236
 
237
 
238
  @pytest.mark.unit
 
244
  papers = []
245
  for i in range(5):
246
  papers.append(
247
+ Paper(
248
+ paperId=f"identical_{i}",
249
+ title=f"identical_{i}",
250
+ abstract="a",
251
+ embedding={"specter": sample_query_embedding},
252
+ influentialCitationCount=10,
253
+ citationCount=50,
254
+ year=2020,
255
+ )
256
  )
257
 
258
  finalists = agent.rank_papers(papers, query="identical")
 
261
  assert len(finalists) == 5
262
 
263
  # All should have identical scores
264
+ scores = [p.final_score for p in finalists]
265
  # Scores should be equal (or very close) for identical inputs
266
  assert all(abs(s - scores[0]) < 1e-6 for s in scores)
267
 
268
  # Order should be stable-ish (we accept preserving input order)
269
+ assert [p.paperId for p in finalists] == [f"identical_{i}" for i in range(5)]
270
 
271
 
272
  @pytest.mark.unit
 
302
  for i in range(15):
303
  similarity_offset = i * 0.1 # Decreasing similarity
304
  papers.append(
305
+ Paper(
306
+ paperId=f"paper_{i}",
307
+ title=f"paper_{i}",
308
+ abstract="a",
309
+ embedding={"specter": (sample_query_embedding - similarity_offset)},
310
+ influentialCitationCount=10,
311
+ citationCount=50,
312
+ year=2020,
313
+ )
314
  )
315
 
316
  finalists = agent.rank_papers(papers, query="rank", top_k=10)
 
319
  assert len(finalists) == 10
320
 
321
  # Should be the top 10 (highest similarity first)
322
+ returned_ids = [p.paperId for p in finalists]
323
  assert len(returned_ids) == 10
324
 
325
 
 
329
  agent = RankingAgent()
330
 
331
  papers = [
332
+ Paper(
333
+ paperId="zero_auth",
334
+ title="zero_auth",
335
+ abstract="a",
336
+ embedding={"specter": np.random.rand(384)},
337
+ influentialCitationCount=0,
338
+ citationCount=100,
339
+ year=2020,
340
+ ),
341
+ Paper(
342
+ paperId="zero_impact",
343
+ title="zero_impact",
344
+ abstract="a",
345
+ embedding={"specter": np.random.rand(384)},
346
+ influentialCitationCount=50,
347
+ citationCount=0,
348
+ year=2020,
349
+ ),
350
  ]
351
 
352
  finalists = agent.rank_papers(papers, query="q")
353
 
354
  # At least one paper should show zero authority or impact related component
355
+ assert any(getattr(p, "authority_score", 0.0) == 0.0 for p in finalists)
356
 
357
 
358
  @pytest.mark.unit
 
361
  agent = RankingAgent()
362
 
363
  papers = [
364
+ Paper(
365
+ paperId="too_old",
366
+ title="too_old",
367
+ abstract="a",
368
+ embedding={"specter": np.random.rand(384)},
369
+ influentialCitationCount=10,
370
+ citationCount=50,
371
+ year=2000, # Below 2015
372
+ ),
373
+ Paper(
374
+ paperId="too_new",
375
+ title="too_new",
376
+ abstract="a",
377
+ embedding={"specter": np.random.rand(384)},
378
+ influentialCitationCount=10,
379
+ citationCount=50,
380
+ year=2030, # Above 2025
381
+ ),
382
  ]
383
 
384
  finalists = agent.rank_papers(papers, query="q")
385
 
386
  # Both should have recency score values within 0..1 after normalization
387
+ recency_scores = [paper.recency_score for paper in finalists]
388
  assert all(0.0 <= s <= 1.0 for s in recency_scores)
389
 
390
 
 
398
  papers = []
399
  for i in range(3):
400
  papers.append(
401
+ Paper(
402
+ paperId=f"p{i}",
403
+ title="t",
404
+ abstract="a",
405
+ embedding={"specter": np.ones(384)},
406
+ influentialCitationCount=1,
407
+ citationCount=1,
408
+ year=2020,
409
+ )
410
  )
411
 
412
  finalists = agent.rank_papers(papers, query="q")
 
420
 
421
  # Create papers with different score profiles
422
  papers = [
423
+ Paper(
424
+ paperId="high_semantic",
425
+ title="High Semantic",
426
+ abstract="high semantic abstract",
427
+ embedding={"specter": np.ones(384)},
428
+ influentialCitationCount=10,
429
+ citationCount=20,
430
+ year=2020,
431
+ ),
432
+ Paper(
433
+ paperId="high_citations",
434
+ title="High Citations",
435
+ abstract="high citations abstract",
436
+ embedding={"specter": np.zeros(384)},
437
+ influentialCitationCount=1000,
438
+ citationCount=5000,
439
+ year=2015,
440
+ ),
441
+ Paper(
442
+ paperId="high_recency",
443
+ title="High Recency",
444
+ abstract="high recency abstract",
445
+ embedding={"specter": np.zeros(384)},
446
+ influentialCitationCount=10,
447
+ citationCount=20,
448
+ year=2025,
449
+ ),
450
  ]
451
 
452
  finalists = agent.rank_papers(papers, query="q")
453
 
454
  # High semantic should rank first (perfect similarity)
455
+ assert finalists[0].paperId == "high_semantic"
456
  # High citations and recency follow (order may vary depending on ties)
457
+ assert set([finalists[1].paperId, finalists[2].paperId]) == {
458
  "high_citations",
459
  "high_recency",
460
  }
 
475
  }
476
 
477
  papers = [
478
+ Paper(**{**base_paper, "paperId": "old", "title": "Old Paper", "year": 2015}),
479
+ Paper(**{**base_paper, "paperId": "new", "title": "New Paper", "year": 2025}),
480
  ]
481
 
482
  finalists = agent.rank_papers(papers, query="q")
483
 
484
  # New paper should rank higher due to recency boost
485
+ assert finalists[0].paperId == "new"
486
+ assert finalists[1].paperId == "old"
487
 
488
  # Recency scores should be greater for the newer paper
489
+ assert finalists[0].recency_score > finalists[1].recency_score
490
 
491
 
492
  @pytest.mark.unit
 
501
  papers = []
502
  for i in range(3):
503
  papers.append(
504
+ Paper(
505
+ paperId=f"e{i}",
506
+ title="t",
507
+ abstract="a",
508
+ embedding={"specter": np.ones(384)},
509
+ influentialCitationCount=0,
510
+ citationCount=0,
511
+ year=2020,
512
+ )
513
  )
514
 
515
  finalists = agent.rank_papers(papers, query="q")
ui/components.py CHANGED
@@ -1,9 +1,10 @@
1
  """Reusable UI components for Necthrall."""
2
 
3
- from nicegui import ui
4
- from loguru import logger
5
  import json
6
 
 
 
 
7
 
8
  def render_loading():
9
  """Render the loading spinner with status text."""
@@ -27,11 +28,9 @@ def render_answer(result):
27
  """Construct and copy content to clipboard."""
28
  content = result.answer + "\n\n### Sources Cited\n"
29
  for idx, passage in enumerate(result.passages):
30
- metadata = (
31
- passage.node.metadata if hasattr(passage.node, "metadata") else {}
32
- )
33
- title = metadata.get("paper_title", "Unknown Source")
34
- url = metadata.get("pdf_url", "") or metadata.get("url", "")
35
  content += f"{idx + 1}. {title} - {url}\n"
36
 
37
  # Serialize to JSON to handle quotes/newlines safely
@@ -77,19 +76,13 @@ def render_sources(passages):
77
  for idx, passage in enumerate(passages):
78
  try:
79
  # Extract passage info
80
- text = (
81
- passage.node.get_content()
82
- if hasattr(passage.node, "get_content")
83
- else str(passage.node)
84
- )
85
- metadata = (
86
- passage.node.metadata if hasattr(passage.node, "metadata") else {}
87
- )
88
- paper_title = metadata.get("paper_title", "Unknown Source")
89
- paper_id = metadata.get("paper_id", "")
90
  section = metadata.get("section", "")
91
  # Try to get PDF URL from metadata
92
- pdf_url = metadata.get("pdf_url", "") or metadata.get("url", "")
93
 
94
  with ui.expansion().classes("source-card").props("dense") as expansion:
95
  # Header slot for title
 
1
  """Reusable UI components for Necthrall."""
2
 
 
 
3
  import json
4
 
5
+ from loguru import logger
6
+ from nicegui import ui
7
+
8
 
9
  def render_loading():
10
  """Render the loading spinner with status text."""
 
28
  """Construct and copy content to clipboard."""
29
  content = result.answer + "\n\n### Sources Cited\n"
30
  for idx, passage in enumerate(result.passages):
31
+ metadata = getattr(passage, "metadata", {})
32
+ title = metadata.get("title", "Unknown Source")
33
+ url = metadata.get("url", "")
 
 
34
  content += f"{idx + 1}. {title} - {url}\n"
35
 
36
  # Serialize to JSON to handle quotes/newlines safely
 
76
  for idx, passage in enumerate(passages):
77
  try:
78
  # Extract passage info
79
+ text = getattr(passage, "text", "")
80
+ metadata = getattr(passage, "metadata", {})
81
+ paper_title = metadata.get("title", "Unknown Source")
82
+ paper_id = getattr(passage, "paper_id", "")
 
 
 
 
 
 
83
  section = metadata.get("section", "")
84
  # Try to get PDF URL from metadata
85
+ pdf_url = metadata.get("url", "")
86
 
87
  with ui.expansion().classes("source-card").props("dense") as expansion:
88
  # Header slot for title
ui/pages.py CHANGED
@@ -359,38 +359,34 @@ def init_ui(fastapi_app):
359
  try:
360
  import json
361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  result_data = {
363
  "answer": result.answer,
364
  "execution_time": result.execution_time,
365
  "finalists": len(result.finalists),
366
- "passages": [
367
- {
368
- "content": (
369
- passage.node.get_content()
370
- if hasattr(passage.node, "get_content")
371
- else str(passage.node)
372
- ),
373
- "title": (
374
- passage.node.metadata.get(
375
- "paper_title", "Unknown"
376
- )
377
- if hasattr(passage.node, "metadata")
378
- else "Unknown"
379
- ),
380
- "section": (
381
- passage.node.metadata.get("section", "")
382
- if hasattr(passage.node, "metadata")
383
- else ""
384
- ),
385
- "url": (
386
- passage.node.metadata.get("pdf_url", "")
387
- or passage.node.metadata.get("url", "")
388
- if hasattr(passage.node, "metadata")
389
- else ""
390
- ),
391
- }
392
- for passage in result.passages
393
- ],
394
  "query": query_text,
395
  }
396
  ui.run_javascript(
@@ -591,15 +587,14 @@ def init_ui(fastapi_app):
591
  ):
592
  with expansion.add_slot("header"):
593
  with ui.column().classes("w-full"):
594
- ui.label(passage["title"]).classes(
595
- "source-title"
596
- )
597
 
598
  meta_parts = []
599
- if passage["section"]:
600
- meta_parts.append(
601
- passage["section"]
602
- )
603
  meta_parts.append(
604
  f"Citation [{idx + 1}]"
605
  )
@@ -607,14 +602,15 @@ def init_ui(fastapi_app):
607
  " • ".join(meta_parts)
608
  ).classes("source-meta")
609
 
610
- if passage["url"]:
 
611
  with ui.row().classes(
612
  "items-center mt-2"
613
  ):
614
  with (
615
  ui.element("a")
616
  .props(
617
- f'href="{passage["url"]}" target="_blank"'
618
  )
619
  .classes(
620
  "source-link-btn"
@@ -633,9 +629,9 @@ def init_ui(fastapi_app):
633
  )
634
 
635
  with ui.column().classes("passage-content"):
636
- ui.label(passage["content"]).classes(
637
- "source-snippet"
638
- )
639
 
640
  logger.info(
641
  f"✅ Restored cached result for query: {cached_data['query']}"
 
359
  try:
360
  import json
361
 
362
+ # Serialize passages (Lightweight for localStorage)
363
+ serialized_passages = []
364
+ for p in result.passages:
365
+ # Handle Pydantic Passage object
366
+ text = getattr(p, "text", "")
367
+ metadata = getattr(p, "metadata", {})
368
+ score = getattr(p, "score", None)
369
+
370
+ # Truncate content to prevent localStorage overflow
371
+ content_snippet = (
372
+ text[:200] + "..." if len(text) > 200 else text
373
+ )
374
+
375
+ serialized_passages.append(
376
+ {
377
+ "content": content_snippet,
378
+ "title": metadata.get("title", "Unknown"),
379
+ "url": metadata.get("url", ""),
380
+ "score": score,
381
+ "section": metadata.get("section", ""),
382
+ }
383
+ )
384
+
385
  result_data = {
386
  "answer": result.answer,
387
  "execution_time": result.execution_time,
388
  "finalists": len(result.finalists),
389
+ "passages": serialized_passages,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
  "query": query_text,
391
  }
392
  ui.run_javascript(
 
587
  ):
588
  with expansion.add_slot("header"):
589
  with ui.column().classes("w-full"):
590
+ ui.label(
591
+ passage.get("title", "Unknown")
592
+ ).classes("source-title")
593
 
594
  meta_parts = []
595
+ section = passage.get("section")
596
+ if section:
597
+ meta_parts.append(section)
 
598
  meta_parts.append(
599
  f"Citation [{idx + 1}]"
600
  )
 
602
  " • ".join(meta_parts)
603
  ).classes("source-meta")
604
 
605
+ url = passage.get("url")
606
+ if url:
607
  with ui.row().classes(
608
  "items-center mt-2"
609
  ):
610
  with (
611
  ui.element("a")
612
  .props(
613
+ f'href="{url}" target="_blank"'
614
  )
615
  .classes(
616
  "source-link-btn"
 
629
  )
630
 
631
  with ui.column().classes("passage-content"):
632
+ ui.label(
633
+ passage.get("content", "")
634
+ ).classes("source-snippet")
635
 
636
  logger.info(
637
  f"✅ Restored cached result for query: {cached_data['query']}"