Adam Cseresznye commited on
Commit
3d1a04f
·
1 Parent(s): cd26350

Implement async Semantic Scholar client and add LLM router

Browse files
Files changed (42) hide show
  1. agents/semantic_scholar_client.py +355 -12
  2. models/state.py +1 -1
  3. pyproject.toml +51 -0
  4. scripts/analyze_test_categories.py +0 -1
  5. scripts/batch_benchmark.py +0 -1
  6. scripts/benchmark_agent_comparison.py +0 -1
  7. scripts/benchmark_week2_performance.py +0 -1
  8. scripts/check_abstract_availability.py +0 -1
  9. scripts/check_env.py +0 -1
  10. scripts/check_imports.py +0 -1
  11. scripts/collect_openalex_stats.py +0 -1
  12. scripts/debug_chunker.py +0 -1
  13. scripts/debug_embedding_call.py +0 -1
  14. scripts/debug_openalex_diagnostics.py +0 -1
  15. scripts/debug_openalex_response.py +0 -1
  16. scripts/debug_pdf_availability.py +0 -1
  17. scripts/debug_pop_query.py +0 -1
  18. scripts/debug_processing_run.py +0 -1
  19. scripts/embedding_demo.py +0 -1
  20. scripts/generate_test_data.py +0 -1
  21. scripts/pdf_test_extraction.py +0 -1
  22. scripts/pdf_test_search.py +0 -1
  23. scripts/performance_test.py +0 -1
  24. scripts/performance_test_script.py +0 -1
  25. scripts/performance_validation.py +0 -1
  26. scripts/quick_performance_test.py +0 -1
  27. scripts/run_llm_test.py +20 -0
  28. scripts/run_semantic_scholar_client.py +84 -0
  29. scripts/show_recommended_models.py +0 -1
  30. scripts/test_end_to_end_pipeline.py +0 -1
  31. scripts/test_hybrid_normalization.py +0 -1
  32. scripts/test_necthrall_real.py +0 -1
  33. scripts/test_openalex_direct.py +0 -1
  34. scripts/test_single_query.py +0 -1
  35. scripts/validate_synthesis_day2.py +0 -1
  36. scripts/verify_dll_fix.py +0 -1
  37. state_schema_documentation.md +0 -145
  38. tests/integration/test_api.py +30 -10
  39. tests/integration/test_semantic_scholar_client_integration.py +61 -0
  40. tests/unit/test_llm_router.py +105 -0
  41. tests/unit/test_semantic_scholar_client.py +211 -0
  42. utils/llm_router.py +153 -0
agents/semantic_scholar_client.py CHANGED
@@ -1,28 +1,371 @@
1
- """Stub Semantic Scholar client for retrieval stage.
2
 
3
- This is intentionally minimal: a class definition and docstring so future
4
- implementations can plug in network calls and parsing logic.
 
 
 
 
 
 
 
 
 
 
 
5
  """
6
 
7
- from typing import Any, Dict, List
 
 
 
 
 
 
 
 
 
8
 
9
 
10
  class SemanticScholarClient:
11
- """Client stub wrapping Semantic Scholar API interactions.
12
 
13
- Methods should be implemented to fetch papers for a given query and
14
- return structured dicts compatible with the pipeline's `State.papers`.
 
 
 
 
 
 
15
  """
16
 
17
- def __init__(self, api_key: str | None = None) -> None:
18
  self.api_key = api_key
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- def search(self, query: str, limit: int = 10) -> List[Dict[str, Any]]:
21
- """Search Semantic Scholar for `query` and return list of raw hits.
22
 
23
- Currently a stub that should be implemented in future work.
 
 
24
  """
25
- raise NotImplementedError("SemanticScholarClient.search is not implemented")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
 
28
  __all__ = ["SemanticScholarClient"]
 
1
+ """Async Semantic Scholar client used by the retrieval agent.
2
 
3
+ Implements multi-query parallel search with basic rate limiting, retries
4
+ and normalization helper for the pipeline `State`.
5
+
6
+ Usage example:
7
+ client = SemanticScholarClient(api_key="...")
8
+ papers = await client.multi_query_search([
9
+ "primary query",
10
+ "broad query",
11
+ "alternative query",
12
+ ], limit_per_query=100)
13
+
14
+ The returned items are normalized dictionaries matching the project's
15
+ State.papers expectations.
16
  """
17
 
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import time
22
+ from typing import Any, Dict, List, Optional
23
+
24
+ import aiohttp
25
+ from loguru import logger
26
+
27
+ SEMANTIC_SCHOLAR_SEARCH_URL = "https://api.semanticscholar.org/graph/v1/paper/search"
28
 
29
 
30
  class SemanticScholarClient:
31
+ """Async Semantic Scholar client.
32
 
33
+ Responsibilities
34
+ - Run three variant queries in parallel (PRIMARY / BROAD / ALTERNATIVE)
35
+ - Deduplicate by `paperId`
36
+ - Filter to papers with `openAccessPdf.url`
37
+ - Request SPECTER2 embeddings via `fields`
38
+ - Use an asyncio.Semaphore(100) to rate-limit concurrent requests
39
+
40
+ The client is intentionally small and uses aiohttp for async HTTP calls.
41
  """
42
 
43
+ def __init__(self, api_key: Optional[str] = None, *, rate_limit: int = 100) -> None:
44
  self.api_key = api_key
45
+ # Global semaphore to cap concurrent outbound requests
46
+ self._semaphore = asyncio.Semaphore(rate_limit)
47
+ # Default per-request timeout (seconds) used for client sessions
48
+ self._timeout_seconds = 10
49
+
50
+ async def multi_query_search(
51
+ self,
52
+ queries: List[str],
53
+ limit_per_query: int = 100,
54
+ fields: Optional[List[str]] = None,
55
+ ) -> List[Dict[str, Any]]:
56
+ """Run multiple search queries in parallel and return normalized papers.
57
+
58
+ Args:
59
+ queries: List[str] of three query variants (primary, broad, alt).
60
+ limit_per_query: number of results to request per query (default 100).
61
+ fields: optional list of fields to request from the API.
62
 
63
+ Returns:
64
+ List of normalized paper dicts (deduplicated, filtered).
65
 
66
+ Notes:
67
+ - Uses asyncio.gather(..., return_exceptions=True) so a single
68
+ failing query won't cancel the others.
69
  """
