~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
refactor: centralize LLM JSON parsing into shared json_utils module (#2220)
LearningCircuita5363de7bf13
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.pyindex 94c3956816..4d29eeffd7 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@@ -2,12 +2,11 @@Cross-engine search result filter implementation."""-import jsonfrom typing import Dict, Listfrom loguru import logger-from ...utilities.search_utilities import remove_think_tags+from ...utilities.json_utils import extract_json, get_llm_response_textfrom .base_filter import BaseFilter@@ -131,24 +130,10 @@ If no results seem relevant to the query, return an empty array: []"""try:# Get LLM's evaluationresponse = self.model.invoke(prompt)+ response_text = get_llm_response_text(response)+ ranked_indices = extract_json(response_text, expected_type=list)- # Extract response text- if hasattr(response, "content"):- response_text = remove_think_tags(response.content)- else:- response_text = remove_think_tags(str(response))-- # Clean up response- response_text = response_text.strip()-- # Find JSON array in response- start_idx = response_text.find("[")- end_idx = response_text.rfind("]")-- if start_idx >= 0 and end_idx > start_idx:- array_text = response_text[start_idx : end_idx + 1]- ranked_indices = json.loads(array_text)-+ if ranked_indices is not None:# If not reordering, just filter based on the indicesif not reorder:# Just keep the results that were deemed relevantdiff --git a/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py b/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.pyindex b183430d27..31c994fbcf 100644--- a/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py+++ b/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py@@ -9,7 +9,7 @@ from typing import Dict, Listfrom loguru import loggerfrom .base_filter import BaseFilter-from ...utilities.search_utilities import remove_think_tags+from ...utilities.json_utils import extract_json, get_llm_response_textclass FollowUpRelevanceFilter(BaseFilter):@@ -132,26 +132,20 @@ Return the indices of relevant sources as a JSON array:"""try:response = self.model.invoke(prompt)- content = remove_think_tags(response.content).strip()+ content = get_llm_response_text(response)# Parse JSON response- import json+ indices = extract_json(content, expected_type=list)- try:- indices = json.loads(content)+ if indices is not None:# Validate it's a list of integers- if not isinstance(indices, list):- raise ValueError("Response is not a list")indices = [int(i)for i in indicesif isinstance(i, (int, float)) and int(i) < len(sources)]-- except (json.JSONDecodeError, ValueError) as parse_error:- logger.debug(- f"Failed to parse JSON, attempting regex fallback: {parse_error}"- )+ else:+ logger.debug("Failed to parse JSON, attempting regex fallback")# Fallback to regex extractionimport rediff --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.pyindex cbc09d34c2..78975c238a 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@@ -20,6 +20,7 @@ from typing import Dict, List, Tuplefrom loguru import logger+from ...utilities.json_utils import extract_json, get_llm_response_textfrom ...utilities.search_cache import get_search_cachefrom ..candidate_exploration import ConstraintGuidedExplorerfrom ..constraint_checking import DualConfidenceChecker@@ -458,27 +459,26 @@ Format as JSON:Return only entities that are clearly {entity_type} entities."""response = await self.model.ainvoke(prompt)+ response_text = get_llm_response_text(response)+ entities_data = extract_json(response_text, expected_type=list)- try:- entities_data = json.loads(response.content)- entities = []-- for data in entities_data:- entity = EntityCandidate(- name=data["name"],- entity_type=entity_type,- aliases=data.get("aliases", []),- properties=data.get("properties", {}),- sources=[r.get("url", "") for r in results[:3]],- )- entities.append(entity)-- return entities-- except json.JSONDecodeError:+ if entities_data is None:logger.warning("Failed to parse entity extraction response")return []+ entities = []+ for data in entities_data:+ entity = EntityCandidate(+ name=data["name"],+ entity_type=entity_type,+ aliases=data.get("aliases", []),+ properties=data.get("properties", {}),+ sources=[r.get("url", "") for r in results[:3]],+ )+ entities.append(entity)++ return entities+async def _search_with_questions(self, questions: List[str], entity_type: str) -> List[EntityCandidate]: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.pyindex 42a5b34436..7797f4d56b 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@@ -9,10 +9,11 @@ This strategy orchestrates iterative refinement of research results by:5. Repeating until quality threshold is met or max iterations reached"""-import jsonfrom typing import Dict, Optionalfrom loguru import logger+from ...utilities.json_utils import extract_json, get_llm_response_text+from .base_strategy import BaseSearchStrategyfrom .followup.enhanced_contextual_followup import (EnhancedContextualFollowUpStrategy,@@ -451,23 +452,11 @@ Your refinement query can be as long and specific as needed to get good results.try:response = self.model.invoke(prompt)+ content = get_llm_response_text(response)- # Extract content from response- if hasattr(response, "content"):- content = response.content- else:- content = str(response)-- # Parse JSON from response- # If LLM includes markdown code blocks, extract the JSON- if "```json" in content:- json_str = content.split("```json")[1].split("```")[0].strip()- elif "```" in content:- json_str = content.split("```")[1].split("```")[0].strip()- else:- json_str = content-- evaluation = json.loads(json_str)+ 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 evaluationif "action" not in evaluation: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.pyindex 91295a3337..6a424e8609 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@@ -9,6 +9,8 @@ from typing import Dict, List, Optional, Tuplefrom loguru import logger+from ...utilities.json_utils import extract_json+from ..candidate_exploration import AdaptiveExplorerfrom ..constraint_checking import DualConfidenceCheckerfrom ..constraints import ConstraintAnalyzer@@ -183,15 +185,9 @@ class LLMConstraintProcessor:def _parse_decomposition(self, content):"""Parse LLM decomposition response"""- try:- # Extract JSON from the response- start = content.find("{")- end = content.rfind("}") + 1- if start != -1 and end != -1:- json_str = content[start:end]- return json.loads(json_str)- except Exception:- logger.exception("Failed to parse decomposition")+ result = extract_json(content, expected_type=dict)+ if result is not None:+ return result# Fallback to simple structurereturn {@@ -204,14 +200,9 @@ class LLMConstraintProcessor:def _parse_combinations(self, content):"""Parse LLM combinations response"""- try:- start = content.find("[")- end = content.rfind("]") + 1- if start != -1 and end != -1:- json_str = content[start:end]- return json.loads(json_str)- except Exception:- logger.exception("Failed to parse combinations")+ result = extract_json(content, expected_type=list)+ if result is not None:+ return result# Fallbackreturn [@@ -222,14 +213,9 @@ class LLMConstraintProcessor:def _parse_creative_searches(self, content):"""Parse LLM creative searches response"""- try:- start = content.find("[")- end = content.rfind("]") + 1- if start != -1 and end != -1:- json_str = content[start:end]- return json.loads(json_str)- except Exception:- logger.exception("Failed to parse creative searches")+ result = extract_json(content, expected_type=list)+ if result is not None:+ return result# Fallbackreturn [@@ -240,14 +226,9 @@ class LLMConstraintProcessor:def _parse_optimized_searches(self, content):"""Parse LLM optimized searches response"""- try:- start = content.find("{")- end = content.rfind("}") + 1- if start != -1 and end != -1:- json_str = content[start:end]- return json.loads(json_str)- except Exception:- logger.exception("Failed to parse optimized searches")+ result = extract_json(content, expected_type=dict)+ if result is not None:+ return result# Fallbackreturn {@@ -345,14 +326,9 @@ class EarlyRejectionManager:def _parse_confidence(self, content):"""Parse confidence assessment"""- try:- start = content.find("{")- end = content.rfind("}") + 1- if start != -1 and end != -1:- json_str = content[start:end]- return json.loads(json_str)- except Exception:- logger.exception("Failed to parse confidence")+ result = extract_json(content, expected_type=dict)+ if result is not None:+ return resultreturn {"positive_confidence": 0.5,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.pyindex 6ab9e31844..1f7e56b0fb 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@@ -4,13 +4,13 @@ Enhanced with LLM-driven constraint processing, early rejection, and immediate e"""import asyncio-import jsonfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom dataclasses import dataclassfrom typing import Dict, List, Optional, Tuplefrom loguru import logger+from ...utilities.json_utils import extract_jsonfrom ...utilities.search_cache import get_search_cache, normalize_entity_queryfrom ..candidate_exploration import (AdaptiveExplorer,@@ -152,14 +152,9 @@ class LLMConstraintProcessor:def _parse_decomposition(self, content):"""Parse LLM decomposition response"""- try:- start = content.find("{")- end = content.rfind("}") + 1- if start != -1 and end != -1:- json_str = content[start:end]- return json.loads(json_str)- except Exception:- logger.exception("Failed to parse decomposition")+ result = extract_json(content, expected_type=dict)+ if result is not None:+ return result# If parsing fails, return empty dict - let the system handle gracefullylogger.warning(@@ -169,14 +164,9 @@ class LLMConstraintProcessor:def _parse_combinations(self, content):"""Parse LLM combinations response"""- try:- start = content.find("[")- end = content.rfind("]") + 1- if start != -1 and end != -1:- json_str = content[start:end]- return json.loads(json_str)- except Exception:- logger.exception("Failed to parse combinations")+ result = extract_json(content, expected_type=list)+ if result is not None:+ return result# If parsing fails, return empty list - let the system handle gracefullylogger.warning("Failed to parse LLM combinations, returning empty list")@@ -256,14 +246,9 @@ class EarlyRejectionManager:def _parse_confidence(self, content):"""Parse confidence assessment"""- try:- start = content.find("{")- end = content.rfind("}") + 1- if start != -1 and end != -1:- json_str = content[start:end]- return json.loads(json_str)- except Exception:- logger.exception("Failed to parse confidence")+ result = extract_json(content, expected_type=dict)+ if result is not None:+ return resultreturn {"positive_confidence": 0.5,diff --git a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py b/src/local_deep_research/advanced_search_system/strategies/news_strategy.pyindex bdfc333814..dcbd231765 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@@ -5,12 +5,11 @@ Uses optimized prompts and search patterns for news aggregation.from typing import List, Dict, Any, Optionalfrom datetime import datetime, UTC-import json-import refrom loguru import loggerfrom .base_strategy import BaseSearchStrategyfrom ..questions.news_question import NewsQuestionGenerator+from ...utilities.json_utils import extract_jsonclass NewsAggregationStrategy(BaseSearchStrategy):@@ -148,14 +147,7 @@ Ensure variety across different categories when possible.def _extract_json_from_response(self, content: str) -> Optional[Dict]:"""Extract JSON from LLM response"""- try:- # Try to find JSON in the response- json_match = re.search(r"\{.*\}", content, re.DOTALL)- if json_match:- return json.loads(json_match.group())- except Exception:- logger.exception("Error extracting JSON")- return None+ return extract_json(content, expected_type=dict)def _format_news_summary(self, news_items: List[Dict]) -> str:"""Format news items into a readable summary"""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.pyindex dcd8e91c6d..d8dd44ab50 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@@ -9,6 +9,7 @@ from .source_based_strategy import SourceBasedSearchStrategyfrom .focused_iteration_strategy import FocusedIterationStrategyfrom ..findings.topic import Topic, TopicGraphfrom ..findings.repository import FindingsRepository+from ...utilities.json_utils import extract_json, get_llm_response_textfrom ...utilities.thread_context import preserve_research_context@@ -753,21 +754,11 @@ Consider similarity to lead sources when deciding.try:response = self.model.invoke(reorganize_prompt)- response_text = str(- response.content- if hasattr(response, "content")- else response- )-- # Parse JSON- import json- import re+ response_text = get_llm_response_text(response)- json_match = re.search(r"\[.*\]", response_text, re.DOTALL)- if json_match:- reassignments = json.loads(json_match.group())- else:- reassignments = json.loads(response_text)+ reassignments = extract_json(response_text, expected_type=list)+ if reassignments is None:+ reassignments = []# Process reassignmentsfor assignment in reassignments:diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.pyindex 1824626378..42fc1d82b8 100644--- a/src/local_deep_research/domain_classifier/classifier.py+++ b/src/local_deep_research/domain_classifier/classifier.py@@ -8,6 +8,7 @@ from ..database.session_context import get_user_db_sessionfrom ..database.models import ResearchResourcefrom .models import DomainClassificationfrom ..config.llm_config import get_llm+from ..utilities.json_utils import extract_json, get_llm_response_text# Predefined categories for domain classification@@ -218,27 +219,11 @@ JSON Response:"""llm = self._get_llm()response = llm.invoke(prompt)+ response_text = get_llm_response_text(response)- # Extract content from response- if hasattr(response, "content"):- response_text = response.content- else:- response_text = str(response)-- # Parse JSON response- try:- result = json.loads(response_text)- except json.JSONDecodeError:- # Try to extract JSON from response- import re-- json_match = re.search(r"\{.*\}", response_text, re.DOTALL)- if json_match:- result = json.loads(json_match.group())- else:- raise ValueError(- "Could not parse JSON from LLM response"- )+ result = extract_json(response_text, expected_type=dict)+ if result is None:+ raise ValueError("Could not parse JSON from LLM response")# Create or update classificationif existing:diff --git a/src/local_deep_research/news/core/news_analyzer.py b/src/local_deep_research/news/core/news_analyzer.pyindex 02a522cd7a..a44c77f14d 100644--- a/src/local_deep_research/news/core/news_analyzer.py+++ b/src/local_deep_research/news/core/news_analyzer.py@@ -10,6 +10,7 @@ from loguru import loggerfrom .utils import generate_card_idfrom ..utils.topic_generator import generate_topicsfrom ...config.llm_config import get_llm+from ...utilities.json_utils import extract_json, get_llm_response_textclass NewsAnalyzer:@@ -131,21 +132,11 @@ Focus on genuinely newsworthy stories.try:response = self.llm_client.invoke(prompt)- content = (- response.content- if hasattr(response, "content")- else str(response)- )+ content = get_llm_response_text(response)# Parse JSON response- import json- import re-- # Extract JSON array- json_match = re.search(r"\[.*\]", content, re.DOTALL)- if json_match:- news_items = json.loads(json_match.group())-+ news_items = extract_json(content, expected_type=list)+ if news_items is not None:# Validate and clean itemsvalid_items = []for item in news_items[:max_items]:diff --git a/src/local_deep_research/news/utils/topic_generator.py b/src/local_deep_research/news/utils/topic_generator.pyindex 25340bc0a4..df1b1b61b4 100644--- a/src/local_deep_research/news/utils/topic_generator.py+++ b/src/local_deep_research/news/utils/topic_generator.py@@ -5,7 +5,8 @@ Uses LLM to extract relevant topics/tags from news content.from loguru import loggerfrom typing import List-import json++from ...utilities.json_utils import extract_json, get_llm_response_textdef generate_topics(@@ -73,37 +74,28 @@ Requirements:Return ONLY a JSON array of topic strings, like: ["Topic 1", "Topic 2", "Topic 3"]"""response = llm.invoke(prompt)- content = response.content.strip()+ content = get_llm_response_text(response)# Try to parse the JSON response- try:- # Clean up common LLM response patterns- if content.startswith("```json"):- content = content[7:]- if content.endswith("```"):- content = content[:-3]- content = content.strip()-- topics = json.loads(content)-- if isinstance(topics, list):- # Clean and validate each topic- cleaned_topics = []- for topic in topics:- if isinstance(topic, str):- cleaned = topic.strip()- if cleaned and len(cleaned) <= 30: # Max topic length- cleaned_topics.append(cleaned)-- logger.debug(f"Generated topics: {cleaned_topics}")- return cleaned_topics[:max_topics]-- except json.JSONDecodeError:- logger.debug(f"Failed to parse LLM topics as JSON: {content}")- # Try to extract topics from plain text response- if "," in content:- topics = [t.strip().strip("\"'") for t in content.split(",")]- return [t for t in topics if t and len(t) <= 30][:max_topics]+ topics = extract_json(content, expected_type=list)++ if topics is not None:+ # Clean and validate each topic+ cleaned_topics = []+ for topic in topics:+ if isinstance(topic, str):+ cleaned = topic.strip()+ if cleaned and len(cleaned) <= 30: # Max topic length+ cleaned_topics.append(cleaned)++ logger.debug(f"Generated topics: {cleaned_topics}")+ return cleaned_topics[:max_topics]++ # Try to extract topics from plain text response+ logger.debug(f"Failed to parse LLM topics as JSON: {content}")+ if "," in content:+ topics = [t.strip().strip("\"'") for t in content.split(",")]+ return [t for t in topics if t and len(t) <= 30][:max_topics]except Exception as e:logger.debug(f"LLM topic generation failed: {e}")diff --git a/src/local_deep_research/utilities/json_utils.py b/src/local_deep_research/utilities/json_utils.pynew file mode 100644index 0000000000..63b42d393b--- /dev/null+++ b/src/local_deep_research/utilities/json_utils.py@@ -0,0 +1,181 @@+"""+Centralized utilities for extracting and parsing JSON from LLM responses.++Provides two public functions:+- get_llm_response_text: Extract text from LLM response objects+- extract_json: Parse JSON from LLM-generated text with robust cleaning+"""++import json+import re+from typing import Optional, Type, Union++from loguru import logger+++def get_llm_response_text(response) -> str:+ """Extract text content from an LLM response object.++ Handles LangChain AIMessage (.content), plain text responses (.text),+ and arbitrary objects (via str()). Removes <think> tags from the output.++ Args:+ response: LLM response object, string, or None.++ Returns:+ Extracted text with think tags removed. Empty string for None input.+ """+ if response is None:+ return ""+ if hasattr(response, "content") and response.content is not None:+ raw = response.content+ elif hasattr(response, "text") and response.text is not None:+ raw = response.text+ else:+ raw = str(response)+ if not isinstance(raw, str):+ raw = str(raw)+ return _remove_think_tags(raw)+++def extract_json(+ text: str,+ expected_type: Optional[Type] = None,+) -> Optional[Union[dict, list]]:+ """Extract and parse JSON from LLM-generated text.++ Applies a cleaning pipeline to handle common LLM output patterns:+ code fences, think tags, prose surrounding JSON, and minor artifacts.++ Args:+ text: Raw text potentially containing JSON.+ expected_type: Expected JSON type (dict or list). If specified,+ bracket extraction is ordered to prefer the matching type.+ None accepts either type.++ Returns:+ Parsed dict or list, or None if no valid JSON found.+ """+ if not text or not text.strip():+ return None++ text = text.strip()+ text = _strip_code_fences(text)+ text = _remove_think_tags(text)++ # Step 1: Try direct parse+ try:+ result = json.loads(text)+ if isinstance(result, (dict, list)):+ if expected_type is None or isinstance(result, expected_type):+ return result+ # Type mismatch — fall through to bracket extraction+ except (json.JSONDecodeError, ValueError):+ pass++ # Step 2: Bracket extraction ordered by expected_type+ if expected_type is list:+ bracket_pairs = [("[", "]"), ("{", "}")]+ elif expected_type is dict:+ bracket_pairs = [("{", "}"), ("[", "]")]+ else:+ bracket_pairs = [("{", "}"), ("[", "]")]++ for open_char, close_char in bracket_pairs:+ extracted = _extract_by_brackets(text, open_char, close_char)+ if extracted is None:+ continue++ # Try parsing the extracted substring+ try:+ result = json.loads(extracted)+ if isinstance(result, (dict, list)):+ if expected_type is None or isinstance(result, expected_type):+ return result+ except (json.JSONDecodeError, ValueError):+ pass++ # Try cleaning LLM artifacts and retrying+ cleaned = _clean_llm_json_artifacts(extracted)+ if cleaned != extracted:+ try:+ result = json.loads(cleaned)+ if isinstance(result, (dict, list)):+ if expected_type is None or isinstance(+ result, expected_type+ ):+ return result+ except (json.JSONDecodeError, ValueError):+ pass++ logger.debug("No valid JSON found in text")+ return None+++# ---------------------------------------------------------------------------+# Private helpers+# ---------------------------------------------------------------------------+++def _remove_think_tags(text: str) -> str:+ """Remove <think>...</think> tags from text.++ Duplicated from search_utilities to keep this module free of+ internal package dependencies (follows type_utils.py convention).+ """+ text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL)+ text = re.sub(r"</think>", "", text)+ text = re.sub(r"<think>", "", text)+ return text.strip()+++def _strip_code_fences(text: str) -> str:+ """Remove markdown code fences from text.++ Uses split-based extraction (not startswith) to handle fences+ appearing mid-text with surrounding prose.+ """+ if "```json" in text:+ parts = text.split("```json")+ if len(parts) > 1:+ return parts[1].split("```")[0].strip()+ elif "```" in text:+ parts = text.split("```")+ if len(parts) >= 3:+ return parts[1].strip()+ return text+++def _extract_by_brackets(+ text: str, open_char: str, close_char: str+) -> Optional[str]:+ """Extract substring between outermost matching brackets.++ Uses find()/rfind() which is equivalent to re.search with re.DOTALL+ for bracket matching.+ """+ start = text.find(open_char)+ end = text.rfind(close_char)+ if start >= 0 and end > start:+ return text[start : end + 1]+ return None+++def _clean_llm_json_artifacts(text: str) -> str:+ """Clean common LLM JSON artifacts from malformed JSON text.++ Only called after json.loads has already failed, so the text is+ already malformed. These regexes cannot corrupt valid JSON.++ Handles:+ - Trailing commas before ] or }+ - Inline // comments+ - Ellipsis entries (... or "...")+ """+ # Remove trailing commas+ text = re.sub(r",\s*([}\]])", r"\1", text)+ # Remove // line comments+ text = re.sub(r"//[^\n]*", "", text)+ # Remove ellipsis entries+ text = re.sub(r',?\s*"?\.\.\.+"?\s*,?', "", text)+ return textdiff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.pyindex f00516dd0e..39ac35e803 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@@ -1,4 +1,3 @@-import jsonfrom loguru import loggerfrom datetime import datetime, UTCfrom typing import Dict, List@@ -9,7 +8,7 @@ from langchain_community.document_transformers import BeautifulSoupTransformerfrom langchain_core.language_models import BaseLLMfrom ...config.search_config import QUALITY_CHECK_DDG_URLS-from ...utilities.search_utilities import remove_think_tags+from ...utilities.json_utils import extract_json, get_llm_response_textclass FullSearchResults:@@ -58,7 +57,11 @@ class FullSearchResults:try:# Get LLM's evaluationresponse = self.llm.invoke(prompt)- good_indices = json.loads(remove_think_tags(response.content))+ response_text = get_llm_response_text(response)+ good_indices = extract_json(response_text, expected_type=list)++ if good_indices is None:+ good_indices = []# Return only the results with good URLsreturn [r for i, r in enumerate(results) if i in good_indices]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.pyindex 2b613567f4..e5d7cf44a0 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@@ -1,4 +1,3 @@-import jsonimport osimport concurrent.futuresfrom typing import Any, Dict, List, Optional@@ -9,6 +8,7 @@ from loguru import loggerfrom ...config.search_config import get_setting_from_snapshotfrom ...utilities.enums import SearchMode+from ...utilities.json_utils import extract_json, get_llm_response_textfrom ...utilities.thread_context import preserve_research_contextfrom ...web.services.socket_service import SocketIOServicefrom ..search_engine_base import BaseSearchEngine@@ -399,21 +399,11 @@ Select up to {self.max_engines_to_select} engines that would best answer this qulogger.debug("Sending prompt to LLM for engine selection")# Get LLM responseresponse = self.llm.invoke(prompt)+ content = get_llm_response_text(response)- # Handle different response formats- if hasattr(response, "content"):- content = response.content.strip()- else:- content = str(response).strip()-- # Extract JSON array- start_idx = content.find("[")- end_idx = content.rfind("]")-- if start_idx >= 0 and end_idx > start_idx:- array_text = content[start_idx : end_idx + 1]- indices = json.loads(array_text)+ indices = extract_json(content, expected_type=list)+ if indices is not None:# Convert indices to engine names (from the filtered list)selected_engines = []for idx in indices: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.pyindex d00bc44727..eb444d220e 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@@ -8,6 +8,7 @@ from loguru import loggerfrom ...config import llm_config, search_configfrom ...security.safe_requests import safe_get+from ...utilities.json_utils import extract_json, get_llm_response_textfrom ..search_engine_base import BaseSearchEngine@@ -885,16 +886,11 @@ Do not include any other text or explanation."""try:response = self.llm.invoke(prompt)- response_text = response.content.strip()+ response_text = get_llm_response_text(response)- # Extract JSON array from response- start_idx = response_text.find("[")- end_idx = response_text.rfind("]")-- if start_idx >= 0 and end_idx > start_idx:- array_text = response_text[start_idx : end_idx + 1]- ranked_indices = json.loads(array_text)+ ranked_indices = extract_json(response_text, expected_type=list)+ if ranked_indices is not None:# Return the results in ranked orderranked_results = []for idx in ranked_indices: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.pyindex a4c0277dc0..d7b2079189 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@@ -8,9 +8,9 @@ import requestsfrom langchain_core.language_models import BaseLLMfrom loguru import logger-from ...utilities.search_utilities import remove_think_tags+from ...utilities.json_utils import extract_json, get_llm_response_text+from ...utilities.search_utilities import remove_think_tags, LANGUAGE_CODE_MAPfrom ..search_engine_base import BaseSearchEngine-from ...utilities.search_utilities import LANGUAGE_CODE_MAPfrom ...security import safe_getHEADERS = {@@ -156,27 +156,12 @@ NOW RETURN ONLY THE JSON OBJECT."""# Get response from LLMresponse = self.llm.invoke(prompt)+ response_text = get_llm_response_text(response)- response_text = (- getattr(response, "content", None)- or getattr(response, "text", None)- or str(response)- )-- # Find possible JSON object boundaries- start = response_text.find("{")- end = response_text.rfind("}")-- # Validate boundaries before slicing- if start == -1 or end == -1 or end <= start:- raise ValueError("No valid JSON boundaries found")-- json_str = response_text[start : end + 1]-- data = json.loads(json_str)+ data = extract_json(response_text, expected_type=dict)- if not isinstance(data, dict):- raise ValueError("Extracted JSON is not an object")+ if data is None:+ raise ValueError("No valid JSON found in response")optimized_query = (data.get("query", "")).strip()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.pyindex dfa5bc57fd..0afdd21b88 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@@ -1,4 +1,3 @@-import jsonimport timefrom abc import ABC, abstractmethodfrom datetime import datetime, UTC@@ -15,6 +14,7 @@ from tenacity import (from tenacity.wait import wait_basefrom ..advanced_search_system.filters.base_filter import BaseFilter+from ..utilities.json_utils import extract_json, get_llm_response_textfrom ..utilities.thread_context import set_search_context# Lazy import for metrics to avoid database dependencies in programmatic mode@@ -538,85 +538,65 @@ Respond with ONLY the JSON array, no other text."""# Log the raw response for debugginglogger.info(f"Raw LLM response for relevance filtering: {response}")- # Handle different response formats- response_text = ""- if hasattr(response, "content"):- response_text = response.content- else:- response_text = str(response)-- # Clean up response- response_text = response_text.strip()+ response_text = get_llm_response_text(response)logger.debug(f"Cleaned response text: {response_text}")- # Find JSON array in response- start_idx = response_text.find("[")- end_idx = response_text.rfind("]")-- if start_idx >= 0 and end_idx > start_idx:- array_text = response_text[start_idx : end_idx + 1]- try:- ranked_indices = json.loads(array_text)- logger.info(f"LLM returned indices: {ranked_indices}")+ ranked_indices = extract_json(response_text, expected_type=list)- # Validate that ranked_indices is a list of integers- if not isinstance(ranked_indices, list):- logger.warning(- "LLM response is not a list, returning empty results"- )- return []+ if ranked_indices is not None:+ logger.info(f"LLM returned indices: {ranked_indices}")- if not all(isinstance(idx, int) for idx in ranked_indices):- logger.warning(- "LLM response contains non-integer indices, returning empty results"- )- return []+ # Validate that ranked_indices is a list of integers+ if not isinstance(ranked_indices, list):+ logger.warning(+ "LLM response is not a list, returning empty results"+ )+ return []- # Log analysis of the indices- max_index = max(ranked_indices) if ranked_indices else -1- min_index = min(ranked_indices) if ranked_indices else -1- logger.info(- f"Index analysis: min={min_index}, max={max_index}, "- f"valid_range=0-{len(previews) - 1}, count={len(ranked_indices)}"+ if not all(isinstance(idx, int) for idx in ranked_indices):+ logger.warning(+ "LLM response contains non-integer indices, returning empty results")+ return []- # Return the results in ranked order- ranked_results = []- out_of_range = []- for idx in ranked_indices:- if 0 <= idx < len(previews):- ranked_results.append(previews[idx])- else:- out_of_range.append(idx)- logger.warning(- f"Index {idx} out of range (valid: 0-{len(previews) - 1}), skipping"- )-- if out_of_range:- logger.error(- f"Out of range indices: {out_of_range}. "- f"Total previews: {len(previews)}, "- f"All returned indices: {ranked_indices}"- )+ # Log analysis of the indices+ max_index = max(ranked_indices) if ranked_indices else -1+ min_index = min(ranked_indices) if ranked_indices else -1+ logger.info(+ f"Index analysis: min={min_index}, max={max_index}, "+ f"valid_range=0-{len(previews) - 1}, count={len(ranked_indices)}"+ )- # Limit to max_filtered_results if specified- if (- self.max_filtered_results- and len(ranked_results) > self.max_filtered_results- ):- logger.info(- f"Limiting filtered results to top {self.max_filtered_results}"+ # Return the results in ranked order+ ranked_results = []+ out_of_range = []+ for idx in ranked_indices:+ if 0 <= idx < len(previews):+ ranked_results.append(previews[idx])+ else:+ out_of_range.append(idx)+ logger.warning(+ f"Index {idx} out of range (valid: 0-{len(previews) - 1}), skipping")- return ranked_results[: self.max_filtered_results]- return ranked_results+ if out_of_range:+ logger.error(+ f"Out of range indices: {out_of_range}. "+ f"Total previews: {len(previews)}, "+ f"All returned indices: {ranked_indices}"+ )- except json.JSONDecodeError as e:- logger.warning(- f"Failed to parse JSON from LLM response: {e}"+ # Limit to max_filtered_results if specified+ if (+ self.max_filtered_results+ and len(ranked_results) > self.max_filtered_results+ ):+ logger.info(+ f"Limiting filtered results to top {self.max_filtered_results}")- logger.debug(f"Problematic JSON text: {array_text}")- return []+ return ranked_results[: self.max_filtered_results]++ return ranked_resultselse:logger.warning("Could not find JSON array in response, returning original previews"diff --git a/tests/utilities/test_json_utils.py b/tests/utilities/test_json_utils.pynew file mode 100644index 0000000000..025daf0f9a--- /dev/null+++ b/tests/utilities/test_json_utils.py@@ -0,0 +1,486 @@+"""Tests for json_utils module."""++from unittest.mock import Mock+++class TestGetLlmResponseText:+ """Tests for get_llm_response_text function."""++ def test_extracts_content_attribute(self):+ """Test that .content attribute is extracted from response."""+ from local_deep_research.utilities.json_utils import (+ get_llm_response_text,+ )++ response = Mock()+ response.content = "Hello world"+ assert get_llm_response_text(response) == "Hello world"++ def test_falls_back_to_text_attribute(self):+ """Test that .text is used when .content is not available."""+ from local_deep_research.utilities.json_utils import (+ get_llm_response_text,+ )++ response = Mock(spec=[])+ response.text = "Hello text"+ assert get_llm_response_text(response) == "Hello text"++ def test_content_takes_precedence_over_text(self):+ """Test that .content is preferred over .text."""+ from local_deep_research.utilities.json_utils import (+ get_llm_response_text,+ )++ response = Mock()+ response.content = "from content"+ response.text = "from text"+ assert get_llm_response_text(response) == "from content"++ def test_plain_string_passthrough(self):+ """Test that a plain string is returned via str()."""+ from local_deep_research.utilities.json_utils import (+ get_llm_response_text,+ )++ assert get_llm_response_text("plain string") == "plain string"++ def test_none_input_returns_empty_string(self):+ """Test that None input returns empty string."""+ from local_deep_research.utilities.json_utils import (+ get_llm_response_text,+ )++ assert get_llm_response_text(None) == ""++ def test_content_none_falls_through_to_text(self):+ """Test that content=None falls through to .text."""+ from local_deep_research.utilities.json_utils import (+ get_llm_response_text,+ )++ response = Mock()+ response.content = None+ response.text = "from text"+ assert get_llm_response_text(response) == "from text"++ def test_non_string_content_converted(self):+ """Test that non-string .content is converted to string."""+ from local_deep_research.utilities.json_utils import (+ get_llm_response_text,+ )++ response = Mock()+ response.content = 42+ assert get_llm_response_text(response) == "42"++ def test_removes_paired_think_tags(self):+ """Test that paired <think>...</think> tags are removed."""+ from local_deep_research.utilities.json_utils import (+ get_llm_response_text,+ )++ response = Mock()+ response.content = "<think>reasoning</think>Result here"+ assert get_llm_response_text(response) == "Result here"++ def test_removes_orphaned_think_tags(self):+ """Test that orphaned opening or closing think tags are removed."""+ from local_deep_research.utilities.json_utils import (+ get_llm_response_text,+ )++ response = Mock()+ response.content = "</think>Result<think>"+ assert get_llm_response_text(response) == "Result"++ def test_removes_multiline_think_tags(self):+ """Test that multiline think tag content is removed."""+ from local_deep_research.utilities.json_utils import (+ get_llm_response_text,+ )++ response = Mock()+ response.content = "<think>\nline1\nline2\n</think>\nActual content"+ assert get_llm_response_text(response) == "Actual content"+++class TestExtractJson:+ """Tests for extract_json function."""++ def test_pure_json_dict(self):+ """Test parsing a pure JSON dict string."""+ from local_deep_research.utilities.json_utils import extract_json++ result = extract_json('{"key": "value"}')+ assert result == {"key": "value"}++ def test_pure_json_list(self):+ """Test parsing a pure JSON list string."""+ from local_deep_research.utilities.json_utils import extract_json++ result = extract_json("[1, 2, 3]")+ assert result == [1, 2, 3]++ def test_nested_structures(self):+ """Test parsing nested JSON structures."""+ from local_deep_research.utilities.json_utils import extract_json++ text = '{"items": [{"id": 1}, {"id": 2}]}'+ result = extract_json(text)+ assert result == {"items": [{"id": 1}, {"id": 2}]}++ def test_code_fence_json(self):+ """Test extracting JSON from ```json code fences."""+ from local_deep_research.utilities.json_utils import extract_json++ text = '```json\n{"key": "value"}\n```'+ result = extract_json(text)+ assert result == {"key": "value"}++ def test_bare_code_fence(self):+ """Test extracting JSON from bare ``` code fences."""+ from local_deep_research.utilities.json_utils import extract_json++ text = "```\n[1, 2, 3]\n```"+ result = extract_json(text)+ assert result == [1, 2, 3]++ def test_code_fence_with_surrounding_prose(self):+ """Test extracting JSON from code fences with text around them."""+ from local_deep_research.utilities.json_utils import extract_json++ text = (+ 'Here is the result:\n```json\n{"key": "value"}\n```\n'+ "Hope that helps!"+ )+ result = extract_json(text)+ assert result == {"key": "value"}++ def test_dict_embedded_in_prose(self):+ """Test extracting JSON dict embedded in prose text."""+ from local_deep_research.utilities.json_utils import extract_json++ text = 'The answer is {"key": "value"} as shown above.'+ result = extract_json(text)+ assert result == {"key": "value"}++ def test_list_embedded_in_prose(self):+ """Test extracting JSON list embedded in prose text."""+ from local_deep_research.utilities.json_utils import extract_json++ text = "Here are the indices: [3, 0, 7, 1] sorted by relevance."+ result = extract_json(text, expected_type=list)+ assert result == [3, 0, 7, 1]++ def test_expected_type_list_prefers_brackets(self):+ """Test that expected_type=list tries [] before {}."""+ from local_deep_research.utilities.json_utils import extract_json++ text = 'Prefix {"a": 1} and also [1, 2, 3] suffix'+ result = extract_json(text, expected_type=list)+ assert result == [1, 2, 3]++ def test_expected_type_dict_prefers_braces(self):+ """Test that expected_type=dict tries {} before []."""+ from local_deep_research.utilities.json_utils import extract_json++ text = 'Prefix [1, 2, 3] and also {"a": 1} suffix'+ result = extract_json(text, expected_type=dict)+ assert result == {"a": 1}++ def test_type_mismatch_falls_through(self):+ """Test that type mismatch on direct parse falls to extraction."""+ from local_deep_research.utilities.json_utils import extract_json++ text = '{"items": [1, 2, 3]}'+ result = extract_json(text, expected_type=list)+ assert result == [1, 2, 3]++ def test_type_mismatch_no_alternative_returns_none(self):+ """Test that type mismatch with no matching brackets returns None."""+ from local_deep_research.utilities.json_utils import extract_json++ text = "just plain text no json here"+ result = extract_json(text, expected_type=list)+ assert result is None++ def test_think_tags_cleaned_before_parse(self):+ """Test that think tags are removed before JSON parsing."""+ from local_deep_research.utilities.json_utils import extract_json++ text = '<think>reasoning here</think>{"key": "value"}'+ result = extract_json(text)+ assert result == {"key": "value"}++ def test_none_input_returns_none(self):+ """Test that None input returns None."""+ from local_deep_research.utilities.json_utils import extract_json++ assert extract_json(None) is None++ def test_empty_string_returns_none(self):+ """Test that empty string returns None."""+ from local_deep_research.utilities.json_utils import extract_json++ assert extract_json("") is None++ def test_whitespace_only_returns_none(self):+ """Test that whitespace-only string returns None."""+ from local_deep_research.utilities.json_utils import extract_json++ assert extract_json(" \n\t ") is None++ def test_no_json_returns_none(self):+ """Test that text without JSON returns None."""+ from local_deep_research.utilities.json_utils import extract_json++ assert extract_json("Hello, I have no JSON here.") is None++ def test_invalid_json_in_brackets_returns_none(self):+ """Test that invalid JSON inside brackets returns None."""+ from local_deep_research.utilities.json_utils import extract_json++ assert extract_json("{not valid json at all}") is None++ def test_json_scalar_returns_none(self):+ """Test that JSON scalars (number, string) return None."""+ from local_deep_research.utilities.json_utils import extract_json++ assert extract_json("42") is None+ assert extract_json('"just a string"') is None++ def test_unicode_content_preserved(self):+ """Test that unicode content in JSON is preserved."""+ from local_deep_research.utilities.json_utils import extract_json++ text = '{"name": "café", "city": "München"}'+ result = extract_json(text)+ assert result == {"name": "café", "city": "München"}++ def test_multiline_json(self):+ """Test parsing multiline JSON with whitespace."""+ from local_deep_research.utilities.json_utils import extract_json++ text = '{\n "key1": "value1",\n "key2": "value2"\n}'+ result = extract_json(text)+ assert result == {"key1": "value1", "key2": "value2"}++ def test_expected_type_none_accepts_dict(self):+ """Test that expected_type=None accepts dict."""+ from local_deep_research.utilities.json_utils import extract_json++ result = extract_json('{"a": 1}', expected_type=None)+ assert result == {"a": 1}++ def test_expected_type_none_accepts_list(self):+ """Test that expected_type=None accepts list."""+ from local_deep_research.utilities.json_utils import extract_json++ result = extract_json("[1, 2]", expected_type=None)+ assert result == [1, 2]++ def test_nested_brackets_extracted_correctly(self):+ """Test that nested brackets use outermost match."""+ from local_deep_research.utilities.json_utils import extract_json++ text = 'prefix {"a": {"b": [1, 2]}} suffix'+ result = extract_json(text)+ assert result == {"a": {"b": [1, 2]}}++ def test_list_of_dicts(self):+ """Test parsing a list of dictionaries."""+ from local_deep_research.utilities.json_utils import extract_json++ text = '[{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]'+ result = extract_json(text, expected_type=list)+ assert result == [+ {"id": 1, "name": "a"},+ {"id": 2, "name": "b"},+ ]+++class TestExtractJsonLlmArtifacts:+ """Tests for LLM artifact cleaning in extract_json."""++ def test_trailing_comma_in_array(self):+ """Test that trailing commas in arrays are handled."""+ from local_deep_research.utilities.json_utils import extract_json++ result = extract_json("[1, 2, 3,]")+ assert result == [1, 2, 3]++ def test_trailing_comma_in_object(self):+ """Test that trailing commas in objects are handled."""+ from local_deep_research.utilities.json_utils import extract_json++ result = extract_json('{"a": 1, "b": 2,}')+ assert result == {"a": 1, "b": 2}++ def test_inline_comments(self):+ """Test that // comments are cleaned from JSON."""+ from local_deep_research.utilities.json_utils import extract_json++ text = "[1, 2, // this is best\n3]"+ result = extract_json(text, expected_type=list)+ assert result == [1, 2, 3]++ def test_ellipsis_in_array(self):+ """Test that ellipsis entries are removed from arrays."""+ from local_deep_research.utilities.json_utils import extract_json++ result = extract_json("[1, 2, ...]")+ assert result == [1, 2]++ def test_quoted_ellipsis_in_array(self):+ """Test that quoted ellipsis in valid JSON is preserved (valid JSON)."""+ from local_deep_research.utilities.json_utils import extract_json++ # This is valid JSON, so direct parse succeeds without artifact cleaning+ result = extract_json('[1, 2, "..."]')+ assert result == [1, 2, "..."]++ def test_unquoted_ellipsis_in_malformed_json(self):+ """Test that ellipsis is cleaned from malformed JSON."""+ from local_deep_research.utilities.json_utils import extract_json++ # Trailing comma + ellipsis makes this invalid, triggers cleaning+ result = extract_json("[1, 2, ...,]")+ assert result == [1, 2]++ def test_combined_artifacts(self):+ """Test cleaning multiple artifact types at once."""+ from local_deep_research.utilities.json_utils import extract_json++ text = "[1, 2, // comment\n3, ...,]"+ result = extract_json(text, expected_type=list)+ assert result == [1, 2, 3]++ def test_clean_json_not_modified(self):+ """Test that valid JSON is not affected by artifact cleaning."""+ from local_deep_research.utilities.json_utils import extract_json++ text = '{"url": "https://example.com/path", "count": 5}'+ result = extract_json(text)+ assert result == {+ "url": "https://example.com/path",+ "count": 5,+ }++ def test_trailing_comma_in_prose(self):+ """Test trailing comma cleanup with surrounding prose."""+ from local_deep_research.utilities.json_utils import extract_json++ text = "The result is: [1, 2, 3,] as expected"+ result = extract_json(text, expected_type=list)+ assert result == [1, 2, 3]+++class TestStripCodeFences:+ """Tests for _strip_code_fences private helper."""++ def test_json_code_fence(self):+ """Test stripping ```json code fences."""+ from local_deep_research.utilities.json_utils import (+ _strip_code_fences,+ )++ text = '```json\n{"key": "value"}\n```'+ assert _strip_code_fences(text) == '{"key": "value"}'++ def test_bare_code_fence(self):+ """Test stripping bare ``` code fences."""+ from local_deep_research.utilities.json_utils import (+ _strip_code_fences,+ )++ text = "```\n[1, 2, 3]\n```"+ assert _strip_code_fences(text) == "[1, 2, 3]"++ def test_no_code_fence(self):+ """Test that text without code fences is returned unchanged."""+ from local_deep_research.utilities.json_utils import (+ _strip_code_fences,+ )++ text = '{"key": "value"}'+ assert _strip_code_fences(text) == '{"key": "value"}'++ def test_stray_backticks_not_treated_as_fence(self):+ """Test that stray backticks are not treated as code fences."""+ from local_deep_research.utilities.json_utils import (+ _strip_code_fences,+ )++ text = "Use ``` for code blocks"+ assert _strip_code_fences(text) == "Use ``` for code blocks"++ def test_json_fence_with_surrounding_text(self):+ """Test code fence extraction with text before and after."""+ from local_deep_research.utilities.json_utils import (+ _strip_code_fences,+ )++ text = 'Here is the JSON:\n```json\n{"a": 1}\n```\nDone!'+ assert _strip_code_fences(text) == '{"a": 1}'+++class TestExtractByBrackets:+ """Tests for _extract_by_brackets private helper."""++ def test_extract_dict_brackets(self):+ """Test extracting content between { and }."""+ from local_deep_research.utilities.json_utils import (+ _extract_by_brackets,+ )++ text = 'prefix {"key": "value"} suffix'+ result = _extract_by_brackets(text, "{", "}")+ assert result == '{"key": "value"}'++ def test_extract_list_brackets(self):+ """Test extracting content between [ and ]."""+ from local_deep_research.utilities.json_utils import (+ _extract_by_brackets,+ )++ text = "prefix [1, 2, 3] suffix"+ result = _extract_by_brackets(text, "[", "]")+ assert result == "[1, 2, 3]"++ def test_missing_open_bracket_returns_none(self):+ """Test that missing open bracket returns None."""+ from local_deep_research.utilities.json_utils import (+ _extract_by_brackets,+ )++ result = _extract_by_brackets("no brackets here}", "{", "}")+ assert result is None++ def test_missing_close_bracket_returns_none(self):+ """Test that missing close bracket returns None."""+ from local_deep_research.utilities.json_utils import (+ _extract_by_brackets,+ )++ result = _extract_by_brackets("{no close bracket", "{", "}")+ assert result is None++ def test_close_before_open_returns_none(self):+ """Test that close bracket before open returns None."""+ from local_deep_research.utilities.json_utils import (+ _extract_by_brackets,+ )++ result = _extract_by_brackets("} before {", "{", "}")+ assert result is None++ def test_nested_brackets_uses_outermost(self):+ """Test that nested brackets extract outermost pair."""+ from local_deep_research.utilities.json_utils import (+ _extract_by_brackets,+ )++ text = '{"a": {"b": 1}}'+ result = _extract_by_brackets(text, "{", "}")+ assert result == '{"a": {"b": 1}}'