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.

Fix AttributeError on list-type LLM content (recovered from #4628) (#4644)

LearningCircuitc5a09daec638
diff --git a/changelog.d/+list-content-block-extraction.bugfix.md b/changelog.d/+list-content-block-extraction.bugfix.md
new file mode 100644
index 0000000000..9e099a3777
--- /dev/null
+++ b/changelog.d/+list-content-block-extraction.bugfix.md
@@ -0,0 +1 @@
+`get_llm_response_text` now extracts the text from list-type LLM content blocks (Anthropic extended-thinking / tool-use responses, where `message.content` is a list of blocks) instead of stringifying the list to its Python `repr`. This fixes garbled entity, sub-query, and candidate parsing, and stops direct `.content` consumers from crashing on list content.
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 479e270642..ed60a31fda 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
@@ -15,6 +15,7 @@ from loguru import logger
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint
+from ...utilities.json_utils import get_llm_response_text
class ExplorationStrategy(Enum):
@@ -205,7 +206,7 @@ Give me multiple possible answers, one per line:
try:
response = self.model.invoke(prompt)
- content = response.content.strip()
+ content = get_llm_response_text(response)
# Parse multiple answers
answers = []
@@ -246,7 +247,7 @@ Names:
"""
try:
- response = self.model.invoke(prompt).content.strip()
+ response = get_llm_response_text(self.model.invoke(prompt))
# Parse response into names
names = []
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 31a26c0cb1..d521e5e35f 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
@@ -11,6 +11,8 @@ from loguru import logger
from langchain_core.language_models.chat_models import BaseChatModel
+from ...utilities.json_utils import get_llm_response_text
+
class FollowUpContextHandler:
"""
@@ -155,7 +157,7 @@ Return up to 10 most important entities, one per line.
response = self.model.invoke(prompt)
entities = [
line.strip()
- for line in response.content.strip().split("\n")
+ for line in get_llm_response_text(response).split("\n")
if line.strip()
]
return entities[:10]
@@ -293,7 +295,7 @@ Create a summary of {max_sentences} sentences that captures the most relevant in
try:
response = self.model.invoke(prompt)
- summary = response.content.strip()
+ summary = get_llm_response_text(response)
# Apply length constraint if specified
if max_length and len(summary) > max_length:
@@ -340,7 +342,7 @@ What specific information is missing or needs clarification? List up to 5 gaps,
response = self.model.invoke(prompt)
gaps = [
line.strip()
- for line in response.content.strip().split("\n")
+ for line in get_llm_response_text(response).split("\n")
if line.strip()
]
return gaps[:5]
diff --git a/src/local_deep_research/advanced_search_system/questions/decomposition_question.py b/src/local_deep_research/advanced_search_system/questions/decomposition_question.py
index 9df63b7c2e..f232652d91 100644
--- a/src/local_deep_research/advanced_search_system/questions/decomposition_question.py
+++ b/src/local_deep_research/advanced_search_system/questions/decomposition_question.py
@@ -4,6 +4,7 @@ from langchain_core.language_models import BaseLLM
from loguru import logger
from .base_question import BaseQuestionGenerator
+from ...utilities.json_utils import get_llm_response_text
class DecompositionQuestionGenerator(BaseQuestionGenerator):
@@ -132,13 +133,9 @@ What are the security implications of X?
# Get response from LLM
response = self.model.invoke(prompt)
- # Handle different response formats (string or object with content attribute)
- sub_queries_text = ""
- if hasattr(response, "content"):
- sub_queries_text = response.content.strip()
- else:
- # Handle string responses
- sub_queries_text = str(response).strip()
+ # Handle different response formats (string or object with content
+ # attribute, including list-form content blocks) via coercion.
+ sub_queries_text = get_llm_response_text(response)
# Check for the common "No language models available" error
if (
@@ -252,12 +249,9 @@ Sub-questions:
simple_response = self.model.invoke(simple_prompt)
- # Handle different response formats
- simple_text = ""
- if hasattr(simple_response, "content"):
- simple_text = simple_response.content.strip()
- else:
- simple_text = str(simple_response).strip()
+ # Handle different response formats (including list-form
+ # content blocks) via coercion.
+ simple_text = get_llm_response_text(simple_response)
# Check again for language model errors
if (
diff --git a/src/local_deep_research/utilities/json_utils.py b/src/local_deep_research/utilities/json_utils.py
index 66b6a75a48..12d762113a 100644
--- a/src/local_deep_research/utilities/json_utils.py
+++ b/src/local_deep_research/utilities/json_utils.py
@@ -17,7 +17,9 @@ 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.
+ list-type content blocks (Anthropic extended-thinking / tool-use, where
+ ``.content`` is a list of blocks), and arbitrary objects (via str()).
+ Removes <think> tags from the output.
Args:
response: LLM response object, string, or None.
@@ -33,11 +35,47 @@ def get_llm_response_text(response) -> str:
raw = response.text
else:
raw = str(response)
+ if isinstance(raw, list):
+ # Anthropic-style content blocks, e.g.
+ # [{"type": "text", "text": "..."}, {"type": "tool_use", ...}].
+ # Extract and join the text so downstream string ops get clean text
+ # rather than the list's Python repr (the #4615 data-corruption bug).
+ raw = _coerce_content_blocks(raw)
if not isinstance(raw, str):
raw = str(raw)
return _remove_think_tags(raw)
+def _coerce_content_blocks(blocks: list) -> str:
+ """Join the text from a list of LLM content blocks into a plain string.
+
+ Some providers (notably Anthropic, and some LangChain paths) return
+ ``message.content`` as a list of blocks rather than a string — for
+ example ``[{"type": "text", "text": "Paris"}, {"type": "tool_use", ...}]``.
+ Keep only the textual parts; skip non-text blocks (tool_use, thinking,
+ etc.) so callers that then ``.strip()`` / ``.split()`` operate on real
+ text instead of the list's ``repr()``.
+
+ Accepts blocks that are plain strings, dicts with a ``"text"`` key (when
+ ``type`` is ``"text"`` or unset), or objects exposing a ``.text`` str
+ attribute. Returns ``""`` for an empty/textless list.
+ """
+ parts: list[str] = []
+ for block in blocks:
+ if isinstance(block, str):
+ parts.append(block)
+ elif isinstance(block, dict):
+ if block.get("type", "text") == "text" and isinstance(
+ block.get("text"), str
+ ):
+ parts.append(block["text"])
+ else:
+ text_attr = getattr(block, "text", None)
+ if isinstance(text_attr, str):
+ parts.append(text_attr)
+ return "".join(parts)
+
+
def extract_json(
text: str,
expected_type: Optional[Type] = None,
diff --git a/tests/advanced_search_system/test_list_content_coercion.py b/tests/advanced_search_system/test_list_content_coercion.py
new file mode 100644
index 0000000000..6b57b79eda
--- /dev/null
+++ b/tests/advanced_search_system/test_list_content_coercion.py
@@ -0,0 +1,227 @@
+"""
+Regression tests for issue #4615.
+
+Several call sites consumed ``response.content`` directly and called string
+methods (``.strip()``, ``.split()``, ``len()``) on it. When a provider returns
+content in LIST form (Anthropic content blocks from extended-thinking/tool-use),
+this raised AttributeError/TypeError. The fix routes those reads through
+``get_llm_response_text``, which coerces non-string content to a string.
+
+These tests build fake responses whose ``.content`` is a LIST (simulating
+Anthropic content blocks) and confirm the corrected sites no longer raise and
+return the expected string.
+"""
+
+from unittest.mock import Mock
+
+
+def _list_content_response(text):
+ """Build a fake LLM response with Anthropic-style list content blocks."""
+ response = Mock()
+ response.content = [{"type": "text", "text": text}]
+ return response
+
+
+class TestGetLLMResponseTextBlocks:
+ """Root-cause regression for #4615: get_llm_response_text must EXTRACT the
+ text from list-type content blocks, not stringify the list to its repr.
+
+ These assert *clean* extraction (exact equality), so they fail against the
+ old ``str(raw)`` behavior — which returned ``"[{'type': 'text', ...}]"``.
+ """
+
+ def _msg(self, content):
+ response = Mock()
+ response.content = content
+ return response
+
+ def test_single_text_block_extracted_clean(self):
+ from local_deep_research.utilities.json_utils import (
+ get_llm_response_text,
+ )
+
+ out = get_llm_response_text(
+ self._msg([{"type": "text", "text": "Paris"}])
+ )
+ assert out == "Paris"
+ assert "'type'" not in out and "[{" not in out # no repr leakage
+
+ def test_newlines_preserved_so_split_works(self):
+ from local_deep_research.utilities.json_utils import (
+ get_llm_response_text,
+ )
+
+ out = get_llm_response_text(
+ self._msg([{"type": "text", "text": "A\nB\nC"}])
+ )
+ # The #4615 corruption turned "\n" into literal "\\n", collapsing splits.
+ assert out.split("\n") == ["A", "B", "C"]
+
+ def test_multiple_text_blocks_joined(self):
+ from local_deep_research.utilities.json_utils import (
+ get_llm_response_text,
+ )
+
+ out = get_llm_response_text(
+ self._msg(
+ [
+ {"type": "text", "text": "Hello "},
+ {"type": "text", "text": "world"},
+ ]
+ )
+ )
+ assert out == "Hello world"
+
+ def test_tool_use_block_skipped(self):
+ from local_deep_research.utilities.json_utils import (
+ get_llm_response_text,
+ )
+
+ out = get_llm_response_text(
+ self._msg(
+ [
+ {"type": "text", "text": "answer"},
+ {"type": "tool_use", "name": "search", "input": {"q": "x"}},
+ ]
+ )
+ )
+ assert out == "answer"
+
+ def test_empty_list_returns_empty_string(self):
+ from local_deep_research.utilities.json_utils import (
+ get_llm_response_text,
+ )
+
+ assert get_llm_response_text(self._msg([])) == ""
+
+ def test_plain_string_content_unchanged(self):
+ from local_deep_research.utilities.json_utils import (
+ get_llm_response_text,
+ )
+
+ # String content must pass straight through (block coercion only
+ # applies to list content); no leading/trailing space to avoid the
+ # helper's existing strip behavior masking the check.
+ assert get_llm_response_text(self._msg("hello world")) == "hello world"
+
+
+class TestFollowUpContextManagerListContent:
+ """followup_context_manager.py sites (issue #4615)."""
+
+ def _handler(self, text):
+ from local_deep_research.advanced_search_system.knowledge.followup_context_manager import (
+ FollowUpContextHandler,
+ )
+
+ model = Mock()
+ model.invoke.return_value = _list_content_response(text)
+ return FollowUpContextHandler(model)
+
+ def test_extract_entities_does_not_raise_on_list_content(self):
+ handler = self._handler("Paris")
+ research_data = {
+ "formatted_findings": "Some prior findings about Paris."
+ }
+
+ entities = handler._extract_entities(research_data)
+
+ assert isinstance(entities, list)
+ # Coerced content preserves the underlying text — cleanly, not as the
+ # list's repr (the #4615 data-corruption regression).
+ assert "Paris" in entities
+ assert not any("'type'" in e or "[{" in e for e in entities)
+
+ def test_generate_summary_does_not_raise_on_list_content(self):
+ handler = self._handler("A concise summary.")
+
+ summary = handler._generate_summary(
+ findings="x" * 5000, # long enough to trigger an LLM call
+ query="follow-up question",
+ )
+
+ assert isinstance(summary, str)
+ assert "A concise summary." in summary
+ assert "'type'" not in summary and "[{" not in summary
+
+ def test_identify_gaps_does_not_raise_on_list_content(self):
+ handler = self._handler("Missing detail about funding.")
+ research_data = {"formatted_findings": "Some prior findings."}
+
+ gaps = handler.identify_gaps(research_data, "follow-up question")
+
+ assert isinstance(gaps, list)
+ assert any("funding" in gap for gap in gaps)
+ assert not any("'type'" in g or "[{" in g for g in gaps)
+
+
+class TestDecompositionQuestionListContent:
+ """decomposition_question.py sites (issue #4615)."""
+
+ def test_generate_questions_does_not_raise_on_list_content(self):
+ from local_deep_research.advanced_search_system.questions.decomposition_question import (
+ DecompositionQuestionGenerator,
+ )
+
+ model = Mock()
+ model.invoke.return_value = _list_content_response(
+ "What is X?\nHow does X work?\nWhy is X important?"
+ )
+ generator = DecompositionQuestionGenerator(model)
+
+ questions = generator.generate_questions("X technology", context="")
+
+ assert isinstance(questions, list)
+ # Non-tautological: the pre-fix path crashes and falls back to generic
+ # default questions, so the LLM's actual questions would be absent and
+ # the repr ("'type'") would leak. Both checks fail on the old behavior.
+ assert any("How does X work?" in q for q in questions)
+ assert not any("'type'" in q or "[{" in q for q in questions)
+
+
+class TestBaseExplorerListContent:
+ """base_explorer.py sites (issue #4615)."""
+
+ def _explorer(self, text):
+ from local_deep_research.advanced_search_system.candidate_exploration.base_explorer import (
+ BaseCandidateExplorer,
+ )
+
+ class _TestExplorer(BaseCandidateExplorer):
+ def explore(
+ self, initial_query, constraints=None, entity_type=None
+ ):
+ pass
+
+ def generate_exploration_queries(
+ self, base_query, found_candidates, constraints=None
+ ):
+ return []
+
+ model = Mock()
+ model.invoke.return_value = _list_content_response(text)
+ return _TestExplorer(
+ model=model,
+ search_engine=Mock(),
+ max_candidates=50,
+ max_search_time=60.0,
+ )
+
+ def test_generate_answer_candidates_does_not_raise_on_list_content(self):
+ explorer = self._explorer("Alice Smith")
+
+ answers = explorer._generate_answer_candidates(
+ "Who discovered X?", "search content"
+ )
+
+ assert isinstance(answers, list)
+ assert "Alice Smith" in answers
+ assert not any("'type'" in a or "[{" in a for a in answers)
+
+ def test_extract_entity_names_does_not_raise_on_list_content(self):
+ explorer = self._explorer("Marie Curie")
+
+ names = explorer._extract_entity_names("Some text with a name.")
+
+ assert isinstance(names, list)
+ assert "Marie Curie" in names
+ assert not any("'type'" in n or "[{" in n for n in names)
diff --git a/tests/utilities/test_json_utils_real_world.py b/tests/utilities/test_json_utils_real_world.py
index 245daeb957..ba5cc1fdde 100644
--- a/tests/utilities/test_json_utils_real_world.py
+++ b/tests/utilities/test_json_utils_real_world.py
@@ -71,7 +71,8 @@ class TestContentAttributeFormats:
def test_content_attribute_is_list_of_content_blocks(self):
"""LangChain multimodal AIMessage can have content as a list of blocks.
- get_llm_response_text should convert this to a string."""
+ get_llm_response_text extracts the text from the text blocks (joining
+ them, dropping non-text blocks like image_url) — not the list repr."""
class FakeMessage:
content = [
@@ -80,11 +81,11 @@ class TestContentAttributeFormats:
]
text = get_llm_response_text(FakeMessage())
- # content is a list (not str), so it gets converted via str()
- assert isinstance(text, str)
- # The string representation should contain the JSON
- assert "key" in text
- assert "value" in text
+ # The text block is extracted cleanly; the image_url block is dropped.
+ assert text == '{"key": "value"}'
+ # Not the list's Python repr, and no non-text block content leaks.
+ assert "image_url" not in text
+ assert "data:" not in text
class TestBracketMismatchEdgeCases: