File size: 13,326 Bytes
d520909
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
"""
Query Planner Agent

Decomposes complex queries into sub-queries and identifies query intent.
Follows the "Decomposed Prompting" approach from FAANG research.

Key Features:
- Multi-hop query decomposition
- Query intent classification (factoid, comparison, aggregation, etc.)
- Dependency graph for sub-queries
- Query expansion with synonyms and related terms
"""

from typing import List, Optional, Dict, Any, Literal
from pydantic import BaseModel, Field
from loguru import logger
from enum import Enum
import json
import re

try:
    import httpx
    HTTPX_AVAILABLE = True
except ImportError:
    HTTPX_AVAILABLE = False


class QueryIntent(str, Enum):
    """Classification of query intent."""
    FACTOID = "factoid"              # Simple fact lookup
    COMPARISON = "comparison"        # Compare multiple entities
    AGGREGATION = "aggregation"      # Summarize across documents
    CAUSAL = "causal"                # Why/how questions
    PROCEDURAL = "procedural"        # Step-by-step instructions
    DEFINITION = "definition"        # What is X?
    LIST = "list"                    # List items matching criteria
    MULTI_HOP = "multi_hop"          # Requires multiple reasoning steps


class SubQuery(BaseModel):
    """A decomposed sub-query."""
    id: str
    query: str
    intent: QueryIntent
    depends_on: List[str] = Field(default_factory=list)
    priority: int = Field(default=1, ge=1, le=5)
    filters: Dict[str, Any] = Field(default_factory=dict)
    expected_answer_type: str = Field(default="text")


class QueryPlan(BaseModel):
    """Complete query execution plan."""
    original_query: str
    intent: QueryIntent
    sub_queries: List[SubQuery]
    expanded_terms: List[str] = Field(default_factory=list)
    requires_aggregation: bool = False
    confidence: float = Field(default=1.0, ge=0.0, le=1.0)


