Skip to content

~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.

perf(news,benchmarks): async cores for news generators, analyzer and benchmark graders — tranche 2 of #5854 (#6246)

LearningCircuit1152fed3455b
diff --git a/changelog.d/6246.misc.md b/changelog.d/6246.misc.md
new file mode 100644
index 0000000000..c2b83202ac
--- /dev/null
+++ b/changelog.d/6246.misc.md
@@ -0,0 +1 @@
+News headline/topic generation and benchmark grading now expose async entry points that await `ainvoke`; existing synchronous entry points continue to use `invoke`. Both paths normalize text from supported content-block responses. NewsAnalyzer methods are now async and preserve the supplied settings snapshot for nested topic generation. Adaptive retry remains disabled in production. Model construction and shared resource cleanup retain their existing behavior, so these async entry points do not guarantee that every operation is nonblocking. Part of #5854.
diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.py
index 326868413d..8c66abd72b 100644
--- a/src/local_deep_research/benchmarks/graders.py
+++ b/src/local_deep_research/benchmarks/graders.py
@@ -8,12 +8,14 @@ import json
from loguru import logger
from pathlib import Path
import re
+import time
from typing import Any, Callable, Dict, List, Optional
from langchain_core.messages.human import HumanMessage
from ..config.llm_config import get_llm
from ..llm.providers.base import normalize_provider
+from ..utilities.json_utils import get_llm_response_text
from .templates import BROWSECOMP_GRADER_TEMPLATE, SIMPLEQA_GRADER_TEMPLATE
@@ -144,6 +146,132 @@ def extract_answer_from_response(
}
+def _select_grader_template(dataset_type: str) -> str:
+ """Pick the grading template for a dataset type."""
+ return (
+ BROWSECOMP_GRADER_TEMPLATE
+ if dataset_type.lower() == "browsecomp"
+ else SIMPLEQA_GRADER_TEMPLATE
+ )
+
+
+def _build_grading_prompt(template: str, result_data: Dict[str, Any]) -> str:
+ """Format the grading prompt for one result."""
+ return template.format(
+ question=result_data.get("problem", ""),
+ correct_answer=result_data.get("correct_answer", ""),
+ response=result_data.get("response", ""),
+ )
+
+
+def _call_grader_llm(evaluation_llm, grading_prompt: str):
+ """Invoke synchronously and normalize supported text/content-block responses."""
+ if hasattr(evaluation_llm, "invoke") and callable(evaluation_llm.invoke):
+ prompt = (
+ [HumanMessage(content=grading_prompt)]
+ if hasattr(evaluation_llm, "chat_messages")
+ else grading_prompt
+ )
+ response = evaluation_llm.invoke(prompt)
+ else:
+ response = evaluation_llm(grading_prompt)
+ return get_llm_response_text(response)
+
+
+async def _acall_grader_llm(evaluation_llm, grading_prompt: str):
+ """Await the async interface, retaining the injected sync-only fallback."""
+ if hasattr(evaluation_llm, "ainvoke") and callable(evaluation_llm.ainvoke):
+ prompt = (
+ [HumanMessage(content=grading_prompt)]
+ if hasattr(evaluation_llm, "chat_messages")
+ else grading_prompt
+ )
+ response = await evaluation_llm.ainvoke(prompt)
+ return get_llm_response_text(response)
+ return _call_grader_llm(evaluation_llm, grading_prompt)
+
+
+def _parse_grading_response(
+ grading_response: str, dataset_type: str
+) -> Dict[str, Any]:
+ """Extract the grading fields from the grader's raw response."""
+ if dataset_type.lower() == "browsecomp":
+ # BrowseComp-specific extraction
+ extracted_answer_match = re.search(
+ r"extracted_final_answer:\s*(.*?)(?:\n|$)", grading_response
+ )
+ extracted_answer = (
+ extracted_answer_match.group(1).strip()
+ if extracted_answer_match
+ else "None"
+ )
+
+ reasoning_match = re.search(
+ r"reasoning:\s*(.*?)(?:\n\n|\ncorrect:|\Z)",
+ grading_response,
+ re.DOTALL,
+ )
+ reasoning = reasoning_match.group(1).strip() if reasoning_match else ""
+
+ correct_match = re.search(
+ r"correct:\s*(yes|no)", grading_response, re.IGNORECASE
+ )
+ is_correct = (
+ (correct_match.group(1).lower() == "yes")
+ if correct_match
+ else False
+ )
+
+ confidence_match = re.search(r"confidence:\s*(\d+)", grading_response)
+ confidence = confidence_match.group(1) if confidence_match else "100"
+ else:
+ # SimpleQA extraction
+ extracted_answer_match = re.search(
+ r"Extracted Answer:\s*(.*?)(?:\n|$)", grading_response
+ )
+ extracted_answer = (
+ extracted_answer_match.group(1).strip()
+ if extracted_answer_match
+ else "None"
+ )
+
+ reasoning_match = re.search(
+ r"Reasoning:\s*(.*?)(?:\nCorrect:|\Z)",
+ grading_response,
+ re.DOTALL,
+ )
+ reasoning = reasoning_match.group(1).strip() if reasoning_match else ""
+
+ correct_match = re.search(
+ r"Correct:\s*(yes|no)", grading_response, re.IGNORECASE
+ )
+ is_correct = (
+ (correct_match.group(1).lower() == "yes")
+ if correct_match
+ else False
+ )
+
+ confidence = "100" # SimpleQA doesn't have confidence
+
+ return {
+ "extracted_by_grader": extracted_answer,
+ "reasoning": reasoning,
+ "is_correct": is_correct,
+ "graded_confidence": confidence,
+ "grader_response": grading_response,
+ }
+
+
+def _grading_error_result(exc: Exception) -> Dict[str, Any]:
+ """Build the single-result payload for a failed grading call."""
+ return {
+ "grading_error": str(exc),
+ "is_correct": False,
+ "graded_confidence": "0",
+ "grader_response": f"Grading failed: {exc!s}",
+ }
+
+
def grade_single_result(
result_data: Dict[str, Any],
dataset_type: str = "simpleqa",
@@ -153,6 +281,11 @@ def grade_single_result(
"""
Grade a single benchmark result using LLM.
+ The synchronous entry point uses ``invoke`` without running the async
+ core on a temporary event loop. Callers already on an event loop can
+ await the corresponding ``_async`` entry point. Resource cleanup uses
+ the shared close helper; it is separate from invocation dispatch.
+
Args:
result_data: Dictionary containing result data with keys: id, problem, correct_answer, response, extracted_answer
dataset_type: Type of dataset
@@ -166,142 +299,78 @@ def grade_single_result(
evaluation_llm = get_evaluation_llm(evaluation_config, settings_snapshot)
try:
- # Select appropriate template
- template = (
- BROWSECOMP_GRADER_TEMPLATE
- if dataset_type.lower() == "browsecomp"
- else SIMPLEQA_GRADER_TEMPLATE
- )
-
- question = result_data.get("problem", "")
- correct_answer = result_data.get("correct_answer", "")
- response = result_data.get("response", "")
-
- logger.info(f"Grading single result: {question[:50]}...")
-
- # Format grading prompt
- grading_prompt = template.format(
- question=question, correct_answer=correct_answer, response=response
- )
-
- import time
+ grading_prompt = _start_single_grading(result_data, dataset_type)
eval_llm_start = time.time()
- logger.info(
- f"Starting grading LLM call (prompt length: {len(grading_prompt)} chars)..."
- )
+ grading_response = _call_grader_llm(evaluation_llm, grading_prompt)
+ _log_grading_call_done(eval_llm_start)
- # Grade using LLM
- if hasattr(evaluation_llm, "invoke") and callable(
- evaluation_llm.invoke
- ):
- if hasattr(evaluation_llm, "chat_messages"):
- # Handle ChatOpenAI and similar models that use messages
- grading_response = evaluation_llm.invoke(
- [HumanMessage(content=grading_prompt)]
- ).content
- else:
- # Handle other LLM types
- grading_response = evaluation_llm.invoke(grading_prompt)
- if hasattr(grading_response, "content"):
- grading_response = grading_response.content
- else:
- # Fallback for other LLM interfaces
- grading_response = str(evaluation_llm(grading_prompt))
-
- eval_llm_elapsed = time.time() - eval_llm_start
- logger.info(f"Grading LLM call completed in {eval_llm_elapsed:.2f}s")
+ return _parse_grading_response(grading_response, dataset_type)
- # Extract grading information using regex
- if dataset_type.lower() == "browsecomp":
- # BrowseComp-specific extraction
- extracted_answer_match = re.search(
- r"extracted_final_answer:\s*(.*?)(?:\n|$)", grading_response
- )
- extracted_answer = (
- extracted_answer_match.group(1).strip()
- if extracted_answer_match
- else "None"
- )
+ except Exception as e:
+ logger.exception("Error grading single result")
+ return _grading_error_result(e)
+ finally:
+ from ..utilities.resource_utils import safe_close
- reasoning_match = re.search(
- r"reasoning:\s*(.*?)(?:\n\n|\ncorrect:|\Z)",
- grading_response,
- re.DOTALL,
- )
- reasoning = (
- reasoning_match.group(1).strip() if reasoning_match else ""
- )
+ safe_close(evaluation_llm, "grader LLM")
- correct_match = re.search(
- r"correct:\s*(yes|no)", grading_response, re.IGNORECASE
- )
- is_correct = (
- (correct_match.group(1).lower() == "yes")
- if correct_match
- else False
- )
- confidence_match = re.search(
- r"confidence:\s*(\d+)", grading_response
- )
- confidence = (
- confidence_match.group(1) if confidence_match else "100"
- )
- else:
- # SimpleQA extraction
- extracted_answer_match = re.search(
- r"Extracted Answer:\s*(.*?)(?:\n|$)", grading_response
- )
- extracted_answer = (
- extracted_answer_match.group(1).strip()
- if extracted_answer_match
- else "None"
- )
+async def grade_single_result_async(
+ result_data: Dict[str, Any],
+ dataset_type: str = "simpleqa",
+ evaluation_config: Optional[Dict[str, Any]] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+) -> Dict[str, Any]:
+ """Async core of :func:`grade_single_result`: one awaited ainvoke (#5854).
- reasoning_match = re.search(
- r"Reasoning:\s*(.*?)(?:\nCorrect:|\Z)",
- grading_response,
- re.DOTALL,
- )
- reasoning = (
- reasoning_match.group(1).strip() if reasoning_match else ""
- )
+ For callers that already run on an event loop. Mirrors the sync
+ entry point; only the LLM call line differs.
+ """
+ # Get evaluation LLM
+ evaluation_llm = get_evaluation_llm(evaluation_config, settings_snapshot)
- correct_match = re.search(
- r"Correct:\s*(yes|no)", grading_response, re.IGNORECASE
- )
- is_correct = (
- (correct_match.group(1).lower() == "yes")
- if correct_match
- else False
- )
+ try:
+ grading_prompt = _start_single_grading(result_data, dataset_type)
- confidence = "100" # SimpleQA doesn't have confidence
+ eval_llm_start = time.time()
+ grading_response = await _acall_grader_llm(
+ evaluation_llm, grading_prompt
+ )
+ _log_grading_call_done(eval_llm_start)
- # Format graded result
- return {
- "extracted_by_grader": extracted_answer,
- "reasoning": reasoning,
- "is_correct": is_correct,
- "graded_confidence": confidence,
- "grader_response": grading_response,
- }
+ return _parse_grading_response(grading_response, dataset_type)
except Exception as e:
logger.exception("Error grading single result")
- return {
- "grading_error": str(e),
- "is_correct": False,
- "graded_confidence": "0",
- "grader_response": f"Grading failed: {e!s}",
- }
+ return _grading_error_result(e)
finally:
from ..utilities.resource_utils import safe_close
safe_close(evaluation_llm, "grader LLM")
+def _start_single_grading(
+ result_data: Dict[str, Any], dataset_type: str
+) -> str:
+ """Log the start of a single grading call and build its prompt."""
+ template = _select_grader_template(dataset_type)
+ question = result_data.get("problem", "")
+ logger.info(f"Grading single result: {question[:50]}...")
+
+ grading_prompt = _build_grading_prompt(template, result_data)
+ logger.info(
+ f"Starting grading LLM call (prompt length: {len(grading_prompt)} chars)..."
+ )
+ return grading_prompt
+
+
+def _log_grading_call_done(eval_llm_start: float) -> None:
+ """Log how long the grading LLM call took."""
+ eval_llm_elapsed = time.time() - eval_llm_start
+ logger.info(f"Grading LLM call completed in {eval_llm_elapsed:.2f}s")
+
+
def grade_results(
results_file: str,
output_file: str,
@@ -313,6 +382,11 @@ def grade_results(
"""
Grade benchmark results using LLM.
+ This synchronous entry point calls the grader through ``invoke``
+ without running the async core on a temporary loop. Shared resource
+ cleanup retains its existing behavior. Callers already on a loop
+ should await :func:`grade_results_async` instead.
+
Args:
results_file: Path to results file
output_file: Path to save graded results
@@ -321,8 +395,8 @@ def grade_results(
progress_callback: Optional callback for progress updates
settings_snapshot: Optional snapshot so the grader LLM is
constructed under the user's egress policy. Without it
- the LLM PEP's snapshot guard skips and the grader can
- silently reach a cloud LLM under require_local_endpoint.
+ the LLM PEP takes its snapshot-less path, which fails
+ closed with PolicyDeniedError for any non-local provider.
Returns:
List of graded results
@@ -344,22 +418,39 @@ def grade_results(
safe_close(evaluation_llm, "grader LLM")
-def _grade_results_inner(
- evaluation_llm,
+async def grade_results_async(
results_file: str,
output_file: str,
- dataset_type: str,
- progress_callback: Optional[Callable[[int, int, Dict], None]],
+ dataset_type: str = "simpleqa",
+ evaluation_config: Optional[Dict[str, Any]] = None,
+ progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
- """Inner implementation of grade_results, separated for cleanup."""
- # Select appropriate template
- template = (
- BROWSECOMP_GRADER_TEMPLATE
- if dataset_type.lower() == "browsecomp"
- else SIMPLEQA_GRADER_TEMPLATE
- )
+ """Async core of :func:`grade_results`: awaited ainvoke calls (#5854).
- # Load results
+ For callers that already run on an event loop.
+ """
+ # Get evaluation LLM
+ evaluation_llm = get_evaluation_llm(evaluation_config, settings_snapshot)
+
+ try:
+ return await _grade_results_inner_async(
+ evaluation_llm,
+ results_file,
+ output_file,
+ dataset_type,
+ progress_callback,
+ )
+ finally:
+ from ..utilities.resource_utils import safe_close
+
+ safe_close(evaluation_llm, "grader LLM")
+
+
+def _load_results_for_grading(
+ results_file: str, output_file: str
+) -> List[Dict[str, Any]]:
+ """Load the results to grade and clear any previous output file."""
results = []
with open(results_file, "r", encoding="utf-8") as f:
for line in f:
@@ -371,176 +462,216 @@ def _grade_results_inner(
if output_path.exists():
output_path.unlink()
- graded_results = []
- correct_count = 0
+ return results
- # Process each result
- for idx, result in enumerate(results):
- question = result.get("problem", "")
- correct_answer = result.get("correct_answer", "")
- response = result.get("response", "")
- # Call progress callback if provided
- if progress_callback:
- progress_callback(
- idx,
- len(results),
- {"status": "grading", "index": idx, "total": len(results)},
- )
+def _append_graded_line(output_file: str, payload: Dict[str, Any]) -> None:
+ """Append one graded (or errored) result to the output file."""
+ with open(output_file, "a", encoding="utf-8") as f:
+ f.write(json.dumps(payload) + "\n")
- logger.info(f"Grading {idx + 1}/{len(results)}: {question[:50]}...")
- # Format grading prompt
- grading_prompt = template.format(
- question=question, correct_answer=correct_answer, response=response
+def _start_batch_item(
+ template: str,
+ result: Dict[str, Any],
+ idx: int,
+ total: int,
+ progress_callback: Optional[Callable[[int, int, Dict], None]],
+) -> str:
+ """Report progress for one batch item and build its grading prompt."""
+ # Call progress callback if provided
+ if progress_callback:
+ progress_callback(
+ idx,
+ total,
+ {"status": "grading", "index": idx, "total": total},
)
- try:
- # Grade using LLM
- if hasattr(evaluation_llm, "invoke") and callable(
- evaluation_llm.invoke
- ):
- if hasattr(evaluation_llm, "chat_messages"):
- # Handle ChatOpenAI and similar models that use messages
- grading_response = evaluation_llm.invoke(
- [HumanMessage(content=grading_prompt)]
- ).content
- else:
- # Handle other LLM types
- grading_response = evaluation_llm.invoke(grading_prompt)
- if hasattr(grading_response, "content"):
- grading_response = grading_response.content
- else:
- # Fallback for other LLM interfaces
- grading_response = str(evaluation_llm(grading_prompt))
-
- # Extract grading information using regex
- if dataset_type.lower() == "browsecomp":
- # BrowseComp-specific extraction
- extracted_answer_match = re.search(
- r"extracted_final_answer:\s*(.*?)(?:\n|$)", grading_response
- )
- extracted_answer = (
- extracted_answer_match.group(1).strip()
- if extracted_answer_match
- else "None"
- )
+ question = result.get("problem", "")
+ logger.info(f"Grading {idx + 1}/{total}: {question[:50]}...")
- reasoning_match = re.search(
- r"reasoning:\s*(.*?)(?:\n\n|\ncorrect:|\Z)",
- grading_response,
- re.DOTALL,
- )
- reasoning = (
- reasoning_match.group(1).strip() if reasoning_match else ""
- )
+ return _build_grading_prompt(template, result)
- correct_match = re.search(
- r"correct:\s*(yes|no)", grading_response, re.IGNORECASE
- )
- is_correct = (
- (correct_match.group(1).lower() == "yes")
- if correct_match
- else False
- )
- confidence_match = re.search(
- r"confidence:\s*(\d+)", grading_response
- )
- confidence = (
- confidence_match.group(1) if confidence_match else "100"
- )
- else:
- # SimpleQA extraction
- extracted_answer_match = re.search(
- r"Extracted Answer:\s*(.*?)(?:\n|$)", grading_response
- )
- extracted_answer = (
- extracted_answer_match.group(1).strip()
- if extracted_answer_match
- else "None"
- )
+def _finish_batch_item(
+ result: Dict[str, Any],
+ grading_response: str,
+ dataset_type: str,
+ output_file: str,
+ idx: int,
+ total: int,
+ progress_callback: Optional[Callable[[int, int, Dict], None]],
+ graded_results: List[Dict[str, Any]],
+) -> bool:
+ """Parse, record and report one successfully graded batch item."""
+ parsed = _parse_grading_response(grading_response, dataset_type)
+ is_correct = parsed["is_correct"]
+
+ # Format graded result
+ graded_result = result.copy()
+ graded_result.update(parsed)
+
+ graded_results.append(graded_result)
+
+ # Write to output file
+ _append_graded_line(output_file, graded_result)
+
+ # Call progress callback if provided
+ if progress_callback:
+ progress_callback(
+ idx,
+ total,
+ {
+ "status": "graded",
+ "is_correct": is_correct,
+ "result": graded_result,
+ },
+ )
- reasoning_match = re.search(
- r"Reasoning:\s*(.*?)(?:\nCorrect:|\Z)",
- grading_response,
- re.DOTALL,
- )
- reasoning = (
- reasoning_match.group(1).strip() if reasoning_match else ""
- )
+ return is_correct
- correct_match = re.search(
- r"Correct:\s*(yes|no)", grading_response, re.IGNORECASE
- )
- is_correct = (
- (correct_match.group(1).lower() == "yes")
- if correct_match
- else False
- )
- confidence = "100" # SimpleQA doesn't have confidence
+def _fail_batch_item(
+ result: Dict[str, Any],
+ exc: Exception,
+ output_file: str,
+ idx: int,
+ total: int,
+ progress_callback: Optional[Callable[[int, int, Dict], None]],
+ graded_results: List[Dict[str, Any]],
+) -> None:
+ """Record and report one batch item whose grading raised."""
+ # Handle error
+ error_result = result.copy()
+ error_result["grading_error"] = str(exc)
+
+ _append_graded_line(output_file, error_result)
+
+ graded_results.append(error_result)
+
+ # Call progress callback if provided
+ if progress_callback:
+ progress_callback(
+ idx,
+ total,
+ {
+ "status": "error",
+ "error": str(exc),
+ "result": error_result,
+ },
+ )
- if is_correct:
- correct_count += 1
- # Format graded result
- graded_result = result.copy()
- graded_result.update(
- {
- "extracted_by_grader": extracted_answer,
- "reasoning": reasoning,
- "is_correct": is_correct,
- "graded_confidence": confidence,
- "grader_response": grading_response,
- }
- )
+def _log_grading_summary(correct_count: int, total: int) -> None:
+ """Log the final accuracy of a grading run."""
+ accuracy = correct_count / total if total else 0
+ logger.info(f"Grading complete. Accuracy: {accuracy:.3f}")
+ logger.info(f"Correct: {correct_count}/{total}")
- graded_results.append(graded_result)
-
- # Write to output file
- with open(output_file, "a", encoding="utf-8") as f:
- f.write(json.dumps(graded_result) + "\n")
-
- # Call progress callback if provided
- if progress_callback:
- progress_callback(
- idx,
- len(results),
- {
- "status": "graded",
- "is_correct": is_correct,
- "result": graded_result,
- },
- )
+def _grade_results_inner(
+ evaluation_llm,
+ results_file: str,
+ output_file: str,
+ dataset_type: str,
+ progress_callback: Optional[Callable[[int, int, Dict], None]],
+) -> List[Dict[str, Any]]:
+ """Inner implementation of grade_results, separated for cleanup."""
+ template = _select_grader_template(dataset_type)
+ results = _load_results_for_grading(results_file, output_file)
+
+ graded_results: List[Dict[str, Any]] = []
+ correct_count = 0
+ total = len(results)
+
+ # Process each result
+ for idx, result in enumerate(results):
+ grading_prompt = _start_batch_item(
+ template, result, idx, total, progress_callback
+ )
+
+ try:
+ grading_response = _call_grader_llm(evaluation_llm, grading_prompt)
+ if _finish_batch_item(
+ result,
+ grading_response,
+ dataset_type,
+ output_file,
+ idx,
+ total,
+ progress_callback,
+ graded_results,
+ ):
+ correct_count += 1
except Exception as e:
logger.exception(f"Error grading result {idx + 1}")
+ _fail_batch_item(
+ result,
+ e,
+ output_file,
+ idx,
+ total,
+ progress_callback,
+ graded_results,
+ )
- # Handle error
- error_result = result.copy()
- error_result["grading_error"] = str(e)
-
- with open(output_file, "a", encoding="utf-8") as f:
- f.write(json.dumps(error_result) + "\n")
-
- graded_results.append(error_result)
-
- # Call progress callback if provided
- if progress_callback:
- progress_callback(
- idx,
- len(results),
- {
- "status": "error",
- "error": str(e),
- "result": error_result,
- },
- )
+ _log_grading_summary(correct_count, total)
- accuracy = correct_count / len(results) if results else 0
- logger.info(f"Grading complete. Accuracy: {accuracy:.3f}")
- logger.info(f"Correct: {correct_count}/{len(results)}")
+ return graded_results
+
+
+async def _grade_results_inner_async(
+ evaluation_llm,
+ results_file: str,
+ output_file: str,
+ dataset_type: str,
+ progress_callback: Optional[Callable[[int, int, Dict], None]],
+) -> List[Dict[str, Any]]:
+ """Async counterpart of :func:`_grade_results_inner`.
+
+ Only the LLM call line differs.
+ """
+ template = _select_grader_template(dataset_type)
+ results = _load_results_for_grading(results_file, output_file)
+
+ graded_results: List[Dict[str, Any]] = []
+ correct_count = 0
+ total = len(results)
+
+ # Process each result
+ for idx, result in enumerate(results):
+ grading_prompt = _start_batch_item(
+ template, result, idx, total, progress_callback
+ )
+
+ try:
+ grading_response = await _acall_grader_llm(
+ evaluation_llm, grading_prompt
+ )
+ if _finish_batch_item(
+ result,
+ grading_response,
+ dataset_type,
+ output_file,
+ idx,
+ total,
+ progress_callback,
+ graded_results,
+ ):
+ correct_count += 1
+ except Exception as e:
+ logger.exception(f"Error grading result {idx + 1}")
+ _fail_batch_item(
+ result,
+ e,
+ output_file,
+ idx,
+ total,
+ progress_callback,
+ graded_results,
+ )
+
+ _log_grading_summary(correct_count, total)
return graded_results
diff --git a/src/local_deep_research/news/core/news_analyzer.py b/src/local_deep_research/news/core/news_analyzer.py
index 3e8f767d44..662dff3a03 100644
--- a/src/local_deep_research/news/core/news_analyzer.py
+++ b/src/local_deep_research/news/core/news_analyzer.py
@@ -8,7 +8,7 @@ from datetime import datetime, timezone, UTC
from loguru import logger
from .utils import generate_card_id
-from ..utils.topic_generator import generate_topics
+from ..utils.topic_generator import generate_topics_async
from ...config.llm_config import get_llm
from ...utilities.json_utils import extract_json, get_llm_response_text
@@ -39,9 +39,12 @@ class NewsAnalyzer:
LLM is constructed under the user's egress policy. The
news scheduler runs in background threads without a
live request context, so without an explicit snapshot
- the PEP guard at the top of ``get_llm`` skips and a
- cloud LLM can fire under require_local_endpoint.
+ ``get_llm`` takes its snapshot-less path, which fails
+ closed with ``PolicyDeniedError`` for any non-local
+ provider — the analyzer cannot be constructed at all
+ instead of quietly reaching a cloud LLM.
"""
+ self._settings_snapshot = settings_snapshot
self._owns_llm = llm_client is None
self.llm_client = llm_client or get_llm(
settings_snapshot=settings_snapshot
@@ -54,7 +57,7 @@ class NewsAnalyzer:
if self._owns_llm:
safe_close(self.llm_client, "news analyzer LLM")
- def analyze_news(
+ async def analyze_news(
self, search_results: List[Dict[str, Any]]
) -> Dict[str, Any]:
"""
@@ -72,7 +75,7 @@ class NewsAnalyzer:
try:
# Step 1: Extract news items table
logger.debug("Extracting news items")
- news_items = self.extract_news_items(search_results)
+ news_items = await self.extract_news_items(search_results)
# Step 2: Generate overview components (separate LLM calls for modularity)
logger.debug("Generating analysis components")
@@ -85,12 +88,16 @@ class NewsAnalyzer:
if news_items:
# Each component is generated independently
- components["big_picture"] = self.generate_big_picture(
+ components["big_picture"] = await self.generate_big_picture(
news_items
)
- components["watch_for"] = self.generate_watch_for(news_items)
- components["patterns"] = self.generate_patterns(news_items)
- components["topics"] = self.extract_topics(news_items)
+ components["watch_for"] = await self.generate_watch_for(
+ news_items
+ )
+ components["patterns"] = await self.generate_patterns(
+ news_items
+ )
+ components["topics"] = await self.extract_topics(news_items)
components["categories"] = self._count_categories(news_items)
components["impact_summary"] = self._summarize_impact(
news_items
@@ -106,7 +113,7 @@ class NewsAnalyzer:
logger.exception("Error analyzing news")
return self._empty_analysis()
- def extract_news_items(
+ async def extract_news_items(
self, search_results: List[Dict[str, Any]], max_items: int = 10
) -> List[Dict[str, Any]]:
"""
@@ -149,7 +156,7 @@ Focus on genuinely newsworthy stories.
"""
try:
- response = self.llm_client.invoke(prompt)
+ response = await self.llm_client.ainvoke(prompt)
content = get_llm_response_text(response)
# Parse JSON response
@@ -170,7 +177,9 @@ Focus on genuinely newsworthy stories.
return []
- def generate_big_picture(self, news_items: List[Dict[str, Any]]) -> str:
+ async def generate_big_picture(
+ self, news_items: List[Dict[str, Any]]
+ ) -> str:
"""
Generate the big picture summary of how events connect.
@@ -202,14 +211,16 @@ News stories:
THE BIG PICTURE:"""
try:
- response = self.llm_client.invoke(prompt)
+ response = await self.llm_client.ainvoke(prompt)
content = get_llm_response_text(response)
return content.strip()
except Exception:
logger.exception("Error generating big picture")
return ""
- def generate_watch_for(self, news_items: List[Dict[str, Any]]) -> List[str]:
+ async def generate_watch_for(
+ self, news_items: List[Dict[str, Any]]
+ ) -> List[str]:
"""
Generate list of developments to watch for in next 24-48 hours.
@@ -247,7 +258,7 @@ WATCH FOR:
-"""
try:
- response = self.llm_client.invoke(prompt)
+ response = await self.llm_client.ainvoke(prompt)
content = get_llm_response_text(response)
# Parse bullet points
@@ -267,7 +278,7 @@ WATCH FOR:
logger.exception("Error generating watch items")
return []
- def generate_patterns(self, news_items: List[Dict[str, Any]]) -> str:
+ async def generate_patterns(self, news_items: List[Dict[str, Any]]) -> str:
"""
Identify emerging patterns from today's news.
@@ -306,14 +317,14 @@ Top headlines:
PATTERN RECOGNITION (1-2 sentences):"""
try:
- response = self.llm_client.invoke(prompt)
+ response = await self.llm_client.ainvoke(prompt)
content = get_llm_response_text(response)
return content.strip()
except Exception:
logger.exception("Error generating patterns")
return ""
- def extract_topics(
+ async def extract_topics(
self, news_items: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
"""
@@ -334,11 +345,12 @@ PATTERN RECOGNITION (1-2 sentences):"""
summary = item.get("summary", "")
category = item.get("category", "")
- extracted = generate_topics(
+ extracted = await generate_topics_async(
query=headline,
findings=summary,
category=category,
max_topics=3,
+ settings_snapshot=self._settings_snapshot,
)
for topic in extracted:
diff --git a/src/local_deep_research/news/utils/headline_generator.py b/src/local_deep_research/news/utils/headline_generator.py
index 4c6cf8874f..e1d712a715 100644
--- a/src/local_deep_research/news/utils/headline_generator.py
+++ b/src/local_deep_research/news/utils/headline_generator.py
@@ -3,9 +3,11 @@ Headline generation utilities for news items.
Uses LLM to generate concise, meaningful headlines from long queries and findings.
"""
-from typing import Optional
+from typing import Any, Optional
from loguru import logger
+from ...utilities.json_utils import get_llm_response_text
+
def generate_headline(
query: str,
@@ -16,15 +18,21 @@ def generate_headline(
"""
Generate a concise headline from a query and optional findings.
+ The synchronous entry point uses ``invoke`` without running the async
+ core on a temporary event loop. Callers already on an event loop can
+ await the corresponding ``_async`` entry point. Resource cleanup uses
+ the shared close helper; it is separate from invocation dispatch.
+
Args:
query: The search query or research question
findings: Optional findings/content to help generate better headline
max_length: Maximum length for the headline
settings_snapshot: Optional settings snapshot so the LLM call
picks up the active egress policy. Background callers
- should pass this through; without it, the LLM PEP's
- ``settings_snapshot is not None`` guard skips and a cloud
- LLM can fire even under require_local_endpoint.
+ should pass this through; without it ``get_llm`` takes its
+ snapshot-less path, which fails closed with
+ ``PolicyDeniedError`` for any non-local provider, so
+ headline generation fails rather than reaching a cloud LLM.
Returns:
A concise headline string
@@ -33,20 +41,87 @@ def generate_headline(
llm_headline = _generate_with_llm(
query, findings, max_length, settings_snapshot
)
+ return _finalize_headline(llm_headline)
+
+
+async def generate_headline_async(
+ query: str,
+ findings: str = "",
+ max_length: int = 100,
+ settings_snapshot: Optional[dict] = None,
+) -> str:
+ """Async core of generate_headline: one awaited ainvoke (#5854).
+
+ For callers that already run on an event loop. Applies the same
+ failure sentinel as :func:`generate_headline` via
+ :func:`_finalize_headline`.
+ """
+ llm_headline = await _generate_with_llm_async(
+ query, findings, max_length, settings_snapshot
+ )
+ return _finalize_headline(llm_headline)
+
+
+def _finalize_headline(llm_headline: Optional[str]) -> str:
+ """Apply the failure sentinel shared by both generate_headline paths."""
+ # No fallback - if LLM fails, indicate failure
if llm_headline:
return llm_headline
- # No fallback - if LLM fails, indicate failure
return "[Headline generation failed]"
+def _build_headline_prompt(findings: str) -> Optional[str]:
+ """Build the headline prompt, or None when there is nothing to summarize."""
+ # Focus only on the findings/report content, not the query
+ if not findings:
+ logger.debug("No findings provided for headline generation")
+ return None
+
+ # Use the COMPLETE findings - no character limit
+ findings_preview = findings
+ logger.debug(f"Generating headline with {len(findings)} chars of findings")
+
+ return f"""Generate a comprehensive news headline that captures the key events from the research report below.
+
+Research Findings:
+{findings_preview}
+
+Requirements:
+- Include MULTIPLE major events if several important things happened (e.g., "Earthquake Strikes California While Wildfires Rage; Global Markets Tumble Amid Political Tensions")
+- Capture as much important information as possible in the headline
+- Be specific about locations, impacts, and key details
+- Professional news headline style but can be longer to include more information
+- Focus on the most impactful findings from the report
+- Use semicolons or commas to separate multiple major events
+- No quotes or punctuation at start/end
+- Base the headline ONLY on the actual findings in the report
+
+Generate only the headline text, nothing else."""
+
+
+def _clean_headline(response: Any) -> Optional[str]:
+ """Clean and validate the headline the LLM returned."""
+ headline = get_llm_response_text(response).strip()
+
+ # Clean up the generated headline
+ headline = headline.strip("\"'.,!?")
+
+ # Validate the headline
+ if headline:
+ logger.debug(f"Generated headline: {headline}")
+ return headline
+
+ return None
+
+
def _generate_with_llm(
query: str,
findings: str,
max_length: int,
settings_snapshot: Optional[dict] = None,
) -> Optional[str]:
- """Generate headline using LLM."""
+ """Generate headline using LLM (sync path)."""
try:
from ...config.llm_config import get_llm
@@ -54,44 +129,46 @@ def _generate_with_llm(
llm = get_llm(temperature=0.3, settings_snapshot=settings_snapshot)
try:
- # Focus only on the findings/report content, not the query
- if not findings:
- logger.debug("No findings provided for headline generation")
+ prompt = _build_headline_prompt(findings)
+ if prompt is None:
return None
- # Use the COMPLETE findings - no character limit
- findings_preview = findings
- logger.debug(
- f"Generating headline with {len(findings)} chars of findings"
- )
+ response = llm.invoke(prompt)
+ return _clean_headline(response)
+ finally:
+ from ...utilities.resource_utils import safe_close
- prompt = f"""Generate a comprehensive news headline that captures the key events from the research report below.
+ safe_close(llm, "headline LLM")
-Research Findings:
-{findings_preview}
+ except Exception as e:
+ logger.debug(f"LLM headline generation failed: {e}")
-Requirements:
-- Include MULTIPLE major events if several important things happened (e.g., "Earthquake Strikes California While Wildfires Rage; Global Markets Tumble Amid Political Tensions")
-- Capture as much important information as possible in the headline
-- Be specific about locations, impacts, and key details
-- Professional news headline style but can be longer to include more information
-- Focus on the most impactful findings from the report
-- Use semicolons or commas to separate multiple major events
-- No quotes or punctuation at start/end
-- Base the headline ONLY on the actual findings in the report
+ return None
-Generate only the headline text, nothing else."""
- response = llm.invoke(prompt)
- headline: str = str(response.content).strip()
+async def _generate_with_llm_async(
+ query: str,
+ findings: str,
+ max_length: int,
+ settings_snapshot: Optional[dict] = None,
+) -> Optional[str]:
+ """Generate headline using LLM (async path).
- # Clean up the generated headline
- headline = headline.strip("\"'.,!?")
+ Mirrors :func:`_generate_with_llm`; only the LLM call line differs.
+ """
+ try:
+ from ...config.llm_config import get_llm
+
+ # Use the configured model for headline generation
+ llm = get_llm(temperature=0.3, settings_snapshot=settings_snapshot)
+
+ try:
+ prompt = _build_headline_prompt(findings)
+ if prompt is None:
+ return None
- # Validate the headline
- if headline:
- logger.debug(f"Generated headline: {headline}")
- return headline
+ response = await llm.ainvoke(prompt)
+ return _clean_headline(response)
finally:
from ...utilities.resource_utils import safe_close
diff --git a/src/local_deep_research/news/utils/topic_generator.py b/src/local_deep_research/news/utils/topic_generator.py
index 401f7bbe2e..dc95ba3673 100644
--- a/src/local_deep_research/news/utils/topic_generator.py
+++ b/src/local_deep_research/news/utils/topic_generator.py
@@ -4,7 +4,7 @@ Uses LLM to extract relevant topics/tags from news content.
"""
from loguru import logger
-from typing import List
+from typing import List, Optional
from ...utilities.json_utils import extract_json, get_llm_response_text
@@ -19,6 +19,11 @@ def generate_topics(
"""
Generate relevant topics/tags from news content.
+ The synchronous entry point uses ``invoke`` without running the async
+ core on a temporary event loop. Callers already on an event loop can
+ await the corresponding ``_async`` entry point. Resource cleanup uses
+ the shared close helper; it is separate from invocation dispatch.
+
Args:
query: The search query or research question
findings: The research findings/content
@@ -26,7 +31,10 @@ def generate_topics(
max_topics: Maximum number of topics to generate
settings_snapshot: User settings snapshot threaded to get_llm so
the LLM PEP (evaluate_llm_endpoint) fires under
- llm.require_local_endpoint. Mirrors headline_generator.py.
+ llm.require_local_endpoint. Without it get_llm takes its
+ snapshot-less path, which fails closed with
+ PolicyDeniedError for any non-local provider. Mirrors
+ headline_generator.py.
Returns:
List of topic strings
@@ -36,6 +44,29 @@ def generate_topics(
query, findings, category, max_topics, settings_snapshot
)
+ return _finalize_topics(topics, max_topics)
+
+
+async def generate_topics_async(
+ query: str,
+ findings: str = "",
+ category: str = "",
+ max_topics: int = 5,
+ settings_snapshot=None,
+) -> List[str]:
+ """Async core of generate_topics: one awaited ainvoke (#5854).
+
+ For callers that already run on an event loop.
+ """
+ topics = await _generate_with_llm_async(
+ query, findings, category, max_topics, settings_snapshot
+ )
+
+ return _finalize_topics(topics, max_topics)
+
+
+def _finalize_topics(topics: List[str], max_topics: int) -> List[str]:
+ """Apply the failure sentinel and validation shared by both paths."""
# No fallback - if LLM fails, mark as missing
if not topics:
topics = ["[Topic generation failed]"]
@@ -44,6 +75,66 @@ def generate_topics(
return _validate_topics(topics, max_topics)
+def _build_topic_prompt(
+ query: str,
+ findings: str,
+ category: str,
+ max_topics: int,
+) -> str:
+ """Build the topic-extraction prompt."""
+ # Prepare context
+ query_preview = query[:500] if len(query) > 500 else query
+ findings_preview = (
+ findings[:1000] if findings and len(findings) > 1000 else findings
+ )
+
+ return f"""Extract relevant topics/tags from this news content.
+
+Query: {query_preview}
+{f"Content: {findings_preview}" if findings_preview else ""}
+{f"Category: {category}" if category else ""}
+
+Generate {max_topics} specific, relevant topics that would help categorize and filter this news item.
+
+Requirements:
+- Each topic should be 1-3 words
+- Topics should be specific and meaningful
+- Include geographic regions if mentioned
+- Include key entities (countries, organizations, people)
+- Include event types (conflict, economy, disaster, etc.)
+- Topics should be diverse and cover different aspects
+
+Return ONLY a JSON array of topic strings, like: ["Topic 1", "Topic 2", "Topic 3"]"""
+
+
+def _parse_topics_response(
+ content: str, max_topics: int
+) -> Optional[List[str]]:
+ """Parse the LLM's topics response; None when nothing usable came back."""
+ # Try to parse the JSON response
+ topics = extract_json(content, expected_type=list)
+
+ if topics is not None:
+ # Clean and validate each topic
+ cleaned_topics = []
+ for topic in topics:
+ if isinstance(topic, str):
+ cleaned = topic.strip()
+ if cleaned and len(cleaned) <= 30: # Max topic length
+ cleaned_topics.append(cleaned)
+
+ logger.debug(f"Generated topics: {cleaned_topics}")
+ return cleaned_topics[:max_topics]
+
+ # Try to extract topics from plain text response
+ logger.debug(f"Failed to parse LLM topics as JSON: {content}")
+ if "," in content:
+ topics = [t.strip().strip("\"'") for t in content.split(",")]
+ return [t for t in topics if t and len(t) <= 30][:max_topics]
+
+ return None
+
+
def _generate_with_llm(
query: str,
findings: str,
@@ -51,7 +142,7 @@ def _generate_with_llm(
max_topics: int,
settings_snapshot=None,
) -> List[str]:
- """Generate topics using LLM."""
+ """Generate topics using LLM (sync path)."""
try:
from ...config.llm_config import get_llm
@@ -63,55 +154,55 @@ def _generate_with_llm(
llm = get_llm(temperature=0.5, settings_snapshot=settings_snapshot)
try:
- # Prepare context
- query_preview = query[:500] if len(query) > 500 else query
- findings_preview = (
- findings[:1000]
- if findings and len(findings) > 1000
- else findings
- )
+ prompt = _build_topic_prompt(query, findings, category, max_topics)
- prompt = f"""Extract relevant topics/tags from this news content.
+ response = llm.invoke(prompt)
+ content = get_llm_response_text(response)
-Query: {query_preview}
-{f"Content: {findings_preview}" if findings_preview else ""}
-{f"Category: {category}" if category else ""}
+ parsed = _parse_topics_response(content, max_topics)
+ if parsed is not None:
+ return parsed
+ finally:
+ from ...utilities.resource_utils import safe_close
-Generate {max_topics} specific, relevant topics that would help categorize and filter this news item.
+ safe_close(llm, "topic LLM")
-Requirements:
-- Each topic should be 1-3 words
-- Topics should be specific and meaningful
-- Include geographic regions if mentioned
-- Include key entities (countries, organizations, people)
-- Include event types (conflict, economy, disaster, etc.)
-- Topics should be diverse and cover different aspects
+ except Exception as e:
+ logger.debug(f"LLM topic generation failed: {e}")
-Return ONLY a JSON array of topic strings, like: ["Topic 1", "Topic 2", "Topic 3"]"""
+ return []
- response = llm.invoke(prompt)
+
+async def _generate_with_llm_async(
+ query: str,
+ findings: str,
+ category: str,
+ max_topics: int,
+ settings_snapshot=None,
+) -> List[str]:
+ """Generate topics using LLM (async path).
+
+ Mirrors :func:`_generate_with_llm`; only the LLM call line differs.
+ """
+ try:
+ from ...config.llm_config import get_llm
+
+ logger.debug(
+ f"Topic generation - findings length: {len(findings) if findings else 0}, category: {category}"
+ )
+
+ # Use the configured model for topic generation
+ llm = get_llm(temperature=0.5, settings_snapshot=settings_snapshot)
+
+ try:
+ prompt = _build_topic_prompt(query, findings, category, max_topics)
+
+ response = await llm.ainvoke(prompt)
content = get_llm_response_text(response)
- # Try to parse the JSON response
- topics = extract_json(content, expected_type=list)
-
- if topics is not None:
- # Clean and validate each topic
- cleaned_topics = []
- for topic in topics:
- if isinstance(topic, str):
- cleaned = topic.strip()
- if cleaned and len(cleaned) <= 30: # Max topic length
- cleaned_topics.append(cleaned)
-
- logger.debug(f"Generated topics: {cleaned_topics}")
- return cleaned_topics[:max_topics]
-
- # Try to extract topics from plain text response
- logger.debug(f"Failed to parse LLM topics as JSON: {content}")
- if "," in content:
- topics = [t.strip().strip("\"'") for t in content.split(",")]
- return [t for t in topics if t and len(t) <= 30][:max_topics]
+ parsed = _parse_topics_response(content, max_topics)
+ if parsed is not None:
+ return parsed
finally:
from ...utilities.resource_utils import safe_close
diff --git a/tests/benchmarks/test_graders_sync_async_paths.py b/tests/benchmarks/test_graders_sync_async_paths.py
new file mode 100644
index 0000000000..23241021f9
--- /dev/null
+++ b/tests/benchmarks/test_graders_sync_async_paths.py
@@ -0,0 +1,256 @@
+"""
+Path separation for the benchmark graders.
+
+``grade_single_result`` / ``grade_results`` are called from plain threads
+(the benchmark daemon, the CLI). They must reach the grader LLM through
+``invoke`` and must never create an event loop: langchain caches one async
+HTTP client per process and that client stays bound to the loop that first
+used it, so a throwaway ``asyncio.run`` loop leaves a closed-loop
+keep-alive connection behind and the provider SDK silently re-sends the
+request on the next call — every graded item billed twice.
+
+``grade_single_result_async`` / ``grade_results_async`` are the mirror
+image: they use ``ainvoke``.
+"""
+
+import asyncio
+import json
+from unittest.mock import AsyncMock, MagicMock, Mock, patch
+
+import pytest
+
+from local_deep_research.benchmarks.graders import (
+ grade_results,
+ grade_results_async,
+ grade_single_result,
+ grade_single_result_async,
+)
+
+RESULT = {
+ "id": "1",
+ "problem": "What is 2+2?",
+ "correct_answer": "4",
+ "response": "4",
+}
+
+SYNC_GRADE = "Extracted Answer: 4\nReasoning: sync\nCorrect: yes"
+ASYNC_GRADE = "Extracted Answer: 4\nReasoning: async\nCorrect: yes"
+
+
+def _dual_llm() -> MagicMock:
+ """A grader LLM exposing both interfaces so either could be chosen."""
+ llm = MagicMock()
+ del llm.chat_messages # take the plain-prompt sub-branch
+ llm.invoke.return_value = Mock(content=SYNC_GRADE)
+ llm.ainvoke = AsyncMock(return_value=Mock(content=ASYNC_GRADE))
+ return llm
+
+
+class _EventLoopCreated(AssertionError):
+ """Raised when the code under test tries to start an event loop."""
+
+
+def _no_event_loop():
+ """Patchers that make any attempt to start an event loop fail loudly."""
+ boom = Mock(
+ side_effect=_EventLoopCreated(
+ "the synchronous path must not create an event loop"
+ )
+ )
+ return (
+ patch("asyncio.run", boom),
+ patch("asyncio.new_event_loop", boom),
+ )
+
+
+def _write_results(tmp_path):
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text(json.dumps(RESULT) + "\n", encoding="utf-8")
+ return str(results_file), str(tmp_path / "graded.jsonl")
+
+
+class TestGradeSingleResultSyncPath:
+ """grade_single_result() stays on invoke and starts no event loop."""
+
+ def test_uses_invoke_and_not_ainvoke(self):
+ llm = _dual_llm()
+
+ with patch(
+ "local_deep_research.benchmarks.graders.get_evaluation_llm",
+ return_value=llm,
+ ):
+ graded = grade_single_result(RESULT)
+
+ assert graded["is_correct"] is True
+ assert graded["reasoning"] == "sync"
+ llm.invoke.assert_called_once()
+ llm.ainvoke.assert_not_called()
+
+ def test_starts_no_event_loop(self):
+ # spec without "ainvoke": the sync path may not even look for it.
+ llm = Mock(spec=["invoke", "close"])
+ llm.invoke.return_value = Mock(content=SYNC_GRADE)
+
+ run_patch, new_loop_patch = _no_event_loop()
+ with (
+ patch(
+ "local_deep_research.benchmarks.graders.get_evaluation_llm",
+ return_value=llm,
+ ),
+ run_patch,
+ new_loop_patch,
+ ):
+ graded = grade_single_result(RESULT)
+
+ assert graded["is_correct"] is True
+ assert "grading_error" not in graded
+
+ def test_chat_messages_sub_branch_without_ainvoke(self):
+ """A sync-only chat model still takes the HumanMessage sub-branch."""
+ from langchain_core.messages.human import HumanMessage
+
+ llm = Mock(spec=["invoke", "chat_messages"])
+ llm.invoke.return_value = Mock(content=SYNC_GRADE)
+
+ with patch(
+ "local_deep_research.benchmarks.graders.get_evaluation_llm",
+ return_value=llm,
+ ):
+ graded = grade_single_result(RESULT)
+
+ assert graded["is_correct"] is True
+ (messages,), _ = llm.invoke.call_args
+ assert isinstance(messages[0], HumanMessage)
+
+ def test_event_loop_guard_is_armed(self):
+ """The guard used above really does fire on asyncio.run()."""
+
+ async def _noop():
+ return None
+
+ coro = _noop()
+ run_patch, _ = _no_event_loop()
+ try:
+ with run_patch, pytest.raises(_EventLoopCreated):
+ asyncio.run(coro)
+ finally:
+ coro.close()
+
+
+class TestGradeSingleResultAsyncPath:
+ """grade_single_result_async() stays on ainvoke."""
+
+ def test_uses_ainvoke_and_not_invoke(self):
+ llm = _dual_llm()
+
+ with patch(
+ "local_deep_research.benchmarks.graders.get_evaluation_llm",
+ return_value=llm,
+ ):
+ graded = asyncio.run(grade_single_result_async(RESULT))
+
+ assert graded["reasoning"] == "async"
+ llm.ainvoke.assert_awaited_once()
+ llm.invoke.assert_not_called()
+
+
+class TestGradeResultsSyncPath:
+ """grade_results() stays on invoke and starts no event loop."""
+
+ def test_uses_invoke_and_not_ainvoke(self, tmp_path):
+ llm = _dual_llm()
+ results_file, output_file = _write_results(tmp_path)
+
+ with patch(
+ "local_deep_research.benchmarks.graders.get_evaluation_llm",
+ return_value=llm,
+ ):
+ graded = grade_results(results_file, output_file)
+
+ assert [g["reasoning"] for g in graded] == ["sync"]
+ llm.invoke.assert_called_once()
+ llm.ainvoke.assert_not_called()
+
+ def test_starts_no_event_loop(self, tmp_path):
+ llm = Mock(spec=["invoke", "close"])
+ llm.invoke.return_value = Mock(content=SYNC_GRADE)
+ results_file, output_file = _write_results(tmp_path)
+
+ run_patch, new_loop_patch = _no_event_loop()
+ with (
+ patch(
+ "local_deep_research.benchmarks.graders.get_evaluation_llm",
+ return_value=llm,
+ ),
+ run_patch,
+ new_loop_patch,
+ ):
+ graded = grade_results(results_file, output_file)
+
+ assert len(graded) == 1
+ assert "grading_error" not in graded[0]
+
+
+class TestGradeResultsAsyncPath:
+ """grade_results_async() stays on ainvoke."""
+
+ def test_uses_ainvoke_and_not_invoke(self, tmp_path):
+ llm = _dual_llm()
+ results_file, output_file = _write_results(tmp_path)
+
+ with patch(
+ "local_deep_research.benchmarks.graders.get_evaluation_llm",
+ return_value=llm,
+ ):
+ graded = asyncio.run(grade_results_async(results_file, output_file))
+
+ assert [g["reasoning"] for g in graded] == ["async"]
+ llm.ainvoke.assert_awaited_once()
+ llm.invoke.assert_not_called()
+
+
+class TestGradingErrorMarkerUnchanged:
+ """grade_single_result keeps its documented failure payload."""
+
+ def test_failure_payload(self):
+ llm = Mock(spec=["invoke", "close"])
+ llm.invoke.side_effect = RuntimeError("provider down")
+
+ with patch(
+ "local_deep_research.benchmarks.graders.get_evaluation_llm",
+ return_value=llm,
+ ):
+ graded = grade_single_result(RESULT)
+
+ assert graded["is_correct"] is False
+ assert graded["grading_error"] == "provider down"
+ assert graded["graded_confidence"] == "0"
+
+
[email protected]("asynchronous", [False, True])
[email protected]("chat_messages", [False, True])
+def test_structured_grade_uses_text_blocks(asynchronous, chat_messages):
+ llm = _dual_llm()
+ if chat_messages:
+ llm.chat_messages = []
+ content = [
+ {"type": "thinking", "thinking": "Correct: no"},
+ {"type": "text", "text": "Extracted Answer: 4\nReasoning: matches\n"},
+ {"type": "text", "text": "Correct: yes"},
+ ]
+ llm.invoke.return_value = Mock(content=content)
+ llm.ainvoke.return_value = Mock(content=content)
+ with patch(
+ "local_deep_research.benchmarks.graders.get_evaluation_llm",
+ return_value=llm,
+ ):
+ graded = (
+ asyncio.run(grade_single_result_async(RESULT))
+ if asynchronous
+ else grade_single_result(RESULT)
+ )
+ assert graded["is_correct"] is True
+ assert graded["extracted_by_grader"] == "4"
+ assert graded["reasoning"] == "matches"
+ assert "grading_error" not in graded
+ assert "Correct: no" not in graded["grader_response"]
diff --git a/tests/news/test_generators_sync_async_paths.py b/tests/news/test_generators_sync_async_paths.py
new file mode 100644
index 0000000000..f42b5e7638
--- /dev/null
+++ b/tests/news/test_generators_sync_async_paths.py
@@ -0,0 +1,234 @@
+"""
+Path separation for the news headline/topic generators.
+
+The synchronous entry points (``generate_headline`` / ``generate_topics``)
+must reach the LLM through ``invoke`` and must never create an event loop:
+langchain caches one async HTTP client per process, keyed only on
+base_url/timeout, and that client stays bound to the loop that first used
+it. Driving the async core on a throwaway ``asyncio.run`` loop therefore
+leaves a closed-loop keep-alive connection behind, and the provider SDK
+silently re-sends the request on the next call.
+
+The async cores (``*_async``) are the mirror image: they must use
+``ainvoke`` and never fall back to the blocking ``invoke``.
+"""
+
+import asyncio
+from unittest.mock import AsyncMock, MagicMock, Mock, patch
+
+import pytest
+
+from local_deep_research.news.utils.headline_generator import (
+ generate_headline,
+ generate_headline_async,
+)
+from local_deep_research.news.utils.topic_generator import (
+ generate_topics,
+ generate_topics_async,
+)
+
+
+def _dual_llm(sync_content: str, async_content: str) -> MagicMock:
+ """An LLM exposing both interfaces so either one could be chosen."""
+ llm = MagicMock()
+ llm.invoke.return_value = Mock(content=sync_content)
+ llm.ainvoke = AsyncMock(return_value=Mock(content=async_content))
+ return llm
+
+
+class _EventLoopCreated(AssertionError):
+ """Raised when the code under test tries to start an event loop."""
+
+
+def _no_event_loop():
+ """Patchers that make any attempt to start an event loop fail loudly."""
+ boom = Mock(
+ side_effect=_EventLoopCreated(
+ "the synchronous path must not create an event loop"
+ )
+ )
+ return (
+ patch("asyncio.run", boom),
+ patch("asyncio.new_event_loop", boom),
+ )
+
+
+class TestHeadlineSyncPath:
+ """generate_headline() stays on invoke and starts no event loop."""
+
+ def test_uses_invoke_and_not_ainvoke(self):
+ llm = _dual_llm("Sync Headline", "Async Headline")
+
+ with patch(
+ "local_deep_research.config.llm_config.get_llm", return_value=llm
+ ):
+ result = generate_headline(query="q", findings="some findings")
+
+ assert result == "Sync Headline"
+ llm.invoke.assert_called_once()
+ llm.ainvoke.assert_not_called()
+
+ def test_starts_no_event_loop(self):
+ # spec without "ainvoke": the sync path may not even look for it.
+ llm = Mock(spec=["invoke", "close"])
+ llm.invoke.return_value = Mock(content="Loop-free Headline")
+
+ run_patch, new_loop_patch = _no_event_loop()
+ with (
+ patch(
+ "local_deep_research.config.llm_config.get_llm",
+ return_value=llm,
+ ),
+ run_patch,
+ new_loop_patch,
+ ):
+ result = generate_headline(query="q", findings="some findings")
+
+ assert result == "Loop-free Headline"
+
+ def test_event_loop_guard_is_armed(self):
+ """The guard used above really does fire on asyncio.run()."""
+
+ async def _noop():
+ return None
+
+ coro = _noop()
+ run_patch, _ = _no_event_loop()
+ try:
+ with run_patch, pytest.raises(_EventLoopCreated):
+ asyncio.run(coro)
+ finally:
+ coro.close()
+
+
+class TestHeadlineAsyncPath:
+ """generate_headline_async() stays on ainvoke."""
+
+ def test_uses_ainvoke_and_not_invoke(self):
+ llm = _dual_llm("Sync Headline", "Async Headline")
+
+ with patch(
+ "local_deep_research.config.llm_config.get_llm", return_value=llm
+ ):
+ result = asyncio.run(
+ generate_headline_async(query="q", findings="some findings")
+ )
+
+ assert result == "Async Headline"
+ llm.ainvoke.assert_awaited_once()
+ llm.invoke.assert_not_called()
+
+
+class TestTopicsSyncPath:
+ """generate_topics() stays on invoke and starts no event loop."""
+
+ def test_uses_invoke_and_not_ainvoke(self):
+ llm = _dual_llm('["Sync Topic"]', '["Async Topic"]')
+
+ with patch(
+ "local_deep_research.config.llm_config.get_llm", return_value=llm
+ ):
+ result = generate_topics(query="q", findings="findings")
+
+ assert result == ["sync topic"]
+ llm.invoke.assert_called_once()
+ llm.ainvoke.assert_not_called()
+
+ def test_starts_no_event_loop(self):
+ llm = Mock(spec=["invoke", "close"])
+ llm.invoke.return_value = Mock(content='["Loop Free"]')
+
+ run_patch, new_loop_patch = _no_event_loop()
+ with (
+ patch(
+ "local_deep_research.config.llm_config.get_llm",
+ return_value=llm,
+ ),
+ run_patch,
+ new_loop_patch,
+ ):
+ result = generate_topics(query="q", findings="findings")
+
+ assert result == ["loop free"]
+
+
+class TestTopicsAsyncPath:
+ """generate_topics_async() stays on ainvoke."""
+
+ def test_uses_ainvoke_and_not_invoke(self):
+ llm = _dual_llm('["Sync Topic"]', '["Async Topic"]')
+
+ with patch(
+ "local_deep_research.config.llm_config.get_llm", return_value=llm
+ ):
+ result = asyncio.run(
+ generate_topics_async(query="q", findings="findings")
+ )
+
+ assert result == ["async topic"]
+ llm.ainvoke.assert_awaited_once()
+ llm.invoke.assert_not_called()
+
+
+class TestFailureMarkersUnchanged:
+ """The sync entry points, and the async headline twin, keep their
+ documented failure markers."""
+
+ def test_headline_failure_marker(self):
+ llm = Mock(spec=["invoke", "close"])
+ llm.invoke.side_effect = RuntimeError("provider down")
+
+ with patch(
+ "local_deep_research.config.llm_config.get_llm", return_value=llm
+ ):
+ assert (
+ generate_headline(query="q", findings="f")
+ == "[Headline generation failed]"
+ )
+
+ def test_topics_failure_marker(self):
+ llm = Mock(spec=["invoke", "close"])
+ llm.invoke.side_effect = RuntimeError("provider down")
+
+ with patch(
+ "local_deep_research.config.llm_config.get_llm", return_value=llm
+ ):
+ assert generate_topics(query="q", findings="f") == [
+ "[topic generation failed]"
+ ]
+
+ def test_headline_async_failure_marker(self):
+ """The async twin must apply the same failure sentinel as the
+ sync entry point, not silently return None."""
+ llm = Mock(spec=["ainvoke", "close"])
+ llm.ainvoke = AsyncMock(side_effect=RuntimeError("provider down"))
+
+ with patch(
+ "local_deep_research.config.llm_config.get_llm", return_value=llm
+ ):
+ result = asyncio.run(
+ generate_headline_async(query="q", findings="f")
+ )
+
+ assert result == "[Headline generation failed]"
+
+
[email protected]("asynchronous", [False, True])
+def test_headline_extracts_only_text_from_content_blocks(asynchronous):
+ content = [
+ {"type": "thinking", "thinking": "internal reasoning"},
+ {"type": "text", "text": '"Clear headline."'},
+ {"type": "tool_use", "id": "tool-only", "name": "unused", "input": {}},
+ ]
+ llm = _dual_llm("", "")
+ llm.invoke.return_value = Mock(content=content)
+ llm.ainvoke.return_value = Mock(content=content)
+ with patch(
+ "local_deep_research.config.llm_config.get_llm", return_value=llm
+ ):
+ result = (
+ asyncio.run(generate_headline_async(query="q", findings="report"))
+ if asynchronous
+ else generate_headline(query="q", findings="report")
+ )
+ assert result == "Clear headline"
diff --git a/tests/news/test_news_analyzer.py b/tests/news/test_news_analyzer.py
index 3b7127e9ee..95473ad73d 100644
--- a/tests/news/test_news_analyzer.py
+++ b/tests/news/test_news_analyzer.py
@@ -11,7 +11,8 @@ Tests cover:
- Error handling
"""
-from unittest.mock import Mock, patch
+import asyncio
+from unittest.mock import AsyncMock, Mock, patch
class TestNewsAnalyzerInit:
@@ -21,7 +22,7 @@ class TestNewsAnalyzerInit:
"""Test initialization with custom LLM client."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
analyzer = NewsAnalyzer(llm_client=mock_llm)
assert analyzer.llm_client is mock_llm
@@ -31,7 +32,7 @@ class TestNewsAnalyzerInit:
with patch(
"local_deep_research.news.core.news_analyzer.get_llm"
) as mock_get_llm:
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_get_llm.return_value = mock_llm
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
@@ -50,7 +51,7 @@ class TestNewsAnalyzer:
analyzer = NewsAnalyzer(llm_client=Mock())
- result = analyzer.analyze_news([])
+ result = asyncio.run(analyzer.analyze_news([]))
assert result["items"] == []
assert result["item_count"] == 0
@@ -217,7 +218,7 @@ class TestExtractNewsItems:
analyzer = NewsAnalyzer(llm_client=Mock())
analyzer.llm_client = None
- result = analyzer.extract_news_items([{"title": "Test"}])
+ result = asyncio.run(analyzer.extract_news_items([{"title": "Test"}]))
assert result == []
@@ -225,7 +226,7 @@ class TestExtractNewsItems:
"""Test successful news item extraction."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = """
[
@@ -233,12 +234,14 @@ class TestExtractNewsItems:
{"headline": "Another Story", "summary": "More details here", "category": "Sports"}
]
"""
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items(
- [{"title": "Test", "snippet": "content"}]
+ result = asyncio.run(
+ analyzer.extract_news_items(
+ [{"title": "Test", "snippet": "content"}]
+ )
)
assert len(result) == 2
@@ -250,7 +253,7 @@ class TestExtractNewsItems:
"""Test extraction respects max_items parameter."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
# Return more items than max
mock_response.content = """
@@ -262,12 +265,14 @@ class TestExtractNewsItems:
{"headline": "Item 5", "summary": "Summary 5"}
]
"""
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items(
- [{"title": "Test", "snippet": "content"}], max_items=3
+ result = asyncio.run(
+ analyzer.extract_news_items(
+ [{"title": "Test", "snippet": "content"}], max_items=3
+ )
)
assert len(result) == 3
@@ -276,7 +281,7 @@ class TestExtractNewsItems:
"""Test that invalid items are filtered out."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = """
[
@@ -285,12 +290,14 @@ class TestExtractNewsItems:
{"summary": "Missing Headline"}
]
"""
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items(
- [{"title": "Test", "snippet": "content"}]
+ result = asyncio.run(
+ analyzer.extract_news_items(
+ [{"title": "Test", "snippet": "content"}]
+ )
)
assert len(result) == 1
@@ -300,13 +307,15 @@ class TestExtractNewsItems:
"""Test that LLM errors are handled gracefully."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
- mock_llm.invoke.side_effect = Exception("LLM Error")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = Exception("LLM Error")
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items(
- [{"title": "Test", "snippet": "content"}]
+ result = asyncio.run(
+ analyzer.extract_news_items(
+ [{"title": "Test", "snippet": "content"}]
+ )
)
assert result == []
@@ -315,15 +324,17 @@ class TestExtractNewsItems:
"""Test that malformed JSON is handled gracefully."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = "This is not valid JSON at all"
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items(
- [{"title": "Test", "snippet": "content"}]
+ result = asyncio.run(
+ analyzer.extract_news_items(
+ [{"title": "Test", "snippet": "content"}]
+ )
)
assert result == []
@@ -332,15 +343,17 @@ class TestExtractNewsItems:
"""Test handling response that returns string directly."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
# Response without .content attribute
mock_response = '[{"headline": "Test", "summary": "Summary"}]'
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items(
- [{"title": "Test", "snippet": "content"}]
+ result = asyncio.run(
+ analyzer.extract_news_items(
+ [{"title": "Test", "snippet": "content"}]
+ )
)
assert len(result) == 1
@@ -357,7 +370,9 @@ class TestGenerateBigPicture:
analyzer = NewsAnalyzer(llm_client=Mock())
analyzer.llm_client = None
- result = analyzer.generate_big_picture([{"headline": "Test"}])
+ result = asyncio.run(
+ analyzer.generate_big_picture([{"headline": "Test"}])
+ )
assert result == ""
@@ -367,7 +382,7 @@ class TestGenerateBigPicture:
analyzer = NewsAnalyzer(llm_client=Mock())
- result = analyzer.generate_big_picture([])
+ result = asyncio.run(analyzer.generate_big_picture([]))
assert result == ""
@@ -375,10 +390,10 @@ class TestGenerateBigPicture:
"""Test successful big picture generation."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = " The economy is shifting towards AI. "
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
@@ -387,22 +402,24 @@ class TestGenerateBigPicture:
{"headline": "Tech Growth", "summary": "Sector growing rapidly"},
]
- result = analyzer.generate_big_picture(news_items)
+ result = asyncio.run(analyzer.generate_big_picture(news_items))
assert result == "The economy is shifting towards AI."
- mock_llm.invoke.assert_called_once()
+ mock_llm.ainvoke.assert_called_once()
def test_generate_big_picture_handles_error(self):
"""Test that errors are handled gracefully."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
- mock_llm.invoke.side_effect = Exception("LLM Error")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = Exception("LLM Error")
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_big_picture(
- [{"headline": "Test", "summary": "S"}]
+ result = asyncio.run(
+ analyzer.generate_big_picture(
+ [{"headline": "Test", "summary": "S"}]
+ )
)
assert result == ""
@@ -419,7 +436,9 @@ class TestGenerateWatchFor:
analyzer = NewsAnalyzer(llm_client=Mock())
analyzer.llm_client = None
- result = analyzer.generate_watch_for([{"headline": "Test"}])
+ result = asyncio.run(
+ analyzer.generate_watch_for([{"headline": "Test"}])
+ )
assert result == []
@@ -429,7 +448,7 @@ class TestGenerateWatchFor:
analyzer = NewsAnalyzer(llm_client=Mock())
- result = analyzer.generate_watch_for([])
+ result = asyncio.run(analyzer.generate_watch_for([]))
assert result == []
@@ -437,14 +456,14 @@ class TestGenerateWatchFor:
"""Test successful watch_for generation."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = """
- Market opening on Monday
- Fed announcement expected
- Earnings reports due
"""
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
@@ -456,7 +475,7 @@ class TestGenerateWatchFor:
}
]
- result = analyzer.generate_watch_for(news_items)
+ result = asyncio.run(analyzer.generate_watch_for(news_items))
assert len(result) == 3
assert "Market opening on Monday" in result
@@ -465,10 +484,10 @@ class TestGenerateWatchFor:
"""Test that developing stories are prioritized."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = "- Watch item 1"
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
@@ -485,17 +504,17 @@ class TestGenerateWatchFor:
},
]
- analyzer.generate_watch_for(news_items)
+ asyncio.run(analyzer.generate_watch_for(news_items))
# Check that the prompt contains the developing story
- call_args = mock_llm.invoke.call_args[0][0]
+ call_args = mock_llm.ainvoke.call_args[0][0]
assert "Breaking" in call_args
def test_generate_watch_for_limits_to_five(self):
"""Test that watch_for items are limited to 5."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = """
- Item 1
@@ -506,12 +525,14 @@ class TestGenerateWatchFor:
- Item 6
- Item 7
"""
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for(
- [{"headline": "Test", "summary": "S", "is_developing": True}]
+ result = asyncio.run(
+ analyzer.generate_watch_for(
+ [{"headline": "Test", "summary": "S", "is_developing": True}]
+ )
)
assert len(result) <= 5
@@ -520,13 +541,15 @@ class TestGenerateWatchFor:
"""Test that errors are handled gracefully."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
- mock_llm.invoke.side_effect = Exception("LLM Error")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = Exception("LLM Error")
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for(
- [{"headline": "Test", "summary": "S", "is_developing": True}]
+ result = asyncio.run(
+ analyzer.generate_watch_for(
+ [{"headline": "Test", "summary": "S", "is_developing": True}]
+ )
)
assert result == []
@@ -543,7 +566,7 @@ class TestGeneratePatterns:
analyzer = NewsAnalyzer(llm_client=Mock())
analyzer.llm_client = None
- result = analyzer.generate_patterns([{"headline": "Test"}])
+ result = asyncio.run(analyzer.generate_patterns([{"headline": "Test"}]))
assert result == ""
@@ -553,7 +576,7 @@ class TestGeneratePatterns:
analyzer = NewsAnalyzer(llm_client=Mock())
- result = analyzer.generate_patterns([])
+ result = asyncio.run(analyzer.generate_patterns([]))
assert result == ""
@@ -561,10 +584,10 @@ class TestGeneratePatterns:
"""Test successful pattern generation."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = " Technology dominates today's headlines. "
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
@@ -574,7 +597,7 @@ class TestGeneratePatterns:
{"headline": "Sports Update", "category": "Sports"},
]
- result = analyzer.generate_patterns(news_items)
+ result = asyncio.run(analyzer.generate_patterns(news_items))
assert result == "Technology dominates today's headlines."
@@ -582,13 +605,15 @@ class TestGeneratePatterns:
"""Test that errors are handled gracefully."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
- mock_llm.invoke.side_effect = Exception("LLM Error")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = Exception("LLM Error")
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_patterns(
- [{"headline": "Test", "category": "Tech"}]
+ result = asyncio.run(
+ analyzer.generate_patterns(
+ [{"headline": "Test", "category": "Tech"}]
+ )
)
assert result == ""
@@ -604,7 +629,8 @@ class TestExtractTopics:
analyzer = NewsAnalyzer(llm_client=Mock())
with patch(
- "local_deep_research.news.core.news_analyzer.generate_topics"
+ "local_deep_research.news.core.news_analyzer.generate_topics_async",
+ new_callable=AsyncMock,
) as mock_gen:
mock_gen.return_value = ["AI", "Machine Learning"]
@@ -618,7 +644,7 @@ class TestExtractTopics:
}
]
- result = analyzer.extract_topics(news_items)
+ result = asyncio.run(analyzer.extract_topics(news_items))
assert len(result) >= 1
assert any(topic["name"] == "AI" for topic in result)
@@ -630,7 +656,8 @@ class TestExtractTopics:
analyzer = NewsAnalyzer(llm_client=Mock())
with patch(
- "local_deep_research.news.core.news_analyzer.generate_topics"
+ "local_deep_research.news.core.news_analyzer.generate_topics_async",
+ new_callable=AsyncMock,
) as mock_gen:
# Same topic from multiple items
mock_gen.return_value = ["AI"]
@@ -650,7 +677,7 @@ class TestExtractTopics:
},
]
- result = analyzer.extract_topics(news_items)
+ result = asyncio.run(analyzer.extract_topics(news_items))
# Should have only one "AI" topic
ai_topics = [t for t in result if t["name"] == "AI"]
@@ -665,7 +692,8 @@ class TestExtractTopics:
analyzer = NewsAnalyzer(llm_client=Mock())
with patch(
- "local_deep_research.news.core.news_analyzer.generate_topics"
+ "local_deep_research.news.core.news_analyzer.generate_topics_async",
+ new_callable=AsyncMock,
) as mock_gen:
mock_gen.return_value = ["Climate"]
@@ -684,7 +712,7 @@ class TestExtractTopics:
},
]
- result = analyzer.extract_topics(news_items)
+ result = asyncio.run(analyzer.extract_topics(news_items))
climate_topic = next(t for t in result if t["name"] == "Climate")
assert climate_topic["impact_score"] == 9
@@ -696,7 +724,8 @@ class TestExtractTopics:
analyzer = NewsAnalyzer(llm_client=Mock())
with patch(
- "local_deep_research.news.core.news_analyzer.generate_topics"
+ "local_deep_research.news.core.news_analyzer.generate_topics_async",
+ new_callable=AsyncMock,
) as mock_gen:
# Return many topics
mock_gen.side_effect = [
@@ -713,7 +742,7 @@ class TestExtractTopics:
for i in range(10)
]
- result = analyzer.extract_topics(news_items)
+ result = asyncio.run(analyzer.extract_topics(news_items))
assert len(result) <= 10
@@ -724,7 +753,8 @@ class TestExtractTopics:
analyzer = NewsAnalyzer(llm_client=Mock())
with patch(
- "local_deep_research.news.core.news_analyzer.generate_topics"
+ "local_deep_research.news.core.news_analyzer.generate_topics_async",
+ new_callable=AsyncMock,
) as mock_gen:
mock_gen.return_value = ["Technology"]
@@ -737,7 +767,7 @@ class TestExtractTopics:
}
]
- result = analyzer.extract_topics(news_items)
+ result = asyncio.run(analyzer.extract_topics(news_items))
assert "query" in result[0]
assert "Technology" in result[0]["query"]
@@ -750,7 +780,7 @@ class TestAnalyzeNews:
"""Test complete news analysis flow."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
# Mock response for extract_news_items
extract_response = Mock()
@@ -760,7 +790,7 @@ class TestAnalyzeNews:
text_response = Mock()
text_response.content = "Analysis text"
- mock_llm.invoke.return_value = extract_response
+ mock_llm.ainvoke.return_value = extract_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
@@ -777,23 +807,34 @@ class TestAnalyzeNews:
"impact_score": 8,
}
],
+ new_callable=AsyncMock,
):
with patch.object(
- analyzer, "generate_big_picture", return_value="Big picture"
+ analyzer,
+ "generate_big_picture",
+ return_value="Big picture",
+ new_callable=AsyncMock,
):
with patch.object(
- analyzer, "generate_watch_for", return_value=["Watch item"]
+ analyzer,
+ "generate_watch_for",
+ return_value=["Watch item"],
+ new_callable=AsyncMock,
):
with patch.object(
- analyzer, "generate_patterns", return_value="Pattern"
+ analyzer,
+ "generate_patterns",
+ return_value="Pattern",
+ new_callable=AsyncMock,
):
with patch.object(
analyzer,
"extract_topics",
return_value=[{"name": "Topic"}],
+ new_callable=AsyncMock,
):
- result = analyzer.analyze_news(
- [{"title": "Raw result"}]
+ result = asyncio.run(
+ analyzer.analyze_news([{"title": "Raw result"}])
)
assert result["item_count"] == 1
@@ -810,9 +851,12 @@ class TestAnalyzeNews:
analyzer = NewsAnalyzer(llm_client=Mock())
with patch.object(
- analyzer, "extract_news_items", side_effect=Exception("Error")
+ analyzer,
+ "extract_news_items",
+ side_effect=Exception("Error"),
+ new_callable=AsyncMock,
):
- result = analyzer.analyze_news([{"title": "Test"}])
+ result = asyncio.run(analyzer.analyze_news([{"title": "Test"}]))
assert result["items"] == []
assert result["item_count"] == 0
@@ -823,8 +867,13 @@ class TestAnalyzeNews:
analyzer = NewsAnalyzer(llm_client=Mock())
- with patch.object(analyzer, "extract_news_items", return_value=[]):
- result = analyzer.analyze_news([{"title": "Test"}])
+ with patch.object(
+ analyzer,
+ "extract_news_items",
+ return_value=[],
+ new_callable=AsyncMock,
+ ):
+ result = asyncio.run(analyzer.analyze_news([{"title": "Test"}]))
# Should return basic structure without calling other methods
assert result["items"] == []
@@ -956,13 +1005,13 @@ class TestNewsAnalyzerEdgeCases:
"""Test analyze_news handles exceptions gracefully."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
- mock_llm.invoke.side_effect = Exception("LLM unavailable")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = Exception("LLM unavailable")
analyzer = NewsAnalyzer(llm_client=mock_llm)
# Should return empty analysis on error
- result = analyzer.analyze_news([{"title": "Test"}])
+ result = asyncio.run(analyzer.analyze_news([{"title": "Test"}]))
assert result["items"] == []
assert result["item_count"] == 0
@@ -971,14 +1020,14 @@ class TestNewsAnalyzerEdgeCases:
"""Test extract_news_items with empty search results."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = "[]"
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([])
+ result = asyncio.run(analyzer.extract_news_items([]))
# Should still call LLM even with empty results
assert result == []
@@ -987,18 +1036,18 @@ class TestNewsAnalyzerEdgeCases:
"""Test extract_news_items handles JSON with surrounding text."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = """
Here are the news items:
[{"headline": "Test", "summary": "Summary"}]
That's all the news.
"""
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([{"title": "Raw"}])
+ result = asyncio.run(analyzer.extract_news_items([{"title": "Raw"}]))
assert len(result) == 1
assert result[0]["headline"] == "Test"
@@ -1007,10 +1056,10 @@ class TestNewsAnalyzerEdgeCases:
"""Test watch_for uses all stories when no developing stories."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = "- Watch item"
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
@@ -1020,7 +1069,7 @@ class TestNewsAnalyzerEdgeCases:
{"headline": "Story 2", "summary": "S", "is_developing": False},
]
- result = analyzer.generate_watch_for(news_items)
+ result = asyncio.run(analyzer.generate_watch_for(news_items))
assert len(result) >= 0 # Should use fallback
@@ -1028,19 +1077,21 @@ class TestNewsAnalyzerEdgeCases:
"""Test watch_for strips various bullet markers correctly."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = """
- Item with dash
• Item with bullet
* Item with asterisk
"""
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for(
- [{"headline": "Test", "summary": "S", "is_developing": True}]
+ result = asyncio.run(
+ analyzer.generate_watch_for(
+ [{"headline": "Test", "summary": "S", "is_developing": True}]
+ )
)
# All bullet markers should be stripped
@@ -1053,10 +1104,10 @@ class TestNewsAnalyzerEdgeCases:
"""Test patterns method groups items by category."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = "Tech dominates"
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
@@ -1066,7 +1117,7 @@ class TestNewsAnalyzerEdgeCases:
{"headline": "Sport 1", "category": "Sports"},
]
- result = analyzer.generate_patterns(news_items)
+ result = asyncio.run(analyzer.generate_patterns(news_items))
assert result == "Tech dominates"
@@ -1076,7 +1127,7 @@ class TestNewsAnalyzerEdgeCases:
analyzer = NewsAnalyzer(llm_client=Mock())
- result = analyzer.extract_topics([])
+ result = asyncio.run(analyzer.extract_topics([]))
assert result == []
@@ -1087,7 +1138,8 @@ class TestNewsAnalyzerEdgeCases:
analyzer = NewsAnalyzer(llm_client=Mock())
with patch(
- "local_deep_research.news.core.news_analyzer.generate_topics"
+ "local_deep_research.news.core.news_analyzer.generate_topics_async",
+ new_callable=AsyncMock,
) as mock_gen:
# Return same topic multiple times for first two items
mock_gen.side_effect = [
@@ -1117,7 +1169,7 @@ class TestNewsAnalyzerEdgeCases:
},
]
- result = analyzer.extract_topics(news_items)
+ result = asyncio.run(analyzer.extract_topics(news_items))
# AI should be first (frequency 2) then Blockchain (frequency 1)
assert result[0]["name"] == "AI"
@@ -1217,14 +1269,14 @@ class TestNewsAnalyzerLLMResponses:
"""Test handling when LLM returns dict instead of list."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = '{"error": "Invalid format"}'
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([{"title": "Test"}])
+ result = asyncio.run(analyzer.extract_news_items([{"title": "Test"}]))
# Should return empty list on parse failure
assert result == []
@@ -1233,7 +1285,7 @@ class TestNewsAnalyzerLLMResponses:
"""Test handling when LLM returns nested JSON."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = """
{
@@ -1242,11 +1294,11 @@ class TestNewsAnalyzerLLMResponses:
]
}
"""
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([{"title": "Test"}])
+ result = asyncio.run(analyzer.extract_news_items([{"title": "Test"}]))
# Should extract the inner array
assert len(result) == 1
@@ -1255,15 +1307,17 @@ class TestNewsAnalyzerLLMResponses:
"""Test big picture strips newlines correctly."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = "\n\n The economy is changing. \n\n"
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_big_picture(
- [{"headline": "Test", "summary": "S"}]
+ result = asyncio.run(
+ analyzer.generate_big_picture(
+ [{"headline": "Test", "summary": "S"}]
+ )
)
assert result == "The economy is changing."
@@ -1272,15 +1326,17 @@ class TestNewsAnalyzerLLMResponses:
"""Test watch_for with empty LLM response."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = ""
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for(
- [{"headline": "Test", "summary": "S", "is_developing": True}]
+ result = asyncio.run(
+ analyzer.generate_watch_for(
+ [{"headline": "Test", "summary": "S", "is_developing": True}]
+ )
)
assert result == []
@@ -1289,15 +1345,17 @@ class TestNewsAnalyzerLLMResponses:
"""Test patterns with empty LLM response."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = " " # Whitespace only
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_patterns(
- [{"headline": "Test", "category": "Tech"}]
+ result = asyncio.run(
+ analyzer.generate_patterns(
+ [{"headline": "Test", "category": "Tech"}]
+ )
)
assert result == ""
@@ -1485,15 +1543,15 @@ class TestAnalyzeNewsFlow:
"""Test that analysis skips components when no items extracted."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = "[]" # No items
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
with patch.object(analyzer, "generate_big_picture") as mock_big_picture:
- result = analyzer.analyze_news([{"title": "Test"}])
+ result = asyncio.run(analyzer.analyze_news([{"title": "Test"}]))
# big_picture should not be called for empty items
mock_big_picture.assert_not_called()
@@ -1503,14 +1561,14 @@ class TestAnalyzeNewsFlow:
"""Test that analysis includes timestamp."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = "[]"
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.analyze_news([{"title": "Test"}])
+ result = asyncio.run(analyzer.analyze_news([{"title": "Test"}]))
assert "timestamp" in result
# Timestamp should be ISO format
@@ -1520,10 +1578,10 @@ class TestAnalyzeNewsFlow:
"""Test that analysis counts original search results."""
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_response = Mock()
mock_response.content = '[{"headline": "Test", "summary": "S"}]'
- mock_llm.invoke.return_value = mock_response
+ mock_llm.ainvoke.return_value = mock_response
analyzer = NewsAnalyzer(llm_client=mock_llm)
@@ -1533,14 +1591,32 @@ class TestAnalyzeNewsFlow:
{"title": "Result 3"},
]
- with patch.object(analyzer, "generate_big_picture", return_value=""):
- with patch.object(analyzer, "generate_watch_for", return_value=[]):
+ with patch.object(
+ analyzer,
+ "generate_big_picture",
+ return_value="",
+ new_callable=AsyncMock,
+ ):
+ with patch.object(
+ analyzer,
+ "generate_watch_for",
+ return_value=[],
+ new_callable=AsyncMock,
+ ):
with patch.object(
- analyzer, "generate_patterns", return_value=""
+ analyzer,
+ "generate_patterns",
+ return_value="",
+ new_callable=AsyncMock,
):
with patch.object(
- analyzer, "extract_topics", return_value=[]
+ analyzer,
+ "extract_topics",
+ return_value=[],
+ new_callable=AsyncMock,
):
- result = analyzer.analyze_news(search_results)
+ result = asyncio.run(
+ analyzer.analyze_news(search_results)
+ )
assert result["search_result_count"] == 3
diff --git a/tests/news/test_news_analyzer_behavior.py b/tests/news/test_news_analyzer_behavior.py
index 5b195acf8f..ef8d9e5eb6 100644
--- a/tests/news/test_news_analyzer_behavior.py
+++ b/tests/news/test_news_analyzer_behavior.py
@@ -4,8 +4,9 @@ Tests _validate_news_item, _count_categories, _summarize_impact,
_prepare_snippets, _empty_analysis, and LLM-dependent methods with mocks.
"""
+import asyncio
from datetime import datetime
-from unittest.mock import Mock, patch
+from unittest.mock import AsyncMock, Mock, patch
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
@@ -366,13 +367,13 @@ class TestAnalyzeNews:
def test_empty_input_returns_empty_analysis(self):
analyzer = _make_analyzer()
- result = analyzer.analyze_news([])
+ result = asyncio.run(analyzer.analyze_news([]))
assert result["items"] == []
assert result["item_count"] == 0
def test_none_input_returns_empty_analysis(self):
analyzer = _make_analyzer()
- result = analyzer.analyze_news(None)
+ result = asyncio.run(analyzer.analyze_news(None))
assert result["item_count"] == 0
@@ -384,42 +385,44 @@ class TestExtractNewsItems:
def test_no_llm_returns_empty(self):
analyzer = _make_analyzer(llm_client=None)
- result = analyzer.extract_news_items([{"title": "Test"}])
+ result = asyncio.run(analyzer.extract_news_items([{"title": "Test"}]))
assert result == []
def test_with_llm_parses_json_response(self):
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(
content='[{"headline": "AI Breakthrough", "summary": "Major discovery"}]'
)
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([{"title": "Source"}])
+ result = asyncio.run(analyzer.extract_news_items([{"title": "Source"}]))
assert len(result) == 1
assert result[0]["headline"] == "AI Breakthrough"
assert "id" in result[0] # ID should be generated
def test_invalid_json_returns_empty(self):
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="not valid json at all")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(content="not valid json at all")
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([{"title": "Source"}])
+ result = asyncio.run(analyzer.extract_news_items([{"title": "Source"}]))
assert result == []
def test_respects_max_items(self):
- mock_llm = Mock()
+ mock_llm = AsyncMock()
items = [
{"headline": f"News {i}", "summary": f"Summary {i}"}
for i in range(20)
]
import json
- mock_llm.invoke.return_value = Mock(content=json.dumps(items))
+ mock_llm.ainvoke.return_value = Mock(content=json.dumps(items))
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([{"title": "Source"}], max_items=5)
+ result = asyncio.run(
+ analyzer.extract_news_items([{"title": "Source"}], max_items=5)
+ )
assert len(result) <= 5
def test_filters_invalid_items(self):
- mock_llm = Mock()
+ mock_llm = AsyncMock()
items = [
{"headline": "Valid", "summary": "Summary"},
{"headline": "", "summary": "No headline"},
@@ -427,16 +430,16 @@ class TestExtractNewsItems:
]
import json
- mock_llm.invoke.return_value = Mock(content=json.dumps(items))
+ mock_llm.ainvoke.return_value = Mock(content=json.dumps(items))
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([{"title": "Source"}])
+ result = asyncio.run(analyzer.extract_news_items([{"title": "Source"}]))
assert len(result) == 2
def test_llm_exception_returns_empty(self):
- mock_llm = Mock()
- mock_llm.invoke.side_effect = RuntimeError("LLM failed")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = RuntimeError("LLM failed")
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([{"title": "Source"}])
+ result = asyncio.run(analyzer.extract_news_items([{"title": "Source"}]))
assert result == []
@@ -448,29 +451,36 @@ class TestGenerateBigPicture:
def test_no_llm_returns_empty(self):
analyzer = _make_analyzer(llm_client=None)
- assert analyzer.generate_big_picture([{"headline": "Test"}]) == ""
+ assert (
+ asyncio.run(analyzer.generate_big_picture([{"headline": "Test"}]))
+ == ""
+ )
def test_empty_items_returns_empty(self):
- mock_llm = Mock()
+ mock_llm = AsyncMock()
analyzer = _make_analyzer(llm_client=mock_llm)
- assert analyzer.generate_big_picture([]) == ""
+ assert asyncio.run(analyzer.generate_big_picture([])) == ""
def test_with_llm_returns_content(self):
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(
content=" The big picture is clear. "
)
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.generate_big_picture(
- [{"headline": "News", "summary": "Sum"}]
+ result = asyncio.run(
+ analyzer.generate_big_picture(
+ [{"headline": "News", "summary": "Sum"}]
+ )
)
assert result == "The big picture is clear."
def test_llm_error_returns_empty(self):
- mock_llm = Mock()
- mock_llm.invoke.side_effect = RuntimeError("fail")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = RuntimeError("fail")
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.generate_big_picture([{"headline": "News"}])
+ result = asyncio.run(
+ analyzer.generate_big_picture([{"headline": "News"}])
+ )
assert result == ""
@@ -482,61 +492,72 @@ class TestGenerateWatchFor:
def test_no_llm_returns_empty(self):
analyzer = _make_analyzer(llm_client=None)
- assert analyzer.generate_watch_for([{"headline": "Test"}]) == []
+ assert (
+ asyncio.run(analyzer.generate_watch_for([{"headline": "Test"}]))
+ == []
+ )
def test_empty_items_returns_empty(self):
- mock_llm = Mock()
+ mock_llm = AsyncMock()
analyzer = _make_analyzer(llm_client=mock_llm)
- assert analyzer.generate_watch_for([]) == []
+ assert asyncio.run(analyzer.generate_watch_for([])) == []
def test_parses_bullet_points(self):
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(
content="- First item\n- Second item\n- Third item"
)
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for(
- [{"headline": "News", "is_developing": True}]
+ result = asyncio.run(
+ analyzer.generate_watch_for(
+ [{"headline": "News", "is_developing": True}]
+ )
)
assert len(result) == 3
assert result[0] == "First item"
def test_strips_bullet_markers(self):
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(
content="* Item one\n- Item two\n\u2022 Item three"
)
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for(
- [{"headline": "News", "is_developing": True}]
+ result = asyncio.run(
+ analyzer.generate_watch_for(
+ [{"headline": "News", "is_developing": True}]
+ )
)
assert all(not item.startswith(("-", "*", "\u2022")) for item in result)
def test_max_5_items(self):
- mock_llm = Mock()
+ mock_llm = AsyncMock()
lines = "\n".join([f"- Item {i}" for i in range(10)])
- mock_llm.invoke.return_value = Mock(content=lines)
+ mock_llm.ainvoke.return_value = Mock(content=lines)
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for(
- [{"headline": "News", "is_developing": True}]
+ result = asyncio.run(
+ analyzer.generate_watch_for(
+ [{"headline": "News", "is_developing": True}]
+ )
)
assert len(result) <= 5
def test_filters_header_lines(self):
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(
content="WATCH FOR:\n- Real item\nWatch for:\n- Another item"
)
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for(
- [{"headline": "News", "is_developing": True}]
+ result = asyncio.run(
+ analyzer.generate_watch_for(
+ [{"headline": "News", "is_developing": True}]
+ )
)
assert "WATCH FOR:" not in result
assert "Watch for:" not in result
def test_uses_developing_stories_first(self):
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="- Watch this")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(content="- Watch this")
analyzer = _make_analyzer(llm_client=mock_llm)
items = [
{
@@ -546,29 +567,31 @@ class TestGenerateWatchFor:
},
{"headline": "Old", "is_developing": False, "summary": "done"},
]
- analyzer.generate_watch_for(items)
+ asyncio.run(analyzer.generate_watch_for(items))
# Verify LLM was called (developing stories used)
- mock_llm.invoke.assert_called_once()
- call_args = mock_llm.invoke.call_args[0][0]
+ mock_llm.ainvoke.assert_called_once()
+ call_args = mock_llm.ainvoke.call_args[0][0]
assert "Developing" in call_args
def test_falls_back_to_first_5_when_no_developing(self):
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="- Watch this")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(content="- Watch this")
analyzer = _make_analyzer(llm_client=mock_llm)
items = [
{"headline": f"Story {i}", "is_developing": False}
for i in range(10)
]
- analyzer.generate_watch_for(items)
- mock_llm.invoke.assert_called_once()
+ asyncio.run(analyzer.generate_watch_for(items))
+ mock_llm.ainvoke.assert_called_once()
def test_llm_error_returns_empty(self):
- mock_llm = Mock()
- mock_llm.invoke.side_effect = RuntimeError("fail")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = RuntimeError("fail")
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for(
- [{"headline": "News", "is_developing": True}]
+ result = asyncio.run(
+ analyzer.generate_watch_for(
+ [{"headline": "News", "is_developing": True}]
+ )
)
assert result == []
@@ -581,26 +604,31 @@ class TestGeneratePatterns:
def test_no_llm_returns_empty(self):
analyzer = _make_analyzer(llm_client=None)
- assert analyzer.generate_patterns([{"headline": "Test"}]) == ""
+ assert (
+ asyncio.run(analyzer.generate_patterns([{"headline": "Test"}]))
+ == ""
+ )
def test_empty_items_returns_empty(self):
- mock_llm = Mock()
+ mock_llm = AsyncMock()
analyzer = _make_analyzer(llm_client=mock_llm)
- assert analyzer.generate_patterns([]) == ""
+ assert asyncio.run(analyzer.generate_patterns([])) == ""
def test_with_llm_returns_content(self):
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content=" Pattern detected. ")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(content=" Pattern detected. ")
analyzer = _make_analyzer(llm_client=mock_llm)
items = [{"headline": "AI News", "category": "Tech"}]
- result = analyzer.generate_patterns(items)
+ result = asyncio.run(analyzer.generate_patterns(items))
assert result == "Pattern detected."
def test_llm_error_returns_empty(self):
- mock_llm = Mock()
- mock_llm.invoke.side_effect = RuntimeError("fail")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = RuntimeError("fail")
analyzer = _make_analyzer(llm_client=mock_llm)
- result = analyzer.generate_patterns(
- [{"headline": "Test", "category": "Tech"}]
+ result = asyncio.run(
+ analyzer.generate_patterns(
+ [{"headline": "Test", "category": "Tech"}]
+ )
)
assert result == ""
diff --git a/tests/news/test_news_analyzer_coverage.py b/tests/news/test_news_analyzer_coverage.py
index ec1abad031..0bc73e6226 100644
--- a/tests/news/test_news_analyzer_coverage.py
+++ b/tests/news/test_news_analyzer_coverage.py
@@ -12,9 +12,10 @@ Focuses on edge cases and scenarios not covered by existing test files:
- analyze_news: exception path returns empty analysis
"""
+import asyncio
import json
from datetime import datetime
-from unittest.mock import Mock, patch
+from unittest.mock import AsyncMock, Mock, patch
import pytest
@@ -29,7 +30,7 @@ from local_deep_research.news.core.news_analyzer import NewsAnalyzer
@pytest.fixture
def analyzer():
"""NewsAnalyzer with a no-op mock LLM (does not own it)."""
- mock_llm = Mock()
+ mock_llm = AsyncMock()
return NewsAnalyzer(llm_client=mock_llm)
@@ -395,7 +396,7 @@ class TestClose:
def test_close_does_not_close_external_llm(self):
"""When llm_client is provided externally, close() should NOT close it."""
- mock_llm = Mock()
+ mock_llm = AsyncMock()
na = NewsAnalyzer(llm_client=mock_llm)
assert na._owns_llm is False
na.close()
@@ -406,7 +407,7 @@ class TestClose:
with patch(
"local_deep_research.news.core.news_analyzer.get_llm"
) as mock_get:
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_get.return_value = mock_llm
na = NewsAnalyzer()
assert na._owns_llm is True
@@ -424,21 +425,24 @@ class TestAnalyzeNewsExceptionPath:
def test_exception_in_extract_returns_empty(self):
"""If extract_news_items raises, analyze_news catches and returns empty."""
- mock_llm = Mock()
+ mock_llm = AsyncMock()
na = NewsAnalyzer(llm_client=mock_llm)
with patch.object(
- na, "extract_news_items", side_effect=RuntimeError("boom")
+ na,
+ "extract_news_items",
+ side_effect=RuntimeError("boom"),
+ new_callable=AsyncMock,
):
- result = na.analyze_news([{"content": "data"}])
+ result = asyncio.run(na.analyze_news([{"content": "data"}]))
assert result["items"] == []
assert result["item_count"] == 0
def test_empty_search_results_skips_llm(self):
"""Empty input should return empty analysis without invoking LLM."""
- mock_llm = Mock()
+ mock_llm = AsyncMock()
na = NewsAnalyzer(llm_client=mock_llm)
- result = na.analyze_news([])
- mock_llm.invoke.assert_not_called()
+ result = asyncio.run(na.analyze_news([]))
+ mock_llm.ainvoke.assert_not_called()
assert result["item_count"] == 0
@@ -451,39 +455,41 @@ class TestExtractNewsItemsIDsAndFiltering:
"""Tests for extract_news_items ID assignment and item filtering."""
def test_each_item_gets_unique_id(self):
- mock_llm = Mock()
+ mock_llm = AsyncMock()
items = [
{"headline": f"News {i}", "summary": f"Summary {i}"}
for i in range(3)
]
- mock_llm.invoke.return_value = Mock(content=json.dumps(items))
+ mock_llm.ainvoke.return_value = Mock(content=json.dumps(items))
na = NewsAnalyzer(llm_client=mock_llm)
- result = na.extract_news_items([{"title": "source"}])
+ result = asyncio.run(na.extract_news_items([{"title": "source"}]))
ids = [item["id"] for item in result]
assert len(ids) == len(set(ids)), "All IDs should be unique"
def test_invalid_items_filtered_out(self):
- mock_llm = Mock()
+ mock_llm = AsyncMock()
items = [
{"headline": "Valid", "summary": "Yes"},
{"headline": "", "summary": "No headline"},
{"summary": "Missing headline entirely"},
{"headline": "Also valid", "summary": "Content"},
]
- mock_llm.invoke.return_value = Mock(content=json.dumps(items))
+ mock_llm.ainvoke.return_value = Mock(content=json.dumps(items))
na = NewsAnalyzer(llm_client=mock_llm)
- result = na.extract_news_items([{"title": "source"}])
+ result = asyncio.run(na.extract_news_items([{"title": "source"}]))
assert len(result) == 2
headlines = {r["headline"] for r in result}
assert "Valid" in headlines
assert "Also valid" in headlines
def test_max_items_caps_output(self):
- mock_llm = Mock()
+ mock_llm = AsyncMock()
items = [{"headline": f"H{i}", "summary": f"S{i}"} for i in range(20)]
- mock_llm.invoke.return_value = Mock(content=json.dumps(items))
+ mock_llm.ainvoke.return_value = Mock(content=json.dumps(items))
na = NewsAnalyzer(llm_client=mock_llm)
- result = na.extract_news_items([{"title": "source"}], max_items=3)
+ result = asyncio.run(
+ na.extract_news_items([{"title": "source"}], max_items=3)
+ )
assert len(result) <= 3
diff --git a/tests/news/test_news_analyzer_extended.py b/tests/news/test_news_analyzer_extended.py
index f5c02022bd..bbcb33bf7d 100644
--- a/tests/news/test_news_analyzer_extended.py
+++ b/tests/news/test_news_analyzer_extended.py
@@ -16,7 +16,8 @@ Tests cover:
- _summarize_impact() helper
"""
-from unittest.mock import Mock, patch
+import asyncio
+from unittest.mock import AsyncMock, Mock, patch
class TestNewsAnalyzerInit:
@@ -27,7 +28,7 @@ class TestNewsAnalyzerInit:
with patch(
"local_deep_research.news.core.news_analyzer.get_llm"
) as mock_get_llm:
- mock_llm = Mock()
+ mock_llm = AsyncMock()
mock_get_llm.return_value = mock_llm
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
@@ -39,7 +40,7 @@ class TestNewsAnalyzerInit:
def test_init_with_custom_llm_client(self):
"""Initializes with provided LLM client."""
- mock_llm = Mock()
+ mock_llm = AsyncMock()
with patch(
"local_deep_research.news.core.news_analyzer.get_llm"
@@ -65,7 +66,7 @@ class TestAnalyzeNewsEmpty:
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer()
- result = analyzer.analyze_news([])
+ result = asyncio.run(analyzer.analyze_news([]))
assert result["items"] == []
assert result["item_count"] == 0
@@ -81,7 +82,7 @@ class TestAnalyzeNewsEmpty:
analyzer = NewsAnalyzer()
# Passing empty list as None would fail differently
- result = analyzer.analyze_news([])
+ result = asyncio.run(analyzer.analyze_news([]))
assert "items" in result
assert "timestamp" in result
@@ -153,7 +154,9 @@ class TestExtractNewsItemsNoLLM:
analyzer = NewsAnalyzer(llm_client=None)
# Manually set to None to bypass the default
analyzer.llm_client = None
- result = analyzer.extract_news_items([{"content": "test"}])
+ result = asyncio.run(
+ analyzer.extract_news_items([{"content": "test"}])
+ )
assert result == []
@@ -163,55 +166,57 @@ class TestExtractNewsItemsWithLLM:
def test_calls_llm_invoke(self):
"""Calls LLM invoke method."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="[]")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(content="[]")
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- analyzer.extract_news_items([{"content": "test news"}])
+ asyncio.run(analyzer.extract_news_items([{"content": "test news"}]))
- mock_llm.invoke.assert_called_once()
+ mock_llm.ainvoke.assert_called_once()
def test_parses_json_array_response(self):
"""Parses JSON array from response."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(
content='[{"headline": "Test News", "category": "tech", "summary": "A test", "impact_score": 5}]'
)
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([{"content": "test"}])
+ result = asyncio.run(analyzer.extract_news_items([{"content": "test"}]))
assert len(result) >= 0 # May filter invalid items
def test_handles_invalid_json_gracefully(self):
"""Handles invalid JSON gracefully."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="not json")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(content="not json")
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.extract_news_items([{"content": "test"}])
+ result = asyncio.run(analyzer.extract_news_items([{"content": "test"}]))
# Should not raise, returns empty or partial result
assert isinstance(result, list)
def test_respects_max_items_parameter(self):
"""Includes max_items in prompt."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="[]")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(content="[]")
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- analyzer.extract_news_items([{"content": "test"}], max_items=5)
+ asyncio.run(
+ analyzer.extract_news_items([{"content": "test"}], max_items=5)
+ )
# Check prompt includes max_items
- call_args = mock_llm.invoke.call_args[0][0]
+ call_args = mock_llm.ainvoke.call_args[0][0]
assert "5" in call_args
@@ -252,27 +257,31 @@ class TestGenerateBigPicture:
def test_returns_string(self):
"""Returns string result."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="Big picture summary")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(content="Big picture summary")
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_big_picture([{"headline": "Test"}])
+ result = asyncio.run(
+ analyzer.generate_big_picture([{"headline": "Test"}])
+ )
assert isinstance(result, str)
def test_calls_llm_with_news_items(self):
"""Calls LLM with news items."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="Summary")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(content="Summary")
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- analyzer.generate_big_picture([{"headline": "Breaking News"}])
+ asyncio.run(
+ analyzer.generate_big_picture([{"headline": "Breaking News"}])
+ )
- mock_llm.invoke.assert_called_once()
+ mock_llm.ainvoke.assert_called_once()
class TestGenerateWatchFor:
@@ -280,15 +289,17 @@ class TestGenerateWatchFor:
def test_returns_list(self):
"""Returns list of items to watch."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(
content="- Watch item 1\n- Watch item 2"
)
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for([{"headline": "Developing story"}])
+ result = asyncio.run(
+ analyzer.generate_watch_for([{"headline": "Developing story"}])
+ )
assert isinstance(result, list)
@@ -298,13 +309,15 @@ class TestGeneratePatterns:
def test_returns_string(self):
"""Returns string result."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="Patterns found")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(content="Patterns found")
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_patterns([{"headline": "Story 1"}])
+ result = asyncio.run(
+ analyzer.generate_patterns([{"headline": "Story 1"}])
+ )
assert isinstance(result, str)
@@ -315,7 +328,8 @@ class TestExtractTopics:
def test_returns_list(self):
"""Returns list of topics."""
with patch(
- "local_deep_research.news.core.news_analyzer.generate_topics"
+ "local_deep_research.news.core.news_analyzer.generate_topics_async",
+ new_callable=AsyncMock,
) as mock_gen:
mock_gen.return_value = ["AI", "Tech"]
@@ -329,7 +343,9 @@ class TestExtractTopics:
)
analyzer = NewsAnalyzer()
- result = analyzer.extract_topics([{"headline": "AI news"}])
+ result = asyncio.run(
+ analyzer.extract_topics([{"headline": "AI news"}])
+ )
assert isinstance(result, list)
@@ -439,33 +455,36 @@ class TestAnalyzeNewsIntegration:
def test_analyze_news_with_results(self):
"""analyze_news with valid results returns full analysis."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.return_value = Mock(
content='[{"headline": "Test", "category": "tech", "summary": "A test", "impact_score": 5}]'
)
with patch(
- "local_deep_research.news.core.news_analyzer.generate_topics"
+ "local_deep_research.news.core.news_analyzer.generate_topics_async",
+ new_callable=AsyncMock,
) as mock_gen:
mock_gen.return_value = ["test topic"]
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.analyze_news([{"content": "test content"}])
+ result = asyncio.run(
+ analyzer.analyze_news([{"content": "test content"}])
+ )
assert "items" in result
assert "timestamp" in result
def test_analyze_news_handles_llm_error(self):
"""analyze_news handles LLM errors gracefully."""
- mock_llm = Mock()
- mock_llm.invoke.side_effect = Exception("LLM error")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = Exception("LLM error")
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.analyze_news([{"content": "test"}])
+ result = asyncio.run(analyzer.analyze_news([{"content": "test"}]))
# Should return empty analysis on error
assert "items" in result
@@ -592,19 +611,21 @@ class TestGenerateBigPictureEdgeCases:
analyzer = NewsAnalyzer()
# Manually set llm_client to None for this test
analyzer.llm_client = None
- result = analyzer.generate_big_picture([])
+ result = asyncio.run(analyzer.generate_big_picture([]))
assert result == ""
def test_llm_error_returns_empty(self):
"""LLM error returns empty string."""
- mock_llm = Mock()
- mock_llm.invoke.side_effect = Exception("API error")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = Exception("API error")
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_big_picture([{"headline": "Test"}])
+ result = asyncio.run(
+ analyzer.generate_big_picture([{"headline": "Test"}])
+ )
assert result == ""
@@ -623,18 +644,20 @@ class TestGenerateWatchForEdgeCases:
analyzer = NewsAnalyzer()
analyzer.llm_client = None
- result = analyzer.generate_watch_for([])
+ result = asyncio.run(analyzer.generate_watch_for([]))
assert result == []
def test_llm_error_returns_empty_list(self):
"""LLM error returns empty list."""
- mock_llm = Mock()
- mock_llm.invoke.side_effect = Exception("API error")
+ mock_llm = AsyncMock()
+ mock_llm.ainvoke.side_effect = Exception("API error")
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
analyzer = NewsAnalyzer(llm_client=mock_llm)
- result = analyzer.generate_watch_for([{"headline": "Story"}])
+ result = asyncio.run(
+ analyzer.generate_watch_for([{"headline": "Story"}])
+ )
assert result == []
diff --git a/tests/news/test_news_analyzer_list_content.py b/tests/news/test_news_analyzer_list_content.py
index df502cacbc..63bb27aa08 100644
--- a/tests/news/test_news_analyzer_list_content.py
+++ b/tests/news/test_news_analyzer_list_content.py
@@ -7,7 +7,8 @@ raised AttributeError inside a broad ``except``, so each generator returned an
empty result instead of the model's text.
"""
-from unittest.mock import Mock
+import asyncio
+from unittest.mock import AsyncMock, Mock, patch
from local_deep_research.news.core.news_analyzer import NewsAnalyzer
@@ -26,8 +27,8 @@ NEWS_ITEMS = [
def _analyzer(text):
response = Mock()
response.content = [{"type": "text", "text": text}]
- analyzer = NewsAnalyzer(llm_client=Mock())
- analyzer.llm_client.invoke.return_value = response
+ analyzer = NewsAnalyzer(llm_client=AsyncMock())
+ analyzer.llm_client.ainvoke.return_value = response
return analyzer
@@ -35,7 +36,7 @@ def test_generate_big_picture_returns_model_text():
analyzer = _analyzer("The broader trend is consolidation.")
assert (
- analyzer.generate_big_picture(NEWS_ITEMS)
+ asyncio.run(analyzer.generate_big_picture(NEWS_ITEMS))
== "The broader trend is consolidation."
)
@@ -43,7 +44,7 @@ def test_generate_big_picture_returns_model_text():
def test_generate_watch_for_splits_lines():
analyzer = _analyzer("- First signal\n- Second signal")
- watch_for = analyzer.generate_watch_for(NEWS_ITEMS)
+ watch_for = asyncio.run(analyzer.generate_watch_for(NEWS_ITEMS))
assert any("First signal" in entry for entry in watch_for)
assert any("Second signal" in entry for entry in watch_for)
@@ -53,6 +54,37 @@ def test_generate_patterns_returns_model_text():
analyzer = _analyzer("Two unrelated stories share a supply chain cause.")
assert (
- analyzer.generate_patterns(NEWS_ITEMS)
+ asyncio.run(analyzer.generate_patterns(NEWS_ITEMS))
== "Two unrelated stories share a supply chain cause."
)
+
+
+def test_topic_generation_preserves_analyzer_settings_snapshot():
+ snapshot = {"llm.provider": "openai", "policy.egress_scope": "public_only"}
+ analyzer = NewsAnalyzer(llm_client=Mock(), settings_snapshot=snapshot)
+ with patch(
+ "local_deep_research.news.core.news_analyzer.generate_topics_async",
+ new_callable=AsyncMock,
+ return_value=["configured topic"],
+ ) as topics:
+ result = asyncio.run(
+ analyzer.extract_topics(
+ [
+ {
+ "headline": "H",
+ "summary": "S",
+ "category": "C",
+ "id": "item",
+ }
+ ]
+ )
+ )
+ topics.assert_awaited_once_with(
+ query="H",
+ findings="S",
+ category="C",
+ max_topics=3,
+ settings_snapshot=snapshot,
+ )
+ assert topics.await_args.kwargs["settings_snapshot"] is snapshot
+ assert result[0]["name"] == "configured topic"