70
+ if fields is None:
71
+ fields = [
72
+ "paperId",
73
+ "title",
74
+ "abstract",
75
+ "year",
76
+ "citationCount",
77
+ "influentialCitationCount",
78
+ "openAccessPdf",
79
+ "embedding.specter_v2",
80
+ "authors",
81
+ "venue",
82
+ "externalIds",
83
+ ]
84
+
85
+ # Log entry with a short preview so we can diagnose slow queries
86
+ logger.debug("multi_query_search entry: queries=%s", [q[:80] for q in queries])
87
+
88
+ # Use a pooled connector and a client timeout for better performance
89
+ connector = aiohttp.TCPConnector(limit=100, limit_per_host=25)
90
+ timeout = aiohttp.ClientTimeout(total=self._timeout_seconds)
91
+
92
+ async with aiohttp.ClientSession(
93
+ connector=connector, timeout=timeout
94
+ ) as session:
95
+ tasks = [
96
+ self._run_query(session, q, limit_per_query, fields) for q in queries
97
+ ]
98
+
99
+ start = time.perf_counter()
100
+ raw_results = await asyncio.gather(*tasks, return_exceptions=True)
101
+ elapsed = time.perf_counter() - start
102
+ logger.debug("multi_query_search finished in {:.3f}s", elapsed)
103
+
104
+ # Collect successful results, log exceptions
105
+ hits: List[Dict[str, Any]] = []
106
+ for idx, r in enumerate(raw_results):
107
+ if isinstance(r, Exception):
108
+ # Log with query context and exception stack
109
+ logger.exception("Query failed: %s", queries[idx])
110
+ elif isinstance(r, list):
111
+ hits.extend(r)
112
+ else:
113
+ # Unexpected return but try to continue
114
+ logger.warning("Unexpected result type from query: %s", type(r))
115
+
116
+ # Deduplicate by paperId
117
+ seen: Dict[str, Dict[str, Any]] = {}
118
+ for p in hits:
119
+ pid = p.get("paperId")
120
+ if not pid:
121
+ continue
122
+ if pid in seen:
123
+ continue
124
+ # Filter: require openAccessPdf.url
125
+ oa = p.get("openAccessPdf")
126
+ if not oa or not oa.get("url"):
127
+ continue
128
+ seen[pid] = self.normalize_paper(p)
129
+
130
+ papers = list(seen.values())
131
+
132
+ # Fetch embeddings for all papers using batch paper details endpoint
133
+ if papers:
134
+ logger.debug("Fetching embeddings for %d papers", len(papers))
135
+ papers = await self._enrich_with_embeddings(papers)
136
+
137
+ logger.info(
138
+ "multi_query_search returning %d papers (deduped & filtered)", len(papers)
139
+ )
140
+ return papers
141
+
142
+ async def _run_query(
143
+ self,
144
+ session: aiohttp.ClientSession,
145
+ query: str,
146
+ limit: int,
147
+ fields: List[str],
148
+ ) -> List[Dict[str, Any]]:
149
+ """Wrapper around _fetch_query that handles retries and backoff."""
150
+ max_retries = 3
151
+ backoff = 0.5
152
+ for attempt in range(1, max_retries + 1):
153
+ try:
154
+ return await self._fetch_query(session, query, limit, fields)
155
+ except Exception as exc:
156
+ # Log and retry with exponential backoff on transient errors
157
+ logger.exception(
158
+ "Query attempt %d/%d failed for query=%s",
159
+ attempt,
160
+ max_retries,
161
+ query,
162
+ )
163
+ if attempt == max_retries:
164
+ raise
165
+ await asyncio.sleep(backoff)
166
+ backoff *= 2
167
+
168
+ return []
169
+
170
+ async def _fetch_query(
171
+ self,
172
+ session: aiohttp.ClientSession,
173
+ query: str,
174
+ limit: int,
175
+ fields: List[str],
176
+ ) -> List[Dict[str, Any]]:
177
+ """Perform a single search request and return the raw data list.
178
+
179
+ This method uses the shared semaphore to limit concurrency.
180
+ """
181
+ params = {"query": query, "limit": str(limit), "fields": ",".join(fields)}
182
+ headers = {}
183
+ if self.api_key:
184
+ headers["x-api-key"] = self.api_key
185
+
186
+ # Semaphore prevents >100 simultaneous requests
187
+ await self._semaphore.acquire()
188
+ try:
189
+ try:
190
+ async with session.get(
191
+ SEMANTIC_SCHOLAR_SEARCH_URL, params=params, headers=headers
192
+ ) as resp:
193
+ # Handle common HTTP responses
194
+ if resp.status == 200:
195
+ try:
196
+ data = await resp.json()
197
+ except Exception as e:
198
+ # Malformed JSON or unexpected body
199
+ logger.exception("Failed to parse JSON for query=%s", query)
200
+ raise RuntimeError("Malformed JSON response") from e
201
+ # API returns {"data": [...], ...}
202
+ return data.get("data", [])
203
+ elif resp.status == 429:
204
+ # Rate limited: respect Retry-After header when available
205
+ retry_after = resp.headers.get("Retry-After")
206
+ if retry_after:
207
+ try:
208
+ wait = float(retry_after)
209
+ logger.debug("Received Retry-After=%s, sleeping", wait)
210
+ await asyncio.sleep(wait)
211
+ except Exception:
212
+ pass
213
+ text = await resp.text()
214
+ logger.error(
215
+ "Semantic Scholar rate limited (429) for query=%s: %s",
216
+ query,
217
+ text,
218
+ )
219
+ raise RuntimeError("Semantic Scholar API rate limited (429)")
220
+ elif resp.status == 503:
221
+ text = await resp.text()
222
+ logger.error(
223
+ "Semantic Scholar service unavailable (503) for query=%s: %s",
224
+ query,
225
+ text,
226
+ )
227
+ raise RuntimeError("Semantic Scholar service unavailable (503)")
228
+ else:
229
+ text = await resp.text()
230
+ logger.error(
231
+ "Semantic Scholar returned status %s for query=%s: %s",
232
+ resp.status,
233
+ query,
234
+ text,
235
+ )
236
+ return []
237
+ except asyncio.TimeoutError as te:
238
+ logger.exception(
239
+ "Timeout when calling Semantic Scholar for query=%s", query
240
+ )
241
+ raise
242
+ except aiohttp.ClientError as ce:
243
+ logger.exception(
244
+ "Network error when calling Semantic Scholar for query=%s", query
245
+ )
246
+ raise
247
+ finally:
248
+ self._semaphore.release()
249
+
250
+ async def _enrich_with_embeddings(
251
+ self, papers: List[Dict[str, Any]]
252
+ ) -> List[Dict[str, Any]]:
253
+ """Fetch embeddings for papers using the batch paper details endpoint.
254
+
255
+ The search API doesn't return embeddings, so we need to make separate
256
+ requests to get them. We use the batch endpoint to fetch up to 500
257
+ papers at a time.
258
+ """
259
+ # Semantic Scholar batch endpoint for paper details
260
+ batch_url = "https://api.semanticscholar.org/graph/v1/paper/batch"
261
+
262
+ # Process in batches of 500 (API limit)
263
+ batch_size = 500
264
+ connector = aiohttp.TCPConnector(limit=100, limit_per_host=25)
265
+ timeout = aiohttp.ClientTimeout(total=30)
266
+
267
+ async with aiohttp.ClientSession(
268
+ connector=connector, timeout=timeout
269
+ ) as session:
270
+ for i in range(0, len(papers), batch_size):
271
+ batch = papers[i : i + batch_size]
272
+ paper_ids = [p["paperId"] for p in batch]
273
+
274
+ # Prepare request body
275
+ params = {"fields": "paperId,embedding"}
276
+ headers = {"Content-Type": "application/json"}
277
+ if self.api_key:
278
+ headers["x-api-key"] = self.api_key
279
+
280
+ await self._semaphore.acquire()
281
+ try:
282
+ async with session.post(
283
+ batch_url,
284
+ params=params,
285
+ headers=headers,
286
+ json={"ids": paper_ids},
287
+ ) as resp:
288
+ if resp.status == 200:
289
+ batch_data = await resp.json()
290
+ # batch_data is a list of papers with embeddings
291
+ embedding_map = {}
292
+ for paper_detail in batch_data:
293
+ if paper_detail and "paperId" in paper_detail:
294
+ pid = paper_detail["paperId"]
295
+ emb = paper_detail.get("embedding")
296
+ if emb:
297
+ embedding_map[pid] = emb
298
+
299
+ # Update papers with embeddings
300
+ for paper in batch:
301
+ pid = paper["paperId"]
302
+ if pid in embedding_map:
303
+ emb_data = embedding_map[pid]
304
+ # Extract specter_v2 vector
305
+ if (
306
+ isinstance(emb_data, dict)
307
+ and "vector" in emb_data
308
+ ):
309
+ paper["embedding"]["specter_v2"] = emb_data[
310
+ "vector"
311
+ ]
312
+ elif isinstance(emb_data, list):
313
+ # Sometimes API returns vector directly
314
+ paper["embedding"]["specter_v2"] = emb_data
315
+ else:
316
+ text = await resp.text()
317
+ logger.warning(
318
+ "Failed to fetch embeddings batch (status %d): %s",
319
+ resp.status,
320
+ text[:200],
321
+ )
322
+ except Exception as e:
323
+ logger.exception("Error fetching embeddings batch: %s", e)
324
+ finally:
325
+ self._semaphore.release()
326
+
327
+ return papers
328
+
329
+ def normalize_paper(self, paper: Dict[str, Any]) -> Dict[str, Any]:
330
+ """Normalize a raw paper dict from Semantic Scholar into the pipeline schema.
331
+
332
+ This function extracts the expected fields and applies sensible
333
+ defaults when fields are missing. Inline comments explain each
334
+ transformation to aid readability.
335
+ """
336
+ # Extract embedding if present. The API may return either a nested
337
+ # 'embedding' dict containing 'specter_v2' or a flattened key
338
+ # 'embedding.specter_v2'. Prefer nested form when available.
339
+ specter_vec = None
340
+ emb_block = paper.get("embedding")
341
+ if isinstance(emb_block, dict):
342
+ specter_vec = emb_block.get("specter_v2")
343
+ elif "embedding.specter_v2" in paper:
344
+ specter_vec = paper.get("embedding.specter_v2")
345
+
346
+ # Build normalized dict with defaults for missing fields
347
+ normalized: Dict[str, Any] = {
348
+ # Identity
349
+ "paperId": paper.get("paperId"),
350
+ # Textual metadata
351
+ "title": paper.get("title"),
352
+ "abstract": paper.get("abstract"),
353
+ "year": paper.get("year"),
354
+ # Citation statistics with safe defaults
355
+ "citationCount": paper.get("citationCount", 0),
356
+ "influentialCitationCount": paper.get("influentialCitationCount", 0),
357
+ # PDF info: ensure we always return a dict (may be empty)
358
+ "openAccessPdf": paper.get("openAccessPdf") or {},
359
+ # Embedding: only include specter_v2 when available
360
+ "embedding": {"specter_v2": specter_vec} if specter_vec is not None else {},
361
+ # Authors list and venue
362
+ "authors": paper.get("authors", []),
363
+ "venue": paper.get("venue"),
364
+ # External identifiers like DOI or ArXiv id
365
+ "externalIds": paper.get("externalIds", {}),
366
+ }
367
+
368
+ return normalized
369
 
