~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
refactor(pipeline): route the question/filter/explorer/context LLM calls through one helper — tranche 5 of #5854 (#6277)
LearningCircuit5af94a3473c9
diff --git a/changelog.d/6277.misc.md b/changelog.d/6277.misc.mdnew file mode 100644index 0000000000..3b77341ccd--- /dev/null+++ b/changelog.d/6277.misc.md@@ -0,0 +1 @@+The research pipeline's question generators, result filters, candidate explorers, follow-up context manager, evidence evaluator, findings synthesizer, summarization and constraint analysis, agent fetch tool and the news/LangGraph strategies now make their model calls through one shared `invoke_llm_sync` helper. The helper keeps the synchronous client and raw response; token-usage attribution skips this dispatch frame, so the pipeline caller is retained for injected raw models while wrapped models keep their existing `config/llm_config.py` attribution, with the filter's visible effect being on the recorded call stack. An `ainvoke_llm` helper and `RateLimitedLLMWrapper.ainvoke` are added for future async callers, with regression coverage for credential scrubbing and exception-chain suppression. Pipeline callers remain synchronous. Fifth tranche of #5854.diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.pyindex 556c8ead2b..b27d99b58d 100644--- a/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py@@ -19,6 +19,7 @@ from .base_explorer import (ExplorationResult,ExplorationStrategy,)+from ...utilities.llm_utils import invoke_llm_syncclass AdaptiveExplorer(BaseCandidateExplorer):@@ -248,7 +249,9 @@ Query:"""try:- response = get_llm_response_text(self.model.invoke(prompt)).strip()+ response = get_llm_response_text(+ invoke_llm_sync(self.model, prompt)+ ).strip()return response if response != base_query else Noneexcept Exception as e:logger.debug(@@ -277,7 +280,9 @@ Related search term:"""try:- response = get_llm_response_text(self.model.invoke(prompt)).strip()+ response = get_llm_response_text(+ invoke_llm_sync(self.model, prompt)+ ).strip()return response if response != base_query else Noneexcept Exception as e:logger.debug(diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.pyindex ed60a31fda..e1e5918e4d 100644--- a/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py@@ -16,6 +16,7 @@ from loguru import loggerfrom ..candidates.base_candidate import Candidatefrom ..constraints.base_constraint import Constraintfrom ...utilities.json_utils import get_llm_response_text+from ...utilities.llm_utils import invoke_llm_syncclass ExplorationStrategy(Enum):@@ -205,7 +206,7 @@ Give me multiple possible answers, one per line:"""try:- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)content = get_llm_response_text(response)# Parse multiple answers@@ -247,7 +248,9 @@ Names:"""try:- response = get_llm_response_text(self.model.invoke(prompt))+ response = get_llm_response_text(+ invoke_llm_sync(self.model, prompt)+ )# Parse response into namesnames = []diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.pyindex c579cd905d..35b4745b1d 100644--- a/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py@@ -20,6 +20,7 @@ from .base_explorer import (ExplorationResult,ExplorationStrategy,)+from ...utilities.llm_utils import invoke_llm_syncclass ParallelExplorer(BaseCandidateExplorer):@@ -206,7 +207,9 @@ Format as numbered list:4. [query]"""- response = get_llm_response_text(self.model.invoke(prompt)).strip()+ response = get_llm_response_text(+ invoke_llm_sync(self.model, prompt)+ ).strip()# Parse numbered listqueries = []diff --git a/src/local_deep_research/advanced_search_system/constraints/constraint_analyzer.py b/src/local_deep_research/advanced_search_system/constraints/constraint_analyzer.pyindex 04f37ba3a6..f366a719d6 100644--- a/src/local_deep_research/advanced_search_system/constraints/constraint_analyzer.py+++ b/src/local_deep_research/advanced_search_system/constraints/constraint_analyzer.py@@ -10,6 +10,7 @@ from loguru import loggerfrom ...utilities.json_utils import get_llm_response_textfrom .base_constraint import Constraint, ConstraintType+from ...utilities.llm_utils import invoke_llm_syncclass ConstraintAnalyzer:@@ -56,7 +57,7 @@ Weight: [0.0-1.0]Focus on answer verification, not query parsing."""- content = get_llm_response_text(self.model.invoke(prompt))+ content = get_llm_response_text(invoke_llm_sync(self.model, prompt))constraints = []current_constraint = {}diff --git a/src/local_deep_research/advanced_search_system/evidence/evaluator.py b/src/local_deep_research/advanced_search_system/evidence/evaluator.pyindex 693ea50667..9d6dd8ce24 100644--- a/src/local_deep_research/advanced_search_system/evidence/evaluator.py+++ b/src/local_deep_research/advanced_search_system/evidence/evaluator.py@@ -10,6 +10,7 @@ from loguru import loggerfrom ...utilities.json_utils import get_llm_response_textfrom ..constraints.base_constraint import Constraintfrom .base_evidence import Evidence, EvidenceType+from ...utilities.llm_utils import invoke_llm_syncclass EvidenceEvaluator:@@ -58,7 +59,7 @@ REASONING: [explanation]QUOTE: [relevant text]"""- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)content = get_llm_response_text(response)# Parse responsediff --git a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.pyindex c965242e80..100266bf13 100644--- a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py+++ b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py@@ -8,6 +8,7 @@ from loguru import loggerfrom ...utilities.json_utils import extract_json, get_llm_response_textfrom .base_filter import BaseFilter+from ...utilities.llm_utils import invoke_llm_syncclass CrossEngineFilter(BaseFilter):@@ -164,7 +165,7 @@ If no results seem relevant to the query, return an empty array: []"""try:# Get LLM's evaluation- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)response_text = get_llm_response_text(response)ranked_indices = extract_json(response_text, expected_type=list)diff --git a/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py b/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.pyindex ade8289e08..7a1cb6d382 100644--- a/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py+++ b/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py@@ -10,6 +10,7 @@ from loguru import loggerfrom .base_filter import BaseFilterfrom ...utilities.json_utils import extract_json, get_llm_response_text+from ...utilities.llm_utils import invoke_llm_syncclass FollowUpRelevanceFilter(BaseFilter):@@ -157,7 +158,7 @@ Instructions:Return the indices of relevant sources as a JSON array:"""try:- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)content = get_llm_response_text(response)# Parse JSON responsediff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.pyindex 528d4476f2..14329e6c02 100644--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py@@ -59,6 +59,7 @@ from ...utilities.thread_context import get_search_contextfrom ...web_search_engines.search_engine_factory import create_search_enginefrom .base_filter import BaseFilterfrom ...constants import DEFAULT_SEARCH_TOOL+from ...utilities.llm_utils import invoke_llm_sync# Patterns that indicate a venue is a conference, not a journal.@@ -699,7 +700,7 @@ class JournalReputationFilter(BaseFilter):"locations. Output only the clean name, no explanation.")try:- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)content = getattr(response, "content", None) or responsecleaned = str(content).strip().strip('"').strip("'")if not cleaned:@@ -791,7 +792,9 @@ JOURNAL INFORMATION:{journal_info_text}"""- response_text = get_llm_response_text(self.model.invoke(prompt))+ response_text = get_llm_response_text(+ invoke_llm_sync(self.model, prompt)+ )logger.debug(f"Tier 4 LLM response for '{journal_name}': {response_text}")diff --git a/src/local_deep_research/advanced_search_system/findings/repository.py b/src/local_deep_research/advanced_search_system/findings/repository.pyindex 2776b469ef..9cdf212dad 100644--- a/src/local_deep_research/advanced_search_system/findings/repository.py+++ b/src/local_deep_research/advanced_search_system/findings/repository.py@@ -10,6 +10,7 @@ from langchain_core.language_models import BaseLanguageModelfrom ...utilities.search_utilities import format_findingsfrom .base_findings import BaseFindingsRepository+from ...utilities.llm_utils import invoke_llm_syncdef format_links(links: List[Dict]) -> str:@@ -365,7 +366,7 @@ Use IEEE style citations [1], [2], etc. Never make up your own citations."Using Windows-compatible timeout for LLM invocation")response = invoke_with_timeout(- 120, self.model.invoke, prompt+ 120, invoke_llm_sync, self.model, prompt)# <think> tags are stripped centrally in ProcessingLLMWrapper;@@ -406,7 +407,7 @@ Use IEEE style citations [1], [2], etc. Never make up your own citations.with timeout(120, "LLM invocation timed out after 120 seconds"):- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)# <think> tags are stripped centrally in ProcessingLLMWrapper;# keep only a shape-guard for non-message returns.diff --git a/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py b/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.pyindex 74f6e31821..166ce0d5d4 100644--- a/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py+++ b/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py@@ -12,6 +12,7 @@ from loguru import loggerfrom langchain_core.language_models.chat_models import BaseChatModelfrom ...utilities.json_utils import get_llm_response_text+from ...utilities.llm_utils import invoke_llm_syncclass FollowUpContextHandler:@@ -154,7 +155,7 @@ Return up to 10 most important entities, one per line."""try:- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)entities = [line.strip()for line in get_llm_response_text(response).split("\n")@@ -294,7 +295,7 @@ Create a summary of {max_sentences} sentences that captures the most relevant in"""try:- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)summary = get_llm_response_text(response)# Apply length constraint if specified@@ -339,7 +340,7 @@ What specific information is missing or needs clarification? List up to 5 gaps,"""try:- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)gaps = [line.strip()for line in get_llm_response_text(response).split("\n")diff --git a/src/local_deep_research/advanced_search_system/questions/atomic_fact_question.py b/src/local_deep_research/advanced_search_system/questions/atomic_fact_question.pyindex f92580fe9a..8a5fbdfed3 100644--- a/src/local_deep_research/advanced_search_system/questions/atomic_fact_question.py+++ b/src/local_deep_research/advanced_search_system/questions/atomic_fact_question.py@@ -8,6 +8,7 @@ from typing import Dict, List, Optionalfrom ...utilities.json_utils import get_llm_response_textfrom .base_question import BaseQuestionGenerator+from ...utilities.llm_utils import invoke_llm_syncclass AtomicFactQuestionGenerator(BaseQuestionGenerator):@@ -77,7 +78,7 @@ What geographic features are named after body parts?Where did falls occur between specific dates?"""- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)response_text = get_llm_response_text(response)@@ -142,7 +143,7 @@ Focus on facts not yet explored.Return ONLY the questions, one per line."""- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)response_text = get_llm_response_text(response)diff --git a/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py b/src/local_deep_research/advanced_search_system/questions/browsecomp_question.pyindex 34935ca48e..0b197914b8 100644--- a/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py+++ b/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py@@ -9,6 +9,7 @@ from loguru import loggerfrom ...utilities.json_utils import get_llm_response_textfrom .base_question import BaseQuestionGenerator+from ...utilities.llm_utils import invoke_llm_syncclass BrowseCompQuestionGenerator(BaseQuestionGenerator):@@ -94,7 +95,7 @@ LOCATIONS: [entity1], [entity2], ...DESCRIPTORS: [entity1], [entity2], ..."""- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)content = get_llm_response_text(response)entities: Dict[str, List[str]] = {@@ -278,7 +279,7 @@ Focus on finding the specific answer, not general information.Format: One search per line"""- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)content = get_llm_response_text(response)# Extract searches from responsediff --git a/src/local_deep_research/advanced_search_system/questions/decomposition_question.py b/src/local_deep_research/advanced_search_system/questions/decomposition_question.pyindex f232652d91..01acf05af4 100644--- a/src/local_deep_research/advanced_search_system/questions/decomposition_question.py+++ b/src/local_deep_research/advanced_search_system/questions/decomposition_question.py@@ -5,6 +5,7 @@ from loguru import loggerfrom .base_question import BaseQuestionGeneratorfrom ...utilities.json_utils import get_llm_response_text+from ...utilities.llm_utils import invoke_llm_syncclass DecompositionQuestionGenerator(BaseQuestionGenerator):@@ -131,7 +132,7 @@ What are the security implications of X?try:# Get response from LLM- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)# Handle different response formats (string or object with content# attribute, including list-form content blocks) via coercion.@@ -247,7 +248,7 @@ Sub-questions:2.3. """- simple_response = self.model.invoke(simple_prompt)+ simple_response = invoke_llm_sync(self.model, simple_prompt)# Handle different response formats (including list-form# content blocks) via coercion.diff --git a/src/local_deep_research/advanced_search_system/questions/flexible_browsecomp_question.py b/src/local_deep_research/advanced_search_system/questions/flexible_browsecomp_question.pyindex 67125ff071..bce87dd705 100644--- a/src/local_deep_research/advanced_search_system/questions/flexible_browsecomp_question.py+++ b/src/local_deep_research/advanced_search_system/questions/flexible_browsecomp_question.py@@ -8,6 +8,7 @@ from typing import Dict, Listfrom ...utilities.json_utils import get_llm_response_textfrom .browsecomp_question import BrowseCompQuestionGenerator+from ...utilities.llm_utils import invoke_llm_syncclass FlexibleBrowseCompQuestionGenerator(BrowseCompQuestionGenerator):@@ -59,7 +60,7 @@ Current findings:Create {num_questions} diverse search queries. Avoid exact duplicates. One per line."""- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)content = get_llm_response_text(response)# Extract searchesdiff --git a/src/local_deep_research/advanced_search_system/questions/standard_question.py b/src/local_deep_research/advanced_search_system/questions/standard_question.pyindex a983e4dd0d..9672bb9e26 100644--- a/src/local_deep_research/advanced_search_system/questions/standard_question.py+++ b/src/local_deep_research/advanced_search_system/questions/standard_question.py@@ -9,6 +9,7 @@ from loguru import loggerfrom ...utilities.json_utils import get_llm_response_textfrom .base_question import BaseQuestionGenerator+from ...utilities.llm_utils import invoke_llm_syncclass StandardQuestionGenerator(BaseQuestionGenerator):@@ -39,7 +40,7 @@ class StandardQuestionGenerator(BaseQuestionGenerator):else:prompt = f" You will have follow up questions. First, identify if your knowledge is outdated (high chance). Today: {current_time}. Generate {questions_per_iteration} high-quality internet search questions to exactly answer: {query}\n\n\nFormat: One question per line, e.g. \n Q: question1 \n Q: question2\n\n"- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)response_text = get_llm_response_text(response)@@ -87,7 +88,7 @@ Format your response as a numbered list with ONLY the sub-questions, one per linOnly provide the numbered sub-questions, nothing else."""try:- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)content = get_llm_response_text(response)diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.pyindex ebadc1cdf1..ec2c9c3ba8 100644--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py@@ -31,6 +31,7 @@ from ...security import (sanitize_error_for_client,scrub_error,)+from ...utilities.llm_utils import invoke_llm_syncfrom ...utilities.chunk_anchor import (build_chunk_anchor_url,extract_chunk_index,@@ -2864,7 +2865,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):f"Based on these sources:\n" + "\n".join(summaries))try:- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)return get_llm_response_text(response)except Exception as exc:logger.exception("Fallback synthesis failed")diff --git a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py b/src/local_deep_research/advanced_search_system/strategies/news_strategy.pyindex c8de13b6c0..afca844741 100644--- a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/news_strategy.py@@ -15,6 +15,7 @@ from .base_strategy import (from ..questions.news_question import NewsQuestionGeneratorfrom ...database.thread_local_session import thread_cleanupfrom ...utilities.json_utils import extract_json+from ...utilities.llm_utils import invoke_llm_syncclass NewsAggregationStrategy(BaseSearchStrategy):@@ -75,7 +76,7 @@ class NewsAggregationStrategy(BaseSearchStrategy):prompt = self._create_news_analysis_prompt(snippets)try:- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)content = (response.contentif hasattr(response, "content")diff --git a/src/local_deep_research/advanced_search_system/summarization/base.py b/src/local_deep_research/advanced_search_system/summarization/base.pyindex 7958752185..3a927b413d 100644--- a/src/local_deep_research/advanced_search_system/summarization/base.py+++ b/src/local_deep_research/advanced_search_system/summarization/base.py@@ -6,6 +6,7 @@ from langchain_core.language_models.chat_models import BaseChatModelfrom loguru import loggerfrom ...utilities.search_utilities import remove_think_tags+from ...utilities.llm_utils import invoke_llm_syncclass BaseSummarizer(ABC):@@ -39,7 +40,7 @@ class BaseSummarizer(ABC):prompt = self._build_prompt(content[: self.INPUT_TRUNCATE_CHARS])try:- response = self.model.invoke(prompt)+ response = invoke_llm_sync(self.model, prompt)except Exception:logger.opt(exception=True).debug("LLM summarization failed")return ""diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.pyindex c3271bd64c..6d1c7ce7a3 100644--- a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py+++ b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py@@ -39,6 +39,7 @@ from local_deep_research.security import (redact_url_for_log,sanitize_error_for_client,)+from local_deep_research.utilities.llm_utils import invoke_llm_syncfrom .library_resolver import (is_citation_reference,@@ -497,7 +498,7 @@ def _make_summary_fetch_tool(prompt = template.format(**fmt_kwargs)try:- summary_msg = model.invoke(prompt)+ summary_msg = invoke_llm_sync(model, prompt)summary = getattr(summary_msg, "content", str(summary_msg)).strip()diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.pyindex f4bebb4bea..0436ce27dd 100644--- a/src/local_deep_research/metrics/token_counter.py+++ b/src/local_deep_research/metrics/token_counter.py@@ -144,7 +144,19 @@ class TokenCountingCallback(BaseCallbackHandler):calling_function = Nonecall_stack = Nonetry:- stack = inspect.stack()+ # The shared synchronous dispatcher is transparent to caller+ # attribution. Remove its frame before applying the frame budget+ # so it neither replaces an injected model's real caller nor+ # displaces an outer caller from the persisted diagnostic stack.+ stack = [+ frame+ for frame in inspect.stack()+ if not (+ frame.function == "invoke_llm_sync"+ and Path(frame.filename).parts[-3:]+ == ("local_deep_research", "utilities", "llm_utils.py")+ )+ ]# Skip the first few frames (this method, langchain internals)# Look for the first frame that's in our project directory.diff --git a/src/local_deep_research/utilities/llm_utils.py b/src/local_deep_research/utilities/llm_utils.pyindex bb62da271a..8f476c1c8c 100644--- a/src/local_deep_research/utilities/llm_utils.py+++ b/src/local_deep_research/utilities/llm_utils.py@@ -17,6 +17,8 @@ from ..config.thread_settings import get_setting_from_snapshot__all__ = [+ "ainvoke_llm",+ "invoke_llm_sync","get_model_identifier","get_ollama_base_url","get_server_url",@@ -24,6 +26,46 @@ __all__ = []+def invoke_llm_sync(llm: Any, prompt: Any) -> Any:+ """Invoke an LLM on the synchronous client (#5854).++ This is deliberately a plain ``llm.invoke(prompt)`` and starts no+ event loop: langchain's cached ``httpx.AsyncClient`` is bound to the+ loop that first used it, so bridging a sync caller onto ``ainvoke``+ with a throwaway loop double-sends or hard-fails from the second call+ onward (see #6293). The helper exists to give the research pipeline's+ question generators, filters, explorers, context managers and+ evaluators one call site to change once a single-loop runner makes+ the async path safe.++ Returns the RAW response object, so each caller's existing parsing+ (``get_llm_response_text`` / ``.content`` / ``extract_json``) is+ untouched. Callers that pass extra keyword arguments to the model+ (for example ``relevance_filter.py`` calling+ ``llm.invoke(prompt, **invoke_kwargs)``) are outside this signature+ and keep calling the model directly.+ """+ return llm.invoke(prompt)+++async def ainvoke_llm(llm: Any, prompt: Any) -> Any:+ """Async core matching :func:`invoke_llm_sync` (#5854).++ Additive: nothing in production awaits this yet. It becomes usable+ once the process has a single long-lived event loop for the LLM+ clients (#6293) and ``TokenCountingCallback`` records call-site+ attribution on the async dispatch path (#6294); ``ainvoke`` coverage+ on ``RateLimitedLLMWrapper`` (#6232) is in place, with the wrapper's+ remaining surfaces tracked in #6296.++ Every production model is a ``ProcessingLLMWrapper``, which defines+ ``ainvoke``; a wrapped object without it is a configuration error and+ raises ``AttributeError`` rather than silently falling back to the+ sync client.+ """+ return await llm.ainvoke(prompt)++def get_model_identifier(llm: Any) -> str:"""Return a stable string identifier for an LLM instance.diff --git a/tests/metrics/test_token_counting_dispatch_attribution.py b/tests/metrics/test_token_counting_dispatch_attribution.pynew file mode 100644index 0000000000..1ebc68f579--- /dev/null+++ b/tests/metrics/test_token_counting_dispatch_attribution.py@@ -0,0 +1,133 @@+"""Shared synchronous dispatch preserves token-usage caller attribution."""++from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++import pytest++from local_deep_research.metrics.token_counter import TokenCountingCallback+++_MODULE = "local_deep_research.metrics.token_counter"+++def _frame(filename, function, lineno=1):+ return SimpleNamespace(filename=filename, function=function, lineno=lineno)+++ "root",+ [+ "/repo/src/local_deep_research",+ "/venv/lib/python3.12/site-packages/local_deep_research",+ ],+)[email protected]("wrapped", [False, True])+def test_dispatch_preserves_caller_and_full_stack_budget(root, wrapped):+ callback = TokenCountingCallback(research_id="dispatch-attribution")+ caller = _frame(+ f"{root}/report_generator.py", "_determine_report_structure", 367+ )+ dispatch = _frame(f"{root}/utilities/llm_utils.py", "invoke_llm_sync", 47)+ wrapper = _frame(f"{root}/config/llm_config.py", "invoke", 425)+ outer = [+ _frame(f"{root}/runner.py", f"outer_{index}", 100 + index)+ for index in range(1, 6)+ ]+ prefix = [+ _frame("/callback.py", "on_llm_start"),+ _frame("/vendor.py", "invoke"),+ ]+ if wrapped:+ prefix.append(wrapper)+ with patch(+ f"{_MODULE}.inspect.stack", return_value=prefix + [caller] + outer+ ):+ callback.on_llm_start({}, ["synthetic prompt"], run_id="direct")+ with patch(+ f"{_MODULE}.inspect.stack",+ return_value=prefix + [dispatch, caller] + outer,+ ):+ callback.on_llm_start({}, ["synthetic prompt"], run_id="dispatched")++ direct = callback._call_meta["direct"]+ dispatched = callback._call_meta["dispatched"]+ assert dispatched == direct+ assert dispatched["calling_file"] == (+ "config/llm_config.py" if wrapped else "report_generator.py"+ )+ assert dispatched["calling_function"] == (+ "invoke" if wrapped else "_determine_report_structure"+ )+ frames = dispatched["call_stack"].split(" -> ")+ assert len(frames) == 5+ assert "llm_utils.py" not in dispatched["call_stack"]+ assert frames[-1] == (+ "runner.py:outer_3:103" if wrapped else "runner.py:outer_4:104"+ )+++ ("relative_path", "function"),+ [+ ("other/llm_utils.py", "invoke_llm_sync"),+ ("utilities/llm_utils.py", "get_model_identifier"),+ ],+)+def test_other_functions_and_same_named_modules_keep_attribution(+ relative_path, function+):+ callback = TokenCountingCallback(research_id="dispatch-negative-control")+ frames = [+ _frame("/callback.py", "on_llm_start"),+ _frame(f"/repo/src/local_deep_research/{relative_path}", function, 10),+ _frame(+ "/repo/src/local_deep_research/report_generator.py", "generate", 20+ ),+ ]+ with patch(f"{_MODULE}.inspect.stack", return_value=frames):+ callback.on_llm_start({}, ["synthetic prompt"], run_id="other")++ metadata = callback._call_meta["other"]+ assert metadata["calling_file"] == relative_path+ assert metadata["calling_function"] == function+ assert metadata["call_stack"].startswith(f"llm_utils.py:{function}:10 -> ")+++def test_dispatch_without_a_project_caller_has_no_attribution():+ callback = TokenCountingCallback(research_id="dispatch-no-caller")+ frames = [+ _frame("/callback.py", "on_llm_start"),+ _frame(+ "/repo/src/local_deep_research/utilities/llm_utils.py",+ "invoke_llm_sync",+ ),+ _frame("/external/client.py", "run"),+ ]+ with patch(f"{_MODULE}.inspect.stack", return_value=frames):+ callback.on_llm_start({}, ["synthetic prompt"], run_id="external")++ assert callback._call_meta["external"] == {+ "calling_file": None,+ "calling_function": None,+ "call_stack": None,+ }+++def test_llm_utils_module_matches_the_dispatch_frame_filter_literals():+ """The filter in token_counter.py matches frames on+ ``frame.function == "invoke_llm_sync"`` and+ ``Path(frame.filename).parts[-3:] == ("local_deep_research",+ "utilities", "llm_utils.py")``. This anchors both literals against the+ real module, so a rename or move of either fails here instead of only+ silently disabling the dispatch-frame filter.+ """+ from local_deep_research.utilities import llm_utils++ assert Path(llm_utils.__file__).parts[-3:] == (+ "local_deep_research",+ "utilities",+ "llm_utils.py",+ )+ assert llm_utils.invoke_llm_sync.__name__ == "invoke_llm_sync"diff --git a/tests/utilities/test_llm_utils_invoke_helpers.py b/tests/utilities/test_llm_utils_invoke_helpers.pynew file mode 100644index 0000000000..7748621db6--- /dev/null+++ b/tests/utilities/test_llm_utils_invoke_helpers.py@@ -0,0 +1,187 @@+"""Contract tests for ``invoke_llm_sync`` / ``ainvoke_llm`` (#5854).++The two helpers exist so the research pipeline has ONE place that decides+which client an LLM call goes through. What each one must do is a+behavioural contract, not an implementation detail:++* ``invoke_llm_sync`` must stay on the synchronous ``.invoke`` client and+ must not create or run an event loop. Bridging a sync caller onto+ ``ainvoke`` with a throwaway loop is what #6293 documents as+ double-sending (or hard-failing) from the second call onward, because+ langchain caches one ``httpx.AsyncClient`` per process and its+ keep-alive connections are bound to the loop that opened them.+* ``ainvoke_llm`` must await ``.ainvoke`` and must never quietly degrade+ to the sync client, so a misconfigured wrapper is a loud error rather+ than a silent change of transport.+"""++import asyncio+import inspect++import pytest++from local_deep_research.utilities import llm_utils+from local_deep_research.utilities.llm_utils import ainvoke_llm, invoke_llm_sync+++class _LoopTripwire(BaseException):+ """Raised if the helper touches the event loop machinery.++ Derived from ``BaseException`` rather than ``Exception`` so the broad+ ``except Exception`` handlers around production call sites cannot+ swallow it if this stub is ever reused there.+ """+++class _RecordingLLM:+ """Stub model recording both transports separately."""++ def __init__(self, result="response"):+ self.result = result+ self.invoke_calls = []+ self.ainvoke_calls = []++ def invoke(self, prompt):+ self.invoke_calls.append(prompt)+ return self.result++ async def ainvoke(self, prompt):+ self.ainvoke_calls.append(prompt)+ return self.result+++class _SyncOnlyLLM:+ """A wrapped object that never got an ``ainvoke`` — a config error."""++ def __init__(self):+ self.invoke_calls = []++ def invoke(self, prompt):+ self.invoke_calls.append(prompt)+ return "sync"+++def no_event_loop(monkeypatch):+ """Trip if anything starts or creates an event loop."""++ def _tripwire(*args, **kwargs):+ raise _LoopTripwire("the sync helper started an event loop")++ monkeypatch.setattr(asyncio, "run", _tripwire)+ monkeypatch.setattr(asyncio, "new_event_loop", _tripwire)+ monkeypatch.setattr(asyncio.events, "new_event_loop", _tripwire)+ return _tripwire+++def test_invoke_llm_sync_uses_the_sync_client_only(no_event_loop):+ """It calls ``.invoke``, leaves ``.ainvoke`` untouched, starts no loop."""+ llm = _RecordingLLM(result="answer")++ assert invoke_llm_sync(llm, "prompt") == "answer"++ assert llm.invoke_calls == ["prompt"]+ assert llm.ainvoke_calls == [], (+ "invoke_llm_sync reached the async client; that is the #6293 "+ "loop-bound-client hazard"+ )+++def test_invoke_llm_sync_second_consecutive_call_succeeds(no_event_loop):+ """The failure mode #6293 describes only shows up on call #2.++ A per-call ``asyncio.run`` bridge passes a single-call test and then+ raises ``RuntimeError: Event loop is closed`` on the next one, so the+ second call is the assertion that matters.+ """+ llm = _RecordingLLM(result="answer")++ assert invoke_llm_sync(llm, "first") == "answer"+ assert invoke_llm_sync(llm, "second") == "answer"++ assert llm.invoke_calls == ["first", "second"]+ assert llm.ainvoke_calls == []+++def test_invoke_llm_sync_returns_the_raw_response(no_event_loop):+ """No unwrapping: callers do their own ``.content`` / JSON parsing."""+ sentinel = object()+ llm = _RecordingLLM(result=sentinel)++ assert invoke_llm_sync(llm, "prompt") is sentinel+++def test_invoke_llm_sync_propagates_model_errors(no_event_loop):+ """Errors reach the caller's own except-block unchanged."""++ class _Boom:+ def invoke(self, prompt):+ raise ValueError("model exploded")++ with pytest.raises(ValueError, match="model exploded"):+ invoke_llm_sync(_Boom(), "prompt")+++def test_invoke_llm_sync_works_inside_a_running_loop():+ """Callable from a coroutine (``news_strategy.analyze_findings``).++ A sync call is legal there; ``asyncio.run`` inside a running loop is+ not, which is the second reason the helper stays on ``.invoke``.+ """+ llm = _RecordingLLM(result="answer")++ async def _driver():+ return invoke_llm_sync(llm, "prompt")++ assert asyncio.run(_driver()) == "answer"+ assert llm.invoke_calls == ["prompt"]+ assert llm.ainvoke_calls == []+++def test_invoke_llm_sync_is_not_a_coroutine_function():+ """Guards against the helper being turned back into an async bridge."""+ assert not inspect.iscoroutinefunction(invoke_llm_sync)+++async def test_ainvoke_llm_awaits_the_async_client():+ """The async core awaits ``.ainvoke`` and never touches ``.invoke``."""+ llm = _RecordingLLM(result="answer")++ assert await ainvoke_llm(llm, "prompt") == "answer"++ assert llm.ainvoke_calls == ["prompt"]+ assert llm.invoke_calls == [], (+ "ainvoke_llm fell back to the sync client; a transport change "+ "must not happen silently"+ )+++async def test_ainvoke_llm_returns_the_raw_response():+ sentinel = object()+ llm = _RecordingLLM(result=sentinel)++ assert await ainvoke_llm(llm, "prompt") is sentinel+++async def test_ainvoke_llm_raises_when_the_model_has_no_ainvoke():+ """A sync-only object is a configuration error, not a fallback.++ Every production model is a ``ProcessingLLMWrapper``, which always+ defines ``ainvoke``. Falling back to ``.invoke`` here would block the+ awaiting loop and hide the misconfiguration.+ """+ llm = _SyncOnlyLLM()++ with pytest.raises(AttributeError):+ await ainvoke_llm(llm, "prompt")++ assert llm.invoke_calls == []+++def test_helpers_are_exported():+ """Both names are part of the module's public surface."""+ assert "invoke_llm_sync" in llm_utils.__all__+ assert "ainvoke_llm" in llm_utils.__all__diff --git a/tests/web_search_engines/rate_limiting/test_llm_wrapper_pure_logic.py b/tests/web_search_engines/rate_limiting/test_llm_wrapper_pure_logic.pyindex e3e791d757..520c0f2e21 100644--- a/tests/web_search_engines/rate_limiting/test_llm_wrapper_pure_logic.py+++ b/tests/web_search_engines/rate_limiting/test_llm_wrapper_pure_logic.py@@ -6,6 +6,7 @@ Tests cover:parsing, model name cleaning"""+import tracebackimport typesimport pytest@@ -268,6 +269,51 @@ class TestAinvoke:with pytest.raises(RateLimitError):await w.ainvoke("prompt")+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "credential_template",+ [+ "Authorization: Bearer {secret}",+ "x-api-key: {secret}",+ "https://synthetic-user:{secret}@example.invalid/path",+ "https://example.invalid/path?api_key={secret}",+ ],+ )+ async def test_ainvoke_scrubs_credentials_and_exception_context(+ self, credential_template+ ):+ """Catch removal of either scrubbing or exception-chain suppression.++ Checking RateLimitError alone would still pass after either revert.+ The provider's retry hint must survive credential removal.+ """+ from local_deep_research.web_search_engines.rate_limiting.exceptions import (+ RateLimitError,+ )++ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ extract_retry_after,+ )++ secret = "SyntheticCredential6277"+ provider_message = (+ "429 Too Many Requests: retry after 7 seconds; "+ + credential_template.format(secret=secret)+ )+ llm = _make_llm(+ ainvoke=AsyncMock(side_effect=RuntimeError(provider_message))+ )+ w = _wrapper(llm=llm, provider="openai")+ with pytest.raises(RateLimitError) as caught:+ await w.ainvoke("synthetic prompt")++ error = caught.value+ assert secret not in str(error)+ assert secret not in "".join(traceback.format_exception(error))+ assert error.__suppress_context__ is True+ assert extract_retry_after(error) == 7+ llm.ainvoke.assert_awaited_once_with("synthetic prompt")+@pytest.mark.asyncioasync def test_ainvoke_passes_non_rate_limit_errors_through(self):"""Ordinary failures surface unchanged (no RateLimitError wrapping)."""