File size: 6,658 Bytes
891fe52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Parse natural language commands into structured intents."""

import re
import logging
from typing import Optional, Dict, Any
from polyhedra.services.llm_service import LLMService
from polyhedra.agent.models import Intent, IntentType


class IntentParser:
    """
    Parse natural language commands into structured intents.
    
    Uses a combination of:
    1. Pattern matching for common commands
    2. LLM-based parsing for complex/ambiguous commands
    """
    
    def __init__(self, llm_service: Optional[LLMService] = None):
        """
        Initialize intent parser.
        
        Args:
            llm_service: Optional LLM service for complex parsing
        """
        self.llm_service = llm_service
        self.logger = logging.getLogger(__name__)
        
        # Command patterns
        self.patterns = {
            IntentType.RESEARCH_SURVEY: [
                r"(?:research|survey|review)\s+(?:papers?\s+)?(?:on|about)?\s*(.+)",
                r"find\s+(?:papers?\s+)?(?:on|about)\s+(.+)",
                r"(?:what|show me)\s+(?:papers?\s+)?(?:on|about)\s+(.+)",
            ],
            IntentType.PAPER_COMPARISON: [
                r"compare\s+(.+?)\s+(?:vs|versus|and)\s+(.+)",
                r"(?:what|how)\s+(?:is|are)\s+(?:the\s+)?(?:difference|differences)\s+between\s+(.+?)\s+and\s+(.+)",
            ],
            IntentType.GAP_ANALYSIS: [
                r"(?:find|identify|analyze)\s+(?:research\s+)?gaps?\s+in\s+(.+)",
                r"what(?:'\''s|\s+is)\s+missing\s+in\s+(.+)",
            ],
            IntentType.CITATION_FINDING: [
                r"(?:find|get)\s+citations?\s+for\s+(.+)",
                r"cite\s+(.+)",
            ],
        }
    
    async def parse(self, command: str) -> Intent:
        """
        Parse command into intent.
        
        Args:
            command: Natural language command
            
        Returns:
            Parsed Intent object
        """
        command = command.strip()
        
        # Try pattern matching first (fast)
        intent = self._pattern_match(command)
        
        if intent.type != IntentType.UNKNOWN or not self.llm_service:
            return intent
        
        # Fall back to LLM parsing for complex commands
        try:
            intent = await self._llm_parse(command)
        except Exception as e:
            self.logger.warning(f"LLM parsing failed: {e}")
        
        return intent
    
    def _pattern_match(self, command: str) -> Intent:
        """
        Match command against patterns.
        
        Args:
            command: Command text
            
        Returns:
            Intent (may be UNKNOWN)
        """
        command_lower = command.lower()
        
        for intent_type, patterns in self.patterns.items():
            for pattern in patterns:
                match = re.match(pattern, command_lower, re.IGNORECASE)
                if match:
                    # Extract topic and parameters
                    topic = match.group(1).strip()
                    params = self._extract_parameters(command_lower)
                    
                    return Intent(
                        type=intent_type,
                        topic=topic,
                        parameters=params,
                        confidence=0.9,
                        raw_command=command
                    )
        
        # No match
        return Intent(
            type=IntentType.UNKNOWN,
            topic="",
            parameters={},
            confidence=0.0,
            raw_command=command
        )
    
    def _extract_parameters(self, command: str) -> Dict[str, Any]:
        """
        Extract additional parameters from command.
        
        Args:
            command: Command text
            
        Returns:
            Dictionary of parameters
        """
        params = {}
        
        # Extract paper limit
        limit_match = re.search(r'(\d+)\s+papers?', command)
        if limit_match:
            params['limit'] = int(limit_match.group(1))
        
        # Extract depth
        if any(word in command for word in ['brief', 'quick', 'short']):
            params['depth'] = 'brief'
        elif any(word in command for word in ['comprehensive', 'detailed', 'thorough']):
            params['depth'] = 'comprehensive'
        else:
            params['depth'] = 'standard'
        
        # Extract structure
        if 'chronological' in command or 'timeline' in command:
            params['structure'] = 'chronological'
        elif 'methodological' in command or 'methods' in command:
            params['structure'] = 'methodological'
        else:
            params['structure'] = 'thematic'
        
        # Extract year range
        year_match = re.search(r'(?:from|since|after)\s+(\d{4})', command)
        if year_match:
            params['year_from'] = int(year_match.group(1))
        
        year_match = re.search(r'(?:to|until|before)\s+(\d{4})', command)
        if year_match:
            params['year_to'] = int(year_match.group(1))
        
        return params
    
    async def _llm_parse(self, command: str) -> Intent:
        """
        Use LLM to parse complex command.
        
        Args:
            command: Command text
            
        Returns:
            Parsed Intent
        """
        prompt = f"""Parse this research command into structured intent.

Command: "{command}"

Extract:
1. Intent type (research_survey, paper_comparison, gap_analysis, citation_finding, or unknown)
2. Main research topic
3. Parameters: limit (number), depth (brief/standard/comprehensive), structure (thematic/chronological/methodological), year_from, year_to

Respond in JSON format:
{{
  "type": "research_survey",
  "topic": "extracted topic",
  "parameters": {{"limit": 50, "depth": "standard"}}
}}"""

        response, _, _ = await self.llm_service.complete(prompt, model=None)
        
        # Parse JSON response
        import json
        try:
            data = json.loads(response.strip())
            return Intent(
                type=IntentType(data['type']),
                topic=data['topic'],
                parameters=data.get('parameters', {}),
                confidence=0.8,
                raw_command=command
            )
        except (json.JSONDecodeError, KeyError, ValueError) as e:
            self.logger.error(f"Failed to parse LLM response: {e}")
            return Intent(
                type=IntentType.UNKNOWN,
                topic="",
                parameters={},
                confidence=0.0,
                raw_command=command
            )