370
 
371
  __all__ = ["SemanticScholarClient"]
models/state.py CHANGED
@@ -8,7 +8,7 @@ from loguru import logger
8
 
9
 
10
  class State(BaseModel):
11
- """Progressive-enrichment State used by the Necthrall Lite pipeline.
12
 
13
  The State is intentionally lean and uses Optional fields so agents can
14
  populate it step-by-step (progressive enrichment). Field-by-field
 
8
 
9
 
10
  class State(BaseModel):
11
+ """Progressive-enrichment State used by the Necthrall pipeline.
12
 
13
  The State is intentionally lean and uses Optional fields so agents can
14
  populate it step-by-step (progressive enrichment). Field-by-field
pyproject.toml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "necthrall"
7
+ version = "0.1.0"
8
+ description = "Necthrall Lite MVP - AI scientific research assistant"
9
+ authors = [
10
+ {name = "Adam Cseresznye", email = "adam@example.com"},
11
+ ]
12
+ dependencies = [
13
+ "aiohttp>=3.9.0",
14
+ "litellm>=1.0.0",
15
+ "loguru>=0.7.0",
16
+ "python-dotenv>=1.0.0",
17
+ "pytest>=7.0.0",
18
+ "pytest-asyncio>=0.21.0",
19
+ "sentence-transformers>=2.2.0",
20
+ "faiss-cpu>=1.7.0",
21
+ "PyMuPDF>=1.23.0",
22
+ "torch>=2.0.0",
23
+ ]
24
+ requires-python = ">=3.11"
25
+ readme = "README.md"
26
+
27
+ [project.optional-dependencies]
28
+ dev = [
29
+ "black",
30
+ "isort",
31
+ "mypy",
32
+ ]
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["."]
36
+ include = ["agents", "config", "models", "rag", "retrieval", "utils", "scripts"]
37
+
38
+ [tool.setuptools.package-dir]
39
+ "" = "."
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
43
+ python_files = ["test_*.py"]
44
+ python_classes = ["Test*"]
45
+ python_functions = ["test_*"]
46
+ markers = [
47
+ "unit: Unit tests",
48
+ "integration: Integration tests",
49
+ "slow: Slow tests",
50
+ "pdf_dependent: Tests that depend on PDF processing",
51
+ ]
scripts/analyze_test_categories.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/batch_benchmark.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/benchmark_agent_comparison.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/benchmark_week2_performance.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/check_abstract_availability.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/check_env.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/check_imports.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/collect_openalex_stats.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/debug_chunker.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/debug_embedding_call.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/debug_openalex_diagnostics.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/debug_openalex_response.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/debug_pdf_availability.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/debug_pop_query.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/debug_processing_run.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/embedding_demo.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/generate_test_data.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/pdf_test_extraction.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/pdf_test_search.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/performance_test.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/performance_test_script.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/performance_validation.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/quick_performance_test.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/run_llm_test.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ from utils.llm_router import LLMRouter
6
+
7
+
8
+ async def test():
9
+ router = LLMRouter()
10
+ try:
11
+ result = await router.generate(
12
+ prompt="What is intermittent fasting?", model_type="optimization"
13
+ )
14
+ print("Response:", repr(result)[:500])
15
+ except Exception as e:
16
+ print("LLM call failed:", type(e).__name__, str(e))
17
+
18
+
19
+ if __name__ == "__main__":
20
+ asyncio.run(test())
scripts/run_semantic_scholar_client.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import time
3
+ import os
4
+ from dotenv import load_dotenv
5
+
6
+ load_dotenv()
7
+
8
+ from agents.semantic_scholar_client import SemanticScholarClient
9
+
10
+ QUERIES = [
11
+ "intermittent fasting cardiovascular",
12
+ "intermittent fasting heart health",
13
+ "time-restricted eating cardiovascular",
14
+ ]
15
+
16
+
17
+ async def main():
18
+ api_key = os.getenv("SEMANTIC_SCHOLAR_API_KEY")
19
+ if not api_key:
20
+ print("SEMANTIC_SCHOLAR_API_KEY not set; please set it in .env or environment")
21
+ return
22
+
23
+ client = SemanticScholarClient(api_key=api_key)
24
+
25
+ # Use the same fields the client would request to get consistent counts
26
+ fields = [
27
+ "paperId",
28
+ "title",
29
+ "abstract",
30
+ "year",
31
+ "citationCount",
32
+ "influentialCitationCount",
33
+ "openAccessPdf",
34
+ "embedding",
35
+ "authors",
36
+ "venue",
37
+ "externalIds",
38
+ ]
39
+
40
+ start = time.perf_counter()
41
+ import aiohttp
42
+
43
+ query_raw_counts = []
44
+ async with aiohttp.ClientSession() as session:
45
+ for q in QUERIES:
46
+ try:
47
+ data = await client._fetch_query(session, q, 100, fields)
48
+ query_raw_counts.append(len(data))
49
+ except Exception as e:
50
+ print(f"Query error for '{q}': {e}")
51
+ query_raw_counts.append(0)
52
+
53
+ # Now run the full multi_query_search to get deduped & filtered papers
54
+ papers = await client.multi_query_search(QUERIES, limit_per_query=100)
55
+ elapsed = time.perf_counter() - start
56
+
57
+ # Compute stats
58
+ total = len(papers)
59
+ papers_with_pdf = sum(
60
+ 1
61
+ for p in papers
62
+ if p.get("openAccessPdf") and p.get("openAccessPdf").get("url")
63
+ )
64
+ papers_with_embedding = sum(
65
+ 1 for p in papers if p.get("embedding") and p.get("embedding").get("specter_v2")
66
+ )
67
+
68
+ for idx, (q, cnt) in enumerate(zip(QUERIES, query_raw_counts), start=1):
69
+ print(f"Query {idx}: {q} - {cnt} papers")
70
+
71
+ print(f"Total after deduplication: {total} papers")
72
+ print(
73
+ f"Papers with PDFs: {papers_with_pdf} ({(papers_with_pdf/total*100) if total else 0:.0f}%)"
74
+ )
75
+ print(
76
+ f"Papers with embeddings: {papers_with_embedding} ({(papers_with_embedding/total*100) if total else 0:.0f}%)"
77
+ )
78
+ print(f"Execution time: {elapsed:.2f}s")
79
+
80
+ print(papers[:3]) # Print first 3 papers as sample
81
+
82
+
83
+ if __name__ == "__main__":
84
+ asyncio.run(main())
scripts/show_recommended_models.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/test_end_to_end_pipeline.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/test_hybrid_normalization.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/test_necthrall_real.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/test_openalex_direct.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/test_single_query.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/validate_synthesis_day2.py DELETED
@@ -1 +0,0 @@
1
-
 
 
scripts/verify_dll_fix.py DELETED
@@ -1 +0,0 @@
1
-
 
 
state_schema_documentation.md DELETED
@@ -1,145 +0,0 @@
1
- # Necthrall State Schema Documentation
2
-
3
- ## Overview
4
-
5
- The `State` model represents the complete application state for the Necthrall Lite MVP system. It tracks progression through query optimization (Week 1), paper retrieval/filtering, processing outputs (Week 2), and prepares for analysis/synthesis (Week 3).
6
-
7
- ## Core Components
8
-
9
- ### Passage Model
10
-
11
- Represents a scored text passage retrieved from scientific papers.
12
-
13
- **Fields:**
14
- - `content: str` - The actual text content of the passage
15
- - `section: str` - Paper section (must be one of: introduction, methods, results, discussion, other)
16
- - `paper_id: str` - Unique identifier of the source paper
17
- - `retrieval_score: float` - BM25/semantic retrieval score
18
- - `cross_encoder_score: Optional[float]` - Cross-encoder reranking score (optional)
19
- - `final_score: Optional[float]` - Final combined score (optional)
20
-
21
- **Validation:**
22
- - Unknown sections are automatically mapped to "other" with a warning log
23
- - All required fields must be provided
24
-
25
- ### State Model
26
-
27
- #### Identification
28
- - `request_id: str` - Auto-generated UUID for request tracking
29
- - `original_query: str` (alias: `query`) - User's original input query
30
- - `created_at: datetime` - Timestamp when state was created
31
-
32
- #### Query Management (Week 1)
33
- - `optimized_query: Optional[str]` - LLM-optimized query for OpenAlex search
34
- - `refinement_count: int` - Number of refinement iterations (max 2)
35
-
36
- #### Paper Retrieval & Filtering
37
- - `papers_metadata: List[Paper]` - Raw papers from SearchAgent (up to 100 before filtering)
38
- - `filtered_papers: List[Paper]` - Final 25 papers after deduplication and BM25+embedding filtering
39
-
40
- #### Processing Pipeline (Week 2)
41
- - `passages: List[Passage]` - Extracted text passages from papers
42
- - `top_passages: List[Passage]` - Top 10 passages with scores (max 10)
43
- - `processing_stats: Optional[Dict[str, Any]]` - Processing stage timings and counts
44
- - `scores: Optional[Dict[str, Any]]` - Passage scoring results
45
- - `answer: Optional[str]` - Intermediate answer from processing
46
- - `citations: List[int]` - Citation indices
47
- - `metrics: Optional[Dict[str, float]]` - Performance metrics
48
- - `retry_count: int` - Processing retry attempts (max 2)
49
-
50
- #### Acquisition & Metrics
51
- - `pdf_contents: List[PDFContent]` - Downloaded PDF content
52
- - `download_failures: List[ErrorReport]` - Failed download reports
53
- - `acquisition_metrics: Optional[AcquisitionMetrics]` - Download statistics
54
- - `citation_validation: Optional[Dict[str, Any]]` - Citation validation results
55
-
56
- #### Filtering & Quality Metrics
57
- - `filtering_scores: Optional[Dict[str, Any]]` - BM25 and semantic filtering scores
58
- - `dedup_stats: Optional[Dict[str, Any]]` - Deduplication metrics
59
- - `search_quality: Optional[Dict[str, Any]]` - Overall search quality assessment
60
-
61
- #### Week 3 Placeholders
62
- - `analysis_results: Optional[Dict[str, Any]]` - Analysis results (future use)
63
- - `synthesized_answer: Optional[str]` - Final synthesized answer (future use)
64
-
65
- #### Configuration
66
- - `config: Dict[str, Any]` - Application configuration
67
- - `validation_errors: List[str]` - Accumulated validation errors
68
-
69
- ## Validation Rules
70
-
71
- - Query length: 3-256 characters
72
- - Filtered papers: ≤25
73
- - Top passages: ≤10
74
- - Refinement/retry counts: ≤2
75
- - Section values: normalized to allowed set
76
- - Search quality relevance: 0.0-1.0 range
77
-
78
- ## Usage Examples
79
-
80
- ### Basic State Creation
81
- ```python
82
- from models.state import State, Passage
83
-
84
- state = State(original_query="What is quantum computing?")
85
- ```
86
-
87
- ### Adding Top Passages
88
- ```python
89
- passage = Passage(
90
- content="Quantum computing uses qubits instead of bits...",
91
- section="introduction",
92
- paper_id="10.1038/nature12345",
93
- retrieval_score=0.95,
94
- cross_encoder_score=0.87,
95
- final_score=0.91
96
- )
97
-
98
- state.top_passages = [passage]
99
- ```
100
-
101
- ### Legacy Migration
102
- ```python
103
- legacy_data = {
104
- "query": "quantum effects",
105
- "top_passages": [
106
- {
107
- "text": "Quantum mechanics explains...",
108
- "section": "introduction",
109
- "paper_id": "123",
110
- "score": 0.8
111
- }
112
- ]
113
- }
114
-
115
- # Migrate to new schema
116
- state = State.from_legacy_dict(legacy_data)
117
- ```
118
-
119
- ## Schema Evolution
120
-
121
- ### Week 1 → Week 2
122
- - Added `top_passages: List[Passage]` (changed from `List[Dict[str, Any]]`)
123
- - Added `processing_stats` and filtering metrics
124
- - Enhanced Passage model with scoring fields
125
-
126
- ### Week 2 → Week 3
127
- - Added `analysis_results` and `synthesized_answer` placeholders
128
- - Schema prepared for future analysis and synthesis phases
129
-
130
- ## Migration Guide
131
-
132
- Use `State.from_legacy_dict(data)` to upgrade older state dictionaries:
133
-
134
- 1. Maps legacy `passages[].text` to `content`
135
- 2. Converts `List[Dict]` `top_passages` to `List[Passage]`
136
- 3. Provides defaults for missing optional fields
137
- 4. Logs warnings for incompatible data and skips problematic items
138
-
139
- ## Serialization
140
-
141
- The State model serializes cleanly to JSON with:
142
- - Automatic UUID generation for `request_id`
143
- - Alias handling for backward compatibility (`query` ↔ `original_query`)
144
- - Proper datetime formatting
145
- - Default empty lists and None values for optional fields
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/integration/test_api.py CHANGED
@@ -3,9 +3,20 @@ import time
3
  import os
