File size: 6,088 Bytes
89a139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddda2b6
89a139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddda2b6
89a139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddda2b6
89a139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
"""Quality gate module for validating retrieved Semantic Scholar papers.

Provides early-stop validation to ensure sufficient paper quality before proceeding
with downstream processing. Validates against minimum thresholds for paper count,
embedding coverage, abstract coverage, and median semantic similarity.

Usage example:
    from agents.quality_gate import validate_quality
    import numpy as np

    papers = [...]  # List of paper dicts from Semantic Scholar
    query_embedding = np.random.rand(768)  # SPECTER2 embedding (768D)

    result = validate_quality(papers, query_embedding)
    if not result["passed"]:
        print(f"Validation failed: {result['reason']}")
"""

from typing import Dict, List, Tuple
import numpy as np
from loguru import logger


def validate_quality(
    papers: List[Dict], query_embedding: np.ndarray | None = None
) -> Dict:
    """Validate retrieved papers against quality thresholds.

    Performs comprehensive quality checks on Semantic Scholar paper results:
    - Minimum paper count (>=25)
    - Embedding coverage (>=60% have SPECTER2 embeddings)
    - Abstract coverage (>=60% have abstracts)

    Args:
        papers: List of paper dictionaries from Semantic Scholar API.
        query_embedding: 384 or 768-dimensional SPECTER/SPECTER2 embedding of the original query.

    Returns:
        Dict with keys:
        - passed: bool indicating if all criteria met
        - metrics: Dict with paper_count, embedding_coverage, abstract_coverage
        - reason: Human-readable explanation (empty string if passed)

    Raises:
        ValueError: If inputs are invalid (query_embedding not 384D/768D array, papers not list of dicts).
        TypeError: If paper items are not dictionaries or missing required fields.
    """
    # Comprehensive input validation
    _validate_inputs(papers, query_embedding)

    # Compute all metrics
    metrics = _compute_metrics(papers, query_embedding)

    # Log metrics for monitoring
    logger.info(
        "Quality gate metrics computed: paper_count={}, embedding_coverage={:.2%}, "
        "abstract_coverage={:.2%}",
        metrics["paper_count"],
        metrics["embedding_coverage"],
        metrics["abstract_coverage"],
    )

    # Check against thresholds
    passed, reason = _check_thresholds(metrics)

    result = {
        "passed": passed,
        "metrics": metrics,
        "reason": reason,
    }

    if not passed:
        logger.warning("Quality gate failed: {} | Metrics: {}", reason, metrics)

    return result


def _validate_inputs(papers: List[Dict], query_embedding: np.ndarray | None) -> None:
    """Validate input parameters with clear error messages."""
    if not isinstance(papers, list):
        raise TypeError("papers must be a list of dictionaries")

    if not papers:
        raise ValueError("papers list cannot be empty")

    for i, paper in enumerate(papers):
        if not isinstance(paper, dict):
            raise TypeError(f"paper at index {i} must be a dictionary")
        if "paperId" not in paper:
            raise ValueError(f"paper at index {i} missing required 'paperId' field")

    if query_embedding is not None:
        if not isinstance(query_embedding, np.ndarray):
            raise TypeError("query_embedding must be a numpy array")

        if query_embedding.shape not in [(384,), (768,)]:
            raise ValueError(
                f"query_embedding must be 384 or 768-dimensional, got shape {query_embedding.shape}"
            )

        if not np.isfinite(query_embedding).all():
            raise ValueError("query_embedding contains non-finite values (NaN or inf)")


def _compute_metrics(papers: List[Dict], query_embedding: np.ndarray) -> Dict:
    """Compute all quality metrics from papers and query embedding."""
    paper_count = len(papers)

    # Count papers with abstracts
    abstract_count = sum(
        1
        for p in papers
        if isinstance(p.get("abstract"), str) and p["abstract"].strip()
    )
    abstract_coverage = abstract_count / paper_count if paper_count > 0 else 0.0

    # Collect valid embeddings
    embeddings = []
    for p in papers:
        emb_dict = p.get("embedding")
        if emb_dict is not None and isinstance(emb_dict, dict):
            emb = emb_dict.get("specter")
            if emb is not None and isinstance(emb, (list, np.ndarray)):
                try:
                    emb_array = np.array(emb, dtype=np.float32)
                    # Accept both 384 (older SPECTER) and 768 (SPECTER2) dimensions
                    if (
                        emb_array.shape in [(384,), (768,)]
                        and np.isfinite(emb_array).all()
                    ):
                        embeddings.append(emb_array)
                except (ValueError, TypeError):
                    continue  # Skip invalid embeddings

    embedding_count = len(embeddings)
    embedding_coverage = embedding_count / paper_count if paper_count > 0 else 0.0

    return {
        "paper_count": paper_count,
        "embedding_coverage": embedding_coverage,
        "abstract_coverage": abstract_coverage,
    }


def _check_thresholds(metrics: Dict) -> Tuple[bool, str]:
    """Check metrics against quality thresholds and return pass/fail with reason."""
    thresholds = {
        "paper_count": (25, "insufficient paper count ({value} < {threshold})"),
        "embedding_coverage": (
            0.0,
            "low embedding coverage ({value:.2%} < {threshold:.0%})",
        ),
        "abstract_coverage": (
            0.6,
            "low abstract coverage ({value:.2%} < {threshold:.0%})",
        ),
    }

    failures = []
    passed = True

    for metric_name, (threshold, reason_template) in thresholds.items():
        value = metrics[metric_name]
        if value < threshold:
            passed = False
            reason = reason_template.format(value=value, threshold=threshold)
            failures.append(reason)

    if passed:
        reason = "Quality gate passed"
    else:
        reason = "; ".join(failures)

    return passed, reason