File size: 2,048 Bytes
8a111ae | 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 | """Detect user intent from input — code analysis, question, or mixed."""
import re
def detect_intent(text: str) -> str:
"""
Classify input as:
- 'analyze' : user pasted code to be analyzed
- 'chat' : user asked a question or made a statement
- 'mixed' : question about specific code they also pasted
Returns one of: 'analyze', 'chat', 'mixed'
"""
stripped = text.strip()
# Strong code signals: indented blocks, common keywords at line start
code_patterns = [
r"^\s*(def |class |import |from |function |const |let |var |public |private |#include)",
r"^\s*(if |for |while |return |async |await |try:|except:|catch\s*\()",
r"[{}\[\]]\s*$", # lines ending with braces
r"^\s+\w+.*[:=]\s*\S", # indented assignments
r"(->|=>|::|===|!==|&&|\|\|)", # operators common in code
]
question_patterns = [
r"\?",
r"^(what|why|how|when|where|who|can you|could you|explain|describe|tell me|is there|are there|should i|help me)",
r"^(fix|debug|review|check|analyze|look at|improve)",
]
lines = stripped.split("\n")
code_line_count = 0
for line in lines:
for pat in code_patterns:
if re.search(pat, line, re.IGNORECASE):
code_line_count += 1
break
code_ratio = code_line_count / max(len(lines), 1)
has_question = any(
re.search(pat, stripped, re.IGNORECASE | re.MULTILINE)
for pat in question_patterns
)
# Multi-line with mostly code lines → analyze
if len(lines) >= 3 and code_ratio >= 0.4:
if has_question:
return "mixed"
return "analyze"
# Single line or low code ratio with question → chat
if has_question:
return "chat"
# Short single line, no question → chat (treat as conversation)
if len(lines) == 1:
return "chat"
# Default: if there's meaningful code present
if code_ratio >= 0.25:
return "analyze"
return "chat" |