4
 
5
 
6
- @pytest.fixture(autouse=True)
7
  def set_test_env():
8
- """ "Set minimal test environment variables for config validation"""
 
 
 
 
 
 
 
 
 
 
 
9
  os.environ["SEMANTIC_SCHOLAR_API_KEY"] = "test_key"
10
  os.environ["GOOGLE_API_KEY"] = "test_key"
11
  os.environ["GROQ_API_KEY"] = "test_key"
@@ -13,6 +24,15 @@ def set_test_env():
13
  os.environ["SYNTHESIS_MODEL"] = "test_model"
14
  os.environ["SKIP_DOTENV_LOADER"] = "1"
15
 
 
 
 
 
 
 
 
 
 
16
 
17
  @pytest.fixture
18
  def app():
@@ -22,8 +42,8 @@ def app():
22
 
23
 
24
  @pytest.mark.integration
25
- def test_health_endpoint(app):
26
- """ "Test health endpoint returns 200 status"""
27
  from fastapi.testclient import TestClient
28
 
29
  client = TestClient(app)
@@ -37,8 +57,8 @@ def test_health_endpoint(app):
37
 
38
 
39
  @pytest.mark.integration
40
- def test_root_endpoint(app):
41
- """ "Test root endpoint returns 200 status with API documentation links"""
42
  from fastapi.testclient import TestClient
