Skip to content

Phase 4: Inline citations in answers - #383

Merged
neuromechanist merged 9 commits into
feature/issue-360-epic-anthropic-platformfrom
feature/issue-364-phase4-citations
Sep 17, 2026
Merged

neuromechanist merged 9 commits into
feature/issue-360-epic-anthropic-platformfrom
feature/issue-364-phase4-citations

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Answers now carry inline citations that point at the passage they came from. Retrieval tools return Anthropic search_result blocks instead of plain strings, the model attaches search_result_location citations to the spans it actually drew on, and the API and widget surface those as [n] markers plus a numbered source list.

Before this phase the assistant retrieved documentation, GitHub threads, papers and forum posts and then wrote prose with no attribution, sometimes ending with a "next steps" link pointing somewhere other than the source of the claim. The project's first design principle is that researchers need citation-backed answers, so this was the gap that mattered most.

Closes #364
Closes #350
Part of epic #360

Why native instead of a prompt rule

Claude cites search result blocks against exact spans of the retrieved text, so a marker points at the sentence's actual source rather than at a URL the model chose to mention. A prompt rule is a request; this is a property of the response.

Everything the design depends on was checked against the live Claude Platform on AWS endpoint through this repo's own create_anthropic_llm before planning, because Phase 1 shipped a payload-shape bug that only CI caught:

  • search_result blocks are GA on the Messages API, no beta header, supported by every active model except Haiku 3, so both offered models qualify.
  • A LangChain tool returning list[dict] keeps it as ToolMessage.content, and langchain-anthropic 1.7.2 serializes it into tool_result.content with the block intact.
  • Streaming delivers citations as their own chunks carrying only a citations key, arriving at the end of the span they annotate, which is exactly where an inline marker belongs.

Which tools are citable

Citable, because answers are legitimately built from them: retrieve_{id}_docs (the important one, since communities ship 13 to 46 documents and only 1 or 2 are preloaded), fetch_current_page, search_{id}_code_docs, get_{id}_full_docstring, and search_{id}_faq.

Not citable: search_{id}_discussions, list_{id}_recent, search_{id}_papers, search_{id}_papers_live and search_{id}_forum. Every one of those tells the model in its own description that it is for discovery and that its content must not be used to formulate answers. Making them citable would invite exactly the behavior the description forbids. list_{id}_recent was missing that sentence while its four siblings had it, so it got the same wording.

The rule is now a test rather than a comment: TestCitabilityMatchesDescription seeds a real row in every backing table, derives the expectation from each tool's own description text, and fails loudly if a tool is citable while telling the model not to answer from it, or is wired for answering without citation support.

Provider gating

Search result blocks are Anthropic-only and OpenRouter would reject list-shaped tool content, so the tools need to know who is paying. CommunityAssistant.__init__ and create_community_assistant take citations: bool, threaded to _build_tools and create_knowledge_tools; the router passes choice.provider == "anthropic" from the ProviderChoice it already resolves. With the flag false every tool returns byte-for-byte what it returns today, so the OpenRouter BYOK path is untouched. Being per-request also satisfies the API's "every search result in a request must use the same citations.enabled" constraint for free.

When citations are unavailable, _build_system_prompt adds a rule asking for a markdown link after each claim drawn from a retrieved document. Worse than native citations, which is the honest trade, but it keeps the BYOK path useful without pretending the two are equivalent.

Markers and API surface

One marker per unique source, assigned in order of first appearance, so three claims from one document share [1]. src/agents/content.py gained extract_citations, a classify_content_blocks that no longer drops a text block's citations, and the marker tracker. All three call sites use it: _extract_agent_result for non-streaming, and both streaming handlers, which append the marker to the content stream and emit a citation SSE event per new source, repeating the full list on done so a client that missed an event can still render.

AskResponse and ChatResponse gain citations: list[CitationInfo] (marker, source, title, cited_text), empty on the OpenRouter path and whenever the model cited nothing, so the field is always present and never lies.

The widget renders [n] as a superscript link with cited_text as the title attribute plus a compact source list under the answer. Only markers the response actually declared are promoted, isSafeUrl gates the link, everything is escaped, and an answer with no citations looks exactly as it does today.