class QueryPlannerAgent:
    """
    Plans and decomposes queries for optimal retrieval.

    Capabilities:
    1. Identify query complexity and intent
    2. Decompose multi-hop queries into atomic sub-queries
    3. Build dependency graph for sub-query execution
    4. Expand queries with related terms
    """

    SYSTEM_PROMPT = """You are a query planning expert. Your job is to analyze user queries and create optimal retrieval plans.

For each query, you must:
1. Classify the query intent (factoid, comparison, aggregation, causal, procedural, definition, list, multi_hop)
2. Decompose complex queries into simpler sub-queries
3. Identify dependencies between sub-queries
4. Suggest query expansions (synonyms, related terms)

Output your analysis as JSON with this structure:
{
    "intent": "factoid|comparison|aggregation|causal|procedural|definition|list|multi_hop",
    "sub_queries": [
        {
            "id": "sq1",
            "query": "the sub-query text",
            "intent": "factoid",
            "depends_on": [],
            "priority": 1,
            "expected_answer_type": "text|number|date|list|boolean"
        }
    ],
    "expanded_terms": ["synonym1", "related_term1"],
    "requires_aggregation": false,
    "confidence": 0.95
}

For simple queries, return a single sub-query matching the original.
For complex queries requiring multiple steps, break them down logically.
"""

    def __init__(
        self,
        model: str = "llama3.2:3b",
        base_url: str = "http://localhost:11434",
        temperature: float = 0.1,
        use_llm: bool = True,
    ):
        """
        Initialize Query Planner.

        Args:
            model: LLM model for planning
            base_url: Ollama API URL
            temperature: LLM temperature (lower = more deterministic)
            use_llm: If False, use rule-based planning only
        """
        self.model = model
        self.base_url = base_url.rstrip("/")
        self.temperature = temperature
        self.use_llm = use_llm

        logger.info(f"QueryPlannerAgent initialized (model={model}, use_llm={use_llm})")

    def plan(self, query: str) -> QueryPlan:
        """
        Create execution plan for a query.

        Args:
            query: User's natural language query

        Returns:
            QueryPlan with sub-queries and metadata
        """
        # First, try rule-based classification for common patterns
        rule_based_plan = self._rule_based_planning(query)

        if not self.use_llm or not HTTPX_AVAILABLE:
            return rule_based_plan

        # Use LLM for complex query decomposition
        try:
            llm_plan = self._llm_planning(query)

            # Merge rule-based expansions with LLM plan
            if rule_based_plan.expanded_terms:
                llm_plan.expanded_terms = list(set(
                    llm_plan.expanded_terms + rule_based_plan.expanded_terms
                ))

            return llm_plan

        except Exception as e:
            logger.warning(f"LLM planning failed, using rule-based: {e}")
            return rule_based_plan

    def _rule_based_planning(self, query: str) -> QueryPlan:
        """Fast rule-based query planning."""
        query_lower = query.lower().strip()

        # Detect intent from patterns
        intent = self._detect_intent(query_lower)

        # Generate query expansions
        expansions = self._expand_query(query)

        # Check if decomposition is needed
        sub_queries = self._decompose_if_needed(query, intent)

        return QueryPlan(
            original_query=query,
            intent=intent,
            sub_queries=sub_queries,
            expanded_terms=expansions,
            requires_aggregation=intent in [QueryIntent.AGGREGATION, QueryIntent.LIST],
            confidence=0.8,
        )

    def _detect_intent(self, query: str) -> QueryIntent:
        """Detect query intent from patterns."""
        # Definition patterns
        if re.match(r"^(what is|define|what are|what does .* mean)", query):
            return QueryIntent.DEFINITION

        # Comparison patterns
        if any(p in query for p in ["compare", "difference between", "vs", "versus", "better than"]):
            return QueryIntent.COMPARISON

        # List patterns
        if any(p in query for p in ["list", "what are all", "give me all", "enumerate"]):
            return QueryIntent.LIST

        # Causal patterns
        if any(p in query for p in ["why", "how does", "what causes", "reason for"]):
            return QueryIntent.CAUSAL

        # Procedural patterns
        if any(p in query for p in ["how to", "steps to", "process for", "how can i"]):
            return QueryIntent.PROCEDURAL

        # Aggregation patterns
        if any(p in query for p in ["summarize", "overview", "summary of", "main points"]):
            return QueryIntent.AGGREGATION

        # Multi-hop detection (conjunctions, multiple questions)
        if " and " in query and "?" in query:
            return QueryIntent.MULTI_HOP
        if query.count("?") > 1:
            return QueryIntent.MULTI_HOP

        # Default to factoid
        return QueryIntent.FACTOID

    def _expand_query(self, query: str) -> List[str]:
        """Generate query expansions (synonyms, related terms)."""
        expansions = []
        query_lower = query.lower()

        # Domain-specific expansions for patent/legal context
        expansion_map = {
            "patent": ["intellectual property", "IP", "invention", "claim"],
            "license": ["licensing", "agreement", "contract", "terms"],
            "royalty": ["royalties", "payment", "fee", "compensation"],
            "open source": ["OSS", "FOSS", "free software", "open-source"],
            "trademark": ["brand", "mark", "logo"],
            "copyright": ["rights", "authorship", "protection"],
            "infringement": ["violation", "breach", "unauthorized use"],
            "disclosure": ["reveal", "publish", "filing"],
        }

        for term, synonyms in expansion_map.items():
            if term in query_lower:
                expansions.extend(synonyms)

        return list(set(expansions))[:10]  # Limit expansions

    def _decompose_if_needed(self, query: str, intent: QueryIntent) -> List[SubQuery]:
        """Decompose query if complex."""

        # For comparison queries, extract entities being compared
        if intent == QueryIntent.COMPARISON:
            entities = self._extract_comparison_entities(query)
            if len(entities) >= 2:
                sub_queries = []
                for i, entity in enumerate(entities):
                    sub_queries.append(SubQuery(
                        id=f"sq{i+1}",
                        query=f"What are the key characteristics of {entity}?",
                        intent=QueryIntent.FACTOID,
                        priority=1,
                        expected_answer_type="text",
                    ))
                # Add comparison synthesis query
                sub_queries.append(SubQuery(
                    id=f"sq{len(entities)+1}",
                    query=query,
                    intent=QueryIntent.COMPARISON,
                    depends_on=[f"sq{i+1}" for i in range(len(entities))],
                    priority=2,
                    expected_answer_type="text",
                ))
                return sub_queries

        # For multi-hop queries, split on conjunctions
        if intent == QueryIntent.MULTI_HOP and " and " in query.lower():
            parts = re.split(r'\s+and\s+', query, flags=re.IGNORECASE)
            sub_queries = []
            for i, part in enumerate(parts):
                part = part.strip().rstrip("?") + "?"
                sub_queries.append(SubQuery(
                    id=f"sq{i+1}",
                    query=part,
                    intent=QueryIntent.FACTOID,
                    priority=i+1,
                    expected_answer_type="text",
                ))
            return sub_queries

        # Default: single query
        return [SubQuery(
            id="sq1",
            query=query,
            intent=intent,
            priority=1,
            expected_answer_type="text",
        )]

    def _extract_comparison_entities(self, query: str) -> List[str]:
        """Extract entities being compared."""
        patterns = [
            r"(?:compare|difference between)\s+(.+?)\s+(?:and|vs|versus)\s+(.+?)(?:\?|$)",
            r"(.+?)\s+(?:vs|versus)\s+(.+?)(?:\?|$)",
            r"(?:between)\s+(.+?)\s+(?:and)\s+(.+?)(?:\?|$)",
        ]

        for pattern in patterns:
            match = re.search(pattern, query, re.IGNORECASE)
            if match:
                return [match.group(1).strip(), match.group(2).strip()]

        return []

    def _llm_planning(self, query: str) -> QueryPlan:
        """Use LLM for sophisticated query planning."""
        prompt = f"""Analyze this query and create a retrieval plan:

Query: {query}

Provide your analysis as JSON."""

        with httpx.Client(timeout=30.0) as client:
            response = client.post(
                f"{self.base_url}/api/generate",
                json={
                    "model": self.model,
                    "prompt": prompt,
                    "system": self.SYSTEM_PROMPT,
                    "stream": False,
                    "options": {
                        "temperature": self.temperature,
                        "num_predict": 1024,
                    },
                },
            )
            response.raise_for_status()
            result = response.json()

        # Parse JSON from response
        response_text = result.get("response", "")
        plan_data = self._parse_json_response(response_text)

        # Convert to QueryPlan
        sub_queries = []
        for sq_data in plan_data.get("sub_queries", []):
            sub_queries.append(SubQuery(
                id=sq_data.get("id", "sq1"),
                query=sq_data.get("query", query),
                intent=QueryIntent(sq_data.get("intent", "factoid")),
                depends_on=sq_data.get("depends_on", []),
                priority=sq_data.get("priority", 1),
                expected_answer_type=sq_data.get("expected_answer_type", "text"),
            ))

        if not sub_queries:
            sub_queries = [SubQuery(
                id="sq1",
                query=query,
                intent=QueryIntent.FACTOID,
                priority=1,
            )]

        return QueryPlan(
            original_query=query,
            intent=QueryIntent(plan_data.get("intent", "factoid")),
            sub_queries=sub_queries,
            expanded_terms=plan_data.get("expanded_terms", []),
            requires_aggregation=plan_data.get("requires_aggregation", False),
            confidence=plan_data.get("confidence", 0.9),
        )

    def _parse_json_response(self, text: str) -> Dict[str, Any]:
        """Extract JSON from LLM response."""
        # Try to find JSON block
        json_match = re.search(r'\{[\s\S]*\}', text)
        if json_match:
            try:
                return json.loads(json_match.group())
            except json.JSONDecodeError:
                pass

        # Return default structure
        return {
            "intent": "factoid",
            "sub_queries": [],
            "expanded_terms": [],
            "requires_aggregation": False,
            "confidence": 0.7,
        }