DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(search): add Web Risk lookups and renumber filtered citations (#375)
ZQR110192aea79cd494
diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.pyindex 1fe054a20..22744cc13 100644--- a/deeptutor/services/search/__init__.py+++ b/deeptutor/services/search/__init__.py@@ -265,8 +265,9 @@ def get_current_config() -> dict[str, Any]:resolved = resolve_search_runtime_config()source_filtering = dict(_get_source_filter_settings())# Never surface the bearer token to Settings / CLI — only whether Moderation- # is wired (key present + use_moderation).+ # is wired (key present + use_moderation). Same for the Web Risk API key.source_filtering["moderation_configured"] = bool(source_filtering.pop("moderation_api_key", ""))+ source_filtering["web_risk_configured"] = bool(source_filtering.pop("web_risk_api_key", ""))return {"enabled": config.get("enabled", True),"provider": resolved.provider,diff --git a/deeptutor/services/search/source_filter.py b/deeptutor/services/search/source_filter.pyindex 33db42033..295131d71 100644--- a/deeptutor/services/search/source_filter.py+++ b/deeptutor/services/search/source_filter.py@@ -7,8 +7,10 @@ import jsonimport loggingimport osimport re+import threading+import timefrom typing import Any-from urllib.parse import urlparse+from urllib.parse import quote, urlparseimport urllib.requestfrom .types import Citation, SearchResult, WebSearchResponse@@ -76,6 +78,17 @@ _UNSAFE_URL_PATH_PATTERNS: tuple[re.Pattern[str], ...] = tuple(_MODERATION_URL = "https://api.openai.com/v1/moderations"_MODERATION_TIMEOUT_S = 8.0+# Google Web Risk Lookup (#375 stage 3). Opt-in via ``use_web_risk`` plus an+# API key; the free tier is the 100k lookups/month the issue pinned its hopes+# on, so results are cached briefly and shared lookups are deduplicated.+_WEB_RISK_URL = "https://webrisk.googleapis.com/v1/uris:search"+_WEB_RISK_TIMEOUT_S = 5.0+_WEB_RISK_THREAT_TYPES = ("MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE")+_WEB_RISK_CACHE_TTL_S = 900.0+_WEB_RISK_CACHE_MAX = 1024+_web_risk_cache: dict[str, tuple[float, bool]] = {}+_web_risk_cache_lock = threading.Lock()+def _as_bool(value: Any, default: bool = False) -> bool:if value is None:@@ -240,6 +253,64 @@ def _request_openai_moderation(texts: list[str], *, api_key: str) -> list[bool]:return [bool(isinstance(result, dict) and result.get("flagged")) for result in results]+def _request_web_risk(url: str, *, api_key: str) -> bool:+ """Return True when the Web Risk Lookup API flags ``url`` as a threat."""+ parts = [f"threatTypes={threat}" for threat in _WEB_RISK_THREAT_TYPES]+ parts.append(f"uri={quote(url, safe='')}")+ parts.append(f"key={quote(api_key, safe='')}")+ request = urllib.request.Request(+ f"{_WEB_RISK_URL}?{'&'.join(parts)}",+ headers={"User-Agent": "DeepTutor-source-filter/1.0"},+ method="GET",+ )+ with urllib.request.urlopen(request, timeout=_WEB_RISK_TIMEOUT_S) as response: # nosec B310 - hardcoded https constant URL+ raw = json.loads(response.read().decode("utf-8"))+ threat = raw.get("threat") if isinstance(raw, dict) else None+ return bool(isinstance(threat, dict) and threat)+++def _web_risk_rejections(+ urls: list[str],+ *,+ api_key: str,+ request_web_risk: Any | None = None,+) -> set[str]:+ """Return the subset of ``urls`` flagged by Web Risk.++ Fail open on transport/API errors so an outage or exhausted quota never+ blanks every web-search turn — heuristics and Moderation already ran.+ """+ unique = list(dict.fromkeys(url for url in urls if url))+ if not unique or not api_key:+ return set()+ requester = request_web_risk or _request_web_risk+ flagged: set[str] = set()+ now = time.monotonic()+ pending: list[str] = []+ with _web_risk_cache_lock:+ for url in unique:+ entry = _web_risk_cache.get(url)+ if entry is not None and now - entry[0] < _WEB_RISK_CACHE_TTL_S:+ if entry[1]:+ flagged.add(url)+ else:+ pending.append(url)+ for url in pending:+ try:+ is_flagged = bool(requester(url, api_key=api_key))+ except Exception as exc: # noqa: BLE001 — network / JSON / quota quirks+ _logger.warning("Web Risk lookup skipped after error: %s", exc)+ continue+ with _web_risk_cache_lock:+ if len(_web_risk_cache) >= _WEB_RISK_CACHE_MAX:+ for stale in list(_web_risk_cache)[: len(_web_risk_cache) // 2]:+ _web_risk_cache.pop(stale, None)+ _web_risk_cache[url] = (time.monotonic(), is_flagged)+ if is_flagged:+ flagged.add(url)+ return flagged++def _reference_text(*, title: str = "", snippet: str = "", content: str = "") -> str:parts = [str(title or "").strip(), str(snippet or "").strip(), str(content or "").strip()]return "\n".join(part for part in parts if part)@@ -256,17 +327,24 @@ def filter_web_search_response(use_moderation: bool = False,moderation_api_key: str | None = None,request_moderation: Any | None = None,+ use_web_risk: bool = False,+ web_risk_api_key: str | None = None,+ request_web_risk: Any | None = None,) -> WebSearchResponse:"""Drop unsafe or disallowed references from a provider response.- Citation ids and reference labels stay unchanged when an item is removed.- Provider-authored answers already cite those labels, so renumbering here- would turn a harmless gap into incorrect citations.+ When citations are removed, the retained ones are renumbered ``1..k``:+ the provider prose citing the old labels is discarded (the caller rebuilds+ the answer from the retained raw results, whose markers are positional+ ``[i]``), so a contiguous reference list is strictly more truthful than+ keeping stale ids that point at dropped URLs. Removals that leave all+ citations intact keep every label unchanged — the prose still cites them.Stages (in order):1. URL hygiene / domain policy (existing)2. Title + snippet heuristics (``content_filtering``, on by default)3. Optional OpenAI Moderation when ``use_moderation`` and a key are set+ 4. Optional Google Web Risk Lookup when ``use_web_risk`` and a key are set"""if not enabled:return response@@ -278,9 +356,11 @@ def filter_web_search_response(moderation_key = str(moderation_api_key or "").strip()moderation_active = bool(use_moderation and moderation_key)+ web_risk_key = str(web_risk_api_key or "").strip()+ web_risk_active = bool(use_web_risk and web_risk_key)- citation_rows: list[tuple[Citation, str, str, str]] = []- result_rows: list[tuple[SearchResult, str, str, str]] = []+ citation_rows: list[list[Any]] = []+ result_rows: list[list[Any]] = []for citation in response.citations:reason, host = _rejection_reason(@@ -303,7 +383,7 @@ def filter_web_search_response(if not reason and moderation_activeelse "")- citation_rows.append((citation, reason, host, moderation_text))+ citation_rows.append([citation, reason, host, moderation_text])for result in response.search_results:reason, host = _rejection_reason(@@ -326,7 +406,7 @@ def filter_web_search_response(if not reason and moderation_activeelse "")- result_rows.append((result, reason, host, moderation_text))+ result_rows.append([result, reason, host, moderation_text])moderation_decisions = _moderation_rejections([row[3] for row in (*citation_rows, *result_rows) if row[3]],@@ -334,6 +414,20 @@ def filter_web_search_response(request_moderation=request_moderation,)+ for row in (*citation_rows, *result_rows):+ if not row[1] and moderation_decisions.get(row[3], False):+ row[1] = "moderation_flagged"++ web_risk_flagged: set[str] = set()+ if web_risk_active:+ # Only look up URLs that survived every earlier stage — moderation-+ # flagged or heuristic-rejected rows must not burn lookup quota.+ web_risk_flagged = _web_risk_rejections(+ [row[0].url for row in (*citation_rows, *result_rows) if not row[1]],+ api_key=web_risk_key,+ request_web_risk=request_web_risk,+ )+kept_citations: list[Citation] = []kept_results: list[SearchResult] = []removed_citations = 0@@ -348,18 +442,20 @@ def filter_web_search_response(if host and host not in rejected_hosts:rejected_hosts.append(host)- for citation, reason, host, moderation_text in citation_rows:- if not reason and moderation_decisions.get(moderation_text, False):- reason = "moderation_flagged"+ for row in citation_rows:+ citation, reason, host = row[0], row[1], row[2]+ if not reason and citation.url in web_risk_flagged:+ reason = "web_risk_threat"if reason:removed_citations += 1_record_reason(reason, host)else:kept_citations.append(citation)- for result, reason, host, moderation_text in result_rows:- if not reason and moderation_decisions.get(moderation_text, False):- reason = "moderation_flagged"+ for row in result_rows:+ result, reason, host = row[0], row[1], row[2]+ if not reason and result.url in web_risk_flagged:+ reason = "web_risk_threat"if reason:removed_results += 1_record_reason(reason, host)@@ -374,6 +470,7 @@ def filter_web_search_response("answer_invalidated": answer_invalidated,"content_filtering": content_filtering,"moderation_enabled": moderation_active,+ "web_risk_enabled": web_risk_active,"educational_trusted_domains": use_educational_trusted_domains,}@@ -391,6 +488,15 @@ def filter_web_search_response(answer_invalidated = Truepolicy_meta["answer_invalidated"] = True+ if removed_citations:+ # The prose citing the old labels is gone, so renumber the retained+ # citations to match the positional [i] markers the consolidator+ # writes when it rebuilds the answer from raw results.+ for index, citation in enumerate(kept_citations, 1):+ citation.id = index+ citation.reference = f"[{index}]"+ policy_meta["citations_renumbered"] = True+response.citations = kept_citationsresponse.search_results = kept_resultsresponse.metadata["source_filter"] = policy_meta@@ -406,12 +512,23 @@ def resolve_moderation_api_key() -> str:return ""+def resolve_web_risk_api_key() -> str:+ """Pick a Web Risk API key from the process environment."""+ for name in ("GOOGLE_WEB_RISK_API_KEY", "WEB_RISK_API_KEY"):+ value = str(os.environ.get(name) or "").strip()+ if value:+ return value+ return ""++def settings_from_config(config: Any) -> dict[str, Any]:"""Read the optional ``tools.web_search.source_filtering`` config section."""raw = config.get("source_filtering", {}) if isinstance(config, dict) else {}settings = raw if isinstance(raw, dict) else {}use_moderation = _as_bool(settings.get("use_moderation"), False)moderation_key = resolve_moderation_api_key()+ use_web_risk = _as_bool(settings.get("use_web_risk"), False)+ web_risk_key = resolve_web_risk_api_key()return {"enabled": _as_bool(settings.get("enabled"), True),"blocked_domains": _domains(settings.get("blocked_domains")),@@ -423,6 +540,8 @@ def settings_from_config(config: Any) -> dict[str, Any]:),"use_moderation": use_moderation,"moderation_api_key": moderation_key if use_moderation else "",+ "use_web_risk": use_web_risk,+ "web_risk_api_key": web_risk_key if use_web_risk else "",}@@ -430,5 +549,6 @@ __all__ = ["EDUCATIONAL_TRUSTED_DOMAINS","filter_web_search_response","resolve_moderation_api_key",+ "resolve_web_risk_api_key","settings_from_config",]diff --git a/tests/services/search/test_web_search_runtime.py b/tests/services/search/test_web_search_runtime.pyindex aceaa4e44..2cde4a061 100644--- a/tests/services/search/test_web_search_runtime.py+++ b/tests/services/search/test_web_search_runtime.py@@ -14,6 +14,16 @@ from deeptutor.services.search.source_filter import (from deeptutor.services.search.types import Citation, SearchResult, WebSearchResponse[email protected](autouse=True)+def _reset_web_risk_cache():+ """Keep the module-level Web Risk TTL cache from leaking between tests."""+ from deeptutor.services.search import source_filter++ source_filter._web_risk_cache.clear()+ yield+ source_filter._web_risk_cache.clear()++def _expected_source_filter(*,removed_citations: int = 0,@@ -23,7 +33,9 @@ def _expected_source_filter(answer_invalidated: bool = False,content_filtering: bool = True,moderation_enabled: bool = False,+ web_risk_enabled: bool = False,educational_trusted_domains: bool = False,+ citations_renumbered: bool = False,) -> dict:return {"removed_citations": removed_citations,@@ -33,7 +45,9 @@ def _expected_source_filter("answer_invalidated": answer_invalidated,"content_filtering": content_filtering,"moderation_enabled": moderation_enabled,+ "web_risk_enabled": web_risk_enabled,"educational_trusted_domains": educational_trusted_domains,+ **({"citations_renumbered": True} if citations_renumbered else {}),}@@ -292,7 +306,7 @@ def test_web_search_explicit_provider_uses_its_own_key(monkeypatch) -> None:assert captured["kwargs"]["api_key"] == "tavily-key"-def test_source_filter_removes_unsafe_references_and_preserves_ids() -> None:+def test_source_filter_removes_unsafe_references_and_renumbers_ids() -> None:response = WebSearchResponse(query="safe references",answer="",@@ -310,8 +324,8 @@ def test_source_filter_removes_unsafe_references_and_preserves_ids() -> None:filtered = filter_web_search_response(response)- assert [citation.id for citation in filtered.citations] == [2]- assert [citation.reference for citation in filtered.citations] == ["[2]"]+ assert [citation.id for citation in filtered.citations] == [1]+ assert [citation.reference for citation in filtered.citations] == ["[1]"]assert [result.title for result in filtered.search_results] == ["Safe"]assert filtered.metadata["source_filter"] == _expected_source_filter(removed_citations=2,@@ -322,6 +336,7 @@ def test_source_filter_removes_unsafe_references_and_preserves_ids() -> None:"embedded_credentials","unsupported_port",],+ citations_renumbered=True,)@@ -396,10 +411,11 @@ def test_web_search_filters_provider_results_before_consolidation(monkeypatch) -removed_search_results=1,rejected_hosts=["spam.example"],rejected_reasons=["blocked_domain"],+ citations_renumbered=True,)-def test_web_search_filters_answer_provider_citations_without_renumbering(monkeypatch) -> None:+def test_web_search_filters_answer_provider_citations_with_renumbering(monkeypatch) -> None:class _AnswerProvider(_FakeProvider):def __init__(self, name: str):super().__init__(name, supports_answer=True)@@ -445,9 +461,10 @@ def test_web_search_filters_answer_provider_citations_without_renumbering(monkeyassert "Unsafe claim" not in result["answer"]assert "School" in result["answer"]- assert [citation["reference"] for citation in result["citations"]] == ["[2]"]+ assert [citation["reference"] for citation in result["citations"]] == ["[1]"]assert result["source_filter"]["removed_citations"] == 1assert result["source_filter"]["answer_invalidated"] is True+ assert result["source_filter"]["citations_renumbered"] is Truedef test_source_filter_drops_unsafe_title_and_snippet_content() -> None:@@ -487,7 +504,8 @@ def test_source_filter_drops_unsafe_title_and_snippet_content() -> None:filtered = filter_web_search_response(response)- assert [c.id for c in filtered.citations] == [2]+ assert [c.id for c in filtered.citations] == [1]+ assert [c.reference for c in filtered.citations] == ["[1]"]assert [r.title for r in filtered.search_results] == ["Pythagorean theorem"]assert "unsafe_content" in filtered.metadata["source_filter"]["rejected_reasons"]assert filtered.metadata["source_filter"]["content_filtering"] is True@@ -592,7 +610,8 @@ def test_source_filter_optional_moderation_uses_injected_requester() -> None:request_moderation=_fake_moderation,)- assert [c.id for c in filtered.citations] == [2]+ assert [c.id for c in filtered.citations] == [1]+ assert [c.reference for c in filtered.citations] == ["[1]"]assert filtered.metadata["source_filter"]["moderation_enabled"] is Trueassert "moderation_flagged" in filtered.metadata["source_filter"]["rejected_reasons"]assert len(calls) == 1@@ -634,6 +653,8 @@ def test_source_filter_moderation_fails_open_on_errors() -> None:def test_settings_from_config_defaults_and_educational_flag(monkeypatch) -> None:monkeypatch.delenv("OPENAI_API_KEY", raising=False)monkeypatch.delenv("DEEPTUTOR_OPENAI_API_KEY", raising=False)+ monkeypatch.delenv("GOOGLE_WEB_RISK_API_KEY", raising=False)+ monkeypatch.delenv("WEB_RISK_API_KEY", raising=False)defaults = settings_from_config({})assert defaults["enabled"] is True@@ -641,12 +662,16 @@ def test_settings_from_config_defaults_and_educational_flag(monkeypatch) -> Noneassert defaults["use_educational_trusted_domains"] is Falseassert defaults["use_moderation"] is Falseassert defaults["moderation_api_key"] == ""+ assert defaults["use_web_risk"] is False+ assert defaults["web_risk_api_key"] == ""monkeypatch.setenv("OPENAI_API_KEY", "sk-from-env")+ monkeypatch.setenv("GOOGLE_WEB_RISK_API_KEY", "wr-from-env")enabled = settings_from_config({"source_filtering": {"use_moderation": True,+ "use_web_risk": True,"use_educational_trusted_domains": True,"content_filtering": False,}@@ -654,5 +679,162 @@ def test_settings_from_config_defaults_and_educational_flag(monkeypatch) -> None)assert enabled["use_moderation"] is Trueassert enabled["moderation_api_key"] == "sk-from-env"+ assert enabled["use_web_risk"] is True+ assert enabled["web_risk_api_key"] == "wr-from-env"assert enabled["use_educational_trusted_domains"] is Trueassert enabled["content_filtering"] is False+++def test_source_filter_optional_web_risk_uses_injected_requester() -> None:+ looked_up: list[str] = []++ def _fake_web_risk(url: str, *, api_key: str) -> bool:+ assert api_key == "wr-test"+ looked_up.append(url)+ return "scam.example" in url++ response = WebSearchResponse(+ query="homework",+ answer="",+ provider="test",+ citations=[+ Citation(id=1, reference="[1]", url="https://scam.example/gift"),+ Citation(id=2, reference="[2]", url="https://school.example/lesson"),+ Citation(id=3, reference="[3]", url="https://school.example/lesson"),+ ],+ search_results=[],+ )++ filtered = filter_web_search_response(+ response,+ content_filtering=False,+ use_web_risk=True,+ web_risk_api_key="wr-test",+ request_web_risk=_fake_web_risk,+ )++ # Duplicate URLs are deduplicated before hitting the lookup API.+ assert looked_up == ["https://scam.example/gift", "https://school.example/lesson"]+ assert [citation.id for citation in filtered.citations] == [1, 2]+ assert [citation.reference for citation in filtered.citations] == ["[1]", "[2]"]+ assert [citation.url for citation in filtered.citations] == [+ "https://school.example/lesson",+ "https://school.example/lesson",+ ]+ metadata = filtered.metadata["source_filter"]+ assert metadata["web_risk_enabled"] is True+ assert metadata["citations_renumbered"] is True+ assert metadata["rejected_reasons"] == ["web_risk_threat"]+ assert metadata["rejected_hosts"] == ["scam.example"]+++def test_source_filter_web_risk_fails_open_on_errors() -> None:+ def _boom(url: str, *, api_key: str) -> bool:+ raise RuntimeError("web risk down")++ response = WebSearchResponse(+ query="homework",+ answer="",+ provider="test",+ citations=[Citation(id=1, reference="[1]", url="https://school.example/lesson")],+ search_results=[],+ )++ filtered = filter_web_search_response(+ response,+ content_filtering=False,+ use_web_risk=True,+ web_risk_api_key="wr-test",+ request_web_risk=_boom,+ )++ assert len(filtered.citations) == 1+ assert filtered.metadata["source_filter"]["removed_citations"] == 0+ assert "citations_renumbered" not in filtered.metadata["source_filter"]+++def test_source_filter_web_risk_requires_key_and_skips_earlier_rejections() -> None:+ looked_up: list[str] = []++ def _fake_web_risk(url: str, *, api_key: str) -> bool:+ looked_up.append(url)+ return False++ response = WebSearchResponse(+ query="homework",+ answer="",+ provider="test",+ citations=[+ Citation(id=1, reference="[1]", url="https://spam.example/a"),+ Citation(id=2, reference="[2]", url="https://school.example/lesson"),+ ],+ search_results=[],+ )++ # No key configured: the stage stays off entirely.+ filtered = filter_web_search_response(+ response,+ content_filtering=False,+ use_web_risk=True,+ web_risk_api_key="",+ request_web_risk=_fake_web_risk,+ )+ assert len(filtered.citations) == 2+ assert filtered.metadata["source_filter"]["web_risk_enabled"] is False++ # Blocked-domain rows never reach the lookup.+ filtered = filter_web_search_response(+ response,+ content_filtering=False,+ blocked_domains=["spam.example"],+ use_web_risk=True,+ web_risk_api_key="wr-test",+ request_web_risk=_fake_web_risk,+ )+ assert [citation.url for citation in filtered.citations] == ["https://school.example/lesson"]+ assert filtered.metadata["source_filter"]["rejected_reasons"] == ["blocked_domain"]+ assert looked_up == ["https://school.example/lesson"]+++def test_source_filter_web_risk_caches_lookups() -> None:+ from deeptutor.services.search import source_filter++ source_filter._web_risk_cache.clear()+ calls: list[str] = []++ def _fake_web_risk(url: str, *, api_key: str) -> bool:+ calls.append(url)+ return False++ first = WebSearchResponse(+ query="q1",+ answer="",+ provider="test",+ citations=[Citation(id=1, reference="[1]", url="https://school.example/lesson")],+ search_results=[],+ )+ second = WebSearchResponse(+ query="q2",+ answer="",+ provider="test",+ citations=[Citation(id=1, reference="[1]", url="https://school.example/lesson")],+ search_results=[],+ )++ filter_web_search_response(+ first,+ content_filtering=False,+ use_web_risk=True,+ web_risk_api_key="wr-test",+ request_web_risk=_fake_web_risk,+ )+ filter_web_search_response(+ second,+ content_filtering=False,+ use_web_risk=True,+ web_risk_api_key="wr-test",+ request_web_risk=_fake_web_risk,+ )++ assert calls == ["https://school.example/lesson"]+ source_filter._web_risk_cache.clear()