43
 
44
  client = TestClient(app)
@@ -52,8 +72,8 @@ def test_root_endpoint(app):
52
 
53
 
54
  @pytest.mark.integration
55
- def test_health_endpoint_response_time(app):
56
- """ "Test health endpoint response time < 100ms"""
57
  from fastapi.testclient import TestClient
58
 
59
  client = TestClient(app)
@@ -67,8 +87,8 @@ def test_health_endpoint_response_time(app):
67
 
68
 
69
  @pytest.mark.integration
70
- def test_startup_event_logs_configuration(app):
71
- """ "Test startup event logs configuration successfully"""
72
  # This test verifies that the app can start without config validation errors
73
  # In a real scenario, we'd check logs, but for integration test, we ensure no exceptions
74
  from fastapi.testclient import TestClient
 
3
  import os
4
 
5
 
6
+ @pytest.fixture
7
  def set_test_env():
8
+ """Set minimal test environment variables for config validation"""
9
+ # Save original values
10
+ original_values = {
11
+ "SEMANTIC_SCHOLAR_API_KEY": os.environ.get("SEMANTIC_SCHOLAR_API_KEY"),
12
+ "GOOGLE_API_KEY": os.environ.get("GOOGLE_API_KEY"),
13
+ "GROQ_API_KEY": os.environ.get("GROQ_API_KEY"),
14
+ "QUERY_OPTIMIZATION_MODEL": os.environ.get("QUERY_OPTIMIZATION_MODEL"),
15
+ "SYNTHESIS_MODEL": os.environ.get("SYNTHESIS_MODEL"),
16
+ "SKIP_DOTENV_LOADER": os.environ.get("SKIP_DOTENV_LOADER"),
17
+ }
18
+
19
+ # Set test values
20
  os.environ["SEMANTIC_SCHOLAR_API_KEY"] = "test_key"
21
  os.environ["GOOGLE_API_KEY"] = "test_key"
22
  os.environ["GROQ_API_KEY"] = "test_key"
 
24
  os.environ["SYNTHESIS_MODEL"] = "test_model"
25
  os.environ["SKIP_DOTENV_LOADER"] = "1"
26
 
27
+ yield
28
+
29
+ # Restore original values
30
+ for key, value in original_values.items():
31
+ if value is None:
32
+ os.environ.pop(key, None)
33
+ else:
34
+ os.environ[key] = value
35
+
36
 
37
  @pytest.fixture
38
  def app():
 
42
 
43
 
44
  @pytest.mark.integration
45
+ def test_health_endpoint(app, set_test_env):
46
+ """Test health endpoint returns 200 status"""
47
  from fastapi.testclient import TestClient
48
 
49
  client = TestClient(app)
 
57
 
58
 
59
  @pytest.mark.integration
60
+ def test_root_endpoint(app, set_test_env):
61
+ """Test root endpoint returns 200 status with API documentation links"""
62
  from fastapi.testclient import TestClient
63
 
64
  client = TestClient(app)
 
72
 
73
 
74
  @pytest.mark.integration
75
+ def test_health_endpoint_response_time(app, set_test_env):
76
+ """Test health endpoint response time < 100ms"""
77
  from fastapi.testclient import TestClient
78
 
79
  client = TestClient(app)
 
87
 
88
 
89
  @pytest.mark.integration
90
+ def test_startup_event_logs_configuration(app, set_test_env):
91
+ """Test startup event logs configuration successfully"""
92
  # This test verifies that the app can start without config validation errors
