Skip to content

Commit 87d01f6

Browse files
fix(research): retain evidence when extraction is empty
1 parent 3fb194a commit 87d01f6

9 files changed

Lines changed: 276 additions & 22 deletions

‎routes/research/research_routes.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -390,14 +390,20 @@ async def research_library(
390390
if search and search.lower() not in query.lower():
391391
continue
392392
sources = d.get("sources", [])
393+
stats = d.get("stats") if isinstance(d.get("stats"), dict) else {}
394+
try:
395+
analyzed_count = int(stats.get("URLs", 0) or 0)
396+
except (TypeError, ValueError):
397+
analyzed_count = 0
393398
items.append({
394399
"id": p.stem,
395400
"query": query,
396401
"category": d.get("category") or "",
397402
"source_count": len(sources),
403+
"analyzed_count": analyzed_count,
398404
"status": d.get("status", "done"),
399-
"duration": d.get("stats", {}).get("Duration", ""),
400-
"rounds": d.get("stats", {}).get("Rounds", ""),
405+
"duration": stats.get("Duration", ""),
406+
"rounds": stats.get("Rounds", ""),
401407
"started_at": d.get("started_at", 0),
402408
"completed_at": d.get("completed_at", 0),
403409
"archived": bool(d.get("archived")),

‎src/deep_research.py‎

Lines changed: 83 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -817,19 +817,75 @@ async def _fetch_and_extract(self, url: str, question: str,
817817
logger.info(f"Skipping low-quality extraction from {url}")
818818
return None
819819
return parsed
820-
# If JSON parsing fails, treat entire response as evidence
821-
return {
822-
"url": url,
823-
"title": title or page.get("title", ""),
824-
"og_image": page.get("og_image", ""),
825-
"rational": "LLM extraction (raw)",
826-
"evidence": response[:3000],
827-
"summary": response[:500],
828-
}
820+
# Preserve a substantive non-JSON reply as raw evidence. An empty
821+
# final answer is different: reasoning models can spend their whole
822+
# generation inside a stripped thinking block, which previously
823+
# created a fake finding whose summary/evidence were both empty.
824+
raw_response = str(response or "").strip()
825+
if raw_response:
826+
if is_low_quality(raw_response):
827+
logger.info(f"Skipping low-quality extraction from {url}")
828+
return None
829+
return {
830+
"url": url,
831+
"title": title or page.get("title", ""),
832+
"og_image": page.get("og_image", ""),
833+
"rational": "LLM extraction (raw)",
834+
"evidence": raw_response[:3000],
835+
"summary": raw_response[:500],
836+
}
837+
838+
logger.warning(
839+
"Structured extraction returned an empty final answer for %s; "
840+
"preserving bounded rendered-page evidence",
841+
url,
842+
)
843+
return self._rendered_page_finding(url, title, page, content)
829844
except Exception as e:
830845
logger.warning(f"LLM extraction failed for {url}: {e}")
846+
# Retrieval already succeeded. Retain a bounded excerpt so a
847+
# transient or model-specific extractor failure does not erase the
848+
# page, its attribution, and all useful input to synthesis.
849+
return self._rendered_page_finding(url, title, page, content)
850+
851+
@staticmethod
852+
def _rendered_page_finding(
853+
url: str,
854+
title: str,
855+
page: Dict,
856+
content: str,
857+
) -> Optional[Dict]:
858+
"""Build a source-grounded fallback from successfully rendered text."""
859+
rendered = str(content or "").strip()
860+
if not rendered:
831861
return None
832862

863+
evidence = rendered[:6000]
864+
if len(rendered) > 6000:
865+
last_para = evidence.rfind("\n\n")
866+
if last_para > 4800:
867+
evidence = evidence[:last_para]
868+
869+
summary = evidence[:1200]
870+
if len(evidence) > 1200:
871+
last_para = summary.rfind("\n\n")
872+
if last_para > 800:
873+
summary = summary[:last_para]
874+
875+
return {
876+
"url": url,
877+
"title": title or page.get("title", ""),
878+
"og_image": page.get("og_image", ""),
879+
"rational": (
880+
"The page rendered successfully, but the research model did "
881+
"not return a usable structured extraction. Bounded original "
882+
"page evidence was retained instead."
883+
),
884+
"evidence": evidence,
885+
"summary": summary,
886+
"extraction_mode": "rendered_page_fallback",
887+
}
888+
833889
# ------------------------------------------------------------------
834890
# SYNTHESIZE
835891
# ------------------------------------------------------------------
@@ -916,6 +972,12 @@ async def _final_report(self, question: str, report: str) -> str:
916972
max_tokens=self.max_report_tokens,
917973
timeout=180,
918974
)
975+
if not str(result or "").strip():
976+
logger.warning(
977+
"Final report model returned an empty final answer; "
978+
"keeping the source-grounded evolving report"
979+
)
980+
return report
919981

920982
# If report is too short, ask the LLM to expand it
921983
if len(result.split()) < 400:
@@ -1057,8 +1119,17 @@ def _format_findings(self, findings: List[Dict]) -> str:
10571119
title = f.get("title", "")
10581120
summary = f.get("summary", "")
10591121
evidence = f.get("evidence", "")
1060-
# Use summary if available, fall back to truncated evidence
1061-
content = summary if summary else (evidence[:1000] if evidence else "(no content)")
1122+
# Give synthesis both the extractor's conclusion and its actual
1123+
# evidence. Previously a non-empty summary silently displaced the
1124+
# evidence field, weakening source grounding even on good runs.
1125+
if evidence:
1126+
bounded_evidence = evidence[:4000]
1127+
if summary and not bounded_evidence.startswith(summary):
1128+
content = f"Summary: {summary}\n\nEvidence:\n{bounded_evidence}"
1129+
else:
1130+
content = bounded_evidence
1131+
else:
1132+
content = summary or "(no content)"
10621133
parts.append(f"**Finding {i}** — [{title}]({url})\n{content}")
10631134
return "\n\n".join(parts)
10641135

@@ -1085,6 +1156,7 @@ def get_stats(self) -> Dict:
10851156
"Rounds": self.round_count,
10861157
"Queries": len(self.queries_used),
10871158
"URLs": len(self.urls_fetched),
1159+
"Findings": len(self.findings),
10881160
"Model": self.llm_model,
10891161
}
10901162
if self.providers_used:

‎src/research_handler.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -532,7 +532,8 @@ def _extract_sources(findings: list) -> list:
532532
url = f.get("url", "")
533533
title = f.get("title", "") or url
534534
summary = f.get("summary", "") or f.get("evidence", "")
535-
if url and url not in seen and not is_low_quality(summary):
535+
rendered_fallback = f.get("extraction_mode") == "rendered_page_fallback"
536+
if url and url not in seen and (rendered_fallback or not is_low_quality(summary)):
536537
seen.add(url)
537538
entry = {"url": url, "title": title}
538539
og_img = f.get("og_image", "")
@@ -554,7 +555,8 @@ def _extract_raw_findings(findings: list) -> list:
554555
summary = f.get("summary", "")
555556
evidence = f.get("evidence", "")
556557
content = summary if summary else (evidence[:2000] if evidence else "")
557-
if url and content and not is_low_quality(content):
558+
rendered_fallback = f.get("extraction_mode") == "rendered_page_fallback"
559+
if url and content and (rendered_fallback or not is_low_quality(content)):
558560
items.append({"url": url, "title": title, "summary": content})
559561
return items
560562
except Exception as e:

‎src/visual_report.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -806,6 +806,11 @@ def _inject_images(report_html: str, images: List[str]) -> Tuple[str, int]:
806806
color: var(--text-muted); font-size: 0.75rem;
807807
margin-left: auto; flex-shrink: 0;
808808
}}
809+
.source-warning {{
810+
padding: 1rem 1.1rem; border: 1px solid #a8612a;
811+
border-radius: 10px; color: #f0b77e; background: rgba(168, 97, 42, 0.1);
812+
font-size: 0.9rem; line-height: 1.55;
813+
}}
809814
810815
/* ── Chat-about CTA ────────────────────────────────── */
811816
.chat-cta {{
@@ -1841,7 +1846,7 @@ def generate_visual_report(
18411846

18421847
# Build stats bar
18431848
stat_items = []
1844-
for key, label in [("Duration", "Duration"), ("Rounds", "Rounds"), ("Queries", "Queries"), ("URLs", "URLs Analyzed"), ("Model", "Model"), ("Search", "Search")]:
1849+
for key, label in [("Duration", "Duration"), ("Rounds", "Rounds"), ("Queries", "Queries"), ("URLs", "URLs Analyzed"), ("Findings", "Findings Retained"), ("Model", "Model"), ("Search", "Search")]:
18451850
val = stats.get(key)
18461851
if val is not None:
18471852
stat_items.append(
@@ -1878,6 +1883,15 @@ def generate_visual_report(
18781883
+ "\n".join(items)
18791884
+ "\n</div>\n</details>\n</div>"
18801885
)
1886+
elif stats.get("URLs"):
1887+
sources_html = (
1888+
'<div class="sources-panel">\n'
1889+
'<div class="source-warning"><strong>Unsourced draft:</strong> '
1890+
'pages were discovered and rendered, but no usable source extracts '
1891+
'were retained. Treat this narrative as unverified and rerun the '
1892+
'research with a working extraction model.</div>\n'
1893+
'</div>'
1894+
)
18811895

18821896
timestamp = datetime.now().strftime("%B %d, %Y at %H:%M")
18831897

‎static/js/research/jobs.js‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,8 @@ async function _syncLibrary(options = {}) {
107107
query: item.query || existing.query,
108108
status: 'done',
109109
elapsed: elapsed || existing.elapsed || 0,
110-
sourceCount: item.source_count || existing.sourceCount || 0,
110+
sourceCount: item.source_count ?? existing.sourceCount ?? 0,
111+
analyzedCount: item.analyzed_count ?? existing.analyzedCount ?? 0,
111112
thumbnail: item.thumbnail || existing.thumbnail || '',
112113
category: item.category || existing.category || '',
113114
_fromLibrary: true,
@@ -125,7 +126,8 @@ async function _syncLibrary(options = {}) {
125126
id: item.id, query: item.query, status: 'done',
126127
progress: {}, startedAt: (item.started_at || 0) * 1000,
127128
elapsed, result: null, sources: null, findings: null,
128-
sourceCount: item.source_count || 0,
129+
sourceCount: item.source_count ?? 0,
130+
analyzedCount: item.analyzed_count ?? 0,
129131
thumbnail: item.thumbnail || '',
130132
category: item.category || '',
131133
errorMsg: null, avgDuration: null, modelName: null,
@@ -198,6 +200,8 @@ export async function retryJob(jobId) {
198200
job.result = null;
199201
job.sources = null;
200202
job.findings = null;
203+
job.sourceCount = 0;
204+
job.analyzedCount = 0;
201205
job.elapsed = 0;
202206
job.avgDuration = null;
203207
_notify();
@@ -262,6 +266,7 @@ function _makeJob(query, settings) {
262266
query, settings, status: 'queued',
263267
progress: {}, startedAt: null, elapsed: 0,
264268
result: null, sources: null, findings: null,
269+
analyzedCount: 0,
265270
category: settings?.category || '',
266271
errorMsg: null, avgDuration: null,
267272
modelName: null, endpointName: null,

‎static/js/research/panel.js‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -985,14 +985,20 @@ function _buildJobCard(job) {
985985
// Library-loaded jobs have sources=null but pre-set sourceCount; fresh jobs
986986
// populate sources directly. Prefer the pre-set count if present.
987987
const srcCount = job.sources?.length ?? job.sourceCount ?? 0;
988-
// 0 sources = the research couldn't gather/extract anything — flag it.
988+
const analyzedCount = job.analyzedCount || job.progress?.total_sources || 0;
989+
// Distinguish discovery failure from extraction failure. The old card told
990+
// users to switch search engines even when Firecrawl had rendered dozens
991+
// of pages and the research model alone returned no usable extracts.
989992
const failed = srcCount === 0;
993+
const extractionFailed = failed && analyzedCount > 0;
990994
if (failed) card.classList.add('research-job-failed');
991995
const doneBadge = failed
992-
? `<span class="research-cat-badge research-cat-failed">${_cancelIcon} no results</span>`
996+
? `<span class="research-cat-badge research-cat-failed">${_cancelIcon} ${extractionFailed ? 'extraction failed' : 'no results'}</span>`
993997
: (job.category ? `<span class="research-cat-badge">${_esc(job.category)}</span>` : `<span class="research-cat-badge research-cat-standard">standard</span>`);
994998
const failNote = failed
995-
? `<div class="research-job-failnote">Couldn't extract anything — try rephrasing the question, or switch the search engine in Settings.</div>`
999+
? `<div class="research-job-failnote">${extractionFailed
1000+
? `Found and rendered ${analyzedCount} page${analyzedCount === 1 ? '' : 's'}, but the research model returned no usable source extracts. Rerun after changing the research model or extraction settings.`
1001+
: `Search returned no pages. Try rephrasing the question or switch the search engine in Settings.`}</div>`
9961002
: '';
9971003
const thumbSource = (job.sources || []).find(s => s && (s.image || s.og_image));
9981004
const thumbUrl = job.thumbnail || thumbSource?.image || thumbSource?.og_image || '';
@@ -1003,7 +1009,7 @@ function _buildJobCard(job) {
10031009
<div class="research-job-header">
10041010
<span class="research-job-query">${_esc(job.query)}</span>${doneBadge}
10051011
${modelTag}
1006-
<span class="research-job-meta">${elapsed} -- ${srcCount} sources</span>
1012+
<span class="research-job-meta">${elapsed} -- ${srcCount} sources${failed && analyzedCount ? ` -- ${analyzedCount} pages rendered` : ''}</span>
10071013
</div>
10081014
${failNote}
10091015
<div class="research-job-actions">

‎tests/test_deep_research_extraction_controls.py‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import pytest
88

99
from src.deep_research import DeepResearcher
10+
from src.research_handler import ResearchHandler
1011

1112

1213
class _ControlledResearcher(DeepResearcher):
@@ -231,6 +232,104 @@ async def fake_llm(messages, **kwargs):
231232
assert calls == ["firecrawl", "native"]
232233

233234

235+
@pytest.mark.asyncio
236+
async def test_empty_extractor_answer_preserves_rendered_page_evidence(monkeypatch):
237+
search_mod = types.ModuleType("src.search")
238+
search_mod.firecrawl_scrape = lambda url, timeout: {
239+
"success": True,
240+
"content": "# Model card\n\nVerified benchmark details from the rendered page.",
241+
"title": "Rendered model card",
242+
"og_image": "",
243+
}
244+
search_mod.fetch_webpage_content = lambda *args, **kwargs: pytest.fail(
245+
"native fetch must not run after a successful Firecrawl scrape"
246+
)
247+
monkeypatch.setitem(sys.modules, "src.search", search_mod)
248+
249+
async def immediate_to_thread(fn, *args, **kwargs):
250+
return fn(*args, **kwargs)
251+
252+
monkeypatch.setattr(asyncio, "to_thread", immediate_to_thread)
253+
researcher = DeepResearcher(
254+
llm_endpoint="http://local.test/v1/chat/completions",
255+
llm_model="thinking-only-model",
256+
search_provider="firecrawl",
257+
)
258+
259+
async def empty_final_answer(*args, **kwargs):
260+
return ""
261+
262+
researcher._llm = empty_final_answer
263+
result = await researcher._fetch_and_extract(
264+
"https://example.test/model", "compare models", "",
265+
)
266+
267+
assert result["url"] == "https://example.test/model"
268+
assert result["title"] == "Rendered model card"
269+
assert result["extraction_mode"] == "rendered_page_fallback"
270+
assert "Verified benchmark details" in result["summary"]
271+
assert "Verified benchmark details" in result["evidence"]
272+
assert ResearchHandler._extract_sources([result]) == [{
273+
"url": "https://example.test/model",
274+
"title": "Rendered model card",
275+
}]
276+
assert ResearchHandler._extract_raw_findings([result])[0]["url"] == (
277+
"https://example.test/model"
278+
)
279+
280+
281+
@pytest.mark.asyncio
282+
async def test_extractor_exception_preserves_rendered_page_evidence(monkeypatch):
283+
search_mod = types.ModuleType("src.search")
284+
search_mod.firecrawl_scrape = lambda url, timeout: {
285+
"success": True,
286+
"content": "Rendered evidence survives a model timeout.",
287+
"title": "Source",
288+
"og_image": "",
289+
}
290+
search_mod.fetch_webpage_content = lambda *args, **kwargs: pytest.fail(
291+
"native fetch must not run after a successful Firecrawl scrape"
292+
)
293+
monkeypatch.setitem(sys.modules, "src.search", search_mod)
294+
295+
async def immediate_to_thread(fn, *args, **kwargs):
296+
return fn(*args, **kwargs)
297+
298+
monkeypatch.setattr(asyncio, "to_thread", immediate_to_thread)
299+
researcher = DeepResearcher(
300+
llm_endpoint="http://local.test/v1/chat/completions",
301+
llm_model="timeout-model",
302+
search_provider="firecrawl",
303+
)
304+
305+
async def timeout(*args, **kwargs):
306+
raise TimeoutError("model timed out")
307+
308+
researcher._llm = timeout
309+
result = await researcher._fetch_and_extract(
310+
"https://example.test/source", "question", "",
311+
)
312+
313+
assert result["extraction_mode"] == "rendered_page_fallback"
314+
assert result["summary"] == "Rendered evidence survives a model timeout."
315+
316+
317+
def test_format_findings_keeps_summary_and_evidence():
318+
researcher = DeepResearcher(
319+
llm_endpoint="http://local.test/v1/chat/completions",
320+
llm_model="local-model",
321+
)
322+
rendered = researcher._format_findings([{
323+
"url": "https://example.test/source",
324+
"title": "Source",
325+
"summary": "Concise conclusion.",
326+
"evidence": "Detailed benchmark evidence.",
327+
}])
328+
329+
assert "Concise conclusion." in rendered
330+
assert "Detailed benchmark evidence." in rendered
331+
332+
234333
def test_extraction_timeout_allows_long_local_model_runs():
235334
researcher = DeepResearcher(
236335
llm_endpoint="http://local.test/v1/chat/completions",

0 commit comments

Comments
 (0)