Repository navigation
Phase 4: Inline citations in answers - #383
neuromechanist merged 9 commits into
Conversation
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.
Preview Deployment
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.
|
Adding a security fix found by chasing the one finding the review agent was mid-way through when it terminated: it was checking
Phase 4 made that reachable from the least trusted input the widget renders: the citation 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 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 |
7f1415b
into
feature/issue-360-epic-anthropic-platform
|
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. No live verification of streamed citations (important). This was the right thing to push on. Added an One thing the review could not have known: the streaming path refuses to run without an
Residual risk, widget marker collision. Accepting this as a documented limitation rather than fixing it here. Plain Full suite: 2085 passed, 13 skipped, 1 pre-existing failure ( |
…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.
Summary
Answers now carry inline citations that point at the passage they came from. Retrieval tools return Anthropic
search_resultblocks instead of plain strings, the model attachessearch_result_locationcitations 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_llmbefore planning, because Phase 1 shipped a payload-shape bug that only CI caught:search_resultblocks are GA on the Messages API, no beta header, supported by every active model except Haiku 3, so both offered models qualify.list[dict]keeps it asToolMessage.content, and langchain-anthropic 1.7.2 serializes it intotool_result.contentwith the block intact.citationskey, 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, andsearch_{id}_faq.Not citable:
search_{id}_discussions,list_{id}_recent,search_{id}_papers,search_{id}_papers_liveandsearch_{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}_recentwas 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:
TestCitabilityMatchesDescriptionseeds 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__andcreate_community_assistanttakecitations: bool, threaded to_build_toolsandcreate_knowledge_tools; the router passeschoice.provider == "anthropic"from theProviderChoiceit 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 samecitations.enabled" constraint for free.When citations are unavailable,
_build_system_promptadds 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.pygainedextract_citations, aclassify_content_blocksthat no longer drops a text block'scitations, and the marker tracker. All three call sites use it:_extract_agent_resultfor non-streaming, and both streaming handlers, which append the marker to the content stream and emit acitationSSE event per new source, repeating the full list ondoneso a client that missed an event can still render.AskResponseandChatResponsegaincitations: 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 withcited_textas the title attribute plus a compact source list under the answer. Only markers the response actually declared are promoted,isSafeUrlgates the link, everything is escaped, and an answer with no citations looks exactly as it does today.Test plan
test_version_shows_version(Modernize the stale CLI integration tests in test_llm.py #369 territory), unrelated to this diff.ruff check .andruff format --check .clean.extract_citationsandclassify_content_blocksassert againsttests/fixtures/citation_response.json, a recorded realAIMessage.contentfrom 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.[1]resolves tohttps://www.hedtags.org/ndx-hed/and[2]tohttps://www.hedtags.org/ndx-hed/description.html; eachcited_textis 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 onecitationevent per new source and the full list repeated ondone.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.