DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(search): add reference safety filtering (#375)
XZH57f39ce18344
diff --git a/README.md b/README.mdindex e5f80e89c..8cf1d7fa2 100644--- a/README.md+++ b/README.md@@ -463,6 +463,22 @@ Everything under `data/user/settings/` is plain JSON/YAML. The **Settings** page| `main.yaml` | Runtime behavior defaults and path injection || `agents.yaml` | Capability/tool temperature and token settings |+Web Search references are filtered by default: only public `http`/`https` URLs+without embedded credentials or unusual ports are surfaced. Deployments can add+an education-focused domain policy under `tools.web_search.source_filtering` in+`main.yaml`:++```yaml+tools:+ web_search:+ source_filtering:+ blocked_domains: [spam.example]+ trusted_domains: [edu.cn, arxiv.org]+```++When `trusted_domains` is non-empty, references are limited to those domains+and their subdomains; `blocked_domains` always takes precedence.+Project-root `.env` is **not** read as an application config file. For a minimal model setup, open **Settings → Models**, add an LLM profile (Base URL / API key / model name), and save. Add an embedding profile only if you plan to use Knowledge Base / RAG features.</details>diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.pyindex 4b6b012cf..cab938edf 100644--- a/deeptutor/services/search/__init__.py+++ b/deeptutor/services/search/__init__.py@@ -33,6 +33,7 @@ from .providers import (get_providers_info,list_providers,)+from .source_filter import filter_web_search_response, settings_from_configfrom .types import Citation, SearchResult, WebSearchResponse_logger = logging.getLogger(__name__)@@ -192,6 +193,8 @@ def web_search(if response is None:raise Exception("web search failed: " + "; ".join(failures))+ response = filter_web_search_response(response, **settings_from_config(config))+# Auto-consolidate for providers that don't generate their own answers.if not supports_answer:if consolidation_custom_template is None:@@ -236,6 +239,7 @@ def get_current_config() -> dict[str, Any]:"supported_providers": sorted(SUPPORTED_SEARCH_PROVIDERS),"deprecated_providers": sorted(DEPRECATED_SEARCH_PROVIDERS),"consolidation_template": config.get("consolidation_template") or None,+ "source_filtering": settings_from_config(config),"template_providers": list(PROVIDER_TEMPLATES.keys()),}@@ -254,6 +258,7 @@ __all__ = ["Citation","SearchResult","AnswerConsolidator",+ "filter_web_search_response","PROVIDER_TEMPLATES","BaseSearchProvider","SearchProvider",diff --git a/deeptutor/services/search/source_filter.py b/deeptutor/services/search/source_filter.pynew file mode 100644index 000000000..993074aed--- /dev/null+++ b/deeptutor/services/search/source_filter.py@@ -0,0 +1,178 @@+"""Reference safety filtering shared by every web-search provider."""++from __future__ import annotations++import ipaddress+from typing import Any+from urllib.parse import urlparse++from .types import Citation, SearchResult, WebSearchResponse++_ALLOWED_PORTS = frozenset({80, 443})+_PRIVATE_HOST_SUFFIXES = (".local", ".internal", ".lan", ".home.arpa")+++def _as_bool(value: Any, default: bool = False) -> bool:+ if value is None:+ return default+ if isinstance(value, str):+ return value.strip().lower() not in {"false", "0", "no", "off", ""}+ return bool(value)+++def _domains(value: Any) -> tuple[str, ...]:+ """Normalize a YAML domain list into lowercase registry-compatible hosts."""+ if isinstance(value, str):+ rows = value.replace(",", " ").split()+ elif isinstance(value, (list, tuple)):+ rows = value+ else:+ return ()++ normalized: list[str] = []+ for row in rows:+ raw = str(row or "").strip().lower().rstrip(".")+ if raw.startswith("*."):+ raw = raw[1:]+ if not raw:+ continue+ try:+ host = raw.encode("idna").decode("ascii").lstrip(".").rstrip(".")+ except UnicodeError:+ host = raw.lstrip(".").rstrip(".")+ if host and host not in normalized:+ normalized.append(host)+ return tuple(normalized)+++def _matches_domain(host: str, patterns: tuple[str, ...]) -> bool:+ return any(host == pattern or host.endswith(f".{pattern}") for pattern in patterns)+++def _rejection_reason(+ url: str,+ *,+ blocked_domains: tuple[str, ...],+ trusted_domains: tuple[str, ...],+) -> tuple[str, str]:+ """Return ``(reason, host)`` for a reference URL that must not be surfaced."""+ candidate = str(url or "").strip()+ if not candidate:+ return "missing_url", ""+ if any(character.isspace() or ord(character) < 0x20 for character in candidate):+ return "malformed_url", ""++ try:+ parsed = urlparse(candidate)+ port = parsed.port+ except ValueError:+ return "malformed_url", ""++ if parsed.scheme.lower() not in {"http", "https"}:+ return "unsupported_scheme", ""+ if not parsed.hostname:+ return "missing_hostname", ""++ try:+ host = parsed.hostname.encode("idna").decode("ascii").lower().rstrip(".")+ except UnicodeError:+ return "malformed_hostname", ""++ if parsed.username is not None or parsed.password is not None:+ return "embedded_credentials", host+ if port is not None and port not in _ALLOWED_PORTS:+ return "unsupported_port", host++ try:+ address = ipaddress.ip_address(host)+ except ValueError:+ address = None+ if address is not None and not address.is_global:+ return "non_public_address", host+ if address is None and (+ host == "localhost" or not host or "." not in host or host.endswith(_PRIVATE_HOST_SUFFIXES)+ ):+ return "non_public_hostname", host++ if _matches_domain(host, blocked_domains):+ return "blocked_domain", host+ if trusted_domains and not _matches_domain(host, trusted_domains):+ return "untrusted_domain", host+ return "", host+++def filter_web_search_response(+ response: WebSearchResponse,+ *,+ enabled: bool = True,+ blocked_domains: Any = None,+ trusted_domains: Any = 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.+ """+ if not enabled:+ return response++ blocked = _domains(blocked_domains)+ trusted = _domains(trusted_domains)+ kept_citations: list[Citation] = []+ kept_results: list[SearchResult] = []+ removed_citations = 0+ removed_results = 0+ rejected_hosts: list[str] = []++ for citation in response.citations:+ reason, host = _rejection_reason(+ citation.url,+ blocked_domains=blocked,+ trusted_domains=trusted,+ )+ if reason:+ removed_citations += 1+ if host and host not in rejected_hosts:+ rejected_hosts.append(host)+ else:+ kept_citations.append(citation)++ for result in response.search_results:+ reason, host = _rejection_reason(+ result.url,+ blocked_domains=blocked,+ trusted_domains=trusted,+ )+ if reason:+ removed_results += 1+ if host and host not in rejected_hosts:+ rejected_hosts.append(host)+ else:+ kept_results.append(result)++ if not removed_citations and not removed_results:+ return response++ response.citations = kept_citations+ response.search_results = kept_results+ response.metadata["source_filter"] = {+ "removed_citations": removed_citations,+ "removed_search_results": removed_results,+ "rejected_hosts": rejected_hosts,+ }+ return response+++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 {}+ return {+ "enabled": _as_bool(settings.get("enabled"), True),+ "blocked_domains": _domains(settings.get("blocked_domains")),+ "trusted_domains": _domains(settings.get("trusted_domains")),+ }+++__all__ = ["filter_web_search_response", "settings_from_config"]diff --git a/tests/services/search/test_web_search_runtime.py b/tests/services/search/test_web_search_runtime.pyindex a034cbb80..8f5333bd2 100644--- a/tests/services/search/test_web_search_runtime.py+++ b/tests/services/search/test_web_search_runtime.py@@ -6,7 +6,8 @@ import pytestfrom deeptutor.services.config.provider_runtime import ResolvedSearchConfigfrom deeptutor.services.search import web_search-from deeptutor.services.search.types import WebSearchResponse+from deeptutor.services.search.source_filter import filter_web_search_response+from deeptutor.services.search.types import Citation, SearchResult, WebSearchResponseclass _FakeProvider:@@ -29,11 +30,13 @@ class _FailingProvider(_FakeProvider):raise RuntimeError("202 Ratelimit")-def _patch_runtime(monkeypatch, resolved: ResolvedSearchConfig, **kwargs) -> None:+def _patch_runtime(+ monkeypatch, resolved: ResolvedSearchConfig, *, config: dict | None = None, **kwargs+) -> None:"""Pin the resolved config and keep the fallback chain off the real catalog."""monkeypatch.setattr("deeptutor.services.search._get_web_search_config",- lambda: {"enabled": True},+ lambda: {"enabled": True, **(config or {})},)monkeypatch.setattr("deeptutor.services.search.resolve_search_runtime_config",@@ -204,3 +207,146 @@ def test_web_search_explicit_provider_uses_its_own_key(monkeypatch) -> None:web_search("hello", provider="tavily")assert captured["provider"] == "tavily"assert captured["kwargs"]["api_key"] == "tavily-key"+++def test_source_filter_removes_unsafe_references_and_preserves_ids() -> None:+ response = WebSearchResponse(+ query="safe references",+ answer="",+ provider="test",+ citations=[+ Citation(id=1, reference="[1]", url="javascript:alert(1)"),+ Citation(id=2, reference="[2]", url="https://school.example/a"),+ Citation(id=3, reference="[3]", url="https://user:[email protected]/a"),+ ],+ search_results=[+ SearchResult(title="Safe", url="https://school.example/a", snippet="ok"),+ SearchResult(title="Internal", url="http://127.0.0.1:8000/admin", snippet="no"),+ ],+ )++ 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 [result.title for result in filtered.search_results] == ["Safe"]+ assert filtered.metadata["source_filter"] == {+ "removed_citations": 2,+ "removed_search_results": 1,+ "rejected_hosts": ["example.com", "127.0.0.1"],+ }+++def test_source_filter_supports_blocked_and_trusted_domain_policies() -> None:+ response = WebSearchResponse(+ query="education",+ answer="",+ provider="test",+ citations=[+ Citation(id=1, reference="[1]", url="https://spam.example/a"),+ Citation(id=2, reference="[2]", url="https://lesson.trusted.edu/a"),+ Citation(id=3, reference="[3]", url="https://other.example/a"),+ ],+ search_results=[],+ )++ filtered = filter_web_search_response(+ response,+ blocked_domains=["spam.example"],+ trusted_domains=["trusted.edu"],+ )++ assert [citation.url for citation in filtered.citations] == ["https://lesson.trusted.edu/a"]+ assert filtered.metadata["source_filter"]["rejected_hosts"] == [+ "spam.example",+ "other.example",+ ]+++def test_web_search_filters_provider_results_before_consolidation(monkeypatch) -> None:+ class _UnsafeProvider(_FakeProvider):+ def search(self, query: str, **kwargs):+ return WebSearchResponse(+ query=query,+ answer="",+ provider=self.name,+ citations=[+ Citation(id=1, reference="[1]", url="https://spam.example/a"),+ Citation(id=2, reference="[2]", url="https://school.example/a"),+ ],+ search_results=[+ SearchResult(title="Spam", url="https://spam.example/a", snippet="bad"),+ SearchResult(title="School", url="https://school.example/a", snippet="good"),+ ],+ )++ _patch_runtime(+ monkeypatch,+ ResolvedSearchConfig(+ provider="brave",+ requested_provider="brave",+ api_key="brave-key",+ max_results=5,+ ),+ config={+ "enabled": True,+ "source_filtering": {"blocked_domains": ["spam.example"]},+ },+ )+ monkeypatch.setattr(+ "deeptutor.services.search.get_provider",+ lambda name, **kwargs: _UnsafeProvider(name),+ )++ result = web_search("education")++ assert "spam.example" not in result["answer"]+ assert "**[1] School**" in result["answer"]+ assert [row["url"] for row in result["search_results"]] == ["https://school.example/a"]+ assert result["source_filter"] == {+ "removed_citations": 1,+ "removed_search_results": 1,+ "rejected_hosts": ["spam.example"],+ }+++def test_web_search_filters_answer_provider_citations_without_renumbering(monkeypatch) -> None:+ class _AnswerProvider(_FakeProvider):+ def __init__(self, name: str):+ super().__init__(name, supports_answer=True)++ def search(self, query: str, **kwargs):+ return WebSearchResponse(+ query=query,+ answer="Lesson [2]",+ provider=self.name,+ citations=[+ Citation(id=1, reference="[1]", url="https://spam.example/a"),+ Citation(id=2, reference="[2]", url="https://school.example/a"),+ ],+ search_results=[],+ )++ _patch_runtime(+ monkeypatch,+ ResolvedSearchConfig(+ provider="brave",+ requested_provider="brave",+ api_key="brave-key",+ max_results=5,+ ),+ config={+ "enabled": True,+ "source_filtering": {"blocked_domains": ["spam.example"]},+ },+ )+ monkeypatch.setattr(+ "deeptutor.services.search.get_provider",+ lambda name, **kwargs: _AnswerProvider(name),+ )++ result = web_search("education")++ assert result["answer"] == "Lesson [2]"+ assert [citation["reference"] for citation in result["citations"]] == ["[2]"]+ assert result["source_filter"]["removed_citations"] == 1