File size: 7,716 Bytes
212c959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
web.py β€” Real-time web search utilities.

Search cascade:
  1. Tavily  (fast, structured results, needs API key)
  2. DuckDuckGo  (free, no key needed) β€” fallback when Tavily fails/empty
"""
from __future__ import annotations

import asyncio
import logging
import re
from typing import Any

logger = logging.getLogger(__name__)


# ── Detection heuristics ──────────────────────────────────────────────────────

# Keywords that strongly indicate the user wants live/current information.
_REALTIME_WORDS = re.compile(
    r"""(?ix)
    \b(
      latest | newest | recent | currently | right now | as of today |
      today | tonight | this morning | this evening | this week | this month | this year |
      yesterday | last night | last week | last month |
      breaking | live | ongoing | just (happened|announced|released|launched|dropped) |
      in \s+ the \s+ news | trending | viral |
      current | now | update | updates |
      score | result | results | winner | winners | standings |
      stock | crypto | bitcoin | ethereum | price | prices | rate | rates | exchange \s+ rate |
      weather | forecast | temperature | rain | storm | hurricane | earthquake |
      election | vote | votes | poll | polls |
      match | game | tournament | championship | cup | league | ipl | nba | nfl | premier \s+ league |
      war | conflict | attack | protest | summit | deal | treaty |
      launch | released | announced | unveiled | dropped | update |
      who \s+ won | who \s+ is \s+ winning | what \s+ happened | what \s+ is \s+ happening |
      how \s+ much \s+ is | what \s+ is \s+ the \s+ (current|latest|price|value) |
      did \s+ \w+ \s+ (win|lose|beat|happen|say|announce|release) |
      when \s+ did | when \s+ is \s+ (the \s+)?(next|upcoming) |
      2024 | 2025 | 2026
    )\b
    """,
)

# Phrases that only make sense for live data (even without trigger words)
_REALTIME_PHRASES = [
    "current president",
    "prime minister",
    "today's",
    "this week's",
    "live score",
    "box office",
    "number one",
    "top charts",
    "inflation rate",
    "gdp growth",
    "unemployment rate",
    "oil price",
    "gold price",
    "market cap",
    "nifty 50",
    "sensex",
    "dow jones",
    "s&p 500",
    "nasdaq",
]

# Questions that are clearly NOT real-time (don't over-search)
_SKIP_RE = re.compile(
    r"""(?ix)
    \b(
      what \s+ is \s+ (machine \s+ learning|artificial \s+ intelligence|python|java|
                       gravity|photosynthesis|democracy|capitalism|blockchain|
                       deep \s+ learning|neural \s+ network) |
      how \s+ does \s+ \w+ \s+ work |
      explain \s+ (me \s+)? (the \s+)? \w+ |
      write \s+ (a|an|me) \s+ (poem|story|essay|function|code|program|script|letter) |
      help \s+ me \s+ (with|understand|write|debug|fix|code) |
      what \s+ are \s+ the \s+ (best \s+ practices|benefits|advantages|disadvantages) |
      history \s+ of |
      definition \s+ of |
      difference \s+ between
    )\b
    """,
)


def should_web_search(user_message: str) -> bool:
    """
    Decide whether the user message warrants a real-time web search.
    Returns True when the query is likely time-sensitive or current-events related.
    """
    msg = (user_message or "").strip()
    if not msg:
        return False

    # Skip clearly non-real-time educational/coding questions
    if _SKIP_RE.search(msg):
        return False

    # Hard-match real-time keywords
    if _REALTIME_WORDS.search(msg):
        return True

    # Phrase match
    msg_lower = msg.lower()
    if any(phrase in msg_lower for phrase in _REALTIME_PHRASES):
        return True

    # Question starting with "who is" / "who was" often needs current info
    if re.match(r"(?i)^who\s+(is|are|was|were)\s+", msg):
        return True

    # "What is X?" for things that change (stock prices, scores, etc.)
    if re.match(r"(?i)^what('?s|\s+is|\s+are)\s+(the\s+)?(current|latest|today)", msg):
        return True

    return False


# ── Tavily search ─────────────────────────────────────────────────────────────

async def _tavily_search(api_key: str, query: str, max_results: int) -> list[dict[str, Any]]:
    def _do() -> dict[str, Any]:
        from tavily import TavilyClient
        return TavilyClient(api_key=api_key).search(query=query, max_results=max_results)

    result = await asyncio.to_thread(_do)
    return result.get("results") or []


# ── DuckDuckGo search ─────────────────────────────────────────────────────────

async def _ddg_search(query: str, max_results: int) -> list[dict[str, Any]]:
    def _do() -> list[dict[str, Any]]:
        from duckduckgo_search import DDGS
        with DDGS() as ddgs:
            return list(ddgs.text(query, max_results=max_results))

    return await asyncio.to_thread(_do)


# ── Format results to context string ─────────────────────────────────────────

def _format_results(results: list[dict[str, Any]], source: str) -> str:
    if not results:
        return ""
    lines: list[str] = [f"πŸ” Web search results ({source}):"]
    for i, r in enumerate(results, start=1):
        title   = (r.get("title") or "").strip()
        url     = (r.get("url") or r.get("href") or "").strip()
        snippet = (r.get("content") or r.get("body") or r.get("snippet") or "").strip()
        if not snippet:
            snippet = "No snippet available."
        lines.append(f"\n{i}. **{title}**\n   {snippet}\n   Source: {url}")
    return "\n".join(lines)


# ── Public entry point ────────────────────────────────────────────────────────

async def fetch_web_context(
    query: str,
    *,
    tavily_api_key: str | None = None,
    max_results: int = 5,
) -> str | None:
    """
    Try Tavily first, fall back to DuckDuckGo.
    Returns a formatted context string or None if both fail.
    """
    # 1. Tavily
    if tavily_api_key:
        try:
            results = await _tavily_search(tavily_api_key, query, max_results)
            if results:
                logger.info("web_search source=tavily query=%r results=%d", query, len(results))
                return _format_results(results, "Tavily")
            logger.info("web_search tavily returned 0 results for %r, trying DuckDuckGo", query)
        except Exception as exc:
            logger.warning("web_search tavily_failed=%r, falling back to DuckDuckGo", exc)

    # 2. DuckDuckGo fallback
    try:
        results = await _ddg_search(query, max_results)
        if results:
            logger.info("web_search source=duckduckgo query=%r results=%d", query, len(results))
            return _format_results(results, "DuckDuckGo")
    except Exception as exc:
        logger.warning("web_search duckduckgo_failed=%r", exc)

    return None


# ── Legacy compat (keep old name so graph.py import doesn't break) ────────────
async def tavily_search_to_context(
    api_key: str,
    query: str,
    *,
    max_results: int = 5,
) -> str:
    """Deprecated: use fetch_web_context instead."""
    ctx = await fetch_web_context(query, tavily_api_key=api_key, max_results=max_results)
    return ctx or "No relevant web results found."