DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(search): filter unsafe web-search titles and snippets (#1205)
ZQR11015e47f0d3def9
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.pyindex 5470d0991..f6e52f2db 100644--- a/deeptutor/services/config/runtime_settings.py+++ b/deeptutor/services/config/runtime_settings.py@@ -45,6 +45,9 @@ DEFAULT_SYSTEM_SETTINGS: dict[str, Any] = {"enabled": True,"blocked_domains": [],"trusted_domains": [],+ "content_filtering": True,+ "use_educational_trusted_domains": False,+ "use_moderation": False,},# Chat attachment policy. Size caps gate what the composer accepts and# what the turn runtime / partner upload endpoints extract; the char@@ -1164,6 +1167,11 @@ class RuntimeSettingsService:"enabled": _coerce_bool(source_filter.get("enabled"), True),"blocked_domains": _string_or_list(source_filter.get("blocked_domains")),"trusted_domains": _string_or_list(source_filter.get("trusted_domains")),+ "content_filtering": _coerce_bool(source_filter.get("content_filtering"), True),+ "use_educational_trusted_domains": _coerce_bool(+ source_filter.get("use_educational_trusted_domains"), False+ ),+ "use_moderation": _coerce_bool(source_filter.get("use_moderation"), False),},"chat_attachment_max_file_mb": max_file_mb,"chat_attachment_max_total_mb": max_total_mb,diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.pyindex cec76d14a..1fe054a20 100644--- a/deeptutor/services/search/__init__.py+++ b/deeptutor/services/search/__init__.py@@ -263,6 +263,10 @@ def get_current_config() -> dict[str, Any]:"""Get effective web search configuration for UI/CLI display."""config = _get_web_search_config()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).+ source_filtering["moderation_configured"] = bool(source_filtering.pop("moderation_api_key", ""))return {"enabled": config.get("enabled", True),"provider": resolved.provider,@@ -277,7 +281,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": _get_source_filter_settings(),+ "source_filtering": source_filtering,"template_providers": list(PROVIDER_TEMPLATES.keys()),}diff --git a/deeptutor/services/search/source_filter.py b/deeptutor/services/search/source_filter.pyindex fe0667286..bfb85ccdf 100644--- a/deeptutor/services/search/source_filter.py+++ b/deeptutor/services/search/source_filter.py@@ -3,14 +3,79 @@from __future__ import annotationsimport ipaddress+import json+import logging+import os+import refrom typing import Anyfrom urllib.parse import urlparse+import urllib.requestfrom .types import Citation, SearchResult, WebSearchResponse+_logger = logging.getLogger(__name__)+_ALLOWED_PORTS = frozenset({80, 443})_PRIVATE_HOST_SUFFIXES = (".local", ".internal", ".lan", ".home.arpa")+# Opt-in educational allowlist (#375). Enabled only when+# ``use_educational_trusted_domains`` is true — never silently replaces an+# empty trusted list.+EDUCATIONAL_TRUSTED_DOMAINS: tuple[str, ...] = (+ "wikipedia.org",+ "wikimedia.org",+ "khanacademy.org",+ "britannica.com",+ "arxiv.org",+ "nih.gov",+ "nasa.gov",+ "edu",+ "ac.uk",+ "gov",+ "scholastic.com",+ "coursera.org",+ "edx.org",+ "mit.edu",+ "stanford.edu",+ "harvard.edu",+ "ox.ac.uk",+ "cam.ac.uk",+)++# Title / snippet / URL-path heuristics. Prefer strong tokens over soft words+# that collide with educational topics (e.g. bare "sex" in sex education).+_UNSAFE_CONTENT_PATTERNS: tuple[re.Pattern[str], ...] = tuple(+ re.compile(pattern, re.IGNORECASE)+ for pattern in (+ r"\bporn(?:ography|ographic|hub|tube|o)?\b",+ r"\bxnxx\b",+ r"\bxvideos?\b",+ r"\bonlyfans\b",+ r"\bnsfw\b",+ r"\bxxx\b",+ r"\berotic(?:a)?\b",+ r"\bcamgirl(?:s)?\b",+ r"\bescor(?:t|ts)\b",+ r"\bonline\s+casino\b",+ r"\bgambling\b",+ r"\bbetting\s+odds\b",+ r"\bslot\s+machines?\b",+ r"\bdrug\s+marketplace\b",+ r"\bbuy\s+(?:weed|cocaine|fentanyl)\b",+ )+)++_UNSAFE_URL_PATH_PATTERNS: tuple[re.Pattern[str], ...] = tuple(+ re.compile(pattern, re.IGNORECASE)+ for pattern in (+ r"/(?:porn|xxx|sexcam|escort|casino|gambling)(?:/|$)",+ r"\.(?:xxx)(?:/|$)",+ )+)++_MODERATION_URL = "https://api.openai.com/v1/moderations"+_MODERATION_TIMEOUT_S = 8.0+def _as_bool(value: Any, default: bool = False) -> bool:if value is None:@@ -46,6 +111,15 @@ def _domains(value: Any) -> tuple[str, ...]:return tuple(normalized)+def _merge_domains(*groups: tuple[str, ...]) -> tuple[str, ...]:+ merged: list[str] = []+ for group in groups:+ for host in group:+ if host and host not in merged:+ merged.append(host)+ return tuple(merged)++def _matches_domain(host: str, patterns: tuple[str, ...]) -> bool:return any(host == pattern or host.endswith(f".{pattern}") for pattern in patterns)@@ -102,30 +176,111 @@ def _rejection_reason(return "", host+def _content_rejection_reason(*, title: str, snippet: str, url: str) -> str:+ """Heuristic title/snippet/path check for clearly non-educational material."""+ haystack = f"{title}\n{snippet}".strip()+ if haystack:+ for pattern in _UNSAFE_CONTENT_PATTERNS:+ if pattern.search(haystack):+ return "unsafe_content"+ path = ""+ try:+ path = urlparse(str(url or "")).path or ""+ except ValueError:+ path = str(url or "")+ combined = f"{path}\n{url}"+ for pattern in _UNSAFE_URL_PATH_PATTERNS:+ if pattern.search(combined):+ return "unsafe_content"+ return ""+++def _moderation_rejections(+ texts: list[str],+ *,+ api_key: str,+ request_moderation: Any | None = None,+) -> dict[str, bool]:+ """Return batched Moderation decisions keyed by the submitted text.++ Fail open on transport/API errors so a Moderation outage does not blank+ every web-search turn — heuristics already ran.+ """+ payloads = list(dict.fromkeys(text.strip()[:4000] for text in texts if text.strip()))+ if not payloads or not api_key:+ return {}+ requester = request_moderation or _request_openai_moderation+ try:+ flagged = requester(payloads, api_key=api_key)+ if not isinstance(flagged, (list, tuple)) or len(flagged) != len(payloads):+ raise ValueError("Moderation returned an unexpected result count")+ except Exception as exc: # noqa: BLE001 — network / JSON / provider quirks+ _logger.warning("OpenAI Moderation skipped after error: %s", exc)+ return {}+ return {text: bool(decision) for text, decision in zip(payloads, flagged, strict=True)}+++def _request_openai_moderation(texts: list[str], *, api_key: str) -> list[bool]:+ body = json.dumps({"input": texts}).encode("utf-8")+ request = urllib.request.Request(+ _MODERATION_URL,+ data=body,+ headers={+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json",+ "User-Agent": "DeepTutor-source-filter/1.0",+ },+ method="POST",+ )+ with urllib.request.urlopen(request, timeout=_MODERATION_TIMEOUT_S) as response:+ raw = json.loads(response.read().decode("utf-8"))+ results = raw.get("results") if isinstance(raw, dict) else None+ if not isinstance(results, list) or len(results) != len(texts):+ raise ValueError("Moderation returned an unexpected result count")+ return [bool(isinstance(result, dict) and result.get("flagged")) for result in results]+++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)++def filter_web_search_response(response: WebSearchResponse,*,enabled: bool = True,blocked_domains: Any = None,trusted_domains: Any = None,+ content_filtering: bool = True,+ use_educational_trusted_domains: bool = False,+ use_moderation: bool = False,+ moderation_api_key: str | None = None,+ request_moderation: 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 herewould turn a harmless gap into incorrect citations.++ 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"""if not enabled:return responseblocked = _domains(blocked_domains)trusted = _domains(trusted_domains)- kept_citations: list[Citation] = []- kept_results: list[SearchResult] = []- removed_citations = 0- removed_results = 0- answer_invalidated = False- rejected_hosts: list[str] = []+ if use_educational_trusted_domains:+ trusted = _merge_domains(trusted, EDUCATIONAL_TRUSTED_DOMAINS)++ moderation_key = str(moderation_api_key or "").strip()+ moderation_active = bool(use_moderation and moderation_key)++ citation_rows: list[tuple[Citation, str, str, str]] = []+ result_rows: list[tuple[SearchResult, str, str, str]] = []for citation in response.citations:reason, host = _rejection_reason(@@ -133,12 +288,22 @@ def filter_web_search_response(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)+ if not reason and content_filtering:+ reason = _content_rejection_reason(+ title=citation.title,+ snippet="\n".join(part for part in (citation.snippet, citation.content) if part),+ url=citation.url,+ )+ moderation_text = (+ _reference_text(+ title=citation.title,+ snippet=citation.snippet,+ content=citation.content,+ )[:4000]+ if not reason and moderation_active+ else ""+ )+ citation_rows.append((citation, reason, host, moderation_text))for result in response.search_results:reason, host = _rejection_reason(@@ -146,14 +311,75 @@ def filter_web_search_response(blocked_domains=blocked,trusted_domains=trusted,)+ if not reason and content_filtering:+ reason = _content_rejection_reason(+ title=result.title,+ snippet="\n".join(part for part in (result.snippet, result.content) if part),+ url=result.url,+ )+ moderation_text = (+ _reference_text(+ title=result.title,+ snippet=result.snippet,+ content=result.content,+ )[:4000]+ if not reason and moderation_active+ else ""+ )+ result_rows.append((result, reason, host, moderation_text))++ moderation_decisions = _moderation_rejections(+ [row[3] for row in (*citation_rows, *result_rows) if row[3]],+ api_key=moderation_key,+ request_moderation=request_moderation,+ )++ kept_citations: list[Citation] = []+ kept_results: list[SearchResult] = []+ removed_citations = 0+ removed_results = 0+ answer_invalidated = False+ rejected_hosts: list[str] = []+ rejected_reasons: list[str] = []++ def _record_reason(reason: str, host: str = "") -> None:+ if reason and reason not in rejected_reasons:+ rejected_reasons.append(reason)+ 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"+ 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"if reason:removed_results += 1- if host and host not in rejected_hosts:- rejected_hosts.append(host)+ _record_reason(reason, host)else:kept_results.append(result)+ policy_meta = {+ "removed_citations": removed_citations,+ "removed_search_results": removed_results,+ "rejected_hosts": rejected_hosts,+ "rejected_reasons": rejected_reasons,+ "answer_invalidated": answer_invalidated,+ "content_filtering": content_filtering,+ "moderation_enabled": moderation_active,+ "educational_trusted_domains": use_educational_trusted_domains,+ }+if not removed_citations and not removed_results:+ # Still record policy flags so callers / Settings can introspect.+ response.metadata["source_filter"] = policy_metareturn responseif removed_citations and response.answer.strip():@@ -163,27 +389,46 @@ def filter_web_search_response(# the retained raw results.response.answer = ""answer_invalidated = True+ policy_meta["answer_invalidated"] = Trueresponse.citations = kept_citationsresponse.search_results = kept_results- response.metadata["source_filter"] = {- "removed_citations": removed_citations,- "removed_search_results": removed_results,- "rejected_hosts": rejected_hosts,- "answer_invalidated": answer_invalidated,- }+ response.metadata["source_filter"] = policy_metareturn response+def resolve_moderation_api_key() -> str:+ """Pick a Moderation bearer token from the process environment."""+ for name in ("OPENAI_API_KEY", "DEEPTUTOR_OPENAI_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()return {"enabled": _as_bool(settings.get("enabled"), True),"blocked_domains": _domains(settings.get("blocked_domains")),"trusted_domains": _domains(settings.get("trusted_domains")),+ "content_filtering": _as_bool(settings.get("content_filtering"), True),+ "use_educational_trusted_domains": _as_bool(+ settings.get("use_educational_trusted_domains"),+ False,+ ),+ "use_moderation": use_moderation,+ "moderation_api_key": moderation_key if use_moderation else "",}-__all__ = ["filter_web_search_response", "settings_from_config"]+__all__ = [+ "EDUCATIONAL_TRUSTED_DOMAINS",+ "filter_web_search_response",+ "resolve_moderation_api_key",+ "settings_from_config",+]diff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.pyindex 4760f57ed..1be4f9de4 100644--- a/tests/services/config/test_runtime_settings.py+++ b/tests/services/config/test_runtime_settings.py@@ -73,6 +73,30 @@ def test_web_search_source_filter_defaults_to_safe_runtime_json(tmp_path) -> Non"enabled": True,"blocked_domains": [],"trusted_domains": [],+ "content_filtering": True,+ "use_educational_trusted_domains": False,+ "use_moderation": False,+ }++ service.save_system(+ {+ "web_search_source_filtering": {+ "enabled": True,+ "blocked_domains": ["unsafe.example"],+ "trusted_domains": [],+ "content_filtering": False,+ "use_educational_trusted_domains": True,+ "use_moderation": True,+ }+ }+ )+ assert service.load_system()["web_search_source_filtering"] == {+ "enabled": True,+ "blocked_domains": ["unsafe.example"],+ "trusted_domains": [],+ "content_filtering": False,+ "use_educational_trusted_domains": True,+ "use_moderation": True,}diff --git a/tests/services/search/test_web_search_runtime.py b/tests/services/search/test_web_search_runtime.pyindex 88ce50cd2..aceaa4e44 100644--- a/tests/services/search/test_web_search_runtime.py+++ b/tests/services/search/test_web_search_runtime.py@@ -6,10 +6,37 @@ import pytestfrom deeptutor.services.config.provider_runtime import ResolvedSearchConfigfrom deeptutor.services.search import web_search-from deeptutor.services.search.source_filter import filter_web_search_response+from deeptutor.services.search.source_filter import (+ EDUCATIONAL_TRUSTED_DOMAINS,+ filter_web_search_response,+ settings_from_config,+)from deeptutor.services.search.types import Citation, SearchResult, WebSearchResponse+def _expected_source_filter(+ *,+ removed_citations: int = 0,+ removed_search_results: int = 0,+ rejected_hosts: list[str] | None = None,+ rejected_reasons: list[str] | None = None,+ answer_invalidated: bool = False,+ content_filtering: bool = True,+ moderation_enabled: bool = False,+ educational_trusted_domains: bool = False,+) -> dict:+ return {+ "removed_citations": removed_citations,+ "removed_search_results": removed_search_results,+ "rejected_hosts": rejected_hosts or [],+ "rejected_reasons": rejected_reasons or [],+ "answer_invalidated": answer_invalidated,+ "content_filtering": content_filtering,+ "moderation_enabled": moderation_enabled,+ "educational_trusted_domains": educational_trusted_domains,+ }++class _FakeProvider:def __init__(self, name: str, supports_answer: bool = False):self.name = name@@ -286,12 +313,16 @@ def test_source_filter_removes_unsafe_references_and_preserves_ids() -> None: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"],- "answer_invalidated": False,- }+ assert filtered.metadata["source_filter"] == _expected_source_filter(+ removed_citations=2,+ removed_search_results=1,+ rejected_hosts=["example.com", "127.0.0.1"],+ rejected_reasons=[+ "unsupported_scheme",+ "embedded_credentials",+ "unsupported_port",+ ],+ )def test_source_filter_supports_blocked_and_trusted_domain_policies() -> None:@@ -360,12 +391,12 @@ def test_web_search_filters_provider_results_before_consolidation(monkeypatch) -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"],- "answer_invalidated": False,- }+ assert result["source_filter"] == _expected_source_filter(+ removed_citations=1,+ removed_search_results=1,+ rejected_hosts=["spam.example"],+ rejected_reasons=["blocked_domain"],+ )def test_web_search_filters_answer_provider_citations_without_renumbering(monkeypatch) -> None:@@ -417,3 +448,211 @@ def test_web_search_filters_answer_provider_citations_without_renumbering(monkeyassert [citation["reference"] for citation in result["citations"]] == ["[2]"]assert result["source_filter"]["removed_citations"] == 1assert result["source_filter"]["answer_invalidated"] is True+++def test_source_filter_drops_unsafe_title_and_snippet_content() -> None:+ response = WebSearchResponse(+ query="math",+ answer="",+ provider="test",+ citations=[+ Citation(+ id=1,+ reference="[1]",+ url="https://lesson.example/algebra",+ title="Free porn tube clips",+ snippet="watch now",+ ),+ Citation(+ id=2,+ reference="[2]",+ url="https://lesson.example/geometry",+ title="Triangle congruence",+ snippet="SAS and ASA",+ ),+ ],+ search_results=[+ SearchResult(+ title="Online casino jackpots",+ url="https://lesson.example/casino",+ snippet="spin the wheel",+ ),+ SearchResult(+ title="Pythagorean theorem",+ url="https://lesson.example/pythagoras",+ snippet="a^2 + b^2 = c^2",+ ),+ ],+ )++ filtered = filter_web_search_response(response)++ assert [c.id for c in filtered.citations] == [2]+ 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+++def test_source_filter_content_filtering_can_be_disabled() -> None:+ response = WebSearchResponse(+ query="math",+ answer="",+ provider="test",+ citations=[+ Citation(+ id=1,+ reference="[1]",+ url="https://lesson.example/a",+ title="Free porn tube clips",+ snippet="nsfw",+ ),+ ],+ search_results=[],+ )++ filtered = filter_web_search_response(response, content_filtering=False)++ assert len(filtered.citations) == 1+ assert filtered.metadata["source_filter"]["content_filtering"] is False+ assert filtered.metadata["source_filter"]["removed_citations"] == 0+++def test_source_filter_educational_trusted_domains_are_opt_in() -> None:+ response = WebSearchResponse(+ query="history",+ answer="",+ provider="test",+ citations=[+ Citation(id=1, reference="[1]", url="https://en.wikipedia.org/wiki/Gravity"),+ Citation(id=2, reference="[2]", url="https://random.blog.example/post"),+ ],+ search_results=[],+ )++ # Without the educational preset, an empty trusted list means no allowlist.+ open_policy = filter_web_search_response(response)+ assert len(open_policy.citations) == 2+ assert open_policy.metadata["source_filter"]["educational_trusted_domains"] is False++ locked = filter_web_search_response(+ WebSearchResponse(+ query="history",+ answer="",+ provider="test",+ citations=[+ Citation(id=1, reference="[1]", url="https://en.wikipedia.org/wiki/Gravity"),+ Citation(id=2, reference="[2]", url="https://random.blog.example/post"),+ ],+ search_results=[],+ ),+ use_educational_trusted_domains=True,+ )+ assert [c.url for c in locked.citations] == ["https://en.wikipedia.org/wiki/Gravity"]+ assert locked.metadata["source_filter"]["educational_trusted_domains"] is True+ assert "untrusted_domain" in locked.metadata["source_filter"]["rejected_reasons"]+ assert "wikipedia.org" in EDUCATIONAL_TRUSTED_DOMAINS+++def test_source_filter_optional_moderation_uses_injected_requester() -> None:+ calls: list[list[str]] = []++ def _fake_moderation(texts: list[str], *, api_key: str) -> list[bool]:+ assert api_key == "sk-test"+ calls.append(texts)+ return ["flag this" in text.lower() for text in texts]++ response = WebSearchResponse(+ query="news",+ answer="",+ provider="test",+ citations=[+ Citation(+ id=1,+ reference="[1]",+ url="https://news.example/a",+ title="Ordinary headline",+ snippet="flag this please",+ ),+ Citation(+ id=2,+ reference="[2]",+ url="https://news.example/b",+ title="Keep me",+ snippet="classroom notes",+ ),+ ],+ search_results=[],+ )++ filtered = filter_web_search_response(+ response,+ content_filtering=False,+ use_moderation=True,+ moderation_api_key="sk-test",+ request_moderation=_fake_moderation,+ )++ assert [c.id for c in filtered.citations] == [2]+ assert filtered.metadata["source_filter"]["moderation_enabled"] is True+ assert "moderation_flagged" in filtered.metadata["source_filter"]["rejected_reasons"]+ assert len(calls) == 1+ assert len(calls[0]) == 2+++def test_source_filter_moderation_fails_open_on_errors() -> None:+ def _boom(texts: list[str], *, api_key: str) -> list[bool]:+ raise RuntimeError("moderation down")++ response = WebSearchResponse(+ query="news",+ answer="",+ provider="test",+ citations=[+ Citation(+ id=1,+ reference="[1]",+ url="https://news.example/a",+ title="Keep me",+ snippet="classroom notes",+ ),+ ],+ search_results=[],+ )++ filtered = filter_web_search_response(+ response,+ content_filtering=False,+ use_moderation=True,+ moderation_api_key="sk-test",+ request_moderation=_boom,+ )++ assert len(filtered.citations) == 1+ assert filtered.metadata["source_filter"]["removed_citations"] == 0+++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)++ defaults = settings_from_config({})+ assert defaults["enabled"] is True+ assert defaults["content_filtering"] is True+ assert defaults["use_educational_trusted_domains"] is False+ assert defaults["use_moderation"] is False+ assert defaults["moderation_api_key"] == ""++ monkeypatch.setenv("OPENAI_API_KEY", "sk-from-env")+ enabled = settings_from_config(+ {+ "source_filtering": {+ "use_moderation": True,+ "use_educational_trusted_domains": True,+ "content_filtering": False,+ }+ }+ )+ assert enabled["use_moderation"] is True+ assert enabled["moderation_api_key"] == "sk-from-env"+ assert enabled["use_educational_trusted_domains"] is True+ assert enabled["content_filtering"] is False