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.

chore(lint): add ruff rules for logging, performance, exceptions, and print detection (#3211)

LearningCircuit12160e26e180
diff --git a/.pre-commit-hooks/check-sensitive-logging.py b/.pre-commit-hooks/check-sensitive-logging.py
index f31d2c34ac..ba019a39a8 100755
--- a/.pre-commit-hooks/check-sensitive-logging.py
+++ b/.pre-commit-hooks/check-sensitive-logging.py
@@ -159,7 +159,7 @@ class SensitiveLoggingChecker(ast.NodeVisitor):
}:
if isinstance(node.func.value, ast.Name):
return node.func.value.id == "logger"
- elif isinstance(node.func.value, ast.Attribute):
+ if isinstance(node.func.value, ast.Attribute):
# Handle self.logger, cls.logger, etc.
return node.func.value.attr == "logger"
return False
@@ -233,24 +233,24 @@ class SensitiveLoggingChecker(ast.NodeVisitor):
"""Check if an expression references any of the given variable names."""
if isinstance(expr, ast.Name):
return expr.id in var_names
- elif isinstance(expr, ast.JoinedStr):
+ if isinstance(expr, ast.JoinedStr):
# f-string: check each formatted value
return any(
isinstance(v, ast.FormattedValue)
and self._expr_references_vars(v.value, var_names)
for v in expr.values
)
- elif isinstance(expr, ast.Call):
+ if isinstance(expr, ast.Call):
# str(e), repr(e), type(e), etc.
return any(
self._expr_references_vars(a, var_names) for a in expr.args
)
- elif isinstance(expr, ast.BinOp):
+ if isinstance(expr, ast.BinOp):
# "message: %s" % e
return self._expr_references_vars(
expr.right, var_names
) or self._expr_references_vars(expr.left, var_names)
- elif isinstance(expr, ast.Tuple):
+ if isinstance(expr, ast.Tuple):
# ("message %s %s", e, other)
return any(
self._expr_references_vars(el, var_names) for el in expr.elts
diff --git a/examples/api_usage/http/advanced/http_api_examples.py b/examples/api_usage/http/advanced/http_api_examples.py
index b271050e81..837a1a9d92 100755
--- a/examples/api_usage/http/advanced/http_api_examples.py
+++ b/examples/api_usage/http/advanced/http_api_examples.py
@@ -164,8 +164,7 @@ class LDRClient:
if response.status_code == 200:
return response.json()
- else:
- raise Exception(f"Failed to start research: {response.text}")
+ raise Exception(f"Failed to start research: {response.text}")
def get_research_status(self, research_id: str) -> Dict[str, Any]:
"""Get the status of a research task."""
@@ -190,7 +189,7 @@ class LDRClient:
if status.get("status") == "completed":
return self.get_research_result(research_id)
- elif status.get("status") == "failed":
+ if status.get("status") == "failed":
raise Exception(
f"Research failed: {status.get('error', 'Unknown error')}"
)
diff --git a/examples/api_usage/http/advanced/simple_http_example.py b/examples/api_usage/http/advanced/simple_http_example.py
index 38bd5ffbc5..9234cf8164 100755
--- a/examples/api_usage/http/advanced/simple_http_example.py
+++ b/examples/api_usage/http/advanced/simple_http_example.py
@@ -221,7 +221,7 @@ def main():
if current_status == "completed":
print("🎉 Research completed successfully!")
break
- elif current_status == "failed":
+ if current_status == "failed":
print(
f"❌ Research failed: {status.get('error', 'Unknown error')}"
)
@@ -361,7 +361,7 @@ def main():
print("🎉 Results displayed successfully!")
break # Exit retry loop - success!
- elif results_response.status_code == 404:
+ if results_response.status_code == 404:
results_retries += 1
elapsed_time = results_retries * 10
print(
diff --git a/examples/llm_integration/advanced_custom_llm.py b/examples/llm_integration/advanced_custom_llm.py
index 366e93c1c1..bf0956d26c 100644
--- a/examples/llm_integration/advanced_custom_llm.py
+++ b/examples/llm_integration/advanced_custom_llm.py
@@ -175,7 +175,7 @@ def create_configured_llm(config: Dict[str, Any]) -> BaseChatModel:
retry_delay=config.get("retry_delay", 1.0),
)
- elif llm_type == "configurable":
+ if llm_type == "configurable":
return ConfigurableLLM(
model_name=config.get("model_name", "config-v1"),
response_style=config.get("style", "technical"),
@@ -183,15 +183,14 @@ def create_configured_llm(config: Dict[str, Any]) -> BaseChatModel:
include_confidence=config.get("include_confidence", False),
)
- elif llm_type == "expert":
+ if llm_type == "expert":
return DomainExpertLLM(
domain=config.get("domain", "general"),
expertise_level=config.get("expertise_level", 0.8),
)
- else:
- # Default fallback
- return ConfigurableLLM()
+ # Default fallback
+ return ConfigurableLLM()
def main():
diff --git a/examples/optimization/example_multi_benchmark.py b/examples/optimization/example_multi_benchmark.py
index 60da992936..25b34d0813 100644
--- a/examples/optimization/example_multi_benchmark.py
+++ b/examples/optimization/example_multi_benchmark.py
@@ -63,7 +63,7 @@ except ImportError:
"questions_per_iteration": 5,
"search_strategy": "parallel",
}, 0.78
- elif (
+ if (
"browsecomp" in benchmark_weights
and benchmark_weights["browsecomp"] > 0
):
@@ -73,13 +73,12 @@ except ImportError:
"questions_per_iteration": 2,
"search_strategy": "iterdrag",
}, 0.81
- else:
- # SimpleQA only (default)
- return {
- "iterations": 3,
- "questions_per_iteration": 2,
- "search_strategy": "standard",
- }, 0.75
+ # SimpleQA only (default)
+ return {
+ "iterations": 3,
+ "questions_per_iteration": 2,
+ "search_strategy": "standard",
+ }, 0.75
def optimize_for_quality(*args, **kwargs):
benchmark_weights = kwargs.get(
diff --git a/pyproject.toml b/pyproject.toml
index 035dcf73f5..1f4b5971c2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -247,9 +247,17 @@ indent-width = 4
[tool.ruff.lint]
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
-select = ["E4", "E7", "E9", "F", "S"]
+select = [
+ "E4", "E7", "E9", "F", "S",
+ # --- Wave 2: logging, performance, return style, exceptions, print, comprehensions ---
+ "G", # flake8-logging-format: lazy formatting in logger calls
+ "PERF", # perflint: performance anti-patterns
+ "RET", # flake8-return: unnecessary assign-before-return, superfluous else
+ "TRY", # tryceratops: exception handling patterns
+ "T20", # flake8-print: print statement detection in production code
+ "C4", # flake8-comprehensions: unnecessary comprehensions/calls
+]
ignore = [
- "E722",
# --- Bandit (S) rules suppressed globally for existing code patterns ---
# try-except-pass/continue: pervasive cleanup pattern throughout codebase
"S110", # try-except-pass
@@ -258,6 +266,12 @@ ignore = [
"S603", # subprocess-without-shell-equals-true
"S606", # start-process-with-no-shell
"S607", # start-process-with-partial-path
+ # --- Wave 2: rules ignored initially due to high violation counts ---
+ # TODO: fix violations and remove ignore
+ "TRY003", # raise-vanilla-args — overly pedantic for built-in exceptions
+ "TRY004", # type-check-without-type-error — breaks API contracts; ruff autofix was removed
+ "TRY300", # try-consider-else — unintuitive syntax; conflicts with RET505
+ "PERF401", # manual-list-comprehension — no reliable autofix; negligible real-world impact
]
# Allow fix for all enabled rules (when `--fix`) is provided.
@@ -268,14 +282,27 @@ unfixable = []
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
[tool.ruff.lint.per-file-ignores]
-# Tests: assert is the standard pattern; hardcoded values are test fixtures
-"tests/**" = ["S101", "S104", "S105", "S106", "S107", "S108", "S113", "S311", "S324", "S602", "S608"]
-# Examples: hardcoded passwords are demo values; random is for simulation
-"examples/**" = ["S105", "S311"]
+# Tests: assert is the standard pattern; hardcoded values are test fixtures; print is fine
+"tests/**" = ["S101", "S104", "S105", "S106", "S107", "S108", "S113", "S311", "S324", "S602", "S608", "T20", "TRY201", "G004", "C420", "TRY002", "C408", "C401", "C416", "C414", "PERF102", "PERF402", "PERF403", "RET503", "RET504", "TRY301"]
+# Examples: hardcoded values are demo fixtures; print is fine; bare exceptions acceptable
+"examples/**" = ["S105", "S311", "T201", "TRY002", "C408", "C401", "C416", "PERF102", "PERF402", "PERF403", "RET503", "RET502", "RET504", "TRY301"]
# Cookiecutter hooks: shell=True is needed for cross-platform compat
-"cookiecutter-docker/**" = ["S602"]
+"cookiecutter-docker/**" = ["S602", "T201"]
# CI scripts: test password is intentional
"scripts/ci/**" = ["S105"]
+# Pre-commit hooks: print is the interface
+".pre-commit-hooks/**" = ["T201", "RET503", "RET504"]
+# Scripts: print is the interface
+"scripts/**" = ["T201"]
+".github/scripts/**" = ["T201"]
+# CLI modules: print is the interface
+"src/local_deep_research/cli/**" = ["T201"]
+# Benchmarks: print is used for output/reporting (includes benchmarks/cli.py)
+"src/local_deep_research/benchmarks/**" = ["T201"]
+# Web/settings files with intentional print for startup/debug
+"src/local_deep_research/settings/logger.py" = ["T201"]
+"src/local_deep_research/web/routes/route_registry.py" = ["T201"]
+"src/local_deep_research/web_search_engines/rate_limiting/cli.py" = ["T201"]
# Server config: binding to 0.0.0.0 is intentional for containerized deployment
"src/local_deep_research/web/server_config.py" = ["S104"]
"src/local_deep_research/web/routes/settings_routes.py" = ["S104"]
diff --git a/scripts/generate_config_docs.py b/scripts/generate_config_docs.py
index 976626b505..5fe7c8f78c 100755
--- a/scripts/generate_config_docs.py
+++ b/scripts/generate_config_docs.py
@@ -348,12 +348,11 @@ def generate_docs(
if existing == new_content:
print("OK: Configuration docs are up to date.")
return 0
- else:
- print(
- f"FAIL: {output_file} is out of date. "
- "Run 'python scripts/generate_config_docs.py' to regenerate it."
- )
- return 1
+ print(
+ f"FAIL: {output_file} is out of date. "
+ "Run 'python scripts/generate_config_docs.py' to regenerate it."
+ )
+ return 1
output_file.parent.mkdir(parents=True, exist_ok=True)
output_file.write_text(new_content)
diff --git a/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py b/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py
index 926d4cad3e..b23a4f8701 100644
--- a/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py
+++ b/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py
@@ -177,17 +177,16 @@ class BrowseCompAnswerDecoder:
try:
if scheme == "base64":
return self._decode_base64(text)
- elif scheme == "hex":
+ if scheme == "hex":
return self._decode_hex(text)
- elif scheme == "url_encoding":
+ if scheme == "url_encoding":
return self._decode_url(text)
- elif scheme == "rot13":
+ if scheme == "rot13":
return self._decode_rot13(text)
- elif scheme == "caesar_cipher":
+ if scheme == "caesar_cipher":
return self._decode_caesar(text)
- else:
- logger.warning(f"Unknown decoding scheme: {scheme}")
- return None
+ logger.warning(f"Unknown decoding scheme: {scheme}")
+ return None
except Exception as e:
logger.debug(f"Failed to apply {scheme} decoding: {e}")
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py
index 48f5c11233..13d092ea0b 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py
@@ -205,18 +205,17 @@ class AdaptiveExplorer(BaseCandidateExplorer):
try:
if strategy == "direct_search":
return self._direct_search_query(base_query)
- elif strategy == "synonym_expansion":
+ if strategy == "synonym_expansion":
return self._synonym_expansion_query(base_query)
- elif strategy == "category_exploration":
+ if strategy == "category_exploration":
return self._category_exploration_query(
base_query, found_candidates
)
- elif strategy == "related_terms":
+ if strategy == "related_terms":
return self._related_terms_query(base_query, found_candidates)
- elif strategy == "constraint_focused" and constraints:
+ if strategy == "constraint_focused" and constraints:
return self._constraint_focused_query(base_query, constraints)
- else:
- return self._direct_search_query(base_query)
+ return self._direct_search_query(base_query)
except Exception:
logger.exception(f"Error generating query with strategy {strategy}")
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py
index 0a6c79aa00..479e270642 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py
@@ -132,17 +132,16 @@ class BaseCandidateExplorer(ABC):
f"Search '{query[:50]}...' returned {len(results)} results"
)
return formatted_results
- elif isinstance(results, dict):
+ if isinstance(results, dict):
# If results is already a dict, use it as is
result_count = len(results.get("results", []))
logger.info(
f"Search '{query[:50]}...' returned {result_count} results"
)
return results
- else:
- # Unknown format, return empty
- logger.warning(f"Unknown search result format: {type(results)}")
- return {"results": [], "query": query}
+ # Unknown format, return empty
+ logger.warning(f"Unknown search result format: {type(results)}")
+ return {"results": [], "query": query}
except Exception:
logger.exception(f"Error executing search '{query}'")
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/diversity_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/diversity_explorer.py
index 6b70645536..2871f9bb69 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/diversity_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/diversity_explorer.py
@@ -207,31 +207,28 @@ class DiversityExplorer(BaseCandidateExplorer):
# Simple categorization based on common patterns
if any(word in name for word in ["mountain", "peak", "summit", "hill"]):
return "mountain"
- elif any(
+ if any(
word in name
for word in ["lake", "river", "creek", "stream", "pond"]
):
return "water"
- elif any(
+ if any(
word in name for word in ["park", "forest", "reserve", "wilderness"]
):
return "park"
- elif any(word in name for word in ["trail", "path", "route", "way"]):
+ if any(word in name for word in ["trail", "path", "route", "way"]):
return "trail"
- elif any(word in name for word in ["canyon", "gorge", "valley", "gap"]):
+ if any(word in name for word in ["canyon", "gorge", "valley", "gap"]):
return "canyon"
- elif any(
+ if any(
word in name for word in ["cliff", "bluff", "overlook", "viewpoint"]
):
return "viewpoint"
- elif any(
- word in name for word in ["island", "beach", "coast", "shore"]
- ):
+ if any(word in name for word in ["island", "beach", "coast", "shore"]):
return "coastal"
- elif any(word in name for word in ["city", "town", "county", "state"]):
+ if any(word in name for word in ["city", "town", "county", "state"]):
return "place"
- else:
- return "other"
+ return "other"
def _calculate_diversity_score(self, candidates: List[Candidate]) -> float:
"""Calculate diversity score for a set of candidates."""
@@ -271,14 +268,12 @@ class DiversityExplorer(BaseCandidateExplorer):
)
threshold = avg_count * 0.5 # Categories with less than 50% of average
- underrepresented = [
+ return [
category
for category, count in self.category_counts.items()
if count < threshold and count < self.category_limit
]
- return underrepresented
-
def _generate_diversity_queries(
self,
base_query: str,
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py
index a0b0b0435f..d646921d72 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py
@@ -201,7 +201,7 @@ class ProgressiveExplorer:
)[0]
# Combine candidate with uncovered entities
- for entity_type, entity_list in uncovered.items():
+ for entity_list in uncovered.values():
for entity in entity_list[:2]:
search = f'"{top_candidate}" {entity}'
if search.lower() not in self.progress.searched_terms:
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py
index ad510c6e78..25c592ef65 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py
@@ -92,11 +92,8 @@ class BaseConstraintChecker(ABC):
"""Gather evidence for a constraint using the provided evidence gatherer."""
if self.evidence_gatherer:
return self.evidence_gatherer(candidate, constraint)
- else:
- logger.warning(
- "No evidence gatherer provided - cannot gather evidence"
- )
- return []
+ logger.warning("No evidence gatherer provided - cannot gather evidence")
+ return []
def _log_constraint_result(
self,
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py
index 7d199ae6ed..dd70494d1c 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py
@@ -216,8 +216,5 @@ class ConstraintChecker:
"""Gather evidence for a constraint using the provided evidence gatherer."""
if self.evidence_gatherer:
return self.evidence_gatherer(candidate, constraint)
- else:
- logger.warning(
- "No evidence gatherer provided - cannot gather evidence"
- )
- return []
+ logger.warning("No evidence gatherer provided - cannot gather evidence")
+ return []
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py
index a966ea3dcf..b257ac9e33 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py
@@ -233,22 +233,21 @@ class DualConfidenceChecker(BaseConstraintChecker):
f"(round {reevaluation_count}) - high uncertainty: {avg_uncertainty:.0%}"
)
continue
- else:
- # Final result or early rejection
- if reevaluation_count > 0:
- logger.info(
- f"✅ Final evaluation for {candidate.name} | {constraint.value} "
- f"after {reevaluation_count} re-evaluation(s)"
- )
+ # Final result or early rejection
+ if reevaluation_count > 0:
+ logger.info(
+ f"✅ Final evaluation for {candidate.name} | {constraint.value} "
+ f"after {reevaluation_count} re-evaluation(s)"
+ )
- return {
- "positive": avg_positive,
- "negative": avg_negative,
- "uncertainty": avg_uncertainty,
- "score": score,
- "evidence_list": evidence_list,
- "reevaluation_count": reevaluation_count,
- }
+ return {
+ "positive": avg_positive,
+ "negative": avg_negative,
+ "uncertainty": avg_uncertainty,
+ "score": score,
+ "evidence_list": evidence_list,
+ "reevaluation_count": reevaluation_count,
+ }
# Should not reach here, but fallback
return {
@@ -394,19 +393,18 @@ Just give the number:"""
}
],
}
- else:
- return {
- "should_reject": True,
- "reason": f"Poor answer quality: {quality_score}%",
- "detailed_results": [
- {
- "constraint": "answer_quality",
- "negative_confidence": (100 - quality_score)
- / 100.0,
- "source": "answer_quality_check",
- }
- ],
- }
+ return {
+ "should_reject": True,
+ "reason": f"Poor answer quality: {quality_score}%",
+ "detailed_results": [
+ {
+ "constraint": "answer_quality",
+ "negative_confidence": (100 - quality_score)
+ / 100.0,
+ "source": "answer_quality_check",
+ }
+ ],
+ }
# Parsing failed - accept by default
return {
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py b/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py
index 07bc17d00e..060806ccf9 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py
@@ -393,55 +393,47 @@ class IntelligentConstraintRelaxer:
relaxed_constraint.text = relaxed_text
return relaxed_constraint
- else:
- # If we can't copy the constraint, return a simple string representation
- return relaxed_text
+ # If we can't copy the constraint, return a simple string representation
+ return relaxed_text
def _get_constraint_type(self, constraint: object) -> str:
"""Extract constraint type from constraint object."""
if hasattr(constraint, "type"):
if hasattr(constraint.type, "value"):
return constraint.type.value
- else:
- return str(constraint.type)
- elif hasattr(constraint, "constraint_type"):
+ return str(constraint.type)
+ if hasattr(constraint, "constraint_type"):
return constraint.constraint_type
- else:
- # Try to infer from constraint text
- constraint_text = str(constraint).lower()
-
- if any(
- word in constraint_text
- for word in ["name", "called", "known as"]
- ):
- return "NAME_PATTERN"
- elif any(
- word in constraint_text
- for word in ["location", "country", "city"]
- ):
- return "LOCATION"
- elif any(
- word in constraint_text
- for word in ["year", "date", "when", "time"]
- ):
- return "TEMPORAL"
- elif any(
- word in constraint_text
- for word in ["number", "count", "amount"]
- ):
- return "STATISTIC"
- elif any(
- word in constraint_text
- for word in ["event", "happened", "occurred"]
- ):
- return "EVENT"
- elif any(
- word in constraint_text
- for word in ["than", "more", "less", "compared"]
- ):
- return "COMPARISON"
- else:
- return "PROPERTY"
+ # Try to infer from constraint text
+ constraint_text = str(constraint).lower()
+
+ if any(
+ word in constraint_text for word in ["name", "called", "known as"]
+ ):
+ return "NAME_PATTERN"
+ if any(
+ word in constraint_text for word in ["location", "country", "city"]
+ ):
+ return "LOCATION"
+ if any(
+ word in constraint_text for word in ["year", "date", "when", "time"]
+ ):
+ return "TEMPORAL"
+ if any(
+ word in constraint_text for word in ["number", "count", "amount"]
+ ):
+ return "STATISTIC"
+ if any(
+ word in constraint_text
+ for word in ["event", "happened", "occurred"]
+ ):
+ return "EVENT"
+ if any(
+ word in constraint_text
+ for word in ["than", "more", "less", "compared"]
+ ):
+ return "COMPARISON"
+ return "PROPERTY"
def analyze_relaxation_impact(
self,
diff --git a/src/local_deep_research/advanced_search_system/constraints/base_constraint.py b/src/local_deep_research/advanced_search_system/constraints/base_constraint.py
index 07cdd8775b..1d87d834da 100644
--- a/src/local_deep_research/advanced_search_system/constraints/base_constraint.py
+++ b/src/local_deep_research/advanced_search_system/constraints/base_constraint.py
@@ -40,14 +40,13 @@ class Constraint:
"""Convert constraint to search terms."""
if self.type == ConstraintType.PROPERTY:
return self.value
- elif self.type == ConstraintType.NAME_PATTERN:
+ if self.type == ConstraintType.NAME_PATTERN:
return f"{self.value} name trail mountain"
- elif self.type == ConstraintType.EVENT:
+ if self.type == ConstraintType.EVENT:
return f"{self.value} accident incident"
- elif self.type == ConstraintType.STATISTIC:
+ if self.type == ConstraintType.STATISTIC:
return f"{self.value} statistics data"
- else:
- return str(self.value)
+ return str(self.value)
def is_critical(self) -> bool:
"""Determine if this is a critical constraint that must be satisfied."""
diff --git a/src/local_deep_research/advanced_search_system/evidence/evaluator.py b/src/local_deep_research/advanced_search_system/evidence/evaluator.py
index e706dccb6f..0c9a900a51 100644
--- a/src/local_deep_research/advanced_search_system/evidence/evaluator.py
+++ b/src/local_deep_research/advanced_search_system/evidence/evaluator.py
@@ -150,10 +150,9 @@ QUOTE: [relevant text]
# This is a simplified version - could be made more sophisticated
if constraint.value.lower() in evidence.claim.lower():
return 1.0
- elif any(
+ if any(
word in evidence.claim.lower()
for word in constraint.value.lower().split()
):
return 0.8
- else:
- return 0.6 # Partial match at best
+ return 0.6 # Partial match at best
diff --git a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
index 497077eb69..622bd4279e 100644
--- a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
@@ -216,15 +216,14 @@ If no results seem relevant to the query, return an empty array: []"""
reindex=reindex,
start_index=start_index,
)
- else:
- logger.info(
- "Could not find JSON array in response, returning original results"
- )
- return self._prepare_and_return(
- results[: min(self.max_results, len(results))],
- reindex=reindex,
- start_index=start_index,
- )
+ logger.info(
+ "Could not find JSON array in response, returning original results"
+ )
+ return self._prepare_and_return(
+ results[: min(self.max_results, len(results))],
+ reindex=reindex,
+ start_index=start_index,
+ )
except Exception:
logger.exception("Cross-engine filtering error")
diff --git a/src/local_deep_research/advanced_search_system/findings/repository.py b/src/local_deep_research/advanced_search_system/findings/repository.py
index f90e227e7b..5812069304 100644
--- a/src/local_deep_research/advanced_search_system/findings/repository.py
+++ b/src/local_deep_research/advanced_search_system/findings/repository.py
@@ -386,7 +386,7 @@ Use IEEE style citations [1], [2], etc. Never make up your own citations.
@contextmanager
def timeout(seconds, message="Operation timed out"):
def signal_handler(signum, frame):
- raise TimeoutError(message)
+ raise TimeoutError(message) # noqa: TRY301 — signal handler, not caught by enclosing try
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
@@ -456,17 +456,16 @@ Use IEEE style citations [1], [2], etc. Never make up your own citations.
# Return more detailed error message based on type
if error_type == "timeout":
return "Error: Failed to synthesize final answer due to LLM timeout. Please check your connection or try again later."
- elif error_type == "token_limit":
+ if error_type == "token_limit":
return "Error: Failed to synthesize final answer due to token limit exceeded. Try reducing the scope of your query."
- elif error_type == "rate_limit":
+ if error_type == "rate_limit":
return "Error: Failed to synthesize final answer due to LLM rate limit. Please try again in a few minutes."
- elif error_type == "connection":
+ if error_type == "connection":
return "Error: Failed to synthesize final answer due to connection issues. Please check your internet connection and LLM service status."
- elif error_type == "authentication":
+ if error_type == "authentication":
return "Error: Failed to synthesize final answer due to authentication issues. Please check your API keys."
- else:
- # Generic error with details
- return f"Error: Failed to synthesize final answer. LLM error: {invoke_error!s}"
+ # Generic error with details
+ return f"Error: Failed to synthesize final answer. LLM error: {invoke_error!s}"
except Exception as e:
# Catch potential errors during prompt construction or logging itself
diff --git a/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py b/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py
index 7038594286..381b7271a0 100644
--- a/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py
+++ b/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py
@@ -54,7 +54,7 @@ class FollowUpContextHandler:
logger.info(f"Building context for follow-up: {follow_up_query}")
# Extract all components
- context = {
+ return {
"parent_research_id": research_data.get("research_id", ""),
"original_query": research_data.get("query", ""),
"follow_up_query": follow_up_query,
@@ -68,8 +68,6 @@ class FollowUpContextHandler:
"metadata": self._extract_metadata(research_data),
}
- return context
-
def _extract_findings(self, research_data: Dict) -> str:
"""
Extract and format findings from past research.
@@ -94,8 +92,7 @@ class FollowUpContextHandler:
if not findings_parts:
return "No previous findings available"
- combined = "\n\n".join(findings_parts)
- return combined
+ return "\n\n".join(findings_parts)
def _extract_sources(self, research_data: Dict) -> List[Dict]:
"""
diff --git a/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py b/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py
index 25a935a9a1..9d786097f2 100644
--- a/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py
+++ b/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py
@@ -141,8 +141,7 @@ class AdaptiveQueryGenerator:
template_vars["value"] = constraint.value
try:
- query = best_pattern.template.format(**template_vars)
- return query
+ return best_pattern.template.format(**template_vars)
except KeyError:
return None
diff --git a/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py b/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py
index 0f37d958a7..a515150c33 100644
--- a/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py
+++ b/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py
@@ -106,7 +106,6 @@ DESCRIPTORS: [entity1], [entity2], ...
"descriptors": [],
}
- # current_category = None # Not currently used
for line in content.strip().split("\n"):
line = line.strip()
if ":" in line:
@@ -229,9 +228,7 @@ DESCRIPTORS: [entity1], [entity2], ...
strategy_instruction = ""
if results_by_iteration:
# Check if recent searches are failing (returning 0 results)
- recent_iterations = [
- i for i in range(max(1, iteration - 5), iteration)
- ]
+ recent_iterations = list(range(max(1, iteration - 5), iteration))
zero_count = sum(
1
for i in recent_iterations
diff --git a/src/local_deep_research/advanced_search_system/questions/flexible_browsecomp_question.py b/src/local_deep_research/advanced_search_system/questions/flexible_browsecomp_question.py
index 120a1151d9..93368fe2dd 100644
--- a/src/local_deep_research/advanced_search_system/questions/flexible_browsecomp_question.py
+++ b/src/local_deep_research/advanced_search_system/questions/flexible_browsecomp_question.py
@@ -30,7 +30,7 @@ class FlexibleBrowseCompQuestionGenerator(BrowseCompQuestionGenerator):
"""Generate searches with more freedom and less rigid instructions."""
# Check if recent searches are failing
- recent_iterations = [i for i in range(max(1, iteration - 5), iteration)]
+ recent_iterations = list(range(max(1, iteration - 5), iteration))
zero_count = sum(
1 for i in recent_iterations if results_by_iteration.get(i, 1) == 0
)
diff --git a/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py b/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py
index 1e5b098385..bc479e87a2 100644
--- a/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py
+++ b/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py
@@ -142,7 +142,7 @@ Evidence: [explanation]
for c in constraints:
type_groups[c.type].append(c)
- for ctype, group in type_groups.items():
+ for group in type_groups.values():
if len(group) > 1:
cluster = ConstraintCluster(
constraints=group,
diff --git a/src/local_deep_research/advanced_search_system/source_management/diversity_manager.py b/src/local_deep_research/advanced_search_system/source_management/diversity_manager.py
index aa67c641ce..e2116f5d2e 100644
--- a/src/local_deep_research/advanced_search_system/source_management/diversity_manager.py
+++ b/src/local_deep_research/advanced_search_system/source_management/diversity_manager.py
@@ -472,9 +472,9 @@ Return up to 3 topic areas, one per line.
# Source type gaps
if metrics.type_diversity < 0.7:
- current_types = set(
+ current_types = {
p.source_type for p in self.source_profiles.values()
- )
+ }
desired_types = {"academic", "government", "news", "wiki"}
missing_types = desired_types - current_types
if missing_types:
diff --git a/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py b/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py
index 47596d936a..79c4fe468d 100644
--- a/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py
@@ -258,16 +258,15 @@ CONFIDENCE: [0-1 score of how confident we are in the current answer]
"""
if step.step_type == StepType.CONSTRAINT_EXTRACTION:
return self._extract_constraints(query)
- elif step.step_type == StepType.INITIAL_SEARCH:
+ if step.step_type == StepType.INITIAL_SEARCH:
return self._perform_initial_search(step.description)
- elif step.step_type == StepType.VERIFICATION:
+ if step.step_type == StepType.VERIFICATION:
return self._verify_candidates(step.description)
- elif step.step_type == StepType.REFINEMENT:
+ if step.step_type == StepType.REFINEMENT:
return self._refine_search(step.description)
- elif step.step_type == StepType.SYNTHESIS:
+ if step.step_type == StepType.SYNTHESIS:
return self._synthesize_current_knowledge(query)
- else:
- return step
+ return step
def _extract_constraints(self, query: str) -> StepResult:
"""Extract specific constraints and clues from the query.
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
index 0c06ac4de2..c60eb6d820 100644
--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
@@ -334,12 +334,11 @@ class BrowseCompEntityStrategy(BaseSearchStrategy):
# Default based on common patterns
if "who" in query_lower:
return "person"
- elif "which" in query_lower:
+ if "which" in query_lower:
return "product"
- elif "what" in query_lower and "company" in query_lower:
+ if "what" in query_lower and "company" in query_lower:
return "company"
- else:
- return "entity"
+ return "entity"
async def _discover_entities(
self,
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
index 60263b6cb7..0d694452be 100644
--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
@@ -313,12 +313,12 @@ ALL_CLUES_SUMMARY:
for clue in unverified_clues
):
return f"{top_candidate['name']} accident fall death {' '.join(self.query_clues.temporal_clues[:1])}"
- elif any(
+ if any(
"search and rescue" in clue.lower() or "sar" in clue.lower()
for clue in unverified_clues
):
return f"{top_candidate['name']} search and rescue incidents 2014 statistics"
- elif any("84.5" in clue for clue in unverified_clues):
+ if any("84.5" in clue for clue in unverified_clues):
return f"{top_candidate['name']} 2014 search rescue statistics Grand Canyon 2022 comparison"
# Initial searches - combine multiple clues
@@ -335,7 +335,7 @@ ALL_CLUES_SUMMARY:
return " ".join(key_terms)
# Second iteration - add temporal/incident info
- elif self.iteration == 2:
+ if self.iteration == 2:
key_terms = []
if self.query_clues.temporal_clues:
key_terms.extend(self.query_clues.temporal_clues[:1])
@@ -378,7 +378,7 @@ ALL_CLUES_SUMMARY:
return " ".join(
self.query_clues.comparison_clues[:1] + ["statistics data"]
)
- elif self.query_clues.numerical_clues:
+ if self.query_clues.numerical_clues:
return " ".join(
self.query_clues.numerical_clues[:1]
+ ["official statistics 2014 2022"]
diff --git a/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
index 016d1473c1..feb9dccfc6 100644
--- a/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
@@ -1201,12 +1201,11 @@ Return one {entity_type} name per line. Only include names that could satisfy th
"current_knowledge": current_knowledge,
"search_results": search_results,
}
- else:
- # Return empty knowledge if no results
- return {
- "current_knowledge": f"No results found for query: {search_query}",
- "search_results": [],
- }
+ # Return empty knowledge if no results
+ return {
+ "current_knowledge": f"No results found for query: {search_query}",
+ "search_results": [],
+ }
except Exception as e:
logger.exception("Simple search error")
return {
diff --git a/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py b/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
index 8bb789d72a..f5f38719c5 100644
--- a/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
@@ -278,10 +278,9 @@ class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
try:
results = self._execute_search(query)
- evidence = self._extract_evidence_from_results(
+ return self._extract_evidence_from_results(
results, candidate, constraint
)
- return evidence
except Exception:
logger.exception(f"Error gathering evidence for {candidate.name}")
return []
@@ -344,16 +343,16 @@ class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
for word in ["definitely", "certainly", "absolutely"]
):
return 0.9
- elif any(
+ if any(
word in response.lower()
for word in ["likely", "probably", "appears"]
):
return 0.7
- elif any(
+ if any(
word in response.lower() for word in ["possibly", "maybe", "might"]
):
return 0.5
- elif any(
+ if any(
word in response.lower() for word in ["unlikely", "doubtful", "not"]
):
return 0.3
diff --git a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
index ec83b9d27c..d634cddbca 100644
--- a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
@@ -1241,9 +1241,8 @@ Include which constraints were satisfied and which weren't.
if top_score >= self.confidence_threshold:
return "Verifying top candidate"
- elif top_score >= 0.7:
+ if top_score >= 0.7:
return "Gathering final evidence"
- elif top_score >= 0.5:
+ if top_score >= 0.5:
return "Refining candidate scores"
- else:
- return "Exploring candidate evidence"
+ return "Exploring candidate evidence"
diff --git a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py
index 88e061fa88..ec381c5323 100644
--- a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py
+++ b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py
@@ -103,7 +103,7 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
def _initialize_patterns(self) -> Dict[str, QueryPattern]:
"""Initialize query patterns for different constraint types."""
- patterns = {
+ return {
"property_basic": QueryPattern(
pattern="{value} {constraint_type}",
constraint_types=[ConstraintType.PROPERTY],
@@ -128,11 +128,10 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
constraint_types=[],
),
}
- return patterns
def _initialize_sources(self) -> Dict[str, SourceProfile]:
"""Initialize source profiles for diversity tracking."""
- sources = {
+ return {
"wikipedia": SourceProfile(
source_name="wikipedia",
specialties=["characters", "properties", "general"],
@@ -151,7 +150,6 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
),
"web": SourceProfile(source_name="web", specialties=["general"]),
}
- return sources
def analyze_topic(self, query: str) -> Dict:
"""Analyze a topic using enhanced evidence-based approach."""
diff --git a/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py
index 88a3a3c29f..7a22670f2f 100644
--- a/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py
@@ -308,7 +308,7 @@ Return only the queries, one per line.
type_groups[c.type].append(c)
# Try different evidence gathering strategies
- for constraint_type, constraints in type_groups.items():
+ for constraints in type_groups.values():
# Try single constraint
for c in constraints[:2]:
query = self._create_evidence_query(candidate, [c])
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py
index adf5a4c197..30310434b4 100644
--- a/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py
@@ -447,28 +447,6 @@ Your refinement query can be as long and specific as needed to get good results.
content = get_llm_response_text(response)
evaluation = extract_json(content, expected_type=dict)
- if evaluation is None:
- raise ValueError("Could not parse JSON from LLM response")
-
- # Validate and clean up the evaluation
- if "action" not in evaluation:
- evaluation["action"] = "COMPLETE"
-
- evaluation["action"] = evaluation["action"].upper()
- if evaluation["action"] not in ["REFINE", "COMPLETE"]:
- evaluation["action"] = "COMPLETE"
-
- # Ensure confidence is a float between 0 and 1
- evaluation["confidence"] = max(
- 0.0, min(1.0, float(evaluation.get("confidence", 0.5)))
- )
-
- # Ensure gaps is a list
- if not isinstance(evaluation.get("gaps", []), list):
- evaluation["gaps"] = []
-
- return evaluation
-
except Exception as e:
logger.exception("Error in LLM evaluation")
# Return default to continue without refinement
@@ -480,6 +458,34 @@ Your refinement query can be as long and specific as needed to get good results.
"refinement_query": None,
}
+ if evaluation is None:
+ return {
+ "action": "COMPLETE",
+ "confidence": 0.5,
+ "gaps": [],
+ "reasoning": "Could not parse JSON from LLM response",
+ "refinement_query": None,
+ }
+
+ # Validate and clean up the evaluation
+ if "action" not in evaluation:
+ evaluation["action"] = "COMPLETE"
+
+ evaluation["action"] = evaluation["action"].upper()
+ if evaluation["action"] not in ["REFINE", "COMPLETE"]:
+ evaluation["action"] = "COMPLETE"
+
+ # Ensure confidence is a float between 0 and 1
+ evaluation["confidence"] = max(
+ 0.0, min(1.0, float(evaluation.get("confidence", 0.5)))
+ )
+
+ # Ensure gaps is a list
+ if not isinstance(evaluation.get("gaps", []), list):
+ evaluation["gaps"] = []
+
+ return evaluation
+
def _build_research_context(
self, results: Dict, original_query: str
) -> Dict:
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
index 9e80e3f715..78292d050f 100644
--- a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
@@ -98,7 +98,7 @@ Initial Search Results:
"""IterDRAG implementation of the topic analysis process."""
findings = []
current_knowledge = ""
- section_links = list()
+ section_links = []
self._update_progress(
"Initializing IterDRAG research system",
@@ -263,7 +263,6 @@ Initial Search Results:
}
findings.append(finding)
# Optionally update current_knowledge even if analysis failed?
- # current_knowledge += f"\n\nError analyzing results for: {sub_query}"
# Final answer synthesis based on all sub-query findings
self._update_progress(
diff --git a/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
index ee6a9f98f8..488de0848d 100644
--- a/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
@@ -83,9 +83,7 @@ class LLMConstraintProcessor:
"""LLM generates smart combinations of atomic elements"""
# Flatten all elements for the LLM to see
- all_elements = {}
- for constraint_id, elements in decomposed_constraints.items():
- all_elements[constraint_id] = elements
+ all_elements = dict(decomposed_constraints.items())
prompt = f"""
I have decomposed constraints into these atomic elements:
diff --git a/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py b/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py
index b9abfaff3a..d60b8e2c85 100644
--- a/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py
@@ -289,7 +289,7 @@ class MCPSearchStrategy(BaseSearchStrategy):
)
break
- elif parsed["type"] == "action":
+ if parsed["type"] == "action":
# LLM wants to call a tool
tool_name = parsed.get("tool")
arguments = parsed.get("arguments", {})
@@ -533,9 +533,7 @@ class MCPSearchStrategy(BaseSearchStrategy):
"questions": questions,
"formatted_findings": formatted_output,
"current_knowledge": synthesized_content,
- "sources": list(
- set(s for s in self._sources if isinstance(s, str))
- ),
+ "sources": list({s for s in self._sources if isinstance(s, str)}),
"search_results": self.all_search_results,
"documents": documents,
"reasoning_trace": self._history,
@@ -1051,18 +1049,17 @@ class MCPSearchStrategy(BaseSearchStrategy):
if "executor" in tool:
# Built-in tool with executor function
return tool["executor"](arguments)
- elif "mcp_server" in tool:
+ if "mcp_server" in tool:
# MCP tool
return self._execute_mcp_tool(
tool["mcp_server"],
tool["mcp_tool"],
arguments,
)
- else:
- return {
- "status": "error",
- "content": f"Tool {tool_name} has no executor",
- }
+ return {
+ "status": "error",
+ "content": f"Tool {tool_name} has no executor",
+ }
def _execute_web_search(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
"""Execute web search tool."""
@@ -1187,10 +1184,9 @@ class MCPSearchStrategy(BaseSearchStrategy):
return {"status": "success", "content": formatted_content}
- else:
- error_msg = result.get("error", "Download failed")
- logger.warning(f"Content download failed: {error_msg}")
- return {"status": "error", "content": error_msg}
+ error_msg = result.get("error", "Download failed")
+ logger.warning(f"Content download failed: {error_msg}")
+ return {"status": "error", "content": error_msg}
except ImportError:
logger.warning("ContentFetcher not available")
@@ -1421,8 +1417,7 @@ class MCPSearchStrategy(BaseSearchStrategy):
# Extract engine name from class name
class_name = self.search.__class__.__name__
# Convert "ArXivSearchEngine" -> "arxiv"
- name = class_name.replace("SearchEngine", "").lower()
- return name
+ return class_name.replace("SearchEngine", "").lower()
except Exception:
logger.debug("best-effort class name extraction", exc_info=True)
return ""
diff --git a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
index d2032e9dc4..6ae460096e 100644
--- a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
@@ -221,7 +221,6 @@ class EarlyRejectionManager:
def should_reject_early(self, confidence_result):
"""Determine if candidate should be rejected early"""
- # positive = confidence_result.get("positive_confidence", 0.5) # Not currently used
negative = confidence_result.get("negative_confidence", 0.3)
# Only reject if we have strong negative evidence (not just lack of positive evidence)
@@ -345,19 +344,18 @@ class ModularStrategy(BaseSearchStrategy):
uncertainty_penalty=0.1,
negative_weight=1.5,
)
- elif checker_type == "strict":
+ if checker_type == "strict":
return StrictChecker(
model=self.model,
evidence_gatherer=self._gather_evidence_for_constraint,
)
- elif checker_type == "threshold":
+ if checker_type == "threshold":
return ThresholdChecker(
model=self.model,
evidence_gatherer=self._gather_evidence_for_constraint,
acceptance_threshold=0.7,
)
- else:
- raise ValueError(f"Unknown constraint checker type: {checker_type}")
+ raise ValueError(f"Unknown constraint checker type: {checker_type}")
def _create_candidate_explorer(self, strategy_type: str):
"""Create the appropriate candidate explorer."""
@@ -367,24 +365,23 @@ class ModularStrategy(BaseSearchStrategy):
model=self.model,
max_workers=4,
)
- elif strategy_type == "adaptive":
+ if strategy_type == "adaptive":
return AdaptiveExplorer(
search_engine=self.search_engine,
model=self.model,
learning_rate=0.1,
)
- elif strategy_type == "constraint_guided":
+ if strategy_type == "constraint_guided":
return ConstraintGuidedExplorer(
search_engine=self.search_engine, model=self.model
)
- elif strategy_type == "diversity":
+ if strategy_type == "diversity":
return DiversityExplorer(
search_engine=self.search_engine,
model=self.model,
diversity_factor=0.3,
)
- else:
- raise ValueError(f"Unknown exploration strategy: {strategy_type}")
+ raise ValueError(f"Unknown exploration strategy: {strategy_type}")
async def search(
self,
@@ -861,11 +858,9 @@ Provide a clear, factual answer that addresses the original question and explain
)
if years:
- for year in years:
- query_parts.append(year)
+ query_parts.extend(years)
elif decades:
- for decade in decades:
- query_parts.append(decade)
+ query_parts.extend(decades)
else:
query_parts.append(constraint_value)
diff --git a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py b/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
index 7fb3b1c7df..836df7fd21 100644
--- a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
@@ -89,9 +89,8 @@ class NewsAggregationStrategy(BaseSearchStrategy):
news_data["news_items"]
),
}
- else:
- # Fallback to simple extraction
- return self._fallback_news_extraction(snippets)
+ # Fallback to simple extraction
+ return self._fallback_news_extraction(snippets)
except Exception:
logger.exception("Error analyzing news findings")
diff --git a/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py b/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
index 91f2d7758e..61013adce5 100644
--- a/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
@@ -167,6 +167,7 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
self.stage_candidates = {
0: self.candidates, # Final results as last stage
}
+ return None
def _create_strict_combinations(self) -> List[SearchCombination]:
"""Create initial strict constraint combinations."""
diff --git a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
index 4a9810b25c..6462a49d42 100644
--- a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
@@ -60,7 +60,7 @@ class RapidSearchStrategy(BaseSearchStrategy):
findings = []
all_search_results = []
collected_snippets = []
- section_links = list()
+ section_links = []
self._update_progress(
"Initializing rapid research system",
diff --git a/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py b/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py
index be3a911cd5..af14bccd56 100644
--- a/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py
@@ -122,18 +122,17 @@ class RecursiveDecompositionStrategy(BaseSearchStrategy):
return self._handle_decomposition(
query, decomposition_decision, recursion_depth
)
- else:
- # Add search decision to findings
- self.findings.append(
- {
- "phase": f"Direct Search Decision (Depth {recursion_depth})",
- "content": f"Searching directly for: {query}",
- "reasoning": decomposition_decision["reasoning"],
- "timestamp": self._get_timestamp(),
- }
- )
+ # Add search decision to findings
+ self.findings.append(
+ {
+ "phase": f"Direct Search Decision (Depth {recursion_depth})",
+ "content": f"Searching directly for: {query}",
+ "reasoning": decomposition_decision["reasoning"],
+ "timestamp": self._get_timestamp(),
+ }
+ )
- return self._use_source_based_strategy(query)
+ return self._use_source_based_strategy(query)
def _decide_decomposition(self, query: str) -> Dict:
"""Decide whether to decompose the query or search directly.
@@ -274,12 +273,10 @@ When creating subtasks, ensure they maintain relevance to the original topic."""
)
# Aggregate results
- aggregated_result = self._aggregate_subtask_results(
+ return self._aggregate_subtask_results(
query, subtask_results, recursion_depth
)
- return aggregated_result
-
def _aggregate_subtask_results(
self,
original_query: str,
diff --git a/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py b/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
index 1312aee8dd..34f504764a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
@@ -93,17 +93,16 @@ class SmartDecompositionStrategy(BaseSearchStrategy):
# Check if it's specifically a BrowseComp-style puzzle
if self._is_browsecomp_style(query):
return self._use_browsecomp_strategy(query)
- else:
- return self._use_evidence_strategy(query)
- elif query_type == QueryType.CONSTRAINT_BASED:
return self._use_evidence_strategy(query)
- elif query_type == QueryType.HIERARCHICAL or query_type in [
+ if query_type == QueryType.CONSTRAINT_BASED:
+ return self._use_evidence_strategy(query)
+ if query_type == QueryType.HIERARCHICAL or query_type in [
QueryType.COMPARATIVE,
QueryType.EXPLORATORY,
]:
return self._use_recursive_strategy(query)
- else: # FACTUAL or unknown
- return self._use_adaptive_strategy(query)
+ # FACTUAL or unknown
+ return self._use_adaptive_strategy(query)
def _classify_query(self, query: str) -> QueryType:
"""Classify the query type to determine best strategy.
diff --git a/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py b/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
index 756068b626..59c75faba4 100644
--- a/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
@@ -46,9 +46,8 @@ class SmartQueryStrategy(EarlyStopConstrainedStrategy):
if self.use_llm_query_generation:
# Use LLM to generate smart queries
return self._generate_smart_query(constraints)
- else:
- # Fallback to improved standard approach
- return self._build_standard_query(constraints)
+ # Fallback to improved standard approach
+ return self._build_standard_query(constraints)
def _generate_smart_query(self, constraints: List[Constraint]) -> str:
"""Use LLM to generate optimal search queries."""
diff --git a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
index 5a7c287ef5..2ea17d91f3 100644
--- a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
@@ -80,7 +80,7 @@ class StandardSearchStrategy(BaseSearchStrategy):
current_knowledge = ""
iteration = 0
total_iterations = self.max_iterations
- section_links = list()
+ section_links = []
self._update_progress(
"Initializing research system",
diff --git a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
index 6902fe5737..98dff9afd7 100644
--- a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
@@ -288,7 +288,7 @@ Response:"""
f"Skipping source {i} '{source.get('title', '')}' - marked as irrelevant"
)
continue # Skip to next source
- elif response_text == "-":
+ if response_text == "-":
# Create new topic
topic_index = -1
else:
@@ -774,7 +774,7 @@ Consider similarity to lead sources when deciding.
if target == i:
# Keep in current topic
continue
- elif target == -2:
+ if target == -2:
# Remove from topic
logger.info(
f"Removing source '{source_data['source'].get('title')}' from topic '{topic.title}'"
@@ -1112,10 +1112,6 @@ Otherwise, respond with only the follow-up question, nothing else.
)
# Filter topics by relevance to the original query
- # DISABLED: Too aggressive filtering removing valid topics
- # relevant_topics = self._filter_topics_by_relevance(
- # validated_topics, query
- # )
relevant_topics = validated_topics # Skip relevance filtering
logger.info(
f"Filtered from {len(validated_topics)} to {len(relevant_topics)} relevant topics"
@@ -1268,10 +1264,6 @@ Otherwise, respond with only the follow-up question, nothing else.
):
validated_refined.append(topic)
- # DISABLED: Too aggressive filtering removing valid topics
- # relevant_topics = self._filter_topics_by_relevance(
- # validated_refined, query
- # )
relevant_topics = validated_refined # Skip relevance filtering
logger.info(
f"After refinement iteration {len(self.refinement_questions)}: {len(relevant_topics)} relevant topics"
diff --git a/src/local_deep_research/api/benchmark_functions.py b/src/local_deep_research/api/benchmark_functions.py
index ce4d47b55c..573a3f04fc 100644
--- a/src/local_deep_research/api/benchmark_functions.py
+++ b/src/local_deep_research/api/benchmark_functions.py
@@ -63,7 +63,7 @@ def evaluate_simpleqa(
evaluation_config["provider"] = evaluation_provider
# Run the benchmark
- results = run_simpleqa_benchmark(
+ return run_simpleqa_benchmark(
num_examples=num_examples,
output_dir=output_dir,
search_config=search_config,
@@ -71,8 +71,6 @@ def evaluate_simpleqa(
human_evaluation=human_evaluation,
)
- return results
-
def evaluate_browsecomp(
num_examples: int = 100,
@@ -119,7 +117,7 @@ def evaluate_browsecomp(
evaluation_config["provider"] = evaluation_provider
# Run the benchmark
- results = run_browsecomp_benchmark(
+ return run_browsecomp_benchmark(
num_examples=num_examples,
output_dir=output_dir,
search_config=search_config,
@@ -127,8 +125,6 @@ def evaluate_browsecomp(
human_evaluation=human_evaluation,
)
- return results
-
def evaluate_xbench_deepsearch(
num_examples: int = 100,
@@ -177,7 +173,7 @@ def evaluate_xbench_deepsearch(
evaluation_config["provider"] = evaluation_provider
# Run the benchmark
- results = run_xbench_deepsearch_benchmark(
+ return run_xbench_deepsearch_benchmark(
num_examples=num_examples,
output_dir=output_dir,
search_config=search_config,
@@ -185,8 +181,6 @@ def evaluate_xbench_deepsearch(
human_evaluation=human_evaluation,
)
- return results
-
def get_available_benchmarks() -> list[dict[str, str]]:
"""
@@ -277,8 +271,7 @@ def compare_configurations(
}
# Add any remaining config items
- for key, value in config.items():
- search_config[key] = value
+ search_config.update(config)
# Run benchmark with this configuration
benchmark_result = run_benchmark(
diff --git a/src/local_deep_research/api/client.py b/src/local_deep_research/api/client.py
index eedce2c334..4e66875007 100644
--- a/src/local_deep_research/api/client.py
+++ b/src/local_deep_research/api/client.py
@@ -152,12 +152,11 @@ class LDRClient:
self.username = username
logger.info(f"Successfully logged in as {username}")
return True
- else:
- logger.warning("Logged in but could not get API CSRF token")
- # Still logged in, just no CSRF for API calls
- self.logged_in = True
- self.username = username
- return True
+ logger.warning("Logged in but could not get API CSRF token")
+ # Still logged in, just no CSRF for API calls
+ self.logged_in = True
+ self.username = username
+ return True
except Exception:
logger.exception("Login error")
@@ -290,10 +289,9 @@ class LDRClient:
)
if results_response.status_code == 200:
return results_response.json()
- else:
- raise RuntimeError("Failed to get results")
+ raise RuntimeError("Failed to get results")
- elif status.get("status") == ResearchStatus.FAILED:
+ if status.get("status") == ResearchStatus.FAILED:
error_msg = status.get("error", "Unknown error")
raise RuntimeError(f"Research failed: {error_msg}")
@@ -309,10 +307,7 @@ class LDRClient:
response = self.session.get(f"{self.base_url}/settings/api")
if response.status_code == 200:
return response.json()
- else:
- raise RuntimeError(
- f"Failed to get settings: {response.status_code}"
- )
+ raise RuntimeError(f"Failed to get settings: {response.status_code}")
def update_setting(self, key: str, value: Any) -> bool:
"""
@@ -361,11 +356,10 @@ class LDRClient:
# Handle different response formats
if isinstance(data, dict):
return data.get("history", data.get("items", []))
- elif isinstance(data, list):
+ if isinstance(data, list):
return data
return []
- else:
- raise RuntimeError(f"Failed to get history: {response.status_code}")
+ raise RuntimeError(f"Failed to get history: {response.status_code}")
def logout(self):
"""Logout and clear session."""
diff --git a/src/local_deep_research/benchmarks/benchmark_functions.py b/src/local_deep_research/benchmarks/benchmark_functions.py
index a0f365fbea..316c498ac8 100644
--- a/src/local_deep_research/benchmarks/benchmark_functions.py
+++ b/src/local_deep_research/benchmarks/benchmark_functions.py
@@ -98,7 +98,7 @@ def evaluate_simpleqa(
evaluation_config["openai_endpoint_url"] = env_url
# Run the benchmark
- results = run_simpleqa_benchmark(
+ return run_simpleqa_benchmark(
num_examples=num_examples,
output_dir=output_dir,
search_config=search_config,
@@ -106,8 +106,6 @@ def evaluate_simpleqa(
human_evaluation=human_evaluation,
)
- return results
-
def evaluate_browsecomp(
num_examples: int = 100,
@@ -186,7 +184,7 @@ def evaluate_browsecomp(
evaluation_config["openai_endpoint_url"] = env_url
# Run the benchmark
- results = run_browsecomp_benchmark(
+ return run_browsecomp_benchmark(
num_examples=num_examples,
output_dir=output_dir,
search_config=search_config,
@@ -194,8 +192,6 @@ def evaluate_browsecomp(
human_evaluation=human_evaluation,
)
- return results
-
def evaluate_xbench_deepsearch(
num_examples: int = 100,
@@ -276,7 +272,7 @@ def evaluate_xbench_deepsearch(
evaluation_config["openai_endpoint_url"] = env_url
# Run the benchmark
- results = run_xbench_deepsearch_benchmark(
+ return run_xbench_deepsearch_benchmark(
num_examples=num_examples,
output_dir=output_dir,
search_config=search_config,
@@ -284,8 +280,6 @@ def evaluate_xbench_deepsearch(
human_evaluation=human_evaluation,
)
- return results
-
def get_available_benchmarks() -> List[Dict[str, str]]:
"""
@@ -375,8 +369,7 @@ def compare_configurations(
}
# Add any remaining config items
- for key, value in config.items():
- search_config[key] = value
+ search_config.update(config)
# Run benchmark with this configuration
benchmark_result = run_benchmark(
diff --git a/src/local_deep_research/benchmarks/cli.py b/src/local_deep_research/benchmarks/cli.py
index ff61a9df56..91d7f3ca71 100644
--- a/src/local_deep_research/benchmarks/cli.py
+++ b/src/local_deep_research/benchmarks/cli.py
@@ -368,13 +368,12 @@ def main():
if args.command == "optimize":
return run_optimization(args)
- elif args.command == "compare":
+ if args.command == "compare":
return run_comparison(args)
- elif args.command == "profile":
+ if args.command == "profile":
return run_profiling(args)
- else:
- print("Please specify a command. Use --help for more information.")
- return 1
+ print("Please specify a command. Use --help for more information.")
+ return 1
if __name__ == "__main__":
diff --git a/src/local_deep_research/benchmarks/comparison/evaluator.py b/src/local_deep_research/benchmarks/comparison/evaluator.py
index 2317541f56..63ccb0193c 100644
--- a/src/local_deep_research/benchmarks/comparison/evaluator.py
+++ b/src/local_deep_research/benchmarks/comparison/evaluator.py
@@ -611,19 +611,16 @@ def _create_spider_chart(
def _gen_axes_patch(self):
if frame == "circle":
return Circle((0.5, 0.5), 0.5)
- elif frame == "polygon":
+ if frame == "polygon":
return RegularPolygon(
(0.5, 0.5), num_vars, radius=0.5, edgecolor="k"
)
- else:
- raise ValueError(
- "Unknown value for 'frame': %s" % frame
- )
+ raise ValueError("Unknown value for 'frame': %s" % frame) # noqa: TRY301 — inside nested method definition, not caught by enclosing try
def _gen_axes_spines(self): # type: ignore[misc]
if frame == "circle":
return super()._gen_axes_spines()
- elif frame == "polygon":
+ if frame == "polygon":
spine_type = Spine.circular_spine
verts = unit_poly_verts(num_vars)
vertices = [(0.5, 0.5)] + verts
@@ -636,10 +633,7 @@ def _create_spider_chart(
spine = Spine(self, spine_type, path) # type: ignore[arg-type]
spine.set_transform(self.transAxes)
return {"polar": spine}
- else:
- raise ValueError(
- "Unknown value for 'frame': %s" % frame
- )
+ raise ValueError("Unknown value for 'frame': %s" % frame) # noqa: TRY301 — inside nested method definition, not caught by enclosing try
def unit_poly_verts(num_vars):
"""Return vertices of polygon for radar chart."""
@@ -679,7 +673,7 @@ def _create_spider_chart(
theta = radar_factory(num_vars)
fig, ax = plt.subplots(
- figsize=(10, 10), subplot_kw=dict(projection="radar")
+ figsize=(10, 10), subplot_kw={"projection": "radar"}
)
# Color map for different configurations
@@ -817,7 +811,7 @@ def _create_pareto_chart(results: List[Dict[str, Any]], output_path: str):
(quality_scores[i], speed_scores[i]),
xytext=(8, 8),
textcoords="offset points",
- bbox=dict(boxstyle="round,pad=0.5", fc="yellow", alpha=0.7),
+ bbox={"boxstyle": "round,pad=0.5", "fc": "yellow", "alpha": 0.7},
)
# Set chart properties
@@ -834,7 +828,7 @@ def _create_pareto_chart(results: List[Dict[str, Any]], output_path: str):
"(no other configuration is better in both quality and speed)",
ha="center",
fontsize=10,
- bbox=dict(boxstyle="round", fc="white", alpha=0.7),
+ bbox={"boxstyle": "round", "fc": "white", "alpha": 0.7},
)
plt.tight_layout()
diff --git a/src/local_deep_research/benchmarks/comparison/results.py b/src/local_deep_research/benchmarks/comparison/results.py
index 7c8b93cb1c..f3f55e5e19 100644
--- a/src/local_deep_research/benchmarks/comparison/results.py
+++ b/src/local_deep_research/benchmarks/comparison/results.py
@@ -54,8 +54,7 @@ class Benchmark_results:
return sorted(
self.results, key=lambda x: x["avg_time_per_question"]
)
- else:
- return sorted(self.results, key=lambda x: x[sort_by], reverse=True)
+ return sorted(self.results, key=lambda x: x[sort_by], reverse=True)
def _load_results(self):
# Load results from file
diff --git a/src/local_deep_research/benchmarks/datasets/base.py b/src/local_deep_research/benchmarks/datasets/base.py
index d83bf8d733..74176c6f20 100644
--- a/src/local_deep_research/benchmarks/datasets/base.py
+++ b/src/local_deep_research/benchmarks/datasets/base.py
@@ -89,14 +89,20 @@ class BenchmarkDataset(ABC):
logger.info(f"Loading dataset from {self.dataset_path}")
+ # Validate file format before attempting to load
+ if not (
+ self.dataset_path.endswith(".csv")
+ or self.dataset_path.endswith(".json")
+ or self.dataset_path.endswith(".jsonl")
+ ):
+ raise ValueError(f"Unsupported file format: {self.dataset_path}")
+
try:
# Load raw data
if self.dataset_path.endswith(".csv"):
df = pd.read_csv(self.dataset_path)
raw_examples = [row.to_dict() for _, row in df.iterrows()]
- elif self.dataset_path.endswith(
- ".json"
- ) or self.dataset_path.endswith(".jsonl"):
+ else:
import json
with open(self.dataset_path, "r") as f:
@@ -106,10 +112,6 @@ class BenchmarkDataset(ABC):
]
else:
raw_examples = json.load(f)
- else:
- raise ValueError(
- f"Unsupported file format: {self.dataset_path}"
- )
# Process each example
processed_examples = []
diff --git a/src/local_deep_research/benchmarks/efficiency/resource_monitor.py b/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
index 093a0b9cec..7690593aa9 100644
--- a/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
+++ b/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
@@ -198,7 +198,7 @@ class ResourceMonitor:
] # Convert to MB
# Calculate statistics
- stats = {
+ return {
"start_time": self.start_time,
"end_time": self.end_time,
"duration": self.end_time - self.start_time
@@ -224,8 +224,6 @@ class ResourceMonitor:
),
}
- return stats
-
def get_system_stats(self) -> Dict[str, Any]:
"""
Get statistics about overall system resource usage.
@@ -242,7 +240,7 @@ class ResourceMonitor:
disk_values = [d["disk_percent"] for d in self.system_data]
# Calculate statistics
- stats = {
+ return {
"start_time": self.start_time,
"end_time": self.end_time,
"duration": self.end_time - self.start_time
@@ -278,8 +276,6 @@ class ResourceMonitor:
),
}
- return stats
-
def get_combined_stats(self) -> Dict[str, Any]:
"""
Get combined resource usage statistics.
@@ -397,7 +393,7 @@ def check_system_resources() -> Dict[str, Any]:
disk = psutil.disk_usage("/")
# Format results
- result = {
+ return {
"available": True,
"cpu_count": cpu_count,
"cpu_physical": cpu_physical,
@@ -411,8 +407,6 @@ def check_system_resources() -> Dict[str, Any]:
"disk_percent": disk.percent,
}
- return result
-
except Exception as e:
logger.exception("Error checking system resources")
return {"error": str(e), "available": False}
diff --git a/src/local_deep_research/benchmarks/efficiency/speed_profiler.py b/src/local_deep_research/benchmarks/efficiency/speed_profiler.py
index 597facd214..2aaa6f5941 100644
--- a/src/local_deep_research/benchmarks/efficiency/speed_profiler.py
+++ b/src/local_deep_research/benchmarks/efficiency/speed_profiler.py
@@ -113,7 +113,7 @@ class SpeedProfiler:
result = self.timings.copy()
# Add averages
- for name, data in result.items():
+ for data in result.values():
if data["count"] > 0:
data["avg"] = data["total"] / data["count"]
diff --git a/src/local_deep_research/benchmarks/runners.py b/src/local_deep_research/benchmarks/runners.py
index 428e35ce86..1d2ca76093 100644
--- a/src/local_deep_research/benchmarks/runners.py
+++ b/src/local_deep_research/benchmarks/runners.py
@@ -424,21 +424,20 @@ def run_benchmark(
"accuracy": metrics.get("accuracy", 0),
}
- else:
- # No evaluation, just return results
- if progress_callback:
- progress_callback(
- "Benchmark complete (no evaluation)",
- 100,
- {"status": "complete_no_eval", "results_path": results_file},
- )
+ # No evaluation, just return results
+ if progress_callback:
+ progress_callback(
+ "Benchmark complete (no evaluation)",
+ 100,
+ {"status": "complete_no_eval", "results_path": results_file},
+ )
- return {
- "status": "complete_no_eval",
- "dataset_type": dataset_type,
- "results_path": results_file,
- "total_examples": total_examples,
- }
+ return {
+ "status": "complete_no_eval",
+ "dataset_type": dataset_type,
+ "results_path": results_file,
+ "total_examples": total_examples,
+ }
def run_simpleqa_benchmark(num_examples: int = 100, **kwargs) -> Dict[str, Any]:
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
index 2c059cbffa..5812848531 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
@@ -226,10 +226,9 @@ def start_benchmark():
"message": "Benchmark started successfully",
}
)
- else:
- return jsonify(
- {"success": False, "error": "Failed to start benchmark"}
- ), 500
+ return jsonify(
+ {"success": False, "error": "Failed to start benchmark"}
+ ), 500
except Exception:
logger.exception("Error starting benchmark")
@@ -267,10 +266,9 @@ def get_running_benchmark():
"completed_examples": running_benchmark.completed_examples,
}
)
- else:
- return jsonify(
- {"success": False, "message": "No running benchmark found"}
- )
+ return jsonify(
+ {"success": False, "message": "No running benchmark found"}
+ )
except Exception:
logger.exception("Error checking for running benchmark")
@@ -301,10 +299,9 @@ def get_benchmark_status(benchmark_run_id: int):
f"estimated_remaining={status.get('estimated_time_remaining')}"
)
return jsonify({"success": True, "status": status})
- else:
- return jsonify(
- {"success": False, "error": "Benchmark run not found"}
- ), 404
+ return jsonify(
+ {"success": False, "error": "Benchmark run not found"}
+ ), 404
except Exception:
logger.exception("Error getting benchmark status")
@@ -327,10 +324,9 @@ def cancel_benchmark(benchmark_run_id: int):
return jsonify(
{"success": True, "message": "Benchmark cancelled successfully"}
)
- else:
- return jsonify(
- {"success": False, "error": "Failed to cancel benchmark"}
- ), 500
+ return jsonify(
+ {"success": False, "error": "Failed to cancel benchmark"}
+ ), 500
except Exception:
logger.exception("Error cancelling benchmark")
@@ -490,10 +486,6 @@ def get_benchmark_results(benchmark_run_id: int):
results = (
session.query(BenchmarkResult)
.filter(BenchmarkResult.benchmark_run_id == benchmark_run_id)
- # Temporarily show all results including pending evaluations
- # .filter(
- # BenchmarkResult.is_correct.isnot(None)
- # ) # Only completed evaluations
.order_by(BenchmarkResult.id.desc()) # Most recent first
.limit(limit)
.all()
@@ -870,10 +862,9 @@ def start_benchmark_simple():
"message": "Benchmark started with current settings",
}
)
- else:
- return jsonify(
- {"success": False, "error": "Failed to start benchmark"}
- ), 500
+ return jsonify(
+ {"success": False, "error": "Failed to start benchmark"}
+ ), 500
except Exception:
logger.exception("Error starting simple benchmark")
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index 902976920a..1348bd139a 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -295,7 +295,7 @@ class BenchmarkService:
.first()
)
if not benchmark_run:
- raise ValueError(
+ raise ValueError( # noqa: TRY301 — caught by except, sets FAILED status in DB
f"Benchmark run {benchmark_run_id} not found"
)
@@ -385,18 +385,16 @@ class BenchmarkService:
# Using in-memory queue tracker for benchmark status tracking
task_id = None
- try:
- # Get the benchmark data that was passed to us
- # We need to retrieve this from the service database or from memory
- benchmark_data = self.active_runs.get(benchmark_run_id, {}).get(
- "data"
- )
+ # Get the benchmark data that was passed to us
+ # We need to retrieve this from the service database or from memory
+ benchmark_data = self.active_runs.get(benchmark_run_id, {}).get("data")
+
+ try:
if not benchmark_data:
- raise ValueError(
+ raise ValueError( # noqa: TRY301
f"Benchmark data for run {benchmark_run_id} not found"
)
-
# Set up settings context for thread-local access
settings_snapshot = benchmark_data.get("settings_snapshot", {})
username = benchmark_data.get("username", "benchmark_user")
diff --git a/src/local_deep_research/citation_handler.py b/src/local_deep_research/citation_handler.py
index 9d7979fc5d..a4d3d6aefb 100644
--- a/src/local_deep_research/citation_handler.py
+++ b/src/local_deep_research/citation_handler.py
@@ -51,7 +51,7 @@ class CitationHandler:
self.llm, settings_snapshot=self.settings_snapshot
)
- elif handler_type in ["forced", "forced_answer", "browsecomp"]:
+ if handler_type in ["forced", "forced_answer", "browsecomp"]:
from .citation_handlers.forced_answer_citation_handler import (
ForcedAnswerCitationHandler,
)
@@ -63,7 +63,7 @@ class CitationHandler:
self.llm, settings_snapshot=self.settings_snapshot
)
- elif handler_type in ["precision", "precision_extraction", "simpleqa"]:
+ if handler_type in ["precision", "precision_extraction", "simpleqa"]:
from .citation_handlers.precision_extraction_handler import (
PrecisionExtractionHandler,
)
@@ -75,17 +75,16 @@ class CitationHandler:
self.llm, settings_snapshot=self.settings_snapshot
)
- else:
- logger.warning(
- f"Unknown citation handler type: {handler_type}, falling back to standard"
- )
- from .citation_handlers.standard_citation_handler import (
- StandardCitationHandler,
- )
+ logger.warning(
+ f"Unknown citation handler type: {handler_type}, falling back to standard"
+ )
+ from .citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
- return StandardCitationHandler(
- self.llm, settings_snapshot=self.settings_snapshot
- )
+ return StandardCitationHandler(
+ self.llm, settings_snapshot=self.settings_snapshot
+ )
def analyze_initial(
self, query: str, search_results: Union[str, List[Dict]]
diff --git a/src/local_deep_research/citation_handlers/precision_extraction_handler.py b/src/local_deep_research/citation_handlers/precision_extraction_handler.py
index b62e3d6be0..6d5253ac68 100644
--- a/src/local_deep_research/citation_handlers/precision_extraction_handler.py
+++ b/src/local_deep_research/citation_handlers/precision_extraction_handler.py
@@ -207,22 +207,19 @@ Provide the precise answer with citations."""
) -> str:
"""Apply precision extraction based on question type."""
- # Check if content already has a good answer in the first line
- # first_line = content.split(".")[0].strip() # Not currently used
-
if question_type == "full_name":
return self._extract_full_name(content, query, sources)
- elif question_type == "name":
+ if question_type == "name":
return self._extract_best_name(content, query, sources)
- elif question_type == "single_choice":
+ if question_type == "single_choice":
return self._extract_single_answer(content, query, sources)
- elif question_type == "dimension":
+ if question_type == "dimension":
return self._extract_dimension(content, query, sources)
- elif question_type == "score":
+ if question_type == "score":
return self._extract_score(content, query, sources)
- elif question_type == "temporal":
+ if question_type == "temporal":
return self._extract_temporal(content, query, sources)
- elif question_type == "number":
+ if question_type == "number":
return self._extract_number(content, query, sources)
return content
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 3df9f7be56..0ed93b91c7 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -228,24 +228,22 @@ def _get_context_window_for_provider(provider_type, settings_snapshot=None):
)
# Ensure it's an integer
return int(window_size) if window_size is not None else 4096
- else:
- # Cloud providers: check if unrestricted mode is enabled
- use_unrestricted = get_setting_from_snapshot(
- "llm.context_window_unrestricted",
- True,
- settings_snapshot=settings_snapshot,
- )
- if use_unrestricted:
- # Let cloud providers auto-handle context (return None or very large value)
- return None # Will be handled per provider
- else:
- # Use user-specified limit
- window_size = get_setting_from_snapshot(
- "llm.context_window_size",
- 128000,
- settings_snapshot=settings_snapshot,
- )
- return int(window_size) if window_size is not None else 128000
+ # Cloud providers: check if unrestricted mode is enabled
+ use_unrestricted = get_setting_from_snapshot(
+ "llm.context_window_unrestricted",
+ True,
+ settings_snapshot=settings_snapshot,
+ )
+ if use_unrestricted:
+ # Let cloud providers auto-handle context (return None or very large value)
+ return None # Will be handled per provider
+ # Use user-specified limit
+ window_size = get_setting_from_snapshot(
+ "llm.context_window_size",
+ 128000,
+ settings_snapshot=settings_snapshot,
+ )
+ return int(window_size) if window_size is not None else 128000
def get_llm(
@@ -322,7 +320,7 @@ def get_llm(
# Validate the result is a BaseChatModel
if not isinstance(llm_instance, BaseChatModel):
- raise ValueError(
+ raise TypeError(
f"Factory function for {provider} must return a BaseChatModel instance, "
f"got {type(llm_instance).__name__}"
)
@@ -330,7 +328,7 @@ def get_llm(
# It's already a proper LLM instance, use it directly
llm_instance = custom_llm
else:
- raise ValueError(
+ raise TypeError(
f"Registered LLM {provider} must be either a BaseChatModel instance "
f"or a callable factory function. Got: {type(custom_llm).__name__}"
)
@@ -425,7 +423,7 @@ def get_llm(
settings_snapshot=settings_snapshot,
)
- elif provider == "openai":
+ if provider == "openai":
api_key = get_setting_from_snapshot(
"llm.openai.api_key", settings_snapshot=settings_snapshot
)
@@ -507,7 +505,7 @@ def get_llm(
settings_snapshot=settings_snapshot,
)
- elif provider == "openai_endpoint":
+ if provider == "openai_endpoint":
api_key = get_setting_from_snapshot(
"llm.openai_endpoint.api_key", settings_snapshot=settings_snapshot
)
@@ -540,7 +538,7 @@ def get_llm(
settings_snapshot=settings_snapshot,
)
- elif provider == "ollama":
+ if provider == "ollama":
try:
# Use the configurable Ollama base URL
raw_base_url = get_setting_from_snapshot(
@@ -556,7 +554,7 @@ def get_llm(
# Check if Ollama is available before trying to use it
if not is_ollama_available(settings_snapshot=settings_snapshot):
- raise ValueError(
+ raise ValueError( # noqa: TRY301 — propagates through except that logs and re-raises
f"Ollama is not available at {base_url}. Please ensure Ollama is running."
)
@@ -589,7 +587,7 @@ def get_llm(
)
if model_name.lower() not in model_names:
- raise ValueError(
+ raise ValueError( # noqa: TRY301 — re-raised by except ValueError below
f"Model '{model_name}' not found in Ollama. Available models: {', '.join(model_names[:5])}"
)
except ValueError:
@@ -891,13 +889,8 @@ def wrap_llm_without_think_tags(
def invoke(self, *args, **kwargs):
# Removed verbose debug logging to reduce log clutter
# Uncomment the lines below if you need to debug LLM requests
- # if hasattr(self.base_llm, "base_url"):
- # logger.debug(f"LLM Request - Base URL: {self.base_llm.base_url}")
- # logger.debug(f"LLM Request - Model: {getattr(self.base_llm, 'model', 'unknown')}")
-
try:
response = self.base_llm.invoke(*args, **kwargs)
- # logger.debug(f"LLM Response - Success, type: {type(response)}")
except Exception as e:
logger.exception("LLM Request - Failed with error")
# Log any URL information from the error
diff --git a/src/local_deep_research/content_fetcher/fetcher.py b/src/local_deep_research/content_fetcher/fetcher.py
index eac24f1f7a..73a6caf8a0 100644
--- a/src/local_deep_research/content_fetcher/fetcher.py
+++ b/src/local_deep_research/content_fetcher/fetcher.py
@@ -250,13 +250,12 @@ class ContentFetcher:
"published_date": metadata.get("published_date"),
}
- else:
- return {
- "status": "error",
- "url": url,
- "source_type": source_name,
- "error": result.skip_reason or "Download failed",
- }
+ return {
+ "status": "error",
+ "url": url,
+ "source_type": source_name,
+ "error": result.skip_reason or "Download failed",
+ }
except Exception as e:
logger.exception(f"Error fetching content from {url}")
diff --git a/src/local_deep_research/database/alembic_runner.py b/src/local_deep_research/database/alembic_runner.py
index f4bd29f403..9b1c243882 100644
--- a/src/local_deep_research/database/alembic_runner.py
+++ b/src/local_deep_research/database/alembic_runner.py
@@ -170,7 +170,7 @@ def needs_migration(engine: Engine) -> bool:
if not tables:
# Fresh database, needs initial migration
return True
- elif "alembic_version" not in tables:
+ if "alembic_version" not in tables:
# Existing database without Alembic - needs stamping then check
return True
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index da775d8d88..6e98a56740 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -144,7 +144,7 @@ class DatabaseManager:
result = conn.execute("SELECT * FROM test").fetchone()
if result != (1,):
- raise Exception("SQLCipher encryption test failed")
+ raise RuntimeError("SQLCipher encryption test failed")
logger.info(
"SQLCipher available and working - databases will be encrypted"
)
@@ -186,16 +186,15 @@ class DatabaseManager:
raise RuntimeError(
"SQLCipher not available. Set LDR_BOOTSTRAP_ALLOW_UNENCRYPTED=true to proceed without encryption (NOT RECOMMENDED)"
)
- else:
- logger.warning(
- "WARNING: Running with UNENCRYPTED databases!\n"
- "This means:\n"
- "- Passwords don't protect data access\n"
- "- API keys are stored in plain text\n"
- "- Anyone with file access can read all data\n"
- "Install SQLCipher for secure operation!"
- )
- return False
+ logger.warning(
+ "WARNING: Running with UNENCRYPTED databases!\n"
+ "This means:\n"
+ "- Passwords don't protect data access\n"
+ "- API keys are stored in plain text\n"
+ "- Anyone with file access can read all data\n"
+ "Install SQLCipher for secure operation!"
+ )
+ return False
def _get_user_db_path(self, username: str) -> Path:
"""Get the path for a user's encrypted database."""
@@ -274,7 +273,7 @@ class DatabaseManager:
apply_sqlcipher_pragmas(cursor, creation_mode=False)
if not verify_sqlcipher_connection(cursor):
- raise ValueError("Failed to verify database key")
+ raise ValueError("Failed to verify database key") # noqa: TRY301 — cleanup in except before re-raise
apply_performance_pragmas(cursor)
except Exception:
diff --git a/src/local_deep_research/database/library_init.py b/src/local_deep_research/database/library_init.py
index fe5e33a3ea..82e36f0621 100644
--- a/src/local_deep_research/database/library_init.py
+++ b/src/local_deep_research/database/library_init.py
@@ -263,7 +263,7 @@ def get_source_type_id(
)
if not source_type:
- raise ValueError(f"Source type not found: {type_name}")
+ raise ValueError(f"Source type not found: {type_name}") # noqa: TRY301 — inside db session context, except logs and re-raises
return source_type.id
diff --git a/src/local_deep_research/database/session_context.py b/src/local_deep_research/database/session_context.py
index dcebb5253f..775f0a4c8e 100644
--- a/src/local_deep_research/database/session_context.py
+++ b/src/local_deep_research/database/session_context.py
@@ -198,17 +198,16 @@ def ensure_db_session(view_func: Callable) -> Callable:
from flask import redirect, url_for
return redirect(url_for("auth.login"))
- else:
- # Try to reopen unencrypted database
- logger.warning(
- f"Reopening unencrypted database for {username} - "
- "ensure this is intentional"
- )
- engine = db_manager.open_user_database(
- username, UNENCRYPTED_DB_PLACEHOLDER
- )
- if engine:
- g.db_session = db_manager.get_session(username)
+ # Try to reopen unencrypted database
+ logger.warning(
+ f"Reopening unencrypted database for {username} - "
+ "ensure this is intentional"
+ )
+ engine = db_manager.open_user_database(
+ username, UNENCRYPTED_DB_PLACEHOLDER
+ )
+ if engine:
+ g.db_session = db_manager.get_session(username)
except Exception:
logger.exception(
diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.py
index aabfaa5268..cd11bcd46a 100644
--- a/src/local_deep_research/database/sqlcipher_utils.py
+++ b/src/local_deep_research/database/sqlcipher_utils.py
@@ -336,15 +336,13 @@ def get_sqlcipher_settings() -> dict:
)
kdf_iterations = DEFAULT_KDF_ITERATIONS
- settings = {
+ return {
"kdf_iterations": kdf_iterations,
"page_size": page_size,
"hmac_algorithm": hmac_algorithm,
"kdf_algorithm": kdf_algorithm,
}
- return settings
-
def apply_cipher_defaults_before_key(
cursor_or_conn: Any,
@@ -556,7 +554,7 @@ def create_sqlcipher_connection(
elif password:
set_sqlcipher_key(cursor, password, db_path=db_path)
else:
- raise ValueError("Either password or hex_key must be provided")
+ raise ValueError("Either password or hex_key must be provided") # noqa: TRY301 — except does connection cleanup before re-raise
# Apply post-key pragmas (cipher_* for existing, kdf_iter for both)
apply_sqlcipher_pragmas(cursor, creation_mode=creation_mode)
@@ -566,7 +564,7 @@ def create_sqlcipher_connection(
# Verify connection works
if not verify_sqlcipher_connection(cursor):
- raise ValueError(
+ raise ValueError( # noqa: TRY301 — except does connection cleanup before re-raise
"Failed to establish encrypted database connection"
)
diff --git a/src/local_deep_research/database/thread_metrics.py b/src/local_deep_research/database/thread_metrics.py
index 3d228e73f7..1bcc2d8c62 100644
--- a/src/local_deep_research/database/thread_metrics.py
+++ b/src/local_deep_research/database/thread_metrics.py
@@ -81,7 +81,7 @@ class ThreadSafeMetricsWriter:
username, password
)
if not session:
- raise ValueError(
+ raise ValueError( # noqa: TRY301 — except does session rollback before re-raise
f"Failed to create session for user {username}"
)
yield session
diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.py
index 6148a11476..1a3b931abc 100644
--- a/src/local_deep_research/domain_classifier/classifier.py
+++ b/src/local_deep_research/domain_classifier/classifier.py
@@ -170,7 +170,7 @@ class DomainClassifier:
if sample.get("preview"):
samples_text.append(f" Preview: {sample['preview'][:100]}...")
- prompt = f"""Classify the following domain into one of the predefined categories.
+ return f"""Classify the following domain into one of the predefined categories.
Domain: {domain}
@@ -190,8 +190,6 @@ Focus on accuracy. If uncertain, use "Other" category with "Unknown" subcategory
JSON Response:"""
- return prompt
-
def classify_domain(
self, domain: str, force_update: bool = False
) -> Optional[DomainClassification]:
@@ -231,7 +229,7 @@ JSON Response:"""
result = extract_json(response_text, expected_type=dict)
if result is None:
- raise ValueError("Could not parse JSON from LLM response")
+ raise ValueError("Could not parse JSON from LLM response") # noqa: TRY301 — inside db session; except logs and returns None
# Create or update classification
if existing:
diff --git a/src/local_deep_research/embeddings/splitters/text_splitter_registry.py b/src/local_deep_research/embeddings/splitters/text_splitter_registry.py
index 3965bd909c..b89dee0510 100644
--- a/src/local_deep_research/embeddings/splitters/text_splitter_registry.py
+++ b/src/local_deep_research/embeddings/splitters/text_splitter_registry.py
@@ -72,13 +72,13 @@ def get_text_splitter(
chunk_overlap=chunk_overlap,
)
- elif splitter_type == "sentence":
+ if splitter_type == "sentence":
return SentenceTransformersTokenTextSplitter(
chunk_overlap=chunk_overlap,
tokens_per_chunk=chunk_size,
)
- elif splitter_type == "semantic":
+ if splitter_type == "semantic":
# Semantic chunking requires embeddings
if embeddings is None:
raise ValueError(
diff --git a/src/local_deep_research/exporters/odt_exporter.py b/src/local_deep_research/exporters/odt_exporter.py
index d7225c090b..eca548929f 100644
--- a/src/local_deep_research/exporters/odt_exporter.py
+++ b/src/local_deep_research/exporters/odt_exporter.py
@@ -75,13 +75,13 @@ class ODTExporter(BaseExporter):
ValueError: If content exceeds maximum size limit
RuntimeError: If Pandoc conversion fails
"""
- try:
- # Check if pypandoc is available
- if not PYPANDOC_AVAILABLE:
- raise RuntimeError(
- "ODT export requires pypandoc. Install with: pip install pypandoc-binary"
- )
+ # Check if pypandoc is available
+ if not PYPANDOC_AVAILABLE:
+ raise RuntimeError(
+ "ODT export requires pypandoc. Install with: pip install pypandoc-binary"
+ )
+ try:
# Check content size limit to prevent OOM errors
self._validate_content_size(markdown_content)
@@ -127,7 +127,7 @@ class ODTExporter(BaseExporter):
odt_bytes = result.stdout
if not odt_bytes:
- raise RuntimeError(
+ raise RuntimeError( # noqa: TRY301 — except only adds logging before re-raise
"Pandoc conversion failed - no output produced"
)
@@ -185,5 +185,4 @@ class ODTExporter(BaseExporter):
Sanitized metadata value safe for pandoc arguments
"""
# Remove potential argument injection patterns
- safe_value = value.replace("--", "").replace("\n", " ")
- return safe_value
+ return value.replace("--", "").replace("\n", " ")
diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.py
index e816b01708..279e2f8f0f 100644
--- a/src/local_deep_research/followup_research/routes.py
+++ b/src/local_deep_research/followup_research/routes.py
@@ -221,10 +221,9 @@ def start_followup():
"error": "Your session has expired. Please log out and log back in to start research.",
}
), 401
- else:
- logger.warning(
- f"No password available for metrics access for user {username}"
- )
+ logger.warning(
+ f"No password available for metrics access for user {username}"
+ )
# Generate new research ID
research_id = str(uuid.uuid4())
diff --git a/src/local_deep_research/followup_research/service.py b/src/local_deep_research/followup_research/service.py
index eddbfcf4d2..e424fcc575 100644
--- a/src/local_deep_research/followup_research/service.py
+++ b/src/local_deep_research/followup_research/service.py
@@ -162,7 +162,7 @@ class FollowUpResearchService:
return {}
# Format context for the strategy
- research_context = {
+ return {
"parent_research_id": parent_research_id,
"past_links": parent_data.get("all_links_of_system", []),
"past_findings": parent_data.get("formatted_findings", ""),
@@ -172,8 +172,6 @@ class FollowUpResearchService:
"original_query": parent_data.get("query", ""),
}
- return research_context
-
def perform_followup(self, request: FollowUpRequest) -> Dict[str, Any]:
"""
Perform a follow-up research based on parent research.
diff --git a/src/local_deep_research/library/download_management/database_init.py b/src/local_deep_research/library/download_management/database_init.py
index efa096aca0..0d938fbf7f 100644
--- a/src/local_deep_research/library/download_management/database_init.py
+++ b/src/local_deep_research/library/download_management/database_init.py
@@ -28,7 +28,7 @@ def init_database():
# Return None since engine is disposed - callers should create their own
# engine/session if they need to interact with the database
- return None
+ return
def verify_table_exists():
@@ -44,9 +44,8 @@ def verify_table_exists():
if "resource_download_status" in table_names:
logger.info("✓ resource_download_status table exists")
return True
- else:
- logger.warning("✗ resource_download_status table missing")
- return False
+ logger.warning("✗ resource_download_status table missing")
+ return False
finally:
# Always dispose engine to prevent file descriptor leaks
engine.dispose()
diff --git a/src/local_deep_research/library/download_management/failure_classifier.py b/src/local_deep_research/library/download_management/failure_classifier.py
index 0407510259..2a5f372d12 100644
--- a/src/local_deep_research/library/download_management/failure_classifier.py
+++ b/src/local_deep_research/library/download_management/failure_classifier.py
@@ -141,16 +141,16 @@ class FailureClassifier:
if status_code:
if status_code == 404:
return PermanentFailure("not_found", "Resource not found (404)")
- elif status_code == 403:
+ if status_code == 403:
return PermanentFailure("forbidden", "Access forbidden (403)")
- elif status_code == 410:
+ if status_code == 410:
return PermanentFailure(
"gone", "Resource permanently removed (410)"
)
- elif status_code == 429:
+ if status_code == 429:
domain = urlparse(url).netloc if url else "unknown"
return RateLimitFailure(domain, details)
- elif status_code == 503:
+ if status_code == 503:
return TemporaryFailure(
"server_error",
"Service temporarily unavailable (503)",
diff --git a/src/local_deep_research/library/download_management/retry_manager.py b/src/local_deep_research/library/download_management/retry_manager.py
index 6a74194a12..da9ec8b72e 100644
--- a/src/local_deep_research/library/download_management/retry_manager.py
+++ b/src/local_deep_research/library/download_management/retry_manager.py
@@ -227,10 +227,9 @@ class RetryManager:
if not can_retry:
if reason and "permanently failed" in reason:
return "permanently_failed"
- elif reason and "cooldown" in reason:
+ if reason and "cooldown" in reason:
return "temporarily_failed"
- else:
- return "unavailable"
+ return "unavailable"
return "available"
def get_retry_statistics(self) -> dict:
diff --git a/src/local_deep_research/llm/providers/implementations/google.py b/src/local_deep_research/llm/providers/implementations/google.py
index 4f726508a8..99d335623b 100644
--- a/src/local_deep_research/llm/providers/implementations/google.py
+++ b/src/local_deep_research/llm/providers/implementations/google.py
@@ -85,11 +85,10 @@ class GoogleProvider(OpenAICompatibleProvider):
f"Found {len(models)} generative models from Google Gemini API"
)
return models
- else:
- logger.warning(
- f"Google Gemini API returned status {response.status_code}"
- )
- return []
+ logger.warning(
+ f"Google Gemini API returned status {response.status_code}"
+ )
+ return []
except Exception:
logger.exception("Error fetching Google Gemini models")
diff --git a/src/local_deep_research/llm/providers/implementations/ollama.py b/src/local_deep_research/llm/providers/implementations/ollama.py
index 0e3ecb5551..91e96ebfe1 100644
--- a/src/local_deep_research/llm/providers/implementations/ollama.py
+++ b/src/local_deep_research/llm/providers/implementations/ollama.py
@@ -164,7 +164,7 @@ class OllamaProvider(BaseLLMProvider):
logger.error(
f"Model '{model_name}' not found in Ollama. Available models: {', '.join(model_names[:5])}"
)
- raise ValueError(
+ raise ValueError( # noqa: TRY301 — re-raised by except ValueError below
f"Model '{model_name}' not found in Ollama"
)
except ValueError:
@@ -269,11 +269,10 @@ class OllamaProvider(BaseLLMProvider):
# Log first 100 chars of response to debug
logger.info(f"Response preview: {str(response.text)[:100]}")
return True
- else:
- logger.warning(
- f"Ollama API returned status code: {response.status_code}"
- )
- return False
+ logger.warning(
+ f"Ollama API returned status code: {response.status_code}"
+ )
+ return False
except requests.exceptions.RequestException:
logger.warning("Request error when checking Ollama")
return False
diff --git a/src/local_deep_research/mcp/client.py b/src/local_deep_research/mcp/client.py
index 494a8fa137..3c59b82093 100644
--- a/src/local_deep_research/mcp/client.py
+++ b/src/local_deep_research/mcp/client.py
@@ -216,7 +216,7 @@ class MCPClient:
):
with attempt:
if self._session is None:
- raise MCPClientError("Session not initialized")
+ raise MCPClientError("Session not initialized") # noqa: TRY301 — re-raised by except MCPClientError
await asyncio.wait_for(
self._session.initialize(),
timeout=min(5.0, self.timeout),
diff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.py
index 7cd6f23c19..0dd0b49fa6 100644
--- a/src/local_deep_research/mcp/server.py
+++ b/src/local_deep_research/mcp/server.py
@@ -162,7 +162,7 @@ def _validate_search_engine(engine: Optional[str]) -> Optional[str]:
available = search_config(settings_snapshot=settings)
if engine not in available:
available_names = sorted(available.keys())
- raise ValidationError(
+ raise ValidationError( # noqa: TRY301
f"Unknown search engine '{engine}'. Available: {', '.join(available_names)}"
)
except ValidationError:
@@ -437,11 +437,11 @@ def generate_report(
not isinstance(searches_per_section, int)
or searches_per_section < 1
):
- raise ValidationError(
+ raise ValidationError( # noqa: TRY301
"Searches per section must be a positive integer"
)
if searches_per_section > 10:
- raise ValidationError("Searches per section cannot exceed 10")
+ raise ValidationError("Searches per section cannot exceed 10") # noqa: TRY301
logger.info(f"Starting report generation for query: {query[:100]}...")
@@ -518,10 +518,10 @@ def analyze_documents(
# Validate parameters
query = _validate_query(query)
if not collection_name or not collection_name.strip():
- raise ValidationError("Collection name cannot be empty")
+ raise ValidationError("Collection name cannot be empty") # noqa: TRY301
collection_name = collection_name.strip()
if not _COLLECTION_NAME_RE.match(collection_name):
- raise ValidationError(
+ raise ValidationError( # noqa: TRY301
"Collection name may only contain letters, digits, spaces, hyphens, and underscores (max 100 chars)"
)
max_results = _validate_max_results(max_results)
@@ -600,7 +600,7 @@ def search(
# Validate engine is non-empty (required parameter)
if not engine or not engine.strip():
- raise ValidationError(
+ raise ValidationError( # noqa: TRY301
"Engine name cannot be empty. Use list_search_engines() to see available options."
)
engine = engine.strip()
@@ -616,7 +616,7 @@ def search(
engines_config = search_config(settings_snapshot=settings)
if engine not in engines_config:
available_names = sorted(engines_config.keys())
- raise ValidationError(
+ raise ValidationError( # noqa: TRY301
f"Unknown search engine '{engine}'. Available: {', '.join(available_names)}"
)
@@ -634,7 +634,7 @@ def search(
else api_key_setting
)
if not api_key:
- raise ValidationError(
+ raise ValidationError( # noqa: TRY301
f"Engine '{engine}' requires an API key. "
f"Set the LDR_SEARCH_ENGINE_WEB_{engine.upper()}_API_KEY environment variable "
f"or configure it in the UI at search.engine.web.{engine}.api_key"
diff --git a/src/local_deep_research/metrics/pricing/pricing_fetcher.py b/src/local_deep_research/metrics/pricing/pricing_fetcher.py
index 98002314c8..b314353c05 100644
--- a/src/local_deep_research/metrics/pricing/pricing_fetcher.py
+++ b/src/local_deep_research/metrics/pricing/pricing_fetcher.py
@@ -225,15 +225,14 @@ class PricingFetcher:
if "gpt" in model_name or "openai" in model_name:
return "openai"
- elif "claude" in model_name or "anthropic" in model_name:
+ if "claude" in model_name or "anthropic" in model_name:
return "anthropic"
- elif "gemini" in model_name or "google" in model_name:
+ if "gemini" in model_name or "google" in model_name:
return "google"
- elif "llama" in model_name or "meta" in model_name:
+ if "llama" in model_name or "meta" in model_name:
return "meta"
- elif "mistral" in model_name:
+ if "mistral" in model_name:
return "mistral"
- elif "ollama" in model_name:
+ if "ollama" in model_name:
return "ollama"
- else:
- return "unknown"
+ return "unknown"
diff --git a/src/local_deep_research/metrics/query_utils.py b/src/local_deep_research/metrics/query_utils.py
index 7ae9ec59a6..be7d231bd8 100644
--- a/src/local_deep_research/metrics/query_utils.py
+++ b/src/local_deep_research/metrics/query_utils.py
@@ -29,7 +29,7 @@ def get_time_filter_condition(period: str, timestamp_column: Column) -> Any:
"""
if period == "all":
return None
- elif period == "7d":
+ if period == "7d":
cutoff = datetime.now(UTC) - timedelta(days=7)
elif period == "30d":
cutoff = datetime.now(UTC) - timedelta(days=30)
@@ -56,7 +56,6 @@ def get_research_mode_condition(research_mode: str, mode_column: Column) -> Any:
"""
if research_mode == "all":
return None
- elif research_mode in ["quick", "detailed"]:
+ if research_mode in ["quick", "detailed"]:
return mode_column == research_mode
- else:
- return None
+ return None
diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.py
index 393923fae3..f4f5c31659 100644
--- a/src/local_deep_research/metrics/token_counter.py
+++ b/src/local_deep_research/metrics/token_counter.py
@@ -140,11 +140,6 @@ class TokenCountingCallback(BaseCallbackHandler):
logger.warning("Error capturing call stack")
# Continue without call stack info if there's an error
- # Debug logging removed to reduce log clutter
- # Uncomment below if you need to debug token counting
- # logger.debug(f"on_llm_start serialized: {serialized}")
- # logger.debug(f"on_llm_start kwargs keys: {list(kwargs.keys()) if kwargs else []}")
-
# First, use preset values if available
if self.preset_model:
self.current_model = self.preset_model
diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.py
index 4d8a36ede3..5f95b9e64b 100644
--- a/src/local_deep_research/news/api.py
+++ b/src/local_deep_research/news/api.py
@@ -106,11 +106,11 @@ def get_news_feed(
Returns:
Dictionary with news items and metadata
"""
- try:
- # Validate limit - allow any positive number
- if limit < 1:
- raise InvalidLimitException(limit)
+ # Validate limit - allow any positive number
+ if limit < 1:
+ raise InvalidLimitException(limit)
+ try:
logger.info(
f"get_news_feed called with user_id={user_id}, limit={limit}"
)
@@ -512,7 +512,7 @@ def get_subscription_history(
)
if not subscription:
- raise SubscriptionNotFoundException(subscription_id)
+ raise SubscriptionNotFoundException(subscription_id) # noqa: TRY301 — re-raised by except NewsAPIException
# Convert to dict for response
subscription_dict = {
@@ -635,14 +635,13 @@ def _format_time_ago(timestamp: str) -> str:
if diff.days > 0:
return f"{diff.days} day{'s' if diff.days > 1 else ''} ago"
- elif diff.seconds > 3600:
+ if diff.seconds > 3600:
hours = diff.seconds // 3600
return f"{hours} hour{'s' if hours > 1 else ''} ago"
- elif diff.seconds > 60:
+ if diff.seconds > 60:
minutes = diff.seconds // 60
return f"{minutes} minute{'s' if minutes > 1 else ''} ago"
- else:
- return "Just now"
+ return "Just now"
except Exception:
logger.exception(f"Error parsing timestamp '{timestamp}'")
return "Recently"
@@ -671,7 +670,7 @@ def get_subscription(subscription_id: str) -> Optional[Dict[str, Any]]:
)
if not subscription:
- raise SubscriptionNotFoundException(subscription_id)
+ raise SubscriptionNotFoundException(subscription_id) # noqa: TRY301 — re-raised by except NewsAPIException
# Convert to API format matching the template expectations
return {
@@ -795,7 +794,7 @@ def update_subscription(
.first()
)
if not subscription:
- raise SubscriptionNotFoundException(subscription_id)
+ raise SubscriptionNotFoundException(subscription_id) # noqa: TRY301 — re-raised by except NewsAPIException
# Update fields
if "name" in data:
@@ -1009,8 +1008,7 @@ def delete_subscription(subscription_id: str) -> Dict[str, Any]:
_notify_scheduler_about_subscription_change("deleted")
return {"status": "success", "deleted": subscription_id}
- else:
- raise SubscriptionNotFoundException(subscription_id)
+ raise SubscriptionNotFoundException(subscription_id) # noqa: TRY301 — re-raised by except NewsAPIException
except NewsAPIException:
# Re-raise our custom exceptions
raise
@@ -1034,19 +1032,19 @@ def get_votes_for_cards(card_ids: list, user_id: str) -> Dict[str, Any]:
from ..database.models.news import UserRating, RatingType
from ..database.session_context import get_user_db_session
- try:
- # Check if we're in a request context
- if not has_request_context():
- # If called outside of request context (e.g., in tests), use user_id directly
- username = user_id if user_id else None
- if not username:
- raise ValueError("No username provided and no request context")
- else:
- # Get username from session
- username = flask_session.get("username")
- if not username:
- raise ValueError("No username in session")
+ # Resolve username before try block
+ if not has_request_context():
+ # If called outside of request context (e.g., in tests), use user_id directly
+ username = user_id if user_id else None
+ if not username:
+ raise ValueError("No username provided and no request context")
+ else:
+ # Get username from session
+ username = flask_session.get("username")
+ if not username:
+ raise ValueError("No username in session")
+ try:
# Get database session
with get_user_db_session(username) as db:
results = {}
@@ -1112,23 +1110,23 @@ def submit_feedback(card_id: str, user_id: str, vote: str) -> Dict[str, Any]:
from ..database.models.news import UserRating, RatingType
from ..database.session_context import get_user_db_session
- try:
- # Validate vote value
- if vote not in ["up", "down"]:
- raise ValueError(f"Invalid vote type: {vote}")
-
- # Check if we're in a request context
- if not has_request_context():
- # If called outside of request context (e.g., in tests), use user_id directly
- username = user_id if user_id else None
- if not username:
- raise ValueError("No username provided and no request context")
- else:
- # Get username from session
- username = flask_session.get("username")
- if not username:
- raise ValueError("No username in session")
+ # Validate vote value
+ if vote not in ["up", "down"]:
+ raise ValueError(f"Invalid vote type: {vote}")
+
+ # Resolve username before try block
+ if not has_request_context():
+ # If called outside of request context (e.g., in tests), use user_id directly
+ username = user_id if user_id else None
+ if not username:
+ raise ValueError("No username provided and no request context")
+ else:
+ # Get username from session
+ username = flask_session.get("username")
+ if not username:
+ raise ValueError("No username in session")
+ try:
# Get database session
with get_user_db_session(username) as db:
# We don't check if the card exists in the database since news items
diff --git a/src/local_deep_research/news/core/storage_manager.py b/src/local_deep_research/news/core/storage_manager.py
index af9e907313..ef559f7c7e 100644
--- a/src/local_deep_research/news/core/storage_manager.py
+++ b/src/local_deep_research/news/core/storage_manager.py
@@ -54,10 +54,9 @@ class StorageManager:
"""Get the current database session from Flask context."""
if has_app_context() and hasattr(g, "db_session") and g.db_session:
return g.db_session
- else:
- # If no session in context, we need to create one
- # This will trigger register_activity
- return None
+ # If no session in context, we need to create one
+ # This will trigger register_activity
+ return None
@property
def cards(self):
@@ -65,14 +64,11 @@ class StorageManager:
session = self._get_current_session()
if session:
return SQLCardStorage(session)
- else:
- # For now, create storage without session
- # This will fail when trying to use it
- if self._cards is None:
- raise RuntimeError(
- "No database session available for news storage"
- )
- return self._cards
+ # For now, create storage without session
+ # This will fail when trying to use it
+ if self._cards is None:
+ raise RuntimeError("No database session available for news storage")
+ return self._cards
@property
def subscriptions(self):
@@ -80,12 +76,9 @@ class StorageManager:
session = self._get_current_session()
if session:
return SQLSubscriptionStorage(session)
- else:
- if self._subscriptions is None:
- raise RuntimeError(
- "No database session available for news storage"
- )
- return self._subscriptions
+ if self._subscriptions is None:
+ raise RuntimeError("No database session available for news storage")
+ return self._subscriptions
@property
def ratings(self):
@@ -93,12 +86,9 @@ class StorageManager:
session = self._get_current_session()
if session:
return SQLRatingStorage(session)
- else:
- if self._ratings is None:
- raise RuntimeError(
- "No database session available for news storage"
- )
- return self._ratings
+ if self._ratings is None:
+ raise RuntimeError("No database session available for news storage")
+ return self._ratings
@property
def preferences(self):
@@ -106,12 +96,9 @@ class StorageManager:
session = self._get_current_session()
if session:
return SQLPreferenceStorage(session)
- else:
- if self._preferences is None:
- raise RuntimeError(
- "No database session available for news storage"
- )
- return self._preferences
+ if self._preferences is None:
+ raise RuntimeError("No database session available for news storage")
+ return self._preferences
def get_user_feed(
self,
diff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.py
index bd461c8567..5f513ce491 100644
--- a/src/local_deep_research/news/flask_api.py
+++ b/src/local_deep_research/news/flask_api.py
@@ -76,13 +76,12 @@ def safe_error_message(e: Exception, context: str = "") -> str:
# Return generic messages based on exception type
if isinstance(e, ValueError):
return "Invalid input provided"
- elif isinstance(e, KeyError):
+ if isinstance(e, KeyError):
return "Required data missing"
- elif isinstance(e, TypeError):
+ if isinstance(e, TypeError):
return "Invalid data format"
- else:
- # Generic message for production
- return f"An error occurred{f' while {context}' if context else ''}"
+ # Generic message for production
+ return f"An error occurred{f' while {context}' if context else ''}"
def _is_job_owned_by_user(job, username, scheduler):
@@ -303,10 +302,7 @@ def vote_on_news() -> Any:
error_msg = str(e)
if "not found" in error_msg.lower():
return jsonify({"error": "Resource not found"}), 404
- else:
- return jsonify(
- {"error": safe_error_message(e, "submitting vote")}
- ), 400
+ return jsonify({"error": safe_error_message(e, "submitting vote")}), 400
except Exception as e:
return jsonify({"error": safe_error_message(e, "submitting vote")}), 500
@@ -376,12 +372,11 @@ def submit_feedback(card_id: str) -> Any:
error_msg = str(e)
if "not found" in error_msg.lower():
return jsonify({"error": "Resource not found"}), 404
- elif "must be" in error_msg.lower():
+ if "must be" in error_msg.lower():
return jsonify({"error": "Invalid input value"}), 400
- else:
- return jsonify(
- {"error": safe_error_message(e, "submitting feedback")}
- ), 400
+ return jsonify(
+ {"error": safe_error_message(e, "submitting feedback")}
+ ), 400
except Exception as e:
return jsonify(
{"error": safe_error_message(e, "submitting feedback")}
@@ -511,8 +506,7 @@ def update_subscription(subscription_id: str) -> Any:
)
if "not found" in original_error.lower():
return jsonify(result), 404
- else:
- return jsonify(result), 400
+ return jsonify(result), 400
return jsonify(result)
@@ -537,8 +531,7 @@ def delete_subscription(subscription_id: str) -> Any:
"message": f"Subscription {subscription_id} deleted",
}
)
- else:
- return jsonify({"error": "Subscription not found"}), 404
+ return jsonify({"error": "Subscription not found"}), 404
except Exception as e:
return jsonify(
@@ -635,14 +628,12 @@ def run_subscription_now(subscription_id: str) -> Any:
"url": f"/progress/{data.get('research_id')}",
}
)
- else:
- return jsonify(
- {"error": data.get("message", "Failed to start research")}
- ), 500
- else:
return jsonify(
- {"error": f"Failed to start research: {response.status_code}"}
- ), response.status_code
+ {"error": data.get("message", "Failed to start research")}
+ ), 500
+ return jsonify(
+ {"error": f"Failed to start research: {response.status_code}"}
+ ), response.status_code
except Exception as e:
return jsonify(
@@ -866,10 +857,8 @@ def stop_scheduler() -> Any:
return jsonify(
{"status": "success", "message": "Scheduler stopped"}
)
- else:
- return jsonify({"message": "Scheduler is not running"}), 200
- else:
- return jsonify({"message": "No scheduler instance found"}), 404
+ return jsonify({"message": "Scheduler is not running"}), 200
+ return jsonify({"message": "No scheduler instance found"}), 404
except Exception as e:
return jsonify(
diff --git a/src/local_deep_research/news/rating_system/storage.py b/src/local_deep_research/news/rating_system/storage.py
index 462e7390d7..e5e1b24992 100644
--- a/src/local_deep_research/news/rating_system/storage.py
+++ b/src/local_deep_research/news/rating_system/storage.py
@@ -160,16 +160,15 @@ class SQLRatingStorage(RatingStorage):
# Update existing rating
self.update(str(existing["id"]), {"rating_value": rating_value})
return str(existing["id"])
- else:
- # Create new rating
- data = {
- "user_id": user_id,
- "item_id": item_id,
- "item_type": item_type,
- "rating_type": rating_type,
- "rating_value": rating_value,
- }
- return self.create(data)
+ # Create new rating
+ data = {
+ "user_id": user_id,
+ "item_id": item_id,
+ "item_type": item_type,
+ "rating_type": rating_type,
+ "rating_value": rating_value,
+ }
+ return self.create(data)
def get_ratings_summary(
self, item_id: str, item_type: str = "card"
diff --git a/src/local_deep_research/news/subscription_manager/scheduler.py b/src/local_deep_research/news/subscription_manager/scheduler.py
index 0a677f81d0..c67a13f94f 100644
--- a/src/local_deep_research/news/subscription_manager/scheduler.py
+++ b/src/local_deep_research/news/subscription_manager/scheduler.py
@@ -1427,18 +1427,17 @@ class NewsScheduler:
"""Convert non-serializable objects to dictionaries."""
if hasattr(obj, "dict"):
return obj.dict()
- elif hasattr(obj, "__dict__"):
+ if hasattr(obj, "__dict__"):
return {
k: make_serializable(v)
for k, v in obj.__dict__.items()
if not k.startswith("_")
}
- elif isinstance(obj, (list, tuple)):
+ if isinstance(obj, (list, tuple)):
return [make_serializable(item) for item in obj]
- elif isinstance(obj, dict):
+ if isinstance(obj, dict):
return {k: make_serializable(v) for k, v in obj.items()}
- else:
- return obj
+ return obj
serializable_result = make_serializable(result)
diff --git a/src/local_deep_research/news/subscription_manager/search_subscription.py b/src/local_deep_research/news/subscription_manager/search_subscription.py
index 746781e6ff..fc7dd238a8 100644
--- a/src/local_deep_research/news/subscription_manager/search_subscription.py
+++ b/src/local_deep_research/news/subscription_manager/search_subscription.py
@@ -126,15 +126,14 @@ class SearchSubscription(BaseSubscription):
if any(term in query_lower for term in ["how to", "tutorial", "guide"]):
# Technical queries - look for updates
return f"{query} latest updates developments"
- elif any(
+ if any(
term in query_lower
for term in ["vulnerability", "security", "breach"]
):
# Security queries - urgent news
return f"{query} breaking news alerts today"
- else:
- # General queries - latest news
- return f"{query} latest news developments"
+ # General queries - latest news
+ return f"{query} latest news developments"
def evolve_query(self, new_terms: Optional[str] = None) -> None:
"""
@@ -154,7 +153,7 @@ class SearchSubscription(BaseSubscription):
def get_statistics(self) -> Dict[str, Any]:
"""Get statistics about this subscription."""
- stats = {
+ return {
"original_query": self.original_query,
"current_query": self.current_query,
"query_evolution_count": len(self.query_history) - 1,
@@ -165,7 +164,6 @@ class SearchSubscription(BaseSubscription):
else 0
),
}
- return stats
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary representation."""
diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.py
index 697f649fc0..79e4ec1020 100644
--- a/src/local_deep_research/notifications/manager.py
+++ b/src/local_deep_research/notifications/manager.py
@@ -169,40 +169,38 @@ class NotificationManager:
Raises:
RateLimitError: If rate limit is exceeded and force=False
"""
- try:
- logger.debug(
- f"Sending notification: event_type={event_type.value}, "
- f"user_id={self._user_id}, force={force}"
- )
- logger.debug(f"Context keys: {list(context.keys())}")
+ logger.debug(
+ f"Sending notification: event_type={event_type.value}, "
+ f"user_id={self._user_id}, force={force}"
+ )
+ logger.debug(f"Context keys: {list(context.keys())}")
- # Check if notifications are enabled for this event type
- should_notify = self._should_notify(event_type)
+ # Check if notifications are enabled for this event type
+ should_notify = self._should_notify(event_type)
+ logger.debug(
+ f"Notification enabled check for {event_type.value}: "
+ f"{should_notify}"
+ )
+
+ if not force and not should_notify:
logger.debug(
- f"Notification enabled check for {event_type.value}: "
- f"{should_notify}"
+ f"Notifications disabled for event type: "
+ f"{event_type.value} (user: {self._user_id})"
)
+ return False
- if not force and not should_notify:
- logger.debug(
- f"Notifications disabled for event type: "
- f"{event_type.value} (user: {self._user_id})"
- )
- return False
+ # Check rate limit using the manager's user_id
+ rate_limit_ok = self._rate_limiter.is_allowed(self._user_id)
+ logger.debug(f"Rate limit check for {self._user_id}: {rate_limit_ok}")
- # Check rate limit using the manager's user_id
- rate_limit_ok = self._rate_limiter.is_allowed(self._user_id)
- logger.debug(
- f"Rate limit check for {self._user_id}: {rate_limit_ok}"
+ if not force and not rate_limit_ok:
+ logger.warning(f"Rate limit exceeded for user {self._user_id}")
+ raise RateLimitError(
+ "Notification rate limit exceeded. "
+ "Please wait before sending more notifications."
)
- if not force and not rate_limit_ok:
- logger.warning(f"Rate limit exceeded for user {self._user_id}")
- raise RateLimitError(
- "Notification rate limit exceeded. "
- "Please wait before sending more notifications."
- )
-
+ try:
# Get service URLs from settings (snapshot or database)
service_urls = self._get_setting(
"notifications.service_url", default=""
@@ -236,9 +234,6 @@ class NotificationManager:
return result
- except RateLimitError:
- logger.warning(f"Rate limit error for user {self._user_id}")
- raise
except Exception:
logger.exception(
f"Error sending notification for {event_type.value} to user "
diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.py
index 939a8b1e8f..23b546b3b3 100644
--- a/src/local_deep_research/notifications/service.py
+++ b/src/local_deep_research/notifications/service.py
@@ -102,10 +102,9 @@ class NotificationService:
if notify_result:
logger.debug(f"Notification sent successfully: '{title[:50]}...'")
return True
- else:
- error_msg = "Failed to send notification to any service"
- logger.warning(error_msg)
- raise SendError(error_msg)
+ error_msg = "Failed to send notification to any service"
+ logger.warning(error_msg)
+ raise SendError(error_msg)
def send(
self,
@@ -137,27 +136,27 @@ class NotificationService:
out of scope. This simple approach is ideal for small deployments
(~5 users) and avoids memory management complexity.
"""
- try:
- # If service_urls are provided, create a new Apprise instance
- if service_urls:
- logger.debug(
- "Creating Apprise instance for provided service URLs"
+ # If service_urls are provided, validate before trying to send
+ if service_urls:
+ logger.debug("Creating Apprise instance for provided service URLs")
+
+ # Validate service URLs for security (SSRF prevention)
+ is_valid, error_msg = (
+ NotificationURLValidator.validate_multiple_urls(
+ service_urls, allow_private_ips=self.allow_private_ips
)
+ )
- # Validate service URLs for security (SSRF prevention)
- is_valid, error_msg = (
- NotificationURLValidator.validate_multiple_urls(
- service_urls, allow_private_ips=self.allow_private_ips
- )
+ if not is_valid:
+ logger.error(
+ f"Service URL validation failed: {error_msg}. "
+ f"URL: {mask_sensitive_url(service_urls)}"
)
+ raise ServiceError(f"Invalid service URL: {error_msg}")
- if not is_valid:
- logger.error(
- f"Service URL validation failed: {error_msg}. "
- f"URL: {mask_sensitive_url(service_urls)}"
- )
- raise ServiceError(f"Invalid service URL: {error_msg}")
-
+ try:
+ # If service_urls are provided, create a new Apprise instance
+ if service_urls:
temp_apprise = apprise.Apprise()
result = temp_apprise.add(service_urls, tag=tag)
@@ -172,18 +171,13 @@ class NotificationService:
return self._send_with_retry(
title, body, temp_apprise, tag, attach
)
- else:
- # Use the configured apprise instance
- if len(self.apprise) == 0:
- logger.debug(
- "No notification services configured in Apprise"
- )
- return False
+ # Use the configured apprise instance
+ if len(self.apprise) == 0:
+ logger.debug("No notification services configured in Apprise")
+ return False
- # Send notification (with retry)
- return self._send_with_retry(
- title, body, self.apprise, tag, attach
- )
+ # Send notification (with retry)
+ return self._send_with_retry(title, body, self.apprise, tag, attach)
except Exception as e:
# Tenacity will retry, but if all retries fail, raise SendError
@@ -225,13 +219,12 @@ class NotificationService:
)
# Send notification
- result = self.send(
+ return self.send(
title=message["title"],
body=message["body"],
service_urls=service_urls,
tag=tag,
)
- return result
def test_service(self, url: str) -> Dict[str, Any]:
"""
@@ -283,11 +276,10 @@ class NotificationService:
"success": True,
"message": "Test notification sent successfully",
}
- else:
- return {
- "success": False,
- "error": "Failed to send test notification",
- }
+ return {
+ "success": False,
+ "error": "Failed to send test notification",
+ }
except Exception:
logger.exception("Error testing notification service")
diff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.py
index 0f030740e0..2a89cc3e25 100644
--- a/src/local_deep_research/report_generator.py
+++ b/src/local_deep_research/report_generator.py
@@ -601,7 +601,4 @@ class IntegratedReportGenerator:
return {"content": final_report_content, "metadata": metadata}
def _generate_error_report(self, query: str, error_msg: str) -> str:
- error_report = (
- f"=== ERROR REPORT ===\nQuery: {query}\nError: {error_msg}"
- )
- return error_report
+ return f"=== ERROR REPORT ===\nQuery: {query}\nError: {error_msg}"
diff --git a/src/local_deep_research/research_library/deletion/routes/delete_routes.py b/src/local_deep_research/research_library/deletion/routes/delete_routes.py
index 652e625493..1909f6573f 100644
--- a/src/local_deep_research/research_library/deletion/routes/delete_routes.py
+++ b/src/local_deep_research/research_library/deletion/routes/delete_routes.py
@@ -85,8 +85,7 @@ def delete_document(document_id):
if result.get("deleted"):
return jsonify({"success": True, **result})
- else:
- return jsonify({"success": False, **result}), 404
+ return jsonify({"success": False, **result}), 404
except Exception as e:
return handle_api_error("deleting document", e)
@@ -111,11 +110,10 @@ def delete_document_blob(document_id):
if result.get("deleted"):
return jsonify({"success": True, **result})
- else:
- error_code = (
- 404 if "not found" in result.get("error", "").lower() else 400
- )
- return jsonify({"success": False, **result}), error_code
+ error_code = (
+ 404 if "not found" in result.get("error", "").lower() else 400
+ )
+ return jsonify({"success": False, **result}), error_code
except Exception as e:
return handle_api_error("deleting document blob", e)
@@ -136,10 +134,7 @@ def get_document_deletion_preview(document_id):
if result.get("found"):
return jsonify({"success": True, **result})
- else:
- return jsonify(
- {"success": False, "error": "Document not found"}
- ), 404
+ return jsonify({"success": False, "error": "Document not found"}), 404
except Exception as e:
return handle_api_error("getting document preview", e)
@@ -174,8 +169,7 @@ def remove_document_from_collection(collection_id, document_id):
if result.get("unlinked"):
return jsonify({"success": True, **result})
- else:
- return jsonify({"success": False, **result}), 404
+ return jsonify({"success": False, **result}), 404
except Exception as e:
return handle_api_error("removing document from collection", e)
@@ -207,10 +201,9 @@ def delete_collection(collection_id):
if result.get("deleted"):
return jsonify({"success": True, **result})
- else:
- error = result.get("error", "Unknown error")
- status_code = 404 if "not found" in error.lower() else 400
- return jsonify({"success": False, **result}), status_code
+ error = result.get("error", "Unknown error")
+ status_code = 404 if "not found" in error.lower() else 400
+ return jsonify({"success": False, **result}), status_code
except Exception as e:
return handle_api_error("deleting collection", e)
@@ -236,8 +229,7 @@ def delete_collection_index(collection_id):
if result.get("deleted"):
return jsonify({"success": True, **result})
- else:
- return jsonify({"success": False, **result}), 404
+ return jsonify({"success": False, **result}), 404
except Exception as e:
return handle_api_error("deleting collection index", e)
@@ -258,10 +250,7 @@ def get_collection_deletion_preview(collection_id):
if result.get("found"):
return jsonify({"success": True, **result})
- else:
- return jsonify(
- {"success": False, "error": "Collection not found"}
- ), 404
+ return jsonify({"success": False, "error": "Collection not found"}), 404
except Exception as e:
return handle_api_error("getting collection preview", e)
diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.py
index c3acc22bf3..37b4f3e7af 100644
--- a/src/local_deep_research/research_library/downloaders/arxiv.py
+++ b/src/local_deep_research/research_library/downloaders/arxiv.py
@@ -30,8 +30,7 @@ class ArxivDownloader(BaseDownloader):
"""Download content from arXiv."""
if content_type == ContentType.TEXT:
return self._download_text(url)
- else:
- return self._download_pdf(url)
+ return self._download_pdf(url)
def download_with_result(
self, url: str, content_type: ContentType = ContentType.PDF
@@ -64,30 +63,25 @@ class ArxivDownloader(BaseDownloader):
content=full_text.encode("utf-8", errors="ignore"),
is_success=True,
)
- else:
- # Just return the extracted text
- return DownloadResult(
- content=extracted_text.encode(
- "utf-8", errors="ignore"
- ),
- is_success=True,
- )
+ # Just return the extracted text
+ return DownloadResult(
+ content=extracted_text.encode("utf-8", errors="ignore"),
+ is_success=True,
+ )
return DownloadResult(
skip_reason=f"Could not retrieve full text for arXiv:{arxiv_id}"
)
- else:
- # Download PDF
- pdf_url = f"https://arxiv.org/pdf/{arxiv_id}.pdf"
- logger.info(f"Downloading arXiv PDF: {arxiv_id}")
+ # Download PDF
+ pdf_url = f"https://arxiv.org/pdf/{arxiv_id}.pdf"
+ logger.info(f"Downloading arXiv PDF: {arxiv_id}")
- pdf_content = super()._download_pdf(pdf_url)
- if pdf_content:
- return DownloadResult(content=pdf_content, is_success=True)
- else:
- return DownloadResult(
- skip_reason=f"Failed to download PDF for arXiv:{arxiv_id} - server may be unavailable"
- )
+ pdf_content = super()._download_pdf(pdf_url)
+ if pdf_content:
+ return DownloadResult(content=pdf_content, is_success=True)
+ return DownloadResult(
+ skip_reason=f"Failed to download PDF for arXiv:{arxiv_id} - server may be unavailable"
+ )
def _download_pdf(
self, url: str, headers: Optional[Dict[str, str]] = None
@@ -134,8 +128,7 @@ class ArxivDownloader(BaseDownloader):
# Combine metadata with full text
full_text = f"{metadata}\n\n{'=' * 80}\nFULL PAPER TEXT\n{'=' * 80}\n\n{extracted_text}"
return full_text.encode("utf-8", errors="ignore")
- else:
- return extracted_text.encode("utf-8", errors="ignore")
+ return extracted_text.encode("utf-8", errors="ignore")
return None
diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.py
index 917f7a236e..691ed9bde5 100644
--- a/src/local_deep_research/research_library/downloaders/base.py
+++ b/src/local_deep_research/research_library/downloaders/base.py
@@ -141,10 +141,9 @@ class BaseDownloader(ABC):
content = self.download(url, content_type)
if content:
return DownloadResult(content=content, is_success=True)
- else:
- return DownloadResult(
- skip_reason="Download failed - content not available"
- )
+ return DownloadResult(
+ skip_reason="Download failed - content not available"
+ )
def download_text(self, url: str) -> Optional[str]:
"""
@@ -245,20 +244,19 @@ class BaseDownloader(ABC):
search_result_count=1, # We got the PDF
)
return response.content
- else:
- logger.warning(
- f"Response is not a PDF: {response.headers.get('content-type', 'unknown')}"
- )
- # Record failure but don't retry for wrong content type
- self.rate_tracker.record_outcome(
- engine_type=engine_type,
- wait_time=wait_time,
- success=False,
- retry_count=attempt,
- error_type="NotPDF",
- )
- return None
- elif response.status_code in [
+ logger.warning(
+ f"Response is not a PDF: {response.headers.get('content-type', 'unknown')}"
+ )
+ # Record failure but don't retry for wrong content type
+ self.rate_tracker.record_outcome(
+ engine_type=engine_type,
+ wait_time=wait_time,
+ success=False,
+ retry_count=attempt,
+ error_type="NotPDF",
+ )
+ return None
+ if response.status_code in [
429,
503,
]: # Rate limit or service unavailable
@@ -280,19 +278,18 @@ class BaseDownloader(ABC):
return None
# Continue retry loop with adaptive wait
continue
- else:
- logger.warning(
- f"Failed to download from {url}: HTTP {response.status_code}"
- )
- # Record failure but don't retry for other status codes
- self.rate_tracker.record_outcome(
- engine_type=engine_type,
- wait_time=wait_time,
- success=False,
- retry_count=attempt,
- error_type=f"HTTP_{response.status_code}",
- )
- return None
+ logger.warning(
+ f"Failed to download from {url}: HTTP {response.status_code}"
+ )
+ # Record failure but don't retry for other status codes
+ self.rate_tracker.record_outcome(
+ engine_type=engine_type,
+ wait_time=wait_time,
+ success=False,
+ retry_count=attempt,
+ error_type=f"HTTP_{response.status_code}",
+ )
+ return None
except (
requests.exceptions.Timeout,
@@ -311,11 +308,10 @@ class BaseDownloader(ABC):
f"{type(e).__name__} downloading from {url} after {max_attempts} attempts"
)
return None
- else:
- logger.warning(
- f"Attempt {attempt}/{max_attempts} - {type(e).__name__} downloading from {url}"
- )
- continue # Retry with adaptive wait
+ logger.warning(
+ f"Attempt {attempt}/{max_attempts} - {type(e).__name__} downloading from {url}"
+ )
+ continue # Retry with adaptive wait
except requests.exceptions.RequestException as e:
logger.exception(f"Request error downloading from {url}")
# Record failure but don't retry
diff --git a/src/local_deep_research/research_library/downloaders/biorxiv.py b/src/local_deep_research/research_library/downloaders/biorxiv.py
index 0c2e41fc16..70a599cea9 100644
--- a/src/local_deep_research/research_library/downloaders/biorxiv.py
+++ b/src/local_deep_research/research_library/downloaders/biorxiv.py
@@ -36,8 +36,7 @@ class BioRxivDownloader(BaseDownloader):
"""Download content from bioRxiv/medRxiv."""
if content_type == ContentType.TEXT:
return self._download_text(url)
- else:
- return self._download_pdf(url)
+ return self._download_pdf(url)
def download_with_result(
self, url: str, content_type: ContentType = ContentType.PDF
@@ -63,36 +62,34 @@ class BioRxivDownloader(BaseDownloader):
return DownloadResult(
skip_reason="Could not extract text from bioRxiv/medRxiv article"
)
- else:
- # Try to download PDF
- pdf_url = self._convert_to_pdf_url(url)
- if not pdf_url:
- return DownloadResult(
- skip_reason="Invalid bioRxiv/medRxiv URL format"
- )
+ # Try to download PDF
+ pdf_url = self._convert_to_pdf_url(url)
+ if not pdf_url:
+ return DownloadResult(
+ skip_reason="Invalid bioRxiv/medRxiv URL format"
+ )
- logger.info(f"Downloading bioRxiv/medRxiv PDF from {pdf_url}")
- pdf_content = super()._download_pdf(pdf_url)
+ logger.info(f"Downloading bioRxiv/medRxiv PDF from {pdf_url}")
+ pdf_content = super()._download_pdf(pdf_url)
- if pdf_content:
- return DownloadResult(content=pdf_content, is_success=True)
- else:
- # Check if it's a server issue or article doesn't exist
- try:
- response = self.session.head(url, timeout=5)
- if response.status_code == 404:
- return DownloadResult(
- skip_reason="Article not found on bioRxiv/medRxiv"
- )
- elif response.status_code >= 500:
- return DownloadResult(
- skip_reason="bioRxiv/medRxiv server temporarily unavailable"
- )
- except requests.RequestException:
- logger.debug("Failed to check bioRxiv/medRxiv URL: %s", url)
+ if pdf_content:
+ return DownloadResult(content=pdf_content, is_success=True)
+ # Check if it's a server issue or article doesn't exist
+ try:
+ response = self.session.head(url, timeout=5)
+ if response.status_code == 404:
return DownloadResult(
- skip_reason="Failed to download PDF from bioRxiv/medRxiv"
+ skip_reason="Article not found on bioRxiv/medRxiv"
)
+ if response.status_code >= 500:
+ return DownloadResult(
+ skip_reason="bioRxiv/medRxiv server temporarily unavailable"
+ )
+ except requests.RequestException:
+ logger.debug("Failed to check bioRxiv/medRxiv URL: %s", url)
+ return DownloadResult(
+ skip_reason="Failed to download PDF from bioRxiv/medRxiv"
+ )
def _download_pdf(
self, url: str, headers: Optional[Dict[str, str]] = None
@@ -141,9 +138,7 @@ class BioRxivDownloader(BaseDownloader):
pdf_url = base_url.rstrip("/") + ".full.pdf"
# Handle content vs. content/early URLs
- pdf_url = pdf_url.replace("/content/early/", "/content/")
-
- return pdf_url
+ return pdf_url.replace("/content/early/", "/content/")
def _fetch_abstract_from_page(self, url: str) -> Optional[str]:
"""Fetch abstract and metadata from bioRxiv/medRxiv page."""
diff --git a/src/local_deep_research/research_library/downloaders/direct_pdf.py b/src/local_deep_research/research_library/downloaders/direct_pdf.py
index 20e2be2750..876fe75c48 100644
--- a/src/local_deep_research/research_library/downloaders/direct_pdf.py
+++ b/src/local_deep_research/research_library/downloaders/direct_pdf.py
@@ -54,8 +54,7 @@ class DirectPDFDownloader(BaseDownloader):
if text:
return text.encode("utf-8")
return None
- else:
- return self._download_pdf(url)
+ return self._download_pdf(url)
def download_with_result(
self, url: str, content_type: ContentType = ContentType.PDF
@@ -70,47 +69,41 @@ class DirectPDFDownloader(BaseDownloader):
return DownloadResult(
content=text.encode("utf-8"), is_success=True
)
- else:
- return DownloadResult(
- skip_reason="PDF downloaded but text extraction failed"
- )
+ return DownloadResult(
+ skip_reason="PDF downloaded but text extraction failed"
+ )
return DownloadResult(
skip_reason="Could not download PDF from direct link"
)
- else:
- # Try to download PDF directly
- logger.info(f"Attempting direct PDF download from {url}")
- pdf_content = super()._download_pdf(url)
+ # Try to download PDF directly
+ logger.info(f"Attempting direct PDF download from {url}")
+ pdf_content = super()._download_pdf(url)
- if pdf_content:
- logger.info(f"Successfully downloaded PDF directly from {url}")
- return DownloadResult(content=pdf_content, is_success=True)
- else:
- # Try to determine specific reason for failure
- try:
- response = self.session.head(
- url, timeout=5, allow_redirects=True
- )
- if response.status_code == 404:
- return DownloadResult(
- skip_reason="PDF file not found (404) - link may be broken"
- )
- elif response.status_code == 403:
- return DownloadResult(
- skip_reason="Access denied (403) - PDF requires authentication"
- )
- elif response.status_code >= 500:
- return DownloadResult(
- skip_reason=f"Server error ({response.status_code}) - try again later"
- )
- else:
- return DownloadResult(
- skip_reason=f"Could not download PDF - server returned status {response.status_code}"
- )
- except Exception:
- return DownloadResult(
- skip_reason="Failed to download PDF from direct link"
- )
+ if pdf_content:
+ logger.info(f"Successfully downloaded PDF directly from {url}")
+ return DownloadResult(content=pdf_content, is_success=True)
+ # Try to determine specific reason for failure
+ try:
+ response = self.session.head(url, timeout=5, allow_redirects=True)
+ if response.status_code == 404:
+ return DownloadResult(
+ skip_reason="PDF file not found (404) - link may be broken"
+ )
+ if response.status_code == 403:
+ return DownloadResult(
+ skip_reason="Access denied (403) - PDF requires authentication"
+ )
+ if response.status_code >= 500:
+ return DownloadResult(
+ skip_reason=f"Server error ({response.status_code}) - try again later"
+ )
+ return DownloadResult(
+ skip_reason=f"Could not download PDF - server returned status {response.status_code}"
+ )
+ except Exception:
+ return DownloadResult(
+ skip_reason="Failed to download PDF from direct link"
+ )
def _download_pdf(
self, url: str, headers: Optional[Dict[str, str]] = None
diff --git a/src/local_deep_research/research_library/downloaders/generic.py b/src/local_deep_research/research_library/downloaders/generic.py
index c3d2436a00..a9b3c1ec88 100644
--- a/src/local_deep_research/research_library/downloaders/generic.py
+++ b/src/local_deep_research/research_library/downloaders/generic.py
@@ -29,9 +29,8 @@ class GenericDownloader(BaseDownloader):
if text:
return text.encode("utf-8")
return None
- else:
- # Try to download as PDF
- return self._download_pdf(url)
+ # Try to download as PDF
+ return self._download_pdf(url)
def download_with_result(
self, url: str, content_type: ContentType = ContentType.PDF
@@ -46,104 +45,100 @@ class GenericDownloader(BaseDownloader):
return DownloadResult(
content=text.encode("utf-8"), is_success=True
)
- else:
- return DownloadResult(
- skip_reason="PDF downloaded but text extraction failed"
- )
+ return DownloadResult(
+ skip_reason="PDF downloaded but text extraction failed"
+ )
return DownloadResult(skip_reason="Could not download PDF from URL")
- else:
- # Try to download as PDF
- logger.info(f"Attempting generic download from {url}")
+ # Try to download as PDF
+ logger.info(f"Attempting generic download from {url}")
+
+ # Try direct download
+ pdf_content = super()._download_pdf(url)
- # Try direct download
- pdf_content = super()._download_pdf(url)
+ if pdf_content:
+ logger.info(f"Successfully downloaded PDF from {url}")
+ return DownloadResult(content=pdf_content, is_success=True)
- if pdf_content:
- logger.info(f"Successfully downloaded PDF from {url}")
- return DownloadResult(content=pdf_content, is_success=True)
-
- # If the URL doesn't end with .pdf, try adding it
- try:
- parsed = urlparse(url)
- if not parsed.path.endswith(".pdf"):
- pdf_url = url.rstrip("/") + ".pdf"
- logger.debug(f"Trying with .pdf extension: {pdf_url}")
- pdf_content = super()._download_pdf(pdf_url)
- else:
- pdf_content = None
- except (ValueError, AttributeError):
- # urlparse can raise ValueError for malformed URLs
+ # If the URL doesn't end with .pdf, try adding it
+ try:
+ parsed = urlparse(url)
+ if not parsed.path.endswith(".pdf"):
+ pdf_url = url.rstrip("/") + ".pdf"
+ logger.debug(f"Trying with .pdf extension: {pdf_url}")
+ pdf_content = super()._download_pdf(pdf_url)
+ else:
pdf_content = None
+ except (ValueError, AttributeError):
+ # urlparse can raise ValueError for malformed URLs
+ pdf_content = None
- if pdf_content:
- logger.info(f"Successfully downloaded PDF from {pdf_url}")
- return DownloadResult(content=pdf_content, is_success=True)
-
- # Diagnostic request: determine WHY the download failed.
- #
- # IMPORTANT: stream=True is intentional here. DO NOT remove it.
- # This block only inspects response.status_code and headers
- # to determine why a download failed (404, 403, paywall, etc.).
- # Without stream=True, the full response body would be downloaded
- # into memory. Since GenericDownloader.can_handle() returns True
- # for ALL URLs, this could mean downloading multi-GB files just
- # to check a status code.
- #
- # The context manager (with ... as response) ensures the streamed
- # connection is properly closed on all code paths, preventing
- # file descriptor leaks (each unclosed stream=True response
- # holds an open socket FD).
- try:
- with self.session.get(
- url, timeout=5, allow_redirects=True, stream=True
- ) as response:
- # Check status code
- if response.status_code == 200:
- # Check if it's HTML instead of PDF
- response_content_type = response.headers.get(
- "content-type", ""
- ).lower()
- if "text/html" in response_content_type:
- return DownloadResult(
- skip_reason="Article page requires login or subscription - no direct PDF link available"
- )
- else:
- return DownloadResult(
- skip_reason=f"Unexpected content type: {response_content_type} - expected PDF"
- )
- elif response.status_code == 404:
- return DownloadResult(
- skip_reason="Article not found (404) - may have been removed or URL is incorrect"
- )
- elif response.status_code == 403:
- return DownloadResult(
- skip_reason="Access denied (403) - article requires subscription or special permissions"
- )
- elif response.status_code == 401:
- return DownloadResult(
- skip_reason="Authentication required - please login to access this article"
- )
- elif response.status_code >= 500:
- return DownloadResult(
- skip_reason=f"Server error ({response.status_code}) - website is experiencing technical issues"
- )
- else:
+ if pdf_content:
+ logger.info(f"Successfully downloaded PDF from {pdf_url}")
+ return DownloadResult(content=pdf_content, is_success=True)
+
+ # Diagnostic request: determine WHY the download failed.
+ #
+ # IMPORTANT: stream=True is intentional here. DO NOT remove it.
+ # This block only inspects response.status_code and headers
+ # to determine why a download failed (404, 403, paywall, etc.).
+ # Without stream=True, the full response body would be downloaded
+ # into memory. Since GenericDownloader.can_handle() returns True
+ # for ALL URLs, this could mean downloading multi-GB files just
+ # to check a status code.
+ #
+ # The context manager (with ... as response) ensures the streamed
+ # connection is properly closed on all code paths, preventing
+ # file descriptor leaks (each unclosed stream=True response
+ # holds an open socket FD).
+ try:
+ with self.session.get(
+ url, timeout=5, allow_redirects=True, stream=True
+ ) as response:
+ # Check status code
+ if response.status_code == 200:
+ # Check if it's HTML instead of PDF
+ response_content_type = response.headers.get(
+ "content-type", ""
+ ).lower()
+ if "text/html" in response_content_type:
return DownloadResult(
- skip_reason=f"Unable to access article - server returned error code {response.status_code}"
+ skip_reason="Article page requires login or subscription - no direct PDF link available"
)
- except requests.exceptions.Timeout:
- return DownloadResult(
- skip_reason="Connection timed out - server took too long to respond"
- )
- except requests.exceptions.ConnectionError:
- return DownloadResult(
- skip_reason="Could not connect to server - website may be down"
- )
- except requests.RequestException:
- logger.warning("Unexpected error checking URL: %s", url)
+ return DownloadResult(
+ skip_reason=f"Unexpected content type: {response_content_type} - expected PDF"
+ )
+ if response.status_code == 404:
+ return DownloadResult(
+ skip_reason="Article not found (404) - may have been removed or URL is incorrect"
+ )
+ if response.status_code == 403:
+ return DownloadResult(
+ skip_reason="Access denied (403) - article requires subscription or special permissions"
+ )
+ if response.status_code == 401:
+ return DownloadResult(
+ skip_reason="Authentication required - please login to access this article"
+ )
+ if response.status_code >= 500:
+ return DownloadResult(
+ skip_reason=f"Server error ({response.status_code}) - website is experiencing technical issues"
+ )
return DownloadResult(
- skip_reason="Network error - could not reach the website"
+ skip_reason=f"Unable to access article - server returned error code {response.status_code}"
)
+ except requests.exceptions.Timeout:
+ return DownloadResult(
+ skip_reason="Connection timed out - server took too long to respond"
+ )
+ except requests.exceptions.ConnectionError:
+ return DownloadResult(
+ skip_reason="Could not connect to server - website may be down"
+ )
+ except requests.RequestException:
+ logger.warning("Unexpected error checking URL: %s", url)
+ return DownloadResult(
+ skip_reason="Network error - could not reach the website"
+ )
def _download_pdf(
self, url: str, headers: Optional[Dict[str, str]] = None
diff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.py
index d7d1eb13b6..18047d704d 100644
--- a/src/local_deep_research/research_library/downloaders/html.py
+++ b/src/local_deep_research/research_library/downloaders/html.py
@@ -165,21 +165,19 @@ class HTMLDownloader(BaseDownloader):
)
# Try to get encoding from response
return response.text
- else:
- logger.warning(
- f"Unexpected content type for HTML download: {content_type}"
- )
- return None
- else:
- logger.warning(f"HTTP {response.status_code} fetching {url}")
- self.rate_tracker.record_outcome(
- engine_type=engine_type,
- wait_time=wait_time,
- success=False,
- retry_count=1,
- error_type=f"HTTP_{response.status_code}",
+ logger.warning(
+ f"Unexpected content type for HTML download: {content_type}"
)
return None
+ logger.warning(f"HTTP {response.status_code} fetching {url}")
+ self.rate_tracker.record_outcome(
+ engine_type=engine_type,
+ wait_time=wait_time,
+ success=False,
+ retry_count=1,
+ error_type=f"HTTP_{response.status_code}",
+ )
+ return None
except Exception as e:
logger.exception(f"Error fetching HTML from {url}")
diff --git a/src/local_deep_research/research_library/downloaders/openalex.py b/src/local_deep_research/research_library/downloaders/openalex.py
index 4a672c42b7..e63ac19611 100644
--- a/src/local_deep_research/research_library/downloaders/openalex.py
+++ b/src/local_deep_research/research_library/downloaders/openalex.py
@@ -86,10 +86,9 @@ class OpenAlexDownloader(BaseDownloader):
if pdf_content:
return DownloadResult(content=pdf_content, is_success=True)
- else:
- return DownloadResult(
- skip_reason="Open access PDF URL found but download failed"
- )
+ return DownloadResult(
+ skip_reason="Open access PDF URL found but download failed"
+ )
def _extract_work_id(self, url: str) -> Optional[str]:
"""
@@ -181,10 +180,9 @@ class OpenAlexDownloader(BaseDownloader):
f"Landing page is a direct PDF link for work {work_id}"
)
return str(landing_url)
- else:
- logger.info(
- f"Landing page is not a PDF (Content-Type: {content_type}), skipping"
- )
+ logger.info(
+ f"Landing page is not a PDF (Content-Type: {content_type}), skipping"
+ )
except Exception:
logger.exception(
f"Failed to validate landing page URL for work {work_id}"
@@ -195,12 +193,11 @@ class OpenAlexDownloader(BaseDownloader):
)
return None
- elif response.status_code == 404:
+ if response.status_code == 404:
logger.warning(f"Work not found in OpenAlex: {work_id}")
return None
- else:
- logger.warning(f"OpenAlex API error: {response.status_code}")
- return None
+ logger.warning(f"OpenAlex API error: {response.status_code}")
+ return None
except requests.exceptions.RequestException:
logger.exception("Failed to query OpenAlex API")
diff --git a/src/local_deep_research/research_library/downloaders/pubmed.py b/src/local_deep_research/research_library/downloaders/pubmed.py
index 47c6f8e340..a35d100e2a 100644
--- a/src/local_deep_research/research_library/downloaders/pubmed.py
+++ b/src/local_deep_research/research_library/downloaders/pubmed.py
@@ -62,9 +62,8 @@ class PubMedDownloader(BaseDownloader):
if content_type == ContentType.TEXT:
# Try to get full text from API
return self._download_text(url)
- else:
- # Download PDF
- return self._download_pdf_content(url)
+ # Download PDF
+ return self._download_pdf_content(url)
def download_with_result(
self, url: str, content_type: ContentType = ContentType.PDF
@@ -77,13 +76,11 @@ class PubMedDownloader(BaseDownloader):
content = self._download_text(url)
if content:
return DownloadResult(content=content, is_success=True)
- else:
- return DownloadResult(
- skip_reason="Full text not available - may require subscription"
- )
- else:
- # Try to download PDF with detailed tracking
- return self._download_pdf_with_result(url)
+ return DownloadResult(
+ skip_reason="Full text not available - may require subscription"
+ )
+ # Try to download PDF with detailed tracking
+ return self._download_pdf_with_result(url)
def _download_pdf_content(self, url: str) -> Optional[bytes]:
"""Download PDF from PubMed/PMC."""
@@ -96,10 +93,10 @@ class PubMedDownloader(BaseDownloader):
if hostname == "ncbi.nlm.nih.gov" and "/pmc/articles/PMC" in path:
return self._download_pmc_direct(url)
# Check for PubMed main site
- elif hostname == "pubmed.ncbi.nlm.nih.gov":
+ if hostname == "pubmed.ncbi.nlm.nih.gov":
return self._download_pubmed(url)
# Check for Europe PMC and subdomains
- elif hostname == "europepmc.org" or hostname.endswith(".europepmc.org"):
+ if hostname == "europepmc.org" or hostname.endswith(".europepmc.org"):
return self._download_europe_pmc(url)
return None
@@ -129,7 +126,7 @@ class PubMedDownloader(BaseDownloader):
skip_reason=f"PMC article {pmc_id} not accessible - may be retracted or embargoed"
)
- elif urlparse(url).hostname == "pubmed.ncbi.nlm.nih.gov":
+ if urlparse(url).hostname == "pubmed.ncbi.nlm.nih.gov":
# Extract PMID
pmid_match = re.search(r"/(\d+)/?", url)
if not pmid_match:
@@ -206,30 +203,20 @@ class PubMedDownloader(BaseDownloader):
skip_reason="No free full-text available - article may be paywalled"
)
- else:
- parsed = urlparse(url)
- hostname = parsed.hostname or ""
- if hostname == "europepmc.org" or hostname.endswith(
- ".europepmc.org"
- ):
- pmc_match = re.search(r"(PMC\d+)", url)
- if pmc_match:
- pmc_id = pmc_match.group(1)
- pdf_content = self._download_via_europe_pmc(pmc_id)
- if pdf_content:
- return DownloadResult(
- content=pdf_content, is_success=True
- )
- return DownloadResult(
- skip_reason=f"Europe PMC article {pmc_id} not accessible"
- )
- return DownloadResult(
- skip_reason="Invalid Europe PMC URL format"
- )
- else:
+ parsed = urlparse(url)
+ hostname = parsed.hostname or ""
+ if hostname == "europepmc.org" or hostname.endswith(".europepmc.org"):
+ pmc_match = re.search(r"(PMC\d+)", url)
+ if pmc_match:
+ pmc_id = pmc_match.group(1)
+ pdf_content = self._download_via_europe_pmc(pmc_id)
+ if pdf_content:
+ return DownloadResult(content=pdf_content, is_success=True)
return DownloadResult(
- skip_reason="Unsupported PubMed/PMC URL format"
+ skip_reason=f"Europe PMC article {pmc_id} not accessible"
)
+ return DownloadResult(skip_reason="Invalid Europe PMC URL format")
+ return DownloadResult(skip_reason="Unsupported PubMed/PMC URL format")
def _download_text(self, url: str) -> Optional[bytes]:
"""Download full text content from PubMed/PMC APIs."""
diff --git a/src/local_deep_research/research_library/downloaders/semantic_scholar.py b/src/local_deep_research/research_library/downloaders/semantic_scholar.py
index 7400500016..192704fb6d 100644
--- a/src/local_deep_research/research_library/downloaders/semantic_scholar.py
+++ b/src/local_deep_research/research_library/downloaders/semantic_scholar.py
@@ -83,10 +83,9 @@ class SemanticScholarDownloader(BaseDownloader):
if pdf_content:
return DownloadResult(content=pdf_content, is_success=True)
- else:
- return DownloadResult(
- skip_reason="Open access PDF URL found but download failed"
- )
+ return DownloadResult(
+ skip_reason="Open access PDF URL found but download failed"
+ )
def _extract_paper_id(self, url: str) -> Optional[str]:
"""
@@ -153,16 +152,15 @@ class SemanticScholarDownloader(BaseDownloader):
)
return None
- elif response.status_code == 404:
+ if response.status_code == 404:
logger.warning(
f"Paper not found in Semantic Scholar: {paper_id}"
)
return None
- else:
- logger.warning(
- f"Semantic Scholar API error: {response.status_code}"
- )
- return None
+ logger.warning(
+ f"Semantic Scholar API error: {response.status_code}"
+ )
+ return None
except requests.exceptions.RequestException:
logger.exception("Failed to query Semantic Scholar API")
diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.py
index 91d7008367..1c46437e0d 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -526,16 +526,13 @@ def download_single_resource(resource_id):
success, error = service.download_resource(resource_id)
if success:
return jsonify({"success": True})
- else:
- logger.warning(
- f"Download failed for resource {resource_id}: {error}"
- )
- return jsonify(
- {
- "success": False,
- "error": "Download failed. Please try again or contact support.",
- }
- ), 500
+ logger.warning(f"Download failed for resource {resource_id}: {error}")
+ return jsonify(
+ {
+ "success": False,
+ "error": "Download failed. Please try again or contact support.",
+ }
+ ), 500
@library_bp.route("/api/download-text/<int:resource_id>", methods=["POST"])
@@ -1306,6 +1303,5 @@ def download_source():
return jsonify(
{"success": True, "message": "Download completed"}
)
- else:
- # Log internal message, but show only generic message to user
- return jsonify({"success": False, "message": "Download failed"})
+ # Log internal message, but show only generic message to user
+ return jsonify({"success": False, "message": "Download failed"})
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index f7e3b1dc6e..3cabd504f8 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -1963,7 +1963,7 @@ def index_collection(collection_id):
# Check for errors from thread
if not error_queue.empty():
- raise error_queue.get()
+ raise error_queue.get() # noqa: TRY301 — re-raises thread exception for per-document error handling
result = result_queue.get()
logger.info(
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 91d2adb3ef..8d40229fd5 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -229,7 +229,7 @@ class DownloadService:
)
if absolute_path and absolute_path.is_file():
return True, str(absolute_path)
- elif absolute_path:
+ if absolute_path:
# File was deleted, mark as not downloaded
tracker.is_downloaded = False
session.commit()
@@ -570,7 +570,7 @@ class DownloadService:
if result.is_success and result.content:
pdf_content = result.content
break
- elif result.skip_reason:
+ if result.skip_reason:
skip_reason = result.skip_reason
logger.info(f"Download skipped: {skip_reason}")
# Keep trying other downloaders unless it's the GenericDownloader
diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.py
index 1b03e8f3dd..7d22cf391c 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -106,14 +106,14 @@ class LibraryService:
"""Apply domain filter to query for Document."""
if domain == "arxiv.org":
return query.filter(model_class.original_url.like("%arxiv.org%"))
- elif domain == "pubmed":
+ if domain == "pubmed":
return query.filter(
or_(
model_class.original_url.like("%pubmed%"),
model_class.original_url.like("%ncbi.nlm.nih.gov%"),
)
)
- elif domain == "other":
+ if domain == "other":
return query.filter(
and_(
~model_class.original_url.like("%arxiv.org%"),
@@ -121,8 +121,7 @@ class LibraryService:
~model_class.original_url.like("%ncbi.nlm.nih.gov%"),
)
)
- else:
- return query.filter(model_class.original_url.like(f"%{domain}%"))
+ return query.filter(model_class.original_url.like(f"%{domain}%"))
def _apply_search_filter(self, query, model_class, search_query: str):
"""Apply search filter to query for Document."""
diff --git a/src/local_deep_research/research_library/services/pdf_storage_manager.py b/src/local_deep_research/research_library/services/pdf_storage_manager.py
index 33b1f23ca9..837312f108 100644
--- a/src/local_deep_research/research_library/services/pdf_storage_manager.py
+++ b/src/local_deep_research/research_library/services/pdf_storage_manager.py
@@ -118,7 +118,7 @@ class PDFStorageManager:
logger.debug("PDF storage mode is 'none' - skipping PDF save")
return None, file_size
- elif self.storage_mode == "filesystem":
+ if self.storage_mode == "filesystem":
file_path = self._save_to_filesystem(
pdf_content, filename, url, resource_id
)
@@ -128,7 +128,7 @@ class PDFStorageManager:
logger.info(f"PDF saved to filesystem: {relative_path}")
return relative_path, file_size
- elif self.storage_mode == "database":
+ if self.storage_mode == "database":
self._save_to_database(pdf_content, document, session)
document.storage_mode = "database"
document.file_path = None # No filesystem path
@@ -342,7 +342,7 @@ class PDFStorageManager:
return f"arxiv_{match.group(1)}.pdf"
return f"arxiv_{timestamp}_{resource_id or 'unknown'}.pdf"
- elif hostname == "ncbi.nlm.nih.gov" and "/pmc" in parsed_url.path:
+ if hostname == "ncbi.nlm.nih.gov" and "/pmc" in parsed_url.path:
# Extract PMC ID
match = re.search(r"(PMC\d+)", url)
if match:
@@ -378,7 +378,7 @@ class PDFStorageManager:
document.storage_mode = "none"
return True
- elif storage_mode == "database":
+ if storage_mode == "database":
blob = (
session.query(DocumentBlob)
.filter_by(document_id=document.id)
diff --git a/src/local_deep_research/research_library/services/rag_service_factory.py b/src/local_deep_research/research_library/services/rag_service_factory.py
index 74bf2f615a..dc5338a9d8 100644
--- a/src/local_deep_research/research_library/services/rag_service_factory.py
+++ b/src/local_deep_research/research_library/services/rag_service_factory.py
@@ -138,14 +138,14 @@ def get_rag_service(
index_type=_col(collection.index_type, default_index_type),
db_password=db_password,
)
- elif collection:
+ if collection:
# New collection - use defaults and store them
logger.info(
f"New collection {collection_id}, using and storing default settings"
)
# Create service with defaults
- service = LibraryRAGService(
+ return LibraryRAGService(
username=username,
embedding_model=default_embedding_model,
embedding_provider=default_embedding_provider,
@@ -163,8 +163,6 @@ def get_rag_service(
# Note: We don't store here because we don't have embedding_dimension yet
# It will be stored in index_collection when first document is indexed
- return service
-
# No collection or fallback - use current defaults
return LibraryRAGService(
username=username,
diff --git a/src/local_deep_research/research_library/utils/__init__.py b/src/local_deep_research/research_library/utils/__init__.py
index be9c01312e..5a840845e8 100644
--- a/src/local_deep_research/research_library/utils/__init__.py
+++ b/src/local_deep_research/research_library/utils/__init__.py
@@ -189,11 +189,10 @@ def get_library_storage_path(username: str) -> Path:
# Shared mode: all users use the same directory
base_path.mkdir(parents=True, exist_ok=True)
return base_path
- else:
- # Default: user isolation with subdirectories
- user_dir = base_path / username
- user_dir.mkdir(parents=True, exist_ok=True)
- return user_dir
+ # Default: user isolation with subdirectories
+ user_dir = base_path / username
+ user_dir.mkdir(parents=True, exist_ok=True)
+ return user_dir
def open_file_location(file_path: str) -> bool:
diff --git a/src/local_deep_research/research_scheduler/document_scheduler.py b/src/local_deep_research/research_scheduler/document_scheduler.py
index 79ac36e5af..3769dd5a84 100644
--- a/src/local_deep_research/research_scheduler/document_scheduler.py
+++ b/src/local_deep_research/research_scheduler/document_scheduler.py
@@ -67,11 +67,10 @@ class DocumentSchedulerUtil:
if success:
return True, "Manual document processing triggered successfully"
- else:
- return (
- False,
- "Failed to trigger document processing - user may not be active or processing disabled",
- )
+ return (
+ False,
+ "Failed to trigger document processing - user may not be active or processing disabled",
+ )
except Exception:
logger.exception(
diff --git a/src/local_deep_research/research_scheduler/routes.py b/src/local_deep_research/research_scheduler/routes.py
index 2aed919858..155e847263 100644
--- a/src/local_deep_research/research_scheduler/routes.py
+++ b/src/local_deep_research/research_scheduler/routes.py
@@ -53,8 +53,7 @@ def trigger_manual_run():
if success:
return jsonify({"message": message})
- else:
- return jsonify({"error": message}), 400
+ return jsonify({"error": message}), 400
except Exception:
logger.exception("Error triggering manual run")
return jsonify({"error": "Failed to trigger manual run"}), 500
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index e125e7177b..c1d43edaed 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -292,12 +292,10 @@ class AdvancedSearchSystem:
search_id = str(uuid.uuid4())
# Perform the search
- result = self._perform_search(
+ return self._perform_search(
query, search_id, is_user_search, is_news_search, user_id
)
- return result
-
def _perform_search(
self,
query: str,
diff --git a/src/local_deep_research/search_system_factory.py b/src/local_deep_research/search_system_factory.py
index fa498e85e3..91250bdb34 100644
--- a/src/local_deep_research/search_system_factory.py
+++ b/src/local_deep_research/search_system_factory.py
@@ -167,7 +167,7 @@ def create_strategy(
)
# Focused iteration strategy
- elif strategy_name_lower in ["focused-iteration", "focused_iteration"]:
+ if strategy_name_lower in ["focused-iteration", "focused_iteration"]:
from .advanced_search_system.strategies.focused_iteration_strategy import (
FocusedIterationStrategy,
)
@@ -264,7 +264,7 @@ def create_strategy(
return strategy
# Focused iteration strategy with standard citation handler
- elif strategy_name_lower in [
+ if strategy_name_lower in [
"focused-iteration-standard",
"focused_iteration_standard",
]:
@@ -372,7 +372,7 @@ def create_strategy(
return strategy
# Iterative reasoning strategy (depth variant)
- elif strategy_name_lower in [
+ if strategy_name_lower in [
"iterative-reasoning",
"iterative_reasoning",
"iterative_reasoning_depth",
@@ -388,7 +388,7 @@ def create_strategy(
)
# News aggregation strategy
- elif strategy_name_lower in [
+ if strategy_name_lower in [
"news",
"news_aggregation",
"news-aggregation",
@@ -404,7 +404,7 @@ def create_strategy(
)
# IterDRAG strategy
- elif strategy_name_lower == "iterdrag":
+ if strategy_name_lower == "iterdrag":
from .advanced_search_system.strategies.iterdrag_strategy import (
IterDRAGStrategy,
)
@@ -417,7 +417,7 @@ def create_strategy(
)
# Parallel strategy
- elif strategy_name_lower == "parallel":
+ if strategy_name_lower == "parallel":
from .advanced_search_system.strategies.parallel_search_strategy import (
ParallelSearchStrategy,
)
@@ -432,7 +432,7 @@ def create_strategy(
)
# Rapid strategy
- elif strategy_name_lower == "rapid":
+ if strategy_name_lower == "rapid":
from .advanced_search_system.strategies.rapid_search_strategy import (
RapidSearchStrategy,
)
@@ -445,7 +445,7 @@ def create_strategy(
)
# Recursive decomposition strategy
- elif strategy_name_lower in ["recursive", "recursive-decomposition"]:
+ if strategy_name_lower in ["recursive", "recursive-decomposition"]:
from .advanced_search_system.strategies.recursive_decomposition_strategy import (
RecursiveDecompositionStrategy,
)
@@ -458,7 +458,7 @@ def create_strategy(
)
# Iterative reasoning strategy (different from iterative_reasoning_depth)
- elif strategy_name_lower == "iterative":
+ if strategy_name_lower == "iterative":
from .advanced_search_system.strategies.iterative_reasoning_strategy import (
IterativeReasoningStrategy,
)
@@ -482,7 +482,7 @@ def create_strategy(
)
# Adaptive decomposition strategy
- elif strategy_name_lower == "adaptive":
+ if strategy_name_lower == "adaptive":
from .advanced_search_system.strategies.adaptive_decomposition_strategy import (
AdaptiveDecompositionStrategy,
)
@@ -502,7 +502,7 @@ def create_strategy(
)
# Smart decomposition strategy
- elif strategy_name_lower == "smart":
+ if strategy_name_lower == "smart":
from .advanced_search_system.strategies.smart_decomposition_strategy import (
SmartDecompositionStrategy,
)
@@ -521,7 +521,7 @@ def create_strategy(
)
# BrowseComp optimized strategy
- elif strategy_name_lower == "browsecomp":
+ if strategy_name_lower == "browsecomp":
from .advanced_search_system.strategies.browsecomp_optimized_strategy import (
BrowseCompOptimizedStrategy,
)
@@ -540,7 +540,7 @@ def create_strategy(
)
# Enhanced evidence-based strategy
- elif strategy_name_lower == "evidence":
+ if strategy_name_lower == "evidence":
from .advanced_search_system.strategies.evidence_based_strategy_v2 import (
EnhancedEvidenceBasedStrategy,
)
@@ -561,7 +561,7 @@ def create_strategy(
)
# Constrained search strategy
- elif strategy_name_lower == "constrained":
+ if strategy_name_lower == "constrained":
from .advanced_search_system.strategies.constrained_search_strategy import (
ConstrainedSearchStrategy,
)
@@ -581,7 +581,7 @@ def create_strategy(
)
# Parallel constrained strategy
- elif strategy_name_lower in [
+ if strategy_name_lower in [
"parallel-constrained",
"parallel_constrained",
]:
@@ -605,7 +605,7 @@ def create_strategy(
)
# Early stop constrained strategy
- elif strategy_name_lower in [
+ if strategy_name_lower in [
"early-stop-constrained",
"early_stop_constrained",
]:
@@ -631,7 +631,7 @@ def create_strategy(
)
# Smart query strategy
- elif strategy_name_lower in ["smart-query", "smart_query"]:
+ if strategy_name_lower in ["smart-query", "smart_query"]:
from .advanced_search_system.strategies.smart_query_strategy import (
SmartQueryStrategy,
)
@@ -658,7 +658,7 @@ def create_strategy(
)
# Dual confidence strategy
- elif strategy_name_lower in ["dual-confidence", "dual_confidence"]:
+ if strategy_name_lower in ["dual-confidence", "dual_confidence"]:
from .advanced_search_system.strategies.dual_confidence_strategy import (
DualConfidenceStrategy,
)
@@ -691,7 +691,7 @@ def create_strategy(
)
# Dual confidence with rejection strategy
- elif strategy_name_lower in [
+ if strategy_name_lower in [
"dual-confidence-with-rejection",
"dual_confidence_with_rejection",
]:
@@ -732,7 +732,7 @@ def create_strategy(
)
# Concurrent dual confidence strategy
- elif strategy_name_lower in [
+ if strategy_name_lower in [
"concurrent-dual-confidence",
"concurrent_dual_confidence",
]:
@@ -783,7 +783,7 @@ def create_strategy(
)
# Constraint parallel strategy
- elif strategy_name_lower in [
+ if strategy_name_lower in [
"constraint-parallel",
"constraint_parallel",
]:
@@ -824,7 +824,7 @@ def create_strategy(
)
# Modular strategy
- elif strategy_name_lower in ["modular", "modular-strategy"]:
+ if strategy_name_lower in ["modular", "modular-strategy"]:
from .advanced_search_system.strategies.modular_strategy import (
ModularStrategy,
)
@@ -847,7 +847,7 @@ def create_strategy(
)
# Modular parallel strategy
- elif strategy_name_lower in ["modular-parallel", "modular_parallel"]:
+ if strategy_name_lower in ["modular-parallel", "modular_parallel"]:
from .advanced_search_system.strategies.modular_strategy import (
ModularStrategy,
)
@@ -862,7 +862,7 @@ def create_strategy(
)
# BrowseComp entity strategy
- elif strategy_name_lower in ["browsecomp-entity", "browsecomp_entity"]:
+ if strategy_name_lower in ["browsecomp-entity", "browsecomp_entity"]:
from .advanced_search_system.strategies.browsecomp_entity_strategy import (
BrowseCompEntityStrategy,
)
@@ -874,7 +874,7 @@ def create_strategy(
)
# Topic organization strategy
- elif strategy_name_lower in [
+ if strategy_name_lower in [
"topic-organization",
"topic_organization",
"topic",
@@ -910,7 +910,7 @@ def create_strategy(
)
# Iterative refinement strategy
- elif strategy_name_lower in [
+ if strategy_name_lower in [
"iterative-refinement",
"iterative_refinement",
]:
@@ -945,7 +945,7 @@ def create_strategy(
)
# Standard strategy
- elif strategy_name_lower == "standard":
+ if strategy_name_lower == "standard":
from .advanced_search_system.strategies.standard_strategy import (
StandardSearchStrategy,
)
@@ -958,7 +958,7 @@ def create_strategy(
)
# MCP strategy (ReAct pattern - agentic research)
- elif strategy_name_lower in ["mcp", "agentic"]:
+ if strategy_name_lower in ["mcp", "agentic"]:
from .advanced_search_system.strategies.mcp_strategy import (
MCPSearchStrategy,
)
@@ -979,22 +979,21 @@ def create_strategy(
settings_snapshot=settings_snapshot,
)
- else:
- # Default to source-based if unknown
- logger.warning(
- f"Unknown strategy: {strategy_name}, defaulting to source-based"
- )
- from .advanced_search_system.strategies.source_based_strategy import (
- SourceBasedSearchStrategy,
- )
-
- return SourceBasedSearchStrategy(
- model=model,
- search=search,
- include_text_content=True,
- use_cross_engine_filter=True,
- all_links_of_system=all_links_of_system,
- use_atomic_facts=False,
- settings_snapshot=settings_snapshot,
- search_original_query=kwargs.get("search_original_query", True),
- )
+ # Default to source-based if unknown
+ logger.warning(
+ f"Unknown strategy: {strategy_name}, defaulting to source-based"
+ )
+ from .advanced_search_system.strategies.source_based_strategy import (
+ SourceBasedSearchStrategy,
+ )
+
+ return SourceBasedSearchStrategy(
+ model=model,
+ search=search,
+ include_text_content=True,
+ use_cross_engine_filter=True,
+ all_links_of_system=all_links_of_system,
+ use_atomic_facts=False,
+ settings_snapshot=settings_snapshot,
+ search_original_query=kwargs.get("search_original_query", True),
+ )
diff --git a/src/local_deep_research/security/data_sanitizer.py b/src/local_deep_research/security/data_sanitizer.py
index a5f9a2cac4..fc75ac346b 100644
--- a/src/local_deep_research/security/data_sanitizer.py
+++ b/src/local_deep_research/security/data_sanitizer.py
@@ -64,13 +64,12 @@ class DataSanitizer:
for k, v in data.items()
if k.lower() not in sensitive_keys_lower
}
- elif isinstance(data, list):
+ if isinstance(data, list):
return [
DataSanitizer.sanitize(item, sensitive_keys) for item in data
]
- else:
- # Return primitives unchanged
- return data
+ # Return primitives unchanged
+ return data
@staticmethod
def redact(
@@ -114,14 +113,13 @@ class DataSanitizer:
)
for k, v in data.items()
}
- elif isinstance(data, list):
+ if isinstance(data, list):
return [
DataSanitizer.redact(item, sensitive_keys, redaction_text)
for item in data
]
- else:
- # Return primitives unchanged
- return data
+ # Return primitives unchanged
+ return data
# Convenience functions for direct use
diff --git a/src/local_deep_research/security/decorators.py b/src/local_deep_research/security/decorators.py
index cf28635cad..bb778514e1 100644
--- a/src/local_deep_research/security/decorators.py
+++ b/src/local_deep_research/security/decorators.py
@@ -36,13 +36,13 @@ def require_json_body(
jsonify({"status": "error", "message": error_message}),
400,
)
- elif error_format == "success":
+ if error_format == "success":
return (
jsonify({"success": False, "error": error_message}),
400,
)
- else: # "simple"
- return jsonify({"error": error_message}), 400
+ # "simple"
+ return jsonify({"error": error_message}), 400
return fn(*args, **kwargs)
return wrapper
diff --git a/src/local_deep_research/security/file_write_verifier.py b/src/local_deep_research/security/file_write_verifier.py
index 26da81c928..62910ca6f0 100644
--- a/src/local_deep_research/security/file_write_verifier.py
+++ b/src/local_deep_research/security/file_write_verifier.py
@@ -50,10 +50,9 @@ def _sanitize_sensitive_data(data: Any) -> Any:
else:
result[key] = _sanitize_sensitive_data(value)
return result
- elif isinstance(data, list):
+ if isinstance(data, list):
return [_sanitize_sensitive_data(item) for item in data]
- else:
- return data
+ return data
class FileWriteSecurityError(Exception):
diff --git a/src/local_deep_research/security/path_validator.py b/src/local_deep_research/security/path_validator.py
index b7cdb38a44..6073e9a1c0 100644
--- a/src/local_deep_research/security/path_validator.py
+++ b/src/local_deep_research/security/path_validator.py
@@ -63,27 +63,28 @@ class PathValidator:
try:
# safe_join returns None if the path tries to escape base_dir
safe_path = safe_join(str(base_dir), user_input)
+ except ValueError:
+ raise
+ except Exception as e:
+ logger.warning(f"Path validation failed for input '{user_input}'")
+ raise ValueError(f"Invalid path: {e}") from e
- if safe_path is None:
- logger.warning(f"Path traversal attempt blocked: {user_input}")
- raise ValueError("Invalid path - potential traversal attempt")
-
- result_path = Path(safe_path)
+ if safe_path is None:
+ logger.warning(f"Path traversal attempt blocked: {user_input}")
+ raise ValueError("Invalid path - potential traversal attempt")
- # Check extensions if required
- if (
- required_extensions
- and result_path.suffix not in required_extensions
- ):
- raise ValueError(
- f"Invalid file type. Allowed: {required_extensions}"
- )
+ result_path = Path(safe_path)
- return result_path
+ # Check extensions if required
+ if (
+ required_extensions
+ and result_path.suffix not in required_extensions
+ ):
+ raise ValueError(
+ f"Invalid file type. Allowed: {required_extensions}"
+ )
- except Exception as e:
- logger.warning(f"Path validation failed for input '{user_input}'")
- raise ValueError(f"Invalid path: {e}") from e
+ return result_path
@staticmethod
def validate_local_filesystem_path(
@@ -381,19 +382,18 @@ class PathValidator:
raise ValueError(f"Config file not found: {path_obj}")
return path_obj
- else:
- # For relative paths, use the config root
- if config_root is None:
- from ..config.paths import get_data_directory
+ # For relative paths, use the config root
+ if config_root is None:
+ from ..config.paths import get_data_directory
- config_root = get_data_directory()
+ config_root = get_data_directory()
- validated = PathValidator.validate_safe_path(
- config_path,
- config_root,
- allow_absolute=False,
- required_extensions=PathValidator.CONFIG_EXTENSIONS,
- )
- if validated is None:
- raise ValueError(f"Invalid config path: {config_path}")
- return validated
+ validated = PathValidator.validate_safe_path(
+ config_path,
+ config_root,
+ allow_absolute=False,
+ required_extensions=PathValidator.CONFIG_EXTENSIONS,
+ )
+ if validated is None:
+ raise ValueError(f"Invalid config path: {config_path}")
+ return validated
diff --git a/src/local_deep_research/security/security_settings.py b/src/local_deep_research/security/security_settings.py
index eecd9a7076..7fd9d4f53f 100644
--- a/src/local_deep_research/security/security_settings.py
+++ b/src/local_deep_research/security/security_settings.py
@@ -55,12 +55,11 @@ def _convert_value(value: str, target_type: type, key: str) -> Optional[Any]:
if target_type is bool:
# Handle boolean strings properly
return value.lower() in ("true", "1", "yes", "on")
- elif target_type is int:
+ if target_type is int:
return int(value)
- elif target_type is float:
+ if target_type is float:
return float(value)
- else:
- return str(value)
+ return str(value)
except (ValueError, TypeError):
logger.warning(
f"Invalid value for {key}: '{value}' cannot be converted to {target_type.__name__}"
diff --git a/src/local_deep_research/security/url_validator.py b/src/local_deep_research/security/url_validator.py
index 254dc1002a..c33be6cc54 100644
--- a/src/local_deep_research/security/url_validator.py
+++ b/src/local_deep_research/security/url_validator.py
@@ -305,45 +305,40 @@ class URLValidator:
try:
parsed = urlparse(url)
+ except URLValidationError:
+ raise
+ except Exception as e:
+ raise URLValidationError(f"Failed to validate URL: {e}") from e
- # Must have a scheme
- if not parsed.scheme:
- raise URLValidationError(
- "URL must have a scheme (http or https)"
- )
-
- # Must be http or https (callback URLs only)
- if parsed.scheme not in ("http", "https"):
- raise URLValidationError(
- f"URL scheme must be http or https, got: {parsed.scheme}"
- )
+ # Must have a scheme
+ if not parsed.scheme:
+ raise URLValidationError("URL must have a scheme (http or https)")
- # Use the general security validator for additional safety
- if not URLValidator.is_safe_url(url, require_scheme=True):
- raise URLValidationError(
- f"URL failed security validation: {url}"
- )
+ # Must be http or https (callback URLs only)
+ if parsed.scheme not in ("http", "https"):
+ raise URLValidationError(
+ f"URL scheme must be http or https, got: {parsed.scheme}"
+ )
- # Must have a netloc (hostname)
- if not parsed.netloc:
- raise URLValidationError("URL must have a hostname")
+ # Use the general security validator for additional safety
+ if not URLValidator.is_safe_url(url, require_scheme=True):
+ raise URLValidationError(f"URL failed security validation: {url}")
- # Check for obvious hostname issues
- if parsed.netloc.startswith(".") or parsed.netloc.endswith("."):
- raise URLValidationError(f"Invalid hostname: {parsed.netloc}")
+ # Must have a netloc (hostname)
+ if not parsed.netloc:
+ raise URLValidationError("URL must have a hostname")
- # Path should be valid if present
- if parsed.path and not parsed.path.startswith("/"):
- raise URLValidationError(
- f"URL path must start with /: {parsed.path}"
- )
+ # Check for obvious hostname issues
+ if parsed.netloc.startswith(".") or parsed.netloc.endswith("."):
+ raise URLValidationError(f"Invalid hostname: {parsed.netloc}")
- return True
+ # Path should be valid if present
+ if parsed.path and not parsed.path.startswith("/"):
+ raise URLValidationError(
+ f"URL path must start with /: {parsed.path}"
+ )
- except Exception as e:
- if isinstance(e, URLValidationError):
- raise
- raise URLValidationError(f"Failed to validate URL: {e}")
+ return True
@staticmethod
def is_safe_redirect_url(target: str, host_url: str) -> bool:
diff --git a/src/local_deep_research/settings/env_settings.py b/src/local_deep_research/settings/env_settings.py
index ba2ef11de8..df9fe05ffa 100644
--- a/src/local_deep_research/settings/env_settings.py
+++ b/src/local_deep_research/settings/env_settings.py
@@ -164,22 +164,21 @@ class IntegerSetting(EnvSetting[int]):
"""Convert string to integer with validation."""
try:
value = int(raw)
- if self.min_value is not None and value < self.min_value:
- raise ValueError(
- f"{self.env_var} value {value} is below minimum {self.min_value}"
- )
- if self.max_value is not None and value > self.max_value:
- raise ValueError(
- f"{self.env_var} value {value} is above maximum {self.max_value}"
- )
- return value
- except ValueError as e:
- if "invalid literal" in str(e):
- logger.warning(
- f"Invalid integer value '{raw}' for {self.env_var}, using default: {self.default}"
- )
- return self.default
- raise
+ except ValueError:
+ logger.warning(
+ f"Invalid integer value '{raw}' for {self.env_var}, using default: {self.default}"
+ )
+ return self.default
+
+ if self.min_value is not None and value < self.min_value:
+ raise ValueError(
+ f"{self.env_var} value {value} is below minimum {self.min_value}"
+ )
+ if self.max_value is not None and value > self.max_value:
+ raise ValueError(
+ f"{self.env_var} value {value} is above maximum {self.max_value}"
+ )
+ return value
class PathSetting(StringSetting):
@@ -279,15 +278,14 @@ class EnumSetting(EnvSetting[str]):
f"{self.env_var} value '{raw}' not in allowed values: {self.allowed_values}"
)
return raw
- else:
- # Case-insensitive matching
- raw_lower = raw.lower()
- if raw_lower not in self._allowed_lower:
- raise ValueError(
- f"{self.env_var} value '{raw}' not in allowed values: {self.allowed_values}"
- )
- # Return the canonical version (from allowed_values)
- return self._canonical_map[raw_lower]
+ # Case-insensitive matching
+ raw_lower = raw.lower()
+ if raw_lower not in self._allowed_lower:
+ raise ValueError(
+ f"{self.env_var} value '{raw}' not in allowed values: {self.allowed_values}"
+ )
+ # Return the canonical version (from allowed_values)
+ return self._canonical_map[raw_lower]
class SettingsRegistry:
diff --git a/src/local_deep_research/settings/logger.py b/src/local_deep_research/settings/logger.py
index 61368f6275..b40734cd0e 100644
--- a/src/local_deep_research/settings/logger.py
+++ b/src/local_deep_research/settings/logger.py
@@ -151,8 +151,7 @@ def create_settings_summary(settings: Any) -> str:
total = len(settings)
return f"{total} total settings (search engines: {search_engines}, LLM: {llm_settings})"
- else:
- return f"Settings object of type {type(settings).__name__}"
+ return f"Settings object of type {type(settings).__name__}"
def get_settings_log_level() -> str:
diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.py
index 0749bbb3ca..76add0ac55 100644
--- a/src/local_deep_research/settings/manager.py
+++ b/src/local_deep_research/settings/manager.py
@@ -481,24 +481,23 @@ class SettingsManager(ISettingsManager):
)
return query.all()
- else:
- logger.debug(
- "DB is disabled, reading setting '{}' from defaults file.", key
- )
+ logger.debug(
+ "DB is disabled, reading setting '{}' from defaults file.", key
+ )
- settings = []
- for candidate_key, setting in self.default_settings.items():
- if key is None or (
- candidate_key == key or candidate_key.startswith(f"{key}.")
- ):
- settings.append(
- Setting(
- key=candidate_key, # gitleaks:allow
- **_filter_setting_columns(setting),
- )
+ settings = []
+ for candidate_key, setting in self.default_settings.items():
+ if key is None or (
+ candidate_key == key or candidate_key.startswith(f"{key}.")
+ ):
+ settings.append(
+ Setting(
+ key=candidate_key, # gitleaks:allow
+ **_filter_setting_columns(setting),
)
+ )
- return settings
+ return settings
def get_setting(
self, key: str, default: Any = None, check_env: bool = True
@@ -535,12 +534,11 @@ class SettingsManager(ISettingsManager):
settings = self.__query_settings(key)
if len(settings) == 1:
# This is a bottom-level key.
- result = self.__get_typed_setting_value(
+ return self.__get_typed_setting_value(
settings[0], default, check_env
)
# Cache the result
- return result
- elif len(settings) > 1:
+ if len(settings) > 1:
# This is a higher-level key.
settings_map = {}
for setting in settings:
@@ -763,20 +761,20 @@ class SettingsManager(ISettingsManager):
)
# Override default with database value
- result[str(setting.key)] = dict(
- value=setting.value,
- type=setting_type,
- name=setting.name,
- description=setting.description,
- category=setting.category,
- ui_element=setting.ui_element,
- options=setting.options,
- min_value=setting.min_value,
- max_value=setting.max_value,
- step=setting.step,
- visible=setting.visible,
- editable=False if self.settings_locked else setting.editable,
- )
+ result[str(setting.key)] = {
+ "value": setting.value,
+ "type": setting_type,
+ "name": setting.name,
+ "description": setting.description,
+ "category": setting.category,
+ "ui_element": setting.ui_element,
+ "options": setting.options,
+ "min_value": setting.min_value,
+ "max_value": setting.max_value,
+ "step": setting.step,
+ "visible": setting.visible,
+ "editable": False if self.settings_locked else setting.editable,
+ }
# Override from the environment variables if needed.
env_value = check_env_setting(str(setting.key))
diff --git a/src/local_deep_research/utilities/es_utils.py b/src/local_deep_research/utilities/es_utils.py
index 1f031f6391..60a1d14316 100644
--- a/src/local_deep_research/utilities/es_utils.py
+++ b/src/local_deep_research/utilities/es_utils.py
@@ -436,13 +436,11 @@ class ElasticsearchManager:
}
# Execute the search
- response = self.client.search(
+ return self.client.search(
index=index_name,
body=search_query,
)
- return response
-
except Exception:
logger.exception(f"Error searching index '{index_name}'")
return {"error": "Search failed"}
diff --git a/src/local_deep_research/utilities/json_utils.py b/src/local_deep_research/utilities/json_utils.py
index 573da25dbb..66b6a75a48 100644
--- a/src/local_deep_research/utilities/json_utils.py
+++ b/src/local_deep_research/utilities/json_utils.py
@@ -180,5 +180,4 @@ def _clean_llm_json_artifacts(text: str) -> str:
text = re.sub(
r',\s*"?\.\.\.+"?\s*,', ",", text
) # between items: keep one comma
- text = re.sub(r',?\s*"?\.\.\.+"?\s*', "", text) # trailing/leading ellipsis
- return text
+ return re.sub(r',?\s*"?\.\.\.+"?\s*', "", text) # trailing/leading ellipsis
diff --git a/src/local_deep_research/utilities/llm_utils.py b/src/local_deep_research/utilities/llm_utils.py
index 8cf9dec443..fb7a9a04be 100644
--- a/src/local_deep_research/utilities/llm_utils.py
+++ b/src/local_deep_research/utilities/llm_utils.py
@@ -209,14 +209,19 @@ def get_model(
}
# Add additional kwargs
- for key, value in kwargs.items():
- if key not in [
- "DEFAULT_MODEL",
- "DEFAULT_MODEL_TYPE",
- "DEFAULT_TEMPERATURE",
- "MAX_TOKENS",
- ]:
- common_params[key] = value
+ common_params.update(
+ {
+ key: value
+ for key, value in kwargs.items()
+ if key
+ not in [
+ "DEFAULT_MODEL",
+ "DEFAULT_MODEL_TYPE",
+ "DEFAULT_TEMPERATURE",
+ "MAX_TOKENS",
+ ]
+ }
+ )
# Try to load the model based on type
if model_type == "ollama":
@@ -288,13 +293,12 @@ def get_model(
openai_api_base=endpoint_url,
**common_params,
)
- else:
- return ChatOpenAI( # type: ignore[call-arg]
- model=model_name,
- api_key=api_key,
- openai_api_base=endpoint_url,
- **common_params,
- )
+ return ChatOpenAI( # type: ignore[call-arg]
+ model=model_name,
+ api_key=api_key,
+ openai_api_base=endpoint_url,
+ **common_params,
+ )
except ImportError:
logger.exception("langchain_openai not available")
raise
diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.py
index 997c5b9585..8bf996e4ef 100644
--- a/src/local_deep_research/utilities/log_utils.py
+++ b/src/local_deep_research/utilities/log_utils.py
@@ -222,13 +222,13 @@ def frontend_progress_sink(message: loguru.Message) -> None:
# Can't use logger here as it causes deadlock
return
- frontend_log = dict(
- log_entry=dict(
- message=record["message"],
- type=record["level"].name, # Keep original case
- time=record["time"].isoformat(),
- ),
- )
+ frontend_log = {
+ "log_entry": {
+ "message": record["message"],
+ "type": record["level"].name, # Keep original case
+ "time": record["time"].isoformat(),
+ },
+ }
SocketIOService().emit_to_subscribers(
"progress", research_id, frontend_log, enable_logging=False
)
diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.py
index 2e1577bf7d..659bdfc63f 100644
--- a/src/local_deep_research/utilities/search_cache.py
+++ b/src/local_deep_research/utilities/search_cache.py
@@ -93,9 +93,7 @@ class SearchCache:
normalized = " ".join(query.lower().strip().split())
# Remove common punctuation that doesn't affect search
- normalized = normalized.replace('"', "").replace("'", "")
-
- return normalized
+ return normalized.replace('"', "").replace("'", "")
def _get_query_hash(
self, query: str, search_engine: str = "default"
@@ -168,10 +166,9 @@ class SearchCache:
self._access_times[query_hash] = current_time
logger.debug(f"Cache hit (memory) for query: {query[:50]}...")
return entry["results"]
- else:
- # Expired, remove from memory
- self._memory_cache.pop(query_hash, None)
- self._access_times.pop(query_hash, None)
+ # Expired, remove from memory
+ self._memory_cache.pop(query_hash, None)
+ self._access_times.pop(query_hash, None)
# Check database cache
try:
diff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.py
index 77dcfff067..8f200d7c09 100644
--- a/src/local_deep_research/utilities/search_utilities.py
+++ b/src/local_deep_research/utilities/search_utilities.py
@@ -75,7 +75,6 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:
if url is None:
url = link.get("link")
index = link.get("index", "")
- # logger.info(f"URL \n {str(url)} ")
if url:
if url not in url_to_indices:
url_to_indices[url] = []
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 629f1782dc..1688f37ace 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -595,11 +595,12 @@ def apply_middleware(app):
if request.path.startswith("/socket.io"):
try:
if not request.environ.get("werkzeug.socket"):
- return
+ return None
except Exception:
logger.exception("WebSocket preprocessing error")
# Return empty response to prevent further processing
return "", 200
+ return None
# Note: CORS headers for API routes are now handled by SecurityHeaders middleware
# (see src/local_deep_research/security/security_headers.py)
@@ -878,6 +879,7 @@ def register_blueprints(app):
pass
abort(404)
+ return None
def register_error_handlers(app):
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index 55e18b5c56..ba8982b5dd 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -548,8 +548,7 @@ def check_auth():
"""
if session.get("username"):
return jsonify({"authenticated": True, "username": session["username"]})
- else:
- return jsonify({"authenticated": False}), 401
+ return jsonify({"authenticated": False}), 401
@auth_bp.route("/change-password", methods=["GET"])
@@ -686,12 +685,11 @@ def change_password():
"success",
)
return redirect(url_for("auth.login"))
- else:
- flash("Current password is incorrect", "error")
- return render_template(
- "auth/change_password.html",
- password_requirements=PasswordValidator.get_requirements(),
- ), 401
+ flash("Current password is incorrect", "error")
+ return render_template(
+ "auth/change_password.html",
+ password_requirements=PasswordValidator.get_requirements(),
+ ), 401
@auth_bp.route("/integrity-check", methods=["GET"])
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index b26dc6e5ce..77e601c9f0 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -176,9 +176,8 @@ def get_total_logs_for_research(research_id):
int: Total number of logs for the specified research ID.
"""
with get_user_db_session() as session:
- total_logs = (
+ return (
session.query(ResearchLog)
.filter(ResearchLog.research_id == research_id)
.count()
)
- return total_logs
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.py
index 011e9a06bc..4aee530603 100644
--- a/src/local_deep_research/web/queue/processor_v2.py
+++ b/src/local_deep_research/web/queue/processor_v2.py
@@ -173,11 +173,10 @@ class QueueProcessorV2:
**kwargs,
)
return
- else:
- logger.info(
- f"Direct mode: Max concurrent reached ({active_count}/"
- f"{max_concurrent}), queueing {research_id}"
- )
+ logger.info(
+ f"Direct mode: Max concurrent reached ({active_count}/"
+ f"{max_concurrent}), queueing {research_id}"
+ )
else:
logger.info(
f"User {username} has queue_mode={queue_mode}, "
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index ec472b0d1a..865c3a7c1f 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -141,14 +141,13 @@ def api_terminate_research(research_id):
"result": result,
}
)
- else:
- return jsonify(
- {
- "status": "success",
- "message": "Research not found or already completed",
- "result": result,
- }
- )
+ return jsonify(
+ {
+ "status": "success",
+ "message": "Research not found or already completed",
+ "result": result,
+ }
+ )
except Exception:
logger.exception("Error terminating research")
return (
@@ -268,10 +267,9 @@ def api_delete_resource(research_id, resource_id):
"message": "Resource deleted successfully",
}
)
- else:
- return jsonify(
- {"status": "error", "message": "Resource not found"}
- ), 404
+ return jsonify(
+ {"status": "error", "message": "Resource not found"}
+ ), 404
except Exception:
logger.exception("Error deleting resource")
return jsonify(
@@ -520,26 +518,27 @@ def check_ollama_model():
"all_models": model_names,
}
)
+ # Check if models were found at all
+ if not models:
+ logger.warning("No models found in Ollama")
+ message = (
+ "No models found in Ollama. Please pull models first."
+ )
else:
- # Check if models were found at all
- if not models:
- logger.warning("No models found in Ollama")
- message = "No models found in Ollama. Please pull models first."
- else:
- logger.warning(
- f"Model {model_name} not found among {len(models)} available models"
- )
- # Don't expose available models for security reasons
- message = f"Model {model_name} is not available"
-
- return jsonify(
- {
- "available": False,
- "model": model_name,
- "message": message,
- # Remove all_models to prevent information disclosure
- }
+ logger.warning(
+ f"Model {model_name} not found among {len(models)} available models"
)
+ # Don't expose available models for security reasons
+ message = f"Model {model_name} is not available"
+
+ return jsonify(
+ {
+ "available": False,
+ "model": model_name,
+ "message": message,
+ # Remove all_models to prevent information disclosure
+ }
+ )
except ValueError as json_err:
# JSON parsing error
logger.exception(
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index 7f2b81a4e1..6ebbff223e 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -310,7 +310,7 @@ def get_link_analytics(period="30d", username=None):
others_count = len(resources) - top_10_count
# Get unique research IDs to calculate average
- unique_research_ids = set(r.research_id for r in resources)
+ unique_research_ids = {r.research_id for r in resources}
avg_links = (
len(resources) / len(unique_research_ids)
if unique_research_ids
@@ -438,7 +438,7 @@ def get_link_analytics(period="30d", username=None):
def get_available_strategies():
"""Get list of all available search strategies from the search system."""
# This list comes from the AdvancedSearchSystem.__init__ method
- strategies = [
+ return [
{"name": "standard", "description": "Basic iterative search strategy"},
{
"name": "iterdrag",
@@ -519,7 +519,6 @@ def get_available_strategies():
"description": "Entity-focused search for BrowseComp questions with knowledge graph building",
},
]
- return strategies
def get_strategy_analytics(period="30d", username=None):
@@ -1350,8 +1349,7 @@ def api_get_research_rating(research_id):
"updated_at": rating.updated_at.isoformat(),
}
)
- else:
- return jsonify({"status": "success", "rating": None})
+ return jsonify({"status": "success", "rating": None})
except Exception:
logger.exception("Error getting research rating")
@@ -2149,27 +2147,25 @@ def api_classify_domains():
"classification": classification.to_dict(),
}
)
- else:
- return jsonify(
- {
- "status": "error",
- "message": f"Failed to classify domain: {domain}",
- }
- ), 400
- elif batch_mode:
+ return jsonify(
+ {
+ "status": "error",
+ "message": f"Failed to classify domain: {domain}",
+ }
+ ), 400
+ if batch_mode:
# Batch classification - this should really be a background task
# For now, we'll just return immediately and let the frontend poll
logger.info("Starting batch classification of all domains")
results = classifier.classify_all_domains(force_update)
return jsonify({"status": "success", "results": results})
- else:
- return jsonify(
- {
- "status": "error",
- "message": "Must provide either 'domain' or set 'batch': true",
- }
- ), 400
+ return jsonify(
+ {
+ "status": "error",
+ "message": "Must provide either 'domain' or set 'batch': true",
+ }
+ ), 400
except Exception:
logger.exception("Error classifying domains")
@@ -2202,7 +2198,7 @@ def api_classification_progress():
if domain:
domains.add(domain)
- all_domains = sorted(list(domains))
+ all_domains = sorted(domains)
total_domains = len(domains)
# Count classified domains
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index ec092751f8..7b0308aec0 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -425,10 +425,9 @@ def start_research():
"message": "Your session has expired. Please log out and log back in to start research.",
}
), 401
- else:
- logger.warning(
- f"No password available for metrics access for user {username}"
- )
+ logger.warning(
+ f"No password available for metrics access for user {username}"
+ )
# Create a record in the database with explicit UTC timestamp
import uuid
@@ -513,16 +512,22 @@ def start_research():
logger.error(
"Failed to create temporary session for settings snapshot"
)
- raise Exception(
- "Cannot create research without settings snapshot"
- )
+ return jsonify(
+ {
+ "status": "error",
+ "message": "Cannot create research without settings snapshot.",
+ }
+ ), 500
else:
logger.error(
"No password available to create session for settings snapshot"
)
- raise Exception(
- "Cannot create research without settings snapshot"
- )
+ return jsonify(
+ {
+ "status": "error",
+ "message": "Cannot create research without settings snapshot.",
+ }
+ ), 500
except Exception:
logger.exception("Failed to capture settings snapshot")
# Cannot continue without settings snapshot for thread-based research
@@ -574,64 +579,61 @@ def start_research():
params,
session_id,
)
- else:
- # Start immediately
- # Create active research tracking record
- import threading
-
- active_record = UserActiveResearch(
- username=username,
- research_id=research_id,
- status=ResearchStatus.IN_PROGRESS,
- thread_id=str(threading.current_thread().ident),
- settings_snapshot=research_settings,
+ # Start immediately
+ # Create active research tracking record
+ import threading
+
+ active_record = UserActiveResearch(
+ username=username,
+ research_id=research_id,
+ status=ResearchStatus.IN_PROGRESS,
+ thread_id=str(threading.current_thread().ident),
+ settings_snapshot=research_settings,
+ )
+ db_session.add(active_record)
+ db_session.commit()
+ logger.info(f"Created active research record for user {username}")
+
+ # Double-check the count after committing to handle race conditions
+ # Use the existing session for the recheck
+ try:
+ # Use the same session we already have
+ recheck_session = db_session
+ final_count = (
+ recheck_session.query(UserActiveResearch)
+ .filter_by(
+ username=username, status=ResearchStatus.IN_PROGRESS
+ )
+ .count()
)
- db_session.add(active_record)
- db_session.commit()
logger.info(
- f"Created active research record for user {username}"
+ f"Final active count after commit: {final_count}/{max_concurrent_researches}"
)
- # Double-check the count after committing to handle race conditions
- # Use the existing session for the recheck
- try:
- # Use the same session we already have
- recheck_session = db_session
- final_count = (
- recheck_session.query(UserActiveResearch)
- .filter_by(
- username=username, status=ResearchStatus.IN_PROGRESS
- )
- .count()
+ if final_count > max_concurrent_researches:
+ # We exceeded the limit due to a race condition
+ # Remove this record and queue instead
+ logger.warning(
+ f"Race condition detected: {final_count} > {max_concurrent_researches}, moving to queue"
)
- logger.info(
- f"Final active count after commit: {final_count}/{max_concurrent_researches}"
+ db_session.delete(active_record)
+ db_session.commit()
+
+ session_id = session.get("session_id")
+ return _queue_research(
+ db_session,
+ username,
+ research_id,
+ query,
+ mode,
+ research_settings,
+ params,
+ session_id,
+ reason="due to concurrent limit",
+ research=research,
)
-
- if final_count > max_concurrent_researches:
- # We exceeded the limit due to a race condition
- # Remove this record and queue instead
- logger.warning(
- f"Race condition detected: {final_count} > {max_concurrent_researches}, moving to queue"
- )
- db_session.delete(active_record)
- db_session.commit()
-
- session_id = session.get("session_id")
- return _queue_research(
- db_session,
- username,
- research_id,
- query,
- mode,
- research_settings,
- params,
- session_id,
- reason="due to concurrent limit",
- research=research,
- )
- except Exception:
- logger.warning("Could not recheck active count")
+ except Exception:
+ logger.warning("Could not recheck active count")
except Exception:
logger.exception("Failed to create research entry")
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index ffe6759695..a3d50a0b6e 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -466,8 +466,6 @@ def save_all_settings(db_session=None, settings_manager=None):
# Format the message
if key in original_values:
- # Get original value but comment out if not used
- # old_value = original_values[key]
new_value = updated_setting.value if updated_setting else None
# If it's a boolean, use "enabled/disabled" language
@@ -660,7 +658,6 @@ def api_get_all_settings(db_session=None, settings_manager=None):
# Filter by category if requested
if category:
- filtered_settings = {}
# Need to get all setting details to check category
db_settings = db_session.query(Setting).all()
category_keys = [
@@ -668,11 +665,11 @@ def api_get_all_settings(db_session=None, settings_manager=None):
]
# Filter settings by keys
- for key, value in settings.items():
- if key in category_keys:
- filtered_settings[key] = value
-
- settings = filtered_settings
+ settings = {
+ key: value
+ for key, value in settings.items()
+ if key in category_keys
+ }
return jsonify({"status": "success", "settings": settings})
except Exception:
@@ -809,60 +806,53 @@ def api_update_setting(key, db_session=None):
)
return jsonify(response_data)
- else:
- return jsonify(
- {"error": f"Failed to update setting {key}"}
- ), 500
- else:
- # Create new setting with default metadata
- setting_dict = {
- "key": key,
- "value": value,
- "name": key.split(".")[-1].replace("_", " ").title(),
- "description": f"Setting for {key}",
- }
+ return jsonify({"error": f"Failed to update setting {key}"}), 500
+ # Create new setting with default metadata
+ setting_dict = {
+ "key": key,
+ "value": value,
+ "name": key.split(".")[-1].replace("_", " ").title(),
+ "description": f"Setting for {key}",
+ }
- # Add additional metadata if provided
- for field in [
- "type",
- "name",
- "description",
- "category",
- "ui_element",
- "options",
- "min_value",
- "max_value",
- "step",
- "visible",
- "editable",
- ]:
- if field in data:
- setting_dict[field] = data[field]
-
- # Create setting
- db_setting = create_or_update_setting(
- setting_dict, db_session=db_session
- )
+ # Add additional metadata if provided
+ for field in [
+ "type",
+ "name",
+ "description",
+ "category",
+ "ui_element",
+ "options",
+ "min_value",
+ "max_value",
+ "step",
+ "visible",
+ "editable",
+ ]:
+ if field in data:
+ setting_dict[field] = data[field]
+
+ # Create setting
+ db_setting = create_or_update_setting(
+ setting_dict, db_session=db_session
+ )
- if db_setting:
- return (
- jsonify(
- {
- "message": f"Setting {key} created successfully",
- "setting": {
- "key": db_setting.key,
- "value": db_setting.value,
- "type": db_setting.type.value,
- "name": db_setting.name,
- },
- }
- ),
- 201,
- )
- else:
- return jsonify(
- {"error": f"Failed to create setting {key}"}
- ), 500
+ if db_setting:
+ return (
+ jsonify(
+ {
+ "message": f"Setting {key} created successfully",
+ "setting": {
+ "key": db_setting.key,
+ "value": db_setting.value,
+ "type": db_setting.type.value,
+ "name": db_setting.name,
+ },
+ }
+ ),
+ 201,
+ )
+ return jsonify({"error": f"Failed to create setting {key}"}), 500
except Exception:
logger.exception(f"Error updating setting {key}")
return jsonify({"error": "Failed to update setting"}), 500
@@ -889,8 +879,7 @@ def api_delete_setting(key, db_session=None, settings_manager=None):
success = settings_manager.delete_setting(key)
if success:
return jsonify({"message": f"Setting {key} deleted successfully"})
- else:
- return jsonify({"error": f"Failed to delete setting {key}"}), 500
+ return jsonify({"error": f"Failed to delete setting {key}"}), 500
except Exception:
logger.exception(f"Error deleting setting {key}")
return jsonify({"error": "Failed to delete setting"}), 500
@@ -1150,14 +1139,14 @@ def api_get_available_models():
logger.exception(
f"Failed to parse Ollama API response as JSON: {json_err}"
)
- raise Exception(
+ raise ValueError(
f"Ollama API returned invalid JSON: {json_err}"
)
else:
logger.warning(
f"Ollama API returned non-200 status code: {ollama_response.status_code}"
)
- raise Exception(
+ raise ValueError(
f"Ollama API returned status code {ollama_response.status_code}"
)
@@ -1472,18 +1461,17 @@ def _get_engine_icon_and_category(
# Priority: local > scientific > news > code > books > generic > default
if is_local:
return "📁", "Local RAG"
- elif is_scientific:
+ if is_scientific:
return "🔬", "Scientific"
- elif is_news:
+ if is_news:
return "📰", "News"
- elif is_code:
+ if is_code:
return "💻", "Code"
- elif is_books:
+ if is_books:
return "📚", "Books"
- elif is_generic:
+ if is_generic:
return "🌐", "Web Search"
- else:
- return "🔍", "Search"
+ return "🔍", "Search"
@settings_bp.route("/api/available-search-engines", methods=["GET"])
@@ -1636,8 +1624,7 @@ def api_update_search_favorites(db_session=None, settings_manager=None):
"favorites": favorites,
}
)
- else:
- return jsonify({"error": "Failed to update favorites"}), 500
+ return jsonify({"error": "Failed to update favorites"}), 500
except Exception:
logger.exception("Error updating search favorites")
@@ -1683,8 +1670,7 @@ def api_toggle_search_favorite(db_session=None, settings_manager=None):
"favorites": favorites,
}
)
- else:
- return jsonify({"error": "Failed to toggle favorite"}), 500
+ return jsonify({"error": "Failed to toggle favorite"}), 500
except Exception:
logger.exception("Error toggling search favorite")
@@ -1746,7 +1732,7 @@ def open_file_location():
@settings_bp.context_processor
def inject_csrf_token():
"""Inject CSRF token into the template context for all settings routes."""
- return dict(csrf_token=generate_csrf)
+ return {"csrf_token": generate_csrf}
@settings_bp.route("/fix_corrupted_settings", methods=["POST"])
@@ -1816,10 +1802,6 @@ def fix_corrupted_settings(db_session=None):
if not is_corrupted:
continue
- # Get default value from migrations
- # Import commented out as it's not directly used
- # from ..database.migrations import setup_predefined_settings
-
default_value: Any = None
# Try to find a matching default setting based on key
@@ -2012,13 +1994,12 @@ def check_ollama_status():
"version": response.json().get("version", "unknown"),
}
)
- else:
- return jsonify(
- {
- "running": False,
- "error": f"Ollama returned status code {response.status_code}",
- }
- )
+ return jsonify(
+ {
+ "running": False,
+ "error": f"Ollama returned status code {response.status_code}",
+ }
+ )
except requests.exceptions.RequestException:
logger.exception("Ollama check failed")
return jsonify(
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 8d9a0df998..642a5a2593 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -412,7 +412,7 @@ def run_research_process(research_id, query, mode, **kwargs):
# Frequent termination check
if is_termination_requested(research_id):
handle_termination(research_id, username)
- raise ResearchTerminatedException(
+ raise ResearchTerminatedException( # noqa: TRY301 — inside nested callback, not caught by enclosing try
"Research was terminated by user"
)
@@ -556,7 +556,7 @@ def run_research_process(research_id, query, mode, **kwargs):
def check_termination():
if is_termination_requested(research_id):
handle_termination(research_id, username)
- raise ResearchTerminatedException(
+ raise ResearchTerminatedException( # noqa: TRY301 — inside nested callback, not caught by enclosing try
"Research was terminated by user during long-running operation"
)
return False # Not terminated
@@ -705,7 +705,7 @@ def run_research_process(research_id, query, mode, **kwargs):
error_type = "connection_error"
# Raise with improved error message
- raise Exception(
+ raise RuntimeError(
f"{error_message} (Error type: {error_type})"
) from search_error
@@ -1006,7 +1006,7 @@ def run_research_process(research_id, query, mode, **kwargs):
)
if not success:
- raise Exception("Failed to save research report")
+ raise RuntimeError("Failed to save research report") # noqa: TRY301 — triggers research failure handling in outer except
logger.info(
f"Report saved for research_id: {research_id}"
@@ -1188,11 +1188,11 @@ def run_research_process(research_id, query, mode, **kwargs):
except Exception as inner_e:
logger.exception("Error during quick summary generation")
- raise Exception(
+ raise RuntimeError(
f"Error generating quick summary: {inner_e!s}"
)
else:
- raise Exception(
+ raise RuntimeError( # noqa: TRY301 — triggers research failure handling in outer except
"No research findings were generated. Please try again."
)
else:
@@ -1290,7 +1290,7 @@ def run_research_process(research_id, query, mode, **kwargs):
success = False
if not success:
- raise Exception("Failed to save research report")
+ raise RuntimeError("Failed to save research report") # noqa: TRY301 — triggers research failure handling in outer except
logger.info(
f"Report saved to database for research_id: {research_id}"
@@ -1810,43 +1810,38 @@ def cancel_research(research_id, username):
# Call handle_termination to update database
handle_termination(research_id, username)
return True
- else:
- try:
- with get_user_db_session(username) as db_session:
- research = (
- db_session.query(ResearchHistory)
- .filter_by(id=research_id)
- .first()
- )
- if not research:
- logger.info(
- f"Research {research_id} not found in database"
- )
- return False
-
- # Check if already in a terminal state
- if research.status in (
- ResearchStatus.COMPLETED,
- ResearchStatus.SUSPENDED,
- ResearchStatus.FAILED,
- ResearchStatus.ERROR,
- ):
- logger.info(
- f"Research {research_id} already in terminal state: {research.status}"
- )
- return True # Consider this a success since it's already stopped
-
- # If it exists but isn't in active_research, still update status
- research.status = ResearchStatus.SUSPENDED
- db_session.commit()
+ try:
+ with get_user_db_session(username) as db_session:
+ research = (
+ db_session.query(ResearchHistory)
+ .filter_by(id=research_id)
+ .first()
+ )
+ if not research:
+ logger.info(f"Research {research_id} not found in database")
+ return False
+
+ # Check if already in a terminal state
+ if research.status in (
+ ResearchStatus.COMPLETED,
+ ResearchStatus.SUSPENDED,
+ ResearchStatus.FAILED,
+ ResearchStatus.ERROR,
+ ):
logger.info(
- f"Successfully suspended research {research_id}"
+ f"Research {research_id} already in terminal state: {research.status}"
)
- except Exception:
- logger.exception(
- f"Error accessing database for research {research_id}"
- )
- return False
+ return True # Consider this a success since it's already stopped
+
+ # If it exists but isn't in active_research, still update status
+ research.status = ResearchStatus.SUSPENDED
+ db_session.commit()
+ logger.info(f"Successfully suspended research {research_id}")
+ except Exception:
+ logger.exception(
+ f"Error accessing database for research {research_id}"
+ )
+ return False
return True
except Exception:
diff --git a/src/local_deep_research/web/services/research_sources_service.py b/src/local_deep_research/web/services/research_sources_service.py
index 9c0084b7b9..e9526a3f0d 100644
--- a/src/local_deep_research/web/services/research_sources_service.py
+++ b/src/local_deep_research/web/services/research_sources_service.py
@@ -205,11 +205,10 @@ class ResearchSourcesService:
f"Updated research {research_id} with {saved_count} sources"
)
return True
- else:
- logger.warning(
- f"Research {research_id} not found for source update"
- )
- return False
+ logger.warning(
+ f"Research {research_id} not found for source update"
+ )
+ return False
except Exception:
logger.exception("Error updating research with sources")
diff --git a/src/local_deep_research/web/services/resource_service.py b/src/local_deep_research/web/services/resource_service.py
index 35b0475235..1bbd0751ca 100644
--- a/src/local_deep_research/web/services/resource_service.py
+++ b/src/local_deep_research/web/services/resource_service.py
@@ -114,7 +114,7 @@ def delete_resource(resource_id):
)
if not resource:
- raise ValueError(f"Resource with ID {resource_id} not found")
+ raise ValueError(f"Resource with ID {resource_id} not found") # noqa: TRY301 — re-raised by except ValueError
db_session.delete(resource)
db_session.commit()
diff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.py
index 56c75ad1ea..7482c2277a 100644
--- a/src/local_deep_research/web_search_engines/engines/full_search.py
+++ b/src/local_deep_research/web_search_engines/engines/full_search.py
@@ -81,10 +81,7 @@ class FullSearchResults:
if not html or not html.strip():
return ""
paragraphs = justext.justext(html, justext.get_stoplist(self.language))
- cleaned = "\n".join(
- [p.text for p in paragraphs if not p.is_boilerplate]
- )
- return cleaned
+ return "\n".join([p.text for p in paragraphs if not p.is_boilerplate])
def run(self, query: str):
nr_full_text = 0
diff --git a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
index d30b7e517a..1714dd27e6 100644
--- a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
+++ b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
@@ -285,16 +285,13 @@ Example output: searxng,wikipedia,brave"""
),
reverse=True,
)
- else:
- return sorted(
- self.available_engines,
- key=lambda x: (
- self._get_search_config()
- .get(x, {})
- .get("reliability", 0)
- ),
- reverse=True,
- )
+ return sorted(
+ self.available_engines,
+ key=lambda x: (
+ self._get_search_config().get(x, {}).get("reliability", 0)
+ ),
+ reverse=True,
+ )
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
"""
diff --git a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
index 38f0f78228..c73cae23ea 100644
--- a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
+++ b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
@@ -218,7 +218,7 @@ class ParallelSearchEngine(BaseSearchEngine):
if not engine_class.is_public and not self.allow_local_engines:
logger.debug(f"Skipping local/private engine: {name}")
continue
- elif not engine_class.is_public and self.allow_local_engines:
+ if not engine_class.is_public and self.allow_local_engines:
logger.warning(
f"Including local/private engine {name} - data may be exposed"
)
@@ -475,13 +475,12 @@ Select up to {self.max_engines_to_select} engines that would best answer this qu
"results": results,
"count": len(results),
}
- else:
- return {
- "engine": engine_name,
- "success": False,
- "error": "No results",
- "results": [],
- }
+ return {
+ "engine": engine_name,
+ "success": False,
+ "error": "No results",
+ "results": [],
+ }
except Exception:
logger.exception(f"Error executing {engine_name}")
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
index 79a09c01dd..6206aa3af7 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
@@ -123,9 +123,7 @@ class ArXivSearchEngine(BaseSearchEngine):
)
# Get the search results
- papers = list(client.results(search))
-
- return papers
+ return list(client.results(search))
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
"""
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
index 3e4082f028..874f8afb7c 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
@@ -106,11 +106,11 @@ class DuckDuckGoSearchEngine(BaseSearchEngine):
# Check for known rate limit patterns
if "202 Ratelimit" in error_msg or "ratelimit" in error_msg.lower():
raise RateLimitError(f"DuckDuckGo rate limit hit: {sanitized}")
- elif "403" in error_msg or "forbidden" in error_msg.lower():
+ if "403" in error_msg or "forbidden" in error_msg.lower():
raise RateLimitError(
f"DuckDuckGo access forbidden (possible rate limit): {sanitized}"
)
- elif (
+ if (
"timeout" in error_msg.lower()
or "timed out" in error_msg.lower()
):
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_github.py b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
index d294cd3608..92900ec164 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_github.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
@@ -159,9 +159,8 @@ class GitHubSearchEngine(BaseSearchEngine):
f"LLM optimized query from '{query}' to '{optimized_query}'"
)
return optimized_query
- else:
- logger.warning("LLM returned empty query, using original")
- return query
+ logger.warning("LLM returned empty query, using original")
+ return query
except Exception:
logger.exception("Error optimizing query with LLM")
@@ -295,11 +294,10 @@ class GitHubSearchEngine(BaseSearchEngine):
"utf-8", errors="replace"
)
return content
- else:
- logger.warning(
- f"Could not get README for {repo_full_name}: {response.status_code}"
- )
- return ""
+ logger.warning(
+ f"Could not get README for {repo_full_name}: {response.status_code}"
+ )
+ return ""
except Exception:
logger.exception(f"Error getting README for {repo_full_name}")
@@ -388,11 +386,10 @@ class GitHubSearchEngine(BaseSearchEngine):
"utf-8", errors="replace"
)
return content2
- else:
- logger.warning(
- f"Could not get file content: {response.status_code}"
- )
- return ""
+ logger.warning(
+ f"Could not get file content: {response.status_code}"
+ )
+ return ""
except Exception:
logger.exception("Error getting file content")
@@ -721,11 +718,10 @@ class GitHubSearchEngine(BaseSearchEngine):
result["recent_issues"] = issues
return result
- else:
- logger.error(
- f"Error getting repository details: {response.status_code} - {response.text}"
- )
- return {}
+ logger.error(
+ f"Error getting repository details: {response.status_code} - {response.text}"
+ )
+ return {}
except Exception:
logger.exception("Error getting repository details")
@@ -832,17 +828,15 @@ class GitHubSearchEngine(BaseSearchEngine):
results = data.get("items", [])
# Format results
- previews = [
+ return [
self._format_issue_preview(result) for result in results
]
# For issues, we don't need to get full content
- return previews
- else:
- logger.error(
- f"GitHub API error: {response.status_code} - {response.text}"
- )
- return []
+ logger.error(
+ f"GitHub API error: {response.status_code} - {response.text}"
+ )
+ return []
finally:
# Restore original search type
@@ -921,11 +915,10 @@ Do not include any other text or explanation."""
return ranked_results[: self.max_filtered_results]
return ranked_results
- else:
- logger.info(
- "Could not find JSON array in response, returning no previews"
- )
- return []
+ logger.info(
+ "Could not find JSON array in response, returning no previews"
+ )
+ return []
except Exception:
logger.exception("Error filtering GitHub results")
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
index 055a043193..8f0bf28a62 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
@@ -156,7 +156,7 @@ class GooglePSESearchEngine(BaseSearchEngine):
# Check if we got a valid response
if response.get("error"):
error_msg = response["error"].get("message", "Unknown error")
- raise ValueError(f"Google PSE API error: {error_msg}")
+ raise ValueError(f"Google PSE API error: {error_msg}") # noqa: TRY301 — except only adds logging before re-raise
# If we get here, the connection is valid
logger.info("Google PSE connection validated successfully")
@@ -303,8 +303,7 @@ class GooglePSESearchEngine(BaseSearchEngine):
raise RequestException(
f"{error_msg}: {self._sanitize_error_message(str(last_exception))}"
)
- else:
- raise RequestException(error_msg)
+ raise RequestException(error_msg)
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
"""Get search result previews/snippets"""
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py b/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py
index 0001c30870..153b16aeb3 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py
@@ -131,7 +131,7 @@ class MojeekSearchEngine(BaseSearchEngine):
)
if response.status_code == 403:
- raise RateLimitError(
+ raise RateLimitError( # noqa: TRY301 — re-raised by except RateLimitError for base class retry
"Mojeek API rate limit hit (403 Forbidden)"
)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
index 8cf1349449..7acd6bdbc3 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
@@ -225,20 +225,19 @@ class NasaAdsSearchEngine(BaseSearchEngine):
logger.info(f"Successfully formatted {len(previews)} previews")
return previews
- elif response.status_code == 429:
+ if response.status_code == 429:
# Rate limited
logger.warning("NASA ADS rate limit reached")
- raise RateLimitError("NASA ADS rate limit exceeded")
+ raise RateLimitError("NASA ADS rate limit exceeded") # noqa: TRY301 — re-raised by except RateLimitError for base class retry
- elif response.status_code == 401:
+ if response.status_code == 401:
logger.error("NASA ADS API key is invalid or missing")
return []
- else:
- logger.error(
- f"NASA ADS API error: {response.status_code} - {response.text[:200]}"
- )
- return []
+ logger.error(
+ f"NASA ADS API error: {response.status_code} - {response.text[:200]}"
+ )
+ return []
except RateLimitError:
# Re-raise rate limit errors for base class retry handling
@@ -315,7 +314,7 @@ class NasaAdsSearchEngine(BaseSearchEngine):
# Get keywords
keywords = doc.get("keyword", [])
- preview = {
+ return {
"id": bibcode,
"title": title,
"link": url,
@@ -331,8 +330,6 @@ class NasaAdsSearchEngine(BaseSearchEngine):
"type": "academic_paper",
}
- return preview
-
except Exception:
logger.exception(
f"Error formatting NASA ADS document: {doc.get('bibcode', 'unknown')}"
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
index f31fc27740..d87d2c6256 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
@@ -234,16 +234,15 @@ class OpenAlexSearchEngine(BaseSearchEngine):
)
return previews
- elif response.status_code == 429:
+ if response.status_code == 429:
# Rate limited (very rare with OpenAlex)
logger.warning("OpenAlex rate limit reached")
- raise RateLimitError("OpenAlex rate limit exceeded")
+ raise RateLimitError("OpenAlex rate limit exceeded") # noqa: TRY301 — re-raised by except RateLimitError for base class retry
- else:
- logger.error(
- f"OpenAlex API error: {response.status_code} - {response.text[:200]}"
- )
- return []
+ logger.error(
+ f"OpenAlex API error: {response.status_code} - {response.text[:200]}"
+ )
+ return []
except RateLimitError:
# Re-raise rate limit errors for base class retry handling
@@ -346,7 +345,7 @@ class OpenAlexSearchEngine(BaseSearchEngine):
"landing_page_url"
)
- preview = {
+ return {
"id": work_id,
"title": title,
"link": url,
@@ -362,8 +361,6 @@ class OpenAlexSearchEngine(BaseSearchEngine):
"type": "academic_paper",
}
- return preview
-
except Exception:
logger.exception(
f"Error formatting OpenAlex work: {work.get('id', 'unknown')}"
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py b/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py
index 044cc35164..65e02ec76a 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py
@@ -617,9 +617,8 @@ IMPORTANT: Output ONLY the search query. No explanations, no additional text."""
f"Created {len(previews)} separate previews from highlights for doc {doc_id}"
)
return previews
- else:
- # Single preview (original behavior)
- return preview
+ # Single preview (original behavior)
+ return preview
def _get_full_content(
self, relevant_items: List[Dict[str, Any]]
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.py
index 6967cfaf16..c53dc47869 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.py
@@ -77,8 +77,10 @@ class PubChemSearchEngine(BaseSearchEngine):
response.raise_for_status()
data = response.json()
- terms = data.get("dictionary_terms", {}).get("compound", [])
- return terms # type: ignore[no-any-return]
+ terms: list[str] = data.get("dictionary_terms", {}).get(
+ "compound", []
+ )
+ return terms
except RateLimitError:
raise
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
index aa1f5935e3..b326cbb778 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
@@ -202,17 +202,15 @@ class PubMedSearchEngine(BaseSearchEngine):
if unit == "months" or unit == "month":
if amount < 6:
return '"last 6 months"[pdat]'
- elif amount < 12:
+ if amount < 12:
return '"last 1 year"[pdat]'
- else:
- return '"last 2 years"[pdat]'
- elif unit == "years" or unit == "year":
+ return '"last 2 years"[pdat]'
+ if unit == "years" or unit == "year":
if amount < 2:
return '"last 2 years"[pdat]'
- elif amount < 5:
+ if amount < 5:
return '"last 5 years"[pdat]'
- else:
- return '"last 10 years"[pdat]'
+ return '"last 10 years"[pdat]'
return '"last 10 years"[pdat]'
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py b/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py
index b7f7a5b3e5..fc17fb432f 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py
@@ -94,7 +94,7 @@ class RetrieverSearchEngine(BaseSearchEngine):
metadata = doc.metadata or {}
# Build the result
- result = {
+ return {
# Required fields for LDR
"title": metadata.get("title", f"Document {index + 1}"),
"url": metadata.get(
@@ -117,8 +117,6 @@ class RetrieverSearchEngine(BaseSearchEngine):
"retriever_type": self.retriever.__class__.__name__,
}
- return result
-
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
"""
Get preview information from the retriever.
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
index f6b0a8a7e1..204264de68 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
@@ -496,10 +496,7 @@ class SearXNGSearchEngine(BaseSearchEngine):
logger.info("Retrieving full webpage content")
try:
- results_with_content = self.full_search._get_full_content(
- relevant_items
- )
- return results_with_content
+ return self.full_search._get_full_content(relevant_items)
except Exception:
logger.exception("Error retrieving full content")
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
index df07af3616..e1ac84b87b 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
@@ -356,11 +356,10 @@ Return ONLY the optimized search query with no explanation.
f"Found {len(papers)} papers with direct search for query: '{query}'"
)
return papers # type: ignore[no-any-return]
- else:
- logger.warning(
- f"No data in response for direct search query: '{query}'"
- )
- return []
+ logger.warning(
+ f"No data in response for direct search query: '{query}'"
+ )
+ return []
except Exception:
logger.exception("Error in direct search")
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
index 191bc5c87e..4fa1854582 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
@@ -113,7 +113,7 @@ class WaybackSearchEngine(BaseSearchEngine):
if "/" in query and "." in query:
logger.info(f"Treating query as a partial URL: {query}")
return [f"http://{query}"]
- elif "." in query:
+ if "." in query:
logger.info(f"Treating query as a domain: {query}")
return [f"http://{query}"]
@@ -157,7 +157,7 @@ class WaybackSearchEngine(BaseSearchEngine):
# Check for rate limit
if response.status_code == 429:
- raise RateLimitError("Wayback Machine rate limit exceeded")
+ raise RateLimitError("Wayback Machine rate limit exceeded") # noqa: TRY301 — re-raised by except RateLimitError for base class retry
data = response.json()
@@ -194,7 +194,7 @@ class WaybackSearchEngine(BaseSearchEngine):
# Check for rate limit
if response.status_code == 429:
- raise RateLimitError(
+ raise RateLimitError( # noqa: TRY301 — re-raised by except RateLimitError for base class retry
"Wayback Machine CDX API rate limit exceeded"
)
@@ -298,10 +298,9 @@ class WaybackSearchEngine(BaseSearchEngine):
paragraphs = justext.justext(
html, justext.get_stoplist(self.language)
)
- cleaned = "\n".join(
+ return "\n".join(
[p.text for p in paragraphs if not p.is_boilerplate]
)
- return cleaned
except Exception:
logger.exception("Error removing boilerplate")
return html
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py
index 0242a0e987..63ebb063ef 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py
@@ -163,12 +163,12 @@ NOW RETURN ONLY THE JSON OBJECT.
data = extract_json(response_text, expected_type=dict)
if data is None or not isinstance(data, dict):
- raise ValueError("No valid JSON found in response")
+ raise ValueError("No valid JSON found in response") # noqa: TRY301 — caught by except ValueError to fall back to original query
optimized_query: str = str(data.get("query", "")).strip()
if not optimized_query:
- raise ValueError("Query field missing or empty")
+ raise ValueError("Query field missing or empty") # noqa: TRY301 — caught by except ValueError to fall back to original query
except (
ValueError,
@@ -514,6 +514,4 @@ def _clean_wikinews_snippet(snippet: str) -> str:
clean_text = re.sub(r"<.*?>", "", unescaped)
# Normalize whitespace
- clean_text = re.sub(r"\s+", " ", clean_text).strip()
-
- return clean_text
+ return re.sub(r"\s+", " ", clean_text).strip()
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
index bc62bf3255..4db5ca1351 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
@@ -138,8 +138,7 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
# Clean model name
model = model.replace("/", "-").replace(":", "-")
- key = f"{provider}-{url}-{model}"
- return key
+ return f"{provider}-{url}-{model}"
def invoke(self, *args, **kwargs):
"""Invoke the LLM with rate limiting if enabled."""
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index b1edea5689..d06e20b747 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
@@ -758,14 +758,13 @@ class AdaptiveRateLimitTracker:
"""Get quality status string based on average results."""
if recent_avg < 1:
return "CRITICAL"
- elif recent_avg < 3:
+ if recent_avg < 3:
return "WARNING"
- elif recent_avg < 5:
+ if recent_avg < 5:
return "CAUTION"
- elif recent_avg >= 10:
+ if recent_avg >= 10:
return "EXCELLENT"
- else:
- return "GOOD"
+ return "GOOD"
def cleanup_old_data(self, days: int = 30) -> None:
"""
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 61d63dc833..c6c1fe8da2 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -20,8 +20,6 @@ from ..config.thread_settings import get_setting_from_snapshot
from ..utilities.json_utils import extract_json, get_llm_response_text
from ..utilities.thread_context import clear_search_context, set_search_context
-# Lazy import for metrics to avoid database dependencies in programmatic mode
-# from ..metrics.search_tracker import get_search_tracker
from .rate_limiting import RateLimitError, get_tracker
@@ -459,15 +457,14 @@ class BaseSearchEngine(ABC):
# Only re-raise if rate limiting is enabled
if self.rate_tracker.enabled:
raise
- else:
- # If rate limiting is disabled, treat as regular error
- success = False
- error_message = "Rate limit hit but rate limiting disabled"
- logger.warning(
- f"Rate limit hit on {self.__class__.__name__} but rate limiting is disabled"
- )
- results_count = 0
- return []
+ # If rate limiting is disabled, treat as regular error
+ success = False
+ error_message = "Rate limit hit but rate limiting disabled"
+ logger.warning(
+ f"Rate limit hit on {self.__class__.__name__} but rate limiting is disabled"
+ )
+ results_count = 0
+ return []
except Exception as e:
# Other errors - don't retry
success = False
@@ -665,14 +662,11 @@ Respond with ONLY the JSON array, no other text."""
return ranked_results[: self.max_filtered_results]
return ranked_results
- else:
- logger.warning(
- "Could not find JSON array in response, returning original previews"
- )
- logger.debug(
- f"Response text without JSON array: {response_text}"
- )
- return previews[: min(5, len(previews))]
+ logger.warning(
+ "Could not find JSON array in response, returning original previews"
+ )
+ logger.debug(f"Response text without JSON array: {response_text}")
+ return previews[: min(5, len(previews))]
except Exception:
logger.exception("Relevance filtering error")
diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.py
index a82e65c372..4c7e60dd8c 100644
--- a/src/local_deep_research/web_search_engines/search_engine_factory.py
+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py
@@ -46,7 +46,7 @@ def create_search_engine(
settings_snapshot=settings_snapshot,
**kwargs,
)
- elif engine_name == "parallel":
+ if engine_name == "parallel":
logger.info("Creating standard parallel search engine")
from .engines.parallel_search_engine import ParallelSearchEngine
@@ -469,9 +469,8 @@ def _create_full_search_wrapper(
)
# Create the full search wrapper with filtered parameters
- full_search = full_search_class(**wrapper_params)
-
- return full_search # type: ignore[no-any-return]
+ service: BaseSearchEngine = full_search_class(**wrapper_params)
+ return service
except Exception:
logger.exception(
diff --git a/tests/advanced_search_system/knowledge/test_followup_context_manager.py b/tests/advanced_search_system/knowledge/test_followup_context_manager.py
index e5f638673e..9e4ff53174 100644
--- a/tests/advanced_search_system/knowledge/test_followup_context_manager.py
+++ b/tests/advanced_search_system/knowledge/test_followup_context_manager.py
@@ -634,9 +634,9 @@ class TestIntegration:
def invoke_side_effect(prompt):
if "entities" in prompt.lower():
return Mock(content="Python\nMachine Learning\nAI")
- elif "summary" in prompt.lower() or "summarize" in prompt.lower():
+ if "summary" in prompt.lower() or "summarize" in prompt.lower():
return Mock(content="A concise summary of the research.")
- elif "gaps" in prompt.lower():
+ if "gaps" in prompt.lower():
return Mock(content="Gap 1\nGap 2")
return Mock(content="Default response")
diff --git a/tests/api_tests/run_api_tests.py b/tests/api_tests/run_api_tests.py
index 9d76d2f91e..d40ed0da69 100644
--- a/tests/api_tests/run_api_tests.py
+++ b/tests/api_tests/run_api_tests.py
@@ -35,8 +35,7 @@ def main():
"""Main entry point."""
if len(sys.argv) > 1 and sys.argv[1] == "search":
return run_search_engines_test()
- else:
- return run_all_tests()
+ return run_all_tests()
if __name__ == "__main__":
diff --git a/tests/api_tests/test_api_basic.py b/tests/api_tests/test_api_basic.py
index 002d8ebf4a..952599e30a 100644
--- a/tests/api_tests/test_api_basic.py
+++ b/tests/api_tests/test_api_basic.py
@@ -83,7 +83,7 @@ class TestBasicAPI:
try:
error_data = json.loads(response.data)
print(f"[DEBUG] Error response JSON: {error_data}")
- except:
+ except Exception:
print(f"[DEBUG] Raw error response: {response.data.decode()}")
# The API should accept the request format
diff --git a/tests/api_tests/test_research_api_debug.py b/tests/api_tests/test_research_api_debug.py
index 0db848c820..d36b5ca9a0 100644
--- a/tests/api_tests/test_research_api_debug.py
+++ b/tests/api_tests/test_research_api_debug.py
@@ -68,9 +68,8 @@ class ResearchAPIDebugTest:
if response.status_code == 200:
print(" ✅ Server is running")
return True
- else:
- print(f" ❌ Server returned status {response.status_code}")
- return False
+ print(f" ❌ Server returned status {response.status_code}")
+ return False
except requests.exceptions.ConnectionError:
print(" ❌ Cannot connect to server")
return False
@@ -124,11 +123,8 @@ class ResearchAPIDebugTest:
if register_response.status_code in [200, 302]:
print(" ✅ Registration successful")
return True
- else:
- print(
- f" ❌ Registration failed: {register_response.text[:200]}"
- )
- return False
+ print(f" ❌ Registration failed: {register_response.text[:200]}")
+ return False
except Exception as e:
print(f" ❌ Registration error: {e}")
@@ -176,9 +172,8 @@ class ResearchAPIDebugTest:
if login_response.status_code in [200, 302]:
print(" ✅ Login successful")
return True
- else:
- print(f" ❌ Login failed: {login_response.text[:200]}")
- return False
+ print(f" ❌ Login failed: {login_response.text[:200]}")
+ return False
except Exception as e:
print(f" ❌ Authentication error: {e}")
diff --git a/tests/api_tests/test_research_creation.py b/tests/api_tests/test_research_creation.py
index 0f61b7b7ab..c2ee6d1504 100644
--- a/tests/api_tests/test_research_creation.py
+++ b/tests/api_tests/test_research_creation.py
@@ -39,11 +39,10 @@ class TestResearchCreation:
assert "research_id" in data
print(f"\n✅ SUCCESS! Research ID: {data.get('research_id')}")
return data["research_id"]
- else:
- # Alternative response format
- assert "research_id" in data
- print(f"\n✅ SUCCESS! Research ID: {data['research_id']}")
- return data["research_id"]
+ # Alternative response format
+ assert "research_id" in data
+ print(f"\n✅ SUCCESS! Research ID: {data['research_id']}")
+ return data["research_id"]
def test_research_creation_with_minimal_params(self, authenticated_client):
"""Test research creation with minimal parameters."""
diff --git a/tests/api_tests_with_login/pytest_tests/test_research_completion.py b/tests/api_tests_with_login/pytest_tests/test_research_completion.py
index 1dffeca559..01636701d0 100644
--- a/tests/api_tests_with_login/pytest_tests/test_research_completion.py
+++ b/tests/api_tests_with_login/pytest_tests/test_research_completion.py
@@ -44,7 +44,7 @@ def test_research_completion_time(auth_session, base_url):
if status == "completed":
completed = True
break
- elif status == "failed":
+ if status == "failed":
# Get logs to understand failure
logs_response = session.get(
f"{base_url}/api/research/{research_id}/logs"
diff --git a/tests/api_tests_with_login/pytest_tests/test_research_results.py b/tests/api_tests_with_login/pytest_tests/test_research_results.py
index e0474bd81f..84d4508787 100644
--- a/tests/api_tests_with_login/pytest_tests/test_research_results.py
+++ b/tests/api_tests_with_login/pytest_tests/test_research_results.py
@@ -38,7 +38,7 @@ def test_research_produces_valid_report(auth_session, base_url):
status = status_response.json().get("status")
if status == "completed":
break
- elif status == "failed":
+ if status == "failed":
pytest.fail("Research failed")
time.sleep(2)
diff --git a/tests/api_tests_with_login/test_research_api_pytest.py b/tests/api_tests_with_login/test_research_api_pytest.py
index ab4ff118d4..b4a21f3bca 100644
--- a/tests/api_tests_with_login/test_research_api_pytest.py
+++ b/tests/api_tests_with_login/test_research_api_pytest.py
@@ -255,7 +255,7 @@ class TestResearchAPI:
if status == "completed":
completed = True
break
- elif status == "failed":
+ if status == "failed":
# Get logs to understand failure
logs_response = session.get(
f"{BASE_URL}/api/research/{research_id}/logs"
diff --git a/tests/benchmarks/test_benchmark_service.py b/tests/benchmarks/test_benchmark_service.py
index a6c2acb2c4..ad3368ff05 100644
--- a/tests/benchmarks/test_benchmark_service.py
+++ b/tests/benchmarks/test_benchmark_service.py
@@ -1281,12 +1281,11 @@ class TestBenchmarkServiceGetExistingResults:
mock_run
]
return mock_q
- else:
- mock_q = Mock()
- mock_q.filter.return_value.filter.return_value.all.return_value = [
- mock_result
- ]
- return mock_q
+ mock_q = Mock()
+ mock_q.filter.return_value.filter.return_value.all.return_value = [
+ mock_result
+ ]
+ return mock_q
mock_session.query.side_effect = query_side_effect
diff --git a/tests/citation_bugs/test_citation_error_handling.py b/tests/citation_bugs/test_citation_error_handling.py
index 12456b785b..83654b0a01 100644
--- a/tests/citation_bugs/test_citation_error_handling.py
+++ b/tests/citation_bugs/test_citation_error_handling.py
@@ -74,7 +74,6 @@ URL: https://example.com/2"""
assert "[1.5]" in result
# Citation with spaces might be processed
- # body = result.split("## Sources")[0]
# [ 2 ] with spaces is an edge case - formatter might or might not handle it
def test_circular_and_self_referencing(self):
diff --git a/tests/database/test_cache_models.py b/tests/database/test_cache_models.py
index b4d6f0692f..0324a72316 100644
--- a/tests/database/test_cache_models.py
+++ b/tests/database/test_cache_models.py
@@ -319,11 +319,6 @@ class TestCacheModels:
session.commit()
- # Count expired entries
- # expired_count = (
- # session.query(Cache).filter(Cache.expires_at < now).count()
- # )
-
# Delete expired entries
session.query(Cache).filter(Cache.expires_at < now).delete()
session.commit()
diff --git a/tests/embeddings/test_sentence_transformers.py b/tests/embeddings/test_sentence_transformers.py
index e98dc977f4..7620b7121f 100644
--- a/tests/embeddings/test_sentence_transformers.py
+++ b/tests/embeddings/test_sentence_transformers.py
@@ -227,7 +227,7 @@ class TestSentenceTransformersProviderCreateEmbeddings:
def mock_get_setting(key, default=None, settings_snapshot=None):
if key == "embeddings.sentence_transformers.model":
return "custom-model"
- elif key == "embeddings.sentence_transformers.device":
+ if key == "embeddings.sentence_transformers.device":
return "cpu"
return default
diff --git a/tests/feature_tests/test_custom_context.py b/tests/feature_tests/test_custom_context.py
index ee0b9c57c0..a740d4b717 100644
--- a/tests/feature_tests/test_custom_context.py
+++ b/tests/feature_tests/test_custom_context.py
@@ -97,10 +97,6 @@ def modify_llm_creation(
f"Provider {provider} would particularly benefit from custom context size"
)
- # This would actually create the LLM with adjusted max_tokens in the real implementation
- # from local_deep_research.config.llm_config import get_llm
- # llm = get_llm(provider=provider, model_name=model_name)
-
return {
"provider": provider,
"model_name": model_name,
diff --git a/tests/fixtures/search_engine_mocks.py b/tests/fixtures/search_engine_mocks.py
index a33be89008..df72cff125 100644
--- a/tests/fixtures/search_engine_mocks.py
+++ b/tests/fixtures/search_engine_mocks.py
@@ -244,8 +244,7 @@ def mock_error_api_response(mocker):
mock_response.text = error_data.get("error", "Error")
mock_response.json.return_value = error_data
return mock_response
- else:
- # Network-level error
- raise ConnectionError(error_data.get("error", "Unknown error"))
+ # Network-level error
+ raise ConnectionError(error_data.get("error", "Unknown error"))
return _create_error
diff --git a/tests/health_check/run_quick_health_check.py b/tests/health_check/run_quick_health_check.py
index 955e15c3f8..dc213f6d4a 100755
--- a/tests/health_check/run_quick_health_check.py
+++ b/tests/health_check/run_quick_health_check.py
@@ -61,9 +61,8 @@ def run_health_check():
print("🐚 Running shell health check...")
result = subprocess.run([shell_script], capture_output=False, text=True)
return result.returncode == 0
- else:
- print("❌ No health check scripts found")
- return False
+ print("❌ No health check scripts found")
+ return False
def main():
diff --git a/tests/langchain_integration/test_combined_llm_retriever.py b/tests/langchain_integration/test_combined_llm_retriever.py
index 4eed81f681..4b242a9e20 100644
--- a/tests/langchain_integration/test_combined_llm_retriever.py
+++ b/tests/langchain_integration/test_combined_llm_retriever.py
@@ -60,7 +60,7 @@ class CompanyKnowledgeRetriever(BaseRetriever):
},
),
]
- elif self.knowledge_domain == "product":
+ if self.knowledge_domain == "product":
return [
Document(
page_content="Product roadmap focuses on AI-driven features and user experience.",
@@ -79,13 +79,12 @@ class CompanyKnowledgeRetriever(BaseRetriever):
},
),
]
- else:
- return [
- Document(
- page_content="Company mission is to democratize AI technology.",
- metadata={"source": "company_docs", "type": "mission"},
- ),
- ]
+ return [
+ Document(
+ page_content="Company mission is to democratize AI technology.",
+ metadata={"source": "company_docs", "type": "mission"},
+ ),
+ ]
def _get_relevant_documents(self, query: str, **kwargs) -> List[Document]:
"""Get relevant documents based on query."""
@@ -153,14 +152,13 @@ class CompanyCustomLLM(BaseChatModel):
if "engineering" in prompt_lower or "technical" in prompt_lower:
return "Our engineering practices emphasize scalability, security, and maintainability. We follow industry best practices with a focus on microservices architecture and continuous integration."
- elif "product" in prompt_lower or "roadmap" in prompt_lower:
+ if "product" in prompt_lower or "roadmap" in prompt_lower:
return "The product strategy centers on AI-driven features that enhance user productivity. Key focus areas include seamless integrations and intuitive user interfaces."
- elif "security" in prompt_lower:
+ if "security" in prompt_lower:
return "Security is paramount in our systems. We implement defense-in-depth strategies, regular security audits, and automated vulnerability scanning."
- elif "question" in prompt_lower and "generate" in prompt_lower:
+ if "question" in prompt_lower and "generate" in prompt_lower:
return "1. What are the key architectural decisions?\n2. How do we ensure security compliance?\n3. What are the integration requirements?"
- else:
- return f"Our comprehensive approach addresses the query about {prompt[:50]}... with focus on quality and innovation."
+ return f"Our comprehensive approach addresses the query about {prompt[:50]}... with focus on quality and innovation."
@pytest.mark.skipif(
@@ -351,17 +349,16 @@ class TestCombinedLLMRetriever:
if self.call_count == 1:
# Fail on first call
raise RuntimeError("Temporary retriever failure")
- else:
- # Success on retry
- return [
- Document(
- page_content="Fallback content about the query",
- metadata={
- "source": "fallback",
- "retry": self.call_count,
- },
- )
- ]
+ # Success on retry
+ return [
+ Document(
+ page_content="Fallback content about the query",
+ metadata={
+ "source": "fallback",
+ "retry": self.call_count,
+ },
+ )
+ ]
async def _aget_relevant_documents(
self, query: str, **kwargs
diff --git a/tests/mcp/test_concurrent_mcp_calls.py b/tests/mcp/test_concurrent_mcp_calls.py
index ecd21d51d8..097ab0bc47 100644
--- a/tests/mcp/test_concurrent_mcp_calls.py
+++ b/tests/mcp/test_concurrent_mcp_calls.py
@@ -142,7 +142,7 @@ class TestConcurrentToolCallsWithMocks:
return mock_tool_result(
f'{{"message": "{args.get("message", "")}"}}'
)
- elif name == "add":
+ if name == "add":
result = args.get("a", 0) + args.get("b", 0)
return mock_tool_result(f'{{"result": {result}}}')
return mock_tool_result('{"status": "unknown"}')
diff --git a/tests/mcp/test_edge_cases.py b/tests/mcp/test_edge_cases.py
index cb35ec0db2..84596679e5 100644
--- a/tests/mcp/test_edge_cases.py
+++ b/tests/mcp/test_edge_cases.py
@@ -164,7 +164,9 @@ class TestParameterEdgeCases:
)
assert result["status"] == "error"
- assert "nonexistent_engine" in result["error"]
+ assert result[
+ "error"
+ ] # Error message is present (sanitized, may not contain engine name)
def test_invalid_strategy_name(self):
"""Test behavior with invalid strategy name."""
diff --git a/tests/news/recommender/test_topic_based_recommender.py b/tests/news/recommender/test_topic_based_recommender.py
index 1e7af71542..c3a99859b5 100644
--- a/tests/news/recommender/test_topic_based_recommender.py
+++ b/tests/news/recommender/test_topic_based_recommender.py
@@ -499,7 +499,7 @@ class TestGenerateRecommendations:
def mock_create_card(topic, query, user_id):
create_card_calls.append(topic)
- return None # Return None to avoid further processing
+ return # Return None to avoid further processing
recommender._create_recommendation_card = mock_create_card
@@ -567,7 +567,7 @@ class TestGenerateRecommendations:
def mock_create_card(topic, query, user_id):
topics_processed.append(topic)
- return None
+ return
recommender = TopicBasedRecommender(
preference_manager=mock_pref_manager, topic_registry=mock_registry
diff --git a/tests/news/test_api_client_patterns_behavior.py b/tests/news/test_api_client_patterns_behavior.py
index d8ee4a759e..48cb00a5e8 100644
--- a/tests/news/test_api_client_patterns_behavior.py
+++ b/tests/news/test_api_client_patterns_behavior.py
@@ -364,7 +364,7 @@ class TestAuthentication:
def api_key_auth(api_key, location="header", param_name="X-API-Key"):
if location == "header":
return {"headers": {param_name: api_key}}
- elif location == "query":
+ if location == "query":
return {"params": {param_name: api_key}}
return {}
diff --git a/tests/news/test_card_interaction_patterns_behavior.py b/tests/news/test_card_interaction_patterns_behavior.py
index 844e1ef797..01df87aabf 100644
--- a/tests/news/test_card_interaction_patterns_behavior.py
+++ b/tests/news/test_card_interaction_patterns_behavior.py
@@ -112,9 +112,8 @@ class TestVoteToggle:
# Remove vote
interaction["voted"] = None
return "removed"
- else:
- interaction["voted"] = new_vote
- return "changed"
+ interaction["voted"] = new_vote
+ return "changed"
def test_toggle_same_removes(self):
interaction = {"voted": "up"}
diff --git a/tests/news/test_card_storage_logic_behavior.py b/tests/news/test_card_storage_logic_behavior.py
index 96ad287597..af95218fdb 100644
--- a/tests/news/test_card_storage_logic_behavior.py
+++ b/tests/news/test_card_storage_logic_behavior.py
@@ -21,13 +21,12 @@ class TestSourceInfoExtraction:
"source_id": source_info.get("source_id"),
"created_from": source_info.get("created_from"),
}
- else:
- # Fallback to flat fields
- return {
- "source_type": data.get("source_type"),
- "source_id": data.get("source_id"),
- "created_from": data.get("created_from"),
- }
+ # Fallback to flat fields
+ return {
+ "source_type": data.get("source_type"),
+ "source_id": data.get("source_id"),
+ "created_from": data.get("created_from"),
+ }
def test_nested_source(self):
data = {
diff --git a/tests/news/test_monitoring_patterns_behavior.py b/tests/news/test_monitoring_patterns_behavior.py
index 220bbb5f25..17a3b9345f 100644
--- a/tests/news/test_monitoring_patterns_behavior.py
+++ b/tests/news/test_monitoring_patterns_behavior.py
@@ -235,10 +235,9 @@ class TestHealthChecks:
if all_healthy:
return "healthy"
- elif any_healthy:
+ if any_healthy:
return "degraded"
- else:
- return "unhealthy"
+ return "unhealthy"
checks = {"db": {"healthy": True}, "cache": {"healthy": True}}
assert aggregate_health(checks) == "healthy"
@@ -292,7 +291,7 @@ class TestAlerting:
def check_threshold(value, warning_threshold, critical_threshold):
if value >= critical_threshold:
return "critical"
- elif value >= warning_threshold:
+ if value >= warning_threshold:
return "warning"
return "ok"
@@ -355,9 +354,9 @@ class TestAlerting:
def classify_alert(alert):
if alert.get("error_rate", 0) > 50:
return AlertSeverity.CRITICAL
- elif alert.get("error_rate", 0) > 20:
+ if alert.get("error_rate", 0) > 20:
return AlertSeverity.ERROR
- elif alert.get("error_rate", 0) > 5:
+ if alert.get("error_rate", 0) > 5:
return AlertSeverity.WARNING
return AlertSeverity.INFO
@@ -635,7 +634,7 @@ class TestResourceMonitoring:
percent_used = (used_bytes / total_bytes) * 100
if percent_used >= critical_threshold:
return "critical"
- elif percent_used >= warning_threshold:
+ if percent_used >= warning_threshold:
return "warning"
return "ok"
diff --git a/tests/news/test_notification_patterns_behavior.py b/tests/news/test_notification_patterns_behavior.py
index 597fb5c498..d743ebae07 100644
--- a/tests/news/test_notification_patterns_behavior.py
+++ b/tests/news/test_notification_patterns_behavior.py
@@ -481,8 +481,8 @@ class TestQuietHours:
current_hour = datetime.now(timezone.utc).hour
if start < end:
return start <= current_hour < end
- else: # Wraps around midnight
- return current_hour >= start or current_hour < end
+ # Wraps around midnight
+ return current_hour >= start or current_hour < end
def test_no_quiet_hours_set(self):
prefs = {"quiet_hours_start": None, "quiet_hours_end": None}
diff --git a/tests/news/test_rate_limiting_patterns_behavior.py b/tests/news/test_rate_limiting_patterns_behavior.py
index 933fa91df8..006f9df30e 100644
--- a/tests/news/test_rate_limiting_patterns_behavior.py
+++ b/tests/news/test_rate_limiting_patterns_behavior.py
@@ -232,7 +232,7 @@ class TestAdaptiveThrottling:
"""Calculate adaptive rate limit based on success rate."""
if success_rate >= 0.99:
return min(int(base_limit * 1.1), max_limit)
- elif success_rate < 0.90:
+ if success_rate < 0.90:
return max(int(base_limit * 0.8), min_limit)
return base_limit
diff --git a/tests/news/test_security_patterns_behavior.py b/tests/news/test_security_patterns_behavior.py
index c5ceb1dfbf..e72c348915 100644
--- a/tests/news/test_security_patterns_behavior.py
+++ b/tests/news/test_security_patterns_behavior.py
@@ -717,7 +717,7 @@ class TestEncryption:
def secure_hash(data, algorithm="sha256"):
if algorithm == "sha256":
return hashlib.sha256(data.encode()).hexdigest()
- elif algorithm == "sha512":
+ if algorithm == "sha512":
return hashlib.sha512(data.encode()).hexdigest()
return ""
diff --git a/tests/news/test_topic_based_extended.py b/tests/news/test_topic_based_extended.py
index 5a2e4d240e..e39dc0bb7e 100644
--- a/tests/news/test_topic_based_extended.py
+++ b/tests/news/test_topic_based_extended.py
@@ -152,7 +152,7 @@ class TestTopicBasedRecommenderGenerateRecommendations:
def track_creation(*args, **kwargs):
cards_created.append(args[0])
- return None
+ return
with patch.object(
recommender, "_get_trending_topics", return_value=topics
diff --git a/tests/rate_limiting/test_rate_limiting.py b/tests/rate_limiting/test_rate_limiting.py
index 51826f3fb7..bf76ef746d 100644
--- a/tests/rate_limiting/test_rate_limiting.py
+++ b/tests/rate_limiting/test_rate_limiting.py
@@ -52,7 +52,7 @@ class TestAdaptiveRateLimitTracker(unittest.TestCase):
for engine in test_engines:
try:
self.tracker.reset_engine(engine)
- except:
+ except Exception:
pass
def tearDown(self):
@@ -69,7 +69,7 @@ class TestAdaptiveRateLimitTracker(unittest.TestCase):
for engine in test_engines:
try:
self.tracker.reset_engine(engine)
- except:
+ except Exception:
pass
@pytest.mark.timeout(30)
@@ -82,7 +82,7 @@ class TestAdaptiveRateLimitTracker(unittest.TestCase):
try:
self.tracker.reset_engine("TestEngine")
self.tracker.reset_engine("SearXNGSearchEngine")
- except:
+ except Exception:
pass
# Test default engine (unknown)
diff --git a/tests/research_library/routes/test_rag_routes_indexing_coverage.py b/tests/research_library/routes/test_rag_routes_indexing_coverage.py
index be63a1949e..148c7c8283 100644
--- a/tests/research_library/routes/test_rag_routes_indexing_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_indexing_coverage.py
@@ -663,10 +663,9 @@ class TestBackgroundIndexWorker:
call_count["n"] += 1
if document_id == "doc-ok":
return {"status": "success"}
- elif document_id == "doc-skip":
+ if document_id == "doc-skip":
return {"status": "skipped"}
- else:
- raise RuntimeError("indexing exploded")
+ raise RuntimeError("indexing exploded")
mock_svc.index_document.side_effect = index_side_effect
diff --git a/tests/research_library/services/test_library_service.py b/tests/research_library/services/test_library_service.py
index b310a70006..accdda2a5d 100644
--- a/tests/research_library/services/test_library_service.py
+++ b/tests/research_library/services/test_library_service.py
@@ -683,10 +683,9 @@ class TestGetResearchListRatingsPreload:
call_count["n"] += 1
if call_count["n"] == 1:
return mock_main_query # Main research query
- elif call_count["n"] == 2:
+ if call_count["n"] == 2:
return mock_ratings_query # Batch ratings query
- else:
- return mock_domain_query # Domain breakdown queries
+ return mock_domain_query # Domain breakdown queries
mock_session.query.side_effect = query_side_effect
mock_session_context.return_value = mock_session
@@ -811,9 +810,7 @@ class TestLibraryServiceMarkForRedownload:
model_name = getattr(model, "__name__", str(model))
if "Document" in str(model_name) or "Document" in str(model):
return mock_doc_query
- elif "DownloadTracker" in str(model_name) or "Tracker" in str(
- model
- ):
+ if "DownloadTracker" in str(model_name) or "Tracker" in str(model):
return mock_tracker_query
return MagicMock()
diff --git a/tests/research_library/services/test_library_service_collections_stats.py b/tests/research_library/services/test_library_service_collections_stats.py
index 5f2d2c7886..0e65359197 100644
--- a/tests/research_library/services/test_library_service_collections_stats.py
+++ b/tests/research_library/services/test_library_service_collections_stats.py
@@ -265,7 +265,7 @@ class TestGetResearchListWithStats:
call_count["n"] += 1
if call_count["n"] == 1:
return mock_main_query
- elif call_count["n"] == 2:
+ if call_count["n"] == 2:
return mock_ratings_query
return mock_domain_query
@@ -320,7 +320,7 @@ class TestGetResearchListWithStats:
call_count["n"] += 1
if call_count["n"] == 1:
return mock_main_query
- elif call_count["n"] == 2:
+ if call_count["n"] == 2:
return mock_ratings_query
return mock_domain_query
@@ -367,7 +367,7 @@ class TestGetResearchListWithStats:
call_count["n"] += 1
if call_count["n"] == 1:
return mock_main_query
- elif call_count["n"] == 2:
+ if call_count["n"] == 2:
return mock_ratings_query
return mock_domain_query
@@ -417,7 +417,7 @@ class TestGetResearchListWithStats:
call_count["n"] += 1
if call_count["n"] == 1:
return mock_main_query
- elif call_count["n"] == 2:
+ if call_count["n"] == 2:
return mock_ratings_query
return mock_domain_query
diff --git a/tests/research_library/services/test_library_service_crud_deep.py b/tests/research_library/services/test_library_service_crud_deep.py
index 4aa29f94b2..df71f99990 100644
--- a/tests/research_library/services/test_library_service_crud_deep.py
+++ b/tests/research_library/services/test_library_service_crud_deep.py
@@ -345,8 +345,7 @@ class TestGetDocumentByIdHappyPaths:
call_count["n"] += 1
if call_count["n"] == 1:
return mock_main_query
- else:
- return mock_coll_query
+ return mock_coll_query
mock_session.query.side_effect = query_side_effect
_mock_session_cm(mocker, mock_session)
diff --git a/tests/search_engines/test_search_engine_pubchem.py b/tests/search_engines/test_search_engine_pubchem.py
index afaa4b0f1b..b12bf520da 100644
--- a/tests/search_engines/test_search_engine_pubchem.py
+++ b/tests/search_engines/test_search_engine_pubchem.py
@@ -149,8 +149,7 @@ class TestPubChemErrorHandling:
call_count[0] += 1
if call_count[0] == 1:
return mock_autocomplete
- else:
- return mock_not_found
+ return mock_not_found
monkeypatch.setattr(
"local_deep_research.web_search_engines.engines.search_engine_pubchem.safe_get",
@@ -265,12 +264,11 @@ class TestPubChemErrorHandling:
url = args[0]
if "autocomplete" in url:
return mock_autocomplete
- elif "property" in url:
+ if "property" in url:
return mock_properties
- elif "description" in url:
+ if "description" in url:
return mock_description
- else:
- return mock_compound
+ return mock_compound
monkeypatch.setattr(
"local_deep_research.web_search_engines.engines.search_engine_pubchem.safe_get",
diff --git a/tests/search_engines/test_wikipedia_search.py b/tests/search_engines/test_wikipedia_search.py
index 55e156d3db..4ac25a3913 100644
--- a/tests/search_engines/test_wikipedia_search.py
+++ b/tests/search_engines/test_wikipedia_search.py
@@ -45,7 +45,7 @@ def test_wikipedia_search_run(monkeypatch, mock_wikipedia_response):
def mock_summary(title, sentences=5, auto_suggest=False):
if title == "Artificial intelligence":
return "Artificial intelligence (AI) is intelligence demonstrated by machines, in contrast to the natural intelligence displayed by humans."
- elif title == "Machine learning":
+ if title == "Machine learning":
return "Machine learning is a field of artificial intelligence that uses statistical techniques."
return "Default summary"
diff --git a/tests/security/test_rate_limiter_extended.py b/tests/security/test_rate_limiter_extended.py
index 8399956be2..f9bd60de2b 100644
--- a/tests/security/test_rate_limiter_extended.py
+++ b/tests/security/test_rate_limiter_extended.py
@@ -452,7 +452,7 @@ class TestDynamicRateLimitAdjustment:
def get_adjusted_limit(load):
if load > 0.9:
return base_limit * 0.5
- elif load > 0.7:
+ if load > 0.7:
return base_limit * 0.75
return base_limit
diff --git a/tests/settings/env_vars/test_env_var_usage.py b/tests/settings/env_vars/test_env_var_usage.py
index a2d5862853..93f3b42491 100755
--- a/tests/settings/env_vars/test_env_var_usage.py
+++ b/tests/settings/env_vars/test_env_var_usage.py
@@ -204,7 +204,7 @@ class EnvVarChecker(ast.NodeVisitor):
for setting_key in env_registry.list_all_settings():
if env_registry.get_env_var(setting_key) == env_var_name:
return setting_key
- except:
+ except Exception:
pass
return ""
diff --git a/tests/test_google_pse.py b/tests/test_google_pse.py
index 49d1f717e5..1ecc8aeae8 100644
--- a/tests/test_google_pse.py
+++ b/tests/test_google_pse.py
@@ -48,7 +48,7 @@ def check_api_quota(api_key, search_engine_id):
False,
"API quota exceeded. Google PSE has a limit of 100 requests per day on the free tier.",
)
- elif response.status_code != 200:
+ if response.status_code != 200:
return False, f"API error: {response.status_code} - {response.text}"
# If we get here, the API is working
diff --git a/tests/test_llm/test_llm_benchmarks.py b/tests/test_llm/test_llm_benchmarks.py
index 8e1a0a1d61..cd1096b07e 100644
--- a/tests/test_llm/test_llm_benchmarks.py
+++ b/tests/test_llm/test_llm_benchmarks.py
@@ -182,8 +182,7 @@ def test_benchmark_with_custom_llm_factory():
# Return different LLMs based on model name
if model_name == "accurate":
return BenchmarkLLM(correct_answers={"test": "correct"})
- else:
- return BenchmarkLLM(correct_answers={})
+ return BenchmarkLLM(correct_answers={})
register_llm("benchmark_factory", create_benchmark_llm)
diff --git a/tests/test_programmatic_custom_llm_retriever.py b/tests/test_programmatic_custom_llm_retriever.py
index 81238a08ec..13c4ee5952 100644
--- a/tests/test_programmatic_custom_llm_retriever.py
+++ b/tests/test_programmatic_custom_llm_retriever.py
@@ -21,7 +21,7 @@ def _is_ollama_running():
try:
response = requests.get("http://localhost:11434/api/tags", timeout=1)
return response.status_code == 200
- except:
+ except Exception:
return False
diff --git a/tests/test_search_engines_enhanced.py b/tests/test_search_engines_enhanced.py
index d8b5a8ab22..75757c6228 100644
--- a/tests/test_search_engines_enhanced.py
+++ b/tests/test_search_engines_enhanced.py
@@ -42,7 +42,7 @@ class TestWikipediaSearchEnhanced:
def mock_summary(title, sentences=3, auto_suggest=True):
if title == "Artificial intelligence":
return "Artificial intelligence (AI) is intelligence demonstrated by machines, in contrast to natural intelligence."
- elif title == "Machine learning":
+ if title == "Machine learning":
return "Machine learning (ML) is a subset of artificial intelligence that focuses on algorithms."
return "Generic summary"
@@ -341,7 +341,7 @@ class TestMultipleSearchEngines:
def mock_summary(title, sentences=3, auto_suggest=True):
if title == "Artificial intelligence":
return "Artificial intelligence (AI) is intelligence demonstrated by machines."
- elif title == "Machine learning":
+ if title == "Machine learning":
return "Machine learning (ML) is a subset of artificial intelligence."
return "Generic summary"
@@ -369,7 +369,7 @@ class TestMultipleSearchEngines:
):
if "api_key" in key:
return "test_api_key"
- elif "engine_id" in key:
+ if "engine_id" in key:
return "test_engine_id"
return default
diff --git a/tests/ui_tests/test_uuid_fresh_db.py b/tests/ui_tests/test_uuid_fresh_db.py
index 6dc7c6a58e..4d1b60ab0b 100644
--- a/tests/ui_tests/test_uuid_fresh_db.py
+++ b/tests/ui_tests/test_uuid_fresh_db.py
@@ -203,9 +203,8 @@ def test_uuid_with_fresh_schema():
return True
- else:
- print(f"Research submission failed: {research_response.text}")
- return False
+ print(f"Research submission failed: {research_response.text}")
+ return False
if __name__ == "__main__":
diff --git a/tests/ui_tests/test_uuid_research.py b/tests/ui_tests/test_uuid_research.py
index 6a96b150a3..678516fab4 100644
--- a/tests/ui_tests/test_uuid_research.py
+++ b/tests/ui_tests/test_uuid_research.py
@@ -151,9 +151,8 @@ def test_uuid_research():
return True
- else:
- print(f"Research submission failed: {research_response.text}")
- return False
+ print(f"Research submission failed: {research_response.text}")
+ return False
# Now let's also check the database directly
diff --git a/tests/utilities/test_log_utils_deep_coverage.py b/tests/utilities/test_log_utils_deep_coverage.py
index c714850ab3..3f831e426a 100644
--- a/tests/utilities/test_log_utils_deep_coverage.py
+++ b/tests/utilities/test_log_utils_deep_coverage.py
@@ -153,7 +153,7 @@ class TestProcessLogQueue:
def mock_get(timeout=None):
call_count[0] += 1
if call_count[0] == 1:
- return None
+ return
_stop_queue.set()
raise queue.Empty()
diff --git a/tests/web/routes/test_metrics_analytics_logic.py b/tests/web/routes/test_metrics_analytics_logic.py
index 25c203de12..30f9ad2d85 100644
--- a/tests/web/routes/test_metrics_analytics_logic.py
+++ b/tests/web/routes/test_metrics_analytics_logic.py
@@ -232,9 +232,9 @@ def _build_link_session(resources, classifications=None, researches=None):
def query_dispatch(model):
if model is ResearchResource:
return resource_query
- elif model is DomainClassification:
+ if model is DomainClassification:
return classification_query
- elif model is ResearchHistory:
+ if model is ResearchHistory:
return research_query
# Fallback for any other model
return MagicMock()
diff --git a/tests/web/routes/test_settings_routes_deep_coverage2.py b/tests/web/routes/test_settings_routes_deep_coverage2.py
index 88f5eba8f3..7f26d243f4 100644
--- a/tests/web/routes/test_settings_routes_deep_coverage2.py
+++ b/tests/web/routes/test_settings_routes_deep_coverage2.py
@@ -767,10 +767,9 @@ class TestFixCorruptedSettingsDuplicates:
call_count[0] += 1
if call_count[0] == 1:
return dup_query
- elif call_count[0] == 2:
+ if call_count[0] == 2:
return dupe_query
- else:
- return all_query
+ return all_query
mock_session.query.side_effect = _query_side_effect
diff --git a/tests/web/services/test_pdf_extraction_service.py b/tests/web/services/test_pdf_extraction_service.py
index 809bbb08ad..542b42a4a7 100644
--- a/tests/web/services/test_pdf_extraction_service.py
+++ b/tests/web/services/test_pdf_extraction_service.py
@@ -287,15 +287,14 @@ class TestExtractBatch:
"success": True,
"error": None,
}
- else:
- return {
- "text": "",
- "pages": 0,
- "size": 4,
- "filename": filename,
- "success": False,
- "error": "Failed to extract",
- }
+ return {
+ "text": "",
+ "pages": 0,
+ "size": 4,
+ "filename": filename,
+ "success": False,
+ "error": "Failed to extract",
+ }
with patch.object(
PDFExtractionService,
diff --git a/tests/web/services/test_research_service_execution.py b/tests/web/services/test_research_service_execution.py
index dbe3bc7bba..b39ddadbf4 100644
--- a/tests/web/services/test_research_service_execution.py
+++ b/tests/web/services/test_research_service_execution.py
@@ -142,11 +142,11 @@ def _classify_error(error_message):
"""Replicate error classification logic from run_research_process (lines 714-733)."""
if "status code: 503" in error_message:
return "ollama_unavailable"
- elif "status code: 404" in error_message:
+ if "status code: 404" in error_message:
return "model_not_found"
- elif "status code:" in error_message:
+ if "status code:" in error_message:
return "api_error"
- elif "connection" in error_message.lower():
+ if "connection" in error_message.lower():
return "connection_error"
return "unknown"
diff --git a/tests/web_search_engines/engines/test_guardian_coverage.py b/tests/web_search_engines/engines/test_guardian_coverage.py
index 8b891bc6a2..3a239b5a09 100644
--- a/tests/web_search_engines/engines/test_guardian_coverage.py
+++ b/tests/web_search_engines/engines/test_guardian_coverage.py
@@ -767,7 +767,7 @@ class TestAdaptiveSearch:
call_count[0] += 1
if call_count[0] == 1:
return [{"id": "a1"}] # initial: only 1
- elif call_count[0] == 2:
+ if call_count[0] == 2:
return [{"id": f"a{i}"} for i in range(5)] # 6-month: 5
return []
@@ -786,7 +786,7 @@ class TestAdaptiveSearch:
call_count[0] += 1
if call_count[0] <= 2:
return [{"id": "a1"}] # initial and 6mo: only 1
- elif call_count[0] == 3:
+ if call_count[0] == 3:
return [{"id": f"a{i}"} for i in range(4)] # all-time: 4
return []
@@ -804,7 +804,7 @@ class TestAdaptiveSearch:
call_count[0] += 1
if call_count[0] <= 3:
return [{"id": "a1"}] # all prior strategies: 1
- elif call_count[0] == 4:
+ if call_count[0] == 4:
return [{"id": f"a{i}"} for i in range(5)] # no section: 5
return []
diff --git a/tests/web_search_engines/engines/test_search_engine_pubmed.py b/tests/web_search_engines/engines/test_search_engine_pubmed.py
index fd160d623f..ddfbeb44c0 100644
--- a/tests/web_search_engines/engines/test_search_engine_pubmed.py
+++ b/tests/web_search_engines/engines/test_search_engine_pubmed.py
@@ -623,15 +623,14 @@ class TestAdaptiveSearch:
call_count += 1
if call_count == 1:
return ["1", "2"] # Initial call: < 5 results
- else:
- return [
- "1",
- "2",
- "3",
- "4",
- "5",
- "6",
- ] # Expanded: more results
+ return [
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ "6",
+ ] # Expanded: more results
with patch.object(
engine, "_search_pubmed", side_effect=side_effect_search
diff --git a/tests/web_search_engines/test_retriever_registry.py b/tests/web_search_engines/test_retriever_registry.py
index b3ae3fc236..afa7e15418 100644
--- a/tests/web_search_engines/test_retriever_registry.py
+++ b/tests/web_search_engines/test_retriever_registry.py
@@ -308,9 +308,8 @@ class TestThreadSafety:
def get_or_register(i):
if i % 2 == 0:
return registry.get("shared")
- else:
- registry.register(f"new_{i}", Mock())
- return None
+ registry.register(f"new_{i}", Mock())
+ return None
with ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(get_or_register, i) for i in range(100)]