Adam Cseresznye commited on
Commit ·
1a2c92d
1
Parent(s): 31e0e3b
Add golden dataset generation and citation evaluation tests
Browse files- .deepeval/.deepeval_telemetry.txt +3 -0
- README.md +3 -3
- agents/synthesis_agent.py +2 -2
- main.py +1 -1
- pytest.ini +1 -0
- requirements.txt +2 -2
- scripts/generate_golden_dataset.py +147 -0
- tests/citation_metrics.py +108 -0
- tests/data/golden_dataset.json +54 -0
- tests/eval_config.py +81 -0
- tests/test_necthrall_evaluation.py +114 -0
- tests/test_necthrall_real.py +194 -0
- tests/unit/test_acquisition_agent.py +30 -13
- tests/unit/test_pdf_extractor.py +61 -28
- tests/unit/test_synthesis_agent.py +0 -1
- ui/pages.py +4 -3
.deepeval/.deepeval_telemetry.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a66954ec9a99cd1137267a926de44d1d20e0a39a2840dc792b9044e2a8434732
|
| 3 |
+
size 137
|
README.md
CHANGED
|
@@ -29,7 +29,7 @@ pinned: false
|
|
| 29 |
- **🛡️ Privacy First:** Completely stateless. No database, no user accounts, no history.
|
| 30 |
- **🔍 Deep Search:** Queries **Semantic Scholar** to find hundreds of candidates per query, filtered down to the top 10 most relevant open-access papers.
|
| 31 |
- **✅ Verifiable:** Every sentence is backed by an inline citation `[1]` that links directly to the source passage.
|
| 32 |
-
- **🧠 Resilient:** Built on **LiteLLM**, Necthrall prioritizes **
|
| 33 |
|
| 34 |
---
|
| 35 |
|
|
@@ -86,7 +86,7 @@ graph TD
|
|
| 86 |
|
| 87 |
* Python 3.11+
|
| 88 |
* [Semantic Scholar API Key](https://www.semanticscholar.org/product/api) (Free)
|
| 89 |
-
* LLM Provider Key (
|
| 90 |
|
| 91 |
### Local Development
|
| 92 |
|
|
@@ -127,7 +127,7 @@ Necthrall uses **LiteLLM** for model routing. You can configure the following in
|
|
| 127 |
| Variable | Description | Required |
|
| 128 |
| :--- | :--- | :--- |
|
| 129 |
| `SEMANTIC_SCHOLAR_API_KEY` | For searching papers | **Yes** |
|
| 130 |
-
| `PRIMARY_LLM_API_KEY` | Primary LLM (e.g.,
|
| 131 |
| `SECONDARY_LLM_API_KEY` | Fallback LLM (e.g., Llama 3.3) | Optional |
|
| 132 |
-----
|
| 133 |
|
|
|
|
| 29 |
- **🛡️ Privacy First:** Completely stateless. No database, no user accounts, no history.
|
| 30 |
- **🔍 Deep Search:** Queries **Semantic Scholar** to find hundreds of candidates per query, filtered down to the top 10 most relevant open-access papers.
|
| 31 |
- **✅ Verifiable:** Every sentence is backed by an inline citation `[1]` that links directly to the source passage.
|
| 32 |
+
- **🧠 Resilient:** Built on **LiteLLM**, Necthrall prioritizes **Cerebras** for synthesis, automatically switching to **Groq** if the primary model is unavailable or fails.
|
| 33 |
|
| 34 |
---
|
| 35 |
|
|
|
|
| 86 |
|
| 87 |
* Python 3.11+
|
| 88 |
* [Semantic Scholar API Key](https://www.semanticscholar.org/product/api) (Free)
|
| 89 |
+
* LLM Provider Key (Cerebras or Groq)
|
| 90 |
|
| 91 |
### Local Development
|
| 92 |
|
|
|
|
| 127 |
| Variable | Description | Required |
|
| 128 |
| :--- | :--- | :--- |
|
| 129 |
| `SEMANTIC_SCHOLAR_API_KEY` | For searching papers | **Yes** |
|
| 130 |
+
| `PRIMARY_LLM_API_KEY` | Primary LLM (e.g., Llama 3.3) | **Yes** |
|
| 131 |
| `SECONDARY_LLM_API_KEY` | Fallback LLM (e.g., Llama 3.3) | Optional |
|
| 132 |
-----
|
| 133 |
|
agents/synthesis_agent.py
CHANGED
|
@@ -81,14 +81,14 @@ CITATION_QA_TEMPLATE = (
|
|
| 81 |
" - **NO HALLUCINATIONS**: If the text says 'expensive', **DO NOT** invent a number like '$500'. Write 'high cost' instead.\n"
|
| 82 |
" - **Specifics**: Use p-values, N=, and % changes **ONLY** if explicitly stated in the provided text.\n"
|
| 83 |
" - **GRANULAR CITATION**: \n"
|
| 84 |
-
" * **Rule:** Cite the source [
|
| 85 |
" * **Correct:** 'Method A yield is 80% [1] vs. Method B is 40% [2].'\n"
|
| 86 |
" * **Incorrect:** 'Method A yield is 80% vs. Method B is 40% [1][2].'\n"
|
| 87 |
" * **Incorrect:** 'Method A and B yields are 80% and 40% respectively [1].' (Unless [1] contains BOTH numbers).\n"
|
| 88 |
" - **NO CITATION DUMPING**: \n"
|
| 89 |
" * **Strictly Forbidden:** Never group more than 2 citations together (e.g., `[1][2][3]` is prohibited).\n"
|
| 90 |
" * **Requirement:** If multiple sources support a statement, split the statement so each source supports a specific part.\n"
|
| 91 |
-
" - **VERIFICATION**: Ensure the source [
|
| 92 |
"5. **START IMMEDIATELY**: \n"
|
| 93 |
" - Start your response directly with the header '### Executive Summary'.\n"
|
| 94 |
" - Do not use introductory labels like 'Scientific Answer:' or 'Here is the synthesis'.\n\n"
|
|
|
|
| 81 |
" - **NO HALLUCINATIONS**: If the text says 'expensive', **DO NOT** invent a number like '$500'. Write 'high cost' instead.\n"
|
| 82 |
" - **Specifics**: Use p-values, N=, and % changes **ONLY** if explicitly stated in the provided text.\n"
|
| 83 |
" - **GRANULAR CITATION**: \n"
|
| 84 |
+
" * **Rule:** Cite the source [N] *immediately* after the specific statistic it supports.\n"
|
| 85 |
" * **Correct:** 'Method A yield is 80% [1] vs. Method B is 40% [2].'\n"
|
| 86 |
" * **Incorrect:** 'Method A yield is 80% vs. Method B is 40% [1][2].'\n"
|
| 87 |
" * **Incorrect:** 'Method A and B yields are 80% and 40% respectively [1].' (Unless [1] contains BOTH numbers).\n"
|
| 88 |
" - **NO CITATION DUMPING**: \n"
|
| 89 |
" * **Strictly Forbidden:** Never group more than 2 citations together (e.g., `[1][2][3]` is prohibited).\n"
|
| 90 |
" * **Requirement:** If multiple sources support a statement, split the statement so each source supports a specific part.\n"
|
| 91 |
+
" - **VERIFICATION**: Ensure the source [N] *actually contains* the specific number attached to it.\n\n"
|
| 92 |
"5. **START IMMEDIATELY**: \n"
|
| 93 |
" - Start your response directly with the header '### Executive Summary'.\n"
|
| 94 |
" - Do not use introductory labels like 'Scientific Answer:' or 'Here is the synthesis'.\n\n"
|
main.py
CHANGED
|
@@ -132,4 +132,4 @@ ui.run_with(
|
|
| 132 |
if __name__ == "__main__":
|
| 133 |
import uvicorn
|
| 134 |
|
| 135 |
-
uvicorn.run("main:app", host="0.0.0.0", port=7860, log_level="info", reload=
|
|
|
|
| 132 |
if __name__ == "__main__":
|
| 133 |
import uvicorn
|
| 134 |
|
| 135 |
+
uvicorn.run("main:app", host="0.0.0.0", port=7860, log_level="info", reload=False)
|
pytest.ini
CHANGED
|
@@ -11,6 +11,7 @@ markers =
|
|
| 11 |
filterwarnings =
|
| 12 |
ignore:Token indices sequence length is longer than the specified maximum sequence length:UserWarning
|
| 13 |
ignore::DeprecationWarning
|
|
|
|
| 14 |
addopts =
|
| 15 |
--tb=short
|
| 16 |
-q
|
|
|
|
| 11 |
filterwarnings =
|
| 12 |
ignore:Token indices sequence length is longer than the specified maximum sequence length:UserWarning
|
| 13 |
ignore::DeprecationWarning
|
| 14 |
+
ignore::UserWarning
|
| 15 |
addopts =
|
| 16 |
--tb=short
|
| 17 |
-q
|
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:449ac3f9b72672955ffc2826ee3f224b04a9d9cb21ba54019784072919624f25
|
| 3 |
+
size 463
|
scripts/generate_golden_dataset.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
from typing import List, Dict, Any
|
| 6 |
+
from loguru import logger
|
| 7 |
+
|
| 8 |
+
# Add project root to path
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 10 |
+
|
| 11 |
+
from agents.semantic_scholar_client import SemanticScholarClient
|
| 12 |
+
from tests.eval_config import LLMJudge
|
| 13 |
+
|
| 14 |
+
TOPICS = [
|
| 15 |
+
"CRISPR off-target effects",
|
| 16 |
+
"Transformer architecture in NLP",
|
| 17 |
+
"Climate change impact on coral reefs",
|
| 18 |
+
"Quantum computing error correction",
|
| 19 |
+
"mRNA vaccine technology",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
async def generate_dataset():
|
| 24 |
+
logger.info("Starting golden dataset generation...")
|
| 25 |
+
|
| 26 |
+
# Ensure output directory exists
|
| 27 |
+
output_dir = os.path.join("tests", "data")
|
| 28 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 29 |
+
output_file = os.path.join(output_dir, "golden_dataset.json")
|
| 30 |
+
|
| 31 |
+
client = SemanticScholarClient()
|
| 32 |
+
judge = LLMJudge()
|
| 33 |
+
dataset = []
|
| 34 |
+
|
| 35 |
+
for topic in TOPICS:
|
| 36 |
+
logger.info(f"Processing topic: {topic}")
|
| 37 |
+
try:
|
| 38 |
+
# Fetch abstracts
|
| 39 |
+
results = await client.multi_query_search(
|
| 40 |
+
queries=[topic], limit_per_query=5
|
| 41 |
+
)
|
| 42 |
+
abstracts = [r.get("abstract") for r in results if r.get("abstract")]
|
| 43 |
+
|
| 44 |
+
if not abstracts:
|
| 45 |
+
logger.warning(f"No abstracts found for {topic}")
|
| 46 |
+
continue
|
| 47 |
+
|
| 48 |
+
context_text = "\n\n".join(abstracts[:5])
|
| 49 |
+
|
| 50 |
+
# Generate Q&A
|
| 51 |
+
prompt = f"""
|
| 52 |
+
Based on the following labeled scientific abstracts, generate a complex scientific question and its answer.
|
| 53 |
+
|
| 54 |
+
CRITICAL INSTRUCTIONS:
|
| 55 |
+
1. The answer must be derived ONLY from the provided text.
|
| 56 |
+
2. **Every claim in the answer must have an inline citation** in the format [1], [2], etc., corresponding to the abstract numbers below.
|
| 57 |
+
3. Do not create a separate references list; use inline tags only.
|
| 58 |
+
|
| 59 |
+
Abstracts:
|
| 60 |
+
{context_text}
|
| 61 |
+
|
| 62 |
+
Output format:
|
| 63 |
+
Question: [Your question here]
|
| 64 |
+
Answer: [Your answer with inline citations here]
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
response = await judge.a_generate(prompt)
|
| 68 |
+
|
| 69 |
+
# Parse response (robust parsing)
|
| 70 |
+
response_text = response.strip()
|
| 71 |
+
question = ""
|
| 72 |
+
answer = ""
|
| 73 |
+
|
| 74 |
+
# Try to find Question and Answer blocks even with markdown formatting
|
| 75 |
+
import re
|
| 76 |
+
|
| 77 |
+
# Look for "Question:" or "**Question:**" followed by text until "Answer:" or "**Answer:**"
|
| 78 |
+
q_match = re.search(
|
| 79 |
+
r"(?:\*\*|)?Question:(?:\*\*|)?\s*(.*?)\s*(?:\*\*|)?Answer:(?:\*\*|)?",
|
| 80 |
+
response_text,
|
| 81 |
+
re.DOTALL | re.IGNORECASE,
|
| 82 |
+
)
|
| 83 |
+
if q_match:
|
| 84 |
+
question = q_match.group(1).strip()
|
| 85 |
+
|
| 86 |
+
# Look for "Answer:" or "**Answer:**" followed by text until end of string
|
| 87 |
+
a_match = re.search(
|
| 88 |
+
r"(?:\*\*|)?Answer:(?:\*\*|)?\s*(.*)",
|
| 89 |
+
response_text,
|
| 90 |
+
re.DOTALL | re.IGNORECASE,
|
| 91 |
+
)
|
| 92 |
+
if a_match:
|
| 93 |
+
answer = a_match.group(1).strip()
|
| 94 |
+
|
| 95 |
+
if not question or not answer:
|
| 96 |
+
# Fallback to line-by-line if regex fails (though regex covers most cases)
|
| 97 |
+
lines = response_text.split("\n")
|
| 98 |
+
current_section = None
|
| 99 |
+
q_lines = []
|
| 100 |
+
a_lines = []
|
| 101 |
+
|
| 102 |
+
for line in lines:
|
| 103 |
+
clean_line = line.strip()
|
| 104 |
+
if not clean_line:
|
| 105 |
+
continue
|
| 106 |
+
|
| 107 |
+
if "Question:" in clean_line:
|
| 108 |
+
current_section = "Q"
|
| 109 |
+
content = clean_line.split("Question:", 1)[1].strip()
|
| 110 |
+
if content:
|
| 111 |
+
q_lines.append(content)
|
| 112 |
+
elif "Answer:" in clean_line:
|
| 113 |
+
current_section = "A"
|
| 114 |
+
content = clean_line.split("Answer:", 1)[1].strip()
|
| 115 |
+
if content:
|
| 116 |
+
a_lines.append(content)
|
| 117 |
+
elif current_section == "Q":
|
| 118 |
+
q_lines.append(clean_line)
|
| 119 |
+
elif current_section == "A":
|
| 120 |
+
a_lines.append(clean_line)
|
| 121 |
+
|
| 122 |
+
question = " ".join(q_lines).strip()
|
| 123 |
+
answer = " ".join(a_lines).strip()
|
| 124 |
+
|
| 125 |
+
if question and answer:
|
| 126 |
+
entry = {
|
| 127 |
+
"input": question,
|
| 128 |
+
"actual_output": answer,
|
| 129 |
+
"retrieval_context": abstracts[:5],
|
| 130 |
+
}
|
| 131 |
+
dataset.append(entry)
|
| 132 |
+
logger.info(f"Generated entry for {topic}")
|
| 133 |
+
else:
|
| 134 |
+
logger.warning(f"Failed to parse Q&A for {topic}. Response: {response}")
|
| 135 |
+
|
| 136 |
+
except Exception as e:
|
| 137 |
+
logger.error(f"Error processing {topic}: {e}")
|
| 138 |
+
|
| 139 |
+
# Save dataset
|
| 140 |
+
with open(output_file, "w", encoding="utf-8") as f:
|
| 141 |
+
json.dump(dataset, f, indent=2)
|
| 142 |
+
|
| 143 |
+
logger.info(f"Dataset saved to {output_file} with {len(dataset)} entries.")
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
asyncio.run(generate_dataset())
|
tests/citation_metrics.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
from typing import Any, Dict, List, Optional
|
| 5 |
+
from deepeval.metrics import BaseMetric
|
| 6 |
+
from deepeval.test_case import LLMTestCase
|
| 7 |
+
from utils.citation_verifier import CitationVerifier
|
| 8 |
+
from tests.eval_config import LLMJudge
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class CitationValidityMetric(BaseMetric):
|
| 12 |
+
def __init__(self, threshold: float = 1.0):
|
| 13 |
+
self.threshold = threshold
|
| 14 |
+
self.verifier = CitationVerifier()
|
| 15 |
+
self.score = 0.0
|
| 16 |
+
self.reason = ""
|
| 17 |
+
|
| 18 |
+
def measure(self, test_case: LLMTestCase):
|
| 19 |
+
# Extract actual output and retrieval context
|
| 20 |
+
actual_output = test_case.actual_output
|
| 21 |
+
retrieval_context = test_case.retrieval_context
|
| 22 |
+
|
| 23 |
+
# Verify citations
|
| 24 |
+
result = self.verifier.verify(actual_output, retrieval_context)
|
| 25 |
+
|
| 26 |
+
# Set score and reason
|
| 27 |
+
self.score = 1.0 if result["valid"] else 0.0
|
| 28 |
+
self.reason = result["reason"]
|
| 29 |
+
|
| 30 |
+
self.success = self.score >= self.threshold
|
| 31 |
+
return self.score
|
| 32 |
+
|
| 33 |
+
def is_successful(self) -> bool:
|
| 34 |
+
return self.success
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def __name__(self):
|
| 38 |
+
return "Citation Validity"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class CitationAccuracyMetric(BaseMetric):
|
| 42 |
+
def __init__(self, model: LLMJudge, threshold: float = 0.7):
|
| 43 |
+
self.threshold = threshold
|
| 44 |
+
self.model = model
|
| 45 |
+
self.score = 0.0
|
| 46 |
+
self.reason = ""
|
| 47 |
+
|
| 48 |
+
async def a_measure(self, test_case: LLMTestCase):
|
| 49 |
+
actual_output = test_case.actual_output
|
| 50 |
+
retrieval_context = test_case.retrieval_context
|
| 51 |
+
|
| 52 |
+
# Format context for the prompt
|
| 53 |
+
context_str = ""
|
| 54 |
+
for i, ctx in enumerate(retrieval_context):
|
| 55 |
+
context_str += f"Passage {i+1}:\n{ctx}\n\n"
|
| 56 |
+
|
| 57 |
+
prompt = f"""
|
| 58 |
+
You are a strict citation evaluator. Your task is to verify if the citations in the provided text are factually supported by the corresponding passages.
|
| 59 |
+
|
| 60 |
+
Text to Evaluate:
|
| 61 |
+
{actual_output}
|
| 62 |
+
|
| 63 |
+
Reference Passages:
|
| 64 |
+
{context_str}
|
| 65 |
+
|
| 66 |
+
Instructions:
|
| 67 |
+
1. Identify every statement in the text that has a citation (e.g., [1], [2]).
|
| 68 |
+
2. For each citation, check if the referenced Passage (Passage 1 for [1], etc.) explicitly supports the statement.
|
| 69 |
+
3. Calculate a score: (Number of Supported Citations / Total Number of Citations). If there are no citations, return 1.0 (N/A).
|
| 70 |
+
4. Provide a reason explaining which citations were correct and which were incorrect.
|
| 71 |
+
|
| 72 |
+
Output must be valid JSON with the following format:
|
| 73 |
+
{{
|
| 74 |
+
"score": <float between 0.0 and 1.0>,
|
| 75 |
+
"reason": "<explanation>"
|
| 76 |
+
}}
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
response = await self.model.a_generate(prompt)
|
| 80 |
+
|
| 81 |
+
# Parse JSON response
|
| 82 |
+
try:
|
| 83 |
+
# Clean up potential markdown code blocks
|
| 84 |
+
cleaned_response = response.strip()
|
| 85 |
+
if cleaned_response.startswith("```json"):
|
| 86 |
+
cleaned_response = cleaned_response[7:]
|
| 87 |
+
if cleaned_response.endswith("```"):
|
| 88 |
+
cleaned_response = cleaned_response[:-3]
|
| 89 |
+
|
| 90 |
+
data = json.loads(cleaned_response.strip())
|
| 91 |
+
self.score = float(data.get("score", 0.0))
|
| 92 |
+
self.reason = data.get("reason", "No reason provided.")
|
| 93 |
+
except Exception as e:
|
| 94 |
+
self.score = 0.0
|
| 95 |
+
self.reason = f"Failed to parse LLM response: {e}. Response was: {response}"
|
| 96 |
+
|
| 97 |
+
self.success = self.score >= self.threshold
|
| 98 |
+
return self.score
|
| 99 |
+
|
| 100 |
+
def measure(self, test_case: LLMTestCase):
|
| 101 |
+
return asyncio.run(self.a_measure(test_case))
|
| 102 |
+
|
| 103 |
+
def is_successful(self) -> bool:
|
| 104 |
+
return self.success
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def __name__(self):
|
| 108 |
+
return "Citation Accuracy"
|
tests/data/golden_dataset.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"input": "How does the synthetic self\u2011regulating Cas9 switch described in the first abstract mitigate the genotoxic and off\u2011target risks emphasized in the subsequent reviews, and what evidence supports its potential to satisfy current safety and regulatory requirements for CRISPR\u2011based therapeutics?",
|
| 4 |
+
"actual_output": "The synthetic switch simultaneously represses Cas9 at the transcriptional level (via guide\u2011RNA\u2011directed self\u2011cleavage of the cas9 gene) and at the translational level (through the L7Ae:K\u2011turn system), thereby tightly limiting the amount of active nuclease in the cell\u30101\u2020L1-L5\u3011. This dual repression yields detectable Cas9 protein as early as 6\u202fh, which is sufficient to achieve a high frequency of on\u2011target indel formation, while keeping Cas9 expression low enough to suppress off\u2011target mutagenesis throughout a 72\u202fh window\u30101\u2020L7-L10\u3011. \n\nOff\u2011target activity and the resulting genomic instability (small indels, large deletions, inversions, translocations) are repeatedly identified as major sources of genotoxicity in CRISPR\u2011based gene therapies\u30102\u2020L5-L9\u3011\u30103\u2020L3-L7\u3011\u30104\u2020L3-L6\u3011. A variety of genome\u2011wide assays (in silico prediction tools, in vitro cleavage profiling, and in vivo sequencing approaches) have been developed to map these unintended edits and are now integral to pre\u2011clinical risk assessment\u30102\u2020L9-L12\u3011\u30103\u2020L9-L12\u3011\u30104\u2020L7-L10\u3011. \n\nBy restricting Cas9 exposure temporally (\u201chit\u2011and\u2011run\u201d editing) and quantitatively, the synthetic switch directly addresses the safety concerns highlighted in the reviews: it reduces the window during which off\u2011target cleavage can occur, thereby lowering the probability of insertional mutagenesis and other structural variations that could lead to oncogenesis\u30102\u2020L2-L4\u3011\u30103\u2020L5-L8\u3011. Moreover, because the switch is compact enough to be packaged into viral vectors, it can be incorporated into existing delivery platforms without substantially increasing vector size, preserving the efficiency of viral delivery while mitigating the vector\u2011associated genotoxic risk noted for conventional viral\u2011based gene therapies\u30101\u2020L11-L13\u3011\u30102\u2020L1-L3\u3011. \n\nThe demonstrated kinetic profile\u2014early on\u2011target editing coupled with sustained suppression of off\u2011target activity\u2014provides empirical support that the switch can meet the stringent safety benchmarks required by regulatory agencies for CRISPR therapeutics, which now demand comprehensive off\u2011target profiling and mitigation strategies as part of pre\u2011clinical evaluation\u30103\u2020L9-L13\u3011\u30104\u2020L11-L13\u3011. Consequently, the synthetic self\u2011regulating Cas9 system offers a concrete, experimentally validated approach to reconcile the powerful editing capability of CRISPR with the genotoxicity concerns that currently limit its clinical translation.",
|
| 5 |
+
"retrieval_context": [
|
| 6 |
+
"Abstract CRISPR/Cas9 is a powerful genome editing system but uncontrolled Cas9 nuclease expression triggers off-target effects and even in vivo immune responses. Inspired by synthetic biology, here we built a synthetic switch that self-regulates Cas9 expression not only in the transcription step by guide RNA-aided self-cleavage of cas9 gene, but also in the translation step by L7Ae:K-turn repression system. We showed that the synthetic switch enabled simultaneous transcriptional and translational repression, hence stringently attenuating the Cas9 expression. The restricted Cas9 expression induced high efficiency on-target indel mutation while minimizing the off-target effects. Furthermore, we unveiled the correlation between Cas9 expression kinetics and on-target/off-target mutagenesis. The synthetic switch conferred detectable Cas9 expression and concomitant high frequency on-target mutagenesis at as early as 6 h, and restricted the Cas9 expression and off-target effects to minimal levels through 72 h. The synthetic switch is compact enough to be incorporated into viral vectors for self-regulation of Cas9 expression, thereby providing a novel \u2018hit and run\u2019 strategy for in vivo genome editing.",
|
| 7 |
+
"Recent advances in the era of genetic engineering have significantly improved our ability to make precise changes in the genomes of human cells. Throughout the years, clinical trials based on gene therapies have led to the cure of diseases such as X-linked severe combined immunodeficiency (SCID-X1), adenosine deaminase deficiency (ADA-SCID) and Wiskott-Aldrich syndrome. Despite the success gene therapy has had, there is still the risk of genotoxicity due to the potential oncogenesis introduced by utilising viral vectors. Research has focused on alternative strategies like genome editing without viral vectors as a means to reduce genotoxicity introduced by the viral vectors. Although there is an extensive use of RNA-guided genome editing via the clustered regularly interspaced short palindromic repeats (CRISPR) and associated protein-9 (Cas9) technology for biomedical research, its genome-wide target specificity and its genotoxic side effects remain controversial. There have been reports of on- and off-target effects created by CRISPR-Cas9 that can include small and large indels and inversions, highlighting the potential risk of insertional mutagenesis. In the last few years, a plethora of in silico, in vitro and in vivo genome-wide assays have been introduced with the sole purpose of profiling these effects. Here, we are going to discuss the genotoxic obstacles in gene therapies and give an up-to-date overview of methodologies for quantifying CRISPR-Cas9 effects.",
|
| 8 |
+
"Over the last decade, CRISPR has revolutionized drug development due to its potential to cure genetic diseases that currently do not have any treatment. CRISPR was adapted from bacteria for gene editing in human cells in 2012 and, remarkably, only 11 years later has seen it\u2019s very first approval as a medicine for the treatment of sickle cell disease and transfusion-dependent beta-thalassemia. However, the application of CRISPR systems is associated with unintended off-target and on-target alterations (including small indels, and structural variations such as translocations, inversions and large deletions), which are a source of risk for patients and a vital concern for the development of safe therapies. In recent years, a wide range of methods has been developed to detect unwanted effects of CRISPR-Cas nuclease activity. In this review, we summarize the different methods for off-target assessment, discuss their strengths and limitations, and highlight strategies to improve the safety of CRISPR systems. Finally, we discuss their relevance and application for the pre-clinical risk assessment of CRISPR therapeutics within the current regulatory context.",
|
| 9 |
+
"Gene editing stands for the methods to precisely make changes to a specific nucleic acid sequence. With the recent development of the clustered regularly interspaced short palindromic repeats (CRISPR)/Cas9 system, gene editing has become efficient, convenient and programmable, leading to promising translational studies and clinical trials for both genetic and non-genetic diseases. A major concern in the applications of the CRISPR/Cas9 system is about its off-target effects, namely the deposition of unexpected, unwanted, or even adverse alterations to the genome. To date, many methods have been developed to nominate or detect the off-target sites of CRISPR/Cas9, which laid the basis for the successful upgrades of CRISPR/Cas9 derivatives with enhanced precision. In this review, we summarize these technological advancements and discuss about the current challenges in the management of off-target effects for future gene therapy."
|
| 10 |
+
]
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"input": "How do recent adaptations of Transformer architectures\u2014such as replacing self\u2011attention with a time\u2011aware MLP, introducing relative positional encoding, employing linear (performer) attention, and configuring encoder\u2011only versus decoder\u2011only models\u2014impact computational efficiency and prediction accuracy across heterogeneous domains including high\u2011mobility wireless channel prediction, Chinese generative dialogue, rotating\u2011machinery fault diagnosis, and COVID\u201119 CT image classification?",
|
| 14 |
+
"actual_output": "Recent work demonstrates that tailoring the core components of Transformer models to the specific characteristics of a task can simultaneously lower computational demands and preserve or even improve predictive performance. \n\n1. **Replacing self\u2011attention with a time\u2011aware MLP (TMLP).** \n In the LinFormer framework for 6G channel prediction, the conventional quadratic\u2011complexity attention mechanism is substituted by a linear\u2011complexity, time\u2011aware multi\u2011layer perceptron. This redesign dramatically cuts the computational load required for real\u2011time channel aging mitigation while still delivering high\u2011accuracy forecasts, making the model suitable for cost\u2011constrained base stations\u30101\u3011. \n\n2. **Relative positional encoding in a decoder\u2011only architecture.** \n The Chinese generative dialogue system adopts an encoder\u2011free, decoder\u2011only Transformer that uses an \u201cincomplete mask\u201d to enforce one\u2011way autoregressive generation for replies while allowing the question encoder to attend bidirectionally. Crucially, the absolute positional embeddings are replaced by a relative\u2011position scheme embedded directly into the self\u2011attention computation. This modification alleviates the long\u2011range information loss inherent to absolute coding and yields measurable gains in BLEU, embedding\u2011average, grammaticality, and semantic coherence scores\u30102\u3011. \n\n3. **Linear (performer) attention for vision tasks.** \n For COVID\u201119 CT image classification, a hybrid Vision\u2011Transformer/Performer architecture is introduced. The Performer component implements linear\u2011time attention, which scales gracefully with image resolution and reduces memory footprints compared with full self\u2011attention. Coupled with a modified Vision\u2011Transformer backbone, this design attains a state\u2011of\u2011the\u2011art 96\u202f% classification accuracy, confirming that linear attention can sustain high performance in computer\u2011vision domains while easing computational pressure\u30105\u3011. \n\n4. **Encoder\u2011only versus decoder\u2011only configurations and task\u2011specific modifications.** \n The literature survey of Transformer\u2011based models underscores that the choice between encoder\u2011only, decoder\u2011only, or encoder\u2011decoder stacks influences both expressiveness and efficiency, depending on the downstream task (e.g., sequence classification versus generation)\u30103\u3011. In the fault\u2011diagnosis domain, the T4PdM model adapts the standard Transformer to a time\u2011series classification setting, preserving the encoder\u2011centric design but incorporating domain\u2011specific preprocessing and loss functions. This tailored model achieves near\u2011perfect accuracies of 99.98\u202f% (MaFaulDa) and 98\u202f% (CWRU), outperforming prior approaches and illustrating that modest architectural tweaks can translate into substantial gains for industrial predictive\u2011maintenance applications\u30104\u3011. \n\nCollectively, these studies reveal a consistent pattern: **task\u2011aware modifications\u2014whether swapping attention for linear MLPs, embedding relative positional information, or selecting encoder/decoder orientations\u2014enable Transformers to operate more efficiently without sacrificing, and often enhancing, predictive accuracy across communication engineering, natural language generation, industrial fault detection, and medical imaging.**",
|
| 15 |
+
"retrieval_context": [
|
| 16 |
+
"The emergence of 6th generation (6G) mobile networks brings new challenges in supporting high-mobility communications, particularly in addressing the issue of channel aging. While existing channel prediction methods offer improved accuracy at the expense of increased computational complexity, limiting their practical application in mobile networks. To address these challenges, we present LinFormer, an innovative channel prediction framework based on a scalable, all-linear, encoder-only Transformer model. Our approach, inspired by natural language processing (NLP) models such as BERT, adapts an encoder-only architecture specifically for channel prediction tasks. We propose replacing the computationally intensive attention mechanism commonly used in Transformers with a time-aware multi-layer perceptron (TMLP), significantly reducing computational demands. The inherent time awareness of TMLP module makes it particularly suitable for channel prediction tasks. We enhance LinFormer\u2019s training process by employing a weighted mean squared error loss (WMSELoss) function and data augmentation techniques, leveraging larger, readily available communication datasets. Our approach achieves a substantial reduction in computational complexity while maintaining high prediction accuracy, making it more suitable for deployment in cost-effective base stations (BS). Comprehensive experiments using both simulated and measured data demonstrate that LinFormer outperforms existing methods across various mobility scenarios, offering a promising solution for future wireless communication systems.",
|
| 17 |
+
"Natural language processing (NLP) based on deep learning provides a positive performance for generative dialogue system, and the transformer model is a new boost in NLP after the advent of word vectors. In this paper, a Chinese generative dialogue system based on transformer is designed, which only uses a multi-layer transformer decoder to build the system and uses the design of an incomplete mask to realize one-way language generation. That is, questions can perceive context information in both directions, while reply sentences can only output one-way autoregressive. The above system improvements make the one-way generation of dialogue tasks more logical and reasonable, and the performance is better than the traditional dialogue system scheme. In consideration of the long-distance information weakness of absolute position coding, we put forward the improvement of relative position coding in theory, and verify it in subsequent experiments. In the transformer module, the calculation formula of self-attention is modified, and the relative position information is added to replace the absolute position coding of the position embedding layer. The performance of the modified model in BLEU, embedding average, grammatical and semantic coherence is ideal, to enhance long-distance attention.",
|
| 18 |
+
"Transformer architectures are highly expressive because they use self-attention mechanisms to encode long-range dependencies in the input sequences. In this paper, we present a literature review on Transformer-based (TB) models, providing a detailed overview of each model in comparison to the Transformer\u2019s standard architecture. This survey focuses on TB models used in the field of Natural Language Processing (NLP) for textual-based tasks. We begin with an overview of the fundamental concepts at the heart of the success of these models. Then, we classify them based on their architecture and training mode. We compare the advantages and disadvantages of popular techniques in terms of architectural design and experimental value. Finally, we discuss open research, directions, and potential future work to help solve current TB application challenges in NLP.",
|
| 19 |
+
"Deep learning and big data algorithms have become widely used in industrial applications to optimize several tasks in many complex systems. Particularly, deep learning model for diagnosing and prognosing machinery health has leveraged predictive maintenance (PdM) to be more accurate and reliable in decision making, in this way avoiding unnecessary interventions, machinery accidents, and environment catastrophes. Recently, Transformer Neural Networks have gained notoriety and have been increasingly the favorite choice for Natural Language Processing (NLP) tasks. Thus, given their recent major achievements in NLP, this paper proposes the development of an automatic fault classifier model for predictive maintenance based on a modified version of the Transformer architecture, namely T4PdM, to identify multiple types of faults in rotating machinery. Experimental results are developed and presented for the MaFaulDa and CWRU databases. T4PdM was able to achieve an overall accuracy of 99.98% and 98% for both datasets, respectively. In addition, the performance of the proposed model is compared to other previously published works. It has demonstrated the superiority of the model in detecting and classifying faults in rotating industrial machinery. Therefore, the proposed Transformer-based model can improve the performance of machinery fault analysis and diagnostic processes and leverage companies to a new era of the Industry 4.0. In addition, this methodology can be adapted to any other task of time series classification.",
|
| 20 |
+
"Even though vaccines are already in use worldwide, the COVID-19 pandemic is far from over, with some countries re-establishing the lockdown state, the virus has taken over 2 million lives until today, being a serious health issue. Although real-time reverse transcription-polymerase chain reaction (RTPCR) is the \ufb01rst tool for COVID-19 diagnosis, its high false-negative rate and low sensitivity might delay accurate diagnosis. Therefore, fast COVID-19 diagnosis and quarantine, combined with effective vaccination plans, is crucial for the pandemic to be over as soon as possible. To that end, we propose an intelligent system to classify computed tomography (CT) of lung images between a normal, pneumonia caused by something other than the coronavirus or pneumonia caused by the coronavirus. This paper aims to evaluate a complete selfattention mechanism with a Transformer network to capture COVID-19 pattern over CT images. This approach has reached the state-of-the-art in multiple NLP problems and just recently is being applied for computer vision tasks. We combine vision transformer and performer (linear attention transformers), and also a modi\ufb01ed vision transformer, reaching 96.00% accuracy."
|
| 21 |
+
]
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"input": "How do multivariate bleaching prediction models that incorporate both temperature and light (including cloud cover) alter projected bleaching frequencies under low\u2011 and moderate\u2011emission scenarios compared with traditional \u201cexcess\u2011heat\u201d models, and what do these projections imply about the relative threats of heat stress versus ocean acidification to coral calcification?",
|
| 25 |
+
"actual_output": "Multivariate bleaching models that combine sea\u2011surface temperature, downwelling shortwave radiation, and cloud\u2011cover fraction predict that cloudiness can postpone the onset of frequent bleaching by several decades in many reef cells under a low\u2011emission pathway (SSP1\u20112.6)\u202f[1]. However, even with this mitigation, more than 70\u202f% of reef cells still face dangerously frequent bleaching by the end of the century, and under a moderate pathway (SSP2\u20114.5) the increase in thermal stress overwhelms the protective effect of clouds by mid\u2011century\u202f[1]. Incorporating potential thermal adaptation or acclimation can further delay bleaching by up to 40\u202fyears, yet the majority of reefs remain at high risk under SSP2\u20114.5\u202f[1].\n\nIn contrast, the majority of coral\u2011bleaching forecasts in the literature rely on deterministic \u201cexcess\u2011heat\u201d approaches, which account only for temperature anomalies and constitute about one\u2011third of published studies but receive roughly two\u2011thirds of citations\u202f[5].\n\nIndependent climate\u2011change projections using regional regression models (e.g., the Blue Communities model) also show that, under higher\u2011emission scenarios (RCP\u202f8.5), the number of weeks per decade when sea\u2011surface temperature exceeds coral\u2011bleaching thresholds can rise from zero at the start of the century to up to 55 weeks by the 2050s\u202f[2].\n\nRegarding the physiological consequences, experimental and literature syntheses indicate that a +2\u202f\u00b0C thermal anomaly poses a far greater risk to coral calcification than the moderate ocean\u2011acidification (OA) changes projected for 2100 under SSP2\u20114.5 (scenario\u2011B1)\u202f[3]. While OA is expected to cause only modest reductions in coral physiology and pigmentation, heat stress can severely disrupt the metabolic coupling between algal photosynthesis and host respiration that underpins calcification\u202f[3].",
|
| 26 |
+
"retrieval_context": [
|
| 27 |
+
"The increasing frequency of mass coral bleaching and associated coral mortality threaten the future of warmwater coral reefs. Although thermal stress is widely recognized as the main driver of coral bleaching, exposure to light also plays a central role. Future projections of the impacts of climate change on coral reefs have to date focused on temperature change and not considered the role of clouds in attenuating the bleaching response of corals. In this study, we develop temperature- and light-based bleaching prediction algorithms using historical sea surface temperature, cloud cover fraction and downwelling shortwave radiation data together with a global-scale observational bleaching dataset observations. The model is applied to CMIP6 output from the GFDL-ESM4 Earth System Model under four different future scenarios to estimate the effect of incorporating cloudiness on future bleaching frequency, with and without thermal adaptation or acclimation by corals. The results show that in the low emission scenario SSP1-2.6 incorporating clouds into the model delays the bleaching frequency conditions by multiple decades in some regions, yet the majority (>70%) of coral reef cells still experience dangerously frequent bleaching conditions by the end of the century. In the moderate scenario SSP2-4.5, however, the increase in thermal stress is sufficient to overwhelm the mitigating effect of clouds by mid-century. Thermal adaptation or acclimation by corals could further shift the bleaching projections by up to 40 years, yet coral reefs would still experience dangerously frequent bleaching conditions by the end of century in SPP2-4.5. The findings show that multivariate models incorporating factors like light may improve the near-term outlook for coral reefs and help identify future climate refugia. Nonetheless, the long-term future of coral reefs remains questionable if the world stays on a moderate or higher emissions path.",
|
| 28 |
+
"Coral reefs are a natural habitat for many species, as well as being of high economic and touristic significance. However, they represent an extremely sensitive ecosystem with a narrow ecological limit: prolonged high temperatures can lead to bleaching, in which corals expel their symbiotic algae and eventually corals will degrade and die. Based on climate change projections from the Blue Communities regional model, using linear regression, exponential regression, polynomial regression, we found that by the decades 2041\u20132050 and 2051\u20132060, whether with RCP 4.5 or RCP 8.5, the environmental temperature will change beyond the coral capacity threshold. Of particular concern is RCP 8.5, where the number of weeks per decade in which SST exceeds the threshold of coral reef bleaching is up to 55, compared to 0 at the beginning of the century. As well, the El Ni\u00f1o phenomenon often heats up waters to abnormally high temperatures in Cu Lao Cham and, it is projected to rise even further. Consequently, the combination of climate change and El Ni\u00f1o will cause abnormal increases in the seawater environment beyond the coral resistance threshold, leading to degradation of this internationally important site. Decisive and practical action must be taken to deal with climate change in this part of the world.",
|
| 29 |
+
"After three decades of coral research on the impacts of climate change, there is a wide consensus on the adverse effects of heat-stress, but the impacts of ocean acidification (OA) are not well established. Using a review of published studies and an experimental analysis, we confirm the large species-specific component of the OA response, which predicts moderate impacts on coral physiology and pigmentation by 2100 (scenario-B1 or SSP2-4.5), in contrast with the severe disturbances induced by only +2\u2009\u00b0C of thermal anomaly. Accordingly, global warming represents a greater threat for coral calcification than OA. The incomplete understanding of the moderate OA response relies on insufficient attention to key regulatory processes of these symbioses, particularly the metabolic dependence of coral calcification on algal photosynthesis and host respiration. Our capacity to predict the future of coral reefs depends on a correct identification of the main targets and/or processes impacted by climate change stressors. A combination of experimental and literature analyses indicate that heat stress is a greater threat for coral calcification than ocean acidification, stressing the need for further investigation on key regulatory processes.",
|
| 30 |
+
"Coral reefs are marine ecosystems with one of the highest levels of biodiversity that provide valuable goods and services. Coral reefs are fragile ecosystem and highly vulnerable to overfishing, destructive fishing practices, pollution, and natural factors. Climate change is one of the natural factors that impacted coral reefs. Southeast Asian coral reefs have the highest level of biodiversity for the world\u2019s marine ecosystem. Indonesia hold 12.5% of the world\u2019s total coral reefs area (\u00b158.000 km2). Bali is one of the popular area in Indonesia that becomes part of The Coral Triangle (The Coral Triangle and Marine Biodiversity). This research examines the relationship between the level of coral reefs destruction with climate change index in Nusa Dua and Nusa Penida, Bali Province, Indonesia. This research was based on secondary data of the analyzed LANDSAT 7+ and LANDSAT 8 OLI. The method performed by descriptive and quantitative analysis. The result shows that there is the difference about level of coral reefs destruction in 2012 and 2016.",
|
| 31 |
+
"Climate change impact syntheses, such as those by the Intergovernmental Panel on Climate Change, consistently assert that limiting global warming to 1.5\u2009\u00b0C is unlikely to safeguard most of the world\u2019s coral reefs. This prognosis is primarily based on a small subset of available models that apply similar \u2018excess heat\u2019 threshold methodologies. Our systematic review of 79 articles projecting coral reef responses to climate change revealed five main methods. \u2018Excess heat\u2019 models constituted one third (32%) of all studies but attracted a disproportionate share (68%) of citations in the field. Most methods relied on deterministic cause-and-effect rules rather than probabilistic relationships, impeding the field\u2019s ability to estimate uncertainty. To synthesize the available projections, we aimed to identify models with comparable outputs. However, divergent choices in model outputs and scenarios limited the analysis to a fraction of available studies. We found substantial discrepancies in the projected impacts, indicating that the subset of articles serving as a basis for climate change syntheses may project more severe consequences than other studies and methodologies. Drawing on insights from other fields, we propose methods to incorporate uncertainty into deterministic modeling approaches and propose a multi-model ensemble approach to generating probabilistic projections for coral reef futures. Global warming targets are considered inadequate to protect coral reefs, but this prognosis is based on models with similar approaches. This systematic review of studies that project coral responses to climate change found that divergent modelling methodologies had discrepancies in coral reef outcomes, and that those used for climate change syntheses may project more severe consequences than other methods."
|
| 32 |
+
]
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"input": "How can quantum error\u2011correcting codes be employed to actively tune the privacy budget of quantum differential privacy (QDP), and what theoretical, simulation\u2011based, and experimental evidence supports the feasibility of using QEC for this purpose while maintaining reliable error mitigation on current quantum hardware?",
|
| 36 |
+
"actual_output": "Quantum differential privacy (QDP) traditionally relies on the intrinsic, uncontrollable quantum noise of a device, which fixes the attainable privacy budget and limits flexibility\u202f[1]. By deliberately applying quantum error\u2011correcting codes (QEC) to selected single\u2011 or multi\u2011qubit gates, the effective noise error rate of a circuit can be reduced or increased in a controlled manner, thereby allowing the privacy budget to be recalculated after QEC operations with a newly derived formula\u202f[1]. \n\nAn open\u2011source framework that automatically inserts appropriate error\u2011correcting codes into a given algorithm and then performs noise\u2011aware circuit simulation makes it possible to evaluate many QEC configurations efficiently\u202f[2]. \n\nThe performance of a QEC code depends critically on its *distance* (the number of errors it can correct) and the underlying *error probability* of the hardware; sweeping these parameters in simulation reveals how different code distances shift the overall error rate\u202f[3]. \n\nExperimental validation on IBM\u202fQuantum Experience hardware confirms that small\u2011scale QEC schemes are effective in practice: three\u2011qubit bit\u2011flip and phase\u2011flip codes raise the correct\u2011output probability to \u2248\u202f90\u202f% on the ibmq_ourense processor, and applying measurement\u2011error mitigation further improves these figures by 5\u20137\u202f%\u202f[4]. These results show that the random errors introduced by decoherence can indeed be detected and corrected. \n\nFinally, a rigorous mathematical modelling of decoherence processes underpins the design of robust QECCs, ensuring that the error\u2011correction mechanisms target the dominant environmental noise channels\u202f[5]. \n\nTogether, these studies substantiate that quantum error correction can be strategically employed to manage error rates on present-day quantum devices.",
|
| 37 |
+
"retrieval_context": [
|
| 38 |
+
"Quantum computing is a promising paradigm for efficiently solving large and high-complexity problems. However, ensuring privacy within this quantum computing necessitates innovative approaches. Existing research has introduced the concept of quantum differential privacy (QDP) to protect data privacy in quantum computing by leveraging quantum noise. Yet, this method faces limitations due to the fixed and uncontrollable nature of the inherent noise, which directly affects the privacy budget of QDP. Addressing this critical gap, our study proposes a novel approach that utilizes quantum error correction (QEC) techniques not only to mitigate quantum computing errors but also to adjust QDP protection levels precisely. By selectively applying QEC to single or multiple qubit gates, we introduce a method to manipulate the quantum noise error rate effectively. Moreover, we derive a new formula for calculating the overall error rate in a quantum circuit and the adjusted privacy budget after QEC operation. Through extensive numerical simulations, we validate the efficacy of utilizing QEC in tuning privacy protection levels within quantum computing.",
|
| 39 |
+
"Due to the fragility of quantum mechanical effects, real quantum computers are plagued by frequent noise effects that cause errors during computations. Quantum error-correcting codes address this problem by providing means to identify and correct corresponding errors. However, most of the research on quantum error correction is theoretical or has been evaluated for specific hardware models only. Moreover, the development of corresponding codes and the evaluation of whether they indeed solve the problem for a particular hardware model, still often rests on tedious trial-and-error thus far. In this work, we propose an open-source framework that supports engineers and researchers in these tasks by automatically applying error-correcting codes for a given application followed by an automatic noise-aware quantum circuit simulation. Case studies showcase that this allows for a substantially more efficient implementation and evaluation of error-correcting codes.",
|
| 40 |
+
"Quantum Error Correction (QEC) is an important technique for protecting quantum information against decoherence and errors. This involves the design and implementation of algorithms and techniques to minimize error rates and increase the stability of quantum circuits. One of the key parameters in QEC is the distance of the error- correcting code, which determines the number of errors that can be corrected. Another important parameter is the error probability, which quantifies the likelihood of errors occurring in the quantum system. In this context, the goal of a simulation sweep like the one performed in the code is to study the performance of the QEC code for different values of the distance and error probability, and to optimize the code for maximum accuracy. By varying these parameters and observing the performance of the code, researchers can gain insights into how to design better codes and improve the reliability of quantum computing systems. We also discuss the challenges that need to be addressed for quantum computing to realize its potential in solving practical Error-correction problems.",
|
| 41 |
+
"Quantum noise cannot be avoided in the quantum computing devices due to unstable nature of qubits and signals. The error caused by quantum noise can be detected and corrected using different error correcting codes. In this work, we have tested the feasibility and accuracy of three qubit bit flip and phase flip error correcting code in quantum computer provided by International Business Machine Quantum Experience (IBM QX) cloud platform. Among five quantum processors, ibmq_ourense is found to have highest average accuracy 77.9% \u00b1 3.09% on all qubits simultaneously. Three qubits bit flip error correction circuit gave correct output 89.9% \u00b1 1.01% of the time on average. Similarly three qubits phase flip error correction circuit give 88.05% \u00b11.89%. The measurement error mitigation has improved the accuracy of bit flip and phase flip error correction code by 5.01% and 7.01% respectively on average. The error rate shows that the error in quantum computations are random in nature and can be corrected. IBM QX quantum computer are suitable for only small scale quantum computation and demonstrate purpose. Furthermore, the accuracy of error correction codes can be increased with the use of higher accuracy quantum qubits and quantum gates.",
|
| 42 |
+
"Quantum technologies have shown immeasurable potential to effectively solve several information processing tasks such as prime number factorization, unstructured database search or complex macromolecule simulation. As a result of such capability to solve certain problems that are not classically tractable, quantum machines have the potential revolutionize the modern world via applications such as drug design, process optimization, unbreakable communications or machine learning. However, quantum information is prone to suffer from errors caused by the so-called decoherence, which describes the loss in coherence of quantum states associated to their interactions with the surrounding environment. This decoherence phenomenon is present in every quantum information task, be it transmission, processing or even storage of quantum information. Consequently, the protection of quantum information via quantum error correction codes (QECC) is of paramount importance to construct fully operational quantum computers. Understanding environmental decoherence processes and the way they are modeled is fundamental in order to construct effective error correction methods capable of protecting quantum information. In this thesis, the nature of decoherence is studied and mathematically modelled; and QECCs are designed and optimized so that they exhibit better error correction capabilities."
|
| 43 |
+
]
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"input": "How do the delivery strategies of iontophoresis\u2011mediated transdermal administration and lipid\u2011nanoparticle (LNP) encapsulation influence the stability, cellular uptake, and immunogenicity of minimal mRNA vaccines, and what are the implications of these effects for the rapid development and deployment of mRNA\u2011based countermeasures against emerging biological threats?",
|
| 47 |
+
"actual_output": "Iontophoresis (IP) and lipid\u2011nanoparticle (LNP) encapsulation represent two complementary approaches that address distinct challenges of minimal mRNA vaccine delivery. \n\n1. **Enhancement of intracellular uptake and immune activation by iontophoresis** \u2013 The study on a minimal mRNA vaccine encoding the melanoma\u2011associated gp100 peptide demonstrated that IP can drive the transdermal and intracellular transport of the otherwise poorly permeable mRNA molecule, which is hindered by its high molecular weight and negative charge\u202f[2]. IP\u2011mediated delivery resulted in robust activation of skin\u2011resident immune cells, marked elevation of interferon\u2011\u03b3 (IFN\u2011\u03b3) expression, and pronounced infiltration of cytotoxic CD8\u207a T cells within tumor tissue, culminating in potent tumor inhibition in a murine melanoma model\u202f[2]. These findings illustrate that IP can overcome intrinsic delivery barriers of naked mRNA and directly stimulate a cellular immune response.\n\n2. **Stabilization of mRNA and facilitation of antigen\u2011presenting cell uptake by LNPs** \u2013 Lipid nanoparticles protect naked mRNA from extracellular ribonucleases and promote efficient trafficking to antigen\u2011presenting cells\u202f[3]. Systematic variation of LNP size revealed that particles in the 80\u2013100\u202fnm range provide optimal physicochemical stability, exhibiting minimal precipitation and aggregation, and retain their protective function during storage at both 4\u202f\u00b0C and \u201320\u202f\u00b0C, with the latter offering superior long\u2011term stability\u202f[3]. Because smaller LNPs disperse more effectively in solution, they are more readily taken up by dendritic cells, thereby enhancing antigen presentation and the ensuing adaptive immune response\u202f[3].\n\n3. **Implications for rapid vaccine development and deployment** \u2013 The review of mRNA vaccine technology emphasizes that nucleic\u2011acid vaccines bypass the need for large\u2011scale virus culture and attenuation, allowing a swift transition from genome sequencing to vaccine production\u202f[1]. The combination of rapid design (enabled by the nucleic\u2011acid platform) with delivery technologies that improve stability (LNP size optimization) and cellular uptake (IP) can accelerate the generation of safe and effective countermeasures against novel or engineered pathogens\u202f[1,2,3]. Moreover, the review notes that mRNA vaccines do not integrate into host DNA, reinforcing their safety profile for military and civilian use\u202f[1].\n\n**In summary**, iontophoresis directly enhances the transdermal delivery and immunogenic potency of minimal mRNA vaccines, while appropriately sized lipid nanoparticles safeguard mRNA integrity and promote efficient uptake by antigen\u2011presenting cells. Together, these delivery innovations complement the inherent speed of mRNA vaccine design, supporting the rapid development and field deployment of high\u2011efficacy biological defenses against emerging threats\u202f[1\u20113].",
|
| 48 |
+
"retrieval_context": [
|
| 49 |
+
"INTRODUCTION\nVaccine technology has improved substantially since the first smallpox vaccine, developed more than 200\u00a0years ago. As technology improves, vaccines can be produced more safely and reliably for many different pathogens. A recent breakthrough saw the first full deployment of mRNA vaccines to fight a pandemic. Despite the technological and logistical feat of developing a viable vaccine in an abbreviated time frame, there have been many questions about this new approach to vaccine development. The current review will provide descriptions about different types of vaccines as well as answers to some common questions about mRNA vaccines. The purpose is to provide military medical professionals with the information needed to better convey the importance and function of these new vaccines to service members.\n\n\nMATERIALS AND METHODS\nThere were no explicit inclusion or exclusion criteria for articles describing mRNA vaccine technology. References included here were intended to illustrate important principles or empirical evidence in demonstrating the safety, efficacy, and function of mRNA vaccines.\n\n\nDISCUSSION\nThe review describes three different types of vaccines: whole-pathogen, subunit, and nucleic acid. Each vaccine type has different implications for the development and production of a vaccine line. For example, whole-pathogen and subunit vaccines often require growing significant amounts of the vaccine sample in laboratory before the material can be incorporated into the vaccine. Nucleic acid vaccines instead provide cells the opportunity to produce key proteins without needing to reproduce the virus and attenuate it in a laboratory setting. This approach has a notable advantage of speed in moving from genome sequencing to vaccine production, but it also creates some potential confusion. The discussion covers three questions with regard to this confusion. First, was the vaccine developed too quickly? Speed here is a byproduct of the new technology and unprecedented government interdepartmental cooperation. No steps were skipped in development or production. Second, does the vaccine modify DNA? No, the mRNA vaccines never enter the cell nucleus and therefore cannot modify DNA. The discussion clarifies how mRNA enters cells and produces the key proteins required to stimulate an immune system response. Third, how long will immunity last? Because mRNA vaccines are new, long-term immunity cannot be projected without significant further study. Still, the discussion does cover issues in determining vaccine efficacy in clinical laboratory trials versus field effectiveness in the real world.\n\n\nCONCLUSIONS AND FUTURE USES\nThese mRNA vaccines are the newest and most sophisticated defensive tool military medicine has against emerging biological threats. Evolving dangers, such as synthetic biology and engineered pathogens, further enhance the importance of having defensive countermeasures that can be rapidly deployed in response. Current evidence suggests high safety and effectiveness for a biological countermeasure, decades in the making, and military medical personnel should feel confident using and recommending this technology to ensure force health protection.",
|
| 50 |
+
"mRNA vaccines have attracted considerable attention as a result of the 2019 coronavirus pandemic; however, challenges remain regarding use of mRNA vaccines, including insufficient delivery owing to the high molecular weights and high negative charges associated with mRNA. These characteristics of mRNA vaccines impair intracellular uptake and subsequent protein translation. In the current study, we prepared a minimal mRNA vaccine encoding a tumor associated antigen human gp10025-33 peptide (KVPRNQDWL), as a potential treatment for melanoma. Minimal mRNA vaccines have recently shown promise at improving the translational process, and can be prepared via a simple production method. Moreover, we previously reported the successful use of iontophoresis (IP) technology in the delivery of hydrophilic macromolecules into skin layers, as well as intracellular delivery of small interfering RNA (siRNA). We hypothesized that combining IP technology with a newly synthesized minimal mRNA vaccine can improve both transdermal and intracellular delivery of mRNA. Following IP-induced delivery of a mRNA vaccine, an immune response is elicited resulting in activation of skin resident immune cells. As expected, combining both technologies led to potent stimulation of the immune system, which was observed via potent tumor inhibition in mice bearing melanoma. Additionally, there was an elevation in mRNA expression levels of various cytokines, mainly interferon (IFN)-\u03b3, as well as infiltration of cytotoxic CD8+ T cells in the tumor tissue, which are responsible for tumor clearance. This is the first report demonstrating the application of IP for delivery of a minimal mRNA vaccine as a potential melanoma therapeutic.",
|
| 51 |
+
"ABSTRACT Messenger ribonucleic acid (mRNA) technology has been rapidly applied for the development of the COVID-19 vaccine. However, naked mRNA itself is inherently unstable. Lipid nanoparticles (LNPs) protect mRNAs from extracellular ribonucleases and facilitate mRNA trafficking. For mRNA vaccines, antigen-presenting cells utilize LNPs through uptake to elicit antigen-specific immunity. There are reports on the impact of various physical characteristics of LNPs, particularly those with sizes less than 200\u2009nm, especially 50 to 150\u2009nm, on the overall stability and protective efficacy of mRNA vaccines. To address this, a single change in the size of LNPs using the same mRNA stock solution was assessed for the physicochemical characterization of the resulting mRNA-LNPs vaccine, along with the evaluation of their protective efficacy. Particles of smaller sizes generally disperse more effectively in solutions, with minimized occurrence of particle precipitation and aggregation. Here, we demonstrate that the vaccine containing 80\u2013100\u2009nm mRNA-LNPs showed the best stability and protection at 4\u00b0C and \u221220\u00b0C. Furthermore, we can conclude that freezing the vaccine at \u221220\u00b0C is more appropriate for maintaining stability over the long term. This effort is poised to provide a scientific basis for improving the quality of ongoing mRNA vaccine endeavors and providing information on the development of novel products."
|
| 52 |
+
]
|
| 53 |
+
}
|
| 54 |
+
]
|
tests/eval_config.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import Optional, List
|
| 3 |
+
from deepeval.models.base_model import DeepEvalBaseLLM
|
| 4 |
+
import litellm
|
| 5 |
+
from config import config
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class LLMJudge(DeepEvalBaseLLM):
|
| 11 |
+
def __init__(self):
|
| 12 |
+
self.model_name = config.SYNTHESIS_MODEL
|
| 13 |
+
self.fallback_model_name = config.SYNTHESIS_FALLBACK
|
| 14 |
+
self.primary_api_key = config.PRIMARY_LLM_API_KEY
|
| 15 |
+
self.secondary_api_key = config.SECONDARY_LLM_API_KEY
|
| 16 |
+
|
| 17 |
+
def load_model(self):
|
| 18 |
+
return self.model_name
|
| 19 |
+
|
| 20 |
+
def generate(self, prompt: str) -> str:
|
| 21 |
+
try:
|
| 22 |
+
response = litellm.completion(
|
| 23 |
+
model=self.model_name,
|
| 24 |
+
messages=[{"role": "user", "content": prompt}],
|
| 25 |
+
api_key=self.primary_api_key,
|
| 26 |
+
temperature=0.1,
|
| 27 |
+
)
|
| 28 |
+
return response.choices[0].message.content
|
| 29 |
+
except Exception as e:
|
| 30 |
+
logger.warning(
|
| 31 |
+
f"Primary model {self.model_name} failed: {e}. Trying fallback."
|
| 32 |
+
)
|
| 33 |
+
if self.fallback_model_name:
|
| 34 |
+
try:
|
| 35 |
+
response = litellm.completion(
|
| 36 |
+
model=self.fallback_model_name,
|
| 37 |
+
messages=[{"role": "user", "content": prompt}],
|
| 38 |
+
api_key=self.secondary_api_key,
|
| 39 |
+
temperature=0.1,
|
| 40 |
+
)
|
| 41 |
+
return response.choices[0].message.content
|
| 42 |
+
except Exception as fallback_e:
|
| 43 |
+
logger.error(
|
| 44 |
+
f"Fallback model {self.fallback_model_name} also failed: {fallback_e}"
|
| 45 |
+
)
|
| 46 |
+
raise fallback_e
|
| 47 |
+
else:
|
| 48 |
+
raise e
|
| 49 |
+
|
| 50 |
+
async def a_generate(self, prompt: str) -> str:
|
| 51 |
+
try:
|
| 52 |
+
response = await litellm.acompletion(
|
| 53 |
+
model=self.model_name,
|
| 54 |
+
messages=[{"role": "user", "content": prompt}],
|
| 55 |
+
api_key=self.primary_api_key,
|
| 56 |
+
temperature=0.1,
|
| 57 |
+
)
|
| 58 |
+
return response.choices[0].message.content
|
| 59 |
+
except Exception as e:
|
| 60 |
+
logger.warning(
|
| 61 |
+
f"Primary model {self.model_name} failed: {e}. Trying fallback."
|
| 62 |
+
)
|
| 63 |
+
if self.fallback_model_name:
|
| 64 |
+
try:
|
| 65 |
+
response = await litellm.acompletion(
|
| 66 |
+
model=self.fallback_model_name,
|
| 67 |
+
messages=[{"role": "user", "content": prompt}],
|
| 68 |
+
api_key=self.secondary_api_key,
|
| 69 |
+
temperature=0.1,
|
| 70 |
+
)
|
| 71 |
+
return response.choices[0].message.content
|
| 72 |
+
except Exception as fallback_e:
|
| 73 |
+
logger.error(
|
| 74 |
+
f"Fallback model {self.fallback_model_name} also failed: {fallback_e}"
|
| 75 |
+
)
|
| 76 |
+
raise fallback_e
|
| 77 |
+
else:
|
| 78 |
+
raise e
|
| 79 |
+
|
| 80 |
+
def get_model_name(self):
|
| 81 |
+
return self.model_name
|
tests/test_necthrall_evaluation.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Validation tests to assess if the golden_dataset is accurate.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from deepeval.metrics import FaithfulnessMetric, AnswerRelevancyMetric
|
| 9 |
+
from deepeval.test_case import LLMTestCase
|
| 10 |
+
from tests.eval_config import LLMJudge
|
| 11 |
+
from tests.citation_metrics import CitationValidityMetric, CitationAccuracyMetric
|
| 12 |
+
|
| 13 |
+
# Load dataset
|
| 14 |
+
DATASET_PATH = os.path.join("tests", "data", "golden_dataset.json")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_dataset():
|
| 18 |
+
if not os.path.exists(DATASET_PATH):
|
| 19 |
+
return []
|
| 20 |
+
with open(DATASET_PATH, "r", encoding="utf-8") as f:
|
| 21 |
+
return json.load(f)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
dataset = load_dataset()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@pytest.fixture
|
| 28 |
+
def llm_judge():
|
| 29 |
+
return LLMJudge()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@pytest.mark.parametrize("entry", dataset)
|
| 33 |
+
def test_faithfulness(entry, llm_judge):
|
| 34 |
+
input_text = entry["input"]
|
| 35 |
+
actual_output = entry["actual_output"]
|
| 36 |
+
retrieval_context = entry["retrieval_context"]
|
| 37 |
+
|
| 38 |
+
metric = FaithfulnessMetric(threshold=0.7, model=llm_judge, include_reason=True)
|
| 39 |
+
|
| 40 |
+
test_case = LLMTestCase(
|
| 41 |
+
input=input_text,
|
| 42 |
+
actual_output=actual_output,
|
| 43 |
+
retrieval_context=retrieval_context,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Measure manually so we can print the score
|
| 47 |
+
metric.measure(test_case)
|
| 48 |
+
|
| 49 |
+
# --- PRINT THE RESULTS ---
|
| 50 |
+
print(f"\n[Faithfulness] Score: {metric.score}")
|
| 51 |
+
print(f"[Faithfulness] Reason: {metric.reason}")
|
| 52 |
+
# -------------------------
|
| 53 |
+
|
| 54 |
+
# Assert success based on the threshold
|
| 55 |
+
assert metric.is_successful(), f"Faithfulness failed. Score: {metric.score}"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@pytest.mark.parametrize("entry", dataset)
|
| 59 |
+
def test_citations(entry, llm_judge):
|
| 60 |
+
input_text = entry["input"]
|
| 61 |
+
actual_output = entry["actual_output"]
|
| 62 |
+
retrieval_context = entry["retrieval_context"]
|
| 63 |
+
|
| 64 |
+
test_case = LLMTestCase(
|
| 65 |
+
input=input_text,
|
| 66 |
+
actual_output=actual_output,
|
| 67 |
+
retrieval_context=retrieval_context,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# 1. Check Validity (Syntax)
|
| 71 |
+
validity_metric = CitationValidityMetric()
|
| 72 |
+
validity_metric.measure(test_case)
|
| 73 |
+
print(f"\n[Citation Validity] Score: {validity_metric.score}")
|
| 74 |
+
print(f"[Citation Validity] Reason: {validity_metric.reason}")
|
| 75 |
+
|
| 76 |
+
# Assert validity first
|
| 77 |
+
assert (
|
| 78 |
+
validity_metric.is_successful()
|
| 79 |
+
), f"Citation Validity Failed: {validity_metric.reason}"
|
| 80 |
+
|
| 81 |
+
# 2. Check Accuracy (Semantics) - Only if validity passes
|
| 82 |
+
accuracy_metric = CitationAccuracyMetric(model=llm_judge)
|
| 83 |
+
accuracy_metric.measure(test_case)
|
| 84 |
+
print(f"[Citation Accuracy] Score: {accuracy_metric.score}")
|
| 85 |
+
print(f"[Citation Accuracy] Reason: {accuracy_metric.reason}")
|
| 86 |
+
|
| 87 |
+
assert (
|
| 88 |
+
accuracy_metric.is_successful()
|
| 89 |
+
), f"Citation Accuracy Failed: {accuracy_metric.reason}"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@pytest.mark.parametrize("entry", dataset)
|
| 93 |
+
def test_answer_relevancy(entry, llm_judge):
|
| 94 |
+
input_text = entry["input"]
|
| 95 |
+
actual_output = entry["actual_output"]
|
| 96 |
+
retrieval_context = entry["retrieval_context"]
|
| 97 |
+
|
| 98 |
+
metric = AnswerRelevancyMetric(threshold=0.7, model=llm_judge, include_reason=True)
|
| 99 |
+
|
| 100 |
+
test_case = LLMTestCase(
|
| 101 |
+
input=input_text,
|
| 102 |
+
actual_output=actual_output,
|
| 103 |
+
retrieval_context=retrieval_context,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# Measure manually so we can print the score
|
| 107 |
+
metric.measure(test_case)
|
| 108 |
+
|
| 109 |
+
# --- PRINT THE RESULTS ---
|
| 110 |
+
print(f"\n[Relevancy] Score: {metric.score}")
|
| 111 |
+
print(f"[Relevancy] Reason: {metric.reason}")
|
| 112 |
+
# -------------------------
|
| 113 |
+
|
| 114 |
+
assert metric.is_successful(), f"Relevancy failed. Score: {metric.score}"
|
tests/test_necthrall_real.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import asyncio
|
| 6 |
+
|
| 7 |
+
# python -m tests.test_necthrall_real
|
| 8 |
+
# --- WINDOWS DLL FIX START ---
|
| 9 |
+
# This must be done BEFORE importing torch
|
| 10 |
+
if os.name == "nt":
|
| 11 |
+
try:
|
| 12 |
+
torch_lib = os.path.join(sys.prefix, "Lib", "site-packages", "torch", "lib")
|
| 13 |
+
if os.path.isdir(torch_lib):
|
| 14 |
+
try:
|
| 15 |
+
os.add_dll_directory(torch_lib)
|
| 16 |
+
except Exception:
|
| 17 |
+
os.environ["PATH"] = torch_lib + os.pathsep + os.environ.get("PATH", "")
|
| 18 |
+
except Exception:
|
| 19 |
+
pass
|
| 20 |
+
# --- WINDOWS DLL FIX END ---
|
| 21 |
+
|
| 22 |
+
# CRITICAL: Import torch FIRST before any other library that might load conflicting DLLs
|
| 23 |
+
# This prevents DLL conflicts with onnxruntime, sentence-transformers, etc.
|
| 24 |
+
try:
|
| 25 |
+
import torch
|
| 26 |
+
except ImportError:
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
from deepeval.metrics import FaithfulnessMetric, AnswerRelevancyMetric
|
| 30 |
+
from deepeval.test_case import LLMTestCase
|
| 31 |
+
from deepeval import assert_test
|
| 32 |
+
from services.query_service import QueryService
|
| 33 |
+
from tests.eval_config import LLMJudge
|
| 34 |
+
from tests.citation_metrics import CitationValidityMetric, CitationAccuracyMetric
|
| 35 |
+
from unittest.mock import patch
|
| 36 |
+
import agents.quality_gate
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Monkey-patch quality gate thresholds for testing
|
| 40 |
+
def lenient_check_thresholds(metrics):
|
| 41 |
+
# Allow fewer papers for testing
|
| 42 |
+
thresholds = {
|
| 43 |
+
"paper_count": (1, "insufficient paper count ({value} < {threshold})"),
|
| 44 |
+
"embedding_coverage": (0.0, "low embedding coverage"),
|
| 45 |
+
"abstract_coverage": (0.0, "low abstract coverage"),
|
| 46 |
+
}
|
| 47 |
+
failures = []
|
| 48 |
+
passed = True
|
| 49 |
+
for metric_name, (threshold, reason_template) in thresholds.items():
|
| 50 |
+
value = metrics[metric_name]
|
| 51 |
+
if value < threshold:
|
| 52 |
+
passed = False
|
| 53 |
+
reason = reason_template.format(value=value, threshold=threshold)
|
| 54 |
+
failures.append(reason)
|
| 55 |
+
|
| 56 |
+
return passed, "; ".join(failures) if not passed else "Quality gate passed"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
agents.quality_gate._check_thresholds = lenient_check_thresholds
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# Load dataset
|
| 63 |
+
DATASET_PATH = os.path.join("tests", "data", "golden_dataset.json")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def load_dataset():
|
| 67 |
+
if not os.path.exists(DATASET_PATH):
|
| 68 |
+
return []
|
| 69 |
+
with open(DATASET_PATH, "r", encoding="utf-8") as f:
|
| 70 |
+
return json.load(f)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# Load only the first 2 entries to save costs/time
|
| 74 |
+
full_dataset = load_dataset()
|
| 75 |
+
dataset = full_dataset[:2] if full_dataset else []
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@pytest.fixture(scope="module")
|
| 79 |
+
def llm_judge():
|
| 80 |
+
return LLMJudge()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@pytest.fixture(scope="module")
|
| 84 |
+
def app_service():
|
| 85 |
+
# Initialize the service (embedding model loads lazily)
|
| 86 |
+
return QueryService()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@pytest.mark.asyncio
|
| 90 |
+
@pytest.mark.parametrize("entry", dataset)
|
| 91 |
+
async def test_necthrall_end_to_end(entry, app_service, llm_judge):
|
| 92 |
+
input_query = entry["input"]
|
| 93 |
+
expected_output = entry[
|
| 94 |
+
"actual_output"
|
| 95 |
+
] # Not strictly used for RAG eval but good for reference
|
| 96 |
+
|
| 97 |
+
print(f"\n\n--- Testing Query: {input_query} ---")
|
| 98 |
+
|
| 99 |
+
# 1. Run the Application (The "Student")
|
| 100 |
+
result = await app_service.process_query(input_query)
|
| 101 |
+
|
| 102 |
+
# Check for pipeline failure
|
| 103 |
+
assert result.success, f"Pipeline failed: {result.error}"
|
| 104 |
+
assert result.answer, "Pipeline returned empty answer"
|
| 105 |
+
|
| 106 |
+
actual_answer = result.answer
|
| 107 |
+
# Extract text from passage objects
|
| 108 |
+
retrieved_passages = [p.text for p in result.passages] if result.passages else []
|
| 109 |
+
|
| 110 |
+
print(f"Answer Generated: {actual_answer[:100]}...")
|
| 111 |
+
print(f"Passages Retrieved: {len(retrieved_passages)}")
|
| 112 |
+
|
| 113 |
+
# 2. Evaluate (The "Teacher")
|
| 114 |
+
test_case = LLMTestCase(
|
| 115 |
+
input=input_query,
|
| 116 |
+
actual_output=actual_answer,
|
| 117 |
+
retrieval_context=retrieved_passages,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# Initialize Metrics
|
| 121 |
+
metrics = [
|
| 122 |
+
FaithfulnessMetric(threshold=0.7, model=llm_judge, include_reason=True),
|
| 123 |
+
AnswerRelevancyMetric(threshold=0.7, model=llm_judge, include_reason=True),
|
| 124 |
+
CitationValidityMetric(threshold=1.0),
|
| 125 |
+
CitationAccuracyMetric(model=llm_judge, threshold=0.7),
|
| 126 |
+
]
|
| 127 |
+
|
| 128 |
+
# Measure and Print Results
|
| 129 |
+
for metric in metrics:
|
| 130 |
+
print(f"\nRunning {metric.__name__}...")
|
| 131 |
+
# Handle async measurement for CitationAccuracyMetric if needed,
|
| 132 |
+
# though deepeval usually handles it via .measure() wrapper.
|
| 133 |
+
# However, since we are in an async test, we can call measure directly.
|
| 134 |
+
metric.measure(test_case)
|
| 135 |
+
print(f"[{metric.__name__}] Score: {metric.score}")
|
| 136 |
+
print(f"[{metric.__name__}] Reason: {metric.reason}")
|
| 137 |
+
|
| 138 |
+
# 3. Assert Success
|
| 139 |
+
# We use assert_test to check all metrics at once
|
| 140 |
+
# assert_test(test_case, metrics)
|
| 141 |
+
|
| 142 |
+
print("\n--- Final Results ---")
|
| 143 |
+
failed_metrics = []
|
| 144 |
+
for metric in metrics:
|
| 145 |
+
if not metric.is_successful():
|
| 146 |
+
failed_metrics.append(f"{metric.__name__} (Score: {metric.score})")
|
| 147 |
+
print(f"❌ {metric.__name__} FAILED")
|
| 148 |
+
else:
|
| 149 |
+
print(f"✅ {metric.__name__} PASSED")
|
| 150 |
+
|
| 151 |
+
if failed_metrics:
|
| 152 |
+
raise AssertionError(
|
| 153 |
+
f"The following metrics failed: {', '.join(failed_metrics)}"
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if __name__ == "__main__":
|
| 158 |
+
# Manual test execution
|
| 159 |
+
async def run_manual_test():
|
| 160 |
+
print("Running manual test...")
|
| 161 |
+
try:
|
| 162 |
+
# Setup
|
| 163 |
+
os.environ["LLM_MODEL_PRIMARY"] = "cerebras/llama3.1-8b"
|
| 164 |
+
os.environ["LLM_MODEL_FALLBACK"] = "groq/llama-3.1-8b-instant"
|
| 165 |
+
|
| 166 |
+
# Initialize fixtures
|
| 167 |
+
judge = LLMJudge()
|
| 168 |
+
|
| 169 |
+
# Load embedding model
|
| 170 |
+
print("Loading embedding model...")
|
| 171 |
+
from config.onnx_embedding import initialize_embedding_model
|
| 172 |
+
|
| 173 |
+
embedding_model = initialize_embedding_model()
|
| 174 |
+
|
| 175 |
+
service = QueryService(embedding_model=embedding_model)
|
| 176 |
+
|
| 177 |
+
# Load data
|
| 178 |
+
data = load_dataset()
|
| 179 |
+
if not data:
|
| 180 |
+
print("No data found.")
|
| 181 |
+
return
|
| 182 |
+
|
| 183 |
+
# Run for first entry
|
| 184 |
+
entry = data[0]
|
| 185 |
+
print(f"Testing query: {entry['input']}")
|
| 186 |
+
await test_necthrall_end_to_end(entry, service, judge)
|
| 187 |
+
print("Test passed!")
|
| 188 |
+
except Exception as e:
|
| 189 |
+
print(f"Test failed: {e}")
|
| 190 |
+
import traceback
|
| 191 |
+
|
| 192 |
+
traceback.print_exc()
|
| 193 |
+
|
| 194 |
+
asyncio.run(run_manual_test())
|
tests/unit/test_acquisition_agent.py
CHANGED
|
@@ -29,16 +29,16 @@ class MockContent:
|
|
| 29 |
self._delay = delay_per_chunk
|
| 30 |
self._chunk_size = chunk_size
|
| 31 |
|
| 32 |
-
async def
|
| 33 |
-
for i in range(0, len(self._data),
|
| 34 |
-
if self._delay:
|
| 35 |
await asyncio.sleep(self._delay)
|
| 36 |
-
yield self._data[i : i +
|
| 37 |
|
| 38 |
|
| 39 |
class MockResponse:
|
| 40 |
def __init__(self, status: int, data: bytes = b"", delay_per_chunk: float = 0.0):
|
| 41 |
-
self.
|
| 42 |
self.content = MockContent(data, delay_per_chunk=delay_per_chunk)
|
| 43 |
|
| 44 |
async def __aenter__(self):
|
|
@@ -47,6 +47,9 @@ class MockResponse:
|
|
| 47 |
async def __aexit__(self, exc_type, exc, tb):
|
| 48 |
return False
|
| 49 |
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
class MockSession:
|
| 52 |
def __init__(self, mapping):
|
|
@@ -59,7 +62,7 @@ class MockSession:
|
|
| 59 |
async def __aexit__(self, exc_type, exc, tb):
|
| 60 |
return False
|
| 61 |
|
| 62 |
-
def get(self, url, *args, **kwargs):
|
| 63 |
entry = self._map.get(url)
|
| 64 |
if entry is None:
|
| 65 |
raise RuntimeError("No mapping for URL")
|
|
@@ -78,7 +81,9 @@ async def test_acquisition_enriches_state_success(monkeypatch):
|
|
| 78 |
async def session_factory(*args, **kwargs):
|
| 79 |
return MockSession(mapping)
|
| 80 |
|
| 81 |
-
monkeypatch.setattr(
|
|
|
|
|
|
|
| 82 |
|
| 83 |
state = State(
|
| 84 |
query="q",
|
|
@@ -107,7 +112,9 @@ async def test_acquisition_timeout_skips(monkeypatch):
|
|
| 107 |
url = "https://example.com/slow.pdf"
|
| 108 |
mapping = {url: (200, data, 0.2)}
|
| 109 |
|
| 110 |
-
monkeypatch.setattr(
|
|
|
|
|
|
|
| 111 |
|
| 112 |
state = State(
|
| 113 |
query="q",
|
|
@@ -129,7 +136,9 @@ async def test_acquisition_http_404_skips(monkeypatch):
|
|
| 129 |
url = "https://example.com/notfound.pdf"
|
| 130 |
mapping = {url: (404, b"", 0.0)}
|
| 131 |
|
| 132 |
-
monkeypatch.setattr(
|
|
|
|
|
|
|
| 133 |
|
| 134 |
state = State(
|
| 135 |
query="q",
|
|
@@ -152,7 +161,9 @@ async def test_acquisition_malformed_pdf_skips(monkeypatch):
|
|
| 152 |
url = "https://example.com/bad.pdf"
|
| 153 |
mapping = {url: (200, b"not-a-pdf", 0.0)}
|
| 154 |
|
| 155 |
-
monkeypatch.setattr(
|
|
|
|
|
|
|
| 156 |
|
| 157 |
state = State(
|
| 158 |
query="q",
|
|
@@ -175,7 +186,9 @@ async def test_acquisition_zero_successes_appends_error(monkeypatch):
|
|
| 175 |
# all 404 -> no successes -> state.errors contains critical message
|
| 176 |
urls = [f"https://example.com/n{i}.pdf" for i in range(3)]
|
| 177 |
mapping = {u: (404, b"", 0.0) for u in urls}
|
| 178 |
-
monkeypatch.setattr(
|
|
|
|
|
|
|
| 179 |
|
| 180 |
finalists = [
|
| 181 |
{"paperId": f"n{i}", "title": "T", "openAccessPdf": {"url": urls[i]}}
|
|
@@ -208,7 +221,9 @@ async def test_acquisition_get_raises_timeout(monkeypatch):
|
|
| 208 |
def get(self, url, *args, **kwargs):
|
| 209 |
raise asyncio.TimeoutError()
|
| 210 |
|
| 211 |
-
monkeypatch.setattr(
|
|
|
|
|
|
|
| 212 |
|
| 213 |
state = State(
|
| 214 |
query="q",
|
|
@@ -243,7 +258,9 @@ async def test_acquisition_parallel_10_with_2_failures(monkeypatch):
|
|
| 243 |
else:
|
| 244 |
mapping[u] = (200, fast_bytes, 0.2)
|
| 245 |
|
| 246 |
-
monkeypatch.setattr(
|
|
|
|
|
|
|
| 247 |
|
| 248 |
finalists = [
|
| 249 |
{"paperId": f"p{i}", "title": "T", "openAccessPdf": {"url": urls[i]}}
|
|
|
|
| 29 |
self._delay = delay_per_chunk
|
| 30 |
self._chunk_size = chunk_size
|
| 31 |
|
| 32 |
+
async def aiter_content(self, chunk_size=1024):
|
| 33 |
+
for i in range(0, len(self._data), chunk_size):
|
| 34 |
+
if self._delay > 0:
|
| 35 |
await asyncio.sleep(self._delay)
|
| 36 |
+
yield self._data[i : i + chunk_size]
|
| 37 |
|
| 38 |
|
| 39 |
class MockResponse:
|
| 40 |
def __init__(self, status: int, data: bytes = b"", delay_per_chunk: float = 0.0):
|
| 41 |
+
self.status_code = status
|
| 42 |
self.content = MockContent(data, delay_per_chunk=delay_per_chunk)
|
| 43 |
|
| 44 |
async def __aenter__(self):
|
|
|
|
| 47 |
async def __aexit__(self, exc_type, exc, tb):
|
| 48 |
return False
|
| 49 |
|
| 50 |
+
def aiter_content(self, chunk_size=1024):
|
| 51 |
+
return self.content.aiter_content(chunk_size)
|
| 52 |
+
|
| 53 |
|
| 54 |
class MockSession:
|
| 55 |
def __init__(self, mapping):
|
|
|
|
| 62 |
async def __aexit__(self, exc_type, exc, tb):
|
| 63 |
return False
|
| 64 |
|
| 65 |
+
async def get(self, url, *args, **kwargs):
|
| 66 |
entry = self._map.get(url)
|
| 67 |
if entry is None:
|
| 68 |
raise RuntimeError("No mapping for URL")
|
|
|
|
| 81 |
async def session_factory(*args, **kwargs):
|
| 82 |
return MockSession(mapping)
|
| 83 |
|
| 84 |
+
monkeypatch.setattr(
|
| 85 |
+
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
|
| 86 |
+
)
|
| 87 |
|
| 88 |
state = State(
|
| 89 |
query="q",
|
|
|
|
| 112 |
url = "https://example.com/slow.pdf"
|
| 113 |
mapping = {url: (200, data, 0.2)}
|
| 114 |
|
| 115 |
+
monkeypatch.setattr(
|
| 116 |
+
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
|
| 117 |
+
)
|
| 118 |
|
| 119 |
state = State(
|
| 120 |
query="q",
|
|
|
|
| 136 |
url = "https://example.com/notfound.pdf"
|
| 137 |
mapping = {url: (404, b"", 0.0)}
|
| 138 |
|
| 139 |
+
monkeypatch.setattr(
|
| 140 |
+
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
|
| 141 |
+
)
|
| 142 |
|
| 143 |
state = State(
|
| 144 |
query="q",
|
|
|
|
| 161 |
url = "https://example.com/bad.pdf"
|
| 162 |
mapping = {url: (200, b"not-a-pdf", 0.0)}
|
| 163 |
|
| 164 |
+
monkeypatch.setattr(
|
| 165 |
+
"curl_cffi.requests.AsyncSession", lambda *a, **k: MockSession(mapping)
|
| 166 |
+
)
|
| 167 |
|
| 168 |
state = State(
|
| 169 |
query="q",
|
|
|
|
| 186 |
# all 404 -> no successes -> state.errors contains critical message
|
| 187 |
urls = [f"https://example.com/n{i}.pdf" for i in range(3)]
|
| 188 |
mapping = {u: (404, b"", 0.0) for u in urls}
|
| 189 |
+
monkeypatch.setattr(
|
| 190 |
+
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
|
| 191 |
+
)
|
| 192 |
|
| 193 |
finalists = [
|
| 194 |
{"paperId": f"n{i}", "title": "T", "openAccessPdf": {"url": urls[i]}}
|
|
|
|
| 221 |
def get(self, url, *args, **kwargs):
|
| 222 |
raise asyncio.TimeoutError()
|
| 223 |
|
| 224 |
+
monkeypatch.setattr(
|
| 225 |
+
"agents.acquisition_agent.AsyncSession", lambda *a, **k: RaisingSession()
|
| 226 |
+
)
|
| 227 |
|
| 228 |
state = State(
|
| 229 |
query="q",
|
|
|
|
| 258 |
else:
|
| 259 |
mapping[u] = (200, fast_bytes, 0.2)
|
| 260 |
|
| 261 |
+
monkeypatch.setattr(
|
| 262 |
+
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
|
| 263 |
+
)
|
| 264 |
|
| 265 |
finalists = [
|
| 266 |
{"paperId": f"p{i}", "title": "T", "openAccessPdf": {"url": urls[i]}}
|
tests/unit/test_pdf_extractor.py
CHANGED
|
@@ -1,9 +1,12 @@
|
|
| 1 |
import pytest
|
|
|
|
|
|
|
| 2 |
|
| 3 |
import fitz
|
| 4 |
|
| 5 |
from utils.pdf_extractor import (
|
| 6 |
-
|
|
|
|
| 7 |
CorruptedPDFError,
|
| 8 |
EmptyPDFError,
|
| 9 |
InsufficientTextError,
|
|
@@ -26,20 +29,30 @@ def make_pdf_bytes(pages: int = 3, long: bool = True) -> bytes:
|
|
| 26 |
@pytest.mark.unit
|
| 27 |
def test_extract_valid_pdf():
|
| 28 |
pdf_bytes = make_pdf_bytes(pages=5, long=True)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
@pytest.mark.unit
|
| 36 |
def test_extract_produces_markdown_structure():
|
| 37 |
"""Test that PyMuPDF4LLM produces Markdown with potential headers."""
|
| 38 |
pdf_bytes = make_pdf_bytes(pages=3, long=True)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
assert isinstance(text, str)
|
| 44 |
assert len(text) >= 500
|
| 45 |
# Note: Exact Markdown format depends on PDF structure
|
|
@@ -49,9 +62,14 @@ def test_extract_produces_markdown_structure():
|
|
| 49 |
@pytest.mark.unit
|
| 50 |
def test_corrupted_pdf_raises_error():
|
| 51 |
corrupted_bytes = b"not-a-pdf"
|
| 52 |
-
with
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
@pytest.mark.unit
|
|
@@ -61,18 +79,28 @@ def test_empty_pdf_raises_error():
|
|
| 61 |
doc = fitz.open()
|
| 62 |
doc.new_page()
|
| 63 |
empty_bytes = doc.write()
|
| 64 |
-
with
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
|
| 69 |
@pytest.mark.unit
|
| 70 |
def test_insufficient_text_raises_error():
|
| 71 |
short_pdf = make_pdf_bytes(pages=1, long=False)
|
| 72 |
-
with
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
@pytest.mark.unit
|
|
@@ -103,13 +131,18 @@ def test_password_protected_pdf_raises_corrupted_error():
|
|
| 103 |
if encrypted_bytes is None:
|
| 104 |
pytest.skip("Could not produce encrypted PDF bytes in this environment")
|
| 105 |
|
| 106 |
-
# If bytes are encrypted, we expect a
|
|
|
|
|
|
|
|
|
|
| 107 |
try:
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
| 1 |
import pytest
|
| 2 |
+
import tempfile
|
| 3 |
+
import os
|
| 4 |
|
| 5 |
import fitz
|
| 6 |
|
| 7 |
from utils.pdf_extractor import (
|
| 8 |
+
extract_text_from_pdf_file,
|
| 9 |
+
PdfExtractionError,
|
| 10 |
CorruptedPDFError,
|
| 11 |
EmptyPDFError,
|
| 12 |
InsufficientTextError,
|
|
|
|
| 29 |
@pytest.mark.unit
|
| 30 |
def test_extract_valid_pdf():
|
| 31 |
pdf_bytes = make_pdf_bytes(pages=5, long=True)
|
| 32 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 33 |
+
tmp.write(pdf_bytes)
|
| 34 |
+
tmp_path = tmp.name
|
| 35 |
+
try:
|
| 36 |
+
text = extract_text_from_pdf_file(tmp_path)
|
| 37 |
+
assert isinstance(text, str)
|
| 38 |
+
assert len(text) >= 500
|
| 39 |
+
finally:
|
| 40 |
+
os.unlink(tmp_path)
|
| 41 |
|
| 42 |
|
| 43 |
@pytest.mark.unit
|
| 44 |
def test_extract_produces_markdown_structure():
|
| 45 |
"""Test that PyMuPDF4LLM produces Markdown with potential headers."""
|
| 46 |
pdf_bytes = make_pdf_bytes(pages=3, long=True)
|
| 47 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 48 |
+
tmp.write(pdf_bytes)
|
| 49 |
+
tmp_path = tmp.name
|
| 50 |
+
try:
|
| 51 |
+
text = extract_text_from_pdf_file(tmp_path)
|
| 52 |
+
# PyMuPDF4LLM may add Markdown formatting
|
| 53 |
+
# At minimum, we should get structured text
|
| 54 |
+
finally:
|
| 55 |
+
os.unlink(tmp_path)
|
| 56 |
assert isinstance(text, str)
|
| 57 |
assert len(text) >= 500
|
| 58 |
# Note: Exact Markdown format depends on PDF structure
|
|
|
|
| 62 |
@pytest.mark.unit
|
| 63 |
def test_corrupted_pdf_raises_error():
|
| 64 |
corrupted_bytes = b"not-a-pdf"
|
| 65 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 66 |
+
tmp.write(corrupted_bytes)
|
| 67 |
+
tmp_path = tmp.name
|
| 68 |
+
try:
|
| 69 |
+
with pytest.raises(PdfExtractionError):
|
| 70 |
+
extract_text_from_pdf_file(tmp_path)
|
| 71 |
+
finally:
|
| 72 |
+
os.unlink(tmp_path)
|
| 73 |
|
| 74 |
|
| 75 |
@pytest.mark.unit
|
|
|
|
| 79 |
doc = fitz.open()
|
| 80 |
doc.new_page()
|
| 81 |
empty_bytes = doc.write()
|
| 82 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 83 |
+
tmp.write(empty_bytes)
|
| 84 |
+
tmp_path = tmp.name
|
| 85 |
+
try:
|
| 86 |
+
with pytest.raises(InsufficientTextError):
|
| 87 |
+
extract_text_from_pdf_file(tmp_path, min_length=500)
|
| 88 |
+
finally:
|
| 89 |
+
os.unlink(tmp_path)
|
| 90 |
|
| 91 |
|
| 92 |
@pytest.mark.unit
|
| 93 |
def test_insufficient_text_raises_error():
|
| 94 |
short_pdf = make_pdf_bytes(pages=1, long=False)
|
| 95 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 96 |
+
tmp.write(short_pdf)
|
| 97 |
+
tmp_path = tmp.name
|
| 98 |
+
try:
|
| 99 |
+
with pytest.raises(InsufficientTextError) as exc:
|
| 100 |
+
extract_text_from_pdf_file(tmp_path, min_length=500)
|
| 101 |
+
assert "Extracted text too short" in str(exc.value)
|
| 102 |
+
finally:
|
| 103 |
+
os.unlink(tmp_path)
|
| 104 |
|
| 105 |
|
| 106 |
@pytest.mark.unit
|
|
|
|
| 131 |
if encrypted_bytes is None:
|
| 132 |
pytest.skip("Could not produce encrypted PDF bytes in this environment")
|
| 133 |
|
| 134 |
+
# If bytes are encrypted, we expect a PdfExtractionError (treat encryption as unreadable)
|
| 135 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 136 |
+
tmp.write(encrypted_bytes)
|
| 137 |
+
tmp_path = tmp.name
|
| 138 |
try:
|
| 139 |
+
try:
|
| 140 |
+
with pytest.raises(PdfExtractionError):
|
| 141 |
+
extract_text_from_pdf_file(tmp_path)
|
| 142 |
+
except AssertionError:
|
| 143 |
+
# If the environment didn't actually encrypt the bytes, allow the test to
|
| 144 |
+
# assert the extractor can extract text instead.
|
| 145 |
+
text = extract_text_from_pdf_file(tmp_path)
|
| 146 |
+
assert isinstance(text, str)
|
| 147 |
+
finally:
|
| 148 |
+
os.unlink(tmp_path)
|
tests/unit/test_synthesis_agent.py
CHANGED
|
@@ -197,7 +197,6 @@ def test_citation_prompt_template_format():
|
|
| 197 |
assert "{context_str}" in CITATION_QA_TEMPLATE
|
| 198 |
assert "{query_str}" in CITATION_QA_TEMPLATE
|
| 199 |
assert "ONLY" in CITATION_QA_TEMPLATE # Emphasis on using only context
|
| 200 |
-
assert "[N]" in CITATION_QA_TEMPLATE # Citation format instruction
|
| 201 |
|
| 202 |
|
| 203 |
@pytest.mark.unit
|
|
|
|
| 197 |
assert "{context_str}" in CITATION_QA_TEMPLATE
|
| 198 |
assert "{query_str}" in CITATION_QA_TEMPLATE
|
| 199 |
assert "ONLY" in CITATION_QA_TEMPLATE # Emphasis on using only context
|
|
|
|
| 200 |
|
| 201 |
|
| 202 |
@pytest.mark.unit
|
ui/pages.py
CHANGED
|
@@ -4,6 +4,7 @@ import asyncio
|
|
| 4 |
from pathlib import Path
|
| 5 |
from nicegui import ui, context, app
|
| 6 |
from loguru import logger
|
|
|
|
| 7 |
|
| 8 |
from ui.styles import CUSTOM_CSS
|
| 9 |
from ui.components import (
|
|
@@ -451,9 +452,9 @@ def init_ui(fastapi_app):
|
|
| 451 |
):
|
| 452 |
# Center everything on all sizes: branding and links stacked and centered
|
| 453 |
with ui.column().classes("w-full items-center gap-2 text-center"):
|
| 454 |
-
ui.label(
|
| 455 |
-
"
|
| 456 |
-
)
|
| 457 |
ui.label(
|
| 458 |
"AI can make mistakes. Always verify important citations."
|
| 459 |
).classes("italic text-sm break-words max-w-full px-4")
|
|
|
|
| 4 |
from pathlib import Path
|
| 5 |
from nicegui import ui, context, app
|
| 6 |
from loguru import logger
|
| 7 |
+
import datetime
|
| 8 |
|
| 9 |
from ui.styles import CUSTOM_CSS
|
| 10 |
from ui.components import (
|
|
|
|
| 452 |
):
|
| 453 |
# Center everything on all sizes: branding and links stacked and centered
|
| 454 |
with ui.column().classes("w-full items-center gap-2 text-center"):
|
| 455 |
+
ui.label(
|
| 456 |
+
f"© {str(datetime.date.today().year)} Necthrall. Research responsibly."
|
| 457 |
+
).classes("font-bold")
|
| 458 |
ui.label(
|
| 459 |
"AI can make mistakes. Always verify important citations."
|
| 460 |
).classes("italic text-sm break-words max-w-full px-4")
|