Test plan

  • Full unit suite: 2080 passed, 13 skipped. The one failure is the pre-registered Rich-ANSI test_version_shows_version (Modernize the stale CLI integration tests in test_llm.py #369 territory), unrelated to this diff.
  • ruff check . and ruff format --check . clean.
  • extract_citations and classify_content_blocks assert against tests/fixtures/citation_response.json, a recorded real AIMessage.content from a Haiku call rather than a hand-built shape. Phase 2's cache-token bug got through precisely because every test hand-built a payload the API never produces.
  • Provider gating and the citability rule are dynamic over the tool factories, so a new tool cannot quietly skip the switch.
  • Live end to end against the platform, which is the only way to see whether markers land in the right places in real prose:
The ndx-hed extension provides three main classes: HedLabMetaData ... HedValueVector
(column-wide HED templates with value placeholders).[2]
Install via pip: `pip install -U ndx-hed`[1]

[1] resolves to https://www.hedtags.org/ndx-hed/ and [2] to https://www.hedtags.org/ndx-hed/description.html; each cited_text is a real span of the named document. Streaming interleaved the markers at event indices 16, 27, 35 and 45 rather than clumping them at the end, with one citation event per new source and the full list repeated on done.

Known limitation

Preloaded documents cannot be cited. Search results have to arrive as tool results or user content, and moving preloaded docs out of the system prompt would break the prompt-caching strategy Phase 1 built. That costs little in practice, 1 or 2 preloaded documents per community against 13 to 46 reachable through the citable retrieval tool, but an answer drawn purely from a preloaded overview will still carry no marker. Filed as #382 with the per-community preload table, rather than hidden.

Review status

Not yet reviewed. Both review agents over this diff terminated on the account's monthly spend limit before producing a report, so unlike Phases 1 to 3 this PR opens without a completed review round. The one partial finding that survived was benign: the marker tracker's state is function-local, so there is no cross-request or cross-turn leakage. A review round will run against this PR before it merges into the epic branch.

Adds src/tools/citations.py with build_search_result(), matching the
search_result content block schema verified live against the Claude
Platform on AWS (GA, no beta header), plus a shared truncate() helper to
replace the truncation logic the tools currently open-code in several
places.
Threads a citations: bool flag through CommunityAssistant,
create_community_assistant, create_knowledge_tools, and the router's
provider resolution, so every citable tool (retrieve_docs,
fetch_current_page, search_papers, search_papers_live, search_code_docs,
get_full_docstring, search_faq, search_forum) returns search_result
blocks instead of formatted strings when the request is running on the
Anthropic path. Discussion search and recent-activity listing stay
string-only, matching their existing "discovery, not answering"
descriptions. Consolidates the open-coded truncation duplicates onto the
new truncate() helper.
Extends classify_content_blocks() with a citations field per text block
(ContentBlock, a 3-field named tuple), adds extract_citations() to flatten
them, and adds CitationTracker to assign stable [n] markers per unique
source in first-appearance order, shared logic for both the streaming and
non-streaming response paths.

tests/fixtures/citation_response.json is a recorded real response payload:
one small claude-haiku-4-5 call (via this repo's create_anthropic_llm),
with a tool bound that returns a build_search_result() block, captured to
avoid the Phase 2 bug class where every test hand-built a citation shape
the API never actually produces.
Adds CitationInfo (marker, source, title, cited_text) and a citations
field to AskResponse and ChatResponse. _extract_agent_result now builds
the answer text with inline [n] markers via a new
_build_answer_with_citations, using CitationTracker so numbering matches
the streaming path. Both SSE streaming generators emit a citation event
the first time a source is cited (with its marker text folded into the
content stream at that point) and repeat the full citation list on the
done event. Threads citations=provider_choice.provider == "anthropic"
into registry.create_assistant so the flag follows the already-resolved
per-request provider choice.
renderInlineMarkdown()/markdownToHtml() take an optional citationsByMarker
lookup and render a bare "[n]" (never a real markdown link) as a
superscript link to its source, with cited_text as the hover title. Each
cited assistant message also gets a compact numbered source list under
the answer. Handles the new "citation" SSE event and the "citations"
field on both the streaming "done" event and the non-streaming /chat
response; markers persist into session history unchanged. Behavior is
identical to today when a message carries no citations (OpenRouter path).

Verified with `node --check`; there is no JS test harness in this
project, so tests/test_frontend/test_widget_citations.py asserts the
invariants by parsing the file, matching test_widget_drift.py's approach.
Adds a fallback prompt rule for the OpenRouter/BYOK path (citations=False,
the default), asking the model to end each claim drawn from a retrieved
source with a markdown link immediately, rather than a links dump at the
end. Folded into the additional_instructions substitution value rather
than a new placeholder, since every community config already includes
{additional_instructions} by convention (a new placeholder would only
reach the default template). Omitted entirely when native citations are
available (citations=True).
Adds the llm-marked integration test that is the Definition of Done on
issue #364: a real request against the Claude Platform on AWS retrieves
an on-demand HED document via retrieve_hed_docs and returns an answer
whose [1] marker and citation both trace back to that document's own URL.
A tool is citable if and only if its description permits answering from
its content. search_{id}_papers, search_{id}_papers_live and
search_{id}_forum all carry "This is for DISCOVERY, not answering" / "Do
NOT use ... content to formulate answers" language, the same language
used to justify excluding search_{id}_discussions and list_{id}_recent,
so they were wrongly shipped citable. Reverts all three to their
pre-Phase-4 string-only behavior with no citations parameter at all, and
reverts search_{id}_forum's description to its original wording
unconditionally (no more citations-dependent description).

list_{id}_recent's description carried no discovery-only language at all,
even though it has always been meant as a non-answerable listing tool
(same category as search_{id}_discussions). Added the same "DISCOVERY,
not answering" / "Do NOT use" framing already used by its four siblings,
so the rule below can be checked mechanically rather than by a
hardcoded name list.

Replaces the gating test with one that encodes the rule itself:
TestCitabilityMatchesDescription seeds real rows across every backing
table, builds the full tool set once, and derives each tool's expected
return type from whether its own description contains discovery-only
language, so a new discovery tool added later is covered without a code
change here. TestProviderGating (real per-tool block content checks) and
TestDiscoveryToolsHaveNoCitationCapability (no factory accepts a
`citations` kwarg it can't honor) are kept alongside it; none of the
three overlap.
@neuromechanist neuromechanist added the feature New feature or enhancement label Sep 17, 2026
@github-actions

github-actions Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-issue-364-phase4-cit-demo.osc.earth
Branch feature/issue-364-phase4-citations
Commit 8b89203

This preview will be updated automatically when you push new commits.

escapeHtml serialized a text node, which escapes & < > but leaves both
quote characters alone. Its output is interpolated into href, title and
value attributes, so a value carrying a double quote closed the attribute
and everything after it parsed as further attributes. Confirmed in a real
DOM: a cited_text of 'prefix" onmouseover="...' produced an anchor with a
live onmouseover handler.

Citations made this reachable from the least trusted input the widget
renders, since cited_text is a verbatim span of a retrieved community
document, but the same gap applied to every pre-existing attribute site.
Fixed in the shared helper. Escaped quotes still render as quotes, and a
code block still copies real quotes because that path reads textContent.

Tests assert the invariant for every attribute interpolation, not just
this one site, and were confirmed to fail against the previous helper.
@neuromechanist

Copy link
Copy Markdown
Member Author

Adding a security fix found by chasing the one finding the review agent was mid-way through when it terminated: it was checking escapeHtml quote behavior in the widget.

escapeHtml set div.textContent and returned innerHTML, which escapes &, < and > but leaves both quote characters alone, because serializing a text node has no reason to escape quotes. Its output is interpolated into href="", title="" and value="" attributes, so a value carrying a double quote closed the attribute and everything after it parsed as further attributes.

Phase 4 made that reachable from the least trusted input the widget renders: the citation title carries cited_text, a verbatim span of a retrieved community document. Confirmed in a real DOM (happy-dom), not argued from the spec: a cited_text of prefix" onmouseover="... produced an anchor carrying a live onmouseover attribute. After the fix the same input yields exactly href/target/rel/title, and the full literal text now survives in the tooltip instead of being truncated at the first quote.

Fixed in the shared helper rather than at the citation site, since the same gap applied to every pre-existing attribute interpolation (markdown link URLs, the source list, option values). Escaped quotes still render as quotes, and code blocks still copy real quotes because that path reads textContent.

Two tests, both confirmed to fail against the previous helper: one on the helper itself, one that enumerates every attribute interpolation in the widget and requires each to pass through escapeHtml or be listed as safe with a reason, so a newly added unescaped attribute fails rather than only this one site.

@neuromechanist
neuromechanist merged commit 7f1415b into feature/issue-360-epic-anthropic-platform Sep 17, 2026
4 of 5 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-364-phase4-citations branch September 17, 2026 15:19
@neuromechanist

Copy link
Copy Markdown
Member Author

Review findings addressed in 1def82a.

FAQ citation payload was uncapped (moderate). Confirmed and fixed. The citation path sent the stored answer whole while the string path truncated to 500 chars; capped at 2000, which is more generous than the display truncation because a citation points at an exact span and a span cut mid-sentence is worse than no citation. TestCitablePayloadsAreBounded now covers per-block size, whole-call size in both modes, and that an ordinary short answer is left alone. Reverting the cap makes two of the three fail with exactly the numbers from the review: 5000 == 2000 + 3, and 25,000 chars against 3,476 on the string path.

No live verification of streamed citations (important). This was the right thing to push on. Added an llm-marked test that drives _stream_ask_response against the real endpoint and ran it: it passes. So the assumption behind tests/test_api/test_citation_streaming.py holds on the wire: a citation really does arrive as its own delta on an on_chat_model_stream chunk, not only on the final aggregated message. The test asserts more than presence: it records the accumulated content at the moment each citation event fires and asserts it ends with that marker's [n], which is what makes a citation inline rather than a trailing bundle of links.

One thing the review could not have known: the streaming path refuses to run without an Origin. _resolve_provider only falls back to the platform key for an authorized origin, so the first run came back 403 API key required rather than reaching the model. The test now takes an origin from HED's own cors_origins instead of hardcoding one, so origin, key source, and the citations flag all hang together the way the production path wires them.

extract_text is dead in production (suggestion). Correct. Kept, with a docstring note: it is the text-side counterpart of extract_citations, it has had no production caller since the API began interleaving markers, and an answer assembled through it would carry citations no client could place.

Residual risk, widget marker collision. Accepting this as a documented limitation rather than fixing it here. Plain [n] was chosen so the marker stays readable in a client that renders nothing special, and switching to a distinctive delimiter would change the API surface, the widget, and the streamed content this PR's tests pin. The collision needs the model's own prose to emit a bare bracketed number that also matches a live marker index; the consequence is one wrong link, not lost data. Filing it as a follow-up alongside the preloaded-documents limitation.

Full suite: 2085 passed, 13 skipped, 1 pre-existing failure (test_version_shows_version, Rich ANSI codes, fails on the base branch too).

neuromechanist added a commit that referenced this pull request Sep 17, 2026
…tions live (#388)

Review findings on PR #383.

search_faq's citation path sent the stored answer uncapped while its string
path truncated to 500 chars. The other two citable tools pass search snippets
that src/knowledge/search.py has already truncated, but a FAQ answer comes
straight from the database, capped only at ingest (5000 chars). Reproduced:
at the default limit=5, one search carried 25,000 chars on the Anthropic path
against 3,476 on the OpenRouter path for the same query, a cost difference
visible only to whichever provider was paying. Capped at 2000 chars, more
generous than the display truncation because a citation points at an exact
span and a span cut mid-sentence is worse than no citation.

TestCitablePayloadsAreBounded covers per-block and whole-call size in both
modes, plus that an ordinary short answer is left alone. Verified both size
tests fail when the cap is reverted (5000 == 2000 + 3, and 25000 chars).

The streaming citation path had no live verification, unlike the
non-streaming one, so it rested on a hand-built chunk shape: the assumption
that a citation arrives as its own delta on an on_chat_model_stream chunk
rather than only on the final aggregated message. Added an llm-marked test
that drives the router's own SSE generator against the real endpoint and
asserts the accumulated content ends with the [n] marker at the moment each
citation event fires, which is what makes a citation inline rather than a
trailing bundle of links. Ran it: passes. It needs an Origin, taken from
HED's cors_origins rather than hardcoded, because the platform key is only
offered to an authorized origin and the citations flag follows the resolved
provider.

extract_text lost its last production caller when the API switched to
citation-aware assembly. Kept as the text-side counterpart of
extract_citations, with a docstring note saying it has no production caller
and why an answer must not be assembled through it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant