File size: 9,772 Bytes
698b399
89a139c
 
 
c5f836c
698b399
c5f836c
 
 
 
 
698b399
c5f836c
 
 
 
89a139c
 
 
 
cb96d83
89a139c
c5f836c
115794d
 
89a139c
698b399
61f9b59
115794d
5b48ad6
9a32423
56bcac1
115794d
 
c5f836c
89a139c
 
 
c5f836c
 
 
 
 
 
 
 
 
 
 
 
698b399
4170752
 
70a17d8
c5f836c
89a139c
 
61f9b59
89a139c
5b48ad6
89a139c
 
 
 
 
5b48ad6
4170752
 
70a17d8
89a139c
 
 
698b399
c5f836c
89a139c
 
115794d
89a139c
 
 
115794d
c5f836c
89a139c
115794d
89a139c
c5f836c
115794d
61f9b59
115794d
 
 
 
 
 
70a17d8
a1bbee2
c59edc0
 
 
 
a1bbee2
698b399
c5f836c
698b399
9a32423
 
 
89a139c
 
 
c59edc0
a1bbee2
89a139c
 
 
 
 
 
 
 
 
9a32423
 
89a139c
 
 
 
 
 
 
 
c5f836c
70a17d8
89a139c
 
a1bbee2
 
 
 
 
 
 
 
89a139c
 
a1bbee2
 
61f9b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5f836c
9a32423
c5f836c
61f9b59
 
 
9a32423
 
 
 
 
 
 
c5f836c
61f9b59
 
 
 
c5f836c
9a32423
698b399
9a32423
 
 
c5f836c
 
9a32423
 
 
a1bbee2
c5f836c
c59edc0
 
 
 
 
 
 
 
 
 
 
115794d
 
c59edc0
 
9a32423
c59edc0
 
9a32423
 
 
c5f836c
 
4170752
9a32423
4170752
9a32423
 
 
 
4170752
c59edc0
89a139c
9a32423
 
 
 
 
 
 
 
 
 
 
89a139c
9a32423
89a139c
 
 
9a32423
 
 
 
 
 
 
 
 
89a139c
9a32423
 
 
 
 
 
 
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""Query service for orchestrating the pipeline.

Handles the complete query processing pipeline with comprehensive error handling,
detailed timing instrumentation, and structured logging.

Stages (1-4):
    1. Query Optimization
    2. Semantic Scholar Search
    3. Quality Gate
    4. Composite Scoring

Stages (5-8):
    5. PDF Acquisition
    6. Processing & Embedding
    7. Hybrid Retrieval
    8. Cross-Encoder Reranking