93
  # In a real scenario, we'd check logs, but for integration test, we ensure no exceptions
94
  from fastapi.testclient import TestClient
tests/integration/test_semantic_scholar_client_integration.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ from typing import List
4
+
5
+ import pytest
6
+ from dotenv import load_dotenv
7
+
8
+ from agents.semantic_scholar_client import SemanticScholarClient
9
+
10
+ load_dotenv()
11
+
12
+
13
+ @pytest.mark.integration
14
+ @pytest.mark.asyncio
15
+ async def test_semantic_scholar_integration_real_api_key():
16
+ """Integration test against the real Semantic Scholar API.
17
+
18
+ Requirements:
19
+ - Requires SEMANTIC_SCHOLAR_API_KEY in the environment (or .env loaded by dev).
20
+ - Performs 3 parallel queries and validates returned papers.
21
+
22
+ This test will be skipped if the API key is not available to avoid
23
+ failing CI runs that don't have secrets configured.
24
+ """
25
+ api_key = os.getenv("SEMANTIC_SCHOLAR_API_KEY")
26
+ if not api_key:
27
+ pytest.skip("SEMANTIC_SCHOLAR_API_KEY is not set; skipping integration test")
28
+
29
+ client = SemanticScholarClient(api_key=api_key)
30
+
31
+ queries: List[str] = [
32
+ "intermittent fasting cardiovascular",
33
+ "intermittent fasting heart health",
34
+ "time-restricted eating cardiovascular outcomes",
35
+ ]
36
+
37
+ start = time.perf_counter()
38
+ papers = await client.multi_query_search(queries, limit_per_query=100)
39
+ elapsed = time.perf_counter() - start
40
+
41
+ # Timing: network varies; assert it's reasonably fast but allow buffer
42
+ assert elapsed < 12.0, f"Query took too long: {elapsed:.2f}s"
43
+
44
+ # Expect several papers after deduplication and PDF filtering
45
+ assert 150 <= len(papers) <= 300, f"Unexpected number of papers: {len(papers)}"
46
+
47
+ # Validate a few returned fields are present
48
+ for p in papers[:10]:
49
+ assert p.get("paperId")
50
+ oa = p.get("openAccessPdf")
51
+ assert oa and oa.get("url")
52
+
53
+ # If embedding data is returned for a paper, validate its dimensionality
54
+ # (SPECTER2 expected to be 768). Do not fail if no embeddings are present
55
+ # for the returned set — the API does not guarantee embeddings for every
56
+ # paper.
57
+ for p in papers:
58
+ emb = p.get("embedding", {}).get("specter_v2")
59
+ if emb:
60
+ assert isinstance(emb, list)
61
+ assert len(emb) == 768
tests/unit/test_llm_router.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from unittest.mock import AsyncMock, patch
3
+ from types import SimpleNamespace
4
+
5
+ from loguru import logger
6
+
7
+ from utils.llm_router import LLMRouter
8
+
9
+
10
+ @pytest.mark.unit
11
+ @pytest.mark.asyncio
12
+ async def test_generate_happy_path():
13
+ """generate should call litellm.acompletion with the primary model and return content"""
14
+ primary_model = "primary_model"
15
+ fallback_model = "fallback_model"
16
+
17
+ # Mock configuration
18
+ with (
19
+ patch("config.config.QUERY_OPTIMIZATION_MODEL", primary_model),
20
+ patch("config.config.QUERY_OPTIMIZATION_FALLBACK", fallback_model),
21
+ patch("litellm.acompletion", new_callable=AsyncMock) as mock_acompletion,
22
+ ):
23
+
24
+ # Mock response object
25
+ response_obj = SimpleNamespace(
26
+ choices=[SimpleNamespace(message=SimpleNamespace(content="ok"))]
27
+ )
28
+ mock_acompletion.return_value = response_obj
29
+
30
+ router = LLMRouter()
31
+ result = await router.generate("test prompt", "optimization")
32
+
33
+ assert result == "ok"
34
+ # assert called once with primary model
35
+ assert mock_acompletion.call_count == 1
36
+ called_kwargs = mock_acompletion.call_args.kwargs
37
+ assert called_kwargs.get("model") == primary_model
38
+ assert called_kwargs.get("timeout") == 30
39
+
40
+
41
+ @pytest.mark.unit
42
+ @pytest.mark.asyncio
43
+ async def test_generate_fallback_path():
44
+ """If primary fails, router should retry with fallback and return content"""
45
+ primary_model = "primary_model"
46
+ fallback_model = "fallback_model"
47
+
48
+ with (
49
+ patch("config.config.QUERY_OPTIMIZATION_MODEL", primary_model),
50
+ patch("config.config.QUERY_OPTIMIZATION_FALLBACK", fallback_model),
51
+ patch("config.config.GOOGLE_API_KEY", "fake_google_key"),
52
+ patch("config.config.GROQ_API_KEY", "fake_groq_key"),
53
+ patch("litellm.acompletion", new_callable=AsyncMock) as mock_acompletion,
54
+ ):
55
+
56
+ # Track call count to alternate between raising exception and returning
57
+ call_count = 0
58
+
59
+ # Configure side effects: raise for primary, return content for fallback
60
+ def side_effect(*args, **kwargs):
61
+ nonlocal call_count
62
+ call_count += 1
63
+ if call_count == 1:
64
+ # First call (primary) should fail
65
+ raise Exception("primary failed")
66
+ else:
67
+ # Second call (fallback) should succeed
68
+ return SimpleNamespace(
69
+ choices=[
70
+ SimpleNamespace(message=SimpleNamespace(content="fallback-ok"))
71
+ ]
72
+ )
73
+
74
+ mock_acompletion.side_effect = side_effect
75
+
76
+ router = LLMRouter()
77
+ result = await router.generate("test prompt", "optimization")
78
+
79
+ assert result == "fallback-ok"
80
+ assert mock_acompletion.call_count == 2
81
+ assert mock_acompletion.call_args_list[0].kwargs.get("model") == primary_model
82
+ assert mock_acompletion.call_args_list[1].kwargs.get("model") == fallback_model
83
+
84
+
85
+ @pytest.mark.unit
86
+ @pytest.mark.asyncio
87
+ async def test_generate_both_fail():
88
+ """If both primary and fallback fail, router should raise the exception"""
89
+ primary_model = "primary_model"
90
+ fallback_model = "fallback_model"
91
+
92
+ with (
93
+ patch("config.config.QUERY_OPTIMIZATION_MODEL", primary_model),
94
+ patch("config.config.QUERY_OPTIMIZATION_FALLBACK", fallback_model),
95
+ patch("litellm.acompletion", new_callable=AsyncMock) as mock_acompletion,
96
+ ):
97
+
98
+ mock_acompletion.side_effect = Exception("both fail")
99
+
100
+ router = LLMRouter()
101
+
102
+ with pytest.raises(Exception):
103
+ await router.generate("test prompt", "optimization")
104
+
105
+ assert mock_acompletion.call_count == 2
tests/unit/test_semantic_scholar_client.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import time
3
+ from typing import Any, Dict, List
4
+
5
+ import aiohttp
6
+ import pytest
7
+
8
+ from agents.semantic_scholar_client import SemanticScholarClient
9
+
10
+
11
+ def make_paper(
12
+ paper_id: int, has_pdf: bool = True, embedding_dim: int = 768
13
+ ) -> Dict[str, Any]:
14
+ base = {
15
+ "paperId": f"P{paper_id}",
16
+ "title": f"Title {paper_id}",
17
+ "abstract": f"Abstract {paper_id}",
18
+ "year": 2020,
19
+ "citationCount": 10,
20
+ "influentialCitationCount": 1,
21
+ "openAccessPdf": {"url": f"https://pdf/{paper_id}.pdf"} if has_pdf else {},
22
+ "embedding": {"specter_v2": [0.0] * embedding_dim},
23
+ "authors": [{"name": "A"}],
24
+ "venue": "Venue",
25
+ "externalIds": {"DOI": f"10.0/test/{paper_id}"},
26
+ }
27
+ return base
28
+
29
+
30
+ class DummyResponse:
31
+ def __init__(self, status: int = 200, data: Dict = None, text: str = ""):
32
+ self.status = status
33
+ self._data = data or {}
34
+ self._text = text
35
+
36
+ async def json(self):
37
+ return self._data
38
+
39
+ async def text(self):
40
+ return self._text
41
+
42
+ async def __aenter__(self):
43
+ return self
44
+
45
+ async def __aexit__(self, exc_type, exc, tb):
46
+ return False
47
+
48
+
49
+ class DummyClientSession:
50
+ """A very small replacement for aiohttp.ClientSession used in tests.
51
+
52
+ It uses a mapping from query->DummyResponse or raises an Exception when
53
+ the mapping value is an Exception instance.
54
+ """
55
+
56
+ def __init__(self, responses: Dict[str, Any]):
57
+ self._responses = responses
58
+
59
+ async def __aenter__(self):
60
+ return self
61
+
62
+ async def __aexit__(self, exc_type, exc, tb):
63
+ return False
64
+
65
+ def get(self, url, params=None, headers=None):
66
+ query = (params or {}).get("query")
67
+ value = self._responses.get(query)
68
+ if isinstance(value, Exception):
69
+ raise value
70
+ # Allow simulated small delay to exercise concurrency
71
+ return DummyResponse(status=200, data={"data": value or []})
72
+
73
+
74
+ @pytest.mark.unit
75
+ @pytest.mark.asyncio
76
+ async def test_happy_path_three_queries(monkeypatch):
77
+ # queries produce overlapping ids to end up with ~200 unique papers
78
+ q1 = [make_paper(i) for i in range(0, 100)]
79
+ q2 = [make_paper(i) for i in range(50, 150)]
80
+ q3 = [make_paper(i) for i in range(100, 200)]
81
+
82
+ responses = {
83
+ "q1": q1,
84
+ "q2": q2,
85
+ "q3": q3,
86
+ }
87
+
88
+ async def _factory(*args, **kwargs):
89
+ return DummyClientSession(responses)
90
+
91
+ monkeypatch.setattr(
92
+ aiohttp, "ClientSession", lambda *a, **k: DummyClientSession(responses)
93
+ )
94
+
95
+ client = SemanticScholarClient()
96
+ start = time.perf_counter()
97
+ papers = await client.multi_query_search(["q1", "q2", "q3"], limit_per_query=100)
98
+ elapsed = time.perf_counter() - start
99
+
100
+ # Should be deduplicated union of ids 0..199 => 200
101
+ assert 150 <= len(papers) <= 300
102
+ assert elapsed < 3.0
103
+
104
+ # Embedding present and has 768 dims
105
+ for p in papers:
106
+ emb = p.get("embedding", {}).get("specter_v2")
107
+ assert emb is not None
108
+ assert len(emb) == 768
109
+
110
+
111
+ @pytest.mark.unit
112
+ @pytest.mark.asyncio
113
+ async def test_deduplication(monkeypatch):
114
+ # q1 and q2 share the same paper
115
+ shared = make_paper(1)
116
+ responses = {"a": [shared, make_paper(2)], "b": [shared, make_paper(3)], "c": []}
117
+ monkeypatch.setattr(
118
+ aiohttp, "ClientSession", lambda *a, **k: DummyClientSession(responses)
119
+ )
120
+
121
+ client = SemanticScholarClient()
122
+ papers = await client.multi_query_search(["a", "b", "c"], limit_per_query=10)
123
+ # shared paper only once
124
+ ids = {p["paperId"] for p in papers}
125
+ assert "P1" in ids
126
+ assert len([pid for pid in ids if pid == "P1"]) == 1
127
+
128
+
129
+ @pytest.mark.unit
130
+ @pytest.mark.asyncio
131
+ async def test_pdf_filtering(monkeypatch):
132
+ p_with = make_paper(1, has_pdf=True)
133
+ p_without = make_paper(2, has_pdf=False)
134
+ responses = {"x": [p_with, p_without], "y": [], "z": []}
135
+ monkeypatch.setattr(
136
+ aiohttp, "ClientSession", lambda *a, **k: DummyClientSession(responses)
137
+ )
138
+
139
+ client = SemanticScholarClient()
140
+ papers = await client.multi_query_search(["x", "y", "z"], limit_per_query=10)
141
+ ids = {p["paperId"] for p in papers}
142
+ assert "P1" in ids
143
+ assert "P2" not in ids
144
+
145
+
146
+ @pytest.mark.unit
147
+ @pytest.mark.asyncio
148
+ async def test_partial_failure(monkeypatch):
149
+ # make one query raise an exception
150
+ p_ok = make_paper(1)
151
+ responses = {
152
+ "ok1": [p_ok],
153
+ "fail": RuntimeError("simulated failure"),
154
+ "ok2": [make_paper(2)],
155
+ }
156
+ monkeypatch.setattr(
157
+ aiohttp, "ClientSession", lambda *a, **k: DummyClientSession(responses)
158
+ )
159
+
160
+ client = SemanticScholarClient()
161
+ papers = await client.multi_query_search(["ok1", "fail", "ok2"], limit_per_query=10)
162
+ # Should return results from ok1 and ok2
163
+ ids = {p["paperId"] for p in papers}
164
+ assert "P1" in ids and "P2" in ids
165
+
166
+
167
+ @pytest.mark.unit
168
+ @pytest.mark.asyncio
169
+ async def test_rate_limiting_many_concurrent_calls(monkeypatch):
170
+ # Create small responses and run multiple client calls concurrently
171
+ resp = [make_paper(i) for i in range(10)]
172
+ responses = {"r": resp, "s": resp, "t": resp}
173
+ monkeypatch.setattr(
174
+ aiohttp, "ClientSession", lambda *a, **k: DummyClientSession(responses)
175
+ )
176
+
177
+ client = SemanticScholarClient()
178
+
179
+ async def call_once():
180
+ return await client.multi_query_search(["r", "s", "t"], limit_per_query=10)
181
+
182
+ tasks = [asyncio.create_task(call_once()) for _ in range(8)]
183
+ results = await asyncio.gather(*tasks)
184
+ # All tasks must complete with results
185
+ for papers in results:
186
+ assert isinstance(papers, list)
187
+ assert len(papers) > 0
188
+
189
+
190
+ @pytest.mark.unit
191
+ @pytest.mark.asyncio
192
+ async def test_deduplication_multiple_duplicates(monkeypatch):
193
+ """Ensure duplicates across and within query results are deduplicated."""
194
+ # Same paper appears multiple times inside q1 and also in q2
195
+ shared = make_paper(42)
196
+ q1 = [shared, shared, make_paper(43)]
197
+ q2 = [shared, make_paper(44)]
198
+ q3 = [make_paper(45)]
199
+
200
+ responses = {"q1": q1, "q2": q2, "q3": q3}
201
+ monkeypatch.setattr(
202
+ aiohttp, "ClientSession", lambda *a, **k: DummyClientSession(responses)
203
+ )
204
+
205
+ client = SemanticScholarClient()
206
+ papers = await client.multi_query_search(["q1", "q2", "q3"], limit_per_query=10)
207
+ ids = [p["paperId"] for p in papers]
208
+ # shared paper should appear exactly once
209
+ assert ids.count("P42") == 1
210
+ # other papers present
211
+ assert "P43" in ids and "P44" in ids and "P45" in ids
utils/llm_router.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Centralized LiteLLM router for model selection and fallback.
2
+
3
+ This module provides LLMRouter which wraps litellm.acompletion calls, picks
4
+ appropriate primary and fallback models from the project's `config` module and
5
+ retries automatically on failure.
6
+
7
+ Usage example:
8
+ router = LLMRouter()
9
+ content = await router.generate("Summarize this paper.", "synthesis")
10
+ """
11
+
12
+ from typing import Optional
13
+ from loguru import logger
14
+ import asyncio
15
+ import litellm
16
+
17
+ import config.config as config
18
+
19
+
20
+ class LLMRouter:
21
+ """A small router for LiteLLM calls that handles primary+fallback selection.
22
+
23
+ It intentionally keeps logic minimal and async to add low overhead to
24
+ actual model calls.
25
+ """
26
+
27
+ def __init__(self) -> None:
28
+ # Store API keys for use in generate method
29
+ self._google_api_key = config.GOOGLE_API_KEY
30
+ self._groq_api_key = config.GROQ_API_KEY
31
+
32
+ # Read model names from config on instantiation. Keep values simple so
33
+ # tests can patch the module attributes.
34
+ self._models = {
35
+ "optimization": (
36
+ config.QUERY_OPTIMIZATION_MODEL,
37
+ config.QUERY_OPTIMIZATION_FALLBACK,
38
+ ),
39
+ "synthesis": (config.SYNTHESIS_MODEL, config.SYNTHESIS_FALLBACK),
40
+ }
41
+
42
+ async def generate(self, prompt: str, model_type: str) -> str:
43
+ """Generate a response for the given `prompt` using models associated
44
+ with `model_type`.
45
+
46
+ This method will attempt a primary model call first and fallback once on
47
+ failure. It returns the inner content of the first choice:
48
+
49
+ response.choices[0].message.content
50
+
51
+ Raises the original exception if both primary and fallback fail.
52
+
53
+ Args:
54
+ prompt: The prompt text to send to the LLM.
55
+ model_type: One of the keys present in the router ("optimization",
56
+ "synthesis").
57
+
58
+ Returns:
59
+ The text content of the first model choice.
60
+ """
61
+
62
+ logger.debug(f"LLMRouter.generate entry: model_type={model_type}")
63
+
64
+ mapping = self._models.get(model_type)
65
+ if mapping is None:
66
+ raise ValueError(f"Unknown model_type: {model_type}")
67
+
68
+ primary, fallback = mapping
69
+ # Choose a default timeout per high level plan
70
+ timeout = 30
71
+
72
+ # Track which model was ultimately used so we can log it at exit
73
+ used_label: Optional[str] = None
74
+ used_model_name: Optional[str] = None
75
+
76
+ try:
77
+ response = await litellm.acompletion(
78
+ model=primary,
79
+ messages=[{"role": "user", "content": prompt}],
80
+ timeout=timeout,
81
+ api_key=self._google_api_key,
82
+ )
83
+ used_label = "primary"
84
+ used_model_name = primary
85
+ except litellm.exceptions.APIError as e:
86
+ # API errors from providers
87
+ logger.warning(f"Primary LLM APIError for model {primary}: {e}")
88
+ logger.info(f"Retrying LLM call with fallback model {fallback}")
89
+ try:
90
+ response = await litellm.acompletion(
91
+ model=fallback,
92
+ messages=[{"role": "user", "content": prompt}],
93
+ timeout=timeout,
94
+ api_key=self._groq_api_key,
95
+ )
96
+ used_label = "fallback"
97
+ used_model_name = fallback
98
+ except (litellm.exceptions.APIError, asyncio.TimeoutError) as e2:
99
+ logger.exception(
100
+ f"Fallback LLM model {fallback} also failed with API/Timeout: {e2}"
101
+ )
102
+ raise
103
+ except Exception:
104
+ logger.exception(f"Fallback LLM model {fallback} also failed")
105
+ raise
106
+ except asyncio.TimeoutError as e:
107
+ # Request timed out
108
+ logger.warning(f"Primary LLM Timeout for model {primary}: {e}")
109
+ logger.info(f"Retrying LLM call with fallback model {fallback}")
110
+ try:
111
+ response = await litellm.acompletion(
112
+ model=fallback,
113
+ messages=[{"role": "user", "content": prompt}],
114
+ timeout=timeout,
115
+ api_key=self._groq_api_key,
116
+ )
117
+ used_label = "fallback"
118
+ used_model_name = fallback
119
+ except (litellm.exceptions.APIError, asyncio.TimeoutError) as e2:
120
+ logger.exception(
121
+ f"Fallback LLM model {fallback} also failed with API/Timeout: {e2}"
122
+ )
123
+ raise
124
+ except Exception:
125
+ logger.exception(f"Fallback LLM model {fallback} also failed")
126
+ raise
127
+ except Exception as e:
128
+ # Unknown/other exceptions
129
+ logger.error(f"Primary LLM unexpected error for model {primary}: {e}")
130
+ logger.info(f"Retrying LLM call with fallback model {fallback}")
131
+ try:
132
+ response = await litellm.acompletion(
133
+ model=fallback,
134
+ messages=[{"role": "user", "content": prompt}],
135
+ timeout=timeout,
136
+ api_key=self._groq_api_key,
137
+ )
138
+ used_label = "fallback"
139
+ used_model_name = fallback
140
+ except Exception:
141
+ logger.exception(f"Fallback LLM model {fallback} also failed")
142
+ raise
143
+
144
+ # Extract the chat content like OpenAI style responses
145
+ try:
146
+ content = response.choices[0].message.content
147
+ logger.debug(
148
+ f"LLMRouter.generate exit: model_type={model_type} used={used_label} model={used_model_name}"
149
+ )
150
+ return content
151
+ except Exception as e:
152
+ logger.exception(f"Unexpected response structure from LLM: {e}")
153
+ raise