Commit ·
115794d
1
Parent(s): 6078097
multi-stage refactor
Browse files- agents/acquisition_agent.py +100 -99
- agents/query_optimization_agent.py +9 -59
- agents/semantic_scholar_client.py +20 -15
- agents/synthesis_agent.py +10 -59
- config/__init__.py +3 -12
- config/config.py +37 -138
- config/embedding_config.py +11 -14
- config/prompts.py +97 -0
- main.py +59 -41
- services/discovery_service.py +21 -37
- services/ingestion_service.py +51 -1
- services/query_service.py +24 -47
- services/rag_service.py +48 -76
- ui/styles.py → static/css/styles.css +12 -15
- tests/eval_config.py +13 -7
- tests/integration/test_api.py +5 -18
- tests/unit/test_acquisition_agent.py +8 -6
- tests/unit/test_config.py +45 -77
- tests/unit/test_llm_router.py +26 -23
- tests/unit/test_query_optimization_agent.py +6 -2
- tests/unit/test_semantic_scholar_client.py +4 -0
- ui/__init__.py +1 -2
- ui/pages.py +17 -18
- utils/llm_router.py +10 -8
- utils/research_assistant_prompts.py +0 -90
agents/acquisition_agent.py
CHANGED
|
@@ -1,15 +1,16 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import asyncio
|
| 4 |
-
import tempfile
|
| 5 |
import os
|
|
|
|
| 6 |
import time
|
| 7 |
-
from typing import
|
| 8 |
-
|
| 9 |
from curl_cffi.requests import AsyncSession, RequestsError
|
|
|
|
| 10 |
|
| 11 |
from models.state import State
|
| 12 |
-
from utils.pdf_extractor import
|
| 13 |
|
| 14 |
# UPDATE THIS BLOCK
|
| 15 |
HEADERS = {
|
|
@@ -69,7 +70,7 @@ class AcquisitionAgent:
|
|
| 69 |
|
| 70 |
TARGET_PDF_COUNT = 5
|
| 71 |
acquired_pdfs = 0
|
| 72 |
-
|
| 73 |
|
| 74 |
finalists = state.finalists
|
| 75 |
logger.info(
|
|
@@ -83,6 +84,10 @@ class AcquisitionAgent:
|
|
| 83 |
async with AsyncSession(impersonate="chrome110", headers=HEADERS) as session:
|
| 84 |
# 1. First, add abstracts for ALL finalists (fast, synchronous)
|
| 85 |
for paper in finalists:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
abstract_text = paper.get("abstract", "")
|
| 87 |
if abstract_text:
|
| 88 |
abstract_passage = dict(paper)
|
|
@@ -93,7 +98,7 @@ class AcquisitionAgent:
|
|
| 93 |
"extraction_error": None,
|
| 94 |
}
|
| 95 |
)
|
| 96 |
-
|
| 97 |
|
| 98 |
# 2. Concurrent PDF acquisition for top candidates
|
| 99 |
# We try the top 12 candidates to get our target of 5 PDFs
|
|
@@ -135,19 +140,22 @@ class AcquisitionAgent:
|
|
| 135 |
# break
|
| 136 |
|
| 137 |
if res and res.get("text"):
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
| 147 |
|
| 148 |
elapsed = time.monotonic() - start_all
|
| 149 |
|
| 150 |
# Update state.passages with final results
|
|
|
|
| 151 |
new_state = state.model_copy(deep=True)
|
| 152 |
new_state.passages = final_passages
|
| 153 |
|
|
@@ -185,99 +193,92 @@ class AcquisitionAgent:
|
|
| 185 |
return None
|
| 186 |
|
| 187 |
logger.debug("Downloading PDF for {pid} from {url}", pid=paper_id, url=url)
|
| 188 |
-
t0 = time.monotonic()
|
| 189 |
-
try:
|
| 190 |
-
tmp_path = await self._download_single_pdf(paper_id, url, session)
|
| 191 |
-
except asyncio.TimeoutError:
|
| 192 |
-
logger.warning("Timeout while downloading PDF for {pid}", pid=paper_id)
|
| 193 |
-
return None
|
| 194 |
-
except RequestsError as e:
|
| 195 |
-
logger.warning(
|
| 196 |
-
"HTTP/client error for {pid}: {err}", pid=paper_id, err=str(e)
|
| 197 |
-
)
|
| 198 |
-
return None
|
| 199 |
-
except Exception as e:
|
| 200 |
-
logger.warning("Download failed for {pid}: {err}", pid=paper_id, err=str(e))
|
| 201 |
-
return None
|
| 202 |
-
dt_download = time.monotonic() - t0
|
| 203 |
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
)
|
| 217 |
-
return None
|
| 218 |
-
dt_extract = time.monotonic() - t1
|
| 219 |
-
|
| 220 |
-
# cleanup temp
|
| 221 |
-
try:
|
| 222 |
-
if tmp_path and os.path.exists(tmp_path):
|
| 223 |
-
os.remove(tmp_path)
|
| 224 |
-
except Exception:
|
| 225 |
-
pass
|
| 226 |
-
|
| 227 |
-
logger.info(
|
| 228 |
-
"Extracted PDF for {pid} (text_length={n}) download={d:.2f}s extract={e:.2f}s",
|
| 229 |
-
pid=paper_id,
|
| 230 |
-
n=len(text),
|
| 231 |
-
d=dt_download,
|
| 232 |
-
e=dt_extract,
|
| 233 |
-
)
|
| 234 |
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
|
| 245 |
async def _download_single_pdf(
|
| 246 |
-
self,
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
Raises RequestsError for network issues or HTTP status >= 400.
|
| 251 |
"""
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
"HTTP {status} when fetching PDF for {pid}",
|
| 263 |
-
status=status,
|
| 264 |
-
pid=paper_id,
|
| 265 |
-
)
|
| 266 |
-
raise RequestsError(f"HTTP {status}")
|
| 267 |
-
|
| 268 |
-
with open(tmp_path, "wb") as fh:
|
| 269 |
-
async for chunk in resp.aiter_content(chunk_size=self._CHUNK_SIZE):
|
| 270 |
-
if not chunk:
|
| 271 |
-
continue
|
| 272 |
-
fh.write(chunk)
|
| 273 |
-
|
| 274 |
-
except RequestsError:
|
| 275 |
-
# ensure file removed on failure
|
| 276 |
-
if os.path.exists(tmp_path):
|
| 277 |
-
os.remove(tmp_path)
|
| 278 |
-
raise
|
| 279 |
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
async def _extract_and_validate(self, tmp_path: str, paper_id: str) -> str:
|
| 283 |
"""Run PyMuPDF extraction in a thread and validate text length.
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import asyncio
|
|
|
|
| 4 |
import os
|
| 5 |
+
import tempfile
|
| 6 |
import time
|
| 7 |
+
from typing import Any, Dict, List, Optional
|
| 8 |
+
|
| 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
|
| 16 |
HEADERS = {
|
|
|
|
| 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 |
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)
|
|
|
|
| 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
|
|
|
|
| 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 |
|
| 157 |
# Update state.passages with final results
|
| 158 |
+
final_passages = list(passages_map.values())
|
| 159 |
new_state = state.model_copy(deep=True)
|
| 160 |
new_state.passages = final_passages
|
| 161 |
|
|
|
|
| 193 |
return None
|
| 194 |
|
| 195 |
logger.debug("Downloading PDF for {pid} from {url}", pid=paper_id, url=url)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 198 |
+
pdf_path = os.path.join(temp_dir, f"{paper_id}.pdf")
|
| 199 |
+
t0 = time.monotonic()
|
| 200 |
+
try:
|
| 201 |
+
await self._download_single_pdf(
|
| 202 |
+
paper_id, url, session, destination_path=pdf_path
|
| 203 |
+
)
|
| 204 |
+
except asyncio.TimeoutError:
|
| 205 |
+
logger.warning("Timeout while downloading PDF for {pid}", pid=paper_id)
|
| 206 |
+
return None
|
| 207 |
+
except RequestsError as e:
|
| 208 |
+
logger.warning(
|
| 209 |
+
"HTTP/client error for {pid}: {err}", pid=paper_id, err=str(e)
|
| 210 |
+
)
|
| 211 |
+
return None
|
| 212 |
+
except Exception as e:
|
| 213 |
+
logger.warning(
|
| 214 |
+
"Download failed for {pid}: {err}", pid=paper_id, err=str(e)
|
| 215 |
+
)
|
| 216 |
+
return None
|
| 217 |
+
dt_download = time.monotonic() - t0
|
| 218 |
+
|
| 219 |
+
# extract and validate
|
| 220 |
+
t1 = time.monotonic()
|
| 221 |
+
try:
|
| 222 |
+
text = await self._extract_and_validate(pdf_path, paper_id)
|
| 223 |
+
except PdfExtractionError as e:
|
| 224 |
+
logger.warning(
|
| 225 |
+
"Extraction failed for {pid}: {err}", pid=paper_id, err=str(e)
|
| 226 |
+
)
|
| 227 |
+
return None
|
| 228 |
+
except Exception as e:
|
| 229 |
+
logger.warning(
|
| 230 |
+
"Unexpected extraction error for {pid}: {err}",
|
| 231 |
+
pid=paper_id,
|
| 232 |
+
err=str(e),
|
| 233 |
+
)
|
| 234 |
+
return None
|
| 235 |
+
dt_extract = time.monotonic() - t1
|
| 236 |
+
|
| 237 |
+
logger.info(
|
| 238 |
+
"Extracted PDF for {pid} (text_length={n}) download={d:.2f}s extract={e:.2f}s",
|
| 239 |
+
pid=paper_id,
|
| 240 |
+
n=len(text),
|
| 241 |
+
d=dt_download,
|
| 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,
|
| 257 |
+
paper_id: str,
|
| 258 |
+
url: str,
|
| 259 |
+
session: AsyncSession,
|
| 260 |
+
destination_path: str,
|
| 261 |
+
) -> None:
|
| 262 |
+
"""Stream-download a single PDF to the destination path.
|
| 263 |
|
| 264 |
Raises RequestsError for network issues or HTTP status >= 400.
|
| 265 |
"""
|
| 266 |
+
resp = await session.get(url, stream=True)
|
| 267 |
+
status = resp.status_code
|
| 268 |
+
if status >= 400:
|
| 269 |
+
# log specific HTTP errors
|
| 270 |
+
logger.warning(
|
| 271 |
+
"HTTP {status} when fetching PDF for {pid}",
|
| 272 |
+
status=status,
|
| 273 |
+
pid=paper_id,
|
| 274 |
+
)
|
| 275 |
+
raise RequestsError(f"HTTP {status}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
+
with open(destination_path, "wb") as fh:
|
| 278 |
+
async for chunk in resp.aiter_content(chunk_size=self._CHUNK_SIZE):
|
| 279 |
+
if not chunk:
|
| 280 |
+
continue
|
| 281 |
+
fh.write(chunk)
|
| 282 |
|
| 283 |
async def _extract_and_validate(self, tmp_path: str, paper_id: str) -> str:
|
| 284 |
"""Run PyMuPDF extraction in a thread and validate text length.
|
agents/query_optimization_agent.py
CHANGED
|
@@ -7,10 +7,12 @@ for passage-level semantic retrieval, and three Semantic Scholar search variants
|
|
| 7 |
|
| 8 |
import ast
|
| 9 |
import json
|
|
|
|
| 10 |
from typing import Any, Dict, Optional
|
| 11 |
|
| 12 |
from loguru import logger
|
| 13 |
|
|
|
|
| 14 |
from utils.llm_router import LLMRouter
|
| 15 |
|
| 16 |
|
|
@@ -133,71 +135,20 @@ class QueryOptimizationAgent:
|
|
| 133 |
def _extract_json_block(self, text: str) -> Optional[str]:
|
| 134 |
"""Extract the first balanced JSON object from text.
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
None when no balanced block is found.
|
| 139 |
"""
|
| 140 |
-
if not text
|
| 141 |
return None
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
ch = text[i]
|
| 147 |
-
if ch == "{":
|
| 148 |
-
depth += 1
|
| 149 |
-
elif ch == "}":
|
| 150 |
-
depth -= 1
|
| 151 |
-
if depth == 0:
|
| 152 |
-
return text[start : i + 1]
|
| 153 |
return None
|
| 154 |
|
| 155 |
def _build_prompt(self, query: str) -> str:
|
| 156 |
"""Build the LLM prompt for query optimization."""
|
| 157 |
-
return
|
| 158 |
-
|
| 159 |
-
Your task: Analyze the user's query and choose the best strategy: 'expansion' or 'decomposition'.
|
| 160 |
-
|
| 161 |
-
User input: "{query}"
|
| 162 |
-
|
| 163 |
-
**Strategy A: Expansion (Default)**
|
| 164 |
-
Use this for single-topic or straightforward queries.
|
| 165 |
-
|
| 166 |
-
**INTENT ANALYSIS (Crucial):**
|
| 167 |
-
Analyze the user's intent to optimize the 'broad' field:
|
| 168 |
-
1. **Overview/Consensus needed?** (e.g., "What is...", "How does...", "Summary of...") -> Set 'broad' to keywords + "review" OR "survey" OR "state of the art".
|
| 169 |
-
2. **Latest News needed?** (e.g., "Recent...", "Newest...", "Updates on...") -> Set 'broad' to keywords + "recent" OR "advances" OR "novel".
|
| 170 |
-
3. **Specific Details?** -> Keep 'broad' as general synonyms.
|
| 171 |
-
|
| 172 |
-
Output Format (JSON):
|
| 173 |
-
{{
|
| 174 |
-
"strategy": "expansion",
|
| 175 |
-
"final_rephrase": "Clear natural language question for semantic search",
|
| 176 |
-
"primary": "3-6 specific keywords",
|
| 177 |
-
"broad": "3-6 keywords optimized for INTENT (e.g., include 'review' or 'recent' if applicable)",
|
| 178 |
-
"alternative": "3-6 keywords focusing on limitations or debates"
|
| 179 |
-
}}
|
| 180 |
-
|
| 181 |
-
**Strategy B: Decomposition**
|
| 182 |
-
Use this for complex, multi-part, or comparative queries that require breaking down.
|
| 183 |
-
Generate a list of sub-queries to be executed independently.
|
| 184 |
-
|
| 185 |
-
Output Format (JSON):
|
| 186 |
-
{{
|
| 187 |
-
"strategy": "decomposition",
|
| 188 |
-
"final_rephrase": "The overarching question in clear natural language",
|
| 189 |
-
"sub_queries": [
|
| 190 |
-
"First sub-question keywords",
|
| 191 |
-
"Second sub-question keywords",
|
| 192 |
-
"..."
|
| 193 |
-
]
|
| 194 |
-
}}
|
| 195 |
-
|
| 196 |
-
**CRITICAL RULES:**
|
| 197 |
-
- 'final_rephrase' is MANDATORY for BOTH strategies.
|
| 198 |
-
- For 'primary', 'broad', 'alternative', and 'sub_queries': DO NOT use boolean operators (AND, OR). Keep them short (3-6 keywords).
|
| 199 |
-
- Return ONLY valid JSON.
|
| 200 |
-
"""
|
| 201 |
|
| 202 |
def _validate_response(self, response: Dict) -> bool:
|
| 203 |
"""Validate that the LLM response contains all required fields based on strategy."""
|
|
@@ -238,4 +189,3 @@ class QueryOptimizationAgent:
|
|
| 238 |
|
| 239 |
|
| 240 |
__all__ = ["QueryOptimizationAgent"]
|
| 241 |
-
__all__ = ["QueryOptimizationAgent"]
|
|
|
|
| 7 |
|
| 8 |
import ast
|
| 9 |
import json
|
| 10 |
+
import re
|
| 11 |
from typing import Any, Dict, Optional
|
| 12 |
|
| 13 |
from loguru import logger
|
| 14 |
|
| 15 |
+
from config.prompts import QUERY_OPTIMIZATION_TEMPLATE
|
| 16 |
from utils.llm_router import LLMRouter
|
| 17 |
|
| 18 |
|
|
|
|
| 135 |
def _extract_json_block(self, text: str) -> Optional[str]:
|
| 136 |
"""Extract the first balanced JSON object from text.
|
| 137 |
|
| 138 |
+
Uses regex to find the first JSON object, handling potential
|
| 139 |
+
Markdown code blocks or conversational text.
|
|
|
|
| 140 |
"""
|
| 141 |
+
if not text:
|
| 142 |
return None
|
| 143 |
|
| 144 |
+
match = re.search(r"(\{.*\})", text, re.DOTALL)
|
| 145 |
+
if match:
|
| 146 |
+
return match.group(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
return None
|
| 148 |
|
| 149 |
def _build_prompt(self, query: str) -> str:
|
| 150 |
"""Build the LLM prompt for query optimization."""
|
| 151 |
+
return QUERY_OPTIMIZATION_TEMPLATE.format(query=query)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
def _validate_response(self, response: Dict) -> bool:
|
| 154 |
"""Validate that the LLM response contains all required fields based on strategy."""
|
|
|
|
| 189 |
|
| 190 |
|
| 191 |
__all__ = ["QueryOptimizationAgent"]
|
|
|
agents/semantic_scholar_client.py
CHANGED
|
@@ -18,12 +18,12 @@ State.papers expectations.
|
|
| 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 |
-
import sys
|
| 27 |
|
| 28 |
logger.remove()
|
| 29 |
logger.add(sys.stderr, level="INFO")
|
|
@@ -50,6 +50,19 @@ class SemanticScholarClient:
|
|
| 50 |
self._semaphore = asyncio.Semaphore(rate_limit)
|
| 51 |
# Default per-request timeout (seconds) used for client sessions
|
| 52 |
self._timeout_seconds = 10
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
async def multi_query_search(
|
| 55 |
self,
|
|
@@ -89,21 +102,13 @@ class SemanticScholarClient:
|
|
| 89 |
# Log entry with a short preview so we can diagnose slow queries
|
| 90 |
logger.info(f"multi_query_search entry: queries= {[q[:80] for q in queries]}")
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
timeout = aiohttp.ClientTimeout(total=self._timeout_seconds)
|
| 95 |
-
|
| 96 |
-
async with aiohttp.ClientSession(
|
| 97 |
-
connector=connector, timeout=timeout
|
| 98 |
-
) as session:
|
| 99 |
-
tasks = [
|
| 100 |
-
self._run_query(session, q, limit_per_query, fields) for q in queries
|
| 101 |
-
]
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
|
| 108 |
# Log how many raw hits we received per input query (primary/broad/alternative
|
| 109 |
# ordering is expected by the caller). This helps diagnose which variant
|
|
|
|
| 18 |
from __future__ import annotations
|
| 19 |
|
| 20 |
import asyncio
|
| 21 |
+
import sys
|
| 22 |
import time
|
| 23 |
from typing import Any, Dict, List, Optional
|
| 24 |
|
| 25 |
import aiohttp
|
| 26 |
from loguru import logger
|
|
|
|
| 27 |
|
| 28 |
logger.remove()
|
| 29 |
logger.add(sys.stderr, level="INFO")
|
|
|
|
| 50 |
self._semaphore = asyncio.Semaphore(rate_limit)
|
| 51 |
# Default per-request timeout (seconds) used for client sessions
|
| 52 |
self._timeout_seconds = 10
|
| 53 |
+
self._session: Optional[aiohttp.ClientSession] = None
|
| 54 |
+
|
| 55 |
+
async def _get_session(self) -> aiohttp.ClientSession:
|
| 56 |
+
if self._session is None or self._session.closed:
|
| 57 |
+
# Create persistent session with connection pooling
|
| 58 |
+
connector = aiohttp.TCPConnector(limit=100, limit_per_host=25)
|
| 59 |
+
timeout = aiohttp.ClientTimeout(total=self._timeout_seconds)
|
| 60 |
+
self._session = aiohttp.ClientSession(connector=connector, timeout=timeout)
|
| 61 |
+
return self._session
|
| 62 |
+
|
| 63 |
+
async def close(self):
|
| 64 |
+
if self._session and not self._session.closed:
|
| 65 |
+
await self._session.close()
|
| 66 |
|
| 67 |
async def multi_query_search(
|
| 68 |
self,
|
|
|
|
| 102 |
# Log entry with a short preview so we can diagnose slow queries
|
| 103 |
logger.info(f"multi_query_search entry: queries= {[q[:80] for q in queries]}")
|
| 104 |
|
| 105 |
+
session = await self._get_session()
|
| 106 |
+
tasks = [self._run_query(session, q, limit_per_query, fields) for q in queries]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
start = time.perf_counter()
|
| 109 |
+
raw_results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 110 |
+
elapsed = time.perf_counter() - start
|
| 111 |
+
logger.info("multi_query_search finished in {:.3f}s", elapsed)
|
| 112 |
|
| 113 |
# Log how many raw hits we received per input query (primary/broad/alternative
|
| 114 |
# ordering is expected by the caller). This helps diagnose which variant
|
agents/synthesis_agent.py
CHANGED
|
@@ -21,68 +21,15 @@ Architecture:
|
|
| 21 |
- Handles empty nodes gracefully with fallback message
|
| 22 |
"""
|
| 23 |
|
|
|
|
| 24 |
from typing import List
|
| 25 |
-
from loguru import logger
|
| 26 |
|
| 27 |
from llama_index.core.schema import NodeWithScore
|
| 28 |
-
from
|
| 29 |
|
|
|
|
|
|
|
| 30 |
from utils.llm_router import LLMRouter
|
| 31 |
-
import re
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
FEW_SHOT_EXAMPLE = """
|
| 35 |
-
**Verdict: Yes, with consensus on mechanism but debate on magnitude.**
|
| 36 |
-
Rapamycin consistently extends lifespan in model organisms via mTOR inhibition [1], though sexual dimorphism in mice remains a significant variable [3].
|
| 37 |
-
|
| 38 |
-
### Evidence Synthesis
|
| 39 |
-
The extension of lifespan by rapamycin is robust and reproducible across diverse taxa, including yeast, nematodes, and mice [1]. The primary mechanism is the inhibition of the *mammalian target of rapamycin* (mTOR) pathway, which mimics caloric restriction and enhances autophagy [4]. In murine models, treatment initiated even in late life (600 days) significantly increases survival rates [2], suggesting the intervention is effective even after aging has commenced.
|
| 40 |
-
|
| 41 |
-
### Critical Nuances & Conflicts
|
| 42 |
-
* **Sexual Dimorphism –** Evidence suggests a stronger effect in females than males. One major study found a 14% extension in females versus only 9% in males at the same dosage [3], potentially due to differences in hepatic drug metabolism.
|
| 43 |
-
* **Dosage Toxicity –** While lifespan is extended, high doses are associated with testicular degeneration [5], indicating a narrow therapeutic window.
|
| 44 |
-
"""
|
| 45 |
-
|
| 46 |
-
CITATION_QA_TEMPLATE = (
|
| 47 |
-
"You are a Senior Scientific Research Fellow briefing a Principal Investigator. "
|
| 48 |
-
"Your goal is to distill a complex body of literature into a definitive, scientifically rigorous synthesis.\n"
|
| 49 |
-
"---------------------\n"
|
| 50 |
-
"### INSTRUCTIONS:\n"
|
| 51 |
-
"1. **THE BLUF (Bottom Line Up Front):**\n"
|
| 52 |
-
" - Start immediately with a bold **Label**. Choose the best fit:\n"
|
| 53 |
-
" * *Binary:* **Verdict: Yes / No / Mixed.**\n"
|
| 54 |
-
" * *Definitional:* **Core Concept: [Phrase].**\n"
|
| 55 |
-
" * *Methodological:* **Standard Protocol: [Method].**\n"
|
| 56 |
-
" * *Open:* **Scientific Consensus: [Theme].**\n"
|
| 57 |
-
" - Follow with a high-level thesis sentence summarizing the answer.\n\n"
|
| 58 |
-
"2. **THE EVIDENCE (Structured & Rigorous):**\n"
|
| 59 |
-
" - **Evidence Synthesis:** Synthesize the high-authority agreement. What is the established truth? (Cite support).\n"
|
| 60 |
-
" - **Critical Nuances:** Discuss conflicts, sexual dimorphism, in vivo vs in vitro discrepancies, or major limitations.\n\n"
|
| 61 |
-
"3. **STYLE & CONSTRAINTS:**\n"
|
| 62 |
-
" - **Target Length:** ~250-350 words. Be dense but readable.\n"
|
| 63 |
-
" - **Bullet Style:** Start every bullet point with a **Bold Concept Label** followed by a dash. Mandatory.\n"
|
| 64 |
-
" - **Tone:** Professional. Use precise terminology.\n"
|
| 65 |
-
" - **Definitions:** Define ONLY non-standard acronyms on first use.\n\n"
|
| 66 |
-
"4. **PROTOCOL FOR INSUFFICIENT DATA:**\n"
|
| 67 |
-
" - If the provided chunks do not contain the answer, do not hallucinate.\n"
|
| 68 |
-
" - Output exactly: **Verdict: Insufficient Evidence.** followed by a brief explanation of what is missing.\n"
|
| 69 |
-
" - If you know of a major scientific consensus that is NOT in the sources, you may add a final section: \n"
|
| 70 |
-
" '### Missing Context'\n"
|
| 71 |
-
" 'Major theories such as [Concept] were not found in the retrieved papers.' (DO NOT CITE THIS).\n\n"
|
| 72 |
-
"5. **CITATION RULES (STRICT):**\n"
|
| 73 |
-
" - **Valid Source Range:** You have access to Sources 1 through {max_id}. **ANY CITATION > {max_id} IS A HALLUCINATION.**\n"
|
| 74 |
-
" - **Atomic Citations:** Every specific claim must be cited immediately [N].\n"
|
| 75 |
-
" - **Verification:** Do not cite a source unless the text explicitly supports the claim.\n"
|
| 76 |
-
" - **The 'Eyes-Only' Rule:** IGNORE YOUR TRAINING DATA. Use ONLY facts present in the text chunks.\n"
|
| 77 |
-
"### REQUIRED OUTPUT FORMAT:\n"
|
| 78 |
-
"---------------------\n"
|
| 79 |
-
f"{FEW_SHOT_EXAMPLE}\n"
|
| 80 |
-
"---------------------\n\n"
|
| 81 |
-
"### CONTEXT CHUNKS (Sources 1-{max_id}):\n"
|
| 82 |
-
"{context_str}\n\n"
|
| 83 |
-
"User Query: {query_str}\n"
|
| 84 |
-
"Answer (using ONLY Sources 1-{max_id}):"
|
| 85 |
-
)
|
| 86 |
|
| 87 |
|
| 88 |
class SynthesisAgent:
|
|
@@ -99,12 +46,14 @@ class SynthesisAgent:
|
|
| 99 |
|
| 100 |
INSUFFICIENT_CONTEXT_MESSAGE = "I cannot answer this based on the provided sources."
|
| 101 |
|
| 102 |
-
def __init__(self, temperature: float = 0.15) -> None:
|
| 103 |
"""Initialize the synthesis agent.
|
| 104 |
|
| 105 |
Args:
|
|
|
|
| 106 |
temperature: LLM temperature for generation (0.15 = focused but not rigid).
|
| 107 |
"""
|
|
|
|
| 108 |
self.router = LLMRouter()
|
| 109 |
self.temperature = temperature
|
| 110 |
logger.info(f"SynthesisAgent initialized with temperature={temperature}")
|
|
@@ -139,7 +88,9 @@ class SynthesisAgent:
|
|
| 139 |
|
| 140 |
# Build the full prompt
|
| 141 |
prompt = CITATION_QA_TEMPLATE.format(
|
| 142 |
-
context_str=context_str,
|
|
|
|
|
|
|
| 143 |
)
|
| 144 |
|
| 145 |
logger.debug(
|
|
|
|
| 21 |
- Handles empty nodes gracefully with fallback message
|
| 22 |
"""
|
| 23 |
|
| 24 |
+
import re
|
| 25 |
from typing import List
|
|
|
|
| 26 |
|
| 27 |
from llama_index.core.schema import NodeWithScore
|
| 28 |
+
from loguru import logger
|
| 29 |
|
| 30 |
+
from config.config import get_settings
|
| 31 |
+
from config.prompts import CITATION_QA_TEMPLATE, FEW_SHOT_EXAMPLE
|
| 32 |
from utils.llm_router import LLMRouter
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
class SynthesisAgent:
|
|
|
|
| 46 |
|
| 47 |
INSUFFICIENT_CONTEXT_MESSAGE = "I cannot answer this based on the provided sources."
|
| 48 |
|
| 49 |
+
def __init__(self, settings: "Settings" = None, temperature: float = 0.15) -> None:
|
| 50 |
"""Initialize the synthesis agent.
|
| 51 |
|
| 52 |
Args:
|
| 53 |
+
settings: Optional settings object. If None, loads from config.
|
| 54 |
temperature: LLM temperature for generation (0.15 = focused but not rigid).
|
| 55 |
"""
|
| 56 |
+
self.settings = settings or get_settings()
|
| 57 |
self.router = LLMRouter()
|
| 58 |
self.temperature = temperature
|
| 59 |
logger.info(f"SynthesisAgent initialized with temperature={temperature}")
|
|
|
|
| 88 |
|
| 89 |
# Build the full prompt
|
| 90 |
prompt = CITATION_QA_TEMPLATE.format(
|
| 91 |
+
context_str=context_str,
|
| 92 |
+
query_str=query,
|
| 93 |
+
max_id=get_settings().RAG_RERANK_TOP_K,
|
| 94 |
)
|
| 95 |
|
| 96 |
logger.debug(
|
config/__init__.py
CHANGED
|
@@ -9,18 +9,9 @@ multi-core mode is enabled before numpy/torch/onnxruntime are imported anywhere.
|
|
| 9 |
|
| 10 |
# CRITICAL: Import threading config before anything else
|
| 11 |
from . import _threading # noqa: F401 (sets env vars, has side effects)
|
| 12 |
-
|
| 13 |
-
from .config import * # noqa: F401,F403 (re-export configuration symbols)
|
| 14 |
|
| 15 |
__all__ = [
|
| 16 |
-
|
| 17 |
-
"
|
| 18 |
-
"QUERY_OPTIMIZATION_MODEL",
|
| 19 |
-
"QUERY_OPTIMIZATION_FALLBACK",
|
| 20 |
-
"SYNTHESIS_MODEL",
|
| 21 |
-
"SYNTHESIS_FALLBACK",
|
| 22 |
-
"PRIMARY_LLM_API_KEY",
|
| 23 |
-
"SECONDARY_LLM_API_KEY",
|
| 24 |
-
"TIMEOUT",
|
| 25 |
-
"validate_config",
|
| 26 |
]
|
|
|
|
| 9 |
|
| 10 |
# CRITICAL: Import threading config before anything else
|
| 11 |
from . import _threading # noqa: F401 (sets env vars, has side effects)
|
| 12 |
+
from .config import Settings, get_settings
|
|
|
|
| 13 |
|
| 14 |
__all__ = [
|
| 15 |
+
"get_settings",
|
| 16 |
+
"Settings",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
]
|
config/config.py
CHANGED
|
@@ -1,150 +1,49 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
Provides model configurations for LiteLLM routing.
|
| 6 |
-
"""
|
| 7 |
|
| 8 |
-
|
| 9 |
-
import time
|
| 10 |
-
from dotenv import load_dotenv
|
| 11 |
-
from loguru import logger
|
| 12 |
|
| 13 |
-
# Load environment variables from .env file (if present).
|
| 14 |
-
# During tests we may set SKIP_DOTENV_LOADER=1 to avoid loading a repo .env
|
| 15 |
-
# which would interfere with tests that expect missing keys.
|
| 16 |
-
if os.getenv("SKIP_DOTENV_LOADER", "").lower() not in ("1", "true", "yes"):
|
| 17 |
-
load_dotenv()
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
# Semantic Scholar API Configuration
|
| 30 |
-
# ============================================================================
|
| 31 |
-
SEMANTIC_SCHOLAR_API_KEY = os.getenv("SEMANTIC_SCHOLAR_API_KEY")
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
QUERY_OPTIMIZATION_MODEL = os.getenv("QUERY_OPTIMIZATION_MODEL")
|
| 38 |
-
QUERY_OPTIMIZATION_FALLBACK = os.getenv("QUERY_OPTIMIZATION_FALLBACK")
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
# Powerful models for final answer generation
|
| 43 |
-
# ============================================================================
|
| 44 |
-
SYNTHESIS_MODEL = os.getenv("SYNTHESIS_MODEL")
|
| 45 |
-
SYNTHESIS_FALLBACK = os.getenv("SYNTHESIS_FALLBACK")
|
| 46 |
|
| 47 |
-
|
| 48 |
-
# API Keys for LiteLLM Providers
|
| 49 |
-
# ============================================================================
|
| 50 |
-
PRIMARY_LLM_API_KEY = os.getenv("PRIMARY_LLM_API_KEY")
|
| 51 |
-
SECONDARY_LLM_API_KEY = os.getenv("SECONDARY_LLM_API_KEY")
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
# ============================================================================
|
| 62 |
-
TIMEOUT = int(os.getenv("TIMEOUT", "30")) # API timeout in seconds
|
| 63 |
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
return "<missing>"
|
| 69 |
-
if len(value) <= 8:
|
| 70 |
-
return value[0:1] + "*" * (len(value) - 1)
|
| 71 |
-
return value[0:4] + "*" * (len(value) - 8) + value[-4:]
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
def validate_config() -> None:
|
| 75 |
-
"""
|
| 76 |
-
Validate that all required environment variables are set.
|
| 77 |
-
|
| 78 |
-
Raises:
|
| 79 |
-
ValueError: If any required environment variable is missing
|
| 80 |
-
|
| 81 |
-
Note:
|
| 82 |
-
This function is safe to call multiple times; it's cheap and completes
|
| 83 |
-
quickly. It is also called automatically when this module is imported.
|
| 84 |
-
"""
|
| 85 |
-
start = time.perf_counter()
|
| 86 |
-
|
| 87 |
-
required_vars = {
|
| 88 |
-
"SEMANTIC_SCHOLAR_API_KEY": {
|
| 89 |
-
"value": SEMANTIC_SCHOLAR_API_KEY,
|
| 90 |
-
"help": "Get free key at https://www.semanticscholar.org/product/api",
|
| 91 |
-
},
|
| 92 |
-
"PRIMARY_LLM_API_KEY": {
|
| 93 |
-
"value": PRIMARY_LLM_API_KEY,
|
| 94 |
-
"help": "Get free key at https://www.cerebras.ai/",
|
| 95 |
-
},
|
| 96 |
-
"SECONDARY_LLM_API_KEY": {
|
| 97 |
-
"value": SECONDARY_LLM_API_KEY,
|
| 98 |
-
"help": "Get free key at https://console.groq.com/keys",
|
| 99 |
-
},
|
| 100 |
-
}
|
| 101 |
-
if WEB3FORMS_ACCESS_KEY:
|
| 102 |
-
logger.info("✓ Contact form configured (Web3Forms)")
|
| 103 |
-
else:
|
| 104 |
-
logger.warning("⚠️ Web3Forms key missing. Submissions will log to console.")
|
| 105 |
-
|
| 106 |
-
missing = []
|
| 107 |
-
empty_values = []
|
| 108 |
-
for var_name, var_info in required_vars.items():
|
| 109 |
-
val = var_info["value"]
|
| 110 |
-
if val is None:
|
| 111 |
-
missing.append(f"{var_name} - {var_info['help']}")
|
| 112 |
-
elif isinstance(val, str) and val.strip() == "":
|
| 113 |
-
empty_values.append(var_name)
|
| 114 |
-
|
| 115 |
-
if empty_values:
|
| 116 |
-
logger.error(
|
| 117 |
-
"Configuration error: environment variables set but empty: {}",
|
| 118 |
-
", ".join(empty_values),
|
| 119 |
-
)
|
| 120 |
-
raise ValueError(
|
| 121 |
-
"The following environment variables are set but empty: "
|
| 122 |
-
+ ", ".join(empty_values)
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
if missing:
|
| 126 |
-
error_msg = (
|
| 127 |
-
"Missing required environment variables:\n"
|
| 128 |
-
+ "\n".join(f" - {m}" for m in missing)
|
| 129 |
-
+ "\n\nCreate a .env file in the project root with these variables. See .env.example for a template."
|
| 130 |
-
)
|
| 131 |
-
logger.error(error_msg)
|
| 132 |
-
raise ValueError(error_msg)
|
| 133 |
-
|
| 134 |
-
# Log masked keys and selected configuration for observability
|
| 135 |
-
logger.info("✓ Configuration validated successfully")
|
| 136 |
-
logger.info(" Query optimization model: {}", QUERY_OPTIMIZATION_MODEL)
|
| 137 |
-
logger.info(" Query optimization fallback: {}", QUERY_OPTIMIZATION_FALLBACK)
|
| 138 |
-
logger.info(" Synthesis model: {}", SYNTHESIS_MODEL)
|
| 139 |
-
logger.info(" Synthesis fallback: {}", SYNTHESIS_FALLBACK)
|
| 140 |
-
logger.info(" Timeout: {}s", TIMEOUT)
|
| 141 |
-
logger.debug(" SEMANTIC_SCHOLAR_API_KEY: {}", _mask_key(SEMANTIC_SCHOLAR_API_KEY))
|
| 142 |
-
logger.debug(" PRIMARY_LLM_API_KEY: {}", _mask_key(PRIMARY_LLM_API_KEY))
|
| 143 |
-
logger.debug(" SECONDARY_LLM_API_KEY: {}", _mask_key(SECONDARY_LLM_API_KEY))
|
| 144 |
-
|
| 145 |
-
elapsed_ms = (time.perf_counter() - start) * 1000.0
|
| 146 |
-
logger.debug("Configuration validation took %.2fms", elapsed_ms)
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
# Validate configuration when module is imported
|
| 150 |
-
validate_config()
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from typing import Optional
|
| 4 |
|
| 5 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
class Settings(BaseSettings):
|
| 11 |
+
# API Keys
|
| 12 |
+
SEMANTIC_SCHOLAR_API_KEY: Optional[str] = None
|
| 13 |
+
PRIMARY_LLM_API_KEY: Optional[str] = None
|
| 14 |
+
SECONDARY_LLM_API_KEY: Optional[str] = None
|
| 15 |
+
WEB3FORMS_ACCESS_KEY: Optional[str] = None
|
| 16 |
|
| 17 |
+
# Models
|
| 18 |
+
QUERY_OPTIMIZATION_MODEL: str = "mistral/ministral-8b-2512"
|
| 19 |
+
QUERY_OPTIMIZATION_FALLBACK: str = "cerebras/llama3.1-8b"
|
| 20 |
+
SYNTHESIS_MODEL: str = "mistral/mistral-large-2512"
|
| 21 |
+
SYNTHESIS_FALLBACK: str = "cerebras/llama-3.3-70b"
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
# Tuning
|
| 24 |
+
RAG_RETRIEVAL_TOP_K: int = 50
|
| 25 |
+
RAG_RERANK_TOP_K: int = 12
|
| 26 |
+
TIMEOUT: int = 30
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
# System
|
| 29 |
+
LOG_LEVEL: str = "INFO"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
def validate_keys(self):
|
| 34 |
+
"""
|
| 35 |
+
Validates that critical API keys are present.
|
| 36 |
+
Logs warnings if they are missing.
|
| 37 |
+
"""
|
| 38 |
+
if not self.SEMANTIC_SCHOLAR_API_KEY:
|
| 39 |
+
logger.warning(
|
| 40 |
+
"SEMANTIC_SCHOLAR_API_KEY is not set. Paper discovery may be limited."
|
| 41 |
+
)
|
| 42 |
|
| 43 |
+
if not self.PRIMARY_LLM_API_KEY:
|
| 44 |
+
logger.warning("PRIMARY_LLM_API_KEY is not set. LLM features will fail.")
|
|
|
|
|
|
|
| 45 |
|
| 46 |
|
| 47 |
+
@lru_cache
|
| 48 |
+
def get_settings() -> Settings:
|
| 49 |
+
return Settings()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
config/embedding_config.py
CHANGED
|
@@ -22,6 +22,7 @@ from __future__ import annotations
|
|
| 22 |
|
| 23 |
import time
|
| 24 |
from typing import Any, Optional
|
|
|
|
| 25 |
from fastapi import FastAPI
|
| 26 |
from loguru import logger
|
| 27 |
|
|
@@ -62,14 +63,11 @@ def _lazy_import_onnx() -> tuple[bool, Optional[callable]]:
|
|
| 62 |
return False, None
|
| 63 |
|
| 64 |
|
| 65 |
-
async def init_embedding(
|
| 66 |
-
"""Initialize ONNX Embedding Model
|
| 67 |
-
|
| 68 |
-
This function handles errors gracefully to allow the app to start
|
| 69 |
-
even if the embedding model cannot be initialized.
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
|
| 74 |
Error Handling:
|
| 75 |
- ImportError: onnxruntime not installed -> logs critical, continues.
|
|
@@ -87,8 +85,7 @@ async def init_embedding(app: FastAPI) -> None:
|
|
| 87 |
"Embedding model not initialized: onnxruntime unavailable. "
|
| 88 |
"Basic features will work, but embedding-based features are disabled."
|
| 89 |
)
|
| 90 |
-
|
| 91 |
-
return
|
| 92 |
|
| 93 |
try:
|
| 94 |
logger.info(f"Initializing Embedding Model: {MODEL_NAME} (ONNX Optimized)")
|
|
@@ -97,9 +94,6 @@ async def init_embedding(app: FastAPI) -> None:
|
|
| 97 |
# This handles caching, validation, and ONNX session creation internally
|
| 98 |
model = init_onnx()
|
| 99 |
|
| 100 |
-
# Store on app state
|
| 101 |
-
app.state.embedding_model = model
|
| 102 |
-
|
| 103 |
duration = time.time() - start
|
| 104 |
|
| 105 |
# Validate dimension (Sanity Check)
|
|
@@ -120,18 +114,20 @@ async def init_embedding(app: FastAPI) -> None:
|
|
| 120 |
except ImportError:
|
| 121 |
logger.info(f"Embedding Ready: {duration:.2f}s | Dim: {EXPECTED_DIM}")
|
| 122 |
|
|
|
|
|
|
|
| 123 |
except RuntimeError as e:
|
| 124 |
# Model file missing - provide helpful instructions
|
| 125 |
logger.error(
|
| 126 |
f"Embedding model file missing: {e}. "
|
| 127 |
f"Run 'python scripts/setup_onnx.py' to download and convert the model."
|
| 128 |
)
|
| 129 |
-
|
| 130 |
|
| 131 |
except Exception as e:
|
| 132 |
# Unexpected error - log and continue
|
| 133 |
logger.exception(f"Failed to initialize embedding model: {e}")
|
| 134 |
-
|
| 135 |
|
| 136 |
|
| 137 |
def get_embedding_model(app: FastAPI) -> Optional[Any]:
|
|
@@ -158,3 +154,4 @@ def get_embedding_model(app: FastAPI) -> Optional[Any]:
|
|
| 158 |
)
|
| 159 |
|
| 160 |
return model
|
|
|
|
|
|
| 22 |
|
| 23 |
import time
|
| 24 |
from typing import Any, Optional
|
| 25 |
+
|
| 26 |
from fastapi import FastAPI
|
| 27 |
from loguru import logger
|
| 28 |
|
|
|
|
| 63 |
return False, None
|
| 64 |
|
| 65 |
|
| 66 |
+
async def init_embedding() -> Optional[Any]:
|
| 67 |
+
"""Initialize ONNX Embedding Model.
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
Returns:
|
| 70 |
+
The initialized embedding model or None if initialization failed.
|
| 71 |
|
| 72 |
Error Handling:
|
| 73 |
- ImportError: onnxruntime not installed -> logs critical, continues.
|
|
|
|
| 85 |
"Embedding model not initialized: onnxruntime unavailable. "
|
| 86 |
"Basic features will work, but embedding-based features are disabled."
|
| 87 |
)
|
| 88 |
+
return None
|
|
|
|
| 89 |
|
| 90 |
try:
|
| 91 |
logger.info(f"Initializing Embedding Model: {MODEL_NAME} (ONNX Optimized)")
|
|
|
|
| 94 |
# This handles caching, validation, and ONNX session creation internally
|
| 95 |
model = init_onnx()
|
| 96 |
|
|
|
|
|
|
|
|
|
|
| 97 |
duration = time.time() - start
|
| 98 |
|
| 99 |
# Validate dimension (Sanity Check)
|
|
|
|
| 114 |
except ImportError:
|
| 115 |
logger.info(f"Embedding Ready: {duration:.2f}s | Dim: {EXPECTED_DIM}")
|
| 116 |
|
| 117 |
+
return model
|
| 118 |
+
|
| 119 |
except RuntimeError as e:
|
| 120 |
# Model file missing - provide helpful instructions
|
| 121 |
logger.error(
|
| 122 |
f"Embedding model file missing: {e}. "
|
| 123 |
f"Run 'python scripts/setup_onnx.py' to download and convert the model."
|
| 124 |
)
|
| 125 |
+
return None
|
| 126 |
|
| 127 |
except Exception as e:
|
| 128 |
# Unexpected error - log and continue
|
| 129 |
logger.exception(f"Failed to initialize embedding model: {e}")
|
| 130 |
+
return None
|
| 131 |
|
| 132 |
|
| 133 |
def get_embedding_model(app: FastAPI) -> Optional[Any]:
|
|
|
|
| 154 |
)
|
| 155 |
|
| 156 |
return model
|
| 157 |
+
return model
|
config/prompts.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FEW_SHOT_EXAMPLE = """
|
| 2 |
+
**Verdict: Yes, with consensus on mechanism but debate on magnitude.**
|
| 3 |
+
Rapamycin consistently extends lifespan in model organisms via mTOR inhibition [1], though sexual dimorphism in mice remains a significant variable [3].
|
| 4 |
+
|
| 5 |
+
### Evidence Synthesis
|
| 6 |
+
The extension of lifespan by rapamycin is robust and reproducible across diverse taxa, including yeast, nematodes, and mice [1]. The primary mechanism is the inhibition of the *mammalian target of rapamycin* (mTOR) pathway, which mimics caloric restriction and enhances autophagy [4]. In murine models, treatment initiated even in late life (600 days) significantly increases survival rates [2], suggesting the intervention is effective even after aging has commenced.
|
| 7 |
+
|
| 8 |
+
### Critical Nuances & Conflicts
|
| 9 |
+
* **Sexual Dimorphism –** Evidence suggests a stronger effect in females than males. One major study found a 14% extension in females versus only 9% in males at the same dosage [3], potentially due to differences in hepatic drug metabolism.
|
| 10 |
+
* **Dosage Toxicity –** While lifespan is extended, high doses are associated with testicular degeneration [5], indicating a narrow therapeutic window.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
CITATION_QA_TEMPLATE = (
|
| 14 |
+
"You are a Senior Scientific Research Fellow briefing a Principal Investigator. "
|
| 15 |
+
"Your goal is to distill a complex body of literature into a definitive, scientifically rigorous synthesis.\n"
|
| 16 |
+
"---------------------\n"
|
| 17 |
+
"### INSTRUCTIONS:\n"
|
| 18 |
+
"1. **THE BLUF (Bottom Line Up Front):**\n"
|
| 19 |
+
" - Start immediately with a bold **Label**. Choose the best fit:\n"
|
| 20 |
+
" * *Binary:* **Verdict: Yes / No / Mixed.**\n"
|
| 21 |
+
" * *Definitional:* **Core Concept: [Phrase].**\n"
|
| 22 |
+
" * *Methodological:* **Standard Protocol: [Method].**\n"
|
| 23 |
+
" * *Open:* **Scientific Consensus: [Theme].**\n"
|
| 24 |
+
" - Follow with a high-level thesis sentence summarizing the answer.\n\n"
|
| 25 |
+
"2. **THE EVIDENCE (Structured & Rigorous):**\n"
|
| 26 |
+
" - **Evidence Synthesis:** Synthesize the high-authority agreement. What is the established truth? (Cite support).\n"
|
| 27 |
+
" - **Critical Nuances:** Discuss conflicts, sexual dimorphism, in vivo vs in vitro discrepancies, or major limitations.\n\n"
|
| 28 |
+
"3. **STYLE & CONSTRAINTS:**\n"
|
| 29 |
+
" - **Target Length:** ~250-350 words. Be dense but readable.\n"
|
| 30 |
+
" - **Bullet Style:** Start every bullet point with a **Bold Concept Label** followed by a dash. Mandatory.\n"
|
| 31 |
+
" - **Tone:** Professional. Use precise terminology.\n"
|
| 32 |
+
" - **Definitions:** Define ONLY non-standard acronyms on first use.\n\n"
|
| 33 |
+
"4. **PROTOCOL FOR INSUFFICIENT DATA:**\n"
|
| 34 |
+
" - If the provided chunks do not contain the answer, do not hallucinate.\n"
|
| 35 |
+
" - Output exactly: **Verdict: Insufficient Evidence.** followed by a brief explanation of what is missing.\n"
|
| 36 |
+
" - If you know of a major scientific consensus that is NOT in the sources, you may add a final section: \n"
|
| 37 |
+
" '### Missing Context'\n"
|
| 38 |
+
" 'Major theories such as [Concept] were not found in the retrieved papers.' (DO NOT CITE THIS).\n\n"
|
| 39 |
+
"5. **CITATION RULES (STRICT):**\n"
|
| 40 |
+
" - **Valid Source Range:** You have access to Sources 1 through {max_id}. **ANY CITATION > {max_id} IS A HALLUCINATION.**\n"
|
| 41 |
+
" - **Atomic Citations:** Every specific claim must be cited immediately [N].\n"
|
| 42 |
+
" - **Verification:** Do not cite a source unless the text explicitly supports the claim.\n"
|
| 43 |
+
" - **The 'Eyes-Only' Rule:** IGNORE YOUR TRAINING DATA. Use ONLY facts present in the text chunks.\n"
|
| 44 |
+
"### REQUIRED OUTPUT FORMAT:\n"
|
| 45 |
+
"---------------------\n"
|
| 46 |
+
f"{FEW_SHOT_EXAMPLE}\n"
|
| 47 |
+
"---------------------\n\n"
|
| 48 |
+
"### CONTEXT CHUNKS (Sources 1-{max_id}):\n"
|
| 49 |
+
"{context_str}\n\n"
|
| 50 |
+
"User Query: {query_str}\n"
|
| 51 |
+
"Answer (using ONLY Sources 1-{max_id}):"
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
QUERY_OPTIMIZATION_TEMPLATE = """You are a query optimization expert for scientific research using Semantic Scholar API.
|
| 55 |
+
|
| 56 |
+
Your task: Analyze the user's query and choose the best strategy: 'expansion' or 'decomposition'.
|
| 57 |
+
|
| 58 |
+
User input: "{query}"
|
| 59 |
+
|
| 60 |
+
**Strategy A: Expansion (Default)**
|
| 61 |
+
Use this for single-topic or straightforward queries.
|
| 62 |
+
|
| 63 |
+
**INTENT ANALYSIS (Crucial):**
|
| 64 |
+
Analyze the user's intent to optimize the 'broad' field:
|
| 65 |
+
1. **Overview/Consensus needed?** (e.g., "What is...", "How does...", "Summary of...") -> Set 'broad' to keywords + "review" OR "survey" OR "state of the art".
|
| 66 |
+
2. **Latest News needed?** (e.g., "Recent...", "Newest...", "Updates on...") -> Set 'broad' to keywords + "recent" OR "advances" OR "novel".
|
| 67 |
+
3. **Specific Details?** -> Keep 'broad' as general synonyms.
|
| 68 |
+
|
| 69 |
+
Output Format (JSON):
|
| 70 |
+
{{
|
| 71 |
+
"strategy": "expansion",
|
| 72 |
+
"final_rephrase": "Clear natural language question for semantic search",
|
| 73 |
+
"primary": "3-6 specific keywords",
|
| 74 |
+
"broad": "3-6 keywords optimized for INTENT (e.g., include 'review' or 'recent' if applicable)",
|
| 75 |
+
"alternative": "3-6 keywords focusing on limitations or debates"
|
| 76 |
+
}}
|
| 77 |
+
|
| 78 |
+
**Strategy B: Decomposition**
|
| 79 |
+
Use this for complex, multi-part, or comparative queries that require breaking down.
|
| 80 |
+
Generate a list of sub-queries to be executed independently.
|
| 81 |
+
|
| 82 |
+
Output Format (JSON):
|
| 83 |
+
{{
|
| 84 |
+
"strategy": "decomposition",
|
| 85 |
+
"final_rephrase": "The overarching question in clear natural language",
|
| 86 |
+
"sub_queries": [
|
| 87 |
+
"First sub-question keywords",
|
| 88 |
+
"Second sub-question keywords",
|
| 89 |
+
"..."
|
| 90 |
+
]
|
| 91 |
+
}}
|
| 92 |
+
|
| 93 |
+
**CRITICAL RULES:**
|
| 94 |
+
- 'final_rephrase' is MANDATORY for BOTH strategies.
|
| 95 |
+
- For 'primary', 'broad', 'alternative', and 'sub_queries': DO NOT use boolean operators (AND, OR). Keep them short (3-6 keywords).
|
| 96 |
+
- Return ONLY valid JSON.
|
| 97 |
+
"""
|
main.py
CHANGED
|
@@ -17,6 +17,7 @@ from datetime import datetime
|
|
| 17 |
|
| 18 |
from fastapi import FastAPI, HTTPException
|
| 19 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 20 |
from loguru import logger
|
| 21 |
from nicegui import ui
|
| 22 |
from pydantic import BaseModel, Field
|
|
@@ -77,66 +78,80 @@ async def lifespan(app: FastAPI):
|
|
| 77 |
Lifespan context manager that handles startup and shutdown logic.
|
| 78 |
Replaces @app.on_event("startup").
|
| 79 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
# --- STARTUP LOGIC ---
|
| 81 |
try:
|
| 82 |
-
|
|
|
|
| 83 |
from services.query_service import QueryService
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
| 87 |
embedding_model = None
|
| 88 |
try:
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
if hasattr(app.state, "embedding_model"):
|
| 93 |
-
embedding_model = app.state.embedding_model
|
| 94 |
-
embedding_loaded = True
|
| 95 |
logger.info("✅ Embedding model loaded successfully")
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
except
|
| 99 |
-
logger.warning(f"⚠️
|
| 100 |
-
|
| 101 |
-
logger.exception("⚠️ Embedding model failed to initialize")
|
| 102 |
-
|
| 103 |
-
# Initialize QueryService with embedding model
|
| 104 |
-
app.state.query_service = QueryService(embedding_model=embedding_model)
|
| 105 |
-
logger.info("🚀 Query service initialized")
|
| 106 |
-
|
| 107 |
-
# Initialize search queue and worker
|
| 108 |
-
app.state.search_queue = asyncio.Queue()
|
| 109 |
|
| 110 |
-
#
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
for i in range(1):
|
| 114 |
-
# Pass app instance to worker
|
| 115 |
-
task = asyncio.create_task(search_worker(app))
|
| 116 |
-
worker_tasks.append(task)
|
| 117 |
|
| 118 |
-
|
|
|
|
|
|
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
|
|
|
| 122 |
|
|
|
|
| 123 |
logger.info("✅ Application startup successful")
|
| 124 |
-
logger.info(f"Query optimization model: {
|
| 125 |
-
logger.info(f"Synthesis model: {
|
| 126 |
|
| 127 |
except Exception as e:
|
| 128 |
-
logger.
|
| 129 |
-
|
|
|
|
|
|
|
| 130 |
|
| 131 |
yield # Application runs here
|
| 132 |
|
| 133 |
# --- SHUTDOWN LOGIC ---
|
| 134 |
-
logger.info("Shutting down
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
-
# Wait for workers to finish cancelling
|
| 139 |
-
await asyncio.gather(*worker_tasks, return_exceptions=True)
|
| 140 |
logger.info("Shutdown complete")
|
| 141 |
|
| 142 |
|
|
@@ -147,6 +162,9 @@ app = FastAPI(
|
|
| 147 |
lifespan=lifespan, # Register the lifespan handler here
|
| 148 |
)
|
| 149 |
|
|
|
|
|
|
|
|
|
|
| 150 |
# Configure CORS
|
| 151 |
app.add_middleware(
|
| 152 |
CORSMiddleware,
|
|
|
|
| 17 |
|
| 18 |
from fastapi import FastAPI, HTTPException
|
| 19 |
from fastapi.middleware.cors import CORSMiddleware
|
| 20 |
+
from fastapi.staticfiles import StaticFiles
|
| 21 |
from loguru import logger
|
| 22 |
from nicegui import ui
|
| 23 |
from pydantic import BaseModel, Field
|
|
|
|
| 78 |
Lifespan context manager that handles startup and shutdown logic.
|
| 79 |
Replaces @app.on_event("startup").
|
| 80 |
"""
|
| 81 |
+
# Initialize state attributes to avoid AttributeErrors if startup fails
|
| 82 |
+
app.state.search_queue = asyncio.Queue()
|
| 83 |
+
app.state.query_service = None
|
| 84 |
+
app.state.embedding_model = None
|
| 85 |
+
app.state.workers = []
|
| 86 |
+
|
| 87 |
# --- STARTUP LOGIC ---
|
| 88 |
try:
|
| 89 |
+
from config.config import get_settings
|
| 90 |
+
from config.embedding_config import init_embedding
|
| 91 |
from services.query_service import QueryService
|
| 92 |
|
| 93 |
+
# 1. Load Settings
|
| 94 |
+
settings = get_settings()
|
| 95 |
+
settings.validate_keys()
|
| 96 |
+
|
| 97 |
+
# 2. Init Embedding Model (puts it on app.state.embedding_model)
|
| 98 |
embedding_model = None
|
| 99 |
try:
|
| 100 |
+
embedding_model = await init_embedding()
|
| 101 |
+
app.state.embedding_model = embedding_model
|
| 102 |
+
if embedding_model:
|
|
|
|
|
|
|
|
|
|
| 103 |
logger.info("✅ Embedding model loaded successfully")
|
| 104 |
+
else:
|
| 105 |
+
logger.warning("⚠️ Embedding model failed to load")
|
| 106 |
+
except Exception as e:
|
| 107 |
+
logger.warning(f"⚠️ Embedding model initialization failed: {e}")
|
| 108 |
+
# app.state.embedding_model is already None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
# 3. Create Singleton QueryService
|
| 111 |
+
# This will internally create Discovery, Ingestion, and RAG services
|
| 112 |
+
query_service = QueryService(settings=settings, embedding_model=embedding_model)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
# 4. Store in State
|
| 115 |
+
app.state.query_service = query_service
|
| 116 |
+
logger.info("🚀 Query service initialized")
|
| 117 |
|
| 118 |
+
# 5. Init Workers
|
| 119 |
+
# Start 3 workers for better concurrency
|
| 120 |
+
app.state.workers = [asyncio.create_task(search_worker(app)) for _ in range(3)]
|
| 121 |
|
| 122 |
+
logger.info("🚀 3 Search workers initialized (Parallel Lanes)")
|
| 123 |
logger.info("✅ Application startup successful")
|
| 124 |
+
logger.info(f"Query optimization model: {settings.QUERY_OPTIMIZATION_MODEL}")
|
| 125 |
+
logger.info(f"Synthesis model: {settings.SYNTHESIS_MODEL}")
|
| 126 |
|
| 127 |
except Exception as e:
|
| 128 |
+
logger.critical(f"Failed to initialize application: {e}")
|
| 129 |
+
# In production, you might want to exit here, but for dev we'll continue
|
| 130 |
+
# so the UI can at least show an error
|
| 131 |
+
# app.state.query_service is already None
|
| 132 |
|
| 133 |
yield # Application runs here
|
| 134 |
|
| 135 |
# --- SHUTDOWN LOGIC ---
|
| 136 |
+
logger.info("Shutting down Necthrall...")
|
| 137 |
+
|
| 138 |
+
# Cancel workers
|
| 139 |
+
if hasattr(app.state, "workers"):
|
| 140 |
+
logger.info("🛑 Shutting down: Cancelling workers...")
|
| 141 |
+
for worker in app.state.workers:
|
| 142 |
+
worker.cancel()
|
| 143 |
+
await asyncio.gather(*app.state.workers, return_exceptions=True)
|
| 144 |
+
|
| 145 |
+
# Close services
|
| 146 |
+
if hasattr(app.state, "query_service") and app.state.query_service:
|
| 147 |
+
await app.state.query_service.close()
|
| 148 |
+
|
| 149 |
+
logger.info("Shutdown complete")
|
| 150 |
+
|
| 151 |
+
logger.info("🛑 Shutting down: Closing services...")
|
| 152 |
+
if hasattr(app.state, "query_service"):
|
| 153 |
+
await app.state.query_service.close()
|
| 154 |
|
|
|
|
|
|
|
| 155 |
logger.info("Shutdown complete")
|
| 156 |
|
| 157 |
|
|
|
|
| 162 |
lifespan=lifespan, # Register the lifespan handler here
|
| 163 |
)
|
| 164 |
|
| 165 |
+
# Mount static files
|
| 166 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 167 |
+
|
| 168 |
# Configure CORS
|
| 169 |
app.add_middleware(
|
| 170 |
CORSMiddleware,
|
services/discovery_service.py
CHANGED
|
@@ -9,20 +9,21 @@ Responsibilities:
|
|
| 9 |
|
| 10 |
import asyncio
|
| 11 |
import time
|
| 12 |
-
from typing import Dict, List, Any, Optional
|
| 13 |
from dataclasses import dataclass
|
|
|
|
|
|
|
| 14 |
from loguru import logger
|
| 15 |
|
| 16 |
-
import config
|
| 17 |
-
from agents.query_optimization_agent import QueryOptimizationAgent
|
| 18 |
-
from agents.semantic_scholar_client import SemanticScholarClient
|
| 19 |
from agents.quality_gate import validate_quality
|
|
|
|
| 20 |
from agents.ranking_agent import RankingAgent
|
|
|
|
|
|
|
| 21 |
from services.exceptions import (
|
| 22 |
-
QueryOptimizationError,
|
| 23 |
-
SemanticScholarError,
|
| 24 |
QualityGateError,
|
|
|
|
| 25 |
RankingError,
|
|
|
|
| 26 |
)
|
| 27 |
|
| 28 |
|
|
@@ -40,30 +41,15 @@ class DiscoveryResult:
|
|
| 40 |
class DiscoveryService:
|
| 41 |
"""Service for paper discovery and ranking."""
|
| 42 |
|
| 43 |
-
def __init__(self):
|
| 44 |
-
self.
|
| 45 |
-
|
| 46 |
-
self.
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
"""Lazy initialization of query optimizer."""
|
| 50 |
-
if self._optimizer is None:
|
| 51 |
-
self._optimizer = QueryOptimizationAgent()
|
| 52 |
-
return self._optimizer
|
| 53 |
-
|
| 54 |
-
def _get_client(self) -> SemanticScholarClient:
|
| 55 |
-
"""Lazy initialization of Semantic Scholar client."""
|
| 56 |
-
if self._client is None:
|
| 57 |
-
self._client = SemanticScholarClient(
|
| 58 |
-
api_key=config.SEMANTIC_SCHOLAR_API_KEY
|
| 59 |
-
)
|
| 60 |
-
return self._client
|
| 61 |
|
| 62 |
-
def
|
| 63 |
-
|
| 64 |
-
if self._ranker is None:
|
| 65 |
-
self._ranker = RankingAgent()
|
| 66 |
-
return self._ranker
|
| 67 |
|
| 68 |
async def _execute_search_and_quality_gate(
|
| 69 |
self,
|
|
@@ -93,9 +79,7 @@ class DiscoveryService:
|
|
| 93 |
)
|
| 94 |
stage_start = time.perf_counter()
|
| 95 |
try:
|
| 96 |
-
papers = await self.
|
| 97 |
-
queries, limit_per_query=100
|
| 98 |
-
)
|
| 99 |
search_key = f"semantic_scholar_search{attempt_label}"
|
| 100 |
timing_breakdown[search_key] = time.perf_counter() - stage_start
|
| 101 |
logger.info(
|
|
@@ -125,7 +109,9 @@ class DiscoveryService:
|
|
| 125 |
stage_start = time.perf_counter()
|
| 126 |
try:
|
| 127 |
query_embedding = None
|
| 128 |
-
quality_result =
|
|
|
|
|
|
|
| 129 |
gate_key = f"quality_gate{attempt_label}"
|
| 130 |
timing_breakdown[gate_key] = time.perf_counter() - stage_start
|
| 131 |
logger.info(
|
|
@@ -169,9 +155,7 @@ class DiscoveryService:
|
|
| 169 |
timing_breakdown["query_optimization"] = 0.0
|
| 170 |
else:
|
| 171 |
try:
|
| 172 |
-
optimized_queries = await self.
|
| 173 |
-
query
|
| 174 |
-
)
|
| 175 |
logger.info(
|
| 176 |
"Optimized queries returned by optimizer: {}", optimized_queries
|
| 177 |
)
|
|
@@ -249,7 +233,7 @@ class DiscoveryService:
|
|
| 249 |
stage_start = time.perf_counter()
|
| 250 |
try:
|
| 251 |
finalists = await asyncio.to_thread(
|
| 252 |
-
self.
|
| 253 |
papers,
|
| 254 |
optimized_queries["final_rephrase"],
|
| 255 |
50, # top_k for Base+Bonus strategy
|
|
|
|
| 9 |
|
| 10 |
import asyncio
|
| 11 |
import time
|
|
|
|
| 12 |
from dataclasses import dataclass
|
| 13 |
+
from typing import Any, Dict, List, Optional
|
| 14 |
+
|
| 15 |
from loguru import logger
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
from agents.quality_gate import validate_quality
|
| 18 |
+
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,
|
| 25 |
RankingError,
|
| 26 |
+
SemanticScholarError,
|
| 27 |
)
|
| 28 |
|
| 29 |
|
|
|
|
| 41 |
class DiscoveryService:
|
| 42 |
"""Service for paper discovery and ranking."""
|
| 43 |
|
| 44 |
+
def __init__(self, settings: Settings):
|
| 45 |
+
self.settings = settings
|
| 46 |
+
# Initialize components immediately
|
| 47 |
+
self.optimizer = QueryOptimizationAgent()
|
| 48 |
+
self.client = SemanticScholarClient(api_key=settings.SEMANTIC_SCHOLAR_API_KEY)
|
| 49 |
+
self.ranker = RankingAgent()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
async def close(self):
|
| 52 |
+
await self.client.close()
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
async def _execute_search_and_quality_gate(
|
| 55 |
self,
|
|
|
|
| 79 |
)
|
| 80 |
stage_start = time.perf_counter()
|
| 81 |
try:
|
| 82 |
+
papers = await self.client.multi_query_search(queries, limit_per_query=100)
|
|
|
|
|
|
|
| 83 |
search_key = f"semantic_scholar_search{attempt_label}"
|
| 84 |
timing_breakdown[search_key] = time.perf_counter() - stage_start
|
| 85 |
logger.info(
|
|
|
|
| 109 |
stage_start = time.perf_counter()
|
| 110 |
try:
|
| 111 |
query_embedding = None
|
| 112 |
+
quality_result = await asyncio.to_thread(
|
| 113 |
+
validate_quality, papers, query_embedding
|
| 114 |
+
)
|
| 115 |
gate_key = f"quality_gate{attempt_label}"
|
| 116 |
timing_breakdown[gate_key] = time.perf_counter() - stage_start
|
| 117 |
logger.info(
|
|
|
|
| 155 |
timing_breakdown["query_optimization"] = 0.0
|
| 156 |
else:
|
| 157 |
try:
|
| 158 |
+
optimized_queries = await self.optimizer.generate_dual_queries(query)
|
|
|
|
|
|
|
| 159 |
logger.info(
|
| 160 |
"Optimized queries returned by optimizer: {}", optimized_queries
|
| 161 |
)
|
|
|
|
| 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
|
services/ingestion_service.py
CHANGED
|
@@ -7,11 +7,15 @@ Responsibilities:
|
|
| 7 |
|
| 8 |
import asyncio
|
| 9 |
import time
|
| 10 |
-
from typing import Dict, List, Any, Optional, TYPE_CHECKING
|
| 11 |
from dataclasses import dataclass
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
from loguru import logger
|
| 13 |
|
| 14 |
from services.exceptions import AcquisitionError, ProcessingError
|
|
|
|
| 15 |
|
| 16 |
if TYPE_CHECKING:
|
| 17 |
from agents.acquisition_agent import AcquisitionAgent
|
|
@@ -110,6 +114,9 @@ class IngestionService:
|
|
| 110 |
timing_breakdown["pdf_acquisition"],
|
| 111 |
len(passages),
|
| 112 |
)
|
|
|
|
|
|
|
|
|
|
| 113 |
except Exception as e:
|
| 114 |
timing_breakdown["pdf_acquisition"] = time.perf_counter() - stage_start
|
| 115 |
logger.warning(
|
|
@@ -158,3 +165,46 @@ class IngestionService:
|
|
| 158 |
chunks=chunks,
|
| 159 |
timing_breakdown=timing_breakdown,
|
| 160 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
import asyncio
|
| 9 |
import time
|
|
|
|
| 10 |
from dataclasses import dataclass
|
| 11 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from llama_index.core.schema import TextNode
|
| 15 |
from loguru import logger
|
| 16 |
|
| 17 |
from services.exceptions import AcquisitionError, ProcessingError
|
| 18 |
+
from utils.embedding_utils import batched_embed
|
| 19 |
|
| 20 |
if TYPE_CHECKING:
|
| 21 |
from agents.acquisition_agent import AcquisitionAgent
|
|
|
|
| 114 |
timing_breakdown["pdf_acquisition"],
|
| 115 |
len(passages),
|
| 116 |
)
|
| 117 |
+
except asyncio.CancelledError:
|
| 118 |
+
logger.info("🛑 PDF Acquisition cancelled by user")
|
| 119 |
+
raise
|
| 120 |
except Exception as e:
|
| 121 |
timing_breakdown["pdf_acquisition"] = time.perf_counter() - stage_start
|
| 122 |
logger.warning(
|
|
|
|
| 165 |
chunks=chunks,
|
| 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.
|
| 177 |
+
"""
|
| 178 |
+
logger.info("🚀 Fast Mode active: Skipping PDF download, using abstracts.")
|
| 179 |
+
chunks = []
|
| 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)
|
| 196 |
+
|
| 197 |
+
# Generate embeddings
|
| 198 |
+
if chunks:
|
| 199 |
+
texts = [node.get_content() for node in chunks]
|
| 200 |
+
embeddings = await asyncio.to_thread(
|
| 201 |
+
batched_embed, texts, self.embedding_model
|
| 202 |
+
)
|
| 203 |
+
for node, embedding in zip(chunks, embeddings):
|
| 204 |
+
node.embedding = (
|
| 205 |
+
embedding.tolist()
|
| 206 |
+
if isinstance(embedding, np.ndarray)
|
| 207 |
+
else embedding
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
return chunks
|
services/query_service.py
CHANGED
|
@@ -20,30 +20,29 @@ from __future__ import annotations
|
|
| 20 |
|
| 21 |
import asyncio
|
| 22 |
import time
|
| 23 |
-
from typing import Dict, List, Any, Optional, TYPE_CHECKING, Callable
|
| 24 |
from dataclasses import dataclass, field
|
|
|
|
|
|
|
| 25 |
from loguru import logger
|
| 26 |
-
from llama_index.core.schema import TextNode
|
| 27 |
-
import numpy as np
|
| 28 |
|
| 29 |
-
from utils.embedding_utils import batched_embed
|
| 30 |
from agents.query_optimization_agent import QueryOptimizationAgent
|
|
|
|
| 31 |
from services.discovery_service import DiscoveryService
|
| 32 |
-
from services.ingestion_service import IngestionService
|
| 33 |
-
from services.rag_service import RAGService
|
| 34 |
from services.exceptions import (
|
| 35 |
-
QueryServiceError,
|
| 36 |
-
QueryOptimizationError,
|
| 37 |
-
SemanticScholarError,
|
| 38 |
-
QualityGateError,
|
| 39 |
-
RankingError,
|
| 40 |
AcquisitionError,
|
| 41 |
ProcessingError,
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
RerankingError,
|
|
|
|
|
|
|
| 44 |
SynthesisError,
|
| 45 |
VerificationError,
|
| 46 |
)
|
|
|
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
@dataclass
|
|
@@ -86,19 +85,24 @@ class QueryService:
|
|
| 86 |
Provides comprehensive error handling and performance monitoring.
|
| 87 |
"""
|
| 88 |
|
| 89 |
-
def __init__(self,
|
| 90 |
"""Initialize the query service.
|
| 91 |
|
| 92 |
Args:
|
|
|
|
| 93 |
embedding_model: Pre-loaded embedding model for query/passage embedding.
|
| 94 |
"""
|
|
|
|
| 95 |
self.embedding_model = embedding_model
|
| 96 |
|
| 97 |
-
# Initialize
|
| 98 |
self.optimization_agent = QueryOptimizationAgent()
|
| 99 |
-
self.discovery_service = DiscoveryService()
|
| 100 |
-
self.ingestion_service = IngestionService(embedding_model
|
| 101 |
-
self.rag_service = RAGService(embedding_model
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
async def process_query(
|
| 104 |
self,
|
|
@@ -210,38 +214,10 @@ class QueryService:
|
|
| 210 |
timing_breakdown.update(ingestion_result.timing_breakdown)
|
| 211 |
chunks = ingestion_result.chunks
|
| 212 |
else:
|
| 213 |
-
|
| 214 |
-
|
| 215 |
)
|
| 216 |
|
| 217 |
-
# Create nodes from abstracts
|
| 218 |
-
for paper in discovery_result.finalists:
|
| 219 |
-
abstract = paper.get("abstract")
|
| 220 |
-
if not abstract:
|
| 221 |
-
continue
|
| 222 |
-
|
| 223 |
-
node = TextNode(text=abstract)
|
| 224 |
-
node.metadata = {
|
| 225 |
-
"paper_id": paper.get("paperId"),
|
| 226 |
-
"paper_title": paper.get("title"),
|
| 227 |
-
"url": paper.get("url")
|
| 228 |
-
or paper.get("openAccessPdf", {}).get("url"),
|
| 229 |
-
"year": paper.get("year"),
|
| 230 |
-
"section": "Abstract",
|
| 231 |
-
}
|
| 232 |
-
chunks.append(node)
|
| 233 |
-
|
| 234 |
-
# Generate embeddings
|
| 235 |
-
if chunks:
|
| 236 |
-
texts = [node.get_content() for node in chunks]
|
| 237 |
-
embeddings = batched_embed(texts, self.embedding_model)
|
| 238 |
-
for node, embedding in zip(chunks, embeddings):
|
| 239 |
-
node.embedding = (
|
| 240 |
-
embedding.tolist()
|
| 241 |
-
if isinstance(embedding, np.ndarray)
|
| 242 |
-
else embedding
|
| 243 |
-
)
|
| 244 |
-
|
| 245 |
# Check if we have chunks to process
|
| 246 |
if not chunks:
|
| 247 |
logger.warning("⚠️ No chunks generated from ingestion (or fast mode)")
|
|
@@ -293,3 +269,4 @@ class QueryService:
|
|
| 293 |
result.error_message = f"Unexpected error: {str(e)}"
|
| 294 |
result.error_stage = "unknown"
|
| 295 |
return result
|
|
|
|
|
|
| 20 |
|
| 21 |
import asyncio
|
| 22 |
import time
|
|
|
|
| 23 |
from dataclasses import dataclass, field
|
| 24 |
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional
|
| 25 |
+
|
| 26 |
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,
|
| 33 |
ProcessingError,
|
| 34 |
+
QualityGateError,
|
| 35 |
+
QueryOptimizationError,
|
| 36 |
+
QueryServiceError,
|
| 37 |
+
RankingError,
|
| 38 |
RerankingError,
|
| 39 |
+
RetrievalError,
|
| 40 |
+
SemanticScholarError,
|
| 41 |
SynthesisError,
|
| 42 |
VerificationError,
|
| 43 |
)
|
| 44 |
+
from services.ingestion_service import IngestionService
|
| 45 |
+
from services.rag_service import RAGService
|
| 46 |
|
| 47 |
|
| 48 |
@dataclass
|
|
|
|
| 85 |
Provides comprehensive error handling and performance monitoring.
|
| 86 |
"""
|
| 87 |
|
| 88 |
+
def __init__(self, settings: Settings, embedding_model: Any):
|
| 89 |
"""Initialize the query service.
|
| 90 |
|
| 91 |
Args:
|
| 92 |
+
settings: Application settings.
|
| 93 |
embedding_model: Pre-loaded embedding model for query/passage embedding.
|
| 94 |
"""
|
| 95 |
+
self.settings = settings
|
| 96 |
self.embedding_model = embedding_model
|
| 97 |
|
| 98 |
+
# Initialize agents/services immediately
|
| 99 |
self.optimization_agent = QueryOptimizationAgent()
|
| 100 |
+
self.discovery_service = DiscoveryService(settings)
|
| 101 |
+
self.ingestion_service = IngestionService(embedding_model)
|
| 102 |
+
self.rag_service = RAGService(embedding_model, settings)
|
| 103 |
+
|
| 104 |
+
async def close(self):
|
| 105 |
+
await self.discovery_service.close()
|
| 106 |
|
| 107 |
async def process_query(
|
| 108 |
self,
|
|
|
|
| 214 |
timing_breakdown.update(ingestion_result.timing_breakdown)
|
| 215 |
chunks = ingestion_result.chunks
|
| 216 |
else:
|
| 217 |
+
chunks = await self.ingestion_service.ingest_abstracts(
|
| 218 |
+
discovery_result.finalists
|
| 219 |
)
|
| 220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
# Check if we have chunks to process
|
| 222 |
if not chunks:
|
| 223 |
logger.warning("⚠️ No chunks generated from ingestion (or fast mode)")
|
|
|
|
| 269 |
result.error_message = f"Unexpected error: {str(e)}"
|
| 270 |
result.error_stage = "unknown"
|
| 271 |
return result
|
| 272 |
+
return result
|
services/rag_service.py
CHANGED
|
@@ -9,23 +9,24 @@ Responsibilities:
|
|
| 9 |
|
| 10 |
import asyncio
|
| 11 |
import time
|
| 12 |
-
from typing import Dict, List, Any, Optional, TYPE_CHECKING
|
| 13 |
-
from dataclasses import dataclass, field
|
| 14 |
from collections import defaultdict
|
|
|
|
|
|
|
|
|
|
| 15 |
from loguru import logger
|
| 16 |
|
|
|
|
| 17 |
from services.exceptions import (
|
| 18 |
-
RetrievalError,
|
| 19 |
RerankingError,
|
|
|
|
| 20 |
SynthesisError,
|
| 21 |
VerificationError,
|
| 22 |
)
|
| 23 |
-
from config.config import RAG_RETRIEVAL_TOP_K, RAG_RERANK_TOP_K
|
| 24 |
|
| 25 |
if TYPE_CHECKING:
|
|
|
|
| 26 |
from retrieval.llamaindex_retriever import LlamaIndexRetriever
|
| 27 |
from retrieval.reranker import CrossEncoderReranker
|
| 28 |
-
from agents.synthesis_agent import SynthesisAgent
|
| 29 |
from utils.citation_verifier import CitationVerifier
|
| 30 |
|
| 31 |
|
|
@@ -42,62 +43,40 @@ class RAGResult:
|
|
| 42 |
class RAGService:
|
| 43 |
"""Service for retrieval, reranking, synthesis, and verification."""
|
| 44 |
|
| 45 |
-
def __init__(self, embedding_model: Any
|
| 46 |
"""Initialize the RAG service.
|
| 47 |
|
| 48 |
Args:
|
| 49 |
embedding_model: Pre-loaded embedding model for retrieval.
|
|
|
|
| 50 |
"""
|
| 51 |
self.embedding_model = embedding_model
|
| 52 |
-
self.
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
# Pre-load CrossEncoderReranker during initialization to avoid ~12s latency
|
| 57 |
-
# on first request. Import here to maintain safe DLL import order on Windows.
|
| 58 |
try:
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
self._reranker = CrossEncoderReranker()
|
| 62 |
except (ImportError, OSError) as e:
|
| 63 |
logger.warning(
|
| 64 |
f"Could not import CrossEncoderReranker: {e}. Reranking will fail if attempted."
|
| 65 |
)
|
| 66 |
-
self.
|
| 67 |
-
|
| 68 |
-
def _get_retriever(self) -> Optional["LlamaIndexRetriever"]:
|
| 69 |
-
"""Lazy initialization of hybrid retriever.
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
if self._retriever is None and self.embedding_model is not None:
|
| 74 |
-
from retrieval.llamaindex_retriever import LlamaIndexRetriever
|
| 75 |
-
|
| 76 |
-
self._retriever = LlamaIndexRetriever(
|
| 77 |
-
embedding_model=self.embedding_model,
|
| 78 |
-
top_k=RAG_RETRIEVAL_TOP_K, # Before reranking
|
| 79 |
-
)
|
| 80 |
-
return self._retriever
|
| 81 |
|
| 82 |
-
|
| 83 |
-
"""Return the pre-loaded cross-encoder reranker."""
|
| 84 |
-
return self._reranker
|
| 85 |
-
|
| 86 |
-
def _get_synthesis_agent(self) -> "SynthesisAgent":
|
| 87 |
-
"""Lazy initialization of synthesis agent."""
|
| 88 |
-
if self._synthesis_agent is None:
|
| 89 |
-
from agents.synthesis_agent import SynthesisAgent
|
| 90 |
-
|
| 91 |
-
self._synthesis_agent = SynthesisAgent()
|
| 92 |
-
return self._synthesis_agent
|
| 93 |
-
|
| 94 |
-
def _get_verifier(self) -> "CitationVerifier":
|
| 95 |
-
"""Lazy initialization of citation verifier."""
|
| 96 |
-
if self._verifier is None:
|
| 97 |
-
from utils.citation_verifier import CitationVerifier
|
| 98 |
-
|
| 99 |
-
self._verifier = CitationVerifier()
|
| 100 |
-
return self._verifier
|
| 101 |
|
| 102 |
def _select_diverse_top_k(
|
| 103 |
self, passages: List[Any], k: int, max_per_paper: int = 3
|
|
@@ -192,26 +171,22 @@ class RAGService:
|
|
| 192 |
)
|
| 193 |
stage_start = time.perf_counter()
|
| 194 |
try:
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
retriever.retrieve, query, chunks
|
| 200 |
-
)
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
else:
|
| 214 |
-
raise RetrievalError("Retriever could not be initialized")
|
| 215 |
except Exception as e:
|
| 216 |
logger.exception("Retrieval failed")
|
| 217 |
raise RetrievalError(f"Failed to retrieve passages: {str(e)}") from e
|
|
@@ -232,20 +207,19 @@ class RAGService:
|
|
| 232 |
)
|
| 233 |
stage_start = time.perf_counter()
|
| 234 |
try:
|
| 235 |
-
|
| 236 |
-
if reranker:
|
| 237 |
# Rerank a larger pool (all retrieved) to allow for diversity filtering
|
| 238 |
reranked_passages = await asyncio.to_thread(
|
| 239 |
-
reranker.rerank, query, passages, top_k=len(passages)
|
| 240 |
)
|
| 241 |
|
| 242 |
# Apply diversity filter
|
| 243 |
logger.info(
|
| 244 |
"Applying diversity filter: selecting top {} with max 3 per paper",
|
| 245 |
-
RAG_RERANK_TOP_K,
|
| 246 |
)
|
| 247 |
passages = self._select_diverse_top_k(
|
| 248 |
-
reranked_passages, k=RAG_RERANK_TOP_K
|
| 249 |
)
|
| 250 |
|
| 251 |
timing_breakdown["reranking"] = time.perf_counter() - stage_start
|
|
@@ -256,9 +230,9 @@ class RAGService:
|
|
| 256 |
)
|
| 257 |
else:
|
| 258 |
logger.warning(
|
| 259 |
-
f"⚠️ Reranker not available - skipping reranking and taking top {RAG_RERANK_TOP_K}"
|
| 260 |
)
|
| 261 |
-
passages = passages[:RAG_RERANK_TOP_K]
|
| 262 |
timing_breakdown["reranking"] = 0.0
|
| 263 |
except Exception as e:
|
| 264 |
logger.exception("Reranking failed")
|
|
@@ -268,8 +242,7 @@ class RAGService:
|
|
| 268 |
logger.info("🤖 Stage 9: Synthesis - generating answer")
|
| 269 |
stage_start = time.perf_counter()
|
| 270 |
try:
|
| 271 |
-
|
| 272 |
-
answer = await synthesis_agent.synthesize(query, passages)
|
| 273 |
timing_breakdown["synthesis"] = time.perf_counter() - stage_start
|
| 274 |
logger.info(
|
| 275 |
"✅ Synthesis completed in {:.3f}s", timing_breakdown["synthesis"]
|
|
@@ -286,8 +259,7 @@ class RAGService:
|
|
| 286 |
logger.info("✅ Stage 10: Verification - checking citations")
|
| 287 |
stage_start = time.perf_counter()
|
| 288 |
try:
|
| 289 |
-
|
| 290 |
-
verification_result = verifier.verify(answer, passages)
|
| 291 |
timing_breakdown["verification"] = time.perf_counter() - stage_start
|
| 292 |
logger.info(
|
| 293 |
"✅ Verification completed in {:.3f}s - score: {}",
|
|
|
|
| 9 |
|
| 10 |
import asyncio
|
| 11 |
import time
|
|
|
|
|
|
|
| 12 |
from collections import defaultdict
|
| 13 |
+
from dataclasses import dataclass, field
|
| 14 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional
|
| 15 |
+
|
| 16 |
from loguru import logger
|
| 17 |
|
| 18 |
+
from config.config import Settings
|
| 19 |
from services.exceptions import (
|
|
|
|
| 20 |
RerankingError,
|
| 21 |
+
RetrievalError,
|
| 22 |
SynthesisError,
|
| 23 |
VerificationError,
|
| 24 |
)
|
|
|
|
| 25 |
|
| 26 |
if TYPE_CHECKING:
|
| 27 |
+
from agents.synthesis_agent import SynthesisAgent
|
| 28 |
from retrieval.llamaindex_retriever import LlamaIndexRetriever
|
| 29 |
from retrieval.reranker import CrossEncoderReranker
|
|
|
|
| 30 |
from utils.citation_verifier import CitationVerifier
|
| 31 |
|
| 32 |
|
|
|
|
| 43 |
class RAGService:
|
| 44 |
"""Service for retrieval, reranking, synthesis, and verification."""
|
| 45 |
|
| 46 |
+
def __init__(self, embedding_model: Any, settings: Settings):
|
| 47 |
"""Initialize the RAG service.
|
| 48 |
|
| 49 |
Args:
|
| 50 |
embedding_model: Pre-loaded embedding model for retrieval.
|
| 51 |
+
settings: Application settings.
|
| 52 |
"""
|
| 53 |
self.embedding_model = embedding_model
|
| 54 |
+
self.settings = settings
|
| 55 |
+
|
| 56 |
+
# Initialize components immediately
|
| 57 |
+
# Note: We keep imports inside __init__ to avoid circular deps and maintain safe DLL import order
|
| 58 |
+
from agents.synthesis_agent import SynthesisAgent
|
| 59 |
+
from retrieval.llamaindex_retriever import LlamaIndexRetriever
|
| 60 |
+
from retrieval.reranker import CrossEncoderReranker
|
| 61 |
+
from utils.citation_verifier import CitationVerifier
|
| 62 |
+
|
| 63 |
+
self.retriever = LlamaIndexRetriever(
|
| 64 |
+
embedding_model=embedding_model,
|
| 65 |
+
top_k=settings.RAG_RETRIEVAL_TOP_K,
|
| 66 |
+
)
|
| 67 |
|
|
|
|
|
|
|
| 68 |
try:
|
| 69 |
+
self.reranker = CrossEncoderReranker()
|
|
|
|
|
|
|
| 70 |
except (ImportError, OSError) as e:
|
| 71 |
logger.warning(
|
| 72 |
f"Could not import CrossEncoderReranker: {e}. Reranking will fail if attempted."
|
| 73 |
)
|
| 74 |
+
self.reranker = None
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
self.synthesis_agent = SynthesisAgent(settings=settings)
|
| 77 |
+
self.verifier = CitationVerifier()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
self.verifier = CitationVerifier()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
def _select_diverse_top_k(
|
| 82 |
self, passages: List[Any], k: int, max_per_paper: int = 3
|
|
|
|
| 171 |
)
|
| 172 |
stage_start = time.perf_counter()
|
| 173 |
try:
|
| 174 |
+
# Retrieve
|
| 175 |
+
retrieved_nodes = await asyncio.to_thread(
|
| 176 |
+
self.retriever.retrieve, query, chunks
|
| 177 |
+
)
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
# Convert nodes to simple dicts/objects if needed,
|
| 180 |
+
# but the original code seems to use the nodes directly or convert them.
|
| 181 |
+
# Let's assume retrieved_nodes are compatible with what reranker expects.
|
| 182 |
+
passages = retrieved_nodes
|
| 183 |
|
| 184 |
+
timing_breakdown["retrieval"] = time.perf_counter() - stage_start
|
| 185 |
+
logger.info(
|
| 186 |
+
"✅ Retrieval completed in {:.3f}s - retrieved {} candidates",
|
| 187 |
+
timing_breakdown["retrieval"],
|
| 188 |
+
len(passages),
|
| 189 |
+
)
|
|
|
|
|
|
|
| 190 |
except Exception as e:
|
| 191 |
logger.exception("Retrieval failed")
|
| 192 |
raise RetrievalError(f"Failed to retrieve passages: {str(e)}") from e
|
|
|
|
| 207 |
)
|
| 208 |
stage_start = time.perf_counter()
|
| 209 |
try:
|
| 210 |
+
if self.reranker:
|
|
|
|
| 211 |
# Rerank a larger pool (all retrieved) to allow for diversity filtering
|
| 212 |
reranked_passages = await asyncio.to_thread(
|
| 213 |
+
self.reranker.rerank, query, passages, top_k=len(passages)
|
| 214 |
)
|
| 215 |
|
| 216 |
# Apply diversity filter
|
| 217 |
logger.info(
|
| 218 |
"Applying diversity filter: selecting top {} with max 3 per paper",
|
| 219 |
+
self.settings.RAG_RERANK_TOP_K,
|
| 220 |
)
|
| 221 |
passages = self._select_diverse_top_k(
|
| 222 |
+
reranked_passages, k=self.settings.RAG_RERANK_TOP_K
|
| 223 |
)
|
| 224 |
|
| 225 |
timing_breakdown["reranking"] = time.perf_counter() - stage_start
|
|
|
|
| 230 |
)
|
| 231 |
else:
|
| 232 |
logger.warning(
|
| 233 |
+
f"⚠️ Reranker not available - skipping reranking and taking top {self.settings.RAG_RERANK_TOP_K}"
|
| 234 |
)
|
| 235 |
+
passages = passages[: self.settings.RAG_RERANK_TOP_K]
|
| 236 |
timing_breakdown["reranking"] = 0.0
|
| 237 |
except Exception as e:
|
| 238 |
logger.exception("Reranking failed")
|
|
|
|
| 242 |
logger.info("🤖 Stage 9: Synthesis - generating answer")
|
| 243 |
stage_start = time.perf_counter()
|
| 244 |
try:
|
| 245 |
+
answer = await self.synthesis_agent.synthesize(query, passages)
|
|
|
|
| 246 |
timing_breakdown["synthesis"] = time.perf_counter() - stage_start
|
| 247 |
logger.info(
|
| 248 |
"✅ Synthesis completed in {:.3f}s", timing_breakdown["synthesis"]
|
|
|
|
| 259 |
logger.info("✅ Stage 10: Verification - checking citations")
|
| 260 |
stage_start = time.perf_counter()
|
| 261 |
try:
|
| 262 |
+
verification_result = self.verifier.verify(answer, passages)
|
|
|
|
| 263 |
timing_breakdown["verification"] = time.perf_counter() - stage_start
|
| 264 |
logger.info(
|
| 265 |
"✅ Verification completed in {:.3f}s - score: {}",
|
ui/styles.py → static/css/styles.css
RENAMED
|
@@ -1,6 +1,3 @@
|
|
| 1 |
-
"""Custom CSS styles for the Necthrall UI."""
|
| 2 |
-
|
| 3 |
-
CUSTOM_CSS = """
|
| 4 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
|
| 5 |
|
| 6 |
:root {
|
|
@@ -120,7 +117,8 @@ body {
|
|
| 120 |
}
|
| 121 |
|
| 122 |
/* Markdown styling within answer */
|
| 123 |
-
.answer-text ul,
|
|
|
|
| 124 |
margin: 0.5rem 0;
|
| 125 |
padding-left: 1.5rem;
|
| 126 |
}
|
|
@@ -325,34 +323,34 @@ a.source-link-btn:visited {
|
|
| 325 |
.search-container {
|
| 326 |
padding: 0 16px;
|
| 327 |
}
|
| 328 |
-
|
| 329 |
.brand-title {
|
| 330 |
font-size: 1.25rem;
|
| 331 |
}
|
| 332 |
-
|
| 333 |
.answer-section {
|
| 334 |
padding: 16px;
|
| 335 |
}
|
| 336 |
-
|
| 337 |
.answer-section p,
|
| 338 |
.answer-section li {
|
| 339 |
word-wrap: break-word;
|
| 340 |
overflow-wrap: break-word;
|
| 341 |
word-break: break-word;
|
| 342 |
}
|
| 343 |
-
|
| 344 |
.source-card {
|
| 345 |
padding: 12px;
|
| 346 |
}
|
| 347 |
-
|
| 348 |
.source-title {
|
| 349 |
font-size: 0.9rem;
|
| 350 |
}
|
| 351 |
-
|
| 352 |
.source-snippet {
|
| 353 |
font-size: 0.8rem;
|
| 354 |
}
|
| 355 |
-
|
| 356 |
.header-container {
|
| 357 |
padding: 10px 16px;
|
| 358 |
}
|
|
@@ -363,12 +361,12 @@ a.source-link-btn:visited {
|
|
| 363 |
padding: 8px 12px !important;
|
| 364 |
font-size: 0.875rem !important;
|
| 365 |
}
|
| 366 |
-
|
| 367 |
.example-queries {
|
| 368 |
flex-direction: column;
|
| 369 |
align-items: stretch;
|
| 370 |
}
|
| 371 |
-
|
| 372 |
.example-btn {
|
| 373 |
justify-content: center;
|
| 374 |
}
|
|
@@ -403,5 +401,4 @@ a.source-link-btn:visited {
|
|
| 403 |
border-color: var(--primary) !important;
|
| 404 |
color: var(--primary) !important;
|
| 405 |
background: rgba(249, 115, 22, 0.05) !important;
|
| 406 |
-
}
|
| 407 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
|
| 2 |
|
| 3 |
:root {
|
|
|
|
| 117 |
}
|
| 118 |
|
| 119 |
/* Markdown styling within answer */
|
| 120 |
+
.answer-text ul,
|
| 121 |
+
.answer-text ol {
|
| 122 |
margin: 0.5rem 0;
|
| 123 |
padding-left: 1.5rem;
|
| 124 |
}
|
|
|
|
| 323 |
.search-container {
|
| 324 |
padding: 0 16px;
|
| 325 |
}
|
| 326 |
+
|
| 327 |
.brand-title {
|
| 328 |
font-size: 1.25rem;
|
| 329 |
}
|
| 330 |
+
|
| 331 |
.answer-section {
|
| 332 |
padding: 16px;
|
| 333 |
}
|
| 334 |
+
|
| 335 |
.answer-section p,
|
| 336 |
.answer-section li {
|
| 337 |
word-wrap: break-word;
|
| 338 |
overflow-wrap: break-word;
|
| 339 |
word-break: break-word;
|
| 340 |
}
|
| 341 |
+
|
| 342 |
.source-card {
|
| 343 |
padding: 12px;
|
| 344 |
}
|
| 345 |
+
|
| 346 |
.source-title {
|
| 347 |
font-size: 0.9rem;
|
| 348 |
}
|
| 349 |
+
|
| 350 |
.source-snippet {
|
| 351 |
font-size: 0.8rem;
|
| 352 |
}
|
| 353 |
+
|
| 354 |
.header-container {
|
| 355 |
padding: 10px 16px;
|
| 356 |
}
|
|
|
|
| 361 |
padding: 8px 12px !important;
|
| 362 |
font-size: 0.875rem !important;
|
| 363 |
}
|
| 364 |
+
|
| 365 |
.example-queries {
|
| 366 |
flex-direction: column;
|
| 367 |
align-items: stretch;
|
| 368 |
}
|
| 369 |
+
|
| 370 |
.example-btn {
|
| 371 |
justify-content: center;
|
| 372 |
}
|
|
|
|
| 401 |
border-color: var(--primary) !important;
|
| 402 |
color: var(--primary) !important;
|
| 403 |
background: rgba(249, 115, 22, 0.05) !important;
|
| 404 |
+
}
|
|
|
tests/eval_config.py
CHANGED
|
@@ -1,18 +1,21 @@
|
|
| 1 |
import logging
|
| 2 |
-
from typing import
|
| 3 |
-
|
| 4 |
import litellm
|
| 5 |
-
from
|
|
|
|
|
|
|
| 6 |
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
|
| 9 |
|
| 10 |
class LLMJudge(DeepEvalBaseLLM):
|
| 11 |
def __init__(self):
|
| 12 |
-
|
| 13 |
-
self.
|
| 14 |
-
self.
|
| 15 |
-
self.
|
|
|
|
| 16 |
|
| 17 |
def load_model(self):
|
| 18 |
return self.model_name
|
|
@@ -79,3 +82,6 @@ class LLMJudge(DeepEvalBaseLLM):
|
|
| 79 |
|
| 80 |
def get_model_name(self):
|
| 81 |
return self.model_name
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import logging
|
| 2 |
+
from typing import List, Optional
|
| 3 |
+
|
| 4 |
import litellm
|
| 5 |
+
from deepeval.models.base_model import DeepEvalBaseLLM
|
| 6 |
+
|
| 7 |
+
from config.config import get_settings
|
| 8 |
|
| 9 |
logger = logging.getLogger(__name__)
|
| 10 |
|
| 11 |
|
| 12 |
class LLMJudge(DeepEvalBaseLLM):
|
| 13 |
def __init__(self):
|
| 14 |
+
settings = get_settings()
|
| 15 |
+
self.model_name = settings.SYNTHESIS_MODEL
|
| 16 |
+
self.fallback_model_name = settings.SYNTHESIS_FALLBACK
|
| 17 |
+
self.primary_api_key = settings.PRIMARY_LLM_API_KEY
|
| 18 |
+
self.secondary_api_key = settings.SECONDARY_LLM_API_KEY
|
| 19 |
|
| 20 |
def load_model(self):
|
| 21 |
return self.model_name
|
|
|
|
| 82 |
|
| 83 |
def get_model_name(self):
|
| 84 |
return self.model_name
|
| 85 |
+
|
| 86 |
+
def get_model_name(self):
|
| 87 |
+
return self.model_name
|
tests/integration/test_api.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
-
import
|
| 2 |
import time
|
| 3 |
-
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
@pytest.fixture
|
|
@@ -53,22 +54,7 @@ def test_health_endpoint(app, set_test_env):
|
|
| 53 |
data = response.json()
|
| 54 |
assert data["status"] == "healthy"
|
| 55 |
assert "timestamp" in data
|
| 56 |
-
assert data["version"] == "3.0.0
|
| 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)
|
| 65 |
-
response = client.get("/")
|
| 66 |
-
|
| 67 |
-
assert response.status_code == 200
|
| 68 |
-
data = response.json()
|
| 69 |
-
assert "message" in data
|
| 70 |
-
assert data["docs"] == "/docs"
|
| 71 |
-
assert data["health"] == "/health"
|
| 72 |
|
| 73 |
|
| 74 |
@pytest.mark.integration
|
|
@@ -96,3 +82,4 @@ def test_startup_event_logs_configuration(app, set_test_env):
|
|
| 96 |
client = TestClient(app)
|
| 97 |
response = client.get("/health")
|
| 98 |
assert response.status_code == 200
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
import time
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
|
| 6 |
|
| 7 |
@pytest.fixture
|
|
|
|
| 54 |
data = response.json()
|
| 55 |
assert data["status"] == "healthy"
|
| 56 |
assert "timestamp" in data
|
| 57 |
+
assert data["version"] == "3.0.0"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
|
| 60 |
@pytest.mark.integration
|
|
|
|
| 82 |
client = TestClient(app)
|
| 83 |
response = client.get("/health")
|
| 84 |
assert response.status_code == 200
|
| 85 |
+
assert response.status_code == 200
|
tests/unit/test_acquisition_agent.py
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
import asyncio
|
| 2 |
import time
|
|
|
|
| 3 |
import pytest
|
| 4 |
|
| 5 |
-
from models.state import State
|
| 6 |
from agents.acquisition_agent import AcquisitionAgent
|
|
|
|
| 7 |
|
| 8 |
|
| 9 |
def make_pdf_bytes(long: bool = True) -> bytes:
|
|
@@ -246,7 +247,7 @@ async def test_acquisition_parallel_10_with_2_failures(monkeypatch):
|
|
| 246 |
if i < 8:
|
| 247 |
mapping[u] = (200, fast_bytes, 0.0)
|
| 248 |
else:
|
| 249 |
-
mapping[u] = (200, fast_bytes,
|
| 250 |
|
| 251 |
monkeypatch.setattr(
|
| 252 |
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
|
|
@@ -259,16 +260,17 @@ async def test_acquisition_parallel_10_with_2_failures(monkeypatch):
|
|
| 259 |
state = State(query="q", finalists=finalists)
|
| 260 |
agent = AcquisitionAgent()
|
| 261 |
# make timeouts small so test doesn't actually wait long
|
| 262 |
-
agent.PER_PDF_TIMEOUT =
|
| 263 |
|
| 264 |
start = time.monotonic()
|
| 265 |
new_state = await agent.process(state)
|
| 266 |
elapsed = time.monotonic() - start
|
| 267 |
|
| 268 |
-
# successful should be
|
| 269 |
passages = new_state.passages or []
|
| 270 |
-
assert len(passages) ==
|
| 271 |
pdf_passages = [p for p in passages if p["text_source"] == "pdf"]
|
| 272 |
-
assert len(pdf_passages) ==
|
| 273 |
# requirement: return in under 4 seconds in real world; here ensure it's fast
|
| 274 |
assert elapsed < 4.0
|
|
|
|
|
|
| 1 |
import asyncio
|
| 2 |
import time
|
| 3 |
+
|
| 4 |
import pytest
|
| 5 |
|
|
|
|
| 6 |
from agents.acquisition_agent import AcquisitionAgent
|
| 7 |
+
from models.state import State
|
| 8 |
|
| 9 |
|
| 10 |
def make_pdf_bytes(long: bool = True) -> bytes:
|
|
|
|
| 247 |
if i < 8:
|
| 248 |
mapping[u] = (200, fast_bytes, 0.0)
|
| 249 |
else:
|
| 250 |
+
mapping[u] = (200, fast_bytes, 2.0)
|
| 251 |
|
| 252 |
monkeypatch.setattr(
|
| 253 |
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
|
|
|
|
| 260 |
state = State(query="q", finalists=finalists)
|
| 261 |
agent = AcquisitionAgent()
|
| 262 |
# make timeouts small so test doesn't actually wait long
|
| 263 |
+
agent.PER_PDF_TIMEOUT = 1.0
|
| 264 |
|
| 265 |
start = time.monotonic()
|
| 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
|
tests/unit/test_config.py
CHANGED
|
@@ -1,100 +1,68 @@
|
|
| 1 |
-
import importlib.util
|
| 2 |
import os
|
| 3 |
-
from pathlib import Path
|
| 4 |
from unittest.mock import patch
|
| 5 |
|
| 6 |
import pytest
|
| 7 |
|
| 8 |
-
|
| 9 |
-
def _load_config_module_from_path(env: dict):
|
| 10 |
-
"""Load config/config.py as an isolated module with given env mapping.
|
| 11 |
-
|
| 12 |
-
We load the file directly to avoid earlier-import interference from other
|
| 13 |
-
parts of the codebase or pytest collection.
|
| 14 |
-
"""
|
| 15 |
-
cfg_path = Path(__file__).resolve().parents[2] / "config" / "config.py"
|
| 16 |
-
assert cfg_path.exists(), f"Config file not found at {cfg_path}"
|
| 17 |
-
# Ensure the repo .env is not loaded during tests
|
| 18 |
-
env = {**env, "SKIP_DOTENV_LOADER": "1"}
|
| 19 |
-
|
| 20 |
-
with patch.dict(os.environ, env, clear=True):
|
| 21 |
-
spec = importlib.util.spec_from_file_location("_temp_config", str(cfg_path))
|
| 22 |
-
module = importlib.util.module_from_spec(spec)
|
| 23 |
-
# Execute module in isolated namespace
|
| 24 |
-
spec.loader.exec_module(module)
|
| 25 |
-
return module
|
| 26 |
|
| 27 |
|
| 28 |
@pytest.mark.unit
|
| 29 |
-
def
|
| 30 |
-
"""
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
"SECONDARY_LLM_API_KEY": "fake_groq",
|
| 34 |
-
}
|
| 35 |
-
with pytest.raises(ValueError) as exc_info:
|
| 36 |
-
_load_config_module_from_path(env)
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
@pytest.mark.unit
|
| 44 |
-
def
|
| 45 |
-
"""
|
| 46 |
env = {
|
| 47 |
-
"
|
| 48 |
-
"
|
|
|
|
|
|
|
| 49 |
}
|
| 50 |
-
with
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
@pytest.mark.unit
|
| 58 |
-
def
|
| 59 |
-
"""
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
"PRIMARY_LLM_API_KEY": "fake_google",
|
| 63 |
-
}
|
| 64 |
-
with pytest.raises(ValueError) as exc_info:
|
| 65 |
-
_load_config_module_from_path(env)
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
|
|
|
| 69 |
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
@pytest.mark.unit
|
| 72 |
-
def test_config_all_keys_present():
|
| 73 |
-
"""Config validation passes when all keys are present."""
|
| 74 |
-
env = {
|
| 75 |
-
"SEMANTIC_SCHOLAR_API_KEY": "fake_ss_key",
|
| 76 |
-
"PRIMARY_LLM_API_KEY": "fake_google_key",
|
| 77 |
-
"SECONDARY_LLM_API_KEY": "fake_groq_key",
|
| 78 |
-
}
|
| 79 |
-
config = _load_config_module_from_path(env)
|
| 80 |
-
# validate_config called on import; calling again should be OK
|
| 81 |
-
config.validate_config()
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
"""Custom model names from env vars override the defaults."""
|
| 91 |
-
env = {
|
| 92 |
-
"SEMANTIC_SCHOLAR_API_KEY": "fake_ss_key",
|
| 93 |
-
"PRIMARY_LLM_API_KEY": "fake_google_key",
|
| 94 |
-
"SECONDARY_LLM_API_KEY": "fake_groq_key",
|
| 95 |
-
"QUERY_OPTIMIZATION_MODEL": "custom/query-model",
|
| 96 |
-
"SYNTHESIS_MODEL": "custom/synthesis-model",
|
| 97 |
-
}
|
| 98 |
-
config = _load_config_module_from_path(env)
|
| 99 |
-
assert config.QUERY_OPTIMIZATION_MODEL == "custom/query-model"
|
| 100 |
-
assert config.SYNTHESIS_MODEL == "custom/synthesis-model"
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
from unittest.mock import patch
|
| 3 |
|
| 4 |
import pytest
|
| 5 |
|
| 6 |
+
from config.config import Settings, get_settings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
|
| 9 |
@pytest.mark.unit
|
| 10 |
+
def test_settings_defaults():
|
| 11 |
+
"""Test that settings have expected default values."""
|
| 12 |
+
# Clear cache to ensure fresh settings
|
| 13 |
+
get_settings.cache_clear()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# Patch env to be empty to test defaults
|
| 16 |
+
with patch.dict(os.environ, {}, clear=True):
|
| 17 |
+
# Pass _env_file=None to ignore .env file
|
| 18 |
+
settings = Settings(_env_file=None)
|
| 19 |
+
assert settings.LOG_LEVEL == "INFO"
|
| 20 |
+
assert settings.TIMEOUT == 30
|
| 21 |
+
assert settings.RAG_RETRIEVAL_TOP_K == 50
|
| 22 |
+
assert settings.SEMANTIC_SCHOLAR_API_KEY is None
|
| 23 |
|
| 24 |
|
| 25 |
@pytest.mark.unit
|
| 26 |
+
def test_settings_env_override():
|
| 27 |
+
"""Test that environment variables override defaults."""
|
| 28 |
env = {
|
| 29 |
+
"LOG_LEVEL": "DEBUG",
|
| 30 |
+
"TIMEOUT": "60",
|
| 31 |
+
"SEMANTIC_SCHOLAR_API_KEY": "test_key",
|
| 32 |
+
"RAG_RETRIEVAL_TOP_K": "100",
|
| 33 |
}
|
| 34 |
+
with patch.dict(os.environ, env, clear=True):
|
| 35 |
+
settings = Settings()
|
| 36 |
+
assert settings.LOG_LEVEL == "DEBUG"
|
| 37 |
+
assert settings.TIMEOUT == 60
|
| 38 |
+
assert settings.SEMANTIC_SCHOLAR_API_KEY == "test_key"
|
| 39 |
+
assert settings.RAG_RETRIEVAL_TOP_K == 100
|
| 40 |
|
| 41 |
|
| 42 |
@pytest.mark.unit
|
| 43 |
+
def test_validate_keys_logging(caplog):
|
| 44 |
+
"""Test that validate_keys logs warnings for missing keys."""
|
| 45 |
+
# Clear cache
|
| 46 |
+
get_settings.cache_clear()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
with patch.dict(os.environ, {}, clear=True):
|
| 49 |
+
settings = Settings(_env_file=None)
|
| 50 |
+
settings.validate_keys()
|
| 51 |
|
| 52 |
+
assert "SEMANTIC_SCHOLAR_API_KEY is not set" in caplog.text
|
| 53 |
+
assert "PRIMARY_LLM_API_KEY is not set" in caplog.text
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
@pytest.mark.unit
|
| 57 |
+
def test_validate_keys_no_warning_when_set(caplog):
|
| 58 |
+
"""Test that validate_keys does not log warnings when keys are present."""
|
| 59 |
+
env = {"SEMANTIC_SCHOLAR_API_KEY": "present", "PRIMARY_LLM_API_KEY": "present"}
|
| 60 |
+
with patch.dict(os.environ, env, clear=True):
|
| 61 |
+
settings = Settings()
|
| 62 |
+
settings.validate_keys()
|
| 63 |
|
| 64 |
+
assert "SEMANTIC_SCHOLAR_API_KEY is not set" not in caplog.text
|
| 65 |
+
assert "PRIMARY_LLM_API_KEY is not set" not in caplog.text
|
| 66 |
|
| 67 |
+
assert "SEMANTIC_SCHOLAR_API_KEY is not set" not in caplog.text
|
| 68 |
+
assert "PRIMARY_LLM_API_KEY is not set" not in caplog.text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/unit/test_llm_router.py
CHANGED
|
@@ -1,23 +1,32 @@
|
|
| 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("
|
| 20 |
-
patch("config.config.QUERY_OPTIMIZATION_FALLBACK", fallback_model),
|
| 21 |
patch("litellm.acompletion", new_callable=AsyncMock) as mock_acompletion,
|
| 22 |
):
|
| 23 |
|
|
@@ -34,22 +43,17 @@ async def test_generate_happy_path():
|
|
| 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("
|
| 50 |
-
patch("config.config.QUERY_OPTIMIZATION_FALLBACK", fallback_model),
|
| 51 |
-
patch("config.config.PRIMARY_LLM_API_KEY", "fake_google_key"),
|
| 52 |
-
patch("config.config.SECONDARY_LLM_API_KEY", "fake_groq_key"),
|
| 53 |
patch("litellm.acompletion", new_callable=AsyncMock) as mock_acompletion,
|
| 54 |
):
|
| 55 |
|
|
@@ -78,20 +82,19 @@ async def test_generate_fallback_path():
|
|
| 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
|
|
|
|
|
|
|
| 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("
|
| 94 |
-
patch("config.config.QUERY_OPTIMIZATION_FALLBACK", fallback_model),
|
| 95 |
patch("litellm.acompletion", new_callable=AsyncMock) as mock_acompletion,
|
| 96 |
):
|
| 97 |
|
|
|
|
|
|
|
|
|
|
| 1 |
from types import SimpleNamespace
|
| 2 |
+
from unittest.mock import AsyncMock, MagicMock, patch
|
| 3 |
|
| 4 |
+
import pytest
|
| 5 |
from loguru import logger
|
| 6 |
|
| 7 |
+
from config.config import Settings
|
| 8 |
from utils.llm_router import LLMRouter
|
| 9 |
|
| 10 |
|
| 11 |
+
@pytest.fixture
|
| 12 |
+
def mock_settings():
|
| 13 |
+
settings = MagicMock(spec=Settings)
|
| 14 |
+
settings.QUERY_OPTIMIZATION_MODEL = "primary_model"
|
| 15 |
+
settings.QUERY_OPTIMIZATION_FALLBACK = "fallback_model"
|
| 16 |
+
settings.SYNTHESIS_MODEL = "synthesis_primary"
|
| 17 |
+
settings.SYNTHESIS_FALLBACK = "synthesis_fallback"
|
| 18 |
+
settings.PRIMARY_LLM_API_KEY = "fake_google_key"
|
| 19 |
+
settings.SECONDARY_LLM_API_KEY = "fake_groq_key"
|
| 20 |
+
return settings
|
| 21 |
+
|
| 22 |
+
|
| 23 |
@pytest.mark.unit
|
| 24 |
@pytest.mark.asyncio
|
| 25 |
+
async def test_generate_happy_path(mock_settings):
|
| 26 |
"""generate should call litellm.acompletion with the primary model and return content"""
|
|
|
|
|
|
|
| 27 |
|
|
|
|
| 28 |
with (
|
| 29 |
+
patch("utils.llm_router.get_settings", return_value=mock_settings),
|
|
|
|
| 30 |
patch("litellm.acompletion", new_callable=AsyncMock) as mock_acompletion,
|
| 31 |
):
|
| 32 |
|
|
|
|
| 43 |
# assert called once with primary model
|
| 44 |
assert mock_acompletion.call_count == 1
|
| 45 |
called_kwargs = mock_acompletion.call_args.kwargs
|
| 46 |
+
assert called_kwargs.get("model") == "primary_model"
|
| 47 |
assert called_kwargs.get("timeout") == 30
|
| 48 |
|
| 49 |
|
| 50 |
@pytest.mark.unit
|
| 51 |
@pytest.mark.asyncio
|
| 52 |
+
async def test_generate_fallback_path(mock_settings):
|
| 53 |
"""If primary fails, router should retry with fallback and return content"""
|
|
|
|
|
|
|
| 54 |
|
| 55 |
with (
|
| 56 |
+
patch("utils.llm_router.get_settings", return_value=mock_settings),
|
|
|
|
|
|
|
|
|
|
| 57 |
patch("litellm.acompletion", new_callable=AsyncMock) as mock_acompletion,
|
| 58 |
):
|
| 59 |
|
|
|
|
| 82 |
|
| 83 |
assert result == "fallback-ok"
|
| 84 |
assert mock_acompletion.call_count == 2
|
| 85 |
+
assert mock_acompletion.call_args_list[0].kwargs.get("model") == "primary_model"
|
| 86 |
+
assert (
|
| 87 |
+
mock_acompletion.call_args_list[1].kwargs.get("model") == "fallback_model"
|
| 88 |
+
)
|
| 89 |
|
| 90 |
|
| 91 |
@pytest.mark.unit
|
| 92 |
@pytest.mark.asyncio
|
| 93 |
+
async def test_generate_both_fail(mock_settings):
|
| 94 |
"""If both primary and fallback fail, router should raise the exception"""
|
|
|
|
|
|
|
| 95 |
|
| 96 |
with (
|
| 97 |
+
patch("utils.llm_router.get_settings", return_value=mock_settings),
|
|
|
|
| 98 |
patch("litellm.acompletion", new_callable=AsyncMock) as mock_acompletion,
|
| 99 |
):
|
| 100 |
|
tests/unit/test_query_optimization_agent.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
-
import pytest
|
| 2 |
-
from unittest.mock import AsyncMock, patch
|
| 3 |
import json
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
from agents.query_optimization_agent import QueryOptimizationAgent
|
| 6 |
|
|
@@ -46,6 +47,7 @@ async def test_generate_dual_queries_llm_timeout_fallback():
|
|
| 46 |
result = await agent.generate_dual_queries(query)
|
| 47 |
|
| 48 |
expected = {
|
|
|
|
| 49 |
"final_rephrase": query,
|
| 50 |
"primary": query,
|
| 51 |
"broad": query,
|
|
@@ -70,6 +72,7 @@ async def test_generate_dual_queries_invalid_json_fallback():
|
|
| 70 |
result = await agent.generate_dual_queries(query)
|
| 71 |
|
| 72 |
expected = {
|
|
|
|
| 73 |
"final_rephrase": query,
|
| 74 |
"primary": query,
|
| 75 |
"broad": query,
|
|
@@ -98,3 +101,4 @@ async def test_generate_dual_queries_empty_query():
|
|
| 98 |
expected = {"final_rephrase": "", "primary": "", "broad": "", "alternative": ""}
|
| 99 |
assert result == expected
|
| 100 |
mock_generate.assert_called_once()
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
+
from unittest.mock import AsyncMock, patch
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
|
| 6 |
from agents.query_optimization_agent import QueryOptimizationAgent
|
| 7 |
|
|
|
|
| 47 |
result = await agent.generate_dual_queries(query)
|
| 48 |
|
| 49 |
expected = {
|
| 50 |
+
"strategy": "expansion",
|
| 51 |
"final_rephrase": query,
|
| 52 |
"primary": query,
|
| 53 |
"broad": query,
|
|
|
|
| 72 |
result = await agent.generate_dual_queries(query)
|
| 73 |
|
| 74 |
expected = {
|
| 75 |
+
"strategy": "expansion",
|
| 76 |
"final_rephrase": query,
|
| 77 |
"primary": query,
|
| 78 |
"broad": query,
|
|
|
|
| 101 |
expected = {"final_rephrase": "", "primary": "", "broad": "", "alternative": ""}
|
| 102 |
assert result == expected
|
| 103 |
mock_generate.assert_called_once()
|
| 104 |
+
mock_generate.assert_called_once()
|
tests/unit/test_semantic_scholar_client.py
CHANGED
|
@@ -55,6 +55,10 @@ class DummyClientSession:
|
|
| 55 |
|
| 56 |
def __init__(self, responses: Dict[str, Any]):
|
| 57 |
self._responses = responses
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
async def __aenter__(self):
|
| 60 |
return self
|
|
|
|
| 55 |
|
| 56 |
def __init__(self, responses: Dict[str, Any]):
|
| 57 |
self._responses = responses
|
| 58 |
+
self.closed = False
|
| 59 |
+
|
| 60 |
+
async def close(self):
|
| 61 |
+
self.closed = True
|
| 62 |
|
| 63 |
async def __aenter__(self):
|
| 64 |
return self
|
ui/__init__.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
"""NiceGUI frontend components for Necthrall."""
|
| 2 |
|
| 3 |
from ui.pages import init_ui
|
| 4 |
-
from ui.styles import CUSTOM_CSS
|
| 5 |
|
| 6 |
-
__all__ = ["init_ui"
|
|
|
|
| 1 |
"""NiceGUI frontend components for Necthrall."""
|
| 2 |
|
| 3 |
from ui.pages import init_ui
|
|
|
|
| 4 |
|
| 5 |
+
__all__ = ["init_ui"]
|
ui/pages.py
CHANGED
|
@@ -1,24 +1,24 @@
|
|
| 1 |
"""Page definitions for the Necthrall UI."""
|
| 2 |
|
| 3 |
import asyncio
|
|
|
|
| 4 |
from pathlib import Path
|
| 5 |
-
|
|
|
|
| 6 |
from loguru import logger
|
| 7 |
-
import
|
| 8 |
|
| 9 |
-
from
|
| 10 |
from ui.components import (
|
| 11 |
-
|
| 12 |
render_answer,
|
| 13 |
-
render_sources,
|
| 14 |
render_error,
|
| 15 |
render_exception_error,
|
| 16 |
-
|
|
|
|
| 17 |
)
|
|
|
|
| 18 |
from ui.policies import PRIVACY_POLICY, TERMS_OF_SERVICE
|
| 19 |
-
from ui.constants import POSTHOG_SCRIPT, KOFI_WIDGET
|
| 20 |
-
import httpx
|
| 21 |
-
from config.config import WEB3FORMS_ACCESS_KEY
|
| 22 |
|
| 23 |
# Path to logo directory
|
| 24 |
LOGO_DIR = (
|
|
@@ -43,7 +43,7 @@ def init_ui(fastapi_app):
|
|
| 43 |
ui.add_head_html(f"<script>{POSTHOG_SCRIPT}</script>")
|
| 44 |
|
| 45 |
# Inject custom CSS
|
| 46 |
-
ui.add_head_html(
|
| 47 |
|
| 48 |
# Inject Ko-fi widget
|
| 49 |
ui.add_body_html(KOFI_WIDGET)
|
|
@@ -147,17 +147,15 @@ def init_ui(fastapi_app):
|
|
| 147 |
submit_btn.disable()
|
| 148 |
|
| 149 |
try:
|
| 150 |
-
if not WEB3FORMS_ACCESS_KEY:
|
| 151 |
logger.warning("WEB3FORMS_ACCESS_KEY missing.")
|
| 152 |
ui.notify(
|
| 153 |
"Message logged (Service not configured).", type="info"
|
| 154 |
)
|
| 155 |
else:
|
| 156 |
-
import json
|
| 157 |
-
|
| 158 |
# 2. Prepare Payload
|
| 159 |
payload = {
|
| 160 |
-
"access_key": WEB3FORMS_ACCESS_KEY,
|
| 161 |
"name": c_name.value,
|
| 162 |
"email": c_email.value,
|
| 163 |
"message": c_msg.value,
|
|
@@ -165,8 +163,10 @@ def init_ui(fastapi_app):
|
|
| 165 |
"botcheck": False,
|
| 166 |
}
|
| 167 |
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
| 170 |
js_code = f"""
|
| 171 |
const response = await fetch('https://api.web3forms.com/submit', {{
|
| 172 |
method: 'POST',
|
|
@@ -179,7 +179,6 @@ def init_ui(fastapi_app):
|
|
| 179 |
return await response.json();
|
| 180 |
"""
|
| 181 |
|
| 182 |
-
# 4. Run JS in the user's browser and await the result
|
| 183 |
result = await ui.run_javascript(js_code, timeout=15.0)
|
| 184 |
|
| 185 |
if result and result.get("success"):
|
|
@@ -457,7 +456,7 @@ def init_ui(fastapi_app):
|
|
| 457 |
ui.input(placeholder="What would you like to research today?")
|
| 458 |
.classes("flex-grow min-w-0")
|
| 459 |
.props(
|
| 460 |
-
"borderless dense "
|
| 461 |
"input-style='font-size: 16px; text-overflow: ellipsis;' "
|
| 462 |
"input-class='placeholder-slate-400'"
|
| 463 |
)
|
|
|
|
| 1 |
"""Page definitions for the Necthrall UI."""
|
| 2 |
|
| 3 |
import asyncio
|
| 4 |
+
import datetime
|
| 5 |
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import httpx
|
| 8 |
from loguru import logger
|
| 9 |
+
from nicegui import app, context, ui
|
| 10 |
|
| 11 |
+
from config.config import get_settings
|
| 12 |
from ui.components import (
|
| 13 |
+
SearchProgress,
|
| 14 |
render_answer,
|
|
|
|
| 15 |
render_error,
|
| 16 |
render_exception_error,
|
| 17 |
+
render_loading,
|
| 18 |
+
render_sources,
|
| 19 |
)
|
| 20 |
+
from ui.constants import KOFI_WIDGET, POSTHOG_SCRIPT
|
| 21 |
from ui.policies import PRIVACY_POLICY, TERMS_OF_SERVICE
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
# Path to logo directory
|
| 24 |
LOGO_DIR = (
|
|
|
|
| 43 |
ui.add_head_html(f"<script>{POSTHOG_SCRIPT}</script>")
|
| 44 |
|
| 45 |
# Inject custom CSS
|
| 46 |
+
ui.add_head_html('<link rel="stylesheet" href="/static/css/styles.css">')
|
| 47 |
|
| 48 |
# Inject Ko-fi widget
|
| 49 |
ui.add_body_html(KOFI_WIDGET)
|
|
|
|
| 147 |
submit_btn.disable()
|
| 148 |
|
| 149 |
try:
|
| 150 |
+
if not get_settings().WEB3FORMS_ACCESS_KEY:
|
| 151 |
logger.warning("WEB3FORMS_ACCESS_KEY missing.")
|
| 152 |
ui.notify(
|
| 153 |
"Message logged (Service not configured).", type="info"
|
| 154 |
)
|
| 155 |
else:
|
|
|
|
|
|
|
| 156 |
# 2. Prepare Payload
|
| 157 |
payload = {
|
| 158 |
+
"access_key": get_settings().WEB3FORMS_ACCESS_KEY,
|
| 159 |
"name": c_name.value,
|
| 160 |
"email": c_email.value,
|
| 161 |
"message": c_msg.value,
|
|
|
|
| 163 |
"botcheck": False,
|
| 164 |
}
|
| 165 |
|
| 166 |
+
import json
|
| 167 |
+
|
| 168 |
+
# 3. Submit via Client-side JS (Web3Forms Free Tier requires this)
|
| 169 |
+
# Note: We use json.dumps to safely serialize the payload into the JS string.
|
| 170 |
js_code = f"""
|
| 171 |
const response = await fetch('https://api.web3forms.com/submit', {{
|
| 172 |
method: 'POST',
|
|
|
|
| 179 |
return await response.json();
|
| 180 |
"""
|
| 181 |
|
|
|
|
| 182 |
result = await ui.run_javascript(js_code, timeout=15.0)
|
| 183 |
|
| 184 |
if result and result.get("success"):
|
|
|
|
| 456 |
ui.input(placeholder="What would you like to research today?")
|
| 457 |
.classes("flex-grow min-w-0")
|
| 458 |
.props(
|
| 459 |
+
"borderless dense autofocus"
|
| 460 |
"input-style='font-size: 16px; text-overflow: ellipsis;' "
|
| 461 |
"input-class='placeholder-slate-400'"
|
| 462 |
)
|
utils/llm_router.py
CHANGED
|
@@ -9,12 +9,13 @@ Usage example:
|
|
| 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 |
-
|
| 18 |
|
| 19 |
|
| 20 |
class LLMRouter:
|
|
@@ -25,18 +26,19 @@ class LLMRouter:
|
|
| 25 |
"""
|
| 26 |
|
| 27 |
def __init__(self) -> None:
|
|
|
|
| 28 |
# Store API keys for use in generate method
|
| 29 |
-
self._primary_api_key =
|
| 30 |
-
self._secondary_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 |
-
|
| 37 |
-
|
| 38 |
),
|
| 39 |
-
"synthesis": (
|
| 40 |
}
|
| 41 |
|
| 42 |
async def _call_model(
|
|
|
|
| 9 |
content = await router.generate("Summarize this paper.", "synthesis")
|
| 10 |
"""
|
| 11 |
|
|
|
|
|
|
|
| 12 |
import asyncio
|
| 13 |
+
from typing import Optional
|
| 14 |
+
|
| 15 |
import litellm
|
| 16 |
+
from loguru import logger
|
| 17 |
|
| 18 |
+
from config.config import get_settings
|
| 19 |
|
| 20 |
|
| 21 |
class LLMRouter:
|
|
|
|
| 26 |
"""
|
| 27 |
|
| 28 |
def __init__(self) -> None:
|
| 29 |
+
settings = get_settings()
|
| 30 |
# Store API keys for use in generate method
|
| 31 |
+
self._primary_api_key = settings.PRIMARY_LLM_API_KEY
|
| 32 |
+
self._secondary_api_key = settings.SECONDARY_LLM_API_KEY
|
| 33 |
|
| 34 |
# Read model names from config on instantiation. Keep values simple so
|
| 35 |
# tests can patch the module attributes.
|
| 36 |
self._models = {
|
| 37 |
"optimization": (
|
| 38 |
+
settings.QUERY_OPTIMIZATION_MODEL,
|
| 39 |
+
settings.QUERY_OPTIMIZATION_FALLBACK,
|
| 40 |
),
|
| 41 |
+
"synthesis": (settings.SYNTHESIS_MODEL, settings.SYNTHESIS_FALLBACK),
|
| 42 |
}
|
| 43 |
|
| 44 |
async def _call_model(
|
utils/research_assistant_prompts.py
DELETED
|
@@ -1,90 +0,0 @@
|
|
| 1 |
-
FEW_SHOT_EXAMPLE = """
|
| 2 |
-
### Executive Summary
|
| 3 |
-
**Intermittent fasting (IF) demonstrates consistent, modest benefits for cardiovascular health, primarily driven by weight loss and improved lipid profiles.**
|
| 4 |
-
|
| 5 |
-
While acute metabolic shifts—such as rapid TMAO reduction—are documented [2], long-term cardiovascular protection remains debated due to high attrition rates in trials (up to 38% [3]) and heterogeneity in fasting protocols [6][7]. Weight and BMI reduction through alternate-day fasting (ADF) achieves a 7% weight loss nadir at 6 months [3], with efficacy comparable to daily caloric restriction [12].
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
### Key Findings
|
| 9 |
-
* **Weight & BMI Reduction:** Alternate-day fasting (ADF) achieves a 7% weight loss nadir at 6 months [3], stabilizing at 4.5% below baseline at 12 months [3]. This efficacy is comparable to daily caloric restriction for overweight adults [12].
|
| 10 |
-
* **Biomarker Modulation:** A single 24-hour water-only fast reduced circulating TMAO from 27.1 to 14.3 ng/ml (p=0.019) [2].
|
| 11 |
-
* **Lipid Profile Improvement:** IF protocols generally lower total cholesterol [6] and LDL-C [7], though the magnitude of effect varies significantly by adherence levels.
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
### Synthesis & Implications
|
| 15 |
-
* **Mechanism of Action:** The benefits appear linked to both systemic weight reduction [3] and acute metabolic pauses that lower inflammatory markers like TMAO [2].
|
| 16 |
-
* **Protocol Viability:** While physiologically effective, the strictness of ADF leads to lower long-term adherence compared to less rigid restrictions [3], potentially limiting its utility as a public health intervention [12].
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
### Methodological Limits
|
| 20 |
-
* **Attrition Bias:** High dropout rates (38% in ADF arms [3]) likely inflate reported benefits by excluding non-adherent participants.
|
| 21 |
-
* **Transient vs. Chronic:** Key biomarkers like TMAO were often measured after acute fasting events [2], not reflecting long-term steady states.
|
| 22 |
-
|
| 23 |
-
---
|
| 24 |
-
|
| 25 |
-
❌ **INCORRECT EXAMPLE:**
|
| 26 |
-
"Fasting reduces TMAO and improves lipid profiles [2][3]."
|
| 27 |
-
*(Violates atomic citation rule—unclear which source supports which claim)*
|
| 28 |
-
|
| 29 |
-
✅ **CORRECT VERSION:**
|
| 30 |
-
"Fasting reduces TMAO [2] and improves lipid profiles [3]."
|
| 31 |
-
"""
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
CITATION_QA_TEMPLATE = (
|
| 35 |
-
"You are a PhD-level research assistant. Your goal is to write a highly dense, rigorous synthesis. "
|
| 36 |
-
"**Longer is NOT better.** Quality is defined by information density and thematic organization.\n"
|
| 37 |
-
"---------------------\n"
|
| 38 |
-
"### CONTEXT CHUNKS (Use ONLY these for citations):\n"
|
| 39 |
-
"{context_str}\n"
|
| 40 |
-
"---------------------\n\n"
|
| 41 |
-
"### INSTRUCTIONS (Follow Strictly):\n"
|
| 42 |
-
"1. **THEMATIC SYNTHESIS**:\n"
|
| 43 |
-
" - **DO NOT** organize bullets by study (e.g., avoid 'Study [1] said...').\n"
|
| 44 |
-
" - **DO** organize by **concepts, mechanisms, or outcomes**.\n"
|
| 45 |
-
" - Cite multiple sources within a single bullet if they support the same theme.\n\n"
|
| 46 |
-
"2. **REQUIRED SECTIONS (Use ### Markdown Headers)**:\n"
|
| 47 |
-
" - **### Executive Summary**: \n"
|
| 48 |
-
" * Start with a **Bold 'Bottom Line' Sentence** summarizing the core conclusion.\n"
|
| 49 |
-
" * Add a line break.\n"
|
| 50 |
-
" * Follow with a concise, high-density paragraph (max 150 words).\n"
|
| 51 |
-
" - **### Key Findings**: Thematic bullet points with hard data.\n"
|
| 52 |
-
" - **### Synthesis & Implications**: Explain the relationship (e.g., trade-offs, complementarity). Replaces simple comparisons.\n"
|
| 53 |
-
" - **### Methodological Limits**: Brief critique (bullet points).\n\n"
|
| 54 |
-
"3. **FORMATTING RULES**:\n"
|
| 55 |
-
" - **NO MARKDOWN TABLES**: Use nested bullet lists only.\n"
|
| 56 |
-
" - **BOLD LEAD-INS**: Start every bullet point with a **Bold Category:**.\n"
|
| 57 |
-
" - **ADAPTIVE COMPARISON**: \n"
|
| 58 |
-
" * **IF** the query compares entities (2 or more), treat every bullet as a 'table row'.\n"
|
| 59 |
-
" * **Rule:** Strictly repeat the 'vs.' pattern for every entity.\n"
|
| 60 |
-
" * **Format:** '**Category:** Entity A (Detail) **vs.** Entity B (Detail).'\n"
|
| 61 |
-
" - **NO IMAGES**: Do not generate image tags.\n\n"
|
| 62 |
-
"4. **QUANTITATIVE DATA & CITATION PRECISION (CRITICAL)**: \n"
|
| 63 |
-
" - **NO OUTSIDE KNOWLEDGE**: You are strictly limited to the provided context chunks above. Do not use external knowledge.\n"
|
| 64 |
-
" - **NO HALLUCINATIONS**: If the text says 'expensive', **DO NOT** invent a number like '$500'. Write 'high cost' instead.\n"
|
| 65 |
-
" - **Specifics**: Use p-values, N=, and % changes **ONLY** if explicitly stated in the provided text.\n"
|
| 66 |
-
" - **ATOMIC CITATION RULE (MANDATORY)**: \n"
|
| 67 |
-
" * Each statistic or claim gets exactly ONE citation [N] immediately after it.\n"
|
| 68 |
-
" * **VERIFICATION STEP**: For every [N], ask yourself: 'Does passage N contain this exact number/claim?'\n"
|
| 69 |
-
" * **Correct:** 'Method A yield is 80% [1] vs. Method B is 40% [2].'\n"
|
| 70 |
-
" * **Incorrect:** 'Method A yield is 80% vs. Method B is 40% [1][2].'\n"
|
| 71 |
-
" * **Incorrect:** 'Method A and B yields are 80% and 40% respectively [1].' (Unless [1] contains BOTH numbers).\n"
|
| 72 |
-
" - **FORBIDDEN PATTERN**: Never group more than 2 citations together (e.g., `[1][2][3]` is prohibited).\n"
|
| 73 |
-
" * **Requirement:** If multiple sources support a statement, split the statement so each source supports a specific part.\n"
|
| 74 |
-
" - **CROSS-CHECK**: Before finalizing, re-read each citation and confirm the passage actually contains that specific fact.\n\n"
|
| 75 |
-
"5. **CITATION VALIDATION (MANDATORY PRE-CHECK)**:\n"
|
| 76 |
-
" - Before writing each sentence with a factual claim, identify which source [N] supports it.\n"
|
| 77 |
-
" - If no source contains the information, write 'Evidence unavailable' or omit the claim entirely.\n"
|
| 78 |
-
" - **NEVER** cite [N] unless you can mentally quote the exact text from passage N that supports your claim.\n"
|
| 79 |
-
" - **PLANNING STEP**: For each key finding, create a mental note:\n"
|
| 80 |
-
" * 'Claim: [X]. Supporting passage: [N]. Key quote from passage: \"...\"'\n"
|
| 81 |
-
" - Then write the synthesis using only these validated claim-passage pairs.\n\n"
|
| 82 |
-
"6. **START IMMEDIATELY**: \n"
|
| 83 |
-
" - Start your response directly with the header '### Executive Summary'.\n"
|
| 84 |
-
" - Do not use introductory labels like 'Scientific Answer:' or 'Here is the synthesis'.\n\n"
|
| 85 |
-
"### REQUIRED OUTPUT FORMAT:\n"
|
| 86 |
-
"---------------------\n"
|
| 87 |
-
f"{FEW_SHOT_EXAMPLE}\n"
|
| 88 |
-
"---------------------\n\n"
|
| 89 |
-
"User Query: {query_str}\n"
|
| 90 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|