"""

from __future__ import annotations

import asyncio
import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional

from loguru import logger

from agents.query_optimization_agent import QueryOptimizationAgent
from config.config import Settings
from models.state import Paper, Passage
from services.discovery_service import DiscoveryService
from services.exceptions import QueryServiceError
from services.ingestion_service import IngestionService
from services.rag_service import RAGService


@dataclass
class PipelineResult:
    """Result of pipeline execution.

    Attributes:
        query: Original user query.
        optimized_queries: Dict with primary, broad, alternative, and final_rephrase.
        quality_gate: Quality gate validation results.
        finalists: Top ranked papers after composite scoring.
        execution_time: Total pipeline execution time in seconds.
        timing_breakdown: Per-stage timing in seconds.
        success: Whether pipeline completed successfully.
        error_message: Error message if pipeline failed.
        error_stage: Stage where error occurred.
        passages: Top ranked passages after reranking.
        answer: Synthesized answer from passages (Stage 9).
        citation_verification: Citation verification result (Stage 10).
        refinement_count: Number of query refinement attempts (0 or 1).
    """

    query: str
    optimized_queries: Dict[str, Any]
    quality_gate: Dict[str, Any]
    finalists: List[Paper]
    execution_time: float
    timing_breakdown: Dict[str, float]
    success: bool
    error_message: Optional[str] = None
    error_stage: Optional[str] = None
    passages: List[Passage] = field(default_factory=list)
    answer: Optional[str] = None
    citation_verification: Optional[Dict[str, Any]] = None
    refinement_count: int = 0


class QueryService:
    """Service for orchestrating the query pipeline.
    Provides comprehensive error handling and performance monitoring.
    """

    def __init__(self, settings: Settings, embedding_model: Any):
        """Initialize the query service.

        Args:
            settings: Application settings.
            embedding_model: Pre-loaded embedding model for query/passage embedding.
        """
        self.settings = settings
        self.embedding_model = embedding_model

        # Initialize agents/services immediately
        self.optimization_agent = QueryOptimizationAgent()
        self.discovery_service = DiscoveryService(settings)
        self.ingestion_service = IngestionService(embedding_model)
        self.rag_service = RAGService(embedding_model, settings)

    async def close(self):
        await self.discovery_service.close()

    async def process_query(
        self,
        query: str,
        deep_mode: bool = True,
        progress_callback: Optional[Callable] = None,
    ) -> PipelineResult:
        """Process a user query through the complete pipeline.

        Stages:
            1-4: Discovery (Optimization, Search, Quality Gate, Ranking)
            5-6: Ingestion (Acquisition, Processing)
            7-10: RAG (Retrieval, Reranking, Synthesis, Verification)

        Args:
            query: The user query string
            deep_mode: Whether to perform deep PDF analysis (True) or fast abstract search (False)
            progress_callback: Optional async callback to report progress

        Returns:
            PipelineResult with all processing results and metadata

        Raises:
            QueryServiceError: For pipeline-specific errors
        """
        start_time = time.perf_counter()
        timing_breakdown = {}

        # Initialize result with defaults
        result = PipelineResult(
            query=query,
            optimized_queries={},
            quality_gate={},
            finalists=[],
            execution_time=0.0,
            timing_breakdown={},
            success=False,
            passages=[],
            refinement_count=0,
        )

        # Helper to safely await callback
        async def report_progress():
            if progress_callback:
                if asyncio.iscoroutinefunction(progress_callback):
                    await progress_callback()
                else:
                    progress_callback()

        try:
            logger.info("Starting query pipeline for: {}", query[:100])
            await report_progress()

            # ======0: Planning (Optimization)
            # =====================================================================
            opt_start = time.perf_counter()
            optimization_result = None
            try:
                optimization_result = (
                    await self.optimization_agent.generate_dual_queries(query)
                )
            except Exception as e:
                logger.error(
                    "Optimization failed in QueryService, proceeding with fallback: {}",
                    e,
                )

            opt_time = time.perf_counter() - opt_start

            # =====================================================================
            # Phase 1: Discovery (Stages 1-4)
            # =====================================================================
            discovery_result = await self.discovery_service.discover(
                query, optimized_data=optimization_result
            )

            # Update result and timing
            result.optimized_queries = discovery_result.optimized_queries
            result.quality_gate = discovery_result.quality_gate
            result.finalists = discovery_result.finalists
            result.refinement_count = discovery_result.refinement_count
            timing_breakdown.update(discovery_result.timing_breakdown)

            # Ensure our optimization time is preserved if we ran it
            if optimization_result:
                timing_breakdown["query_optimization"] = opt_time

            # Check if we have finalists to process
            if not discovery_result.finalists:
                logger.info("ℹ️ No finalists to process")
                result.execution_time = time.perf_counter() - start_time
                result.timing_breakdown = timing_breakdown
                result.success = True
                return result

            # =====================================================================
            # Phase 2: Ingestion (Stages 5-6)
            # =====================================================================
            await report_progress()

            chunks = []

            if deep_mode:
                ingestion_result = await self.ingestion_service.ingest(
                    discovery_result.finalists, query
                )

                # Update timing
                timing_breakdown.update(ingestion_result.timing_breakdown)
                chunks = ingestion_result.chunks
            else:
                chunks = await self.ingestion_service.ingest_abstracts(
                    discovery_result.finalists
                )

            # Check if we have chunks to process
            if not chunks:
                logger.warning("⚠️ No chunks generated from ingestion (or fast mode)")
                result.execution_time = time.perf_counter() - start_time
                result.timing_breakdown = timing_breakdown
                result.success = True
                return result

            # =====================================================================
            # Phase 3: RAG (Stages 7-10)
            # =====================================================================
            await report_progress()

            # Use final_rephrase for RAG if available, else original query
            rag_query = discovery_result.optimized_queries.get("final_rephrase", query)

            rag_result = await self.rag_service.answer(rag_query, chunks)

            # Update result and timing
            result.passages = rag_result.passages
            result.answer = rag_result.answer
            result.citation_verification = rag_result.citation_verification
            timing_breakdown.update(rag_result.timing_breakdown)

            # Finalize result
            result.execution_time = time.perf_counter() - start_time
            result.timing_breakdown = timing_breakdown
            result.success = True

            logger.info(
                "✅ Pipeline completed successfully in {:.3f}s", result.execution_time
            )
            return result

        except QueryServiceError as e:
            logger.error("Pipeline failed at stage {}: {}", e.stage, e.message)
            result.execution_time = time.perf_counter() - start_time
            result.timing_breakdown = timing_breakdown
            result.success = False
            result.error_message = e.message
            result.error_stage = e.stage
            return result

        except Exception as e:
            logger.exception("Unexpected pipeline error")
            result.execution_time = time.perf_counter() - start_time
            result.timing_breakdown = timing_breakdown
            result.success = False
            result.error_message = f"Unexpected error: {str(e)}"
            result.error_stage = "unknown"
            return result