File size: 26,505 Bytes
501bc8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import re
import logging
import json
import io
from typing import List, Dict, Any, Optional
from concurrent.futures import ThreadPoolExecutor

from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.messages import HumanMessage

try:
    from langsmith import traceable
except ImportError:
    def traceable(**kwargs):
        def decorator(fn):
            return fn
        return decorator

from .config import config, SCORING
from .prompt_manager import PromptManager
from .document_processor import DocumentProcessor
from .retriever import Retriever
from .router import IntentRouter
from .slack_formatter import convert_to_slack_blocks
from .agentic_retriever import AgenticRetriever

# Configure Logger
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("SearchEngine")

# Intent display name mapping
INTENT_DISPLAY = {
    "SIMPLE_SEARCH": "간단 검색",
    "DEEP_RESEARCH": "심측 뢄석",
    "ADVISORY": "μ „λž΅ 자문",
    "MULTIMODAL_ANALYSIS": "λ©€ν‹°λͺ¨λ‹¬ 뢄석",
    "SPECIFIC_ITEM_ANALYSIS": "νŠΉμ • ν•­λͺ© 뢄석",
}

class SearchEngine:
    def __init__(self):
        logger.info("Initializing SearchEngine...")
        
        # Initialize LLMs
        # Answer generation LLM (Gemini 2.5 Pro)
        self.llm = ChatGoogleGenerativeAI(
            model=config.llm_model,
            temperature=config.llm_temperature,
            google_api_key=config.google_api_key,
            max_output_tokens=8192,
        )
        # Fast LLM for lightweight tasks (routing) β€” Gemini 2.5 Flash
        self.llm_fast = ChatGoogleGenerativeAI(
            model=config.llm_fast_model,
            temperature=0,
            google_api_key=config.google_api_key,
            max_output_tokens=1024,
        )
        # Agentic retriever LLM (Gemini 2.5 Flash β€” 속도 μš°μ„ )
        self.llm_agent = ChatGoogleGenerativeAI(
            model=config.llm_agent_model,
            temperature=0,
            google_api_key=config.google_api_key,
            max_output_tokens=8192,
        )

        # LangSmith run config β€” injected into every .invoke() / .stream()
        self._run_config = {"metadata": config.langsmith_metadata}

        # Initialize Components
        self.prompt_manager = PromptManager()
        self.doc_processor = DocumentProcessor()
        self.retriever = Retriever()
        self.router = IntentRouter(self.llm_fast, self.prompt_manager, self._run_config)

        # Initialize Chains
        self._init_chains()

        # Initialize Agentic Retriever
        self.agentic_retriever = AgenticRetriever(
            retriever=self.retriever,
            llm_fast=self.llm_agent,
            prompt_manager=self.prompt_manager,
            run_config=self._run_config,
        )

        # Speculative retrieval executor (router + retriever parallel)
        self._executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="speculative")

        logger.info("SearchEngine initialization complete.")

    def _init_chains(self):
        # 1. Simple Search Chain
        simple_prompt_str = self.prompt_manager.get_prompt("simple_search")
        simple_prompt = ChatPromptTemplate.from_template(simple_prompt_str)
        self.simple_search_chain = simple_prompt | self.llm | StrOutputParser()

        # 2. Deep Research Chain
        deep_prompt_str = self.prompt_manager.get_prompt("deep_research")
        deep_prompt = ChatPromptTemplate.from_template(deep_prompt_str)
        self.deep_research_chain = deep_prompt | self.llm | StrOutputParser()

        # 3. Chat Chain
        chat_prompt_str = self.prompt_manager.get_prompt("chat")
        chat_prompt = ChatPromptTemplate.from_template(chat_prompt_str)
        self.chat_chain = chat_prompt | self.llm | StrOutputParser()

        # 4. Specific Analysis Chain
        specific_prompt_str = self.prompt_manager.get_prompt("specific_analysis")
        if not specific_prompt_str:
             logger.warning("specific_analysis prompt not found, using deep_research as fallback.")
             specific_prompt_str = deep_prompt_str
        specific_prompt = ChatPromptTemplate.from_template(specific_prompt_str)
        self.specific_analysis_chain = specific_prompt | self.llm | StrOutputParser()

        # 5. Advisory Chain
        advisory_prompt_str = self.prompt_manager.get_prompt("advisory")
        if not advisory_prompt_str:
            logger.warning("advisory prompt not found, using deep_research as fallback.")
            advisory_prompt_str = deep_prompt_str
        advisory_prompt = ChatPromptTemplate.from_template(advisory_prompt_str)
        self.advisory_chain = advisory_prompt | self.llm | StrOutputParser()


    @staticmethod
    def _parse_llm_json(text: str, fallback: Dict | None = None) -> Dict:
        """Parse LLM text that may contain JSON β€” with multi-tier fallback.

        Tries:  1) direct json.loads  2) ```json fences  3) brace extraction  4) single-quote fix
        Returns *fallback* (default: {"answer": text, "sections": []}) on total failure.
        """
        # 1. Direct parse
        try:
            return json.loads(text)
        except (json.JSONDecodeError, TypeError):
            pass

        # 2. Markdown fence extraction
        match = re.search(r'```json\s*(.*?)\s*```', text, re.DOTALL)
        if match:
            try:
                return json.loads(match.group(1))
            except json.JSONDecodeError:
                pass

        # 3. Brace extraction
        start = text.find('{')
        end = text.rfind('}') + 1
        if start != -1 and end > start:
            try:
                return json.loads(text[start:end])
            except json.JSONDecodeError:
                # 4. Single-quote fix (common in LLM dict-style output)
                try:
                    return json.loads(text[start:end].replace("'", '"'))
                except json.JSONDecodeError:
                    pass

        # 5. Truncated JSON recovery β€” extract answer from incomplete JSON
        #    (e.g., when max_output_tokens cuts off the response mid-JSON)
        #    Works regardless of whether brace extraction was attempted above
        if start != -1:
            answer_match = re.search(r'"answer"\s*:\s*"((?:[^"\\]|\\.)*)"', text)
            if answer_match:
                logger.warning("JSON appears truncated β€” extracted answer field only")
                return {"answer": answer_match.group(1), "sections": []}

        logger.error(f"Failed to parse JSON response. raw_text: {text[:500]}...")
        return fallback if fallback is not None else {"answer": text, "sections": []}

    def _post_process_response(self, response, platform):
        if platform == "slack":
            logger.info(f"Original Response (Length: {len(response)}): {response[:200]}...")

            json_data = self._parse_llm_json(response)

            answer_text = json_data.get("answer", "")
            if answer_text and answer_text.lstrip().startswith("{"):
                json_data["answer"] = "⚠️ 응닡이 λ„ˆλ¬΄ κΈΈμ–΄ ν˜•μ‹ λ³€ν™˜μ— μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. 질문 λ²”μœ„λ₯Ό μ’ν˜€ λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”."
                logger.warning("Raw JSON detected in answer field β€” replaced with guidance message")

            blocks = convert_to_slack_blocks(json_data)
            return {"blocks": blocks, "text": json_data.get("answer", "Response generated.")}

        return response

    def search_and_answer(self, query: str, chat_history: List[Dict] = None, media_file: Dict = None, platform: str = "web", return_debug: bool = False, override_intent: str = None, pre_routing: Dict = None):
        chat_history = chat_history or []
        # If pre_routing is provided (from confirmation flow), use it directly
        if pre_routing:
            is_visual_media = pre_routing.get("is_visual_media", False)
            attached_content = pre_routing.get("attached_content", "")
            image_b64 = pre_routing.get("image_b64")
            mime_type = pre_routing.get("mime_type")
            route_result = pre_routing["route_result"]
            keywords = pre_routing["expanded_keywords"]
        else:
            # 1. Process Media
            is_visual_media, attached_content, image_b64, mime_type = self.doc_processor.process_media_file(media_file)
            # 2. Routing (query expansion deferred to _retrieve_context fallback)
            route_result = self.router.route(query, chat_history, has_image=is_visual_media)
            keywords = route_result.get("keywords", [])

        intent = override_intent or route_result.get("intent", "SIMPLE_SEARCH")
        secondary_intent = route_result.get("secondary_intent")
        confidence = route_result.get("confidence", 0.8)

        # Dispatch
        logger.info(f"Dispatching: intent={intent}, secondary={secondary_intent}, confidence={confidence}, override={override_intent is not None}")

        debug_info = {"routing": route_result, "expanded_keywords": keywords}

        if intent == "MULTIMODAL_ANALYSIS" and is_visual_media:
            answer, mm_debug = self._handle_multimodal(query, keywords, attached_content, image_b64, mime_type, chat_history, platform)
            debug_info.update(mm_debug)
        elif intent == "SPECIFIC_ITEM_ANALYSIS":
             target_query = keywords[0] if keywords else query
             answer, sa_debug = self._handle_specific_analysis(target_query, query, chat_history, platform)
             debug_info.update(sa_debug)
        elif intent == "CHAT":
            answer, chat_debug = self._handle_chat(query, chat_history, platform)
            debug_info.update(chat_debug)
        elif intent == "ADVISORY":
            answer, adv_debug = self._handle_advisory(query, keywords, secondary_intent, attached_content, chat_history, platform)
            debug_info.update(adv_debug)
        else:
            # SIMPLE_SEARCH or DEEP_RESEARCH
            # Blending: if secondary is ADVISORY and confidence is low, upgrade to advisory handler
            if secondary_intent == "ADVISORY" and confidence < 0.7 and not override_intent:
                logger.info(f"Blending: upgrading {intent} + ADVISORY (confidence={confidence})")
                answer, adv_debug = self._handle_advisory(query, keywords, intent, attached_content, chat_history, platform)
                debug_info.update(adv_debug)
            else:
                is_deep = (intent == "DEEP_RESEARCH")
                answer, search_debug = self._handle_search(query, keywords, is_deep, attached_content, chat_history, platform)
                debug_info.update(search_debug)

        if return_debug:
            return {"answer": answer, "debug": debug_info}

        return answer

    def stream_answer(self, query: str, chat_history: List[Dict] = None, media_file: Dict = None,
                      platform: str = "web", override_intent: str = None, pre_routing: Dict = None):
        """Generator that yields streaming chunks for progressive Slack updates.

        Yields:
            ("metadata", dict)   β€” routing info (intent, confidence, keywords)
            ("status", str)      β€” task-based status message for typing indicator
            ("thinking", dict)   β€” structured progress step {step, text} for progress message
            ("text_delta", str)  β€” incremental text chunk from LLM
            ("complete", dict)   β€” final result with answer and debug
        """
        chat_history = chat_history or []

        # ── Preprocessing (same as search_and_answer) ──
        if pre_routing:
            is_visual_media = pre_routing.get("is_visual_media", False)
            attached_content = pre_routing.get("attached_content", "")
            image_b64 = pre_routing.get("image_b64")
            mime_type = pre_routing.get("mime_type")
            route_result = pre_routing["route_result"]
            keywords = pre_routing["expanded_keywords"]
            retriever_future = None
        else:
            is_visual_media, attached_content, image_b64, mime_type = self.doc_processor.process_media_file(media_file)

            # Speculative Retrieval: start retriever in background while router runs
            retriever_future = self._executor.submit(
                self._agentic_retrieve_context, [query], query, "SIMPLE_SEARCH"
            )
            route_result = self.router.route(query, chat_history, has_image=is_visual_media)
            keywords = route_result.get("keywords", [])

        intent = override_intent or route_result.get("intent", "SIMPLE_SEARCH")
        secondary_intent = route_result.get("secondary_intent")
        confidence = route_result.get("confidence", 0.8)

        debug_info = {"routing": route_result, "expanded_keywords": keywords}
        yield ("metadata", {"intent": intent, "confidence": confidence, "keywords": keywords})

        # Thinking: routing info
        if intent == "CHAT":
            yield ("thinking", {"step": "routing", "text": "πŸ’¬ λŒ€ν™” λͺ¨λ“œλ‘œ 닡변을 μ€€λΉ„ν•˜κ³  μžˆμ–΄μš”..."})
        else:
            intent_label = INTENT_DISPLAY.get(intent, intent)
            kw_text = ", ".join(keywords[:5]) if keywords else ""
            yield ("thinking", {
                "step": "routing",
                "text": f'🧭 질문 뢄석 μ™„λ£Œ: "{intent_label}" λ°©μ‹μœΌλ‘œ κ²€μƒ‰ν• κ²Œμš”\n   ν‚€μ›Œλ“œ: {kw_text}'
            })

        # ── Non-streamable intents: fall back to invoke ──
        if (intent == "MULTIMODAL_ANALYSIS" and is_visual_media) or intent == "SPECIFIC_ITEM_ANALYSIS":
            yield ("status", "πŸ”Ž κ΄€λ ¨ 자료λ₯Ό κ²€μƒ‰ν•˜κ³  μžˆμ–΄μš”...")
            result = self.search_and_answer(
                query, chat_history, media_file, platform,
                return_debug=True, override_intent=override_intent, pre_routing=pre_routing,
            )
            yield ("complete", result)
            return

        # ── Determine chain and inputs ──
        formatting_instructions = self._get_formatting_instructions(platform)
        history_str = self._format_chat_history(chat_history)

        if intent == "CHAT":
            yield ("status", "πŸ’¬ 닡변을 μ€€λΉ„ν•˜κ³  μžˆμ–΄μš”...")
            chain = self.chat_chain
            chain_input = {"query": query, "chat_history": history_str, "formatting_instructions": formatting_instructions}
        elif intent == "ADVISORY" or (secondary_intent == "ADVISORY" and confidence < 0.7 and not override_intent):
            yield ("status", "πŸ”Ž AI μ—μ΄μ „νŠΈκ°€ κ΄€λ ¨ 자료λ₯Ό κ²€μƒ‰ν•˜κ³  μžˆμ–΄μš”...")
            if retriever_future:
                try:
                    context_str, ctx_debug = retriever_future.result()
                except Exception as e:
                    logger.warning(f"Speculative retrieval failed, retrying: {e}")
                    context_str, ctx_debug = self._agentic_retrieve_context(keywords, query, "ADVISORY")
            else:
                context_str, ctx_debug = self._agentic_retrieve_context(keywords, query, "ADVISORY")
            yield ("thinking", {"step": "retrieval", "text": "πŸ”Ž AI μ—μ΄μ „νŠΈκ°€ κ΄€λ ¨ λ¬Έμ„œλ₯Ό κ²€μƒ‰ν•˜κ³  λΆ„μ„ν–ˆμ–΄μš”"})
            full_context = f"{context_str}\n{attached_content}" if attached_content else context_str
            chain = self.advisory_chain
            chain_input = {"query": query, "context": full_context, "chat_history": history_str, "formatting_instructions": formatting_instructions}
            debug_info["context_raw"] = ctx_debug
            debug_info["blended_with"] = secondary_intent
        else:
            is_deep = (intent == "DEEP_RESEARCH")
            yield ("status", "πŸ”Ž AI μ—μ΄μ „νŠΈκ°€ κ΄€λ ¨ 자료λ₯Ό κ²€μƒ‰ν•˜κ³  μžˆμ–΄μš”...")
            if retriever_future:
                try:
                    context_str, ctx_debug = retriever_future.result()
                except Exception as e:
                    logger.warning(f"Speculative retrieval failed, retrying: {e}")
                    context_str, ctx_debug = self._agentic_retrieve_context(keywords, query, "DEEP_RESEARCH" if is_deep else "SIMPLE_SEARCH")
            else:
                context_str, ctx_debug = self._agentic_retrieve_context(keywords, query, "DEEP_RESEARCH" if is_deep else "SIMPLE_SEARCH")
            yield ("thinking", {"step": "retrieval", "text": "πŸ”Ž AI μ—μ΄μ „νŠΈκ°€ κ΄€λ ¨ λ¬Έμ„œλ₯Ό κ²€μƒ‰ν•˜κ³  λΆ„μ„ν–ˆμ–΄μš”"})
            full_context = f"{context_str}\n{attached_content}" if attached_content else context_str
            chain = self.deep_research_chain if is_deep else self.simple_search_chain
            chain_input = {"query": query, "context": full_context, "chat_history": history_str, "formatting_instructions": formatting_instructions}
            debug_info["context_raw"] = ctx_debug
            debug_info["keywords"] = keywords

        # ── Stream LLM output ──
        yield ("thinking", {"step": "generating", "text": "✍️ λ‹΅λ³€ μž‘μ„± 쀑..."})
        full_text = ""
        for chunk in chain.stream(chain_input, config=self._run_config):
            full_text += chunk
            yield ("text_delta", chunk)

        # ── Post-process and yield final result ──
        answer = self._post_process_response(full_text, platform)
        yield ("complete", {"answer": answer, "debug": debug_info})

    def routing_only(self, query: str, chat_history: List[Dict] = None, media_file: Dict = None) -> Dict[str, Any]:
        """
        Performs routing only (no search/LLM).
        Query expansion is deferred to _retrieve_context (only if initial results are sparse).
        Returns: {route_result, expanded_keywords, is_visual_media, attached_content, image_b64, mime_type}
        """
        chat_history = chat_history or []
        is_visual_media, attached_content, image_b64, mime_type = self.doc_processor.process_media_file(media_file)

        route_result = self.router.route(query, chat_history, has_image=is_visual_media)
        keywords = route_result.get("keywords", [])

        return {
            "route_result": route_result,
            "expanded_keywords": keywords,
            "is_visual_media": is_visual_media,
            "attached_content": attached_content,
            "image_b64": image_b64,
            "mime_type": mime_type,
        }

    def _handle_multimodal(self, query, keywords, attached_content, image_b64, mime_type, chat_history, platform):
        formatting_instructions = self._get_formatting_instructions(platform)

        # Context Retrieval
        context_str, debug_data = self._agentic_retrieve_context(keywords, query, "MULTIMODAL_ANALYSIS")
        
        mm_analysis_template = self.prompt_manager.get_prompt("multimodal_analysis")
        final_mm_text = mm_analysis_template.format(
            query=query, 
            keywords=keywords, 
            context_str=context_str, 
            formatting_instructions=formatting_instructions
        )
        final_mm_prompt = [
            {"type": "text", "text": final_mm_text},
            {"type": "image_url", "image_url": f"data:{mime_type};base64,{image_b64}"}
        ]
        try:
            response = self.llm.invoke([HumanMessage(content=final_mm_prompt)], config=self._run_config).content
        except Exception as e:
            logger.error(f"Multimodal analysis failed (likely invalid image format): {e}")
            return self._handle_search(query, keywords, False, attached_content + "\n[System: Image passed but failed processing]", chat_history, platform)
        
        if isinstance(response, list):
            response = "".join([str(c) for c in response])
        
        # [Visual QA Fix] Extract text if response looks like a dictionary string
        if isinstance(response, str) and response.strip().startswith("{") and "text" in response:
            parsed = self._parse_llm_json(response, fallback=None)
            if parsed and isinstance(parsed, dict) and 'text' in parsed:
                response = parsed['text']

        answer = self._post_process_response(response, platform)
        return answer, {"context_raw": debug_data, "keywords": keywords}

    def _handle_chat(self, query, chat_history, platform):
        formatting_instructions = self._get_formatting_instructions(platform)
        history_str = self._format_chat_history(chat_history)
        
        response = self.chat_chain.invoke({
            "query": query,
            "chat_history": history_str,
            "formatting_instructions": formatting_instructions
        }, config=self._run_config)
        
        answer = self._post_process_response(response, platform)
        return answer, {}

    def _handle_advisory(self, query, keywords, secondary_intent, attached_content, chat_history, platform):
        """
        Handles advisory/consultative queries: research design, methodology recommendations,
        hypothesis validation, strategic suggestions.
        When secondary_intent is provided (e.g., SIMPLE_SEARCH), retrieves context to ground advice in evidence.
        """
        formatting_instructions = self._get_formatting_instructions(platform)
        history_str = self._format_chat_history(chat_history)

        # Always retrieve context for advisory β€” advice should be grounded in evidence
        context_str, debug_data = self._agentic_retrieve_context(keywords, query, "ADVISORY")
        full_context = f"{context_str}\n{attached_content}" if attached_content else context_str

        response = self.advisory_chain.invoke({
            "query": query,
            "context": full_context,
            "chat_history": history_str,
            "formatting_instructions": formatting_instructions
        }, config=self._run_config)

        answer = self._post_process_response(response, platform)
        return answer, {"context_raw": debug_data, "keywords": keywords, "blended_with": secondary_intent}

    def _handle_specific_analysis(self, target_query, user_query, chat_history, platform):
        """
        Handles analysis for a specific item (Title link or ID).
        Fetches FULL content of that single item and restricts context.
        """
        logger.info(f"Targeting specific item: {target_query}")
        
        # 1. Fetch Specific Item
        item = self.retriever.get_specific_item(target_query)
        
        formatting_instructions = self._get_formatting_instructions(platform)
        history_str = self._format_chat_history(chat_history)

        if not item:
            # Fallback to general search if specific item not found
            logger.warning(f"Specific item '{target_query}' not found. Falling back to Deep Research.")
            return self._handle_search(user_query, [target_query], True, "", chat_history, platform)

        # 2. Construct Focused Context
        full_context = (
            f"!!! SPECIFIC ITEM ANALYSIS SCENARIO !!!\n"
            f"The user wants to analyze ONLY the following item:\n\n"
            f"[{item['source']}] {item['title']} (ID: {item['id']})\n"
            f"Link: {item['link']}\n"
            f"Content:\n{item['content']}\n"
        )

        # 3. Use Specific Analysis Chain
        response = self.specific_analysis_chain.invoke({
            "query": user_query,
            "context": full_context,
            "chat_history": history_str,
            "formatting_instructions": formatting_instructions
        }, config=self._run_config)
        
        answer = self._post_process_response(response, platform)
        debug_data = {
            "results": {"internal": [item] if item['source'] == 'INTERNAL' else [], "baymard": [item] if item['source'] == 'BAYMARD' else [], "nng": [item] if item['source'] == 'NNG' else []},
            "hit_counts": {"internal": 1 if item['source'] == 'INTERNAL' else 0, "baymard": 1 if item['source'] == 'BAYMARD' else 0, "nng": 1 if item['source'] == 'NNG' else 0}
        }
        return answer, {"context_raw": debug_data, "keywords": [target_query]}

    def _handle_search(self, query, keywords, is_deep, attached_content, chat_history, platform):
        formatting_instructions = self._get_formatting_instructions(platform)
        history_str = self._format_chat_history(chat_history)

        # Retrieve Context
        context_str, debug_data = self._agentic_retrieve_context(keywords, query, "DEEP_RESEARCH" if is_deep else "SIMPLE_SEARCH")
        full_context = f"{context_str}\n{attached_content}"
        
        if is_deep:
            chain = self.deep_research_chain
        else:
            chain = self.simple_search_chain

        response = chain.invoke({
            "query": query,
            "context": full_context,
            "chat_history": history_str,
            "formatting_instructions": formatting_instructions
        }, config=self._run_config)
        
        answer = self._post_process_response(response, platform)
        return answer, {"context_raw": debug_data, "keywords": keywords}

    def _agentic_retrieve_context(self, keywords: List[str], original_query: str, intent: str):
        """Uses the agentic retriever (LLM-driven search→read→judge loop)."""
        return self.agentic_retriever.retrieve(
            query=original_query or " ".join(keywords),
            keywords=keywords,
            intent=intent,
        )

    def _get_formatting_instructions(self, platform):
        if platform == "slack":
            return self.prompt_manager.get_prompt("formatting_slack")
        return self.prompt_manager.get_prompt("formatting_web")

    def _format_chat_history(self, chat_history):
        return "\n".join([f"{msg['role']}: {msg['content']}" for msg in chat_history[-SCORING.max_history_messages:]])



if __name__ == "__main__":
    engine = SearchEngine()
    history = []
    print("Search Engine initialized.")
    while True:
        try:
            q = input("\nμ§ˆλ¬Έν•΄ μ£Όμ„Έμš” (μ’…λ£Œ: q): ")
            if q.lower() == 'q':
                break
            print("\nλ‹΅λ³€ 생성 쀑...")
            response = engine.search_and_answer(q, history)
            print(response)
            history.append({"role": "user", "content": q})
            history.append({"role": "assistant", "content": response})
        except KeyboardInterrupt:
            break