SilverElixir commited on
Commit
bcdd628
·
1 Parent(s): f065619

Attach external search snippets to every fresh query, not only when Gemini grounding is missing

Browse files
docs/ARCHITECTURE.md CHANGED
@@ -17,7 +17,7 @@ Routing is fully automatic: the router builds a fresh candidate list for every m
17
  - **A YouTube or website link** → Gemini only. It's the only provider that can read page content (`url_context`) or analyze a video by URL.
18
  - **A video or audio attachment** → video goes to Gemini only (OpenRouter's multimodal models only accept images as base64). Voice/audio is first transcribed cheaply (Groq Whisper) and the text joins the normal routing below; if transcription fails or is unavailable, the audio goes to Gemini as before.
19
  - **An image attachment, no live-info need** → free OpenRouter vision models first, Gemini as a reserve. With a freshness need, Gemini search models go first and OpenRouter vision stays as a fallback.
20
- - **Needs current information** (a lightweight keyword heuristic: "now," "today," "price," "who is currently...," plus an explicit "search the web / погугли" ask; astronomy that depends on the date — sunrise/sunset/moon — triggers it too) → Gemini, prioritizing the models with a real search-grounding quota, then OpenRouter as a reserve, Groq last (knowledge-only answer if both are down). If no live-search Gemini model is left in the route (quota exhausted), a free DuckDuckGo snippet block is attached to the prompt so any provider answers with real data (`WEB_SEARCH_*`); if that fetch fails too, the reply is honestly marked as answered without live search. Freshness prompts additionally carry today's date (Europe/Moscow) so relative days are not guessed.
21
  - **Plain text, no attachments, no freshness need** (the most common case) → Gemma first (offline eval 22.10.2026: 47/50 persona score, ~14.4K free requests/day per model via the Google free tier; 26B-A4B head, 31B next), then Groq (1000 free requests/day: Qwen, then gpt-oss), then OpenRouter, Gemini as reserve. Heavier requests (code, multi-step reasoning, caught by another lightweight heuristic) still start at Groq to spare the scarcer OpenRouter/Gemini quotas, then go to the stronger free OpenRouter models, Gemini as reserve.
22
 
23
  The reasoning: for ordinary messages the bulk quality came out of the offline persona eval with Gemma at the top, and its Google free quota is by far the largest (thousands per day versus 500 for Gemini lite models), so Groq and OpenRouter are now reserves rather than the text backbone. Gemini remains the only provider for links, video, audio and live search.
 
17
  - **A YouTube or website link** → Gemini only. It's the only provider that can read page content (`url_context`) or analyze a video by URL.
18
  - **A video or audio attachment** → video goes to Gemini only (OpenRouter's multimodal models only accept images as base64). Voice/audio is first transcribed cheaply (Groq Whisper) and the text joins the normal routing below; if transcription fails or is unavailable, the audio goes to Gemini as before.
19
  - **An image attachment, no live-info need** → free OpenRouter vision models first, Gemini as a reserve. With a freshness need, Gemini search models go first and OpenRouter vision stays as a fallback.
20
+ - **Needs current information** (a lightweight keyword heuristic: "now," "today," "price," "who is currently...," plus an explicit "search the web / погугли" ask; astronomy that depends on the date — sunrise/sunset/moon — triggers it too) → Gemini, prioritizing the models with a real search-grounding quota, then OpenRouter as a reserve, Groq last. Every freshness/search query also gets a free external snippet block (DuckDuckGo, then Bing RSS and Google News in parallel — `WEB_SEARCH_*`) attached to the prompt, so whichever model answers, including the non-Gemini reserves and users over their daily Gemini limit, has real search results. If that fetch returns nothing (or the switch is off), the reply is honestly marked as answered without live search. Freshness prompts additionally carry today's date (Europe/Moscow) so relative days are not guessed.
21
  - **Plain text, no attachments, no freshness need** (the most common case) → Gemma first (offline eval 22.10.2026: 47/50 persona score, ~14.4K free requests/day per model via the Google free tier; 26B-A4B head, 31B next), then Groq (1000 free requests/day: Qwen, then gpt-oss), then OpenRouter, Gemini as reserve. Heavier requests (code, multi-step reasoning, caught by another lightweight heuristic) still start at Groq to spare the scarcer OpenRouter/Gemini quotas, then go to the stronger free OpenRouter models, Gemini as reserve.
22
 
23
  The reasoning: for ordinary messages the bulk quality came out of the offline persona eval with Gemma at the top, and its Google free quota is by far the largest (thousands per day versus 500 for Gemini lite models), so Groq and OpenRouter are now reserves rather than the text backbone. Gemini remains the only provider for links, video, audio and live search.
lumen_message_core.py CHANGED
@@ -692,7 +692,7 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
692
  _late_entry = bot._user_daily_peek(uid)
693
  if await _refuse_daily_total(message, uid, _late_entry):
694
  return
695
- no_search_note = False
696
  if bot._user_daily_gemini_exhausted(uid, _late_entry):
697
  # Gemma не тратит дефицитную квоту, поэтому остаётся и после лимита:
698
  # обычный текст должен работать, как и обещает отказ (аудит 27.10.2026).
@@ -702,8 +702,7 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
702
  await _refuse_daily_gemini(message, uid, _late_entry)
703
  return
704
  route = allowed
705
- # Свежесть без Gemini — честная пометка, что ответ без поиска.
706
- no_search_note = needs_freshness and not route_has_live_search(route)
707
  # Дошло до обработки: фон, инъекции и отказы выше уже отсеяны.
708
  bot._record_stats_event("messages_received")
709
 
@@ -714,16 +713,14 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
714
  # до промпта — попадает и в пост-хок ретрай, он переиспользует этот ai_prompt.
715
  if needs_freshness:
716
  ai_prompt += "\n\n" + _fresh_date_context()
717
- # Внешний поиск нужен свежему запросу без живого поиска в маршруте (ссылки/YouTube
718
- # читает только Gemini — им сниппеты не замена). Дневной лимит пользователя — не сюда:
719
- # его квота потрачена, ответ идёт с честной пометкой без чужого поиска.
720
- # Выключен свитчом или пуст — тоже отвечаем с пометкой.
721
  need_external_search = (
722
  needs_freshness
723
  and not needs_youtube
724
  and not needs_website
725
- and not no_search_note
726
- and not route_has_live_search(route)
727
  )
728
  web_search_failed = False
729
  snippets_injected = False
@@ -752,6 +749,11 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
752
  web_search_failed = True
753
  elif need_external_search:
754
  web_search_failed = True
 
 
 
 
 
755
  if (
756
  media_tuple is None
757
  and not extra_media
@@ -765,14 +767,14 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
765
  # Стриминг ("живой" эффект печати) имеет смысл только для простого
766
  # текстового обмена без вложений/YouTube — см. _run_route. При пометке
767
  # "без поиска" стрим гасим: она дописывается к готовому ответу.
768
- # Стрим головы без живого поиска при свежем запросе гасим: иначе ответ уйдёт
769
- # без поиска до пост-проверки и ретрай уже невозможен (прод 12.10.2026).
770
  head_has_live_search = (not route) or route_has_live_search(route[:1])
771
  allow_stream = (
772
  not gemini_media_list
773
  and not youtube_url_to_analyze
774
  and not no_search_note
775
- and (not needs_freshness or head_has_live_search)
776
  )
777
  if route_deadline is None:
778
  # Один дедлайн на первый проход и пост-хок ретрай: раньше ретрай
@@ -790,9 +792,9 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
790
  )
791
  answered_grounded = answered_with_live_search(provenance)
792
  if needs_freshness and not snippets_injected and not answered_grounded and not reply_already_sent and not no_search_note:
793
- # План маршрута содержал живой поиск, но ответила модель без него
794
- # (граундинг-модели умерли на квоте по ходу). Догоняем DuckDuckGo
795
- # и один ретрай со сниппетами; не вышло — честная пометка.
796
  retry_snippets: list = []
797
  try:
798
  retry_budget = web_search_timeout_sec()
 
692
  _late_entry = bot._user_daily_peek(uid)
693
  if await _refuse_daily_total(message, uid, _late_entry):
694
  return
695
+ user_gemini_limited = False
696
  if bot._user_daily_gemini_exhausted(uid, _late_entry):
697
  # Gemma не тратит дефицитную квоту, поэтому остаётся и после лимита:
698
  # обычный текст должен работать, как и обещает отказ (аудит 27.10.2026).
 
702
  await _refuse_daily_gemini(message, uid, _late_entry)
703
  return
704
  route = allowed
705
+ user_gemini_limited = True
 
706
  # Дошло до обработки: фон, инъекции и отказы выше уже отсеяны.
707
  bot._record_stats_event("messages_received")
708
 
 
713
  # до промпта — попадает и в пост-хок ретрай, он переиспользует этот ai_prompt.
714
  if needs_freshness:
715
  ai_prompt += "\n\n" + _fresh_date_context()
716
+ # Внешний поиск — для любого свежего запроса: сниппеты едут всем моделям маршрута,
717
+ # а не только резерву, когда grounding-моделей не осталось (задумка поиска: искать
718
+ # умеет не только Gemini). Ссылки/YouTube читает только Gemini — им сниппеты не замена.
719
+ # Выключен свитчом или пуст — отвечаем с пометкой.
720
  need_external_search = (
721
  needs_freshness
722
  and not needs_youtube
723
  and not needs_website
 
 
724
  )
725
  web_search_failed = False
726
  snippets_injected = False
 
749
  web_search_failed = True
750
  elif need_external_search:
751
  web_search_failed = True
752
+ # Пометка «без поиска» — только если поиск реально не дал результатов: при
753
+ # исчерпанном лимите Gemini сниппеты едут дешёвым моделям, а не отключаются.
754
+ no_search_note = user_gemini_limited and needs_freshness and not snippets_injected
755
+ if no_search_note:
756
+ web_search_failed = False
757
  if (
758
  media_tuple is None
759
  and not extra_media
 
767
  # Стриминг ("живой" эффект печати) имеет смысл только для простого
768
  # текстового обмена без вложений/YouTube — см. _run_route. При пометке
769
  # "без поиска" стрим гасим: она дописывается к готовому ответу.
770
+ # Свежий ответ без сниппетов и без grounding-головы не стримим: иначе он
771
+ # уйдёт до пост-проверки и ретрай уже невозможен (прод 12.10.2026).
772
  head_has_live_search = (not route) or route_has_live_search(route[:1])
773
  allow_stream = (
774
  not gemini_media_list
775
  and not youtube_url_to_analyze
776
  and not no_search_note
777
+ and (not needs_freshness or head_has_live_search or snippets_injected)
778
  )
779
  if route_deadline is None:
780
  # Один дедлайн на первый проход и пост-хок ретрай: раньше ретрай
 
792
  )
793
  answered_grounded = answered_with_live_search(provenance)
794
  if needs_freshness and not snippets_injected and not answered_grounded and not reply_already_sent and not no_search_note:
795
+ # Поиск до маршрута ничего не дал, а ответила модель без живого
796
+ # поиска: пробуем ещё раз и один ретрай со сниппетами; не вышло —
797
+ # честная пометка.
798
  retry_snippets: list = []
799
  try:
800
  retry_budget = web_search_timeout_sec()
tests/test_bot_search.py CHANGED
@@ -84,25 +84,81 @@ def test_disabled_search_marks_reply_without_live_search(rate_guard_setup, monke
84
  bot.chat_state.pop(123, None)
85
 
86
 
87
- def test_daily_limit_keeps_note_and_skips_external_search(rate_guard_setup, monkeypatch):
88
- # Граница: дневной лимит пользователя — честная пометка без чужого поиска
89
- # (лимит именно его, обходить поиском нельзя) и без единого сетевого вызова в тестах.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  message = rate_guard_setup()
91
  message.text = "погугли что происходит с ДЦ Яндекса"
92
  monkeypatch.setattr(bot, "_user_daily_gemini_exhausted", lambda uid, entry: True)
 
93
 
94
  async def fake_fetch(query, *, timeout_sec=None, max_results=None):
95
- raise AssertionError("fetch must not run on daily user limit")
96
 
97
  async def fake_run_route(chat_id, ai_prompt, route, message, **kwargs):
 
 
98
  assert all(p != "gemini" for p, _ in route)
99
  return "ok", False
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  monkeypatch.setattr("lumen_message_core.fetch_web_snippets", fake_fetch)
102
  monkeypatch.setattr(bot, "_run_route", fake_run_route)
103
  asyncio.run(bot._handle_message_core(message))
104
  sent_text = bot._safe_reply.await_args[0][1]
105
  assert sent_text.startswith("Answering without web search")
 
106
  bot.chat_state.pop(123, None)
107
 
108
 
@@ -115,10 +171,14 @@ def test_freshness_prompt_carries_today_date(rate_guard_setup, monkeypatch):
115
  message.text = "какая сегодня погода в Москве"
116
  captured: dict = {}
117
 
 
 
 
118
  async def fake_run_route(chat_id, ai_prompt, route, message, **kwargs):
119
  captured["prompt"] = ai_prompt
120
  return "ok", False
121
 
 
122
  monkeypatch.setattr(bot, "_run_route", fake_run_route)
123
  asyncio.run(bot._handle_message_core(message))
124
  prompt = captured["prompt"]
 
84
  bot.chat_state.pop(123, None)
85
 
86
 
87
+ def test_fresh_query_with_live_gemini_still_gets_external_snippets(rate_guard_setup, monkeypatch):
88
+ # Раньше сниппеты подставлялись только когда в маршруте не оставалось
89
+ # grounding-моделей; теперь искать обязана любая ответившая модель, в том
90
+ # числе резервная после 429 у Gemini (прод 28.10.2026).
91
+ message = rate_guard_setup()
92
+ message.text = "погугли что происходит с ДЦ Яндекса"
93
+ captured: dict = {}
94
+
95
+ async def fake_fetch(query, *, timeout_sec=None, max_results=None):
96
+ return [{"title": "Новость", "url": "https://example.com/grounded", "snippet": "Данные"}]
97
+
98
+ async def fake_run_route(chat_id, ai_prompt, route, message, **kwargs):
99
+ captured["prompt"] = ai_prompt
100
+ # Отвечает grounding-модель: пост-хок ретрай не должен маскировать
101
+ # отсутствие предварительной подстановки.
102
+ provenance = kwargs.get("provenance")
103
+ if isinstance(provenance, dict):
104
+ provenance.update(provider="gemini", model="gemini-2.5-flash")
105
+ return "ok", False
106
+
107
+ monkeypatch.setattr("lumen_message_core.fetch_web_snippets", fake_fetch)
108
+ monkeypatch.setattr(bot, "_run_route", fake_run_route)
109
+ asyncio.run(bot._handle_message_core(message))
110
+ assert "https://example.com/grounded" in captured["prompt"]
111
+ bot.chat_state.pop(123, None)
112
+
113
+
114
+ def test_daily_limit_still_gets_external_search_snippets(rate_guard_setup, monkeypatch):
115
+ # Дневной лимит Gemini не отключает внешний поиск: сниппеты едут дешёвым
116
+ # моделям маршрута, иначе они отвечают по памяти (задумка поиска — искать
117
+ # умеет не только Gemini).
118
  message = rate_guard_setup()
119
  message.text = "погугли что происходит с ДЦ Яндекса"
120
  monkeypatch.setattr(bot, "_user_daily_gemini_exhausted", lambda uid, entry: True)
121
+ captured: dict = {}
122
 
123
  async def fake_fetch(query, *, timeout_sec=None, max_results=None):
124
+ return [{"title": "Новость", "url": "https://example.com/daily", "snippet": "Свежие данные"}]
125
 
126
  async def fake_run_route(chat_id, ai_prompt, route, message, **kwargs):
127
+ captured["prompt"] = ai_prompt
128
+ captured["allow_stream"] = kwargs.get("allow_stream")
129
  assert all(p != "gemini" for p, _ in route)
130
  return "ok", False
131
 
132
+ monkeypatch.setattr("lumen_message_core.fetch_web_snippets", fake_fetch)
133
+ monkeypatch.setattr(bot, "_run_route", fake_run_route)
134
+ asyncio.run(bot._handle_message_core(message))
135
+ assert "https://example.com/daily" in captured["prompt"]
136
+ assert captured["allow_stream"] is True
137
+ sent_text = bot._safe_reply.await_args[0][1]
138
+ assert "without web search" not in sent_text
139
+ bot.chat_state.pop(123, None)
140
+
141
+
142
+ def test_daily_limit_with_empty_search_keeps_no_search_note(rate_guard_setup, monkeypatch):
143
+ # Если и внешний поиск пуст — пометка «без поиска» обязана остаться.
144
+ message = rate_guard_setup()
145
+ message.text = "погугли что происходит с ДЦ Яндекса"
146
+ monkeypatch.setattr(bot, "_user_daily_gemini_exhausted", lambda uid, entry: True)
147
+ captured: dict = {}
148
+
149
+ async def fake_fetch(query, *, timeout_sec=None, max_results=None):
150
+ return []
151
+
152
+ async def fake_run_route(chat_id, ai_prompt, route, message, **kwargs):
153
+ captured["allow_stream"] = kwargs.get("allow_stream")
154
+ return "ok", False
155
+
156
  monkeypatch.setattr("lumen_message_core.fetch_web_snippets", fake_fetch)
157
  monkeypatch.setattr(bot, "_run_route", fake_run_route)
158
  asyncio.run(bot._handle_message_core(message))
159
  sent_text = bot._safe_reply.await_args[0][1]
160
  assert sent_text.startswith("Answering without web search")
161
+ assert captured["allow_stream"] is False
162
  bot.chat_state.pop(123, None)
163
 
164
 
 
171
  message.text = "какая сегодня погода в Москве"
172
  captured: dict = {}
173
 
174
+ async def fake_fetch(query, *, timeout_sec=None, max_results=None):
175
+ return []
176
+
177
  async def fake_run_route(chat_id, ai_prompt, route, message, **kwargs):
178
  captured["prompt"] = ai_prompt
179
  return "ok", False
180
 
181
+ monkeypatch.setattr("lumen_message_core.fetch_web_snippets", fake_fetch)
182
  monkeypatch.setattr(bot, "_run_route", fake_run_route)
183
  asyncio.run(bot._handle_message_core(message))
184
  prompt = captured["prompt"]
tests/test_bot_state.py CHANGED
@@ -3044,8 +3044,9 @@ def test_core_refuses_when_user_daily_total_exhausted(rate_guard_setup, monkeypa
3044
 
3045
 
3046
  def test_core_falls_back_without_gemini_and_marks_no_search(rate_guard_setup, monkeypatch):
3047
- # Новое: свежесть без ссылок при исчерпанном Gemini идёт через Groq/OpenRouter
3048
- # с пометкой "без поиска".
 
3049
  message = rate_guard_setup()
3050
  message.text = "что нового сегодня"
3051
  monkeypatch.setattr(bot, "DAILY_USER_GEMINI_LIMIT", 1)
@@ -3053,6 +3054,9 @@ def test_core_falls_back_without_gemini_and_marks_no_search(rate_guard_setup, mo
3053
  captured = {}
3054
  replies = []
3055
 
 
 
 
3056
  async def fake_route(chat_id, ai_prompt, route, msg, **kwargs):
3057
  captured["route"] = route
3058
  captured["allow_stream"] = kwargs.get("allow_stream")
@@ -3061,6 +3065,7 @@ def test_core_falls_back_without_gemini_and_marks_no_search(rate_guard_setup, mo
3061
  async def fake_safe_reply(msg, text, **kwargs):
3062
  replies.append(text)
3063
 
 
3064
  monkeypatch.setattr(bot, "_run_route", fake_route)
3065
  monkeypatch.setattr(bot, "_safe_reply", fake_safe_reply)
3066
  try:
 
3044
 
3045
 
3046
  def test_core_falls_back_without_gemini_and_marks_no_search(rate_guard_setup, monkeypatch):
3047
+ # Свежесть без ссылок при исчерпанном Gemini идёт через Groq/OpenRouter;
3048
+ # внешний поиск пробует дать им сниппеты, и только пустой поиск оставляет
3049
+ # пометку "без поиска".
3050
  message = rate_guard_setup()
3051
  message.text = "что нового сегодня"
3052
  monkeypatch.setattr(bot, "DAILY_USER_GEMINI_LIMIT", 1)
 
3054
  captured = {}
3055
  replies = []
3056
 
3057
+ async def fake_fetch(query, *, timeout_sec=None, max_results=None):
3058
+ return []
3059
+
3060
  async def fake_route(chat_id, ai_prompt, route, msg, **kwargs):
3061
  captured["route"] = route
3062
  captured["allow_stream"] = kwargs.get("allow_stream")
 
3065
  async def fake_safe_reply(msg, text, **kwargs):
3066
  replies.append(text)
3067
 
3068
+ monkeypatch.setattr("lumen_message_core.fetch_web_snippets", fake_fetch)
3069
  monkeypatch.setattr(bot, "_run_route", fake_route)
3070
  monkeypatch.setattr(bot, "_safe_reply", fake_safe_reply)
3071
  try: