Adam Cseresznye commited on
Commit ·
cd26350
1
Parent(s): cc37b0c
Implement FastAPI skeleton with health endpoint and tests
Browse files- agents/__init__.py +5 -0
- agents/query_optimization_agent.py +30 -0
- agents/semantic_scholar_client.py +28 -0
- config.py +0 -1
- config/__init__.py +20 -0
- config/config.py +136 -0
- debug_openalex_output.txt +0 -3
- main.py +84 -0
- models/state.py +89 -0
- performance_log.json +0 -13
- pytest.ini +2 -4
- requirements.txt +2 -2
- src/necthrall_lite/__init__.py +0 -1
- src/necthrall_lite/api/__init__.py +0 -1
- src/necthrall_lite/api/schemas.py +0 -61
- src/necthrall_lite/core/prompts/synthesis_template.py +0 -159
- src/necthrall_lite/services/__init__.py +0 -1
- src/necthrall_lite/services/synthesis_service.py +0 -406
- tests/end_to_end/__init__.py +1 -0
- tests/integration/__init__.py +1 -0
- tests/integration/test_api.py +78 -0
- tests/performance/__init__.py +1 -0
- tests/unit/test_config.py +100 -0
- tests/unit/test_state.py +56 -0
- utils/embedding_manager.py +0 -1
- utils/error_handling.py +0 -1
- utils/llm_client.py +0 -1
- utils/logging_decorator.py +0 -1
- utils/logging_setup.py +0 -1
- utils/openalex_client.py +0 -1
- utils/pipeline_logging.py +0 -1
- utils/scihub_fallback.py +0 -1
- utils/section_detector.py +0 -1
- utils/spacy_error_handler.py +0 -1
agents/__init__.py
CHANGED
|
@@ -1 +1,6 @@
|
|
|
|
|
| 1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agents package for Necthrall Lite.
|
| 2 |
|
| 3 |
+
This module exposes agent classes as they are implemented.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
__all__ = ["SemanticScholarClient", "QueryOptimizationAgent"]
|
agents/query_optimization_agent.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stub query optimization agent.
|
| 2 |
+
|
| 3 |
+
Responsible for producing optimized query variants and lightweight
|
| 4 |
+
transformations useful for later retrieval stages.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import Dict, Optional
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class QueryOptimizationAgent:
|
| 11 |
+
"""Produce query variants and lightweight rewrites.
|
| 12 |
+
|
| 13 |
+
Example usage:
|
| 14 |
+
agent = QueryOptimizationAgent()
|
| 15 |
+
optimized = agent.optimize("deep learning for graph data")
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def __init__(self) -> None:
|
| 19 |
+
pass
|
| 20 |
+
|
| 21 |
+
def optimize(self, query: str) -> Dict[str, Optional[str]]:
|
| 22 |
+
"""Return a dict with `optimized_query` and optional variants.
|
| 23 |
+
|
| 24 |
+
Stub: real implementation should apply paraphrasing, synonyms or
|
| 25 |
+
template-based rewrites.
|
| 26 |
+
"""
|
| 27 |
+
raise NotImplementedError("QueryOptimizationAgent.optimize not implemented")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
__all__ = ["QueryOptimizationAgent"]
|
agents/semantic_scholar_client.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stub Semantic Scholar client for retrieval stage.
|
| 2 |
+
|
| 3 |
+
This is intentionally minimal: a class definition and docstring so future
|
| 4 |
+
implementations can plug in network calls and parsing logic.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import Any, Dict, List
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class SemanticScholarClient:
|
| 11 |
+
"""Client stub wrapping Semantic Scholar API interactions.
|
| 12 |
+
|
| 13 |
+
Methods should be implemented to fetch papers for a given query and
|
| 14 |
+
return structured dicts compatible with the pipeline's `State.papers`.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, api_key: str | None = None) -> None:
|
| 18 |
+
self.api_key = api_key
|
| 19 |
+
|
| 20 |
+
def search(self, query: str, limit: int = 10) -> List[Dict[str, Any]]:
|
| 21 |
+
"""Search Semantic Scholar for `query` and return list of raw hits.
|
| 22 |
+
|
| 23 |
+
Currently a stub that should be implemented in future work.
|
| 24 |
+
"""
|
| 25 |
+
raise NotImplementedError("SemanticScholarClient.search is not implemented")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
__all__ = ["SemanticScholarClient"]
|
config.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|
config/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration package for Necthrall Lite.
|
| 2 |
+
|
| 3 |
+
This package re-exports the policy/configuration from :mod:`config.config`
|
| 4 |
+
so that `import config` exposes the expected configuration variables.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from .config import * # noqa: F401,F403 (re-export configuration symbols)
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
# re-exported names (not exhaustive) - provide common entry points
|
| 11 |
+
"SEMANTIC_SCHOLAR_API_KEY",
|
| 12 |
+
"QUERY_OPTIMIZATION_MODEL",
|
| 13 |
+
"QUERY_OPTIMIZATION_FALLBACK",
|
| 14 |
+
"SYNTHESIS_MODEL",
|
| 15 |
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| 4 |
+
Loads environment variables and validates required API keys.
|
| 5 |
+
Provides model configurations for LiteLLM routing.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 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 |
+
# Configure logger level early
|
| 20 |
+
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
|
| 21 |
+
logger.remove()
|
| 22 |
+
logger.add(lambda msg: print(msg, end=""), level=LOG_LEVEL)
|
| 23 |
+
|
| 24 |
+
# ============================================================================
|
| 25 |
+
# Semantic Scholar API Configuration
|
| 26 |
+
# ============================================================================
|
| 27 |
+
SEMANTIC_SCHOLAR_API_KEY = os.getenv("SEMANTIC_SCHOLAR_API_KEY")
|
| 28 |
+
|
| 29 |
+
# ============================================================================
|
| 30 |
+
# LiteLLM Model Configuration - Query Optimization
|
| 31 |
+
# Fast models for query transformation and variant generation
|
| 32 |
+
# ============================================================================
|
| 33 |
+
QUERY_OPTIMIZATION_MODEL = os.getenv("QUERY_OPTIMIZATION_MODEL")
|
| 34 |
+
QUERY_OPTIMIZATION_FALLBACK = os.getenv("QUERY_OPTIMIZATION_FALLBACK")
|
| 35 |
+
|
| 36 |
+
# ============================================================================
|
| 37 |
+
# LiteLLM Model Configuration - Answer Synthesis
|
| 38 |
+
# Powerful models for final answer generation
|
| 39 |
+
# ============================================================================
|
| 40 |
+
SYNTHESIS_MODEL = os.getenv("SYNTHESIS_MODEL")
|
| 41 |
+
SYNTHESIS_FALLBACK = os.getenv("SYNTHESIS_FALLBACK")
|
| 42 |
+
|
| 43 |
+
# ============================================================================
|
| 44 |
+
# API Keys for LiteLLM Providers
|
| 45 |
+
# ============================================================================
|
| 46 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 47 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 48 |
+
|
| 49 |
+
# ============================================================================
|
| 50 |
+
# Application Settings
|
| 51 |
+
# ============================================================================
|
| 52 |
+
TIMEOUT = int(os.getenv("TIMEOUT", "30")) # API timeout in seconds
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _mask_key(value: str | None) -> str:
|
| 56 |
+
"""Return a masked representation of an API key for safe debug logging."""
|
| 57 |
+
if not value:
|
| 58 |
+
return "<missing>"
|
| 59 |
+
if len(value) <= 8:
|
| 60 |
+
return value[0:1] + "*" * (len(value) - 1)
|
| 61 |
+
return value[0:4] + "*" * (len(value) - 8) + value[-4:]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def validate_config() -> None:
|
| 65 |
+
"""
|
| 66 |
+
Validate that all required environment variables are set.
|
| 67 |
+
|
| 68 |
+
Raises:
|
| 69 |
+
ValueError: If any required environment variable is missing
|
| 70 |
+
|
| 71 |
+
Note:
|
| 72 |
+
This function is safe to call multiple times; it's cheap and completes
|
| 73 |
+
quickly. It is also called automatically when this module is imported.
|
| 74 |
+
"""
|
| 75 |
+
start = time.perf_counter()
|
| 76 |
+
|
| 77 |
+
required_vars = {
|
| 78 |
+
"SEMANTIC_SCHOLAR_API_KEY": {
|
| 79 |
+
"value": SEMANTIC_SCHOLAR_API_KEY,
|
| 80 |
+
"help": "Get free key at https://www.semanticscholar.org/product/api",
|
| 81 |
+
},
|
| 82 |
+
"GOOGLE_API_KEY": {
|
| 83 |
+
"value": GOOGLE_API_KEY,
|
| 84 |
+
"help": "Get free key at https://ai.google.dev/",
|
| 85 |
+
},
|
| 86 |
+
"GROQ_API_KEY": {
|
| 87 |
+
"value": GROQ_API_KEY,
|
| 88 |
+
"help": "Get free key at https://console.groq.com/keys",
|
| 89 |
+
},
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
missing = []
|
| 93 |
+
empty_values = []
|
| 94 |
+
for var_name, var_info in required_vars.items():
|
| 95 |
+
val = var_info["value"]
|
| 96 |
+
if val is None:
|
| 97 |
+
missing.append(f"{var_name} - {var_info['help']}")
|
| 98 |
+
elif isinstance(val, str) and val.strip() == "":
|
| 99 |
+
empty_values.append(var_name)
|
| 100 |
+
|
| 101 |
+
if empty_values:
|
| 102 |
+
logger.error(
|
| 103 |
+
"Configuration error: environment variables set but empty: {}",
|
| 104 |
+
", ".join(empty_values),
|
| 105 |
+
)
|
| 106 |
+
raise ValueError(
|
| 107 |
+
"The following environment variables are set but empty: "
|
| 108 |
+
+ ", ".join(empty_values)
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
if missing:
|
| 112 |
+
error_msg = (
|
| 113 |
+
"Missing required environment variables:\n"
|
| 114 |
+
+ "\n".join(f" - {m}" for m in missing)
|
| 115 |
+
+ "\n\nCreate a .env file in the project root with these variables. See .env.example for a template."
|
| 116 |
+
)
|
| 117 |
+
logger.error(error_msg)
|
| 118 |
+
raise ValueError(error_msg)
|
| 119 |
+
|
| 120 |
+
# Log masked keys and selected configuration for observability
|
| 121 |
+
logger.info("✓ Configuration validated successfully")
|
| 122 |
+
logger.info(" Query optimization model: {}", QUERY_OPTIMIZATION_MODEL)
|
| 123 |
+
logger.info(" Query optimization fallback: {}", QUERY_OPTIMIZATION_FALLBACK)
|
| 124 |
+
logger.info(" Synthesis model: {}", SYNTHESIS_MODEL)
|
| 125 |
+
logger.info(" Synthesis fallback: {}", SYNTHESIS_FALLBACK)
|
| 126 |
+
logger.info(" Timeout: {}s", TIMEOUT)
|
| 127 |
+
logger.debug(" SEMANTIC_SCHOLAR_API_KEY: {}", _mask_key(SEMANTIC_SCHOLAR_API_KEY))
|
| 128 |
+
logger.debug(" GOOGLE_API_KEY: {}", _mask_key(GOOGLE_API_KEY))
|
| 129 |
+
logger.debug(" GROQ_API_KEY: {}", _mask_key(GROQ_API_KEY))
|
| 130 |
+
|
| 131 |
+
elapsed_ms = (time.perf_counter() - start) * 1000.0
|
| 132 |
+
logger.debug("Configuration validation took %.2fms", elapsed_ms)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# Validate configuration when module is imported
|
| 136 |
+
validate_config()
|
debug_openalex_output.txt
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:43cf580b36d0631cc0350ed31caa54b5f1c5c2938f1ee19e233016bc3011bd50
|
| 3 |
-
size 3984
|
|
|
|
|
|
|
|
|
|
|
|
main.py
CHANGED
|
@@ -1 +1,85 @@
|
|
|
|
|
| 1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Minimal FastAPI app for Necthrall Lite MVP.
|
| 2 |
|
| 3 |
+
Exposes a /health endpoint for readiness checks.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from fastapi import FastAPI
|
| 7 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
+
from loguru import logger
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
import sys
|
| 11 |
+
|
| 12 |
+
# Configure loguru
|
| 13 |
+
logger.remove()
|
| 14 |
+
logger.add(
|
| 15 |
+
sys.stdout,
|
| 16 |
+
format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan> - <level>{message}</level>",
|
| 17 |
+
level="INFO",
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
app = FastAPI(
|
| 21 |
+
title="Necthrall Lite API",
|
| 22 |
+
description="AI-powered scientific research assistant",
|
| 23 |
+
version="3.0.0-mvp",
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# Configure CORS (permissive for development)
|
| 27 |
+
app.add_middleware(
|
| 28 |
+
CORSMiddleware,
|
| 29 |
+
allow_origins=["*"], # Will tighten in Week 4
|
| 30 |
+
allow_credentials=True,
|
| 31 |
+
allow_methods=["*"],
|
| 32 |
+
allow_headers=["*"],
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@app.on_event("startup")
|
| 37 |
+
async def startup_event():
|
| 38 |
+
"""Validate configuration at startup"""
|
| 39 |
+
try:
|
| 40 |
+
import config # Triggers validation
|
| 41 |
+
|
| 42 |
+
logger.info("Application startup successful")
|
| 43 |
+
logger.info(f"Query optimization model: {config.QUERY_OPTIMIZATION_MODEL}")
|
| 44 |
+
logger.info(f"Synthesis model: {config.SYNTHESIS_MODEL}")
|
| 45 |
+
except Exception as e:
|
| 46 |
+
logger.exception("Configuration validation failed")
|
| 47 |
+
sys.exit(1)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@app.get("/")
|
| 51 |
+
async def root():
|
| 52 |
+
"""Root endpoint with API documentation link"""
|
| 53 |
+
return {
|
| 54 |
+
"message": "Necthrall API v3.0.0",
|
| 55 |
+
"docs": "/docs",
|
| 56 |
+
"health": "/health",
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@app.get("/health")
|
| 61 |
+
async def health_check():
|
| 62 |
+
"""Health check endpoint"""
|
| 63 |
+
try:
|
| 64 |
+
return {
|
| 65 |
+
"status": "healthy",
|
| 66 |
+
"timestamp": datetime.now().isoformat(),
|
| 67 |
+
"version": "3.0.0-mvp",
|
| 68 |
+
}
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.exception("Health check failed")
|
| 71 |
+
return {
|
| 72 |
+
"status": "unhealthy",
|
| 73 |
+
"error": str(e),
|
| 74 |
+
"timestamp": datetime.now().isoformat(),
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
# Keep local run simple; uvicorn invocation is optional in dev
|
| 80 |
+
try:
|
| 81 |
+
import uvicorn
|
| 82 |
+
|
| 83 |
+
uvicorn.run("main:app", host="127.0.0.1", port=8000, log_level="info")
|
| 84 |
+
except Exception:
|
| 85 |
+
logger.debug("uvicorn not available or failed to start (fine for tests)")
|
models/state.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pydantic import BaseModel, Field, ValidationError
|
| 4 |
+
from typing import Optional, List, Dict, Any
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
from uuid import uuid4
|
| 7 |
+
from loguru import logger
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class State(BaseModel):
|
| 11 |
+
"""Progressive-enrichment State used by the Necthrall Lite pipeline.
|
| 12 |
+
|
| 13 |
+
The State is intentionally lean and uses Optional fields so agents can
|
| 14 |
+
populate it step-by-step (progressive enrichment). Field-by-field
|
| 15 |
+
assignment is validated (see model_config) and helper methods provide
|
| 16 |
+
ergonomic updates and error tracking.
|
| 17 |
+
|
| 18 |
+
Fields are small and serializable (dicts/lists/primitives) to keep the
|
| 19 |
+
model lightweight for tests and local runs.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
# Core identification
|
| 23 |
+
request_id: str = Field(default_factory=lambda: str(uuid4()))
|
| 24 |
+
query: str
|
| 25 |
+
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
| 26 |
+
|
| 27 |
+
# Query optimization (Day 4-5)
|
| 28 |
+
optimized_query: Optional[str] = None
|
| 29 |
+
ss_variants: Optional[Dict[str, str]] = None # {primary, broad, alternative}
|
| 30 |
+
|
| 31 |
+
# Paper retrieval (Day 3)
|
| 32 |
+
papers: Optional[List[Dict[str, Any]]] = None # Raw Semantic Scholar hits
|
| 33 |
+
|
| 34 |
+
# Quality and ranking (Day 4-5)
|
| 35 |
+
quality_gate: Optional[Dict[str, Any]] = None
|
| 36 |
+
ranked_papers: Optional[List[Dict[str, Any]]] = None
|
| 37 |
+
finalists: Optional[List[Dict[str, Any]]] = None # Top 5-10
|
| 38 |
+
|
| 39 |
+
# Passages (Week 2)
|
| 40 |
+
passages: Optional[List[Dict[str, Any]]] = None
|
| 41 |
+
|
| 42 |
+
# Answer and citations (Week 3)
|
| 43 |
+
answer: Optional[str] = None
|
| 44 |
+
citations: Optional[List[Dict[str, Any]]] = None
|
| 45 |
+
|
| 46 |
+
# Error tracking
|
| 47 |
+
errors: List[str] = Field(default_factory=list)
|
| 48 |
+
|
| 49 |
+
# Pydantic v2 config style
|
| 50 |
+
model_config = {
|
| 51 |
+
"arbitrary_types_allowed": True,
|
| 52 |
+
"validate_assignment": True,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
def __init__(self, **data: Any):
|
| 56 |
+
# Keep simple: run BaseModel init then log creation
|
| 57 |
+
super().__init__(**data)
|
| 58 |
+
logger.debug(
|
| 59 |
+
"State initialized: {request_id} query={query}",
|
| 60 |
+
request_id=self.request_id,
|
| 61 |
+
query=self.query,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
def update_fields(self, **kwargs: Any) -> None:
|
| 65 |
+
"""Update fields in-place with validation.
|
| 66 |
+
|
| 67 |
+
Example: state.update_fields(optimized_query="...")
|
| 68 |
+
This performs per-field validation thanks to validate_assignment.
|
| 69 |
+
"""
|
| 70 |
+
for k, v in kwargs.items():
|
| 71 |
+
if not hasattr(self, k):
|
| 72 |
+
raise AttributeError(f"State has no field '{k}'")
|
| 73 |
+
setattr(self, k, v)
|
| 74 |
+
logger.debug(
|
| 75 |
+
"State field updated: {field} -> {value}", field=k, value=repr(v)
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
def append_error(self, message: str) -> None:
|
| 79 |
+
"""Append an error message to the errors list and log it."""
|
| 80 |
+
self.errors.append(message)
|
| 81 |
+
logger.debug("State error appended: {err}", err=message)
|
| 82 |
+
|
| 83 |
+
def to_public(self) -> Dict[str, Any]:
|
| 84 |
+
"""Return a public-appropriate dict (shallow) useful for APIs/logging."""
|
| 85 |
+
# Keep potentially large fields; callers can prune if needed
|
| 86 |
+
return self.model_dump()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
__all__ = ["State"]
|
performance_log.json
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
{"total_papers": 2, "processed_papers": 2, "skipped_papers": 0, "total_sections": 2, "total_chunks": 2, "fallback_used_count": 2, "chunks_embedded": 2, "retrieval_candidates": 2, "reranked_passages": 2, "total_time": 0.02777570000034757, "export_timestamp": 1762567471.6911685, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762567471.6911697}
|
| 2 |
-
{"total_papers": 2, "processed_papers": 2, "skipped_papers": 0, "total_sections": 2, "total_chunks": 2, "fallback_used_count": 2, "chunks_embedded": 2, "retrieval_candidates": 2, "reranked_passages": 2, "total_time": 0.004621799998858478, "export_timestamp": 1762567472.8977654, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762567472.8977673}
|
| 3 |
-
{"total_papers": 2, "processed_papers": 2, "skipped_papers": 0, "total_sections": 2, "total_chunks": 2, "fallback_used_count": 2, "chunks_embedded": 2, "retrieval_candidates": 2, "reranked_passages": 2, "total_time": 0.0217821999995067, "export_timestamp": 1762567473.9212227, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762567473.9212239}
|
| 4 |
-
{"total_papers": 2, "processed_papers": 2, "skipped_papers": 0, "total_sections": 2, "total_chunks": 2, "fallback_used_count": 2, "chunks_embedded": 2, "retrieval_candidates": 2, "reranked_passages": 2, "total_time": 0.004627199999958975, "export_timestamp": 1762567474.9104295, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762567474.9104304}
|
| 5 |
-
{"total_papers": 2, "processed_papers": 2, "skipped_papers": 0, "total_sections": 3, "total_chunks": 3, "fallback_used_count": 1, "chunks_embedded": 3, "retrieval_candidates": 2, "reranked_passages": 2, "total_time": 0.000447300000814721, "export_timestamp": 1762567513.542121, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762567513.542122}
|
| 6 |
-
{"total_papers": 2, "processed_papers": 2, "skipped_papers": 0, "total_sections": 2, "total_chunks": 2, "fallback_used_count": 2, "chunks_embedded": 1, "retrieval_candidates": 1, "reranked_passages": 1, "total_time": 0.00042490000123507343, "export_timestamp": 1762567516.5688536, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762567516.5688548}
|
| 7 |
-
{"total_papers": 2, "processed_papers": 2, "skipped_papers": 0, "total_sections": 2, "total_chunks": 2, "fallback_used_count": 2, "chunks_embedded": 1, "retrieval_candidates": 1, "reranked_passages": 1, "total_time": 0.00043120000009366777, "export_timestamp": 1762567517.5853574, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762567517.5853584}
|
| 8 |
-
{"total_papers": 50, "processed_papers": 26, "skipped_papers": 24, "total_sections": 0, "total_chunks": 1335, "fallback_used_count": 26, "chunks_embedded": 1335, "retrieval_candidates": 15, "reranked_passages": 10, "total_time": 27.682769799999733, "export_timestamp": 1762568156.7731466, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762568156.773149}
|
| 9 |
-
{"total_papers": 50, "processed_papers": 25, "skipped_papers": 25, "total_sections": 0, "total_chunks": 1188, "fallback_used_count": 25, "chunks_embedded": 1188, "retrieval_candidates": 15, "reranked_passages": 10, "total_time": 22.988983400002326, "export_timestamp": 1762569208.669868, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762569208.6698701}
|
| 10 |
-
{"total_papers": 50, "processed_papers": 26, "skipped_papers": 24, "total_sections": 0, "total_chunks": 1331, "fallback_used_count": 26, "chunks_embedded": 1331, "retrieval_candidates": 15, "reranked_passages": 10, "total_time": 26.503664600000775, "export_timestamp": 1762569712.082386, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762569712.0823882}
|
| 11 |
-
{"total_papers": 50, "processed_papers": 14, "skipped_papers": 36, "total_sections": 0, "total_chunks": 798, "fallback_used_count": 14, "chunks_embedded": 798, "retrieval_candidates": 15, "reranked_passages": 10, "total_time": 17.43088020000141, "export_timestamp": 1762570954.1012478, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762570954.10125}
|
| 12 |
-
{"total_papers": 50, "processed_papers": 7, "skipped_papers": 43, "total_sections": 0, "total_chunks": 481, "fallback_used_count": 7, "chunks_embedded": 481, "retrieval_candidates": 15, "reranked_passages": 10, "total_time": 12.750454900000477, "export_timestamp": 1762571188.0552764, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762571188.0552785}
|
| 13 |
-
{"total_papers": 50, "processed_papers": 11, "skipped_papers": 39, "total_sections": 0, "total_chunks": 1159, "fallback_used_count": 11, "chunks_embedded": 1159, "retrieval_candidates": 15, "reranked_passages": 10, "total_time": 25.100210399999924, "export_timestamp": 1762571904.8335934, "agent_version": "1.1.0", "export_type": "minimal", "event": "processing_agent_complete", "timestamp": 1762571904.8335953}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pytest.ini
CHANGED
|
@@ -1,9 +1,7 @@
|
|
| 1 |
-
[
|
| 2 |
testpaths = tests
|
| 3 |
python_files = test_*.py
|
| 4 |
norecursedirs = scripts
|
| 5 |
-
collect_ignore = scripts
|
| 6 |
-
scripts/performance_test.py
|
| 7 |
markers =
|
| 8 |
unit: fast unit tests (<5s, testing individual functions)
|
| 9 |
integration: integration tests (5-30s, testing component interactions)
|
|
@@ -16,4 +14,4 @@ filterwarnings =
|
|
| 16 |
addopts =
|
| 17 |
--tb=short
|
| 18 |
-q
|
| 19 |
-
-m "not performance and not slow"
|
|
|
|
| 1 |
+
[pytest]
|
| 2 |
testpaths = tests
|
| 3 |
python_files = test_*.py
|
| 4 |
norecursedirs = scripts
|
|
|
|
|
|
|
| 5 |
markers =
|
| 6 |
unit: fast unit tests (<5s, testing individual functions)
|
| 7 |
integration: integration tests (5-30s, testing component interactions)
|
|
|
|
| 14 |
addopts =
|
| 15 |
--tb=short
|
| 16 |
-q
|
| 17 |
+
-m "not performance and not slow"
|
requirements.txt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a49236bc9b410686f12e2ba127aef84a31b9ef36a452762c3b8eee256f8a5c9d
|
| 3 |
+
size 271
|
src/necthrall_lite/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
# Necthrall Lite
|
|
|
|
|
|
src/necthrall_lite/api/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
# Necthrall Lite API schemas
|
|
|
|
|
|
src/necthrall_lite/api/schemas.py
DELETED
|
@@ -1,61 +0,0 @@
|
|
| 1 |
-
from pydantic import BaseModel, Field
|
| 2 |
-
from typing import List, Optional
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
class Citation(BaseModel):
|
| 6 |
-
"""Citation metadata for synthesized answers.
|
| 7 |
-
|
| 8 |
-
Fields:
|
| 9 |
-
index: int - The citation number [N] in the answer
|
| 10 |
-
paper_id: str - ID of the cited paper
|
| 11 |
-
text: str - The specific text excerpt being cited
|
| 12 |
-
credibility_score: Optional[int] - Credibility score of the paper (0-100)
|
| 13 |
-
"""
|
| 14 |
-
|
| 15 |
-
index: int = Field(..., ge=1, description="Citation number in the answer")
|
| 16 |
-
paper_id: str = Field(..., description="ID of the cited paper")
|
| 17 |
-
text: str = Field(..., max_length=500, description="Cited text excerpt")
|
| 18 |
-
credibility_score: Optional[int] = Field(
|
| 19 |
-
None, ge=0, le=100, description="Paper credibility score"
|
| 20 |
-
)
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
class SynthesisOutput(BaseModel):
|
| 24 |
-
"""Output from the synthesis agent.
|
| 25 |
-
|
| 26 |
-
Fields:
|
| 27 |
-
answer: str - Synthesized answer with inline [N] citations
|
| 28 |
-
citations: List[Citation] - Metadata for each citation
|
| 29 |
-
consensus_estimate: Optional[str] - Agreement level among sources
|
| 30 |
-
"""
|
| 31 |
-
|
| 32 |
-
answer: str = Field(
|
| 33 |
-
...,
|
| 34 |
-
min_length=50,
|
| 35 |
-
# max_length=5000,
|
| 36 |
-
description="Synthesized answer with citations",
|
| 37 |
-
)
|
| 38 |
-
citations: List[Citation] = Field(..., description="Citation metadata")
|
| 39 |
-
consensus_estimate: Optional[str] = Field(
|
| 40 |
-
None, description="Consensus level among sources"
|
| 41 |
-
)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
class CitationValidation(BaseModel):
|
| 45 |
-
"""Validation result for citations in synthesized answers.
|
| 46 |
-
|
| 47 |
-
Fields:
|
| 48 |
-
total_citations: int - Total unique citations found in the answer
|
| 49 |
-
valid_citations: int - Number of citations within valid range
|
| 50 |
-
invalid_citations: List[int] - List of out-of-range citation numbers
|
| 51 |
-
validation_passed: bool - Whether all citations are valid
|
| 52 |
-
error_details: List[str] - Specific error messages for invalid citations
|
| 53 |
-
"""
|
| 54 |
-
|
| 55 |
-
total_citations: int = Field(..., ge=0, description="Total unique citations found")
|
| 56 |
-
valid_citations: int = Field(..., ge=0, description="Number of valid citations")
|
| 57 |
-
invalid_citations: List[int] = Field(
|
| 58 |
-
..., description="Out-of-range citation numbers"
|
| 59 |
-
)
|
| 60 |
-
validation_passed: bool = Field(..., description="Overall validation result")
|
| 61 |
-
error_details: List[str] = Field(..., description="Specific error messages")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/necthrall_lite/core/prompts/synthesis_template.py
DELETED
|
@@ -1,159 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Synthesis prompt template for zero-hallucination citation verification.
|
| 3 |
-
|
| 4 |
-
This module provides a LangChain PromptTemplate for synthesizing scientific information
|
| 5 |
-
with strict citation grounding and contradiction handling.
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
-
from pydantic import BaseModel, Field
|
| 9 |
-
from typing import List, Optional
|
| 10 |
-
import re
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class Citation(BaseModel):
|
| 14 |
-
"""Citation metadata for synthesized answers."""
|
| 15 |
-
|
| 16 |
-
index: int = Field(..., ge=1, description="Citation number in the answer")
|
| 17 |
-
paper_id: str = Field(..., description="ID of the cited paper")
|
| 18 |
-
text: str = Field(..., max_length=500, description="Cited text excerpt")
|
| 19 |
-
credibility_score: Optional[int] = Field(
|
| 20 |
-
None, ge=0, le=100, description="Paper credibility score"
|
| 21 |
-
)
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
class SynthesisOutput(BaseModel):
|
| 25 |
-
"""Output from the synthesis agent."""
|
| 26 |
-
|
| 27 |
-
answer: str = Field(
|
| 28 |
-
...,
|
| 29 |
-
min_length=50,
|
| 30 |
-
max_length=2500,
|
| 31 |
-
description="Synthesized answer with citations",
|
| 32 |
-
)
|
| 33 |
-
citations: List[Citation] = Field(..., description="Citation metadata")
|
| 34 |
-
consensus_estimate: Optional[str] = Field(
|
| 35 |
-
None, description="Consensus level among sources"
|
| 36 |
-
)
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def validate_passage_numbering(formatted_passages: str) -> None:
|
| 40 |
-
"""
|
| 41 |
-
Validate that passages are numbered consecutively from 1 without duplicates.
|
| 42 |
-
|
| 43 |
-
Args:
|
| 44 |
-
formatted_passages: String containing passages with [N] numbering
|
| 45 |
-
|
| 46 |
-
Raises:
|
| 47 |
-
ValueError: If numbering is invalid
|
| 48 |
-
"""
|
| 49 |
-
numbers = re.findall(r"\[(\d+)\]", formatted_passages)
|
| 50 |
-
if not numbers:
|
| 51 |
-
raise ValueError("No passage numbering found in formatted_passages")
|
| 52 |
-
|
| 53 |
-
unique_nums = sorted(set(int(n) for n in numbers))
|
| 54 |
-
if len(numbers) != len(unique_nums):
|
| 55 |
-
raise ValueError("Passage numbering contains duplicates")
|
| 56 |
-
|
| 57 |
-
expected = list(range(1, len(unique_nums) + 1))
|
| 58 |
-
if unique_nums != expected:
|
| 59 |
-
raise ValueError(
|
| 60 |
-
f"Passage numbering must be consecutive from 1 to {len(unique_nums)} without duplicates. "
|
| 61 |
-
f"Found: {unique_nums}"
|
| 62 |
-
)
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def create_synthesis_prompt(
|
| 66 |
-
query: str, formatted_passages: str, contradiction_context: str
|
| 67 |
-
) -> PromptTemplate:
|
| 68 |
-
"""
|
| 69 |
-
Create a LangChain PromptTemplate for scientific synthesis with citation verification.
|
| 70 |
-
|
| 71 |
-
Args:
|
| 72 |
-
query: The scientific question to answer
|
| 73 |
-
formatted_passages: Numbered passages string with [1], [2], etc.
|
| 74 |
-
contradiction_context: Description of detected contradictions
|
| 75 |
-
|
| 76 |
-
Returns:
|
| 77 |
-
PromptTemplate configured for synthesis with output parsing
|
| 78 |
-
|
| 79 |
-
Raises:
|
| 80 |
-
ValueError: If passage numbering is invalid
|
| 81 |
-
"""
|
| 82 |
-
# Handle missing passages
|
| 83 |
-
if not formatted_passages.strip():
|
| 84 |
-
formatted_passages = (
|
| 85 |
-
"[1] No passages provided. Please provide evidence for analysis."
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
# Validate passage numbering
|
| 89 |
-
try:
|
| 90 |
-
validate_passage_numbering(formatted_passages)
|
| 91 |
-
except ValueError as e:
|
| 92 |
-
# For now, raise; could fallback to simplified prompt in future
|
| 93 |
-
raise e
|
| 94 |
-
|
| 95 |
-
# Create output parser
|
| 96 |
-
parser = PydanticOutputParser(pydantic_object=SynthesisOutput)
|
| 97 |
-
|
| 98 |
-
# Get format instructions
|
| 99 |
-
format_instructions = parser.get_format_instructions()
|
| 100 |
-
|
| 101 |
-
# System prompt with role, rules, and few-shot examples
|
| 102 |
-
# Prompt engineering: Clear rules prevent hallucination, few-shot shows expected format
|
| 103 |
-
system_prompt = """You are a scientific research assistant specializing in citation verification and evidence synthesis.
|
| 104 |
-
|
| 105 |
-
CRITICAL RULES - FOLLOW THESE STRICTLY:
|
| 106 |
-
1. Every factual claim MUST have a citation [N] referencing exactly passage N from the provided passages.
|
| 107 |
-
2. NEVER generate citations that don't exist in the provided passages - this creates hallucinations.
|
| 108 |
-
3. If evidence contradicts, present BOTH viewpoints with credibility context from the passages.
|
| 109 |
-
4. Generate consensus estimates based on agreement patterns: "High consensus", "Moderate consensus", "Low consensus", or "Insufficient evidence".
|
| 110 |
-
5. Refuse speculation - only use information from provided passages.
|
| 111 |
-
6. Structure your answer with clear sections: introduction, body, contradictions (if any), conclusion.
|
| 112 |
-
|
| 113 |
-
FEW-SHOT EXAMPLE:
|
| 114 |
-
|
| 115 |
-
Query: What is the effect of exercise on blood pressure?
|
| 116 |
-
|
| 117 |
-
Passages:
|
| 118 |
-
[1] High-credibility study: Regular aerobic exercise reduces systolic blood pressure by 5-10 mmHg in hypertensive patients.
|
| 119 |
-
[2] Medium-credibility study: Resistance training shows no significant effect on blood pressure.
|
| 120 |
-
|
| 121 |
-
Contradictions: Studies disagree on exercise type effectiveness.
|
| 122 |
-
|
| 123 |
-
Expected JSON Output:
|
| 124 |
-
{{
|
| 125 |
-
"answer": "Exercise can influence blood pressure through different mechanisms. Regular aerobic exercise has been shown to reduce systolic blood pressure by 5-10 mmHg in hypertensive patients [1]. However, resistance training appears to have no significant effect on blood pressure [2].\\n\\nWhile aerobic exercise demonstrates clear benefits, the evidence for resistance training is inconclusive. Consider consulting healthcare providers for personalized recommendations.",
|
| 126 |
-
"citations": [
|
| 127 |
-
{{"index": 1, "paper_id": "study_a", "text": "Regular aerobic exercise reduces systolic blood pressure by 5-10 mmHg", "credibility_score": 85}},
|
| 128 |
-
{{"index": 2, "paper_id": "study_b", "text": "Resistance training shows no significant effect", "credibility_score": 60}}
|
| 129 |
-
],
|
| 130 |
-
"consensus_estimate": "Moderate consensus"
|
| 131 |
-
}}
|
| 132 |
-
|
| 133 |
-
REMEMBER: Only cite passages that exist. If no relevant information, state "Insufficient evidence"."""
|
| 134 |
-
|
| 135 |
-
# Human prompt template
|
| 136 |
-
# Uses f-string style but with LangChain variables for flexibility
|
| 137 |
-
human_template = f"""
|
| 138 |
-
Scientific Question: {{query}}
|
| 139 |
-
|
| 140 |
-
Provided Passages:
|
| 141 |
-
{{formatted_passages}}
|
| 142 |
-
|
| 143 |
-
Contradiction Context: {{contradiction_context}}
|
| 144 |
-
|
| 145 |
-
{{format_instructions}}
|
| 146 |
-
|
| 147 |
-
Answer the question using ONLY the provided passages. Every claim must be cited [N]."""
|
| 148 |
-
|
| 149 |
-
# Combine prompts (system context + human template)
|
| 150 |
-
full_template = system_prompt + "\n\n" + human_template
|
| 151 |
-
|
| 152 |
-
# Create PromptTemplate with partial variables for format instructions
|
| 153 |
-
prompt = PromptTemplate(
|
| 154 |
-
template=full_template,
|
| 155 |
-
input_variables=["query", "formatted_passages", "contradiction_context"],
|
| 156 |
-
partial_variables={"format_instructions": format_instructions},
|
| 157 |
-
)
|
| 158 |
-
|
| 159 |
-
return prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/necthrall_lite/services/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
# Necthrall Lite services
|
|
|
|
|
|
src/necthrall_lite/services/synthesis_service.py
DELETED
|
@@ -1,406 +0,0 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
-
import json
|
| 3 |
-
import time
|
| 4 |
-
from typing import List, Dict, Optional
|
| 5 |
-
from loguru import logger
|
| 6 |
-
import os
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
from utils.llm_client import get_safe_model_name
|
| 10 |
-
|
| 11 |
-
from ..api.schemas import SynthesisOutput, Citation, CitationValidation
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
class SynthesisAgent:
|
| 15 |
-
"""
|
| 16 |
-
Agent for synthesizing evidence-backed answers from scientific paper passages.
|
| 17 |
-
|
| 18 |
-
Uses LangChain's ChatGoogleGenerativeAI with temperature 0.3 for controlled creativity
|
| 19 |
-
while maintaining strict factual grounding. Every claim is supported by inline citations.
|
| 20 |
-
|
| 21 |
-
Features:
|
| 22 |
-
- Generates 300-500 word answers with inline [N] citations
|
| 23 |
-
- Handles contradictory evidence by presenting both sides
|
| 24 |
-
- Integrates credibility scores to prioritize high-quality sources
|
| 25 |
-
- Formats consensus estimates based on source agreement
|
| 26 |
-
- Refuses to answer if evidence is insufficient
|
| 27 |
-
|
| 28 |
-
Usage example:
|
| 29 |
-
agent = SynthesisAgent()
|
| 30 |
-
result = await agent.synthesize(
|
| 31 |
-
query="What are the effects of intermittent fasting?",
|
| 32 |
-
passages=[{"content": "...", "paper_id": "p1", ...}],
|
| 33 |
-
credibility_scores=[{"paper_id": "p1", "score": 85, ...}],
|
| 34 |
-
contradictions=[]
|
| 35 |
-
)
|
| 36 |
-
"""
|
| 37 |
-
|
| 38 |
-
def __init__(self, temperature: float = 0.3, max_tokens: int = 2500):
|
| 39 |
-
self.temperature = temperature
|
| 40 |
-
self.max_tokens = max_tokens
|
| 41 |
-
|
| 42 |
-
# Initialize LLMs
|
| 43 |
-
self.primary_llm = ChatGoogleGenerativeAI(
|
| 44 |
-
model=os.getenv("LLM_MODEL_PRIMARY"),
|
| 45 |
-
temperature=temperature,
|
| 46 |
-
max_tokens=max_tokens,
|
| 47 |
-
)
|
| 48 |
-
self.fallback_llm = ChatGroq(
|
| 49 |
-
model=os.getenv("LLM_MODEL_FALLBACK"),
|
| 50 |
-
temperature=temperature,
|
| 51 |
-
max_tokens=max_tokens,
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
-
async def _invoke_llm_async(self, llm, messages, provider_name) -> Dict:
|
| 55 |
-
"""Invoke LLM asynchronously with logging and error handling."""
|
| 56 |
-
try:
|
| 57 |
-
logger.info(
|
| 58 |
-
json.dumps({"event": "llm_call_start", "provider": provider_name})
|
| 59 |
-
)
|
| 60 |
-
start_time = time.time()
|
| 61 |
-
response = await llm.ainvoke(messages)
|
| 62 |
-
end_time = time.time()
|
| 63 |
-
execution_time = end_time - start_time
|
| 64 |
-
logger.info(
|
| 65 |
-
json.dumps(
|
| 66 |
-
{
|
| 67 |
-
"event": "llm_call_success",
|
| 68 |
-
"provider": provider_name,
|
| 69 |
-
"execution_time": execution_time,
|
| 70 |
-
}
|
| 71 |
-
)
|
| 72 |
-
)
|
| 73 |
-
model_id = get_safe_model_name(llm)
|
| 74 |
-
return {
|
| 75 |
-
"content": response.content,
|
| 76 |
-
"model_used": f"{provider_name}/{model_id}",
|
| 77 |
-
"execution_time": execution_time,
|
| 78 |
-
}
|
| 79 |
-
except Exception as e:
|
| 80 |
-
logger.warning(
|
| 81 |
-
json.dumps(
|
| 82 |
-
{
|
| 83 |
-
"event": "llm_call_failure",
|
| 84 |
-
"provider": provider_name,
|
| 85 |
-
"error": str(e),
|
| 86 |
-
}
|
| 87 |
-
)
|
| 88 |
-
)
|
| 89 |
-
raise e
|
| 90 |
-
|
| 91 |
-
def _build_synthesis_prompt(
|
| 92 |
-
self,
|
| 93 |
-
query: str,
|
| 94 |
-
passages: List[Dict],
|
| 95 |
-
credibility_scores: List[Dict],
|
| 96 |
-
contradictions: Optional[List[Dict]] = None,
|
| 97 |
-
) -> List:
|
| 98 |
-
"""Build the synthesis prompt with passages and instructions."""
|
| 99 |
-
# Create credibility lookup
|
| 100 |
-
cred_lookup = {cs["paper_id"]: cs for cs in credibility_scores}
|
| 101 |
-
|
| 102 |
-
# Format passages with credibility
|
| 103 |
-
formatted_passages = []
|
| 104 |
-
for i, passage in enumerate(passages, 1):
|
| 105 |
-
cred = cred_lookup.get(passage["paper_id"], {})
|
| 106 |
-
score = cred.get("score", 0)
|
| 107 |
-
tier = cred.get("tier", "low")
|
| 108 |
-
formatted_passages.append(
|
| 109 |
-
f"Passage {i} (Paper ID: {passage['paper_id']}, Credibility: {score}/100, Tier: {tier}):\n"
|
| 110 |
-
f"Section: {passage.get('section', 'unknown')}\n"
|
| 111 |
-
f"Content: {passage['content']}\n"
|
| 112 |
-
)
|
| 113 |
-
|
| 114 |
-
passages_text = "\n".join(formatted_passages)
|
| 115 |
-
|
| 116 |
-
# Format contradictions if any
|
| 117 |
-
contradictions_text = ""
|
| 118 |
-
if contradictions:
|
| 119 |
-
contra_list = []
|
| 120 |
-
for contra in contradictions:
|
| 121 |
-
contra_list.append(
|
| 122 |
-
f"- Topic: {contra['topic']}\n"
|
| 123 |
-
f" Claim 1 (Paper {contra['claim_1']['paper_id']}): {contra['claim_1']['text']}\n"
|
| 124 |
-
f" Claim 2 (Paper {contra['claim_2']['paper_id']}): {contra['claim_2']['text']}\n"
|
| 125 |
-
f" Severity: {contra['severity']}\n"
|
| 126 |
-
)
|
| 127 |
-
contradictions_text = "Detected Contradictions:\n" + "\n".join(contra_list)
|
| 128 |
-
|
| 129 |
-
system_prompt = """You are a scientific research assistant synthesizing evidence-backed answers.
|
| 130 |
-
|
| 131 |
-
TASK: Generate a 300-500 word answer to the query using ONLY the provided passages.
|
| 132 |
-
- Use inline citations [N] for EVERY claim, where N corresponds to the passage number.
|
| 133 |
-
- Prioritize high-credibility sources (higher scores, 'high'/'medium' tier).
|
| 134 |
-
- Present contradictory evidence objectively, showing both sides.
|
| 135 |
-
- Calculate consensus: "High consensus" (>80% agreement), "Moderate consensus" (50-80%), "Low consensus" (<50%), "Conflicting evidence".
|
| 136 |
-
- If evidence is insufficient or contradictory without resolution, refuse to answer definitively.
|
| 137 |
-
|
| 138 |
-
FORMAT:
|
| 139 |
-
- Answer in 300-500 words
|
| 140 |
-
- Use [N] citations inline
|
| 141 |
-
- End with consensus estimate
|
| 142 |
-
- Be factual, no hallucinations
|
| 143 |
-
|
| 144 |
-
OUTPUT FORMAT:
|
| 145 |
-
Answer text with [N] citations.
|
| 146 |
-
|
| 147 |
-
Consensus: [estimate]"""
|
| 148 |
-
|
| 149 |
-
user_prompt = f"""Query: {query}
|
| 150 |
-
|
| 151 |
-
Passages:
|
| 152 |
-
{passages_text}
|
| 153 |
-
|
| 154 |
-
{contradictions_text}
|
| 155 |
-
|
| 156 |
-
Please synthesize an answer following the instructions."""
|
| 157 |
-
|
| 158 |
-
return [
|
| 159 |
-
SystemMessage(content=system_prompt),
|
| 160 |
-
HumanMessage(content=user_prompt),
|
| 161 |
-
]
|
| 162 |
-
|
| 163 |
-
def _parse_llm_response(
|
| 164 |
-
self, response_content: str, passages: List[Dict]
|
| 165 |
-
) -> SynthesisOutput:
|
| 166 |
-
"""Parse LLM response into SynthesisOutput format."""
|
| 167 |
-
# Extract answer and consensus
|
| 168 |
-
lines = response_content.strip().split("\n")
|
| 169 |
-
answer_lines = []
|
| 170 |
-
consensus = None
|
| 171 |
-
|
| 172 |
-
for line in lines:
|
| 173 |
-
if line.lower().startswith("consensus:"):
|
| 174 |
-
consensus = line.split(":", 1)[1].strip()
|
| 175 |
-
else:
|
| 176 |
-
answer_lines.append(line)
|
| 177 |
-
|
| 178 |
-
answer = "\n".join(answer_lines).strip()
|
| 179 |
-
|
| 180 |
-
# Extract citations from answer
|
| 181 |
-
citations = []
|
| 182 |
-
import re
|
| 183 |
-
|
| 184 |
-
citation_matches = re.findall(r"\[(\d+)\]", answer)
|
| 185 |
-
|
| 186 |
-
for match in citation_matches:
|
| 187 |
-
idx = int(match)
|
| 188 |
-
if 1 <= idx <= len(passages):
|
| 189 |
-
passage = passages[idx - 1]
|
| 190 |
-
citations.append(
|
| 191 |
-
Citation(
|
| 192 |
-
index=idx,
|
| 193 |
-
paper_id=passage["paper_id"],
|
| 194 |
-
text=(
|
| 195 |
-
passage["content"][:200] + "..."
|
| 196 |
-
if len(passage["content"]) > 200
|
| 197 |
-
else passage["content"]
|
| 198 |
-
),
|
| 199 |
-
credibility_score=None, # Will be filled later if needed
|
| 200 |
-
)
|
| 201 |
-
)
|
| 202 |
-
|
| 203 |
-
# Remove duplicates
|
| 204 |
-
seen = set()
|
| 205 |
-
unique_citations = []
|
| 206 |
-
for cit in citations:
|
| 207 |
-
if cit.index not in seen:
|
| 208 |
-
seen.add(cit.index)
|
| 209 |
-
unique_citations.append(cit)
|
| 210 |
-
|
| 211 |
-
return SynthesisOutput(
|
| 212 |
-
answer=answer, citations=unique_citations, consensus_estimate=consensus
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
def _validate_input(
|
| 216 |
-
self,
|
| 217 |
-
query: str,
|
| 218 |
-
passages: List[Dict],
|
| 219 |
-
credibility_scores: List[Dict],
|
| 220 |
-
contradictions: Optional[List[Dict]] = None,
|
| 221 |
-
) -> None:
|
| 222 |
-
"""Validate input parameters."""
|
| 223 |
-
if not query or not query.strip():
|
| 224 |
-
raise ValueError("Query cannot be empty")
|
| 225 |
-
|
| 226 |
-
if not passages:
|
| 227 |
-
raise ValueError("At least one passage required")
|
| 228 |
-
|
| 229 |
-
if len(passages) > 10:
|
| 230 |
-
raise ValueError("Maximum 10 passages supported")
|
| 231 |
-
|
| 232 |
-
# Check passages have required fields
|
| 233 |
-
for i, p in enumerate(passages):
|
| 234 |
-
if not isinstance(p, dict):
|
| 235 |
-
raise ValueError(f"Passage {i} must be a dictionary")
|
| 236 |
-
if "content" not in p or "paper_id" not in p:
|
| 237 |
-
raise ValueError(
|
| 238 |
-
f"Passage {i} missing required fields: content, paper_id"
|
| 239 |
-
)
|
| 240 |
-
|
| 241 |
-
# Check credibility scores
|
| 242 |
-
if not credibility_scores:
|
| 243 |
-
logger.warning("No credibility scores provided")
|
| 244 |
-
|
| 245 |
-
@staticmethod
|
| 246 |
-
def validate_citations(
|
| 247 |
-
synthesized_answer: str, passages: List[Dict]
|
| 248 |
-
) -> CitationValidation:
|
| 249 |
-
"""
|
| 250 |
-
Validate citations in a synthesized answer against available passages.
|
| 251 |
-
|
| 252 |
-
Extracts all [N] citation patterns from the answer text, validates that each
|
| 253 |
-
citation number N is within the valid range (1 to len(passages)), and generates
|
| 254 |
-
detailed error reports for invalid citations.
|
| 255 |
-
|
| 256 |
-
Args:
|
| 257 |
-
synthesized_answer: The answer text containing [N] citation patterns
|
| 258 |
-
passages: List of passage dictionaries that citations should reference
|
| 259 |
-
|
| 260 |
-
Returns:
|
| 261 |
-
CitationValidation object with validation results and error details
|
| 262 |
-
|
| 263 |
-
Raises:
|
| 264 |
-
ValueError: If passages list is None or empty
|
| 265 |
-
|
| 266 |
-
Examples:
|
| 267 |
-
>>> passages = [{"content": "test", "paper_id": "p1"}, {"content": "test2", "paper_id": "p2"}]
|
| 268 |
-
>>> result = SynthesisAgent.validate_citations("Answer with [1] and [2]", passages)
|
| 269 |
-
>>> result.validation_passed
|
| 270 |
-
True
|
| 271 |
-
|
| 272 |
-
>>> result = SynthesisAgent.validate_citations("Answer with [3]", passages)
|
| 273 |
-
>>> result.validation_passed
|
| 274 |
-
False
|
| 275 |
-
"""
|
| 276 |
-
import re
|
| 277 |
-
|
| 278 |
-
# Validate input
|
| 279 |
-
if passages is None:
|
| 280 |
-
raise ValueError("Passages list cannot be None")
|
| 281 |
-
if not passages:
|
| 282 |
-
raise ValueError("Passages list cannot be empty")
|
| 283 |
-
|
| 284 |
-
num_passages = len(passages)
|
| 285 |
-
|
| 286 |
-
# Compile regex pattern for performance
|
| 287 |
-
citation_pattern = re.compile(r"\[\s*(\d+)\s*\]")
|
| 288 |
-
|
| 289 |
-
# Extract all citation matches
|
| 290 |
-
matches = citation_pattern.findall(synthesized_answer)
|
| 291 |
-
|
| 292 |
-
# Convert to integers and get unique citations
|
| 293 |
-
citation_numbers = set()
|
| 294 |
-
for match in matches:
|
| 295 |
-
try:
|
| 296 |
-
citation_numbers.add(int(match))
|
| 297 |
-
except ValueError:
|
| 298 |
-
logger.warning(f"Invalid citation format: [{match}] - not a number")
|
| 299 |
-
continue
|
| 300 |
-
|
| 301 |
-
total_citations = len(citation_numbers)
|
| 302 |
-
|
| 303 |
-
# Validate each citation
|
| 304 |
-
valid_citations = 0
|
| 305 |
-
invalid_citations = []
|
| 306 |
-
error_details = []
|
| 307 |
-
|
| 308 |
-
for citation_num in sorted(citation_numbers):
|
| 309 |
-
if 1 <= citation_num <= num_passages:
|
| 310 |
-
valid_citations += 1
|
| 311 |
-
else:
|
| 312 |
-
invalid_citations.append(citation_num)
|
| 313 |
-
error_details.append(
|
| 314 |
-
f"Citation [{citation_num}] references non-existent passage "
|
| 315 |
-
f"(valid range: 1-{num_passages})"
|
| 316 |
-
)
|
| 317 |
-
|
| 318 |
-
validation_passed = len(invalid_citations) == 0
|
| 319 |
-
|
| 320 |
-
# Log validation results
|
| 321 |
-
logger.info(
|
| 322 |
-
json.dumps(
|
| 323 |
-
{
|
| 324 |
-
"event": "citation_validation",
|
| 325 |
-
"total_citations": total_citations,
|
| 326 |
-
"valid_citations": valid_citations,
|
| 327 |
-
"invalid_citations": len(invalid_citations),
|
| 328 |
-
"validation_passed": validation_passed,
|
| 329 |
-
}
|
| 330 |
-
)
|
| 331 |
-
)
|
| 332 |
-
|
| 333 |
-
return CitationValidation(
|
| 334 |
-
total_citations=total_citations,
|
| 335 |
-
valid_citations=valid_citations,
|
| 336 |
-
invalid_citations=invalid_citations,
|
| 337 |
-
validation_passed=validation_passed,
|
| 338 |
-
error_details=error_details,
|
| 339 |
-
)
|
| 340 |
-
|
| 341 |
-
async def synthesize(
|
| 342 |
-
self,
|
| 343 |
-
query: str,
|
| 344 |
-
passages: List[Dict],
|
| 345 |
-
credibility_scores: List[Dict],
|
| 346 |
-
contradictions: Optional[List[Dict]] = None,
|
| 347 |
-
) -> SynthesisOutput:
|
| 348 |
-
"""
|
| 349 |
-
Synthesize an evidence-backed answer from passages.
|
| 350 |
-
|
| 351 |
-
Args:
|
| 352 |
-
query: User's scientific question
|
| 353 |
-
passages: Retrieved text passages with metadata
|
| 354 |
-
credibility_scores: Paper credibility assessments
|
| 355 |
-
contradictions: Optional detected contradictory claims
|
| 356 |
-
|
| 357 |
-
Returns:
|
| 358 |
-
SynthesisOutput with answer, citations, and consensus
|
| 359 |
-
|
| 360 |
-
Raises:
|
| 361 |
-
ValueError: If input validation fails
|
| 362 |
-
Exception: If both LLMs fail
|
| 363 |
-
"""
|
| 364 |
-
logger.info(
|
| 365 |
-
"Starting synthesis",
|
| 366 |
-
extra={"query_length": len(query), "passage_count": len(passages)},
|
| 367 |
-
)
|
| 368 |
-
|
| 369 |
-
# Validate input
|
| 370 |
-
self._validate_input(query, passages, credibility_scores, contradictions)
|
| 371 |
-
|
| 372 |
-
# Build prompt
|
| 373 |
-
messages = self._build_synthesis_prompt(
|
| 374 |
-
query, passages, credibility_scores, contradictions
|
| 375 |
-
)
|
| 376 |
-
|
| 377 |
-
# Try primary LLM
|
| 378 |
-
try:
|
| 379 |
-
response = await self._invoke_llm_async(
|
| 380 |
-
self.primary_llm, messages, "gemini"
|
| 381 |
-
)
|
| 382 |
-
except Exception as e:
|
| 383 |
-
logger.info("Primary LLM failed, trying fallback", extra={"error": str(e)})
|
| 384 |
-
try:
|
| 385 |
-
response = await self._invoke_llm_async(
|
| 386 |
-
self.fallback_llm, messages, "groq"
|
| 387 |
-
)
|
| 388 |
-
except Exception as e2:
|
| 389 |
-
logger.error(
|
| 390 |
-
"Both LLMs failed",
|
| 391 |
-
extra={"primary_error": str(e), "fallback_error": str(e2)},
|
| 392 |
-
)
|
| 393 |
-
raise e2
|
| 394 |
-
|
| 395 |
-
# Parse response
|
| 396 |
-
result = self._parse_llm_response(response["content"], passages)
|
| 397 |
-
|
| 398 |
-
logger.info(
|
| 399 |
-
"Synthesis completed",
|
| 400 |
-
extra={
|
| 401 |
-
"answer_length": len(result.answer),
|
| 402 |
-
"citation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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import time
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@pytest.fixture(autouse=True)
|
| 7 |
+
def set_test_env():
|
| 8 |
+
""" "Set minimal test environment variables for config validation"""
|
| 9 |
+
os.environ["SEMANTIC_SCHOLAR_API_KEY"] = "test_key"
|
| 10 |
+
os.environ["GOOGLE_API_KEY"] = "test_key"
|
| 11 |
+
os.environ["GROQ_API_KEY"] = "test_key"
|
| 12 |
+
os.environ["QUERY_OPTIMIZATION_MODEL"] = "test_model"
|
| 13 |
+
os.environ["SYNTHESIS_MODEL"] = "test_model"
|
| 14 |
+
os.environ["SKIP_DOTENV_LOADER"] = "1"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.fixture
|
| 18 |
+
def app():
|
| 19 |
+
from main import app
|
| 20 |
+
|
| 21 |
+
return app
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.mark.integration
|
| 25 |
+
def test_health_endpoint(app):
|
| 26 |
+
""" "Test health endpoint returns 200 status"""
|
| 27 |
+
from fastapi.testclient import TestClient
|
| 28 |
+
|
| 29 |
+
client = TestClient(app)
|
| 30 |
+
response = client.get("/health")
|
| 31 |
+
|
| 32 |
+
assert response.status_code == 200
|
| 33 |
+
data = response.json()
|
| 34 |
+
assert data["status"] == "healthy"
|
| 35 |
+
assert "timestamp" in data
|
| 36 |
+
assert data["version"] == "3.0.0-mvp"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.integration
|
| 40 |
+
def test_root_endpoint(app):
|
| 41 |
+
""" "Test root endpoint returns 200 status with API documentation links"""
|
| 42 |
+
from fastapi.testclient import TestClient
|
| 43 |
+
|
| 44 |
+
client = TestClient(app)
|
| 45 |
+
response = client.get("/")
|
| 46 |
+
|
| 47 |
+
assert response.status_code == 200
|
| 48 |
+
data = response.json()
|
| 49 |
+
assert "message" in data
|
| 50 |
+
assert data["docs"] == "/docs"
|
| 51 |
+
assert data["health"] == "/health"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@pytest.mark.integration
|
| 55 |
+
def test_health_endpoint_response_time(app):
|
| 56 |
+
""" "Test health endpoint response time < 100ms"""
|
| 57 |
+
from fastapi.testclient import TestClient
|
| 58 |
+
|
| 59 |
+
client = TestClient(app)
|
| 60 |
+
start_time = time.time()
|
| 61 |
+
response = client.get("/health")
|
| 62 |
+
end_time = time.time()
|
| 63 |
+
|
| 64 |
+
response_time_ms = (end_time - start_time) * 1000
|
| 65 |
+
assert response_time_ms < 100
|
| 66 |
+
assert response.status_code == 200
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@pytest.mark.integration
|
| 70 |
+
def test_startup_event_logs_configuration(app):
|
| 71 |
+
""" "Test startup event logs configuration successfully"""
|
| 72 |
+
# This test verifies that the app can start without config validation errors
|
| 73 |
+
# In a real scenario, we'd check logs, but for integration test, we ensure no exceptions
|
| 74 |
+
from fastapi.testclient import TestClient
|
| 75 |
+
|
| 76 |
+
client = TestClient(app)
|
| 77 |
+
response = client.get("/health")
|
| 78 |
+
assert response.status_code == 200
|
tests/performance/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Package marker for unit tests
|
tests/unit/test_config.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 test_config_missing_semantic_scholar_key():
|
| 30 |
+
"""Missing Semantic Scholar key should raise ValueError with help URL."""
|
| 31 |
+
env = {
|
| 32 |
+
"GOOGLE_API_KEY": "fake_google",
|
| 33 |
+
"GROQ_API_KEY": "fake_groq",
|
| 34 |
+
}
|
| 35 |
+
with pytest.raises(ValueError) as exc_info:
|
| 36 |
+
_load_config_module_from_path(env)
|
| 37 |
+
|
| 38 |
+
msg = str(exc_info.value)
|
| 39 |
+
assert "SEMANTIC_SCHOLAR_API_KEY" in msg
|
| 40 |
+
assert "semanticscholar.org" in msg
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@pytest.mark.unit
|
| 44 |
+
def test_config_missing_google_key():
|
| 45 |
+
"""Missing GOOGLE_API_KEY should raise ValueError with help URL."""
|
| 46 |
+
env = {
|
| 47 |
+
"SEMANTIC_SCHOLAR_API_KEY": "fake_ss",
|
| 48 |
+
"GROQ_API_KEY": "fake_groq",
|
| 49 |
+
}
|
| 50 |
+
with pytest.raises(ValueError) as exc_info:
|
| 51 |
+
_load_config_module_from_path(env)
|
| 52 |
+
|
| 53 |
+
msg = str(exc_info.value)
|
| 54 |
+
assert "GOOGLE_API_KEY" in msg or "ai.google.dev" in msg
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@pytest.mark.unit
|
| 58 |
+
def test_config_missing_groq_key():
|
| 59 |
+
"""Missing GROQ_API_KEY should raise ValueError with help URL."""
|
| 60 |
+
env = {
|
| 61 |
+
"SEMANTIC_SCHOLAR_API_KEY": "fake_ss",
|
| 62 |
+
"GOOGLE_API_KEY": "fake_google",
|
| 63 |
+
}
|
| 64 |
+
with pytest.raises(ValueError) as exc_info:
|
| 65 |
+
_load_config_module_from_path(env)
|
| 66 |
+
|
| 67 |
+
msg = str(exc_info.value)
|
| 68 |
+
assert "GROQ_API_KEY" in msg or "console.groq.com" in msg
|
| 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 |
+
"GOOGLE_API_KEY": "fake_google_key",
|
| 77 |
+
"GROQ_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 |
+
assert config.SEMANTIC_SCHOLAR_API_KEY == "fake_ss_key"
|
| 84 |
+
assert config.GOOGLE_API_KEY == "fake_google_key"
|
| 85 |
+
assert config.GROQ_API_KEY == "fake_groq_key"
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@pytest.mark.unit
|
| 89 |
+
def test_custom_model_overrides():
|
| 90 |
+
"""Custom model names from env vars override the defaults."""
|
| 91 |
+
env = {
|
| 92 |
+
"SEMANTIC_SCHOLAR_API_KEY": "fake_ss_key",
|
| 93 |
+
"GOOGLE_API_KEY": "fake_google_key",
|
| 94 |
+
"GROQ_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"
|
tests/unit/test_state.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
from pydantic import ValidationError
|
| 6 |
+
|
| 7 |
+
from models.state import State
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@pytest.mark.unit
|
| 11 |
+
def test_state_minimal_init():
|
| 12 |
+
s = State(query="test query")
|
| 13 |
+
assert s.query == "test query"
|
| 14 |
+
# request_id present and looks like a uuid string
|
| 15 |
+
assert isinstance(s.request_id, str)
|
| 16 |
+
assert re.match(r"[0-9a-fA-F\-]{36}", s.request_id)
|
| 17 |
+
assert isinstance(s.timestamp, datetime)
|
| 18 |
+
# Optional fields default to None or empty list for errors
|
| 19 |
+
assert s.optimized_query is None
|
| 20 |
+
assert s.papers is None
|
| 21 |
+
assert s.errors == []
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.mark.unit
|
| 25 |
+
def test_progressive_updates():
|
| 26 |
+
s = State(query="q")
|
| 27 |
+
s.update_fields(optimized_query="q optimized")
|
| 28 |
+
assert s.optimized_query == "q optimized"
|
| 29 |
+
|
| 30 |
+
# simulate retrieval
|
| 31 |
+
papers = [{"id": "p1", "title": "Paper 1"}]
|
| 32 |
+
s.update_fields(papers=papers)
|
| 33 |
+
assert s.papers == papers
|
| 34 |
+
|
| 35 |
+
# ranking
|
| 36 |
+
ranked = [{"id": "p1", "score": 0.9}]
|
| 37 |
+
s.update_fields(ranked_papers=ranked)
|
| 38 |
+
assert s.ranked_papers == ranked
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@pytest.mark.unit
|
| 42 |
+
def test_invalid_types_raise():
|
| 43 |
+
with pytest.raises(ValidationError):
|
| 44 |
+
# query is required and must be a str; passing an int should fail
|
| 45 |
+
State(query=123) # type: ignore
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@pytest.mark.unit
|
| 49 |
+
def test_error_tracking_and_defaults():
|
| 50 |
+
s = State(query="err")
|
| 51 |
+
s.append_error("first error")
|
| 52 |
+
assert s.errors == ["first error"]
|
| 53 |
+
|
| 54 |
+
# defaults regenerated per instance
|
| 55 |
+
s2 = State(query="err2")
|
| 56 |
+
assert s2.request_id != s.request_id
|
utils/embedding_manager.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|
utils/error_handling.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|
utils/llm_client.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|
utils/logging_decorator.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|
utils/logging_setup.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|
utils/openalex_client.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|
utils/pipeline_logging.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|
utils/scihub_fallback.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|
utils/section_detector.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|
utils/spacy_error_handler.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
|
|
|
|
|
|