~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
fix(latex): export a saved report's citation links as \cite (#6831)
Lukas54130f57f290
diff --git a/changelog.d/6831.bugfix.md b/changelog.d/6831.bugfix.mdnew file mode 100644index 0000000000..e410a48599--- /dev/null+++ b/changelog.d/6831.bugfix.md@@ -0,0 +1 @@+LaTeX export now writes a saved report's linked citations as `\cite{N}`. Before, the default numbered format came out as `[\cite{1}](https://…)` and the domain and source-tagged formats as raw markdown links; a link in those formats now becomes `\cite{N}` when its URL matches a Sources entry. A group such as `[2, 3]` becomes one `\cite{2,3}` when the Sources list every member, and is otherwise left as written.diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.pyindex d4b77db5e9..ccadc017f8 100644--- a/src/local_deep_research/text_optimization/citation_formatter.py+++ b/src/local_deep_research/text_optimization/citation_formatter.py@@ -2,6 +2,7 @@import htmlimport re+from array import arrayfrom enum import Enumfrom typing import Any, Dict, List, Optional, Tuplefrom urllib.parse import urlparse, urlsplit@@ -1897,12 +1898,51 @@ def _split_math_segments(text: str) -> list[tuple[str, bool]]:return segments+# The start of a citation link as CitationFormatter writes it: the label+# in double brackets, then the destination. Every hyperlinked mode uses this+# shape; only the label differs ([[1]], [[arxiv.org]], [[arxiv.org-2]],+# [[doi-1]]).+_CITATION_LINK_START_RE = re.compile(r"\[\[([^\[\]\n]+)\]\]\(")+_CITATION_GROUP_LABEL_RE = re.compile(r"\s*\d+(?:,\s*\d+)+\s*")+++def _link_destination_ends(text: str) -> array:+ """For every index, where a link destination starting there ends.++ ``_safe_link_destination`` percent-encodes spaces and any unbalanced+ parenthesis, so a destination it wrote ends at the first ``)`` that+ closes no ``(`` of its own, as in ``https://en.wikipedia.org/wiki/A_(b)``.+ ``ends[i]`` is the index of that ``)`` for a destination starting at+ ``i``, or -1 when whitespace or the end of the text comes first.++ One pass from the right answers every start at once. Scanning forward+ from each ``[[a]](`` instead costs quadratic time on a text full of+ destinations that never close: 20 000 of them took about 40 seconds.+ """+ ends = array("q", [-1]) * (len(text) + 1)+ for position in range(len(text) - 1, -1, -1):+ character = text[position]+ if character == ")":+ ends[position] = position+ elif character == "(":+ # This parenthesis is closed where a destination starting just+ # after it would end; the destination then carries on from there.+ inner = ends[position + 1]+ ends[position] = -1 if inner == -1 else ends[inner + 1]+ elif not character.isspace():+ ends[position] = ends[position + 1]+ return ends++class LaTeXExporter:"""Export markdown documents to LaTeX format."""def __init__(self):# Also match Unicode lenticular brackets 【】 (U+3010 and U+3011) that LLMs sometimes generateself.citation_pattern = re.compile(r"[\[【](\d+)[\]】]")+ self.comma_citation_pattern = re.compile(+ r"[\[【](\d+(?:,\s*\d+)+)[\]】]"+ )self.heading_patterns = [(re.compile(r"^# (.+)$", re.MULTILINE), r"\\section{\1}"),(re.compile(r"^## (.+)$", re.MULTILINE), r"\\subsection{\1}"),@@ -1926,8 +1966,10 @@ class LaTeXExporter:"""latex_content = self._create_latex_header()- # Convert markdown to LaTeX- body_content = content+ # Convert markdown to LaTeX. A saved report was citation-formatted+ # before it was stored, so its citations arrive as links.+ entries = self._sources_entries(content)+ body_content = self._unlink_citations(content, entries)# Escape special LaTeX characters but preserve math mode. A# left-to-right scanner pairs $$...$$ display spans and $...$@@ -1978,6 +2020,16 @@ class LaTeXExporter:body_content = pattern.sub(replacement, body_content)# Convert citations to LaTeX \cite{} format+ # A group becomes one \\cite only when the Sources section lists every+ # member, as CitationFormatter only links the members it can resolve;+ # otherwise it is prose such as "versions [4, 5]" and is left as written.+ def cite_group(match: re.Match[str]) -> str:+ nums = [num.strip() for num in match.group(1).split(",")]+ if all(num in entries for num in nums):+ return "\\cite{" + ",".join(nums) + "}"+ return match.group(0)++ body_content = self.comma_citation_pattern.sub(cite_group, body_content)body_content = self.citation_pattern.sub(r"\\cite{\1}", body_content)# Convert lists@@ -1994,6 +2046,63 @@ class LaTeXExporter:return latex_content+ def _sources_entries(self, content: str) -> dict:+ """The Sources entries, from the same slice the bibliography reads."""+ sources_start, _on_sentinel = find_sources_section(content)+ if sources_start == -1:+ return {}+ return _collect_bibliography_entries(content[sources_start:])++ def _unlink_citations(self, content: str, entries: dict) -> str:+ """Turn the formatter's ``[[label]](url)`` citations back into ``[N]``.++ A number label is the citation index. A group label such as ``1, 2``+ names every member, which its one URL cannot, so it becomes ``[1, 2]``+ when the Sources list has every member. Any other label+ (``arxiv.org``, ``arxiv.org-2``, ``doi-1``) says nothing reliable+ about the index, so the link's destination is looked up among the+ Sources entries instead; when two entries share a URL, the lower+ index is used, since both name the same document. A link that+ resolves to no entry is left as written.+ """+ # Keyed on the destination the formatter would have written. Two URLs+ # that differ only in how a character is spelled, such as `a(b` and+ # `a%28b`, share a key, and the lower index keeps it.+ index_by_destination: Dict[str, str] = {}+ for index in sorted(entries, key=_sort_key):+ destination = _safe_link_destination(entries[index][1])+ if destination:+ index_by_destination.setdefault(destination, index)++ parts = []+ position = 0+ ends = None+ for match in _CITATION_LINK_START_RE.finditer(content):+ if match.start() < position:+ continue+ if ends is None:+ ends = _link_destination_ends(content)+ end = ends[match.end()]+ if end == -1:+ continue+ label = match.group(1)+ if label.isdecimal():+ index = label+ elif _CITATION_GROUP_LABEL_RE.fullmatch(label):+ members = [member.strip() for member in label.split(",")]+ if not all(member in entries for member in members):+ continue+ index = label.strip()+ else:+ index = index_by_destination.get(content[match.end() : end])+ if index is None:+ continue+ parts.append(content[position : match.start()])+ parts.append(f"[{index}]")+ position = end + 1+ parts.append(content[position:])+ return "".join(parts)+def _create_latex_header(self) -> str:"""Create LaTeX document header."""return r"""\documentclass[12pt]{article}diff --git a/tests/text_optimization/test_citation_formatter_contracts.py b/tests/text_optimization/test_citation_formatter_contracts.pyindex e071b17ef6..06d8f48ee8 100644--- a/tests/text_optimization/test_citation_formatter_contracts.py+++ b/tests/text_optimization/test_citation_formatter_contracts.py@@ -306,19 +306,6 @@ class TestRoundTripCitationIdentity:assert "ID - ref2\nTI - Beta Blog\n" in risassert "UR - https://beta.example/post\n" in ris- @pytest.mark.xfail(- strict=True,- reason=(- "DEFECT: LaTeXExporter.citation_pattern lacks the "- "(?<![\\[\u3010]) / (?![\\]\u3011]) guards that "- "CitationFormatter and QuartoExporter both carry, so the "- "inner [1] of an already-formatted [[1]](url) becomes "- "\\cite{1} and the export reads "- "'[\\cite{1}](https://...)'. Live: research_service formats "- "the report before persisting it and the export route feeds "- "the persisted (formatted) markdown to export_to_latex."- ),- )def test_latex_export_of_a_formatted_report_keeps_the_link_intact(self):formatted = CitationFormatter(CitationMode.NUMBER_HYPERLINKSdiff --git a/tests/text_optimization/test_latex_citation_links.py b/tests/text_optimization/test_latex_citation_links.pynew file mode 100644index 0000000000..f06038b7e0--- /dev/null+++ b/tests/text_optimization/test_latex_citation_links.py@@ -0,0 +1,264 @@+"""LaTeX export of a report whose citations are already links.++``research_service`` citation-formats a report before storing it, and the+export route hands that stored markdown to ``LaTeXExporter``. So in every+hyperlinked citation mode the exporter receives ``[[label]](url)`` links+rather than the ``[N]`` brackets it turns into ``\\cite{N}``. These+contracts pin that each such link becomes the ``\\cite`` of the source it+points at, whatever its label.++They pin the generated ``.tex`` only and do not need a TeX installation.+"""++from __future__ import annotations++import random+import time++import pytest++from local_deep_research.text_optimization import citation_formatter+from local_deep_research.text_optimization.citation_formatter import (+ CitationFormatter,+ CitationMode,+ LaTeXExporter,+ _link_destination_ends,+)++SOURCES = (+ "[1] Alpha Paper\nURL: https://arxiv.org/abs/2401.00001\n\n"+ "[2] Beta Paper\nURL: https://arxiv.org/abs/2401.00002\n\n"+ "[3] Gamma Blog\nURL: https://gamma.example/post\n\n"+ "[4] Foo (bar)\nURL: https://en.wikipedia.org/wiki/Foo_(bar)\n"+)++LINKED_MODES = [+ mode for mode in CitationMode if mode is not CitationMode.NO_HYPERLINKS+]+++def report(body: str, sources: str = SOURCES) -> str:+ """Assemble the report shape the formatter and the exporter expect."""+ return f"# Research Report\n\n{body}\n\n## Sources\n\n{sources}"+++def exported_answer(markdown: str) -> str:+ """Return the first body line of the export, the answer paragraph."""+ latex = LaTeXExporter().export_to_latex(markdown)+ body = latex[latex.index("\\section{Research Report}") :]+ return body.splitlines()[2]+++class TestSavedReportCitations:+ """A formatted citation link must come out as ``\\cite{N}``."""++ @pytest.mark.parametrize("mode", LINKED_MODES, ids=lambda mode: mode.value)+ def test_every_linked_mode_exports_its_citations_as_cite(self, mode):+ saved = CitationFormatter(mode).format_document(+ report("Claims [1] and [2, 3]. Wikipedia agrees [4].")+ )+ assert "]](https://" in saved # the stored report carries links++ assert exported_answer(saved) == (+ "Claims \\cite{1} and \\cite{2}\\cite{3}. "+ "Wikipedia agrees \\cite{4}."+ )++ def test_a_number_label_needs_no_sources_block(self):+ markdown = "# Research Report\n\nSee [[7]](https://seven.example/a).\n"++ assert exported_answer(markdown) == "See \\cite{7}."++ def test_two_sources_sharing_a_url_cite_the_lower_index(self):+ sources = (+ "[5] Beta Paper again\nURL: https://beta.example/p\n\n"+ "[2] Beta Paper\nURL: https://beta.example/p\n"+ )+ markdown = report(+ "See [[beta.example]](https://beta.example/p).", sources+ )++ assert exported_answer(markdown) == "See \\cite{2}."++ def test_a_link_that_names_no_source_is_left_as_written(self):+ markdown = report(+ "See [[elsewhere.example]](https://elsewhere.example/p)."+ )++ assert exported_answer(markdown) == (+ "See [[elsewhere.example]](https://elsewhere.example/p)."+ )++ def test_an_empty_destination_names_no_source(self):+ markdown = report("See [[doc]]().", "[1] Real Local Document\n")++ assert exported_answer(markdown) == "See [[doc]]()."++ def test_a_link_resolves_only_through_the_sources_section(self):+ # The bibliography is built from the Sources section alone, so a+ # Sources-shaped line in the answer must not bind a link to key 1.+ markdown = (+ "# Research Report\n\n"+ "See [[evil.example]](https://evil.example/poison).\n\n"+ "[1] Attacker Controlled Entry\n"+ "URL: https://evil.example/poison\n\n"+ "## Sources\n\n"+ "[1] Real Local Document\n"+ )++ assert exported_answer(markdown) == (+ "See [[evil.example]](https://evil.example/poison)."+ )++ def test_a_url_holding_a_citation_shaped_fragment_is_read_once(self):+ sources = "[1] Search\nURL: https://search.example/?q=[[2]](x)\n"+ markdown = report(+ "See [[search.example]](https://search.example/?q=[[2]](x)).",+ sources,+ )++ assert exported_answer(markdown) == "See \\cite{1}."++ def test_brackets_before_parenthesised_prose_are_not_a_link(self):+ # A destination cannot contain a space, so this is text, not a link.+ markdown = report("Table [[7]](see below) lists them.")++ assert exported_answer(markdown) == (+ "Table [\\cite{7}](see below) lists them."+ )++ def test_a_prose_link_is_left_as_written(self):+ markdown = report("See [the paper](https://arxiv.org/abs/2401.00001).")++ assert exported_answer(markdown) == (+ "See [the paper](https://arxiv.org/abs/2401.00001)."+ )++ def test_the_bibliography_is_the_same_as_for_the_plain_report(self):+ plain = report("Claims [1] and [2, 3]. Wikipedia agrees [4].")+ saved = CitationFormatter(+ CitationMode.DOMAIN_ID_HYPERLINKS+ ).format_document(plain)++ def bibliography(markdown: str) -> str:+ latex = LaTeXExporter().export_to_latex(markdown)+ return latex[latex.index("\\begin{thebibliography}") :]++ assert bibliography(saved) == bibliography(plain)+++class TestLinkDestinationScan:+ """Where a link destination ends, found in linear time."""++ @staticmethod+ def scan_from(text: str, start: int) -> int:+ """The per-start scan the one-pass table replaces, as a reference."""+ depth = 0+ for position in range(start, len(text)):+ character = text[position]+ if character.isspace():+ return -1+ if character == "(":+ depth += 1+ elif character == ")":+ if depth == 0:+ return position+ depth -= 1+ return -1++ def test_the_table_agrees_with_a_scan_from_every_start(self):+ rng = random.Random(42)+ for _ in range(300):+ text = "".join(+ rng.choice("()ab ") for _ in range(rng.randrange(40))+ )+ ends = _link_destination_ends(text)+ assert [ends[i] for i in range(len(text))] == [+ self.scan_from(text, i) for i in range(len(text))+ ], text++ @pytest.mark.parametrize("where", ["answer", "sources"])+ def test_unclosed_link_starts_stay_fast(self, where):+ # A destination that never closes, 20 000 times, with no whitespace+ # to end the search: a scan per start took about 40 seconds.+ unclosed = "[[a]](b" * 20000+ if where == "answer":+ markdown = report(unclosed)+ else:+ markdown = report(+ "See [1].", f"[1] Title\nURL: https://x.example/{unclosed}\n"+ )++ started = time.perf_counter()+ LaTeXExporter().export_to_latex(markdown)+ elapsed = time.perf_counter() - started++ assert elapsed < 2.0, f"export took {elapsed:.2f}s"++ def test_a_report_without_citation_links_never_builds_the_table(+ self, monkeypatch+ ):+ # The table costs memory and time for every character of the report,+ # so only a report that holds a citation link may pay for it.+ def refuse(text):+ raise AssertionError("destination table built without a link")++ monkeypatch.setattr(+ citation_formatter, "_link_destination_ends", refuse+ )++ assert exported_answer(report("Claims [1] and [2, 3].")) == (+ "Claims \\cite{1} and \\cite{2,3}."+ )+++class TestCommaGroups:+ """A group of indices in one bracket is one ``\\cite`` with a key list."""++ @pytest.mark.parametrize("group", ["[2, 3]", "[2,3]", "【2, 3】"])+ def test_a_comma_group_becomes_one_cite(self, group):+ markdown = report(f"Both agree {group}.")++ assert exported_answer(markdown) == "Both agree \\cite{2,3}."++ @pytest.mark.parametrize("group", ["[4, 5]", "[1, 9]", "[7, 8]"])+ def test_a_group_with_a_member_the_sources_lack_is_left_as_written(+ self, group+ ):+ # Prose such as "versions [4, 5]": citing it would print [?] for 5.+ markdown = report(f"Supported in versions {group}.")++ assert exported_answer(markdown) == f"Supported in versions {group}."++ def test_sources_without_urls_are_members_too(self):+ # Local documents have no URL; being listed is what makes a member.+ sources = "[1] Local Document A\n\n[2] Local Document B\n"+ markdown = report("Both agree [1, 2].", sources)++ assert exported_answer(markdown) == "Both agree \\cite{1,2}."++ def test_a_group_label_cites_every_member(self):+ # Its one URL names a single source, so looking that up drops the+ # rest of the group.+ markdown = report(+ "Both agree [[2, 3]](https://arxiv.org/abs/2401.00002)."+ )++ assert exported_answer(markdown) == "Both agree \\cite{2,3}."++ def test_a_padded_group_label_cites_every_member(self):+ # A hand-edited label; the formatter itself never pads one.+ markdown = report(+ "Both agree [[ 2, 3 ]](https://arxiv.org/abs/2401.00002)."+ )++ assert exported_answer(markdown) == "Both agree \\cite{2,3}."++ def test_a_group_label_with_a_member_the_sources_lack_is_left_as_written(+ self,+ ):+ markdown = report("See [[4, 5]](https://elsewhere.example/p).")++ assert exported_answer(markdown) == (+ "See [[4, 5]](https://elsewhere.example/p)."+ )