File size: 6,996 Bytes
89a139c
cd26350
89a139c
 
 
cd26350
 
698b399
6078097
115794d
6078097
 
89a139c
 
115794d
89a139c
cd26350
 
 
89a139c
cd26350
395c9ad
89a139c
cd26350
 
 
89a139c
 
61f9b59
89a139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6078097
 
 
89a139c
 
 
 
 
 
 
 
61f9b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89a139c
 
 
 
 
 
 
 
 
 
 
 
 
ad79bac
6078097
 
ad79bac
89a139c
6078097
89a139c
ad79bac
 
6078097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad79bac
 
6078097
 
 
 
 
 
 
 
 
89a139c
 
cd26350
115794d
 
cd26350
115794d
89a139c
 
115794d
 
 
89a139c
 
 
 
115794d
89a139c
 
61f9b59
 
 
 
 
 
 
 
 
 
 
 
396338d
 
 
 
61f9b59
 
 
 
 
 
 
 
 
 
 
 
 
 
89a139c
 
 
61f9b59
89a139c
 
 
 
 
cd26350
 
 
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
"""Query optimization agent for generating focused and variant queries.

Transforms a single user query into dual optimized outputs: a focused final_rephrase
for passage-level semantic retrieval, and three Semantic Scholar search variants
(primary, broad, alternative) for paper-level discovery.
"""

import ast
import json
import re
from typing import Any, Dict, Optional

from loguru import logger

from config.prompts import QUERY_OPTIMIZATION_TEMPLATE
from utils.llm_router import LLMRouter


class QueryOptimizationAgent:
    """Agent that optimizes user queries for hybrid search strategy.

    Uses LLM perform either query decomposition or expansion.
    Handles LLM failures gracefully by falling back to original query.
    """

    def __init__(self) -> None:
        self.router = LLMRouter()

    async def generate_dual_queries(self, query: str) -> Dict[str, Any]:
        """Generate dual optimized query outputs using LLM.

        Args:
            query: The original user query string.

        Returns:
            Dict with keys: final_rephrase, primary, broad, alternative.
            All values are strings. On LLM failure, all values equal the input query.
        """
        logger.debug(
            "QueryOptimizationAgent.generate_dual_queries called with query: {}", query
        )

        prompt = self._build_prompt(query)
        response = await self._call_llm(prompt)

        if response is None:
            logger.warning("LLM call failed, using fallback")
            return self._fallback(query)

        parsed = self._parse_json_response(response)
        if parsed:
            logger.info(f"LLM Output structure: {parsed}")

        if parsed is None:
            logger.warning("JSON parsing failed, using fallback")
            return self._fallback(query)

        if not self._validate_response(parsed):
            logger.warning("LLM response missing required fields, using fallback")
            return self._fallback(query)

        # Log based on strategy
        strategy = parsed.get("strategy", "expansion")
        if strategy == "decomposition":
            logger.info(
                "Query optimization (Decomposition): final_rephrase='{}', sub_queries={}",
                parsed["final_rephrase"],
                parsed["sub_queries"],
            )
        else:
            logger.info(
                "Query optimization (Expansion): final_rephrase='{}', primary='{}', broad='{}', alternative='{}'",
                parsed["final_rephrase"],
                parsed["primary"],
                parsed["broad"],
                parsed["alternative"],
            )
        return parsed

    async def _call_llm(self, prompt: str) -> Optional[str]:
        """Call the LLM and handle timeouts/failures."""
        try:
            response = await self.router.generate(prompt, "optimization")
            logger.debug("LLM response received: {}", response[:200])
            return response
        except Exception as e:
            logger.exception("LLM call failed with exception: {}", e)
            return None

    def _parse_json_response(self, response: str) -> Optional[Dict]:
        """Parse JSON response from LLM, handling both JSON and Python-dict formats."""
        parsed = None

        # 1. Try strict JSON parsing first (fastest/safest)
        try:
            parsed = json.loads(response)
        except json.JSONDecodeError:
            pass

        if parsed is None:
            # 2. Extract the block (handles markdown fences like ```json ... ```)
            json_block = self._extract_json_block(response)
            if json_block:
                # 3. Try strict JSON parsing on the extracted block
                try:
                    parsed = json.loads(json_block)
                except json.JSONDecodeError:
                    # 4. Fallback: Try ast.literal_eval for Python-style dicts
                    try:
                        parsed = ast.literal_eval(json_block)
                    except (ValueError, SyntaxError) as e:
                        logger.warning(
                            "Parsing failed via both json.loads and ast.literal_eval. Error: {}",
                            e,
                        )
                        return None
            else:
                logger.error("No JSON block found in response")
                return None

        # --- FIX: Normalize lists to strings for expansion strategy ---
        if isinstance(parsed, dict):
            # If LLM returns lists for these keys, join them into a single string
            for key in ["primary", "broad", "alternative"]:
                if key in parsed and isinstance(parsed[key], list):
                    parsed[key] = " ".join(str(x) for x in parsed[key])

        return parsed

    def _extract_json_block(self, text: str) -> Optional[str]:
        """Extract the first balanced JSON object from text.

        Uses regex to find the first JSON object, handling potential
        Markdown code blocks or conversational text.
        """
        if not text:
            return None

        match = re.search(r"(\{.*\})", text, re.DOTALL)
        if match:
            return match.group(1)
        return None

    def _build_prompt(self, query: str) -> str:
        """Build the LLM prompt for query optimization."""
        return QUERY_OPTIMIZATION_TEMPLATE.format(query=query)

    def _validate_response(self, response: Dict) -> bool:
        """Validate that the LLM response contains all required fields based on strategy."""
        if not isinstance(response, dict):
            return False

        strategy = response.get("strategy", "expansion")

        # Common mandatory field
        if "final_rephrase" not in response or not isinstance(
            response["final_rephrase"], str
        ):
            return False

        # Ensure intent_type is present, default to "general" if missing
        if "intent_type" not in response:
            response["intent_type"] = "general"

        if strategy == "decomposition":
            return (
                "sub_queries" in response
                and isinstance(response["sub_queries"], list)
                and all(isinstance(q, str) for q in response["sub_queries"])
            )
        else:
            # Expansion strategy (default)
            required_keys = {"primary", "broad", "alternative"}
            return all(key in response for key in required_keys) and all(
                isinstance(response[key], str) for key in required_keys
            )

    def _fallback(self, query: str) -> Dict[str, Any]:
        """Return fallback response using original query for all fields."""
        logger.debug("Using fallback response for query: {}", query)
        return {
            "strategy": "expansion",
            "final_rephrase": query,
            "primary": query,
            "broad": query,
            "alternative": query,
        }


__all__ = ["QueryOptimizationAgent"]