From 4010a33aa3ce046d23ec6247079d2edb66f495c4 Mon Sep 17 00:00:00 2001 From: "Bingxi Zhao (Frank)" <13051345080@163.com> Date: Sat, 11 Apr 2026 12:54:38 +0800 Subject: [PATCH] fix: simplify search consolidation and use explicit runtime config in test runner - Remove CONSOLIDATION_TYPES and explicit consolidation parameter; auto-consolidate for providers without native answer support. - Build LLM/Embedding/Search configs directly from resolved runtime config in ConfigTestRunner instead of relying on global cache. - Clean up default settings by removing unused consolidation fields. Made-with: Cursor --- deeptutor/services/config/test_runner.py | 59 ++++++++++--- deeptutor/services/search/__init__.py | 32 ++++---- deeptutor/services/search/consolidation.py | 96 +++++----------------- deeptutor/services/setup/init.py | 2 - deeptutor/tools/web_search.py | 2 - 5 files changed, 81 insertions(+), 110 deletions(-) diff --git a/deeptutor/services/config/test_runner.py b/deeptutor/services/config/test_runner.py index 2b5d8546b..164165077 100644 --- a/deeptutor/services/config/test_runner.py +++ b/deeptutor/services/config/test_runner.py @@ -13,7 +13,11 @@ from uuid import uuid4 from .env_store import get_env_store from .model_catalog import get_model_catalog_service -from .provider_runtime import resolve_search_runtime_config +from .provider_runtime import ( + resolve_embedding_runtime_config, + resolve_llm_runtime_config, + resolve_search_runtime_config, +) def _redact(value: str) -> str: @@ -115,11 +119,11 @@ class ConfigTestRunner: with temporary_env(env_values): if service == "llm": - asyncio.run(self._test_llm(run)) + asyncio.run(self._test_llm(run, catalog)) elif service == "embedding": - asyncio.run(self._test_embedding(run, model or {})) + asyncio.run(self._test_embedding(run, model or {}, catalog)) elif service == "search": - self._test_search(run) + self._test_search(run, catalog) else: raise ValueError(f"Unsupported service: {service}") if not run.cancelled and run.status == "running": @@ -129,13 +133,26 @@ class ConfigTestRunner: run.status = "failed" run.emit("failed", str(exc)) - async def _test_llm(self, run: TestRun) -> None: + async def _test_llm(self, run: TestRun, catalog: dict[str, Any]) -> None: from deeptutor.services.llm import clear_llm_config_cache, complete as llm_complete - from deeptutor.services.llm import get_llm_config, get_token_limit_kwargs + from deeptutor.services.llm import get_token_limit_kwargs + from deeptutor.services.llm.config import LLMConfig clear_llm_config_cache() run.emit("info", "Loading LLM config from the active catalog selection.") - llm_config = get_llm_config() + resolved = resolve_llm_runtime_config(catalog=catalog) + llm_config = LLMConfig( + model=resolved.model, + api_key=resolved.api_key, + base_url=resolved.base_url, + effective_url=resolved.effective_url, + binding=resolved.binding, + provider_name=resolved.provider_name, + provider_mode=resolved.provider_mode, + api_version=resolved.api_version, + extra_headers=resolved.extra_headers, + reasoning_effort=resolved.reasoning_effort, + ) run.emit("info", f"Resolved model `{llm_config.model}` with binding `{llm_config.binding}`.") run.emit("info", f"Request target: {llm_config.base_url}") token_kwargs = get_token_limit_kwargs(llm_config.model, max_tokens=200) @@ -155,14 +172,30 @@ class ConfigTestRunner: if not snippet: raise ValueError("LLM returned an empty response.") - async def _test_embedding(self, run: TestRun, model: dict[str, Any]) -> None: - from deeptutor.services.embedding import get_embedding_client, get_embedding_config + async def _test_embedding(self, run: TestRun, model: dict[str, Any], catalog: dict[str, Any]) -> None: + from deeptutor.services.embedding.client import EmbeddingClient + from deeptutor.services.embedding.config import EmbeddingConfig run.emit("info", "Loading embedding config from the active catalog selection.") - config = get_embedding_config() + resolved = resolve_embedding_runtime_config(catalog=catalog) + config = EmbeddingConfig( + model=resolved.model, + api_key=resolved.api_key, + base_url=resolved.base_url, + effective_url=resolved.effective_url, + binding=resolved.binding, + provider_name=resolved.provider_name, + provider_mode=resolved.provider_mode, + api_version=resolved.api_version, + extra_headers=resolved.extra_headers, + dim=resolved.dimension, + request_timeout=max(1, resolved.request_timeout), + batch_size=max(1, resolved.batch_size), + batch_delay=max(0.0, resolved.batch_delay), + ) run.emit("info", f"Resolved embedding model `{config.model}` with binding `{config.binding}`.") run.emit("info", f"Request target: {config.base_url}") - client = get_embedding_client() + client = EmbeddingClient(config) vectors = await client.embed(["DeepTutor embedding smoke test"]) if not vectors or not vectors[0]: raise ValueError("Embedding service returned an empty vector.") @@ -179,10 +212,10 @@ class ConfigTestRunner: f"Embedding dimension mismatch. expected={expected_dimension}, actual={actual_dimension}" ) - def _test_search(self, run: TestRun) -> None: + def _test_search(self, run: TestRun, catalog: dict[str, Any]) -> None: from deeptutor.services.search import web_search - resolved = resolve_search_runtime_config() + resolved = resolve_search_runtime_config(catalog=catalog) if not resolved.requested_provider: run.status = "completed" run.emit("completed", "Search skipped because no active provider is configured.") diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.py index 9463e3b16..69c996626 100644 --- a/deeptutor/services/search/__init__.py +++ b/deeptutor/services/search/__init__.py @@ -18,7 +18,7 @@ from deeptutor.services.config import ( ) from .base import SEARCH_API_KEY_ENV, BaseSearchProvider -from .consolidation import CONSOLIDATION_TYPES, PROVIDER_TEMPLATES, AnswerConsolidator +from .consolidation import PROVIDER_TEMPLATES, AnswerConsolidator from .providers import ( _DEPRECATED_UNSUPPORTED, get_available_providers, @@ -84,12 +84,16 @@ def web_search( output_dir: str | None = None, verbose: bool = False, provider: str | None = None, - consolidation: str | None = None, consolidation_custom_template: str | None = None, consolidation_llm_model: str | None = None, **provider_kwargs: Any, ) -> dict[str, Any]: - """Execute web search and return DeepTutor structured response shape.""" + """Execute web search and return DeepTutor structured response shape. + + Consolidation is automatic for providers that return raw SERP results + (``supports_answer=False``). Pass ``consolidation_llm_model`` to + upgrade from template formatting to LLM synthesis. + """ config = _get_web_search_config() if not config.get("enabled", True): _logger.warning("Web search is disabled in config") @@ -138,19 +142,16 @@ def web_search( _logger.error(f"[{search_provider.name}] Search failed: {exc}") raise Exception(f"{search_provider.name} search failed: {exc}") from exc - # Compatibility layer: only apply optional consolidation when requested. - if consolidation is None: - consolidation = config.get("consolidation") - if consolidation_custom_template is None: - consolidation_custom_template = config.get("consolidation_template") or None - if consolidation and not search_provider.supports_answer: - llm_config = {} - if consolidation_llm_model: - llm_config["model"] = consolidation_llm_model + # Auto-consolidate for providers that don't generate their own answers. + if not search_provider.supports_answer: + if consolidation_custom_template is None: + consolidation_custom_template = config.get("consolidation_template") or None + use_llm = bool(consolidation_llm_model) + llm_config = {"model": consolidation_llm_model} if consolidation_llm_model else None consolidator = AnswerConsolidator( - consolidation_type=consolidation, + use_llm=use_llm, custom_template=consolidation_custom_template, - llm_config=llm_config if llm_config else None, + llm_config=llm_config, ) response = consolidator.consolidate(response) @@ -184,9 +185,7 @@ def get_current_config() -> dict[str, Any]: "providers": get_providers_info(), "supported_providers": sorted(SUPPORTED_SEARCH_PROVIDERS), "deprecated_providers": sorted(DEPRECATED_SEARCH_PROVIDERS), - "consolidation": config.get("consolidation"), "consolidation_template": config.get("consolidation_template") or None, - "consolidation_types": CONSOLIDATION_TYPES, "template_providers": list(PROVIDER_TEMPLATES.keys()), } @@ -205,7 +204,6 @@ __all__ = [ "Citation", "SearchResult", "AnswerConsolidator", - "CONSOLIDATION_TYPES", "PROVIDER_TEMPLATES", "BaseSearchProvider", "SearchProvider", diff --git a/deeptutor/services/search/consolidation.py b/deeptutor/services/search/consolidation.py index c7127e3b4..972163d0a 100644 --- a/deeptutor/services/search/consolidation.py +++ b/deeptutor/services/search/consolidation.py @@ -1,9 +1,10 @@ """ Answer Consolidation - Generate answers from raw search results -Supports two strategies: -1. template: Fast Jinja2 template rendering -2. llm: LLM-based answer synthesis (uses project's LLM config from env vars) +Strategies (chosen automatically): +- Provider-specific Jinja2 template when available (serper, jina, serper_scholar) +- Generic fallback template for all other raw-SERP providers +- Optional LLM synthesis when ``use_llm=True`` """ from typing import Any @@ -15,14 +16,9 @@ from deeptutor.services.llm import get_llm_client from .types import WebSearchResponse -# Module logger _logger = get_logger("Search.Consolidation", level="INFO") -# Available consolidation types -CONSOLIDATION_TYPES = ["none", "template", "llm"] - - # ============================================================================= # PROVIDER-SPECIFIC TEMPLATES # ============================================================================= @@ -140,19 +136,13 @@ PROVIDER_TEMPLATES = { class AnswerConsolidator: - """ - Consolidate raw SERP results into formatted answers. + """Consolidate raw SERP results into a formatted answer. - IMPORTANT: Template consolidation only works for providers that have - specific templates defined (serper, jina, serper_scholar). - - For other providers, use: - - consolidation_type="llm" for LLM-based synthesis - - custom_template for a custom Jinja2 template + By default, uses Jinja2 templates (provider-specific when available, + generic fallback otherwise). Set ``use_llm=True`` to upgrade to + LLM-based synthesis instead. """ - # Map provider names to their specific templates - # Only these providers support template consolidation PROVIDER_TEMPLATE_MAP = { "serper": "serper", "jina": "jina", @@ -161,28 +151,17 @@ class AnswerConsolidator: def __init__( self, - consolidation_type: str = "template", + *, + use_llm: bool = False, custom_template: str | None = None, llm_config: dict[str, Any] | None = None, max_results: int = 5, autoescape: bool = True, ): - """ - Initialize consolidator. - - Args: - consolidation_type: "none", "template", or "llm" - custom_template: Custom Jinja2 template string - llm_config: Optional overrides (system_prompt, max_tokens, temperature) - max_results: Maximum results to include in answer - autoescape: Whether to enable Jinja2 autoescape for security (default: True) - """ - self.consolidation_type = consolidation_type + self.use_llm = use_llm self.custom_template = custom_template self.llm_config = llm_config or {} self.max_results = max_results - # Security: autoescape defaults to True (set in function signature above). - # When True, Jinja2 auto-escapes HTML to prevent XSS. self.jinja_env = Environment(loader=BaseLoader(), autoescape=autoescape) # nosec B701 if self.custom_template is not None and autoescape: @@ -193,67 +172,32 @@ class AnswerConsolidator: ) def consolidate(self, response: WebSearchResponse) -> WebSearchResponse: - """ - Consolidate search results into an answer. - - Args: - response: WebSearchResponse with search_results populated - - Returns: - WebSearchResponse with answer field populated - """ - if self.consolidation_type == "none": - _logger.debug("Consolidation disabled, returning raw response") - return response - + """Consolidate search results into an answer.""" results_count = len(response.search_results) - _logger.info( - f"Consolidating {results_count} results from {response.provider} using {self.consolidation_type}" - ) - if self.consolidation_type == "template": - response.answer = self._consolidate_with_template(response) - _logger.success(f"Template consolidation completed ({len(response.answer)} chars)") - elif self.consolidation_type == "llm": + if self.use_llm: + _logger.info(f"Consolidating {results_count} results from {response.provider} via LLM") response.answer = self._consolidate_with_llm(response) _logger.success(f"LLM consolidation completed ({len(response.answer)} chars)") else: - _logger.error(f"Unknown consolidation type: {self.consolidation_type}") - raise ValueError(f"Unknown consolidation type: {self.consolidation_type}") + _logger.info(f"Consolidating {results_count} results from {response.provider} via template") + response.answer = self._consolidate_with_template(response) + _logger.success(f"Template consolidation completed ({len(response.answer)} chars)") return response def _get_template_for_provider(self, provider: str) -> str | None: - """ - Get the template for a specific provider. - - Only provider-specific templates exist because each provider has - different response schemas and metadata. No universal templates. - - Args: - provider: Provider name (e.g., "serper", "jina") - - Returns: - Template string for this provider, or None if no template exists - """ - # 1. Custom template takes highest priority + """Return the best Jinja2 template for *provider*, or ``None``.""" if self.custom_template: _logger.debug(f"Using custom template ({len(self.custom_template)} chars)") return self.custom_template - # 2. Get provider-specific template template_key = self.PROVIDER_TEMPLATE_MAP.get(provider.lower()) if template_key and template_key in PROVIDER_TEMPLATES: _logger.debug(f"Using provider-specific template: {template_key}") return PROVIDER_TEMPLATES[template_key] - # 3. No template exists for this provider - return None for auto-fallback - available = list(PROVIDER_TEMPLATES.keys()) - _logger.warning( - f"No template available for provider '{provider}'. " - f"Template consolidation only works with: {available}. " - f"Auto-falling back to simple result formatting." - ) + _logger.debug(f"No specific template for '{provider}', using generic fallback") return None def _build_provider_context(self, response: WebSearchResponse) -> dict[str, Any]: @@ -424,4 +368,4 @@ Consolidate these results into structured grounding context.""" return "\n".join(lines) -__all__ = ["AnswerConsolidator", "CONSOLIDATION_TYPES", "PROVIDER_TEMPLATES"] +__all__ = ["AnswerConsolidator", "PROVIDER_TEMPLATES"] diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.py index 12c3cdc95..7feecc8ce 100644 --- a/deeptutor/services/setup/init.py +++ b/deeptutor/services/setup/init.py @@ -50,8 +50,6 @@ DEFAULT_MAIN_SETTINGS = { }, "web_search": { "enabled": True, - "consolidation": "template", - "consolidation_template": "", }, }, "capabilities": { diff --git a/deeptutor/tools/web_search.py b/deeptutor/tools/web_search.py index 5a14c9bed..5f247f214 100644 --- a/deeptutor/tools/web_search.py +++ b/deeptutor/tools/web_search.py @@ -28,7 +28,6 @@ Available Providers: # Re-export from services layer from deeptutor.services.search import ( - CONSOLIDATION_TYPES, PROVIDER_TEMPLATES, SEARCH_API_KEY_ENV, AnswerConsolidator, @@ -62,7 +61,6 @@ __all__ = [ "SearchResult", # Consolidation "AnswerConsolidator", - "CONSOLIDATION_TYPES", "PROVIDER_TEMPLATES", # Base class "BaseSearchProvider",